[nextgen/cardstack] add BUTTON_GENERATOR

- support dynamic button resolving
- update all commands using dynstack to latest api
- add supplemental to wolfram
This commit is contained in:
bignutty 2025-02-21 00:42:21 +01:00
parent 3a016dde3d
commit ecaaba9d3c
10 changed files with 356 additions and 176 deletions

View file

@ -2,7 +2,7 @@ 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/index"); const { createDynamicCardStack } = require("#cardstack/index");
const { ResolveCallbackTypes } = require("#cardstack/constants"); const { ResolveCallbackTypes, InteractiveComponentTypes} = require("#cardstack/constants");
const { hexToDecimalColor } = require("#utils/color"); const { hexToDecimalColor } = require("#utils/color");
const { createEmbed, page } = require('#utils/embed'); const { createEmbed, page } = require('#utils/embed');
@ -121,6 +121,7 @@ module.exports = {
cards: pages, cards: pages,
interactive: { interactive: {
episodes_button: { episodes_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Episodes", label: "Episodes",
inline: false, inline: false,
visible: true, visible: true,
@ -176,6 +177,7 @@ module.exports = {
} }
}, },
characters_button: { characters_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Characters", label: "Characters",
inline: false, inline: false,
visible: true, visible: true,
@ -217,6 +219,7 @@ module.exports = {
} }
}, },
related_button: { related_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Related", label: "Related",
inline: false, inline: false,
visible: true, visible: true,

View file

@ -2,7 +2,7 @@ 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/index"); const { createDynamicCardStack } = require("#cardstack/index");
const { ResolveCallbackTypes } = require("#cardstack/constants"); const { ResolveCallbackTypes, InteractiveComponentTypes} = require("#cardstack/constants");
const { hexToDecimalColor } = require("#utils/color"); const { hexToDecimalColor } = require("#utils/color");
const { createEmbed, page } = require('#utils/embed'); const { createEmbed, page } = require('#utils/embed');
@ -110,6 +110,7 @@ module.exports = {
cards: pages, cards: pages,
interactive: { interactive: {
episodes_button: { episodes_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Episodes", label: "Episodes",
inline: false, inline: false,
visible: true, visible: true,
@ -165,6 +166,7 @@ module.exports = {
} }
}, },
characters_button: { characters_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Characters", label: "Characters",
inline: false, inline: false,
visible: true, visible: true,
@ -206,6 +208,7 @@ module.exports = {
} }
}, },
related_button: { related_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Related", label: "Related",
inline: false, inline: false,
visible: true, visible: true,

View file

@ -2,11 +2,10 @@ const { googleNews, googleNewsSupplemental} = require('#api');
const { PERMISSION_GROUPS } = require('#constants'); const { PERMISSION_GROUPS } = require('#constants');
const { createDynamicCardStack } = require("#cardstack/index"); const { createDynamicCardStack } = require("#cardstack/index");
const { ResolveCallbackTypes } = require("#cardstack/constants"); const { ResolveCallbackTypes, InteractiveComponentTypes} = require("#cardstack/constants");
const { createEmbed, page } = require('#utils/embed'); const { createEmbed, page } = require('#utils/embed');
const { acknowledge } = require('#utils/interactions'); const { acknowledge } = require('#utils/interactions');
const { link } = require('#utils/markdown');
const { editOrReply } = require('#utils/message'); const { editOrReply } = require('#utils/message');
const { STATIC_ASSETS, STATIC_ICONS, STATICS} = require("#utils/statics"); const { STATIC_ASSETS, STATIC_ICONS, STATICS} = require("#utils/statics");
@ -76,6 +75,7 @@ module.exports = {
cards: pages, cards: pages,
interactive: { interactive: {
full_coverage_button: { full_coverage_button: {
type: InteractiveComponentTypes.BUTTON,
label: "Full Coverage", label: "Full Coverage",
icon: "button_full_coverage", icon: "button_full_coverage",
inline: true, inline: true,
@ -83,7 +83,7 @@ module.exports = {
return (pg.getState("full_coverage_key") !== null) return (pg.getState("full_coverage_key") !== null)
}, },
condition: true, condition: true,
renderLoadingState: (pg) => { renderLoadingState: () => {
return createEmbed("default", context, { return createEmbed("default", context, {
author: { author: {
name: "Full Coverage", name: "Full Coverage",

View file

@ -1,4 +1,4 @@
const {wolframAlpha} = require("#api"); const { wolframAlpha, wolframSupplemental} = require("#api");
const { paginator } = require('#client'); const { paginator } = require('#client');
const { PERMISSION_GROUPS } = require('#constants'); const { PERMISSION_GROUPS } = require('#constants');
@ -6,10 +6,12 @@ const { createEmbed, formatPaginationEmbeds, 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')
const { STATICS } = require('#utils/statics') const { STATICS, STATIC_ASSETS} = require('#utils/statics')
const {createDynamicCardStack} = require("#cardstack/index");
const {InteractiveComponentTypes, ResolveCallbackTypes} = require("#cardstack/constants");
function createWolframPage(context, pod, query, sources) { function createWolframPage(context, pod, query, sources) {
let res = page(createEmbed("default", context, { let res = createEmbed("default", context, {
author: { author: {
name: pod.title, name: pod.title,
url: `https://www.wolframalpha.com/input?i=${encodeURIComponent(query)}` url: `https://www.wolframalpha.com/input?i=${encodeURIComponent(query)}`
@ -19,24 +21,28 @@ function createWolframPage(context, pod, query, sources) {
iconUrl: STATICS.wolframalpha, iconUrl: STATICS.wolframalpha,
text: `Wolfram|Alpha • ${context.application.name}` text: `Wolfram|Alpha • ${context.application.name}`
} }
})) })
if (pod.icon) res.embeds[0].author.iconUrl = pod.icon if (pod.icon) res.author.iconUrl = pod.icon
if (pod.value) res.embeds[0].description = pod.value.substr(0, 1000) if (pod.value) res.description = pod.value.substr(0, 1000)
if (pod.value && pod.refs) { if (pod.value && pod.refs) {
for (const r of pod.refs) { for (const r of pod.refs) {
let src = Object.values(sources).filter((s) => s.ref == r)[0] let src = Object.values(sources).filter((s) => s.ref === r)[0]
if (!src) continue; if (!src) continue;
// Only add a direct source if one is available // Only add a direct source if one is available
if (src.collections) { if (src.collections) {
res.embeds[0].description += citation(r, src.url, src.title + ' | ' + src.collections[0].text) res.description += citation(r, src.url, src.title + ' | ' + src.collections[0].text)
continue; continue;
} }
if (src.url) res.embeds[0].description += citation(r, src.url, src.title) if (src.url) res.description += citation(r, src.url, src.title)
} }
} }
if (pod.image) res.embeds[0].image = { url: pod.image }; if (pod.image) res.image = { url: pod.image };
return res; return page(res, {}, {
supplemental: pod.states,
pod_icon: pod.icon,
pod_title: pod.title
});
} }
module.exports = { module.exports = {
@ -55,7 +61,6 @@ module.exports = {
run: async (context, args) => { run: async (context, args) => {
await acknowledge(context); await acknowledge(context);
if(context.message.messageReference) { if(context.message.messageReference) {
let msg = await context.message.channel.fetchMessage(context.message.messageReference.messageId); let msg = await context.message.channel.fetchMessage(context.message.messageReference.messageId);
if(msg.content && msg.content.length) args.query = msg.content if(msg.content && msg.content.length) args.query = msg.content
@ -67,16 +72,54 @@ module.exports = {
let search = await wolframAlpha(context, args.query) let search = await wolframAlpha(context, args.query)
search = search.response search = search.response
if (search.body.status == 1) return editOrReply(context, createEmbed("warning", context, search.body.message)) if (search.body.status === 1) return editOrReply(context, createEmbed("warning", context, search.body.message))
let pages = [] let pages = []
for (const res of search.body.data) { for (const res of search.body.data) {
pages.push(createWolframPage(context, res, args.query, search.body.sources)) pages.push(createWolframPage(context, res, args.query, search.body.sources))
} }
await paginator.createPaginator({
context, return await createDynamicCardStack(context, {
pages: formatPaginationEmbeds(pages) cards: pages,
interactive: {
state_buttons: {
type: InteractiveComponentTypes.BUTTON_GENERATOR,
inline: true,
// Resolve Components
resolveComponents: (pg)=>{
if(!pg.getState("supplemental") || pg.getState("supplemental").length === 0) return [];
return pg.getState("supplemental").map((b)=>{
return {
label: b.label,
visible: true,
condition: true,
customId: b.supplemental_key,
icon: "button_wolfram_compute",
renderLoadingState: (pg, component) => {
return createEmbed("default", context, {
author: {
name: `${pg.getState("pod_title")} ${component.label}`,
iconUrl: pg.getState("pod_icon")
},
image: {
url: STATIC_ASSETS.chat_loading
}
})
},
resolvePage: async (pg, component)=>{
let sup = await wolframSupplemental(context, component.customId);
return {
type: ResolveCallbackTypes.REPLACE_PARENT_CARD,
card: createWolframPage(context, sup.response.body.pod_supplemental, args.query, sup.response.body.sources)
}
}
}
})
}
}
}
}); });
} catch (e) { } catch (e) {
if(e.response.body?.error) return editOrReply(context, createEmbed("warning", context, e.response.body.error.message)) if(e.response.body?.error) return editOrReply(context, createEmbed("warning", context, e.response.body.error.message))

View file

@ -54,6 +54,7 @@ const Api = Object.freeze({
SEARCH_WEATHER: '/search/weather', SEARCH_WEATHER: '/search/weather',
SEARCH_WIKIHOW: '/search/wikihow', SEARCH_WIKIHOW: '/search/wikihow',
SEARCH_WOLFRAM_ALPHA: '/search/wolfram-alpha', SEARCH_WOLFRAM_ALPHA: '/search/wolfram-alpha',
SEARCH_WOLFRAM_SUPPLEMENTAL: '/search/wolfram-supplemental',
SEARCH_YOUTUBE: '/search/youtube', SEARCH_YOUTUBE: '/search/youtube',
TTS_IMTRANSLATOR: '/tts/imtranslator', TTS_IMTRANSLATOR: '/tts/imtranslator',

View file

@ -126,7 +126,7 @@ module.exports.googleImages = async function(context, query, nsfw){
}) })
} }
module.exports.googleNews = async function(context, query, nsfw){ module.exports.googleNews = async function(context, query){
return await request(Api.SEARCH_GOOGLE_NEWS, "GET", {}, { return await request(Api.SEARCH_GOOGLE_NEWS, "GET", {}, {
q: query q: query
}) })
@ -232,6 +232,12 @@ module.exports.wolframAlpha = async function(context, query){
}) })
} }
module.exports.wolframSupplemental = async function(context, supplementalKey){
return await request(Api.SEARCH_WOLFRAM_SUPPLEMENTAL, "GET", {}, {
supplemental_key: supplementalKey
})
}
module.exports.youtube = async function(context, query, category){ module.exports.youtube = async function(context, query, category){
return await request(Api.SEARCH_YOUTUBE, "GET", {}, { return await request(Api.SEARCH_YOUTUBE, "GET", {}, {
q: query, q: query,

View file

@ -22,12 +22,32 @@ module.exports.STACK_CACHE_KEYS = Object.freeze({
* - This callback type will also unselect the button * - This callback type will also unselect the button
* - `REPLACE_ROOT_STACK` - Replaces the root stack * - `REPLACE_ROOT_STACK` - Replaces the root stack
* - This callback type will also unselect the button * - This callback type will also unselect the button
*
* @readonly
* @enum {number}
*/ */
module.exports.ResolveCallbackTypes = Object.freeze({ module.exports.ResolveCallbackTypes = Object.freeze({
SUBSTACK: 0, UNKNOWN_CALLBACK_TYPE: 0,
REPLACE_PARENT_CARD: 1, SUBSTACK: 1,
REPLACE_STACK: 2, REPLACE_PARENT_CARD: 2,
0: "SUBSTACK", REPLACE_STACK: 3
1: "REPLACE_PARENT_CARD",
2: "REPLACE_STACK",
}) })
/**
* @typedef {number} InteractiveComponentTypes
**/
/**
* Interactive Component Type
*
* @readonly
* @enum {InteractiveComponentTypes}
*/
module.exports.InteractiveComponentTypes = Object.freeze({
/** Unknown Component Value */
UNKNOWN_COMPONENT_TYPE: 0,
/** A singular dynamic button */
BUTTON: 1,
/** Button generator that can return as many buttons as are necessary. */
BUTTON_GENERATOR: 2
});

View file

@ -8,9 +8,16 @@ const { STATIC_ASSETS } = require("#utils/statics");
const {Context} = require("detritus-client/lib/command"); const {Context} = require("detritus-client/lib/command");
const {MessageComponentTypes, InteractionCallbackTypes} = require("detritus-client/lib/constants"); const {MessageComponentTypes, InteractionCallbackTypes} = require("detritus-client/lib/constants");
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, ComponentButton} = require("detritus-client/lib/utils");
const {DEFAULT_BUTTON_ICON_MAPPINGS, STACK_CACHE_KEYS, BuiltInButtonTypes, ResolveCallbackTypes} = require("./constants"); const {
DEFAULT_BUTTON_ICON_MAPPINGS,
STACK_CACHE_KEYS,
BuiltInButtonTypes,
ResolveCallbackTypes
} = require("./constants");
const {InteractiveComponentTypes} = require("#cardstack/constants");
const {Xid} = require("#utils/hash");
/** /**
* Stores all active card stacks * Stores all active card stacks
@ -56,6 +63,8 @@ class DynamicCardStack {
this.pageState = []; this.pageState = [];
this.currentSelectedSubcategory = null; this.currentSelectedSubcategory = null;
this.currentComponentsBatch = {};
/* /*
this.lastInteraction = Date.now(); this.lastInteraction = Date.now();
this.spawned = 0; this.spawned = 0;
@ -81,6 +90,7 @@ class DynamicCardStack {
* Get a Stack from an attached reference (message/interaction). * Get a Stack from an attached reference (message/interaction).
* @param {Message} ref Attached message/interaction * @param {Message} ref Attached message/interaction
* @returns {DynamicCardStack} * @returns {DynamicCardStack}
* @private
*/ */
_getStackByReference(ref) { _getStackByReference(ref) {
return activeStacks.get(ref); return activeStacks.get(ref);
@ -125,6 +135,7 @@ class DynamicCardStack {
/** /**
* Creates a new cardstack in the given channel * Creates a new cardstack in the given channel
* @private
*/ */
_spawn() { _spawn() {
try { try {
@ -314,38 +325,23 @@ class DynamicCardStack {
return this.pageState[index] || {}; return this.pageState[index] || {};
} }
/** /**
* Renders components and button states * Renders an InteractiveComponent as a ComponentButton
* @param id (Parent) Component ID
* @param button InteractiveComponent
* @param disabled Disabled by default
* @returns ComponentButton Button Component
*/ */
_renderComponents(disabled = false){ _renderButton(id, button, disabled = false) {
let nComponents = new ComponentActionRow({})
let nComponentsSecondary = [new ComponentActionRow({})]
// First Row always starts with built-in components
for(const b of this.buttons){
let btn = {
type: MessageComponentTypes.BUTTON,
customId: b,
style: 2,
disabled: this.activeCardStack.length === 1 || disabled,
emoji: iconAsEmojiObject(DEFAULT_BUTTON_ICON_MAPPINGS[b])
}
nComponents.addButton(btn)
}
for(const b of Object.keys(this.interactive_components)){
let button = this.interactive_components[b];
// Validate if the component should be visible on this page. // Validate if the component should be visible on this page.
// If a function is provided we need to execute it. // If a function is provided we need to execute it.
if(typeof(button.visible) === "boolean" && button.visible === false) continue; if (typeof (button.visible) === "boolean" && button.visible === false) return null;
else if(typeof(button.visible) === "function" && !button.visible(this)) continue; else if (typeof (button.visible) === "function" && !button.visible(this)) return null;
let component = { let component = {
type: MessageComponentTypes.BUTTON, type: MessageComponentTypes.BUTTON,
customId: b, // id/XID is used for dynamically generated components via BUTTON_GENERATOR
customId: button.customId ? id + "/" + Xid(button.customId) : id,
style: button.style || 2, style: button.style || 2,
disabled: disabled disabled: disabled
} }
@ -364,8 +360,58 @@ class DynamicCardStack {
// Change color if this is the active button. // Change color if this is the active button.
// TODO: allow overwriting the "active" color // TODO: allow overwriting the "active" color
if(this.currentSelectedSubcategory === b) component.style = 1; if (this.currentSelectedSubcategory === id) component.style = 1;
// Add to active components cache
this.currentComponentsBatch[component.customId] = button;
return new ComponentButton(component);
}
/**
* Renders components and button states
* @private
*/
_renderComponents(disabled = false) {
// Cache of all currently active (interactive) components.
this.currentComponentsBatch = {};
let nComponents = new ComponentActionRow({})
let nComponentsSecondary = [new ComponentActionRow({})]
// First Row always starts with built-in components
for (const b of this.buttons) {
let btn = {
type: MessageComponentTypes.BUTTON,
customId: b,
style: 2,
disabled: this.activeCardStack.length === 1 || disabled,
emoji: iconAsEmojiObject(DEFAULT_BUTTON_ICON_MAPPINGS[b])
}
nComponents.addButton(btn)
}
for (const b of Object.keys(this.interactive_components)) {
let button = this.interactive_components[b];
let renderedButtons = [];
switch (button.type) {
case InteractiveComponentTypes.BUTTON:
renderedButtons.push(this._renderButton(b, button, disabled));
break;
case InteractiveComponentTypes.BUTTON_GENERATOR:
// Resolve buttons to be rendered
let _buttons = button.resolveComponents(this);
for (const btn of _buttons) {
renderedButtons.push(this._renderButton(b, btn, disabled));
}
break;
default:
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. // Insert the component at the correct slot.
if (button.inline) { if (button.inline) {
// Ensure there is enough space for an inline component. // Ensure there is enough space for an inline component.
@ -374,9 +420,9 @@ class DynamicCardStack {
if (nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5) if (nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5)
nComponentsSecondary.push(new ComponentActionRow({})) nComponentsSecondary.push(new ComponentActionRow({}))
nComponentsSecondary[nComponentsSecondary.length - 1].addButton(component); nComponentsSecondary[nComponentsSecondary.length - 1].addButton(r);
} else { } else {
nComponents.addButton(component); nComponents.addButton(r);
} }
} else { } else {
// Ensure there is space on secondary rows to insert // Ensure there is space on secondary rows to insert
@ -384,7 +430,9 @@ class DynamicCardStack {
if (nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5) if (nComponentsSecondary[nComponentsSecondary.length - 1].components.length >= 5)
nComponentsSecondary.push(new ComponentActionRow({})) nComponentsSecondary.push(new ComponentActionRow({}))
nComponentsSecondary[nComponentsSecondary.length - 1].addButton(component); nComponentsSecondary[nComponentsSecondary.length - 1].addButton(r);
}
}
} }
} }
@ -424,7 +472,7 @@ class DynamicCardStack {
* @private * @private
*/ */
_getCachedValue(index, componentId, key) { _getCachedValue(index, componentId, key) {
if(this.interactive_components[componentId].disableCache) return null; if (this.currentComponentsBatch[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;
@ -435,6 +483,7 @@ class DynamicCardStack {
/** /**
* Handles an interaction from the attached components. * Handles an interaction from the attached components.
* @param {ComponentContext} ctx * @param {ComponentContext} ctx
* @private
*/ */
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({
@ -463,10 +512,12 @@ class DynamicCardStack {
} }
// Interactive Components // Interactive Components
if(this.interactive_components[ctx.data.customId]){ let cid = ctx.data.customId;
if (this.currentComponentsBatch[cid]) {
// 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 === ctx.data.customId){ if (this.currentSelectedSubcategory === cid) {
this.activeCardStack = [...this.cards]; this.activeCardStack = [...this.cards];
this.index = this.rootIndex; this.index = this.rootIndex;
this.currentSelectedSubcategory = null; this.currentSelectedSubcategory = null;
@ -475,15 +526,14 @@ class DynamicCardStack {
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.getCurrentCard(), {components: this._renderComponents(false)}) data: Object.assign(this.getCurrentCard(), {components: this._renderComponents(false)})
}) })
} } else this.currentSelectedSubcategory = cid;
else this.currentSelectedSubcategory = ctx.data.customId;
let resolveTime = Date.now(); let resolveTime = Date.now();
try { try {
// If we have a cached result, retrieve it // 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, cid, 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, cid, STACK_CACHE_KEYS.RESULT_CARDS)];
await ctx.respond({ await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
data: Object.assign(this.getCurrentCard(), {components: this._renderComponents(false)}) data: Object.assign(this.getCurrentCard(), {components: this._renderComponents(false)})
@ -494,7 +544,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.interactive_components[ctx.data.customId].instantResult) { if (!this.currentComponentsBatch[cid].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
@ -506,8 +556,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.interactive_components[ctx.data.customId].renderLoadingState) if (this.currentComponentsBatch[cid].renderLoadingState)
processingEmbed = page(this.interactive_components[ctx.data.customId].renderLoadingState(this)); processingEmbed = page(this.currentComponentsBatch[cid].renderLoadingState(this, this.currentComponentsBatch[cid]));
await ctx.respond({ await ctx.respond({
type: InteractionCallbackTypes.UPDATE_MESSAGE, type: InteractionCallbackTypes.UPDATE_MESSAGE,
@ -516,7 +566,7 @@ class DynamicCardStack {
} }
// Compute the active cardstack. // Compute the active cardstack.
let resolvedNewStack = await this.interactive_components[ctx.data.customId].resolvePage(this); let resolvedNewStack = await this.currentComponentsBatch[cid].resolvePage(this, this.currentComponentsBatch[cid]);
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})`);
@ -541,7 +591,7 @@ class DynamicCardStack {
// 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/refetching since the parent
// has changed and might carry new data. // has changed and might carry new data.
if(!this.interactive_components[ctx.data.customId].disableCache){ if (!this.currentComponentsBatch[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;
@ -595,7 +645,7 @@ class DynamicCardStack {
} }
// Update the card stack with a card from the new stack. // Update the card stack with a card from the new stack.
if(this.interactive_components[ctx.data.customId].instantResult){ if (this.currentComponentsBatch[ctx.data.customId].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()})

View file

@ -101,6 +101,7 @@ module.exports.ICONS_NEXTGEN = Object.freeze({
"open_in_new_alt": "<:nextgen_ico_open_in_new_alt:1336075859181965322>", "open_in_new_alt": "<:nextgen_ico_open_in_new_alt:1336075859181965322>",
"button_full_coverage": "<:ico_full_coverage:1341535912017793045>", "button_full_coverage": "<:ico_full_coverage:1341535912017793045>",
"button_wolfram_compute": "<:ico_wolfram_compute:1342276477269577758>",
/* Brands */ /* Brands */
"brand": "<:nextgen_ico_brand:1336064940670193780>", "brand": "<:nextgen_ico_brand:1336064940670193780>",

53
labscore/utils/hash.js Normal file
View file

@ -0,0 +1,53 @@
// Adapted from https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/Xid.java
const START_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const CHARS = START_CHARS + "0123456789";
const START_RADIX = START_CHARS.length;
const RADIX = CHARS.length;
/**
* A simple utility for shortening identifiers in a stable way. Generates
* short substitution strings deterministically, using a compact
* (1 to 6 characters in length) repesentation of a 32-bit hash of the key.
* The string is suitable to be used as a JavaScript or CSS identifier.
* Collisions are possible but unlikely, depending on the underlying hash algorithm used.
*
* This substitution scheme uses case-sensitive names for maximum
* compression. Digits are also allowed in all but the first character of a
* class name. There are a few characters allowed by the CSS grammar that we
* choose not to use (e.g. the underscore and hyphen), to keep names simple.
*
* Xid should maintain as minimal dependencies as possible to ease its
* integration with other tools, such as server side HTML generators.
*
* (https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/Xid.java#L18-L32)
*
* @param input Input
* @returns {string} Xid
*/
module.exports.Xid = (input) => {
if(typeof(input)==="string"){
var h = 0, i, c;
if (input.length === 0) return h;
for (i = 0; i < input.length; i++) {
c = input.charCodeAt(i);
h = ((h << 5) - h) + c;
h |= 0;
}
if(h<=0) h = h*-1;
input = h;
}
const buf = new Array(6);
let len = 0;
let l = input - Math.floor(Number.MIN_SAFE_INTEGER);
buf[len++] = START_CHARS.charAt(Math.floor(l % START_RADIX));
input = Math.floor(l / START_RADIX);
while (input > 0) {
buf[len++] = CHARS.charAt(input % RADIX);
input = Math.floor(input / RADIX);
}
return buf.slice(0, len).reverse().join("");
}