[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

@ -1,13 +1,15 @@
const { anime } = require('#api');
const { paginator } = require('#client');
const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES } = require('#constants');
const { anime, animeSupplemental} = require('#api');
const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES, COLORS_HEX} = require('#constants');
const { createDynamicCardStack } = require("#cardstack");
const { hexToDecimalColor } = require("#utils/color");
const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed');
const { acknowledge } = require('#utils/interactions');
const { smallPill, link, pill, stringwrapPreserveWords} = require('#utils/markdown');
const { smallPill, link, pill, stringwrapPreserveWords, timestamp, TIMESTAMP_FLAGS} = require('#utils/markdown');
const { editOrReply } = require('#utils/message');
const { InteractionContextTypes, ApplicationIntegrationTypes, ApplicationCommandOptionTypes } = require('detritus-client/lib/constants');
const { STATIC_ASSETS } = require("#utils/statics");
function renderAnimeResultsPage(context, res){
let result = createEmbed("default", context, {
@ -59,7 +61,13 @@ function renderAnimeResultsPage(context, res){
}
return page(result, {}, {
episodes_key: res.supplemental.episodes
// Supplemental keys are provided by the backend,
// allow for fetching extra data related to results.
episodes_key: res.supplemental.episodes,
characters_key: res.supplemental.characters,
name: res.title,
color: hexToDecimalColor(res.color || COLORS_HEX.embed),
cover: res.cover
});
}
@ -98,7 +106,7 @@ module.exports = {
let search = await anime(context, args.query, context.channel.nsfw)
search = search.response
if(search.body.status == 2) return editOrReply(context, createEmbed("error", context, search.body.message))
if(search.body.status === 2) return editOrReply(context, createEmbed("error", context, search.body.message))
let pages = []
for(const res of search.body.results){
@ -107,54 +115,99 @@ module.exports = {
if(!pages.length) return editOrReply(context, createEmbed("warning", context, `No results found.`))
await paginator.createPaginator({
context,
pages: formatPaginationEmbeds(pages),
createDynamicCardStack(context, {
cards: formatPaginationEmbeds(pages),
interactive: {
episodes_button: {
// Button Label
label: "Episodes",
// Next to pagination or new row
inline: false,
visible: true,
condition: (page)=>{
condition: (page) => {
return (page.getState("episodes_key") !== null)
},
// Will resolve all conditions at paginator creation time
precompute_conditions: true,
resolvePage: (page)=>{
// If an interactive button for this index hasn't been
// resolved yet, run this code
page.getState("episodes_key"); // -> supplemental key
renderLoadingState: (pg) => {
return createEmbed("default", context, {
description: `-# ${pg.getState("name")} **Episodes**`,
image: {
url: STATIC_ASSETS.card_skeleton
},
color: pg.getState("color")
})
},
resolvePage: async (pg) => {
let episodes = await animeSupplemental(context, pg.getState("episodes_key"));
/* Resolve supplemental key via api */
let cards = episodes.response.body.episodes.map((e) => {
let card = createEmbed("default", context, {
color: pg.getState("color"),
description: `-# ${pg.getState("name")} **Episodes**\n## `,
fields: []
})
return [...cards];
// Render episode number if available
if (e.episode) card.description += `${e.episode}: `
card.description += e.title;
if (e.description) card.description += `\n\n\n${stringwrapPreserveWords(e.description, 600)}`;
if (e.image) card.image = {url: e.image};
if (pg.getState("cover")) card.thumbnail = {url: pg.getState("cover")};
if (e.duration) card.fields.push({name: "Length", value: e.duration + " min", inline: true})
if (e.date) card.fields.push({
name: "Aired",
value: timestamp(e.date, TIMESTAMP_FLAGS.LONG_DATE),
inline: true
})
return page(card)
})
return formatPaginationEmbeds(cards);
}
},
characters_button: {
// Button Label
label: "Characters",
// Next to pagination or new row
inline: false,
condition: (page)=>{
visible: true,
condition: (page) => {
return (page.getState("characters_key") !== null)
},
resolvePage: (page)=>{
// If an interactive button for this index hasn't been
// resolved yet, run this code
page.getState("characters_key"); // -> supplemental key
renderLoadingState: (pg) => {
return createEmbed("default", context, {
description: `-# ${pg.getState("name")} **Characters**`,
image: {
url: STATIC_ASSETS.card_skeleton
},
color: pg.getState("color")
})
},
resolvePage: async (pg) => {
let characters = await animeSupplemental(context, pg.getState("characters_key"));
/* Resolve supplemental key via api */
let cards = characters.response.body.characters.map((c) => {
let card = createEmbed("default", context, {
color: pg.getState("color"),
description: `-# ${pg.getState("name")} **Characters**\n## ${link(c.url, c.name.full)}`,
fields: []
})
return [...cards];
if (c.description) card.description += `\n\n\n${stringwrapPreserveWords(c.description, 600)}`;
if (c.image) card.image = {url: c.image};
if (pg.getState("cover")) card.thumbnail = {url: pg.getState("cover")};
if (c.age) card.fields.push({name: "Age", value: c.age, inline: true})
return page(card)
})
return formatPaginationEmbeds(cards);
}
}
}
});
}catch(e){
if(e.response?.body?.status == 1) return editOrReply(context, createEmbed("warning", context, e.response?.body?.message))
if(e.response?.body?.status == 2) return editOrReply(context, createEmbed("warning", context, e.response?.body?.message))
if(e.response?.body?.status === 1) return editOrReply(context, createEmbed("warning", context, e.response?.body?.message))
if(e.response?.body?.status === 2) return editOrReply(context, createEmbed("warning", context, e.response?.body?.message))
console.log(e)
return editOrReply(context, createEmbed("error", context, `Unable to perform anime search.`))

View file

@ -1,14 +1,14 @@
const { anime, animeSupplemental} = require('#api');
const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES, COLORS_HEX} = require('#constants');
const { createDynamicCardStack } = require("#cardstack");
const { hexToDecimalColor } = require("#utils/color");
const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed');
const { acknowledge } = require('#utils/interactions');
const { smallPill, link, pill, stringwrapPreserveWords, timestamp, TIMESTAMP_FLAGS} = require('#utils/markdown');
const { editOrReply } = require('#utils/message');
const { DynamicCardStack } = require("../../../labscore/cardstack/DynamicCardStack");
const {STATIC_ASSETS} = require("#utils/statics");
const { STATIC_ASSETS } = require("#utils/statics");
function renderAnimeResultsPage(context, res){
let result = createEmbed("default", context, {
@ -60,6 +60,8 @@ function renderAnimeResultsPage(context, res){
}
return page(result, {}, {
// Supplemental keys are provided by the backend,
// allow for fetching extra data related to results.
episodes_key: res.supplemental.episodes,
characters_key: res.supplemental.characters,
name: res.title,
@ -101,13 +103,11 @@ module.exports = {
if(!pages.length) return editOrReply(context, createEmbed("warning", context, `No results found.`))
new DynamicCardStack(context, {
createDynamicCardStack(context, {
cards: formatPaginationEmbeds(pages),
interactive: {
episodes_button: {
// Button Label
label: "Episodes",
// Next to pagination or new row
inline: false,
visible: true,
condition: (page) => {
@ -154,9 +154,7 @@ module.exports = {
}
},
characters_button: {
// Button Label
label: "Characters",
// Next to pagination or new row
inline: false,
visible: true,
condition: (page) => {
@ -202,5 +200,5 @@ module.exports = {
console.log(e)
return editOrReply(context, createEmbed("error", context, `Unable to perform anime search.`))
}
},
}
};

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 {
}
}
/**
* Returns the currently selected card from the
* active stack.
* @returns {Message} Card
*/
getCurrentCard(){
return this.activeCardStack[this.index];
return this.getCardByIndex(this.index);
}
getPageIndex(){
return this.index;
}
// API for contextual buttons
/**
* Retrieves state from the currently active page
* 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){
// 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 {
// 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));
// 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?
}
// 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.currentPage(), {components:this._renderComponents()}))
return this._edit(Object.assign(this.getCurrentCard(), {components:this._renderComponents()}))
}, 1500)
}
return;
}

View file

@ -0,0 +1,7 @@
const { DynamicCardStack } = require("./DynamicCardStack");
module.exports = {
createDynamicCardStack: (context, options)=>{
return new DynamicCardStack(context, options)
}
}

View file

@ -19,6 +19,7 @@
},
"imports": {
"#api": "./labscore/api/index.js",
"#cardstack": "./labscore/cardstack/index.js",
"#client": "./labscore/client.js",
"#constants": "./labscore/constants.js",
"#logging": "./labscore/logging.js",