[cardstack] fix interaction contexts, cleanup code, add comments/documentation

This commit is contained in:
bignutty 2025-02-12 02:49:22 +01:00
parent 8c036e714a
commit 510cbbe60d
5 changed files with 273 additions and 118 deletions

View file

@ -8,6 +8,10 @@ const { MessageComponentTypes, InteractionCallbackTypes } = require("detritus-cl
const { Message } = require("detritus-client/lib/structures");
const { ComponentContext, Components, ComponentActionRow} = require("detritus-client/lib/utils");
/**
* Stores all active card stacks
* @type {WeakMap<WeakKey, DynamicCardStack>}
*/
const activeStacks = new WeakMap();
const DEFAULT_BUTTON_ICON_MAPPINGS = Object.freeze({
@ -15,12 +19,6 @@ const DEFAULT_BUTTON_ICON_MAPPINGS = Object.freeze({
"previous": "button_chevron_left"
});
const SUBCATEGORY_STATE_TYPES = Object.freeze({
NONE: 0,
SINGLE_PAGE: 1,
MULTI_PAGE: 2,
});
const STACK_CACHE_KEYS = Object.freeze({
RESULT_CARDS: 0
})
@ -58,13 +56,13 @@ class DynamicCardStack {
this.stackCache = {};
this.pageState = [];
this.subcategoryState = SUBCATEGORY_STATE_TYPES.SINGLE_PAGE;
this.currentSelectedSubcategory = null;
/*
this.lastInteraction = Date.now();
this.spawned = 0;
*/
console.log("now spawning " + this.uniqueId)
this._spawn();
}
@ -76,31 +74,41 @@ class DynamicCardStack {
clearTimeout(this.timeout);
this.listener.clear();
if(clearComponents) await this._edit(this.currentPage(), [])
if(clearComponents) await this._edit(this.getCurrentCard(), [])
// Remove reference to free the cardstack for GC
activeStacks.delete(this.context.message);
activeStacks.delete(this.context.message || this.context.interaction);
}
/**
* Get a Stack based on its attached message ID
* @param {*} id Attached message ID
* Get a Stack from an attached reference (message/interaction).
* @param {Message} ref Attached message/interaction
* @returns {DynamicCardStack}
*/
_getStackByMessageId(id){
return activeStacks.get(id);
_getStackByReference(ref){
return activeStacks.get(ref);
}
/**
* Attaches a cardstack to its internal reference.
* @private
*/
_createDynamicCardStack(){
// Kill any previously active cardstacks
if(activeStacks.get(this.context.message)){
console.log(this.uniqueId + " is replacing " + this._getStackByMessageId(this.context.message?.id).uniqueId);
this._getStackByMessageId(this.context.message).kill();
// Kill any previously active cardstacks on this reference
// (prevents oddities when editing a regular command)
if(activeStacks.get(this.context.message || this.context.interaction)){
this._getStackByReference(this.context.message || this.context.interaction).kill();
}
activeStacks.set(this.context.message, this);
activeStacks.set(this.context.message || this.context.interaction, this);
}
/**
* Cretaes a timeout for the paginator.
* TODO: make this work properly
* @returns {number} Timeout
* @private
*/
_createTimeout(){
return setTimeout(()=>{
/*
@ -127,7 +135,8 @@ class DynamicCardStack {
this.activeCardStack = [...this.cards];
// Resolve page state before
// Resolve page state for all
// root pages.
let i = 0;
for(const ac of this.cards){
if(ac["_meta"]){
@ -147,7 +156,7 @@ class DynamicCardStack {
this.timeout = this._createTimeout()
this.spawned = Date.now()
//this.spawned = Date.now()
return this._edit({
...this.getCurrentCard(),
@ -158,21 +167,34 @@ class DynamicCardStack {
}
}
getPageByIndex(index){
/**
* Gets a card from the currently active
* stack by its index
* @param index Page Index
* @returns {*}
*/
getCardByIndex(index){
return this.activeCardStack[index];
}
nextPage(){
/**
* Advances the index and returns the next card from the stack.
* @returns {Message} Card
*/
nextCard(){
this.index = this.index + 1;
if(this.index >= this.activeCardStack.length){
if(this.loopPages) this.index = 0;
}
if(this.currentSelectedSubcategory == null) this.rootIndex = this.index;
console.log("new index: " + this.index)
return Object.assign(this.getPageByIndex(this.index), { components: this._renderComponents() });
return Object.assign(this.getCardByIndex(this.index), { components: this._renderComponents() });
}
/**
* Decreases the index and returns the next card from the stack.
* @returns {Message} Card
*/
previousPage(){
this.index = this.index - 1;
if(this.index < 0){
@ -181,11 +203,7 @@ class DynamicCardStack {
}
if(this.currentSelectedSubcategory == null) this.rootIndex = this.index;
return Object.assign(this.getPageByIndex(this.index), { components: this._renderComponents() });
}
currentPage() {
return Object.assign(this.getPageByIndex(this.index), { components: this._renderComponents() });
return Object.assign(this.getCardByIndex(this.index), { components: this._renderComponents() });
}
/**
@ -206,9 +224,6 @@ class DynamicCardStack {
if(message["_meta"]) delete message["_meta"];
//console.log("GOING OUT:")
//console.log(JSON.stringify(message, null, 2))
try{
return editOrReply(this.context, {
...message,
@ -220,18 +235,17 @@ class DynamicCardStack {
}
}
getCurrentCard(){
return this.activeCardStack[this.index];
}
getPageIndex(){
return this.index;
}
// API for contextual buttons
/**
* Retrieves state from the currently active page
* Returns the currently selected card from the
* active stack.
* @returns {Message} Card
*/
getCurrentCard(){
return this.getCardByIndex(this.index);
}
/**
* Retrieves state from the currently active root card
* @param {String} key
*/
getState(key){
@ -240,6 +254,11 @@ class DynamicCardStack {
return this.pageState[this.rootIndex][key];
}
/**
* Returns all page state.
* Only really intended for debugging purposes.
* @returns {Object}
*/
getAllState(){
return this.pageState;
}
@ -257,7 +276,7 @@ class DynamicCardStack {
type: MessageComponentTypes.BUTTON,
customId: b,
style: 2,
disabled: this.activeCardStack.length === 1 || disabled || (this.subcategoryState !== SUBCATEGORY_STATE_TYPES.SINGLE_PAGE),
disabled: this.activeCardStack.length === 1 || disabled,
emoji: iconAsEmojiObject(DEFAULT_BUTTON_ICON_MAPPINGS[b])
}
@ -279,22 +298,40 @@ class DynamicCardStack {
disabled: disabled
}
if(!disabled && button.condition && typeof(button.condition) == "function") component.disabled = !button.condition(this);
// Dynamic disabling
if(!disabled && button.condition && typeof(button.condition) == "function")
component.disabled = !button.condition(this);
// Dynamic label
if(button.label){
if(typeof(button.label) === "function") component.label = button.label(this);
else component.label = button.label;
}
if(button.icon) component.emoji = iconAsEmojiObject(button.icon) || undefined
// Display the selected button
// Change color if this is the active button.
// TODO: allow overwriting the "active" color
if(this.currentSelectedSubcategory === b) component.style = 1;
if(button.inline) nComponents.addButton(component);
else {
if(nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5){
nComponentsSecondary.push(new ComponentActionRow({}))
// 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(component);
} else {
nComponents.addButton(component);
}
} 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(component);
}
}
@ -303,13 +340,40 @@ class DynamicCardStack {
return [nComponents];
}
/**
* Compute Cache
*
* The compute cache allows storing computed values
* (i.e. resulting card stacks) in order to skip
* refetching or reprocessing substacks when not
* necessary. The cache can be disabled per-component.
*/
/**
* Set an internal cached computed value.
* @param index Root Card Index
* @param componentId Component ID
* @param key Cache Key
* @param value Cache Data
* @private
*/
_setCachedValue(index, componentId, key, value){
if(!this.stackCache[index]) this.stackCache[index] = {};
if(!this.stackCache[index][componentId]) this.stackCache[index][componentId] = {};
this.stackCache[index][componentId][key] = value;
}
/**
* Retrieve an internal cached computed value.
* @param index Root Card Index
* @param componentId Component ID
* @param key Cache Key
* @returns {*|null} Cached Data
* @private
*/
_getCachedValue(index, componentId, key){
if(this.interactive_components[componentId].disableCache) return null;
if(!this.stackCache[index]) return null;
if(!this.stackCache[index][componentId]) return null;
if(!this.stackCache[index][componentId][key]) return null;
@ -317,25 +381,24 @@ class DynamicCardStack {
}
/**
* Handles an interaction from the attached components
* Handles an interaction from the attached components.
* @param {ComponentContext} ctx
*/
async _handleInteraction(ctx){
if(ctx.user.id !== this.context.user.id) return ctx.respond({
type: InteractionCallbackTypes.DEFERRED_UPDATE_MESSAGE
})
this.lastInteraction = Date.now();
//this.lastInteraction = Date.now();
// should be a built-in button
// Built-in Buttons
// TODO: derive this from a constant
if(["next","previous"].includes(ctx.data.customId)){
console.log("triggering button")
switch(ctx.data.customId){
case "next":
return ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: this.nextPage()
data: this.nextCard()
})
case "previous":
return ctx.respond({
@ -348,48 +411,72 @@ class DynamicCardStack {
return;
}
// interactive buttons
// Interactive Components
if(this.interactive_components[ctx.data.customId]){
// If the selected button is already active, disable it
// and restore the root stack at its previous index.
if(this.currentSelectedSubcategory === ctx.data.customId){
console.log("restoring state")
this.activeCardStack = [...this.cards];
this.index = this.rootIndex;
this.currentSelectedSubcategory = null;
return await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.currentPage(), { components: this._renderComponents(false)})
data: Object.assign(this.getCurrentCard(), { components: this._renderComponents(false)})
})
}
else this.currentSelectedSubcategory = ctx.data.customId;
console.log("new category is " + this.currentSelectedSubcategory)
// Reset page index so the new stack starts on page 0
this.index = 0;
try{
// If we have a cached result, retrieve it
if(this._getCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS) !== null){
this.activeCardStack = [...this._getCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS)];
await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.currentPage(), {components:this._renderComponents(false)})
data: Object.assign(this.getCurrentCard(), {components:this._renderComponents(false)})
})
return;
} else {
let processingEmbed = page(createEmbed("default", ctx, {
image: {
url: STATIC_ASSETS.card_skeleton
}
}))
// Controls if we should display a loading (skeleton) embed while the
// 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.interactive_components[ctx.data.customId].instantResult) {
let processingEmbed = page(createEmbed("default", ctx, {
image: {
url: STATIC_ASSETS.card_skeleton
}
}))
if(this.interactive_components[ctx.data.customId].renderLoadingState) processingEmbed = page(this.interactive_components[ctx.data.customId].renderLoadingState(this));
await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(processingEmbed, { components: this._renderComponents(true)})
})
// Render a custom loading skeleton embed
// TODO: maybe allow several loading modes here
// 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.interactive_components[ctx.data.customId].renderLoadingState)
processingEmbed = page(this.interactive_components[ctx.data.customId].renderLoadingState(this));
await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(processingEmbed, { components: this._renderComponents(true)})
})
}
// Compute the active cardstack.
this.activeCardStack = await this.interactive_components[ctx.data.customId].resolvePage(this);
// TODO: this needs several modes/callback types.
// SUBSTACK - Creates a "submenu" with a brand new cardstack
// REPLACE_PARENT - Replaces the parent card in the root stack
// REPLACE_ROOT_STACK - Replaces the root stack
// Cache the computed cardstack for future accessing.
// The cache can be disabled/bypassed if we either
// a) have really big/complex results
// b) want to ensure data is always fresh
if(!this.interactive_components[ctx.data.customId].disableCache){
this._setCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS, [...this.activeCardStack]);
}
@ -400,11 +487,20 @@ class DynamicCardStack {
]
console.log("resolve failed:")
console.log(e)
// TODO: better errors maybe?
}
setTimeout(()=>{
return this._edit(Object.assign(this.currentPage(), {components:this._renderComponents()}))
}, 1500)
// Update the card stack with a card from the new stack.
if(this.interactive_components[ctx.data.customId].instantResult){
await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.getCurrentCard(), { components: this._renderComponents()})
})
} else {
setTimeout(()=>{
return this._edit(Object.assign(this.getCurrentCard(), {components:this._renderComponents()}))
}, 1500)
}
return;
}