diff --git a/scripts/better-tables.js b/scripts/better-tables.js index 4b0b3e5d..9745f1bc 100644 --- a/scripts/better-tables.js +++ b/scripts/better-tables.js @@ -4,8 +4,10 @@ import { StoryBuilder } from './story/story-builder.js'; import { StoryChatCard } from './story/story-chat-card.js'; import { BRTBuilder } from './core/brt-builder.js'; import { BetterResults } from './core/brt-table-results.js'; +import { getRandomItemFromCompendium } from "./core/utils.js"; import { BRTCONFIG } from "./core/config.js"; + export class BetterTables { __constructor() { this._spellCache = undefined; @@ -175,6 +177,14 @@ export class BetterTables { BetterTables.menuCallBackCreateTable(li.data('pack')); } }); + + options.push({ + "name": "Roll on compendium", + "icon": '', + "callback": li => { + BetterTables.menuCallBackRollCompendium(li.data('pack')); + } + }); } /** @@ -208,4 +218,29 @@ export class BetterTables { const rolltable = game.tables.get(rolltable_id); await game.betterTables.betterTableRoll(rolltable); } + + /** + * + * @param {String} compendium ID of the compendium to roll + */ + static async menuCallBackRollCompendium(compendium) { + // Get random item from compendium + const item = await getRandomItemFromCompendium(compendium); + + // prepare card data + const fontSize = Math.max(60, 100 - Math.max(0, item.name.length - 27) * 2); + const chatCardData = { + itemsData: [ + { item: item, quantity: 1, fontSize: fontSize } + ] + }; + const cardHtml = await renderTemplate("modules/better-rolltables/templates/loot-chat-card.hbs", chatCardData); + const chatData = { + flavor: `Rolled from compendium ${item.pack}`, + sound: "sounds/dice.wav", + user: game.user.data._id, + content: cardHtml + }; + ChatMessage.create(chatData); + } } \ No newline at end of file diff --git a/scripts/core/utils.js b/scripts/core/utils.js index 87178b32..0293c2b6 100644 --- a/scripts/core/utils.js +++ b/scripts/core/utils.js @@ -45,4 +45,22 @@ export function separateIdComendiumName(stringWithComendium) { */ export async function getItemFromCompendium(item) { return findInCompendiumByName(item.collection, item.text); +} + +/** + * + * @param {object} compendium reference to compendium to roll + * @returns {object} item from compendium + */ +export async function getRandomItemFromCompendium(compendium) { + const pack = game.packs.get(compendium); + if (!pack) return; + const size = pack.index.size; + if (size === 0) { + ui.notifications.warn(`Compendium ${pack.title} is empty.`); + return; + } + const randonIndex = Math.floor(Math.random() * size); + const randomItem = pack.index.contents[randonIndex]; + return pack.getDocument(randomItem._id); } \ No newline at end of file