[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 { anime, animeSupplemental} = require('#api');
const { paginator } = require('#client'); const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES, COLORS_HEX} = require('#constants');
const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES } = require('#constants');
const { createDynamicCardStack } = require("#cardstack");
const { hexToDecimalColor } = require("#utils/color"); const { hexToDecimalColor } = require("#utils/color");
const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed'); const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed');
const { acknowledge } = require('#utils/interactions'); 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 { editOrReply } = require('#utils/message');
const { InteractionContextTypes, ApplicationIntegrationTypes, ApplicationCommandOptionTypes } = require('detritus-client/lib/constants'); const { InteractionContextTypes, ApplicationIntegrationTypes, ApplicationCommandOptionTypes } = require('detritus-client/lib/constants');
const { STATIC_ASSETS } = require("#utils/statics");
function renderAnimeResultsPage(context, res){ function renderAnimeResultsPage(context, res){
let result = createEmbed("default", context, { let result = createEmbed("default", context, {
@ -59,7 +61,13 @@ function renderAnimeResultsPage(context, res){
} }
return page(result, {}, { 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) let search = await anime(context, args.query, context.channel.nsfw)
search = search.response 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 = [] let pages = []
for(const res of search.body.results){ 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.`)) if(!pages.length) return editOrReply(context, createEmbed("warning", context, `No results found.`))
await paginator.createPaginator({ createDynamicCardStack(context, {
context, cards: formatPaginationEmbeds(pages),
pages: formatPaginationEmbeds(pages),
interactive: { interactive: {
episodes_button: { episodes_button: {
// Button Label
label: "Episodes", label: "Episodes",
// Next to pagination or new row
inline: false, inline: false,
visible: true, visible: true,
condition: (page)=>{ condition: (page) => {
return (page.getState("episodes_key") !== null) return (page.getState("episodes_key") !== null)
}, },
// Will resolve all conditions at paginator creation time renderLoadingState: (pg) => {
precompute_conditions: true, return createEmbed("default", context, {
resolvePage: (page)=>{ description: `-# ${pg.getState("name")} **Episodes**`,
// If an interactive button for this index hasn't been image: {
// resolved yet, run this code url: STATIC_ASSETS.card_skeleton
page.getState("episodes_key"); // -> supplemental key },
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: { characters_button: {
// Button Label
label: "Characters", label: "Characters",
// Next to pagination or new row
inline: false, inline: false,
condition: (page)=>{ visible: true,
condition: (page) => {
return (page.getState("characters_key") !== null) return (page.getState("characters_key") !== null)
}, },
resolvePage: (page)=>{ renderLoadingState: (pg) => {
// If an interactive button for this index hasn't been return createEmbed("default", context, {
// resolved yet, run this code description: `-# ${pg.getState("name")} **Characters**`,
page.getState("characters_key"); // -> supplemental key 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){ }catch(e){
if(e.response?.body?.status == 1) 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)) if(e.response?.body?.status === 2) return editOrReply(context, createEmbed("warning", context, e.response?.body?.message))
console.log(e) console.log(e)
return editOrReply(context, createEmbed("error", context, `Unable to perform anime search.`)) return editOrReply(context, createEmbed("error", context, `Unable to perform anime search.`))

View file

@ -1,14 +1,14 @@
const { anime, animeSupplemental} = require('#api'); const { anime, animeSupplemental} = require('#api');
const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES, COLORS_HEX} = require('#constants'); const { PERMISSION_GROUPS, OMNI_ANIME_FORMAT_TYPES, COLORS_HEX} = require('#constants');
const { createDynamicCardStack } = require("#cardstack");
const { hexToDecimalColor } = require("#utils/color"); const { hexToDecimalColor } = require("#utils/color");
const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed'); const { createEmbed, formatPaginationEmbeds, page } = require('#utils/embed');
const { acknowledge } = require('#utils/interactions'); const { acknowledge } = require('#utils/interactions');
const { smallPill, link, pill, stringwrapPreserveWords, timestamp, TIMESTAMP_FLAGS} = require('#utils/markdown'); const { smallPill, link, pill, stringwrapPreserveWords, timestamp, TIMESTAMP_FLAGS} = require('#utils/markdown');
const { editOrReply } = require('#utils/message'); const { editOrReply } = require('#utils/message');
const { STATIC_ASSETS } = require("#utils/statics");
const { DynamicCardStack } = require("../../../labscore/cardstack/DynamicCardStack");
const {STATIC_ASSETS} = require("#utils/statics");
function renderAnimeResultsPage(context, res){ function renderAnimeResultsPage(context, res){
let result = createEmbed("default", context, { let result = createEmbed("default", context, {
@ -60,6 +60,8 @@ function renderAnimeResultsPage(context, res){
} }
return page(result, {}, { return page(result, {}, {
// Supplemental keys are provided by the backend,
// allow for fetching extra data related to results.
episodes_key: res.supplemental.episodes, episodes_key: res.supplemental.episodes,
characters_key: res.supplemental.characters, characters_key: res.supplemental.characters,
name: res.title, name: res.title,
@ -101,13 +103,11 @@ module.exports = {
if(!pages.length) return editOrReply(context, createEmbed("warning", context, `No results found.`)) if(!pages.length) return editOrReply(context, createEmbed("warning", context, `No results found.`))
new DynamicCardStack(context, { createDynamicCardStack(context, {
cards: formatPaginationEmbeds(pages), cards: formatPaginationEmbeds(pages),
interactive: { interactive: {
episodes_button: { episodes_button: {
// Button Label
label: "Episodes", label: "Episodes",
// Next to pagination or new row
inline: false, inline: false,
visible: true, visible: true,
condition: (page) => { condition: (page) => {
@ -154,9 +154,7 @@ module.exports = {
} }
}, },
characters_button: { characters_button: {
// Button Label
label: "Characters", label: "Characters",
// Next to pagination or new row
inline: false, inline: false,
visible: true, visible: true,
condition: (page) => { condition: (page) => {
@ -202,5 +200,5 @@ module.exports = {
console.log(e) console.log(e)
return editOrReply(context, createEmbed("error", context, `Unable to perform anime search.`)) 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 { Message } = require("detritus-client/lib/structures");
const { ComponentContext, Components, ComponentActionRow} = require("detritus-client/lib/utils"); const { ComponentContext, Components, ComponentActionRow} = require("detritus-client/lib/utils");
/**
* Stores all active card stacks
* @type {WeakMap<WeakKey, DynamicCardStack>}
*/
const activeStacks = new WeakMap(); const activeStacks = new WeakMap();
const DEFAULT_BUTTON_ICON_MAPPINGS = Object.freeze({ const DEFAULT_BUTTON_ICON_MAPPINGS = Object.freeze({
@ -15,12 +19,6 @@ const DEFAULT_BUTTON_ICON_MAPPINGS = Object.freeze({
"previous": "button_chevron_left" "previous": "button_chevron_left"
}); });
const SUBCATEGORY_STATE_TYPES = Object.freeze({
NONE: 0,
SINGLE_PAGE: 1,
MULTI_PAGE: 2,
});
const STACK_CACHE_KEYS = Object.freeze({ const STACK_CACHE_KEYS = Object.freeze({
RESULT_CARDS: 0 RESULT_CARDS: 0
}) })
@ -58,13 +56,13 @@ class DynamicCardStack {
this.stackCache = {}; this.stackCache = {};
this.pageState = []; this.pageState = [];
this.subcategoryState = SUBCATEGORY_STATE_TYPES.SINGLE_PAGE;
this.currentSelectedSubcategory = null; this.currentSelectedSubcategory = null;
/*
this.lastInteraction = Date.now(); this.lastInteraction = Date.now();
this.spawned = 0; this.spawned = 0;
*/
console.log("now spawning " + this.uniqueId)
this._spawn(); this._spawn();
} }
@ -76,31 +74,41 @@ class DynamicCardStack {
clearTimeout(this.timeout); clearTimeout(this.timeout);
this.listener.clear(); 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 // 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 * Get a Stack from an attached reference (message/interaction).
* @param {*} id Attached message ID * @param {Message} ref Attached message/interaction
* @returns {DynamicCardStack} * @returns {DynamicCardStack}
*/ */
_getStackByMessageId(id){ _getStackByReference(ref){
return activeStacks.get(id); return activeStacks.get(ref);
} }
/**
* Attaches a cardstack to its internal reference.
* @private
*/
_createDynamicCardStack(){ _createDynamicCardStack(){
// Kill any previously active cardstacks // Kill any previously active cardstacks on this reference
if(activeStacks.get(this.context.message)){ // (prevents oddities when editing a regular command)
console.log(this.uniqueId + " is replacing " + this._getStackByMessageId(this.context.message?.id).uniqueId); if(activeStacks.get(this.context.message || this.context.interaction)){
this._getStackByMessageId(this.context.message).kill(); 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(){ _createTimeout(){
return setTimeout(()=>{ return setTimeout(()=>{
/* /*
@ -127,7 +135,8 @@ class DynamicCardStack {
this.activeCardStack = [...this.cards]; this.activeCardStack = [...this.cards];
// Resolve page state before // Resolve page state for all
// root pages.
let i = 0; let i = 0;
for(const ac of this.cards){ for(const ac of this.cards){
if(ac["_meta"]){ if(ac["_meta"]){
@ -147,7 +156,7 @@ class DynamicCardStack {
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(),
@ -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]; 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; this.index = this.index + 1;
if(this.index >= this.activeCardStack.length){ if(this.index >= this.activeCardStack.length){
if(this.loopPages) this.index = 0; if(this.loopPages) this.index = 0;
} }
if(this.currentSelectedSubcategory == null) this.rootIndex = this.index; if(this.currentSelectedSubcategory == null) this.rootIndex = this.index;
console.log("new index: " + this.index) return Object.assign(this.getCardByIndex(this.index), { components: this._renderComponents() });
return Object.assign(this.getPageByIndex(this.index), { components: this._renderComponents() });
} }
/**
* Decreases the index and returns the next card from the stack.
* @returns {Message} Card
*/
previousPage(){ previousPage(){
this.index = this.index - 1; this.index = this.index - 1;
if(this.index < 0){ if(this.index < 0){
@ -181,11 +203,7 @@ class DynamicCardStack {
} }
if(this.currentSelectedSubcategory == null) this.rootIndex = this.index; if(this.currentSelectedSubcategory == null) this.rootIndex = this.index;
return Object.assign(this.getPageByIndex(this.index), { components: this._renderComponents() }); return Object.assign(this.getCardByIndex(this.index), { components: this._renderComponents() });
}
currentPage() {
return Object.assign(this.getPageByIndex(this.index), { components: this._renderComponents() });
} }
/** /**
@ -206,9 +224,6 @@ class DynamicCardStack {
if(message["_meta"]) delete message["_meta"]; if(message["_meta"]) delete message["_meta"];
//console.log("GOING OUT:")
//console.log(JSON.stringify(message, null, 2))
try{ try{
return editOrReply(this.context, { return editOrReply(this.context, {
...message, ...message,
@ -220,18 +235,17 @@ class DynamicCardStack {
} }
} }
/**
* Returns the currently selected card from the
* active stack.
* @returns {Message} Card
*/
getCurrentCard(){ 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 * @param {String} key
*/ */
getState(key){ getState(key){
@ -240,6 +254,11 @@ class DynamicCardStack {
return this.pageState[this.rootIndex][key]; return this.pageState[this.rootIndex][key];
} }
/**
* Returns all page state.
* Only really intended for debugging purposes.
* @returns {Object}
*/
getAllState(){ getAllState(){
return this.pageState; return this.pageState;
} }
@ -257,7 +276,7 @@ class DynamicCardStack {
type: MessageComponentTypes.BUTTON, type: MessageComponentTypes.BUTTON,
customId: b, customId: b,
style: 2, 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]) emoji: iconAsEmojiObject(DEFAULT_BUTTON_ICON_MAPPINGS[b])
} }
@ -279,22 +298,40 @@ class DynamicCardStack {
disabled: disabled 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(button.label){
if(typeof(button.label) === "function") component.label = button.label(this); if(typeof(button.label) === "function") component.label = button.label(this);
else component.label = button.label; else component.label = button.label;
} }
if(button.icon) component.emoji = iconAsEmojiObject(button.icon) || undefined 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(this.currentSelectedSubcategory === b) component.style = 1;
if(button.inline) nComponents.addButton(component); // Insert the component at the correct slot.
else { if(button.inline){
if(nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5){ // Ensure there is enough space for an inline component.
nComponentsSecondary.push(new ComponentActionRow({})) 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); nComponentsSecondary[nComponentsSecondary.length - 1].addButton(component);
} }
} }
@ -303,13 +340,40 @@ class DynamicCardStack {
return [nComponents]; 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){ _setCachedValue(index, componentId, key, value){
if(!this.stackCache[index]) this.stackCache[index] = {}; if(!this.stackCache[index]) this.stackCache[index] = {};
if(!this.stackCache[index][componentId]) this.stackCache[index][componentId] = {}; if(!this.stackCache[index][componentId]) this.stackCache[index][componentId] = {};
this.stackCache[index][componentId][key] = value; 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){ _getCachedValue(index, componentId, key){
if(this.interactive_components[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;
if(!this.stackCache[index][componentId][key]) 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 * @param {ComponentContext} ctx
*/ */
async _handleInteraction(ctx){ async _handleInteraction(ctx){
if(ctx.user.id !== this.context.user.id) return ctx.respond({ if(ctx.user.id !== this.context.user.id) return ctx.respond({
type: InteractionCallbackTypes.DEFERRED_UPDATE_MESSAGE 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)){ if(["next","previous"].includes(ctx.data.customId)){
console.log("triggering button")
switch(ctx.data.customId){ switch(ctx.data.customId){
case "next": case "next":
return ctx.respond({ return ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: this.nextPage() data: this.nextCard()
}) })
case "previous": case "previous":
return ctx.respond({ return ctx.respond({
@ -348,48 +411,72 @@ class DynamicCardStack {
return; return;
} }
// interactive buttons // Interactive Components
if(this.interactive_components[ctx.data.customId]){ 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){ if(this.currentSelectedSubcategory === ctx.data.customId){
console.log("restoring state")
this.activeCardStack = [...this.cards]; this.activeCardStack = [...this.cards];
this.index = this.rootIndex; this.index = this.rootIndex;
this.currentSelectedSubcategory = null; this.currentSelectedSubcategory = null;
return await ctx.respond({ return await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, 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; 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; this.index = 0;
try{ try{
// If we have a cached result, retrieve it
if(this._getCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS) !== null){ 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)]; this.activeCardStack = [...this._getCachedValue(this.rootIndex, ctx.data.customId, STACK_CACHE_KEYS.RESULT_CARDS)];
await ctx.respond({ await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.currentPage(), {components:this._renderComponents(false)}) data: Object.assign(this.getCurrentCard(), {components:this._renderComponents(false)})
}) })
return; return;
} else { } else {
let processingEmbed = page(createEmbed("default", ctx, { // Controls if we should display a loading (skeleton) embed while the
image: { // new stack is being fetched/rendered. Instant results should only
url: STATIC_ASSETS.card_skeleton // 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
await ctx.respond({ // TODO: maybe allow several loading modes here
type: InteractionCallbackTypes.UPDATE_MESSAGE, // i.e COPY_PARENT which will copy select fields
data: Object.assign(processingEmbed, { components: this._renderComponents(true)}) // 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); 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){ if(!this.interactive_components[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]);
} }
@ -400,11 +487,20 @@ class DynamicCardStack {
] ]
console.log("resolve failed:") console.log("resolve failed:")
console.log(e) console.log(e)
// TODO: better errors maybe?
} }
setTimeout(()=>{ // Update the card stack with a card from the new stack.
return this._edit(Object.assign(this.currentPage(), {components:this._renderComponents()})) if(this.interactive_components[ctx.data.customId].instantResult){
}, 1500) 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; 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": { "imports": {
"#api": "./labscore/api/index.js", "#api": "./labscore/api/index.js",
"#cardstack": "./labscore/cardstack/index.js",
"#client": "./labscore/client.js", "#client": "./labscore/client.js",
"#constants": "./labscore/constants.js", "#constants": "./labscore/constants.js",
"#logging": "./labscore/logging.js", "#logging": "./labscore/logging.js",