236 lines
12 KiB
JavaScript
236 lines
12 KiB
JavaScript
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
|
|
const { isFoundryGearType } = require('./item-foundry');
|
|
|
|
// D&D 5e keeps an actor's background, species, class and subclass as a reference to an
|
|
// embedded item: `system.details.background` and friends hold that item's id, and the
|
|
// field's `fallback` option hands back the bare id when the item is gone. Dragonroll
|
|
// holds names, so a reference is read through the actor's items and an id that resolves
|
|
// to nothing is dropped. An id travelling back as a name is how Foundry ends up with a
|
|
// background item — and a details reference — that does not exist (Syndria98/dragonroll#54).
|
|
const FOUNDRY_DOCUMENT_ID = /^[A-Za-z0-9_-]{16}$/;
|
|
|
|
function looksLikeFoundryId(value) {
|
|
// Sixteen plain letters is a name; the ids Foundry generates carry a digit.
|
|
return FOUNDRY_DOCUMENT_ID.test(value) && /[0-9]/.test(value) && /[A-Za-z]/.test(value);
|
|
}
|
|
|
|
// The name a `system.details` entry stands for: an embedded item's id resolves to that
|
|
// item's name, and plain text (older system releases store the name here) is the name.
|
|
function detailsName(value, items) {
|
|
const text = asText(value).trim();
|
|
if (!text) return '';
|
|
const referenced = items.find((item) => asText(item?._id ?? item?.id).trim() === text);
|
|
if (referenced) return asText(referenced.name).trim();
|
|
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 features: D&D 5e files species, background, class and monster features
|
|
// under the `feat` item type, each with its text and picture on the item. They are what
|
|
// the sheet's traits tab lists, one row per feature.
|
|
function foundryFeatures(items) {
|
|
return items
|
|
.filter((item) => item.type === 'feat')
|
|
.map((item) => ({
|
|
name: asText(item.name).trim(),
|
|
description: plainText(item.system?.description?.value ?? item.system?.description),
|
|
icon: asText(item.img).trim()
|
|
}))
|
|
.filter((feature) => feature.name);
|
|
}
|
|
|
|
// The free-form traits text: the details field some system releases keep, or what the
|
|
// campaign wrote and the module carries back on its flag. `undefined` says the world
|
|
// holds no text of its own, which keeps a live edit from clearing the campaign's.
|
|
function foundryTraits(source, savedDragonrollFields, replace) {
|
|
const text = plainText(source.system?.details?.trait);
|
|
const campaignTraits = replace ? '' : asText(savedDragonrollFields.traits);
|
|
return text || campaignTraits || undefined;
|
|
}
|
|
|
|
// `replace` is a forced actor sync from the module's context menu (Syndria98/dragonroll#96):
|
|
// it replaces everything the campaign holds for this actor, so the fields a live edit
|
|
// leaves out when the world says nothing are written empty instead of kept. A live Foundry
|
|
// change passes `false` and keeps the campaign's own toggles and text.
|
|
function foundryActorToCharacter(foundryActor, replace = false) {
|
|
const system = foundryActor.system || {};
|
|
const details = system.details || {};
|
|
const abilities = system.abilities || {};
|
|
const attributes = system.attributes || {};
|
|
const movement = attributes.movement || {};
|
|
const items = Array.isArray(foundryActor.items) ? foundryActor.items : [];
|
|
const classItem = items.find((item) => item.type === 'class');
|
|
const subclassItem = items.find((item) => item.type === 'subclass');
|
|
const backgroundItem = items.find((item) => item.type === 'background');
|
|
const traits = system.traits || {};
|
|
const savedDragonrollFields = foundryActor.flags?.['dragonroll-foundry'] || {};
|
|
const savedDragonrollType = savedDragonrollFields.actorType;
|
|
const foundryProficiencies = [
|
|
...stringList(traits.languages?.value),
|
|
...stringList(traits.armor?.value),
|
|
...stringList(traits.weapon?.value),
|
|
...stringList(traits.tool?.value)
|
|
].join(', ');
|
|
|
|
const fields = {
|
|
name: asText(foundryActor.name).trim(),
|
|
type: ['character', 'npc', 'creature'].includes(savedDragonrollType)
|
|
? savedDragonrollType
|
|
: (['character', 'npc', 'creature'].includes(foundryActor.type) ? foundryActor.type : 'character'),
|
|
species: detailsName(details.race || details.species, items),
|
|
className: detailsName(details.class, items) || asText(classItem?.name),
|
|
subclass: detailsName(details.subclass, items) || asText(subclassItem?.name),
|
|
level: numberOr(details.level ?? classItem?.system?.levels, 1),
|
|
background: detailsName(details.background, items) || asText(backgroundItem?.name),
|
|
challengeRating: String(details.cr ?? ''),
|
|
description: plainText(details.biography?.value || details.biography),
|
|
image: asText(foundryActor.img || foundryActor.image),
|
|
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),
|
|
// A replace takes the world's text even when it has none, so what Dragonroll
|
|
// cached on the actor's flag does not survive it; a live edit keeps that text.
|
|
proficiencies: foundryProficiencies || (replace ? '' : asText(savedDragonrollFields.proficiencies)),
|
|
// What the character carries: gear, and gear only (Syndria98/dragonroll#89). A feat
|
|
// is a trait — its tab shows it — and a race is the species; standing them in the
|
|
// inventory next to the longswords is how traits and items got mixed up.
|
|
inventory: items
|
|
.filter((item) => isFoundryGearType(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),
|
|
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'),
|
|
// The features themselves, icons and all: the traits tab draws them like the
|
|
// inventory, and a live edit sends the world's whole item list, so a feature the
|
|
// GM removed in Foundry goes here too.
|
|
features: foundryFeatures(items)
|
|
};
|
|
|
|
// 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, savedDragonrollFields, replace);
|
|
if (worldTraits) fields.traits = worldTraits;
|
|
|
|
// A replace writes the fields a live edit would leave out when the world says
|
|
// nothing, so the campaign's toggles, lists and text for this actor go with it and
|
|
// the row reads as the Foundry actor alone (Syndria98/dragonroll#96).
|
|
if (replace) {
|
|
if (fields.skills === undefined) fields.skills = {};
|
|
if (fields.savingThrows === undefined) fields.savingThrows = {};
|
|
if (fields.tools === undefined) fields.tools = [];
|
|
if (fields.languages === undefined) fields.languages = [];
|
|
if (fields.currency === undefined) fields.currency = {};
|
|
if (fields.traits === undefined) fields.traits = '';
|
|
}
|
|
|
|
return fields;
|
|
}
|
|
|
|
module.exports = { foundryActorToCharacter };
|