Skip to content

Better component handling #240

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

Merged
merged 7 commits into from
Apr 29, 2025

Conversation

thewilloftheshadow
Copy link
Member

@thewilloftheshadow thewilloftheshadow commented Apr 29, 2025

also added in lefthook for optional git hook for running linter

Summary by CodeRabbit

  • New Features

    • Components and modals are now automatically registered when used, streamlining setup.
    • Introduced a structured custom ID system for components and modals to embed and parse contextual data.
    • Component and modal handlers now receive parsed contextual data alongside interactions.
  • Bug Fixes

    • Enhanced interaction matching by comparing parsed keys for components and modals.
  • Documentation

    • Updated docs to showcase automatic registration and the new custom ID format with examples.
  • Refactor

    • Removed manual component and modal registration properties from commands.
    • Simplified component and modal classes by centralizing ID parsing and interaction handling.
  • Chores

    • Added pre-commit linting hook to enforce code quality.

@thewilloftheshadow thewilloftheshadow requested a review from a team as a code owner April 29, 2025 07:56
Copy link

changeset-bot bot commented Apr 29, 2025

🦋 Changeset detected

Latest commit: 8146984

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@buape/carbon Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

This set of changes refactors the component and modal registration system in the Carbon framework. Components and modals are now dynamically registered when used in replies, follow-ups, or when shown, rather than through static arrays or client initialization. The custom ID system for components and modals is overhauled, introducing a parser that extracts structured key-value data from custom IDs, which is then passed to the run methods. The method signatures for run across components and modals are updated to accept this parsed data. Documentation is updated to reflect these changes, including new examples and explanations of the custom ID system.

Changes

Files/Paths Change Summary
.changeset/polite-taxis-give.md, .changeset/salty-worms-kick.md Added changeset files documenting minor feature updates for dynamic component mounting and a custom ID parser system.
apps/rocko/src/commands/testing/button.ts, apps/cloudo/src/commands/testing/button.ts Refactored commands to instantiate components dynamically in run methods; updated ClickMeButton to use a constructor setting dynamic customId and new run signature with parsed data.
apps/rocko/src/commands/testing/every_select.ts, apps/cloudo/src/commands/testing/every_select.ts Removed static components array properties from select menu commands; components are instantiated dynamically in run.
apps/rocko/src/commands/testing/modal.ts, apps/cloudo/src/commands/testing/modal.ts Removed static modals array properties from modal commands; modals are instantiated dynamically in run.
packages/carbon/src/abstracts/BaseCommand.ts Removed components and modals properties; no longer requires static registration of components or modals.
packages/carbon/src/abstracts/BaseInteraction.ts Added automatic registration of components and modals when replying, following up, or showing modals; introduced autoRegisterComponents method.
packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts, packages/carbon/src/abstracts/BaseModalComponent.ts, packages/carbon/src/classes/Modal.ts Removed constructors and additionalData; introduced customIdParser for parsing custom IDs; updated run method signatures to accept parsed data.
packages/carbon/src/classes/Client.ts Removed disableAutoRegister option and all related automatic registration logic from client initialization.
packages/carbon/src/classes/components/Button.ts, ChannelSelectMenu.ts, MentionableSelectMenu.ts, RoleSelectMenu.ts, StringSelectMenu.ts, UserSelectMenu.ts, AnySelectMenu.ts Updated abstract run method signatures to accept parsed data; made minor adjustments to default values and error handling in LinkButton.
packages/carbon/src/internals/ComponentHandler.ts, packages/carbon/src/internals/ModalHandler.ts Changed registration and matching logic to use parsed keys from custom IDs; run methods now receive parsed data as a second argument.
packages/carbon/src/types/index.ts Added new types: ComponentParserResult and ComponentData for structured custom ID parsing.
packages/carbon/src/index.ts Simplified export of component-related types using a wildcard export.
website/content/classes/components/index.mdx, website/content/classes/modals.mdx Updated documentation to reflect automatic registration, new custom ID system, and revised examples demonstrating the new patterns.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Command
    participant Interaction
    participant Component
    participant ComponentHandler
    participant Modal
    participant ModalHandler

    User->>Command: Triggers command (e.g., via message)
    Command->>Interaction: Calls reply()/followUp() with new Component(s)
    Interaction->>ComponentHandler: autoRegisterComponents(components)
    ComponentHandler->>Component: Registers using customIdParser(key)
    User->>Component: Interacts with component
    ComponentHandler->>Component: handleInteraction, parse custom_id, call run(interaction, data)
    Component->>Interaction: run() processes with parsed data

    User->>Command: Triggers modal command
    Command->>Interaction: Calls showModal(new Modal())
    Interaction->>ModalHandler: Registers Modal using customIdParser(key)
    User->>Modal: Submits modal
    ModalHandler->>Modal: handleInteraction, parse custom_id, call run(interaction, data)
    Modal->>Interaction: run() processes with parsed data
Loading

Assessment against linked issues

Objective Addressed Explanation
Allow components to have custom constructors and be instantiated dynamically (#213)
Remove illusion of static registration; ensure dynamic instantiation and data passing (#213)

Suggested labels

p:carbon

Poem

A rabbit hopped with code so bright,
Components now spring forth on sight!
No longer stuck in static rows,
Each button, modal, freely grows.
With custom IDs parsed with glee,
Dynamic flows for all to see!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 593cb09 and 8146984.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • lefthook.yml (1 hunks)
  • package.json (1 hunks)
  • packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (2 hunks)
  • packages/carbon/src/classes/Modal.ts (2 hunks)
  • pnpm-workspace.yaml (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • package.json
  • pnpm-workspace.yaml
  • lefthook.yml
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/carbon/src/classes/Modal.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (3)
packages/carbon/src/types/index.ts (2)
  • ComponentParserResult (12-15)
  • ComponentData (17-17)
packages/carbon/src/utils/customIdParser.ts (1)
  • parseCustomId (3-17)
packages/carbon/src/abstracts/BaseComponentInteraction.ts (1)
  • BaseComponentInteraction (13-59)
🔇 Additional comments (2)
packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (2)

5-8: Added appropriate type imports for component data handling.

The changes to imports appropriately add type definitions for component data handling and the parser utility. Converting BaseComponentInteraction to a type-only import is a good practice to avoid potential circular dependencies.


54-57: LGTM: Updated run method signature properly supports component data

The addition of the data: ComponentData parameter to the run method signature correctly supports the new component data system, allowing components to easily access parsed values from custom IDs.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

@github-actions github-actions bot added the package: carbon The carbon package label Apr 29, 2025
- mount components when used, allowing for custom constructor setups (fixes #213)
- add a better custom ID parsing system (implements #194)
@thewilloftheshadow thewilloftheshadow force-pushed the shadow/better-custom-component-setups branch from 0278f5f to 5aa41b6 Compare April 29, 2025 07:57
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (1)
website/content/classes/components/index.mdx (1)

31-36: 🛠️ Refactor suggestion

Update the run method example to include the data parameter.

The run method example doesn't reflect the updated signature that includes the data parameter. Consider updating it to match the implementation changes.

-async run(interaction: ButtonInteraction) {
+async run(interaction: ButtonInteraction, data: ComponentData) {
  return interaction.reply({
    content: "OMG YOU CLICKED THE BUTTON"
  })
}
🧹 Nitpick comments (5)
packages/carbon/src/classes/Modal.ts (1)

30-56: Consider extracting the duplicate parser implementation.

The customIdParser implementation is identical to the one in BaseModalComponent. Consider extracting this logic to a common utility function to avoid duplication and ensure consistent behavior across the codebase.

+// In a new file like src/utils/customIdParser.ts
+import type { ComponentParserResult } from "../types/index.js"
+
+export function parseCustomId(id: string): ComponentParserResult {
+  const [key, ...data] = id.split(":")
+  if (!key) throw new Error(`Invalid component ID: ${id}`)
+  return {
+    key,
+    data: Object.fromEntries(
+      data.map((d) => {
+        const [k, v] = d.split("=")
+        if (v === "true") return [k, true]
+        if (v === "false") return [k, false]
+        return [k, Number.isNaN(Number(v)) ? v : Number(v)]
+      })
+    )
+  }
+}

// Then in both classes:
-customIdParser: (id: string) => ComponentParserResult = (id) => {
-  const [key, ...data] = id.split(":")
-  if (!key) throw new Error(`Invalid component ID: ${id}`)
-  return {
-    key,
-    data: Object.fromEntries(
-      data.map((d) => {
-        const [k, v] = d.split("=")
-        if (v === "true") return [k, true]
-        if (v === "false") return [k, false]
-        return [k, Number.isNaN(Number(v)) ? v : Number(v)]
-      })
-    )
-  }
-}
+customIdParser: (id: string) => ComponentParserResult = parseCustomId
packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (1)

31-35: Custom-ID format description and implementation are out of sync

The doc-block claims that data segments inside the ID are delimited by semicolons (key:arg1=foo;arg2=bar), but the current implementation (see below) only splits on colons.
Keeping the comment and code aligned prevents surprises for users overriding the parser or crafting IDs manually.

packages/carbon/src/abstracts/BaseInteraction.ts (2)

98-119: autoRegisterComponents misses direct top-level components and does a linear search per component

  1. The Discord API only allows rows at the top level today, but v2 layouts already hinted (isV2) could allow otherwise. A small change lets you future-proof:
-if (component instanceof Row) {
-  for (const childComponent of component.components) {
+const children =
+  component instanceof Row ? component.components : [component as unknown]
+for (const childComponent of children) {
  1. components.find(...) is an O(n) scan for every component.
    Maintaining a Map<key, component> inside the handler would upgrade lookups to O(1) and avoid repeated customIdParser calls.

188-195: Same registration pattern for modals – consider dedup utility / handler lookup

Modal logic duplicates the component logic almost verbatim. Extracting a small helper (e.g. ensureRegistered(collection, key, register) in the handler) will DRY this class and keep behaviour consistent if lookup rules evolve.

website/content/classes/modals.mdx (1)

73-76: Example uses interaction.customIdParser, which is not defined on ModalInteraction

ModalInteraction extends BaseInteraction, but neither defines nor inherits customIdParser.
The correct call is likely this.customIdParser(this.customId) (inside the modal), or you can keep the current call by adding a wrapper on the interaction class.
Updating the snippet prevents copy-paste errors for users.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97e8e23 and 5aa41b6.

📒 Files selected for processing (22)
  • .changeset/polite-taxis-give.md (1 hunks)
  • .changeset/salty-worms-kick.md (1 hunks)
  • apps/rocko/src/commands/testing/button.ts (2 hunks)
  • packages/carbon/src/abstracts/AnySelectMenu.ts (2 hunks)
  • packages/carbon/src/abstracts/BaseCommand.ts (0 hunks)
  • packages/carbon/src/abstracts/BaseInteraction.ts (4 hunks)
  • packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (2 hunks)
  • packages/carbon/src/abstracts/BaseModalComponent.ts (1 hunks)
  • packages/carbon/src/classes/Client.ts (0 hunks)
  • packages/carbon/src/classes/Modal.ts (2 hunks)
  • packages/carbon/src/classes/components/Button.ts (3 hunks)
  • packages/carbon/src/classes/components/ChannelSelectMenu.ts (1 hunks)
  • packages/carbon/src/classes/components/MentionableSelectMenu.ts (1 hunks)
  • packages/carbon/src/classes/components/RoleSelectMenu.ts (1 hunks)
  • packages/carbon/src/classes/components/StringSelectMenu.ts (1 hunks)
  • packages/carbon/src/classes/components/UserSelectMenu.ts (1 hunks)
  • packages/carbon/src/index.ts (1 hunks)
  • packages/carbon/src/internals/ComponentHandler.ts (1 hunks)
  • packages/carbon/src/internals/ModalHandler.ts (1 hunks)
  • packages/carbon/src/types/index.ts (1 hunks)
  • website/content/classes/components/index.mdx (3 hunks)
  • website/content/classes/modals.mdx (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/carbon/src/abstracts/BaseCommand.ts
  • packages/carbon/src/classes/Client.ts
🧰 Additional context used
🧬 Code Graph Analysis (14)
packages/carbon/src/abstracts/AnySelectMenu.ts (1)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/classes/components/ChannelSelectMenu.ts (2)
packages/carbon/src/internals/ChannelSelectMenuInteraction.ts (1)
  • ChannelSelectMenuInteraction (9-20)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/classes/components/RoleSelectMenu.ts (2)
packages/carbon/src/internals/RoleSelectMenuInteraction.ts (1)
  • RoleSelectMenuInteraction (10-25)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/internals/ModalHandler.ts (1)
packages/carbon/src/internals/ModalInteraction.ts (1)
  • ModalInteraction (13-62)
packages/carbon/src/classes/components/Button.ts (2)
packages/carbon/src/internals/ButtonInteraction.ts (1)
  • ButtonInteraction (12-31)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/classes/components/MentionableSelectMenu.ts (2)
packages/carbon/src/internals/MentionableSelectMenuInteraction.ts (1)
  • MentionableSelectMenuInteraction (10-26)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/internals/ComponentHandler.ts (6)
packages/carbon/src/internals/ButtonInteraction.ts (1)
  • ButtonInteraction (12-31)
packages/carbon/src/internals/RoleSelectMenuInteraction.ts (1)
  • RoleSelectMenuInteraction (10-25)
packages/carbon/src/internals/ChannelSelectMenuInteraction.ts (1)
  • ChannelSelectMenuInteraction (9-20)
packages/carbon/src/internals/MentionableSelectMenuInteraction.ts (1)
  • MentionableSelectMenuInteraction (10-26)
packages/carbon/src/internals/StringSelectMenuInteraction.ts (1)
  • StringSelectMenuInteraction (10-25)
packages/carbon/src/internals/UserSelectMenuInteraction.ts (1)
  • UserSelectMenuInteraction (10-25)
packages/carbon/src/abstracts/BaseModalComponent.ts (1)
packages/carbon/src/types/index.ts (1)
  • ComponentParserResult (12-15)
packages/carbon/src/classes/components/UserSelectMenu.ts (2)
packages/carbon/src/internals/UserSelectMenuInteraction.ts (1)
  • UserSelectMenuInteraction (10-25)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (2)
packages/carbon/src/types/index.ts (2)
  • ComponentParserResult (12-15)
  • ComponentData (17-17)
packages/carbon/src/abstracts/BaseComponentInteraction.ts (1)
  • BaseComponentInteraction (13-61)
packages/carbon/src/classes/components/StringSelectMenu.ts (2)
packages/carbon/src/internals/StringSelectMenuInteraction.ts (1)
  • StringSelectMenuInteraction (10-25)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
packages/carbon/src/classes/Modal.ts (2)
packages/carbon/src/types/index.ts (2)
  • ComponentParserResult (12-15)
  • ComponentData (17-17)
packages/carbon/src/internals/ModalInteraction.ts (1)
  • ModalInteraction (13-62)
packages/carbon/src/abstracts/BaseInteraction.ts (3)
packages/carbon/src/types/index.ts (1)
  • MessagePayload (33-64)
packages/carbon/src/classes/components/Row.ts (1)
  • Row (11-63)
packages/carbon/src/utils.ts (1)
  • serializePayload (88-130)
apps/rocko/src/commands/testing/button.ts (2)
packages/carbon/src/internals/ButtonInteraction.ts (1)
  • ButtonInteraction (12-31)
packages/carbon/src/types/index.ts (1)
  • ComponentData (17-17)
🔇 Additional comments (36)
packages/carbon/src/types/index.ts (1)

12-17: Clean implementation of the custom ID parser type system

The new ComponentParserResult and ComponentData types are well-structured and provide a clear foundation for the custom ID parsing system. The types define a key-value structure that will allow components to receive specific data unique to each usage instance.

This implementation aligns perfectly with the PR objective of improving the custom ID parsing system (issue #194).

.changeset/polite-taxis-give.md (1)

1-6: Well-documented changeset for component mounting feature

The changeset appropriately documents the minor version update with a clear description of the feature being added - mounting components when used rather than upfront registration. This matches the PR objective of mounting components only when they are used, enabling custom constructor setups (issue #213).

.changeset/salty-worms-kick.md (1)

1-6: Clear changeset description for custom ID parser system

This changeset effectively documents the implementation of the custom ID parser system as a minor feature, providing component-specific data for each component instance. The description aligns perfectly with the PR objective of adding an improved custom ID parsing system (issue #194).

packages/carbon/src/index.ts (1)

16-16: Export change aligned with the new component system

The change from specific exports to a wildcard export for the BaseMessageInteractiveComponent module is appropriate given the refactoring of the component system. This ensures all new types and functionality from the module are properly exposed to consumers of the package.

packages/carbon/src/classes/components/UserSelectMenu.ts (1)

7-7: Properly imported ComponentData type

The import of the ComponentData type is correctly added to support the updated run method signature.

packages/carbon/src/classes/components/ChannelSelectMenu.ts (1)

7-7: Method signature update for improved custom ID data passing

The run method now accepts a second parameter data of type ComponentData. This change is part of the new custom ID parsing system mentioned in the PR objectives, allowing structured data from custom IDs to be passed to component handlers.

This update aligns well with the PR's goal of improving component handling by enabling custom data to be passed to components when they're used.

Also applies to: 14-17

packages/carbon/src/classes/components/RoleSelectMenu.ts (1)

7-7: Method signature update for improved custom ID data passing

The run method now accepts a second parameter data of type ComponentData. This change is consistent with the updates to other component classes and supports the new custom ID parsing system mentioned in the PR objectives.

This update aligns well with the PR's goal of improving component handling by enabling structured data from custom IDs to be passed directly to component handlers.

Also applies to: 13-16

packages/carbon/src/abstracts/AnySelectMenu.ts (1)

10-10: Method signature update in abstract base class

The abstract run method in AnySelectMenu now includes a data: ComponentData parameter, ensuring that all derived select menu classes receive structured data parsed from custom IDs. This change in the base class maintains consistency across the component hierarchy.

This update to the abstract class is essential for implementing the improved custom ID parsing system mentioned in the PR objectives.

Also applies to: 22-25

packages/carbon/src/classes/components/StringSelectMenu.ts (1)

7-7: Method signature update for improved custom ID data passing

The run method now accepts a second parameter data of type ComponentData. This change is consistent with updates to other component classes and supports the new custom ID parsing system.

This modification completes the pattern of changes across select menu components, ensuring a uniform approach to handling parsed custom ID data.

Also applies to: 13-16

packages/carbon/src/internals/ModalHandler.ts (2)

22-26: Improved modal matching with new custom ID parsing system.

The modal matching logic has been updated to use the parsed keys from custom IDs instead of direct string comparison, which aligns with the new custom ID parsing system introduced in this PR. This change provides more flexibility in how modals are identified and matched.


29-32: Good implementation of data passing to modal run method.

The modal's run method now receives the parsed data extracted from the custom ID as a second parameter. This allows modals to access structured data embedded in their custom IDs, enhancing their contextual awareness and flexibility.

packages/carbon/src/classes/components/MentionableSelectMenu.ts (2)

7-7: Appropriate import added for ComponentData type.

Good addition of the ComponentData type import to support the updated run method signature.


13-16: Updated run method signature to support custom ID data.

The abstract run method signature has been correctly updated to accept the additional data parameter, which aligns with the changes in the ComponentHandler. This enables MentionableSelectMenu components to receive and utilize structured data embedded in their custom IDs.

packages/carbon/src/classes/components/Button.ts (4)

10-10: Appropriate import added for ComponentData type.

Good addition of the ComponentData type import to support the updated run method signature.


40-43: Updated run method signature to support custom ID data.

The abstract run method signature has been correctly updated to accept the additional data parameter, which allows Button components to receive and utilize structured data embedded in their custom IDs.


68-68: Improved default customId for LinkButton.

Changed the default customId from an empty string to "link", which provides a more meaningful identifier and ensures consistency with the custom ID parsing system.


75-77: Added helpful error message for LinkButton run method.

Good addition of a run method implementation that throws an appropriate error message, clarifying that link buttons cannot be used in a run method since they simply navigate to a URL rather than triggering interaction handlers.

packages/carbon/src/internals/ComponentHandler.ts (3)

37-43: Improved component matching with new custom ID parsing system.

The component matching logic has been updated to compare parsed keys from custom IDs rather than raw strings, and it correctly verifies that the component type matches as well. This provides more flexibility in how components are identified and matched.


46-47: Efficient parsing of custom ID.

Good optimization to parse the interaction's custom_id once and reuse the result when calling run methods, rather than parsing it multiple times.


55-55: Consistent implementation of data passing across all component types.

The run method for each component type (Button, SelectMenus) now correctly receives the parsed data as the second parameter. This consistent implementation ensures all components can access structured data embedded in their custom IDs.

Also applies to: 63-63, 71-71, 79-79, 87-87, 95-95

apps/rocko/src/commands/testing/button.ts (5)

7-7: Good import addition for the updated component signature.

The import of ComponentData type is necessary for the updated run method signature in the ClickMeButton class.


20-20: Effective implementation of dynamic component creation.

This approach properly aligns with the new framework design where components are dynamically instantiated within message payloads rather than being declared statically.


30-33: Good use of the new custom ID system.

The constructor effectively implements the new custom ID system by embedding a timestamp as contextual data, which will be parsed and available in the component's run method.


35-38: Correctly updated component run method signature.

The method now properly accepts and utilizes the parsed data from the custom ID. The dynamic response that includes both the timestamp and username provides a good example of using component contextual data.


9-10: Verify that Row is being used correctly after the component changes.

The code uses Row with an array of components but doesn't explicitly import Row from the Carbon package, but it's available since it's imported at line 9.

packages/carbon/src/abstracts/BaseModalComponent.ts (4)

5-5: Appropriate import for the new parser system.

The ComponentParserResult type import is necessary for the return type of the new customIdParser method.


13-17: Good documentation update for customId property.

The updated documentation clearly explains the new purpose of the customId property and its relationship with the custom ID parser system.


21-31: Comprehensive documentation for the customIdParser method.

The documentation thoroughly explains:

  • The default parsing format with examples
  • Type conversion behavior
  • Requirements for custom implementations
  • The purpose and usage of the key and data object

This level of detail will help developers understand and extend the system.


32-46: Robust implementation of the custom ID parser.

The parser implementation:

  1. Correctly extracts the key and data segments
  2. Handles error cases (missing key)
  3. Properly converts string values to appropriate types (boolean, number, string)
  4. Returns a well-structured result object
packages/carbon/src/classes/Modal.ts (3)

8-8: Correct type imports for the parser system.

The import of both ComponentData and ComponentParserResult types is necessary for the updated method signatures and parser implementation.


23-27: Good documentation update for the customId property.

The documentation clearly explains the purpose of custom IDs in the new system and references the parser method.


58-61: Correctly updated Modal run method signature.

The updated method signature now includes the data parameter of type ComponentData, which allows modals to access the parsed data from their custom IDs.

website/content/classes/components/index.mdx (4)

8-8: Clear explanation of the new component registration system.

The documentation clearly explains how components are now automatically registered when used in messages, which aligns with the new framework design.


20-21: Updated example correctly demonstrates dynamic component instantiation.

The example now properly shows components being created dynamically within a Row in the message payload, rather than being declared statically in a components property.


27-27: Good example of the new custom ID format.

The example demonstrates the new format with a key and a key-value pair (ping:action=click), which is consistent with the new custom ID system.


39-70: Excellent documentation of the custom ID system.

This new section provides:

  1. Clear explanation of the custom ID format
  2. A practical example of passing user IDs through custom IDs
  3. Details on automatic type conversion
  4. Mention of the ability to override the parser

This comprehensive explanation will help developers understand and utilize the new system effectively.

@github-actions github-actions bot added the dependencies Dependency updates!! label Apr 29, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (4)
packages/carbon/src/utils/customIdParser.ts (1)

8-15: Consider adding support for array values in custom IDs

The current implementation allows for key-value pairs where values can be strings, booleans, or numbers, but components might benefit from supporting array values for cases where multiple selections or options need to be encoded.

You could enhance the parser to support arrays by detecting repeated keys:

data: Object.fromEntries(
	data.reduce((acc, d) => {
		const [k, v] = d.split("=")
		if (v === "true") return [...acc, [k, true]]
		if (v === "false") return [...acc, [k, false]] 
		const value = Number.isNaN(Number(v)) ? v : Number(v)
		
+		// Check if this key already exists and convert to array if needed
+		const existing = acc.find(item => item[0] === k)?.[1]
+		if (existing !== undefined) {
+			const existingArray = Array.isArray(existing) ? existing : [existing]
+			return acc.map(item => item[0] === k ? [k, [...existingArray, value]] : item)
+		}
		
		return [...acc, [k, value]]
	}, [])
)
packages/carbon/src/utils/verification.ts (1)

23-54: Add input validation and optimizations to valueToUint8Array

The function should validate inputs more thoroughly and could be optimized for hex string parsing.

export function valueToUint8Array(
	value: Uint8Array | ArrayBuffer | Buffer | string,
	format?: string
): Uint8Array {
-	if (value == null) {
+	if (value == null || value === "") {
		return new Uint8Array()
	}
	if (typeof value === "string") {
		if (format === "hex") {
+			// Remove common hex prefixes if present
+			const cleanHex = value.startsWith("0x") ? value.slice(2) : value
+			
+			// Ensure even length for hex string
+			const normalizedHex = cleanHex.length % 2 ? "0" + cleanHex : cleanHex
-			const matches = value.match(/.{1,2}/g)
+			const matches = normalizedHex.match(/.{1,2}/g)
			if (matches == null) {
				throw new Error("Value is not a valid hex string")
			}
+			// More efficient conversion using typed array directly
+			const result = new Uint8Array(matches.length)
+			for (let i = 0; i < matches.length; i++) {
+				const byte = Number.parseInt(matches[i], 16)
+				if (Number.isNaN(byte)) {
+					throw new Error(`Invalid hex character in string: ${matches[i]}`)
+				}
+				result[i] = byte
+			}
+			return result
-			const hexVal = matches.map((byte: string) => Number.parseInt(byte, 16))
-			return new Uint8Array(hexVal)
		}

		return new TextEncoder().encode(value)
	}
	if (Buffer.isBuffer(value)) {
		return new Uint8Array(value)
	}
	if (value instanceof ArrayBuffer) {
		return new Uint8Array(value)
	}
	if (value instanceof Uint8Array) {
		return value
	}
	throw new Error(
		"Unrecognized value type, must be one of: string, Buffer, ArrayBuffer, Uint8Array"
	)
}
packages/carbon/src/utils/payload.ts (2)

15-36: Extract component validation logic to improve readability

The v2 component validation logic is complex and would be more maintainable as a separate function.

The validation logic could be extracted to improve readability:

+// Helper function to validate v2 component usage
+function validateV2Components(payload: MessagePayload): void {
+	// Check if we have v2 components
+	const hasV2Components = payload.components?.some((component) => component.isV2);
+	
+	// If there are no v2 components, no validation needed
+	if (!hasV2Components) return;
+	
+	// Set the v2 components flag
+	payload.flags = payload.flags
+		? payload.flags | MessageFlags.IsComponentsV2
+		: MessageFlags.IsComponentsV2;
+	
+	// Validate no content with v2 components
+	if (payload.content) {
+		throw new Error(
+			"You cannot send a message with both content and v2 components. Use the TextDisplay component as a replacement for the content property in the message."
+		);
+	}
+	
+	// Validate no embeds with v2 components
+	if (payload.embeds) {
+		throw new Error(
+			"You cannot send a message with both embeds and v2 components. Use the Container component as a replacement for the embeds in the message."
+		);
+	}
+}

export const serializePayload = (
	payload: MessagePayload,
	defaultEphemeral = false
): RESTPostAPIChannelMessageJSONBody => {
	if (typeof payload === "string") {
		return { content: payload, flags: defaultEphemeral ? 64 : undefined }
	}
-	if (payload.components?.some((component) => component.isV2)) {
-		payload.flags = payload.flags
-			? payload.flags | MessageFlags.IsComponentsV2
-			: MessageFlags.IsComponentsV2
-	}
-
-	if (
-		payload.flags &&
-		(payload.flags & MessageFlags.IsComponentsV2) ===
-			MessageFlags.IsComponentsV2
-	) {
-		if (payload.content) {
-			throw new Error(
-				"You cannot send a message with both content and v2 components. Use the TextDisplay component as a replacement for the content property in the message."
-			)
-		}
-		if (payload.embeds) {
-			throw new Error(
-				"You cannot send a message with both embeds and v2 components. Use the Container component as a replacement for the embeds in the message."
-			)
-		}
-	}
+	// Validate and set flags for v2 components
+	validateV2Components(payload);

46-48: Use a constant for the ephemeral flag

Using a magic number (64) for the ephemeral flag makes the code less maintainable.

+// Use the MessageFlags enum instead of magic numbers
+import {
	type APIMessageTopLevelComponent,
	MessageFlags,
	type RESTPostAPIChannelMessageJSONBody
} from "discord-api-types/v10"

export const serializePayload = (
	payload: MessagePayload,
	defaultEphemeral = false
): RESTPostAPIChannelMessageJSONBody => {
	if (typeof payload === "string") {
-		return { content: payload, flags: defaultEphemeral ? 64 : undefined }
+		return { content: payload, flags: defaultEphemeral ? MessageFlags.Ephemeral : undefined }
	}
	// ... rest of the function ...
	
	if (defaultEphemeral) {
-		data.flags = payload.flags ? payload.flags | 64 : 64
+		data.flags = payload.flags ? payload.flags | MessageFlags.Ephemeral : MessageFlags.Ephemeral
	}
	return data
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 278dcf8 and 593cb09.

📒 Files selected for processing (32)
  • packages/carbon/src/abstracts/AnySelectMenuInteraction.ts (0 hunks)
  • packages/carbon/src/abstracts/BaseChannel.ts (1 hunks)
  • packages/carbon/src/abstracts/BaseComponentInteraction.ts (1 hunks)
  • packages/carbon/src/abstracts/BaseGuildChannel.ts (1 hunks)
  • packages/carbon/src/abstracts/BaseGuildTextChannel.ts (1 hunks)
  • packages/carbon/src/abstracts/BaseInteraction.ts (4 hunks)
  • packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (2 hunks)
  • packages/carbon/src/abstracts/GuildThreadOnlyChannel.ts (1 hunks)
  • packages/carbon/src/classes/Client.ts (1 hunks)
  • packages/carbon/src/classes/Modal.ts (2 hunks)
  • packages/carbon/src/index.ts (2 hunks)
  • packages/carbon/src/internals/ButtonInteraction.ts (0 hunks)
  • packages/carbon/src/internals/ModalInteraction.ts (1 hunks)
  • packages/carbon/src/plugins/gateway-forwarder/GatewayForwarderPlugin.ts (1 hunks)
  • packages/carbon/src/structures/DmChannel.ts (1 hunks)
  • packages/carbon/src/structures/GroupDmChannel.ts (1 hunks)
  • packages/carbon/src/structures/Guild.ts (1 hunks)
  • packages/carbon/src/structures/GuildForumChannel.ts (1 hunks)
  • packages/carbon/src/structures/GuildMember.ts (1 hunks)
  • packages/carbon/src/structures/GuildStageOrVoiceChannel.ts (1 hunks)
  • packages/carbon/src/structures/GuildTextChannel.ts (1 hunks)
  • packages/carbon/src/structures/GuildThreadChannel.ts (1 hunks)
  • packages/carbon/src/structures/Message.ts (1 hunks)
  • packages/carbon/src/structures/Role.ts (1 hunks)
  • packages/carbon/src/structures/User.ts (1 hunks)
  • packages/carbon/src/types/index.ts (2 hunks)
  • packages/carbon/src/utils.ts (0 hunks)
  • packages/carbon/src/utils/customIdParser.ts (1 hunks)
  • packages/carbon/src/utils/index.ts (1 hunks)
  • packages/carbon/src/utils/payload.ts (1 hunks)
  • packages/carbon/src/utils/verification.ts (1 hunks)
  • website/content/classes/modals.mdx (1 hunks)
💤 Files with no reviewable changes (3)
  • packages/carbon/src/internals/ButtonInteraction.ts
  • packages/carbon/src/abstracts/AnySelectMenuInteraction.ts
  • packages/carbon/src/utils.ts
✅ Files skipped from review due to trivial changes (19)
  • packages/carbon/src/abstracts/BaseChannel.ts
  • packages/carbon/src/abstracts/BaseGuildTextChannel.ts
  • packages/carbon/src/structures/GroupDmChannel.ts
  • packages/carbon/src/plugins/gateway-forwarder/GatewayForwarderPlugin.ts
  • packages/carbon/src/structures/GuildThreadChannel.ts
  • packages/carbon/src/abstracts/GuildThreadOnlyChannel.ts
  • packages/carbon/src/structures/GuildStageOrVoiceChannel.ts
  • packages/carbon/src/abstracts/BaseGuildChannel.ts
  • packages/carbon/src/structures/GuildMember.ts
  • packages/carbon/src/structures/Guild.ts
  • packages/carbon/src/structures/Role.ts
  • packages/carbon/src/internals/ModalInteraction.ts
  • packages/carbon/src/utils/index.ts
  • packages/carbon/src/structures/User.ts
  • packages/carbon/src/structures/GuildTextChannel.ts
  • packages/carbon/src/structures/DmChannel.ts
  • packages/carbon/src/abstracts/BaseComponentInteraction.ts
  • packages/carbon/src/structures/Message.ts
  • packages/carbon/src/structures/GuildForumChannel.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • packages/carbon/src/index.ts
  • packages/carbon/src/classes/Client.ts
  • packages/carbon/src/types/index.ts
  • website/content/classes/modals.mdx
  • packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts
  • packages/carbon/src/abstracts/BaseInteraction.ts
  • packages/carbon/src/classes/Modal.ts
🧰 Additional context used
🧬 Code Graph Analysis (2)
packages/carbon/src/utils/customIdParser.ts (1)
packages/carbon/src/types/index.ts (1)
  • ComponentParserResult (12-15)
packages/carbon/src/utils/payload.ts (1)
packages/carbon/src/types/index.ts (1)
  • MessagePayload (33-64)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Docs

@thewilloftheshadow
Copy link
Member Author

@coderabbitai ignore

Copy link
Contributor

coderabbitai bot commented Apr 29, 2025

✅ Actions performed

Reviews paused.

@thewilloftheshadow thewilloftheshadow added this pull request to the merge queue Apr 29, 2025
Merged via the queue into main with commit 314b16f Apr 29, 2025
9 checks passed
@thewilloftheshadow thewilloftheshadow deleted the shadow/better-custom-component-setups branch April 29, 2025 18:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dependencies Dependency updates!! package: carbon The carbon package
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Components can't have custom constructors Better custom ID system
2 participants