[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 {createDynamicCardStack} = require("#cardstack/index");
const {ResolveCallbackTypes} = require("#cardstack/constants");
const {ResolveCallbackTypes, InteractiveComponentTypes} = require("#cardstack/constants");
module.exports = {
label: "text",
@ -31,8 +31,83 @@ module.exports = {
},
interactive: {
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",
inline: true,
visible: true,
disableCache: true,
resolvePage: ()=>{
@ -45,10 +120,9 @@ module.exports = {
}
},
conditional_button: {
type: InteractiveComponentTypes.BUTTON,
// Button Label
label: "Conditional",
// Next to pagination or new row
inline: false,
visible: (page) => {
return (page.getState("key") === "t_1")
},
@ -63,6 +137,8 @@ module.exports = {
}
},
dynamic_button: {
type: InteractiveComponentTypes.BUTTON,
slot: 3,
// Button Label
label: (page) => {
console.log(page.getState("key"))

View file

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

View file

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

View file

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

View file

@ -70,7 +70,7 @@ class DynamicCardStack {
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
* @returns {number} Timeout
* @private
*/
_createTimeout() {
return setTimeout(() => {
return setTimeout(async () => {
/*
// This currently isn't doable with our Components listener.
if(this.spawned - this.lastInteraction <= this.expires){
@ -129,7 +129,7 @@ class DynamicCardStack {
} else {
this.kill(true);
}*/
this.kill(true);
await this.kill(true);
}, this.expires)
}
@ -138,33 +138,30 @@ class DynamicCardStack {
* @private
*/
_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
this.listener = new Components({
timeout: this.expires,
run: this._handleInteraction.bind(this),
onError: (e) => {
console.log(e)
}
})
// Create internal component listener
this.listener = new Components({
timeout: this.expires,
run: this._handleInteraction.bind(this),
onError: (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({
...this.getCurrentCard(),
components: this.listener
});
} catch (e) {
console.log(e)
}
return this._edit({
...this.getCurrentCard(),
components: this.listener
});
}
/**
@ -189,7 +186,6 @@ class DynamicCardStack {
*/
getCardByIndex(index) {
try {
// TODO: remove this some time after launch
let card = structuredClone(this.activeCardStack[index]);
// This creates an error card with debug information
@ -199,9 +195,10 @@ class DynamicCardStack {
error: "Unable to resolve card.",
content: `Index: \`${this.index}\`, Stack Size: \`${this.index}\`\n` +
(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 = "";
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;
} catch (e) {
console.log(e)
console.error("Card rendering failed:")
console.error(e)
return page(createEmbed("errordetail", this.context, {
error: "Unable to render card:",
content: codeblock("js", [(e ? e.stack || e.message : e).replaceAll(process.cwd(), '')])
@ -261,7 +259,7 @@ class DynamicCardStack {
/**
* Edits the cardstack message.
* Automatically applies and rerenders components.
* Automatically applies and re-renders components.
* @param {Message} cardContent Card Content
* @param {boolean, Array} components Custom Components Array
*/
@ -284,7 +282,8 @@ class DynamicCardStack {
allowedMentions: {parse: [], repliedUser: false}
})
} 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
// Change color if this is the active button.
// TODO: allow overwriting the "active" color
if (this.currentSelectedSubcategory === id) component.style = 1;
if (this.currentSelectedSubcategory === id) component.style = component.activeColor || 1;
// Add to active components cache
this.currentComponentsBatch[component.customId] = button;
if (component.customId.includes("/")) this.currentComponentsBatch[component.customId] = button;
return new ComponentButton(component);
}
@ -373,11 +371,14 @@ class DynamicCardStack {
* @private
*/
_renderComponents(disabled = false) {
// Cache of all currently active (interactive) components.
// Cache of all currently active dynamically generated components.
this.currentComponentsBatch = {};
let nComponents = new ComponentActionRow({})
let nComponentsSecondary = [new ComponentActionRow({})]
// Component Slots
// 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
for (const b of this.buttons) {
@ -389,7 +390,7 @@ class DynamicCardStack {
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)) {
@ -410,34 +411,36 @@ class DynamicCardStack {
console.error("Unknown Component Type: " + button.type + ".")
}
if (renderedButtons.length) {
// TODO: support slot field to select row
for (const r of renderedButtons) {
// 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);
}
}
// null means the button shouldn't be rendered.
for (const r of renderedButtons.filter((rb) => rb !== null)) componentSlots[button.slot || 0].push(r);
}
}
if (nComponentsSecondary[0].components.length >= 1) return [nComponents, ...nComponentsSecondary]
return [nComponents];
let renderedSlots = [];
// 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
* (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.
*/
@ -463,6 +466,17 @@ class DynamicCardStack {
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.
* @param index Root Card Index
@ -472,7 +486,7 @@ class DynamicCardStack {
* @private
*/
_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][componentId]) return null;
@ -513,8 +527,9 @@ class DynamicCardStack {
// Interactive Components
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
// and restore the root stack at its previous index.
if (this.currentSelectedSubcategory === cid) {
@ -544,7 +559,7 @@ class DynamicCardStack {
// new stack is being fetched/rendered. Instant results should only
// ever be used if we rely on local data or can guarantee almost-instant
// processing/fetching times.
if (!this.currentComponentsBatch[cid].instantResult) {
if (!component.instantResult) {
let processingEmbed = page(createEmbed("default", ctx, {
image: {
url: STATIC_ASSETS.card_skeleton
@ -556,8 +571,8 @@ class DynamicCardStack {
// i.e COPY_PARENT which will copy select fields
// from the parent embed or SKELETON_WITH_TITLE.
// -> needs iterating on visual language first
if (this.currentComponentsBatch[cid].renderLoadingState)
processingEmbed = page(this.currentComponentsBatch[cid].renderLoadingState(this, this.currentComponentsBatch[cid]));
if (component.renderLoadingState)
processingEmbed = page(component.renderLoadingState(this, component));
await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
@ -566,7 +581,7 @@ class DynamicCardStack {
}
// 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))
throw new Error(`Invalid Stack Resolve Type (${resolvedNewStack.type})`);
@ -585,13 +600,13 @@ class DynamicCardStack {
// Cache the computed cardstack for future accessing.
// 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
// We currently only cache SUBSTACK responses, as the other
// types probably need revalidating/refetching since the parent
// has changed and might carry new data.
if (!this.currentComponentsBatch[ctx.data.customId].disableCache) {
// types probably need revalidating/re-fetching since the parent
// has changed and might carry new data/state.
if (!this._getComponent(ctx.data.customId).disableCache) {
this._setCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS, [...this.activeCardStack]);
}
break;
@ -639,13 +654,13 @@ class DynamicCardStack {
error: "Card stack rendering failed.",
content: codeblock("js", [(e ? e.stack || e.message : e).replaceAll(process.cwd(), '')])
}))
]
console.log("resolve failed:")
console.log(e)
];
console.error("Card Resolving Failed:")
console.error(e)
}
// Update the card stack with a card from the new stack.
if (this.currentComponentsBatch[ctx.data.customId].instantResult) {
if (component.instantResult) {
await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.getCurrentCard(), {components: this._renderComponents()})