[nextgen/cardstack] add slot support to components

- migrate existing code to slots
- add interactiveComponent.activeColor to overwrite the default "selected" button style
- improve handling of cached components
This commit is contained in:
bignutty 2025-02-21 15:09:04 +01:00
parent e2c8a368c6
commit 668bb946a7
5 changed files with 173 additions and 88 deletions

View file

@ -2,7 +2,7 @@ const { createEmbed, page } = require("#utils/embed");
const { acknowledge } = require("#utils/interactions"); const { acknowledge } = require("#utils/interactions");
const {createDynamicCardStack} = require("#cardstack/index"); const {createDynamicCardStack} = require("#cardstack/index");
const {ResolveCallbackTypes} = require("#cardstack/constants"); const {ResolveCallbackTypes, InteractiveComponentTypes} = require("#cardstack/constants");
module.exports = { module.exports = {
label: "text", label: "text",
@ -31,8 +31,83 @@ module.exports = {
}, },
interactive: { interactive: {
always_active_button: { always_active_button: {
type: InteractiveComponentTypes.BUTTON,
label: "single sub page",
slot: 1,
visible: true,
disableCache: true,
resolvePage: ()=>{
return {
type: ResolveCallbackTypes.SUBSTACK,
cards: [
createEmbed("success", context, "smiley")
].map((p)=>page(p))
}
}
},
always_active_button1: {
type: InteractiveComponentTypes.BUTTON,
label: "single sub page",
slot: 1,
visible: true,
disableCache: true,
resolvePage: ()=>{
return {
type: ResolveCallbackTypes.SUBSTACK,
cards: [
createEmbed("success", context, "smiley")
].map((p)=>page(p))
}
}
},
always_active_button2: {
type: InteractiveComponentTypes.BUTTON,
label: "single sub page",
slot: 1,
visible: true,
disableCache: true,
resolvePage: ()=>{
return {
type: ResolveCallbackTypes.SUBSTACK,
cards: [
createEmbed("success", context, "smiley")
].map((p)=>page(p))
}
}
},
always_active_button3: {
type: InteractiveComponentTypes.BUTTON,
label: "single sub page",
slot: 1,
visible: true,
disableCache: true,
resolvePage: ()=>{
return {
type: ResolveCallbackTypes.SUBSTACK,
cards: [
createEmbed("success", context, "smiley")
].map((p)=>page(p))
}
}
},
always_active_button4: {
type: InteractiveComponentTypes.BUTTON,
label: "single sub page",
slot: 1,
visible: true,
disableCache: true,
resolvePage: ()=>{
return {
type: ResolveCallbackTypes.SUBSTACK,
cards: [
createEmbed("success", context, "smiley")
].map((p)=>page(p))
}
}
},
always_active_button5: {
type: InteractiveComponentTypes.BUTTON,
label: "single sub page", label: "single sub page",
inline: true,
visible: true, visible: true,
disableCache: true, disableCache: true,
resolvePage: ()=>{ resolvePage: ()=>{
@ -45,10 +120,9 @@ module.exports = {
} }
}, },
conditional_button: { conditional_button: {
type: InteractiveComponentTypes.BUTTON,
// Button Label // Button Label
label: "Conditional", label: "Conditional",
// Next to pagination or new row
inline: false,
visible: (page) => { visible: (page) => {
return (page.getState("key") === "t_1") return (page.getState("key") === "t_1")
}, },
@ -63,6 +137,8 @@ module.exports = {
} }
}, },
dynamic_button: { dynamic_button: {
type: InteractiveComponentTypes.BUTTON,
slot: 3,
// Button Label // Button Label
label: (page) => { label: (page) => {
console.log(page.getState("key")) console.log(page.getState("key"))

View file

@ -112,7 +112,6 @@ module.exports = {
episodes_button: { episodes_button: {
type: InteractiveComponentTypes.BUTTON, type: InteractiveComponentTypes.BUTTON,
label: "Episodes", label: "Episodes",
inline: false,
visible: true, visible: true,
condition: (page) => { condition: (page) => {
return (page.getState("episodes_key") !== null) return (page.getState("episodes_key") !== null)
@ -168,7 +167,6 @@ module.exports = {
characters_button: { characters_button: {
type: InteractiveComponentTypes.BUTTON, type: InteractiveComponentTypes.BUTTON,
label: "Characters", label: "Characters",
inline: false,
visible: true, visible: true,
condition: (page) => { condition: (page) => {
return (page.getState("characters_key") !== null) return (page.getState("characters_key") !== null)
@ -210,7 +208,6 @@ module.exports = {
related_button: { related_button: {
type: InteractiveComponentTypes.BUTTON, type: InteractiveComponentTypes.BUTTON,
label: "Related", label: "Related",
inline: false,
visible: true, visible: true,
condition: (page) => { condition: (page) => {
return (page.getState("related_key") !== null) return (page.getState("related_key") !== null)

View file

@ -78,7 +78,6 @@ module.exports = {
type: InteractiveComponentTypes.BUTTON, type: InteractiveComponentTypes.BUTTON,
label: "Full Coverage", label: "Full Coverage",
icon: "button_full_coverage", icon: "button_full_coverage",
inline: true,
visible: (pg) => { visible: (pg) => {
return (pg.getState("full_coverage_key") !== null) return (pg.getState("full_coverage_key") !== null)
}, },

View file

@ -1,8 +1,7 @@
const { wolframAlpha, wolframSupplemental} = require("#api"); const { wolframAlpha, wolframSupplemental} = require("#api");
const { paginator } = require('#client');
const { PERMISSION_GROUPS } = require('#constants'); const { PERMISSION_GROUPS } = require('#constants');
const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed'); const { createEmbed, page } = require('#utils/embed');
const { acknowledge } = require('#utils/interactions'); const { acknowledge } = require('#utils/interactions');
const { citation, smallIconPill } = require('#utils/markdown'); const { citation, smallIconPill } = require('#utils/markdown');
const { editOrReply } = require('#utils/message') const { editOrReply } = require('#utils/message')
@ -84,7 +83,6 @@ module.exports = {
interactive: { interactive: {
state_buttons: { state_buttons: {
type: InteractiveComponentTypes.BUTTON_GENERATOR, type: InteractiveComponentTypes.BUTTON_GENERATOR,
inline: true,
// Resolve Components // Resolve Components
resolveComponents: (pg)=>{ resolveComponents: (pg)=>{
if(!pg.getState("supplemental") || pg.getState("supplemental").length === 0) return []; if(!pg.getState("supplemental") || pg.getState("supplemental").length === 0) return [];

View file

@ -70,7 +70,7 @@ class DynamicCardStack {
this.spawned = 0; this.spawned = 0;
*/ */
this._spawn(); return this._spawn();
} }
/** /**
@ -111,13 +111,13 @@ class DynamicCardStack {
} }
/** /**
* Cretaes a timeout for the paginator. * Creates a timeout for the paginator.
* TODO: make this work properly * TODO: make this work properly
* @returns {number} Timeout * @returns {number} Timeout
* @private * @private
*/ */
_createTimeout() { _createTimeout() {
return setTimeout(() => { return setTimeout(async () => {
/* /*
// This currently isn't doable with our Components listener. // This currently isn't doable with our Components listener.
if(this.spawned - this.lastInteraction <= this.expires){ if(this.spawned - this.lastInteraction <= this.expires){
@ -129,7 +129,7 @@ class DynamicCardStack {
} else { } else {
this.kill(true); this.kill(true);
}*/ }*/
this.kill(true); await this.kill(true);
}, this.expires) }, this.expires)
} }
@ -138,33 +138,30 @@ class DynamicCardStack {
* @private * @private
*/ */
_spawn() { _spawn() {
try { this._createDynamicCardStack(this.context.client);
this._createDynamicCardStack(this.context.client);
this.activeCardStack = [...this.cards]; this.activeCardStack = [...this.cards];
this.updatePageState() this.updatePageState()
// Create internal component listener // Create internal component listener
this.listener = new Components({ this.listener = new Components({
timeout: this.expires, timeout: this.expires,
run: this._handleInteraction.bind(this), run: this._handleInteraction.bind(this),
onError: (e) => { onError: (e) => {
console.log(e) console.error("Component Handler Exception:")
} console.error(e)
}) }
})
this.timeout = this._createTimeout() this.timeout = this._createTimeout()
//this.spawned = Date.now() //this.spawned = Date.now()
return this._edit({ return this._edit({
...this.getCurrentCard(), ...this.getCurrentCard(),
components: this.listener components: this.listener
}); });
} catch (e) {
console.log(e)
}
} }
/** /**
@ -189,7 +186,6 @@ class DynamicCardStack {
*/ */
getCardByIndex(index) { getCardByIndex(index) {
try { try {
// TODO: remove this some time after launch
let card = structuredClone(this.activeCardStack[index]); let card = structuredClone(this.activeCardStack[index]);
// This creates an error card with debug information // This creates an error card with debug information
@ -199,9 +195,10 @@ class DynamicCardStack {
error: "Unable to resolve card.", error: "Unable to resolve card.",
content: `Index: \`${this.index}\`, Stack Size: \`${this.index}\`\n` + content: `Index: \`${this.index}\`, Stack Size: \`${this.index}\`\n` +
(Object.keys(this.getAllStateForPage(this.index)).length >= 1 ? (Object.keys(this.getAllStateForPage(this.index)).length >= 1 ?
codeblock("json", [JSON.stringify(this.getAllStateForPage(this.index), null, 2)]).substr(0, 5000) : "") codeblock("json", [JSON.stringify(this.getAllStateForPage(this.index), null, 2)]).substring(0, 5000) : "")
})) }))
// TODO: remove this some time after migration is complete
if (!card.content) card.content = ""; if (!card.content) card.content = "";
card.content += `\n-# ${icon("flask_mini")} You are using the new page system • Leave feedback or report bugs in our ${link(DISCORD_INVITES.feedback_cardstack, "Discord Server", "labsCore Support", false)}!` card.content += `\n-# ${icon("flask_mini")} You are using the new page system • Leave feedback or report bugs in our ${link(DISCORD_INVITES.feedback_cardstack, "Discord Server", "labsCore Support", false)}!`
@ -222,7 +219,8 @@ class DynamicCardStack {
return card; return card;
} catch (e) { } catch (e) {
console.log(e) console.error("Card rendering failed:")
console.error(e)
return page(createEmbed("errordetail", this.context, { return page(createEmbed("errordetail", this.context, {
error: "Unable to render card:", error: "Unable to render card:",
content: codeblock("js", [(e ? e.stack || e.message : e).replaceAll(process.cwd(), '')]) content: codeblock("js", [(e ? e.stack || e.message : e).replaceAll(process.cwd(), '')])
@ -261,7 +259,7 @@ class DynamicCardStack {
/** /**
* Edits the cardstack message. * Edits the cardstack message.
* Automatically applies and rerenders components. * Automatically applies and re-renders components.
* @param {Message} cardContent Card Content * @param {Message} cardContent Card Content
* @param {boolean, Array} components Custom Components Array * @param {boolean, Array} components Custom Components Array
*/ */
@ -284,7 +282,8 @@ class DynamicCardStack {
allowedMentions: {parse: [], repliedUser: false} allowedMentions: {parse: [], repliedUser: false}
}) })
} catch (e) { } catch (e) {
console.log(e) console.error("Message editing failed:")
console.error(e)
} }
} }
@ -359,11 +358,10 @@ class DynamicCardStack {
if (button.icon) component.emoji = iconAsEmojiObject(button.icon) || undefined if (button.icon) component.emoji = iconAsEmojiObject(button.icon) || undefined
// Change color if this is the active button. // Change color if this is the active button.
// TODO: allow overwriting the "active" color if (this.currentSelectedSubcategory === id) component.style = component.activeColor || 1;
if (this.currentSelectedSubcategory === id) component.style = 1;
// Add to active components cache // Add to active components cache
this.currentComponentsBatch[component.customId] = button; if (component.customId.includes("/")) this.currentComponentsBatch[component.customId] = button;
return new ComponentButton(component); return new ComponentButton(component);
} }
@ -373,11 +371,14 @@ class DynamicCardStack {
* @private * @private
*/ */
_renderComponents(disabled = false) { _renderComponents(disabled = false) {
// Cache of all currently active (interactive) components. // Cache of all currently active dynamically generated components.
this.currentComponentsBatch = {}; this.currentComponentsBatch = {};
let nComponents = new ComponentActionRow({}) // Component Slots
let nComponentsSecondary = [new ComponentActionRow({})] // We currently support up to 5 "slots" (action rows),
// although the amount you can actually use depends
// on how many components are added to each slot.
let componentSlots = [[],[],[],[],[]];
// First Row always starts with built-in components // First Row always starts with built-in components
for (const b of this.buttons) { for (const b of this.buttons) {
@ -389,7 +390,7 @@ class DynamicCardStack {
emoji: iconAsEmojiObject(DEFAULT_BUTTON_ICON_MAPPINGS[b]) emoji: iconAsEmojiObject(DEFAULT_BUTTON_ICON_MAPPINGS[b])
} }
nComponents.addButton(btn) componentSlots[0].push(new ComponentButton(btn));
} }
for (const b of Object.keys(this.interactive_components)) { for (const b of Object.keys(this.interactive_components)) {
@ -410,34 +411,36 @@ class DynamicCardStack {
console.error("Unknown Component Type: " + button.type + ".") console.error("Unknown Component Type: " + button.type + ".")
} }
if (renderedButtons.length) { if (renderedButtons.length) {
// TODO: support slot field to select row // null means the button shouldn't be rendered.
for (const r of renderedButtons) { for (const r of renderedButtons.filter((rb) => rb !== null)) componentSlots[button.slot || 0].push(r);
// Insert the component at the correct slot.
if (button.inline) {
// Ensure there is enough space for an inline component.
if (nComponents.components.length >= 5) {
// Ensure there is space on secondary rows.
if (nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5)
nComponentsSecondary.push(new ComponentActionRow({}))
nComponentsSecondary[nComponentsSecondary.length - 1].addButton(r);
} else {
nComponents.addButton(r);
}
} else {
// Ensure there is space on secondary rows to insert
// the component.
if (nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5)
nComponentsSecondary.push(new ComponentActionRow({}))
nComponentsSecondary[nComponentsSecondary.length - 1].addButton(r);
}
}
} }
} }
if (nComponentsSecondary[0].components.length >= 1) return [nComponents, ...nComponentsSecondary] let renderedSlots = [];
return [nComponents];
// Render slots
for(const components of componentSlots) {
if(components.length === 0) continue;
let row = new ComponentActionRow({});
// Slot all components into their respective rows.
while(components.length > 0) {
row.addButton(components.shift());
// Create a new row for content to overflow in.
if(row.isFull){
renderedSlots.push(row)
row = new ComponentActionRow({});
}
}
// Push rendered row to stack if there are components in it.
if(!row.isEmpty) renderedSlots.push(row);
}
if(renderedSlots.length > 5) console.warn("Component Overflow - Limiting to 5.")
return renderedSlots.splice(0, 5);
} }
/** /**
@ -445,7 +448,7 @@ class DynamicCardStack {
* *
* The compute cache allows storing computed values * The compute cache allows storing computed values
* (i.e. resulting card stacks) in order to skip * (i.e. resulting card stacks) in order to skip
* refetching or reprocessing substacks when not * re-fetching or reprocessing substacks when not
* necessary. The cache can be disabled per-component. * necessary. The cache can be disabled per-component.
*/ */
@ -463,6 +466,17 @@ class DynamicCardStack {
this.stackCache[index][componentId][key] = value; this.stackCache[index][componentId][key] = value;
} }
/**
* Gets an interactive component via its ID.
* @param id Component ID (usually custom_id of the button)
* @returns Interactive Component
* @private
*/
_getComponent(id) {
if (id.includes("/")) return this.currentComponentsBatch[id];
return this.interactive_components[id];
}
/** /**
* Retrieve an internal cached computed value. * Retrieve an internal cached computed value.
* @param index Root Card Index * @param index Root Card Index
@ -472,7 +486,7 @@ class DynamicCardStack {
* @private * @private
*/ */
_getCachedValue(index, componentId, key) { _getCachedValue(index, componentId, key) {
if (this.currentComponentsBatch[componentId].disableCache) return null; if (this._getComponent(componentId).disableCache) return null;
if (!this.stackCache[index]) return null; if (!this.stackCache[index]) return null;
if (!this.stackCache[index][componentId]) return null; if (!this.stackCache[index][componentId]) return null;
@ -513,8 +527,9 @@ class DynamicCardStack {
// Interactive Components // Interactive Components
let cid = ctx.data.customId; let cid = ctx.data.customId;
let component = this._getComponent(cid);
if (this.currentComponentsBatch[cid]) { if (component) {
// If the selected button is already active, disable it // If the selected button is already active, disable it
// and restore the root stack at its previous index. // and restore the root stack at its previous index.
if (this.currentSelectedSubcategory === cid) { if (this.currentSelectedSubcategory === cid) {
@ -544,7 +559,7 @@ class DynamicCardStack {
// new stack is being fetched/rendered. Instant results should only // new stack is being fetched/rendered. Instant results should only
// ever be used if we rely on local data or can guarantee almost-instant // ever be used if we rely on local data or can guarantee almost-instant
// processing/fetching times. // processing/fetching times.
if (!this.currentComponentsBatch[cid].instantResult) { if (!component.instantResult) {
let processingEmbed = page(createEmbed("default", ctx, { let processingEmbed = page(createEmbed("default", ctx, {
image: { image: {
url: STATIC_ASSETS.card_skeleton url: STATIC_ASSETS.card_skeleton
@ -556,8 +571,8 @@ class DynamicCardStack {
// i.e COPY_PARENT which will copy select fields // i.e COPY_PARENT which will copy select fields
// from the parent embed or SKELETON_WITH_TITLE. // from the parent embed or SKELETON_WITH_TITLE.
// -> needs iterating on visual language first // -> needs iterating on visual language first
if (this.currentComponentsBatch[cid].renderLoadingState) if (component.renderLoadingState)
processingEmbed = page(this.currentComponentsBatch[cid].renderLoadingState(this, this.currentComponentsBatch[cid])); processingEmbed = page(component.renderLoadingState(this, component));
await ctx.respond({ await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
@ -566,7 +581,7 @@ class DynamicCardStack {
} }
// Compute the active cardstack. // Compute the active cardstack.
let resolvedNewStack = await this.currentComponentsBatch[cid].resolvePage(this, this.currentComponentsBatch[cid]); let resolvedNewStack = await component.resolvePage(this, component);
if (!Object.values(ResolveCallbackTypes).includes(resolvedNewStack.type)) if (!Object.values(ResolveCallbackTypes).includes(resolvedNewStack.type))
throw new Error(`Invalid Stack Resolve Type (${resolvedNewStack.type})`); throw new Error(`Invalid Stack Resolve Type (${resolvedNewStack.type})`);
@ -585,13 +600,13 @@ class DynamicCardStack {
// Cache the computed cardstack for future accessing. // Cache the computed cardstack for future accessing.
// The cache can be disabled/bypassed if we either // The cache can be disabled/bypassed if we either
// a) have really big/complex results // a) have huge/complex results
// b) want to ensure data is always fresh // b) want to ensure data is always fresh
// We currently only cache SUBSTACK responses, as the other // We currently only cache SUBSTACK responses, as the other
// types probably need revalidating/refetching since the parent // types probably need revalidating/re-fetching since the parent
// has changed and might carry new data. // has changed and might carry new data/state.
if (!this.currentComponentsBatch[ctx.data.customId].disableCache) { if (!this._getComponent(ctx.data.customId).disableCache) {
this._setCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS, [...this.activeCardStack]); this._setCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS, [...this.activeCardStack]);
} }
break; break;
@ -639,13 +654,13 @@ class DynamicCardStack {
error: "Card stack rendering failed.", error: "Card stack rendering failed.",
content: codeblock("js", [(e ? e.stack || e.message : e).replaceAll(process.cwd(), '')]) content: codeblock("js", [(e ? e.stack || e.message : e).replaceAll(process.cwd(), '')])
})) }))
] ];
console.log("resolve failed:") console.error("Card Resolving Failed:")
console.log(e) console.error(e)
} }
// Update the card stack with a card from the new stack. // Update the card stack with a card from the new stack.
if (this.currentComponentsBatch[ctx.data.customId].instantResult) { if (component.instantResult) {
await ctx.respond({ await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.getCurrentCard(), {components: this._renderComponents()}) data: Object.assign(this.getCurrentCard(), {components: this._renderComponents()})