diff --git a/backend/src/models/Actor.js b/backend/src/models/Actor.js index a44b489a..19010dce 100644 --- a/backend/src/models/Actor.js +++ b/backend/src/models/Actor.js @@ -34,10 +34,57 @@ const ActorSchema = new Schema({ max: { type: Number, min: 0, default: 1 } }, proficiencies: { type: String, default: '' }, + // The skills the character is proficient with (Syndria98/dragonroll#83). Dragonroll holds + // whole names; services/actor-foundry.js translates the short keys a Foundry world uses. + skills: { + acrobatics: { type: Boolean, default: false }, + animalHandling: { type: Boolean, default: false }, + arcana: { type: Boolean, default: false }, + athletics: { type: Boolean, default: false }, + deception: { type: Boolean, default: false }, + history: { type: Boolean, default: false }, + insight: { type: Boolean, default: false }, + intimidation: { type: Boolean, default: false }, + investigation: { type: Boolean, default: false }, + medicine: { type: Boolean, default: false }, + nature: { type: Boolean, default: false }, + perception: { type: Boolean, default: false }, + performance: { type: Boolean, default: false }, + persuasion: { type: Boolean, default: false }, + religion: { type: Boolean, default: false }, + sleightOfHand: { type: Boolean, default: false }, + stealth: { type: Boolean, default: false }, + survival: { type: Boolean, default: false } + }, + // Which of the six saving throws the character adds its proficiency bonus to. + savingThrows: { + str: { type: Boolean, default: false }, + dex: { type: Boolean, default: false }, + con: { type: Boolean, default: false }, + int: { type: Boolean, default: false }, + wis: { type: Boolean, default: false }, + cha: { type: Boolean, default: false } + }, + // Tool and language proficiencies: plain names, one per entry. The free-form + // `proficiencies` text keeps whatever else the character is proficient with + // (armour and weapons, say), which has no list of its own. + tools: [{ type: String, trim: true }], + languages: [{ type: String, trim: true }], + // The coins the character holds, in the five D&D denominations. + currency: { + pp: { type: Number, min: 0, default: 0 }, + gp: { type: Number, min: 0, default: 0 }, + ep: { type: Number, min: 0, default: 0 }, + sp: { type: Number, min: 0, default: 0 }, + cp: { type: Number, min: 0, default: 0 } + }, inventory: [{ name: { type: String, trim: true, default: '' }, quantity: { type: Number, min: 1, default: 1 }, - weight: { type: Number, min: 0, default: 0 } + weight: { type: Number, min: 0, default: 0 }, + // The gear's own picture: what a Foundry world sends with the item it stands + // for, shown on the left of the inventory row. + icon: { type: String, default: '' } }], traits: { type: String, default: '' }, spells: { type: String, default: '' }, diff --git a/backend/src/routes/actor.js b/backend/src/routes/actor.js index d67375c2..3958bd54 100644 --- a/backend/src/routes/actor.js +++ b/backend/src/routes/actor.js @@ -22,6 +22,13 @@ function barPool(existing, value) { return { current, max }; } +// The tool and language lists (Syndria98/dragonroll#83): plain names, blank ones and +// repeats dropped. +function textList(value) { + if (!Array.isArray(value)) return []; + return [...new Set(value.map((name) => String(name).trim()).filter(Boolean))]; +} + // Folders the campaign's actors are grouped into, in the shape the sidebar groups by // (the notes, items and maps each keep a tree of their own, see models/Folder.js). async function actorFolders(campaignId) { @@ -65,7 +72,10 @@ router.post('/create', async (req, res) => { router.post('/update', async (req, res) => { try { - const { id, name, species, className, subclass, level, abilityScores, armorClass, speed, hitPoints, hitDice, proficiencies, inventory, traits, spells, image, folder } = req.body; + const { + id, name, species, className, subclass, level, abilityScores, armorClass, speed, hitPoints, hitDice, + proficiencies, skills, savingThrows, tools, languages, currency, inventory, traits, spells, image, folder + } = req.body; if (!id) return res.json({ status: 'error', msg: 'errors.missing-data' }); const actor = await Actor.findById(id); @@ -92,6 +102,14 @@ router.post('/update', async (req, res) => { if (hitPoints !== undefined) actor.hitPoints = barPool(actor.hitPoints, hitPoints); if (hitDice !== undefined) actor.hitDice = barPool(actor.hitDice, hitDice); if (proficiencies !== undefined) actor.proficiencies = proficiencies; + // The lists the sheet toggles and fills in (Syndria98/dragonroll#83): which skills + // and saving throws the character is proficient with, its tools, its languages and + // the coins it carries. + if (skills !== undefined) actor.skills = skills; + if (savingThrows !== undefined) actor.savingThrows = savingThrows; + if (tools !== undefined) actor.tools = textList(tools); + if (languages !== undefined) actor.languages = textList(languages); + if (currency !== undefined) actor.currency = currency; if (inventory !== undefined) actor.inventory = inventory; if (traits !== undefined) actor.traits = traits; if (spells !== undefined) actor.spells = spells; diff --git a/backend/src/services/actor-foundry.js b/backend/src/services/actor-foundry.js index c71bd1a3..8a23970c 100644 --- a/backend/src/services/actor-foundry.js +++ b/backend/src/services/actor-foundry.js @@ -23,6 +23,112 @@ function detailsName(value, items) { return looksLikeFoundryId(text) ? '' : text; } +// --- Skills, saving throws, tools, languages and coins (Syndria98/dragonroll#83) --- + +// The eighteen skills a 5e character has, as the system keys them and as Dragonroll +// names them. The short keys mean nothing outside Foundry, and Dragonroll's sheet holds +// the names it shows a user. +const FOUNDRY_SKILLS = { + acr: 'acrobatics', ani: 'animalHandling', arc: 'arcana', ath: 'athletics', dec: 'deception', + his: 'history', ins: 'insight', itm: 'intimidation', inv: 'investigation', med: 'medicine', + nat: 'nature', prc: 'perception', perf: 'performance', prs: 'persuasion', rel: 'religion', + sle: 'sleightOfHand', stl: 'stealth', sur: 'survival' +}; +const ABILITIES = ['str', 'dex', 'con', 'int', 'wis', 'cha']; +const CURRENCIES = ['pp', 'gp', 'ep', 'sp', 'cp']; + +// Whether one of the system's proficiency fields says the character has that +// proficiency. The system has held it several ways across its releases — a boolean, a +// number of proficiency steps, a list of proficiency modes ('prof', 'exp'), or one of +// those under `value`, `proficient` or `prof` — and worlds run different releases of +// it. Anything above nothing counts as proficient. +function isProficient(value, depth = 0) { + if (value === undefined || value === null || depth > 3) return false; + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value > 0; + if (typeof value === 'string') { + const text = value.trim(); + if (!text) return false; + const number = Number(text); + return Number.isFinite(number) ? number > 0 : text.toLowerCase() !== 'none'; + } + if (Array.isArray(value)) return value.some((entry) => isProficient(entry, depth + 1)); + return ['value', 'proficient', 'prof'].some((key) => isProficient(value[key], depth + 1)); +} + +// A toggled map (skill name or ability → proficient) from whatever the actor lists. +// `null` says the actor says nothing about them at all, which is what keeps a live +// Foundry edit from clearing the toggles the campaign set by hand. +function toggleMap(sources) { + const toggled = {}; + for (const [name, value] of Object.entries(sources)) { + if (value !== undefined) toggled[name] = isProficient(value); + } + return Object.keys(toggled).length ? toggled : null; +} + +function foundrySkills(system) { + const skills = system.skills && typeof system.skills === 'object' ? system.skills : {}; + return toggleMap(Object.fromEntries(Object.entries(FOUNDRY_SKILLS) + .map(([key, name]) => [name, skills[key]]))); +} + +function foundrySavingThrows(system) { + const saves = system.saves && typeof system.saves === 'object' ? system.saves : {}; + return toggleMap(Object.fromEntries(ABILITIES.map((key) => [ + key, + system.savingThrows?.[key] ?? system.abilities?.[key]?.save ?? saves[key] + ]))); +} + +// Tools and languages: the module sends the labels its own CONFIG holds, because a +// world's proficiency lists are keys — and, since the third system release, language +// documents — that mean nothing outside Foundry. Without them the keys are the best +// there is to name a proficiency with, and a bare Foundry document id is worse than +// nothing at all. `null` says the actor says nothing about the kind, `[]` that it has +// none of it. Dragonroll names its lists in full; the world keeps its tools under +// `system.traits.tool` and its languages under `system.traits.languages`. +const TRAIT_FIELDS = { tools: 'tool', languages: 'languages' }; + +function foundryTraitNames(actor, kind) { + const labels = actor.dragonroll?.[kind]; + if (Array.isArray(labels)) { + return [...new Set(labels.map((label) => asText(label).trim()).filter(Boolean))]; + } + const trait = actor.system?.traits?.[TRAIT_FIELDS[kind] ?? kind]; + if (!trait || typeof trait !== 'object') return null; + const names = [ + ...stringList(trait.value), + ...asText(trait.custom).split(',').map((name) => name.trim()) + ].filter((name) => name && !looksLikeFoundryId(name)); + return [...new Set(names)]; +} + +function foundryCurrency(system) { + const coins = system.currency; + if (!coins || typeof coins !== 'object') return null; + return Object.fromEntries(CURRENCIES.map((key) => [key, Math.max(0, numberOr(coins[key], 0))])); +} + +// The character's traits as the world writes them: the free-text details field some +// system releases keep, or its trait items, which are how a monster's traits and a +// character's racial and class features are written. `undefined` says the world holds +// no traits to show. +function foundryTraits(source, items) { + const text = plainText(source.system?.details?.trait); + if (text) return text; + const features = items + .filter((item) => item.type === 'feat' && stringList(item.system?.featType?.value ?? item.system?.featType) + .some((type) => asText(type).toLowerCase().startsWith('tr'))) + .map((item) => { + const name = asText(item.name).trim(); + const description = plainText(item.system?.description?.value ?? item.system?.description); + return name ? `${name}\n${description}`.trim() : ''; + }) + .filter(Boolean); + return features.length ? features.join('\n\n') : undefined; +} + function foundryActorToCharacter(foundryActor) { const system = foundryActor.system || {}; const details = system.details || {}; @@ -43,7 +149,7 @@ function foundryActorToCharacter(foundryActor) { ...stringList(traits.tool?.value) ].join(', '); - return { + const fields = { name: asText(foundryActor.name).trim(), type: ['character', 'npc', 'creature'].includes(savedDragonrollType) ? savedDragonrollType @@ -56,24 +162,45 @@ function foundryActorToCharacter(foundryActor) { challengeRating: String(details.cr ?? ''), description: plainText(details.biography?.value || details.biography), image: asText(foundryActor.img || foundryActor.image), - abilityScores: Object.fromEntries(['str', 'dex', 'con', 'int', 'wis', 'cha'].map((key) => [ + abilityScores: Object.fromEntries(ABILITIES.map((key) => [ key, numberOr(abilities[key]?.value, 10) ])), armorClass: numberOr(attributes.ac?.value ?? attributes.ac, 10), speed: numberOr(movement.walk ?? movement.value, 30), proficiencies: foundryProficiencies || asText(savedDragonrollFields.proficiencies), - traits: asText(savedDragonrollFields.traits), inventory: items .filter((item) => !['class', 'subclass', 'background', 'spell'].includes(item.type)) .map((item) => ({ name: asText(item.name).trim(), quantity: numberOr(item.system?.quantity, 1), - weight: numberOr(item.system?.weight?.value ?? item.system?.weight, 0) + weight: numberOr(item.system?.weight?.value ?? item.system?.weight, 0), + icon: asText(item.img).trim() })) .filter((item) => item.name), spells: items.filter((item) => item.type === 'spell').map((item) => asText(item.name)).filter(Boolean).join('\n') }; + + // What the world says about each of these, when it says anything: leaving a field + // out of the character is what keeps a live Foundry edit from clearing what the + // campaign toggled or wrote for it. Traits lead from the world when it has them, the + // way the proficiencies do; the text the module carries back on its flag is what the + // tab shows for an actor the world says nothing about. + const skills = foundrySkills(system); + if (skills) fields.skills = skills; + const savingThrows = foundrySavingThrows(system); + if (savingThrows) fields.savingThrows = savingThrows; + const tools = foundryTraitNames(foundryActor, 'tools'); + if (tools) fields.tools = tools; + const languages = foundryTraitNames(foundryActor, 'languages'); + if (languages) fields.languages = languages; + const currency = foundryCurrency(system); + if (currency) fields.currency = currency; + const worldTraits = foundryTraits(foundryActor, items); + const campaignTraits = asText(savedDragonrollFields.traits); + if (worldTraits || campaignTraits) fields.traits = worldTraits || campaignTraits; + + return fields; } module.exports = { foundryActorToCharacter }; diff --git a/dragonroll-foundry/scripts/api.js b/dragonroll-foundry/scripts/api.js index e7a18f84..ade39d53 100644 --- a/dragonroll-foundry/scripts/api.js +++ b/dragonroll-foundry/scripts/api.js @@ -474,9 +474,50 @@ function serializeFoundryActor(actor) { if (data.img && !/^(https?:|data:|\/\/)/i.test(data.img)) { data.img = new URL(data.img, window.location.origin).toString(); } + // Tools and languages travel by their names: what the actor holds are proficiency + // keys (and, since the third release of the system, language documents), which mean + // nothing to a sheet outside Foundry. + const names = { tools: foundryTraitNames(actor, "tools"), languages: foundryTraitNames(actor, "languages") }; + if (names.tools || names.languages) data.dragonroll = { ...names }; return data; } +// A proficiency list of `system.traits`: its keys resolved to the labels CONFIG gives +// them, plus whatever the GM typed as a proficiency of their own. `null` for an actor +// that has no such list, an empty array for one that has none of that kind. Dragonroll +// names its lists in full, while the world keeps its tools under `system.traits.tool` +// and its languages under `system.traits.languages`. +const TRAIT_FIELDS = { tools: "tool", languages: "languages" }; + +function foundryTraitNames(actor, kind) { + if (game.system?.id !== "dnd5e") return null; + const trait = actor.system?.traits?.[TRAIT_FIELDS[kind] ?? kind]; + if (!trait || typeof trait !== "object") return null; + + const names = (Array.isArray(trait.value) ? trait.value : []) + .map((key) => foundryProficiencyLabel(kind, key)) + .filter(Boolean); + for (const custom of String(trait.custom ?? "").split(",")) { + const name = custom.trim(); + if (name) names.push(name); + } + return [...new Set(names)]; +} + +function foundryProficiencyLabel(kind, key) { + if (typeof key !== "string" || !key) return ""; + + const entry = CONFIG.DND5E?.[kind === "languages" ? "languages" : "tools"]?.[key]; + const label = entry?.label ?? entry?.name; + if (label) return String(label); + // A language the world added itself stands as a document of its own rather than in + // the system's config. + const document = kind === "languages" ? game.items?.get?.(key) : null; + if (document?.name) return String(document.name); + // The key beats dropping a proficiency the character really has. + return key; +} + function isSupportedCharacterActor(actor) { const savedType = actor.getFlag?.(MODULE_ID, "actorType") || actor.flags?.[MODULE_ID]?.actorType; return ["character", "npc", "creature"].includes(savedType || actor.type); diff --git a/frontend/app/components/windows/CharacterSheetWindow.vue b/frontend/app/components/windows/CharacterSheetWindow.vue index 9d6c0908..93b75ae8 100644 --- a/frontend/app/components/windows/CharacterSheetWindow.vue +++ b/frontend/app/components/windows/CharacterSheetWindow.vue @@ -24,6 +24,23 @@ const abilityStats = [ { key: 'int', label: 'INT' }, { key: 'wis', label: 'WIS' }, { key: 'cha', label: 'CHA' } ]; +// Les habilitats del 5e. Cada una té un cercle que s'encén quan el personatge hi és +// proficient, i la modificadora que tira és la de la característica que mana. +const skillList = [ + { key: 'acrobatics', ability: 'dex' }, { key: 'animalHandling', ability: 'wis' }, + { key: 'arcana', ability: 'int' }, { key: 'athletics', ability: 'str' }, + { key: 'deception', ability: 'cha' }, { key: 'history', ability: 'int' }, + { key: 'insight', ability: 'wis' }, { key: 'intimidation', ability: 'cha' }, + { key: 'investigation', ability: 'int' }, { key: 'medicine', ability: 'wis' }, + { key: 'nature', ability: 'int' }, { key: 'perception', ability: 'wis' }, + { key: 'performance', ability: 'cha' }, { key: 'persuasion', ability: 'cha' }, + { key: 'religion', ability: 'int' }, { key: 'sleightOfHand', ability: 'dex' }, + { key: 'stealth', ability: 'dex' }, { key: 'survival', ability: 'wis' } +]; + +// Les cinc monedes que un personatge porta al damunt. +const currencyUnits = ['pp', 'gp', 'ep', 'sp', 'cp']; + // Les pestanyes del lateral dret reparteixen la fitxa: característiques i combat, // inventari, trets i conjurs. Són pestanyes de marcadors, no una pàgina nova. const tabs = [ @@ -39,6 +56,17 @@ const activeTab = ref('abilities'); // per sota de 760px el marc les fa estar a dins i el marge deixa de fer falta. const TAB_RAIL_WIDTH = 150; +// Les eines i els idiomes viatgen com a llista i el formulari els edita com un quadre +// de text: un nom per línia. Les comes també separen, que és com s'escriuen en una frase. +function proficiencyText(value) { + const names = Array.isArray(value) ? value : String(value ?? '').split(/[\n,]/); + return [...new Set(names.map((name) => String(name).trim()).filter(Boolean))].join('\n'); +} + +function proficiencyList(text) { + return [...new Set(String(text ?? '').split(/[\n,]/).map((name) => String(name).trim()).filter(Boolean))]; +} + function normalizeActor(actor) { return { name: actor?.name ?? '', @@ -60,8 +88,17 @@ function normalizeActor(actor) { max: Number(actor?.hitDice?.max ?? actor?.level ?? 1) }, proficiencies: actor?.proficiencies ?? '', + // El que el personatge sap fer i el que porta: les habilitats i les tirades de + // salvació són cercles que s'encenen, les eines i els idiomes són noms que el + // formulari edita com un text d'una línia per nom, i la moneda són cinc xifres. + skills: Object.fromEntries(skillList.map(({ key }) => [key, Boolean(actor?.skills?.[key])])), + savingThrows: Object.fromEntries(abilityStats.map(({ key }) => [key, Boolean(actor?.savingThrows?.[key])])), + tools: proficiencyText(actor?.tools), + languages: proficiencyText(actor?.languages), + currency: Object.fromEntries(currencyUnits.map((unit) => [unit, Number(actor?.currency?.[unit] ?? 0) || 0])), inventory: (actor?.inventory ?? []).map((item) => ({ - name: item.name ?? '', quantity: Number(item.quantity ?? 1), weight: Number(item.weight ?? 0) + name: item.name ?? '', quantity: Number(item.quantity ?? 1), weight: Number(item.weight ?? 0), + icon: item.icon ?? '' })), traits: actor?.traits ?? '', spells: actor?.spells ?? '', @@ -110,17 +147,37 @@ const carryingCapacity = computed(() => form.value.abilityScores.str * 15); const carriedWeight = computed(() => form.value.inventory.reduce((total, item) => total + (Number(item.quantity) || 0) * (Number(item.weight) || 0), 0)); const carryPercent = computed(() => Math.min(100, carryingCapacity.value ? (carriedWeight.value / carryingCapacity.value) * 100 : 0)); -function abilityModifier(score) { - const modifier = Math.floor((Number(score) - 10) / 2); +// `bonus` és el bonificador de proficiència, per a les habilitats i les tirades de +// salvació del personatge que hi està entrenat. +function abilityModifier(score, bonus = 0) { + const modifier = Math.floor((Number(score) - 10) / 2) + (Number(bonus) || 0); return modifier >= 0 ? `+${modifier}` : String(modifier); } -const imageUrl = computed(() => { - if (!form.value.image) return ''; - return /^(https?:|data:|\/\/)/i.test(form.value.image) - ? form.value.image - : `${getBaseUrl()}/public/${form.value.image}`; -}); +function skillModifier(skill) { + return abilityModifier(form.value.abilityScores[skill.ability], form.value.skills[skill.key] ? proficiencyBonus.value : 0); +} + +function savingThrowModifier(stat) { + return abilityModifier(form.value.abilityScores[stat.key], form.value.savingThrows[stat.key] ? proficiencyBonus.value : 0); +} + +// El cercle d'una habilitat o d'una salvació: s'encén i s'apaga, i es desa amb tota la +// fitxa, com la resta del que s'edita. +function toggleProficiency(group, key) { + form.value[group][key] = !form.value[group][key]; +} + +// Una imatge pot ser una adreça sencera (la que Foundry dona a un objecte, per +// exemple) o un fitxer pujat aquí, que es serveix per `/api/public`. +function resolveImage(image) { + if (!image) return ''; + return /^(https?:|data:|\/\/)/i.test(image) + ? image + : `${getBaseUrl()}/public/${image}`; +} + +const imageUrl = computed(() => resolveImage(form.value.image)); function pickPhoto() { photoInput.value?.click(); @@ -184,6 +241,9 @@ async function saveSheet() { const payload = { id: actorId, ...form.value, + // Les eines i els idiomes van a l'API com a llista, que és com està desats. + tools: proficiencyList(form.value.tools), + languages: proficiencyList(form.value.languages), inventory: form.value.inventory.filter((item) => item.name.trim()) }; const response = await Server().post('/actor/update', payload); @@ -337,12 +397,68 @@ async function saveSheet() { {{ abilityModifier(form.abilityScores[stat.key]) }} + + +

{{ $t('campaigns.character-sheet.saving-throws') }}

+
+ +
+ + +
+

{{ $t('campaigns.character-sheet.skills') }}

+
+ +

{{ $t('campaigns.character-sheet.proficiencies') }}