-
-
Notifications
You must be signed in to change notification settings - Fork 8
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
Better component handling #240
Conversation
🦋 Changeset detectedLatest commit: 8146984 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
Note Reviews pausedUse the following commands to manage reviews:
WalkthroughThis 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 Changes
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
Assessment against linked issues
Suggested labels
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (5)
✅ Files skipped from review due to trivial changes (3)
🚧 Files skipped from review as they are similar to previous changes (1)
🧰 Additional context used🧬 Code Graph Analysis (1)packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (3)
🔇 Additional comments (2)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
0278f5f
to
5aa41b6
Compare
There was a problem hiding this 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 suggestionUpdate 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 inBaseModalComponent
. 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 = parseCustomIdpackages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts (1)
31-35
: Custom-ID format description and implementation are out of syncThe 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
- 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) {
components.find(...)
is anO(n)
scan for every component.
Maintaining aMap<key, component>
inside the handler would upgrade lookups toO(1)
and avoid repeatedcustomIdParser
calls.
188-195
: Same registration pattern for modals – consider dedup utility / handler lookupModal 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 usesinteraction.customIdParser
, which is not defined onModalInteraction
ModalInteraction
extendsBaseInteraction
, but neither defines nor inheritscustomIdParser
.
The correct call is likelythis.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
📒 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 systemThe new
ComponentParserResult
andComponentData
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 featureThe 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 systemThis 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 systemThe 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 typeThe import of the
ComponentData
type is correctly added to support the updatedrun
method signature.packages/carbon/src/classes/components/ChannelSelectMenu.ts (1)
7-7
: Method signature update for improved custom ID data passingThe
run
method now accepts a second parameterdata
of typeComponentData
. 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 passingThe
run
method now accepts a second parameterdata
of typeComponentData
. 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 classThe abstract
run
method inAnySelectMenu
now includes adata: 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 passingThe
run
method now accepts a second parameterdata
of typeComponentData
. 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 updatedrun
method signature in theClickMeButton
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 importRow
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 newcustomIdParser
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:
- Correctly extracts the key and data segments
- Handles error cases (missing key)
- Properly converts string values to appropriate types (boolean, number, string)
- 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
andComponentParserResult
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 typeComponentData
, 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 acomponents
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:
- Clear explanation of the custom ID format
- A practical example of passing user IDs through custom IDs
- Details on automatic type conversion
- Mention of the ability to override the parser
This comprehensive explanation will help developers understand and utilize the new system effectively.
packages/carbon/src/abstracts/BaseMessageInteractiveComponent.ts
Outdated
Show resolved
Hide resolved
There was a problem hiding this 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 IDsThe 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 valueToUint8ArrayThe 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 readabilityThe 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 flagUsing 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
📒 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
@coderabbitai ignore |
✅ Actions performedReviews paused. |
also added in lefthook for optional git hook for running linter
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Refactor
Chores