From 3ab7b46d6b160e2dd5b14fc96c3da9baa3d079f6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 19 Sep 2026 06:37:29 +0200 Subject: [PATCH] feat: add craft imports and skill subtabs --- AGENTS.md | 4 +- README.md | 27 ++++++ TASKS.md | 7 ++ docs/craft-json-v1.md | 106 ++++++++++++++++++++ docs/macros.md | 55 +++++++++++ docs/ravenous-craft-v1.schema.json | 101 +++++++++++++++++++ ravenous_typst | 2 +- roll20_mod/ravenous_craft_import.js | 145 ++++++++++++++++++++++++++++ src/ravenous.css | 14 ++- src/ravenous.html | 5 +- tests/test_build.py | 10 +- tests/test_craft_import.mjs | 98 +++++++++++++++++++ tests/test_worker.mjs | 1 + tools/build.py | 51 +++++++--- 14 files changed, 602 insertions(+), 24 deletions(-) create mode 100644 docs/craft-json-v1.md create mode 100644 docs/macros.md create mode 100644 docs/ravenous-craft-v1.schema.json create mode 100644 roll20_mod/ravenous_craft_import.js create mode 100644 tests/test_craft_import.mjs diff --git a/AGENTS.md b/AGENTS.md index 7188374..36d152c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,9 @@ The main inputs are `ravenous_typst/data/src/character_sheet.yaml`, `ravenous_typst/data/src/schools/*.tsv`, `ravenous_typst/data/src/origines/*.yaml`, glossary YAML, and `ravenous_typst/data/config/build.yaml`. Only school tiers below `build.max_tier_exclusive` are imported. At the pinned submodule revision the -build reports 141 skills and 275 techniques across 11 schools. +build reports 126 sheet skills and 275 techniques across 11 schools. The 15 +resistance definitions remain in the book data but are represented by the +dedicated resistance fields instead of being duplicated in the Skills tab. The monster database is a nested submodule at `ravenous_typst/data/src/db/monsters.db`; initialize it with `git -C ravenous_typst submodule update --init data/src/db` before converter tests. diff --git a/README.md b/README.md index 4f48c76..7768877 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,33 @@ Ces tests simulent l'API Mod et valident le format avec la base épinglée. Un essai dans une partie Roll20 reste nécessaire pour confirmer l'affichage et les limites des GM Notes. +## Import d'objets fabriqués + +`roll20_mod/ravenous_craft_import.js` importe les résultats finalisés d'un +futur site d'artisanat dans un personnage existant. Le contrat JSON versionné +et les exemples sont définis dans [`docs/craft-json-v1.md`](docs/craft-json-v1.md). +Il couvre les armes, protections, consommables et effets temporaires. Le Mod ne +recalcule pas la recette et n'applique aucun effet automatiquement. + +Installez le script comme Mod, puis sélectionnez le token du personnage et +utilisez un JSON direct ou les GM Notes d'un handout privé : + +```text +!ravenous-import-craft {"format":"ravenous-roll20-craft","version":1,"items":[{"type":"consumable","name":"Potion rouge","kind":"Potion","quantity":1}]} +!ravenous-import-craft --handout ID_DU_HANDOUT +!ravenous-import-craft --id ID_DU_PERSONNAGE --handout ID_DU_HANDOUT +``` + +Les joueurs peuvent utiliser cette commande uniquement avec un personnage +qu'ils contrôlent et un handout auquel ils ont accès. Le MJ n'est pas soumis à +ces restrictions. Des actions de macro prêtes à copier pour cet import et les +autres commandes Mod sont regroupées dans [`docs/macros.md`](docs/macros.md). +Vérification locale : + +```sh +node tests/test_craft_import.mjs +``` + ## Mise à jour depuis le livre ```sh diff --git a/TASKS.md b/TASKS.md index e234e0b..c930b61 100644 --- a/TASKS.md +++ b/TASKS.md @@ -22,9 +22,16 @@ parser, browser, or chat. - [x] Add a GM-only character JSON export/import Mod script and a monster database converter. Verify round trips, repeating rows, invalid input, and all master-visible monsters locally. +- [x] Define the versioned craft JSON interface and add a GM-only Mod importer + for weapons, protections, consumables, and temporary effects. Validate all + destinations, handout input, and invalid payloads locally. ## Next: Roll20 smoke test +- [ ] Install `roll20_mod/ravenous_craft_import.js`, import one entry of each + supported type from inline JSON and from a private handout, then reopen the + destination sheet and confirm every field persists. + - [x] Install `roll20_mod/ravenous_import_name.js` as a New Script in a test game, run `!ravenous-import-name {"name":"Ariane"}` as GM, and confirm a single new character appears in the journal. **2026-09-17:** user reports diff --git a/docs/craft-json-v1.md b/docs/craft-json-v1.md new file mode 100644 index 0000000..6cf2cc2 --- /dev/null +++ b/docs/craft-json-v1.md @@ -0,0 +1,106 @@ +# Ravenous craft JSON interface, version 1 + +The machine-readable contract is +[`ravenous-craft-v1.schema.json`](ravenous-craft-v1.schema.json); this page +documents its intended use. + +The crafting website exports finalized sheet values. The Roll20 importer does +not reproduce or verify crafting rules: it validates the envelope, then creates +one repeating sheet row per item. This separation lets the website evolve its +recipe UI without coupling it to Roll20 attribute names. + +## Envelope + +```json +{ + "format": "ravenous-roll20-craft", + "version": 1, + "craft": { + "name": "Lame de braise", + "discipline": "forge", + "element": "Feu", + "recipe": "Acier; Affilage", + "level": 3, + "difficulty": 2 + }, + "items": [] +} +``` + +`items` is required and contains 1–100 entries. `craft` is optional metadata +for producers and archives; the importer validates but does not put it on the +sheet. Put any metadata that players must see in the item's `notes`, `effects`, +or `description` field. Text values are limited to 10,000 characters (names to +150). Numbers must be finite. Unknown fields are rejected so producer mistakes +do not silently disappear. + +## Item types + +Each item requires `type` and a non-empty `name`. Omitted fields keep the +sheet's normal default. JSON numbers and strings are accepted for sheet fields. +For attacks, `dice` is an optional default for the **Nombre de dés** prompt; the +player chooses the actual pool whenever the attack is rolled. + +| `type` | Destination | Allowed fields besides `type` | +| --- | --- | --- | +| `attack` | Combat → Attaques | `name`, `dice`, `threshold`, `temp`, `base_damage`, `damage_per_success`, `break_damage`, `rmax`, `notes`, `dodge_threshold`, `parry_threshold`, `reposition_threshold` | +| `protection` | Combat → Protections | `name`, `protection`, `integrity`, `integrity_max`, `parry`, `dodge`, `effects` | +| `consumable` | Potions & nourriture | `name`, `kind`, `quantity`, `duration`, `description` | +| `modifier` | Effets temporaires | `name`, `duration`, `description` | + +For a consumable, `kind` is exactly `Nourriture`, `Potion`, or `Autre`. +Protection imports intentionally omit `active`: imported armor must be selected +manually for the struck location. The importer never spends ingredients, +changes HP, equips an item, or applies its effects. + +Example containing two outputs from one craft: + +```json +{ + "format": "ravenous-roll20-craft", + "version": 1, + "craft": { "name": "Expédition ardente", "discipline": "forge", "element": "Feu" }, + "items": [ + { + "type": "attack", + "name": "Lame de braise", + "dice": 5, + "threshold": 6, + "base_damage": 8, + "damage_per_success": 2, + "break_damage": 1, + "rmax": 3, + "notes": "Feu — Acier; Affilage" + }, + { + "type": "consumable", + "name": "Huile de braise", + "kind": "Autre", + "quantity": 2, + "duration": "1 combat", + "description": "Enduit une arme; effet déterminé par la recette." + } + ] +} +``` + +## Roll20 commands + +Install `roll20_mod/ravenous_craft_import.js` as a Mod script. Commands are +GM-only. With one destination token selected: + +```text +!ravenous-import-craft {"format":"ravenous-roll20-craft","version":1,"items":[{"type":"consumable","name":"Potion rouge","kind":"Potion","quantity":1}]} +!ravenous-import-craft --handout HANDOUT_ID +``` + +Without a token, or to target a character directly: + +```text +!ravenous-import-craft --id CHARACTER_ID {JSON} +!ravenous-import-craft --id CHARACTER_ID --handout HANDOUT_ID +``` + +For large JSON, paste it into a private handout's **GM Notes** and use the +handout form. Open the destination sheet after import so its workers refresh +derived protection summaries. diff --git a/docs/macros.md b/docs/macros.md new file mode 100644 index 0000000..1ea2680 --- /dev/null +++ b/docs/macros.md @@ -0,0 +1,55 @@ +# Ravenous Roll20 macro memo + +These actions can be pasted into **Collections → Macros → Action**. Install the +corresponding scripts from `roll20_mod/` first. Enable **Show as Token Action** +when the macro operates on a selected token. + +## Player craft import + +The player selects a token linked to a character they control. The JSON must be +stored in the GM Notes of a handout shared with or controlled by that player. + +**Name:** `Ravenous — Importer un objet` + +```text +!ravenous-import-craft --handout ?{ID du handout d'artisanat} +``` + +Players cannot import into another player's character or read an unshared +handout through the script. A GM can use the same macro with any character and +handout. + +## GM character import + +Character import creates a new journal character and remains GM-only. Put the +export JSON in a private handout's GM Notes. + +**Name:** `Ravenous — Importer un personnage` + +```text +!ravenous-import --handout ?{ID du handout personnage} +``` + +## GM character export + +Select one token linked to the character to export. + +**Name:** `Ravenous — Exporter le personnage` + +```text +!ravenous-export +``` + +## GM craft import by character ID + +Useful when the destination character has no token selected. + +**Name:** `Ravenous — Import artisanat par ID` + +```text +!ravenous-import-craft --id ?{ID du personnage} --handout ?{ID du handout d'artisanat} +``` + +Roll20 IDs are the final identifier in the character or handout URL. Handout +imports are preferred over pasting JSON into a query because JSON punctuation +can interfere with Roll20's query syntax. diff --git a/docs/ravenous-craft-v1.schema.json b/docs/ravenous-craft-v1.schema.json new file mode 100644 index 0000000..8d5b0bb --- /dev/null +++ b/docs/ravenous-craft-v1.schema.json @@ -0,0 +1,101 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://books.dandaedre.com/ravenous_sheet/ravenous-craft-v1.schema.json", + "title": "Ravenous Roll20 craft exchange", + "type": "object", + "additionalProperties": false, + "required": ["format", "version", "items"], + "properties": { + "format": { "const": "ravenous-roll20-craft" }, + "version": { "const": 1 }, + "craft": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { "$ref": "#/$defs/name" }, + "discipline": { "$ref": "#/$defs/text" }, + "element": { "$ref": "#/$defs/text" }, + "recipe": { "$ref": "#/$defs/text" }, + "level": { "$ref": "#/$defs/value" }, + "difficulty": { "$ref": "#/$defs/value" } + } + }, + "items": { + "type": "array", + "minItems": 1, + "maxItems": 100, + "items": { + "oneOf": [ + { "$ref": "#/$defs/attack" }, + { "$ref": "#/$defs/protection" }, + { "$ref": "#/$defs/consumable" }, + { "$ref": "#/$defs/modifier" } + ] + } + } + }, + "$defs": { + "name": { "type": "string", "minLength": 1, "maxLength": 150 }, + "text": { "type": "string", "maxLength": 10000 }, + "value": { "oneOf": [{ "$ref": "#/$defs/text" }, { "type": "number" }] }, + "attack": { + "type": "object", + "additionalProperties": false, + "required": ["type", "name"], + "properties": { + "type": { "const": "attack" }, + "name": { "$ref": "#/$defs/name" }, + "dice": { "$ref": "#/$defs/value" }, + "threshold": { "$ref": "#/$defs/value" }, + "temp": { "$ref": "#/$defs/value" }, + "base_damage": { "$ref": "#/$defs/value" }, + "damage_per_success": { "$ref": "#/$defs/value" }, + "break_damage": { "$ref": "#/$defs/value" }, + "rmax": { "$ref": "#/$defs/value" }, + "notes": { "$ref": "#/$defs/value" }, + "dodge_threshold": { "$ref": "#/$defs/value" }, + "parry_threshold": { "$ref": "#/$defs/value" }, + "reposition_threshold": { "$ref": "#/$defs/value" } + } + }, + "protection": { + "type": "object", + "additionalProperties": false, + "required": ["type", "name"], + "properties": { + "type": { "const": "protection" }, + "name": { "$ref": "#/$defs/name" }, + "protection": { "$ref": "#/$defs/value" }, + "integrity": { "$ref": "#/$defs/value" }, + "integrity_max": { "$ref": "#/$defs/value" }, + "parry": { "$ref": "#/$defs/value" }, + "dodge": { "$ref": "#/$defs/value" }, + "effects": { "$ref": "#/$defs/value" } + } + }, + "consumable": { + "type": "object", + "additionalProperties": false, + "required": ["type", "name"], + "properties": { + "type": { "const": "consumable" }, + "name": { "$ref": "#/$defs/name" }, + "kind": { "enum": ["Nourriture", "Potion", "Autre"] }, + "quantity": { "$ref": "#/$defs/value" }, + "duration": { "$ref": "#/$defs/value" }, + "description": { "$ref": "#/$defs/value" } + } + }, + "modifier": { + "type": "object", + "additionalProperties": false, + "required": ["type", "name"], + "properties": { + "type": { "const": "modifier" }, + "name": { "$ref": "#/$defs/name" }, + "duration": { "$ref": "#/$defs/value" }, + "description": { "$ref": "#/$defs/value" } + } + } + } +} diff --git a/ravenous_typst b/ravenous_typst index 3e1310d..c47e56d 160000 --- a/ravenous_typst +++ b/ravenous_typst @@ -1 +1 @@ -Subproject commit 3e1310d2f0735823eb69fce30cb1bd7bae534fab +Subproject commit c47e56d8f87981e489c5408e592167da30e8bf34 diff --git a/roll20_mod/ravenous_craft_import.js b/roll20_mod/ravenous_craft_import.js new file mode 100644 index 0000000..af52a5a --- /dev/null +++ b/roll20_mod/ravenous_craft_import.js @@ -0,0 +1,145 @@ +/* Ravenous craft importer for Roll20 Mod. Commands: + * !ravenous-import-craft JSON (selected token) + * !ravenous-import-craft --id CHARACTER_ID JSON + * !ravenous-import-craft --handout HANDOUT_ID (selected token) + * !ravenous-import-craft --id CHARACTER_ID --handout HANDOUT_ID + * Players are limited to controlled characters and accessible handouts. + * See docs/craft-json-v1.md for the versioned interface. + */ +(function () { + 'use strict'; + var COMMAND = '!ravenous-import-craft'; + var FORMAT = 'ravenous-roll20-craft'; + var VERSION = 1; + var LIMITS = { items: 100, text: 10000, name: 150 }; + var FIELDS = { + attack: ['name', 'dice', 'threshold', 'temp', 'base_damage', 'damage_per_success', + 'break_damage', 'rmax', 'notes', 'dodge_threshold', 'parry_threshold', + 'reposition_threshold'], + protection: ['name', 'protection', 'integrity', 'integrity_max', 'parry', 'dodge', + 'effects'], + consumable: ['kind', 'name', 'quantity', 'duration', 'description'], + modifier: ['name', 'duration', 'description'] + }; + var REQUIRED = { + attack: ['name'], protection: ['name'], consumable: ['name'], modifier: ['name'] + }; + + function whisper(message) { sendChat('Ravenous Craft', '/w gm ' + message); } + function grantsAccess(list, playerId) { + return String(list || '').split(',').some(function (id) { return id === 'all' || id === playerId; }); + } + function canControl(character, playerId) { + return playerIsGM(playerId) || grantsAccess(character && character.get('controlledby'), playerId); + } + function canReadHandout(handout, playerId) { + return playerIsGM(playerId) || grantsAccess(handout && handout.get('controlledby'), playerId) || + grantsAccess(handout && handout.get('inplayerjournals'), playerId); + } + function plainObject(value) { + return value && !Array.isArray(value) && typeof value === 'object'; + } + function validValue(value, key) { + if (typeof value === 'number') return isFinite(value); + return typeof value === 'string' && value.length <= (key === 'name' ? LIMITS.name : LIMITS.text); + } + function validPayload(data) { + if (!plainObject(data) || data.format !== FORMAT || data.version !== VERSION || + Object.keys(data).some(function (key) { return ['format', 'version', 'craft', 'items'].indexOf(key) < 0; }) || + !Array.isArray(data.items) || !data.items.length || data.items.length > LIMITS.items) return false; + if (data.craft !== undefined) { + if (!plainObject(data.craft)) return false; + var metadata = ['name', 'discipline', 'element', 'recipe', 'level', 'difficulty']; + if (Object.keys(data.craft).some(function (key) { return metadata.indexOf(key) < 0; }) || + Object.keys(data.craft).some(function (key) { return !validValue(data.craft[key], key); })) return false; + } + return data.items.every(function (item) { + if (!plainObject(item) || !FIELDS[item.type]) return false; + var allowed = ['type'].concat(FIELDS[item.type]); + if (Object.keys(item).some(function (key) { return allowed.indexOf(key) < 0; })) return false; + if (REQUIRED[item.type].some(function (key) { + return typeof item[key] !== 'string' || !item[key].trim() || item[key].length > LIMITS.name; + })) return false; + if (Object.keys(item).some(function (key) { return key !== 'type' && !validValue(item[key], key); })) return false; + return item.type !== 'consumable' || item.kind === undefined || + ['Nourriture', 'Potion', 'Autre'].indexOf(item.kind) >= 0; + }); + } + function decodeHandout(raw) { + var text = String(raw || ''); + text = text.replace(//gi, '\n').replace(/<\/(?:p|div)>/gi, '\n') + .replace(/<[^>]*>/g, '').replace(/"/g, '"').replace(/'/g, "'") + .replace(/</g, '<').replace(/>/g, '>') + .replace(/&#(?:x([0-9a-f]+)|([0-9]+));/gi, function (_, hex, decimal) { + return String.fromCodePoint(parseInt(hex || decimal, hex ? 16 : 10)); + }).replace(/&/g, '&').replace(/ /g, ' ').trim(); + return JSON.parse(text); + } + function rowId(index) { + return 'craft' + Date.now().toString(36) + index.toString(36) + + Math.floor(Math.random() * 1679616).toString(36); + } + function importCraft(characterId, data) { + if (!validPayload(data)) return whisper('Invalid or unsupported Ravenous craft JSON.'); + var character = getObj('character', characterId); + if (!character) return whisper('Character not found. Select a linked token or use --id CHARACTER_ID.'); + data.items.forEach(function (item, index) { + var section = item.type === 'attack' ? 'attacks' : item.type === 'protection' ? 'protections' : + item.type === 'consumable' ? 'consumables' : 'modifiers'; + var prefix = 'repeating_' + section + '_' + rowId(index) + '_'; + FIELDS[item.type].forEach(function (field) { + if (item[field] === undefined) return; + createObj('attribute', { characterid: characterId, name: prefix + field, + current: String(item[field]), max: '' }); + }); + }); + whisper('Imported ' + data.items.length + ' craft item(s) into ' + character.get('name') + '.'); + } + function selectedCharacterId(message) { + var selected = message.selected || []; + if (selected.length !== 1 || selected[0]._type !== 'graphic') { + whisper('Select one token representing the destination character, or use --id CHARACTER_ID.'); + return ''; + } + var token = getObj('graphic', selected[0]._id); + var id = token && token.get('represents'); + if (!id) whisper('The selected token does not represent a character.'); + return id || ''; + } + function argumentsFrom(input) { + var result = { id: '', handout: '', json: '' }; + var rest = input.trim(); + while (rest.indexOf('--') === 0) { + var match = rest.match(/^--(id|handout)\s+(\S+)\s*/); + if (!match || result[match[1]]) return null; + result[match[1]] = match[2]; + rest = rest.slice(match[0].length); + } + result.json = rest; + if (!!result.handout === !!result.json) return null; + return result; + } + + on('chat:message', function (message) { + if (message.type !== 'api') return; + var content = message.content.trim(); + if (content !== COMMAND && content.indexOf(COMMAND + ' ') !== 0) return; + var args = argumentsFrom(content.slice(COMMAND.length)); + if (!args) return whisper('Usage: ' + COMMAND + ' [--id CHARACTER_ID] JSON or --handout HANDOUT_ID.'); + var characterId = args.id || selectedCharacterId(message); + if (!characterId) return; + if (!canControl(getObj('character', characterId), message.playerid)) + return whisper('Permission denied: the player does not control the destination character.'); + if (args.handout) { + var handout = getObj('handout', args.handout); + if (!handout) return whisper('Handout not found.'); + if (!canReadHandout(handout, message.playerid)) return whisper('Permission denied for that handout.'); + return handout.get('gmnotes', function (notes) { + try { importCraft(characterId, decodeHandout(notes)); } + catch (error) { whisper('Handout does not contain valid Ravenous craft JSON.'); } + }); + } + try { importCraft(characterId, JSON.parse(args.json)); } + catch (error) { whisper('Invalid JSON.'); } + }); +}()); diff --git a/src/ravenous.css b/src/ravenous.css index a1b70dd..810aa9f 100644 --- a/src/ravenous.css +++ b/src/ravenous.css @@ -52,6 +52,8 @@ .location-head { padding:5px 9px; color:var(--muted); font-size:9px; text-align:center; text-transform:uppercase; } .location-grid { border:1px solid var(--border); } .location-row { padding:7px 9px; background:rgba(var(--light-rgb),.72); } +.location-head span:first-child { text-align:left; } +.location-row input { width:100% !important; min-width:0; margin:0; justify-self:stretch; text-align:center; } .location-row:nth-child(even) { background:rgba(var(--accent-rgb),.52); } .location-row strong { color:var(--blood); font-family:"Cinzel",Georgia,serif; } .location-row input[readonly] { color:var(--blood); background:var(--accent); font-weight:bold; } @@ -70,9 +72,13 @@ .skill-row select,.skill-row input,.custom-skill-row select,.custom-skill-row input { height:28px; margin:0; vertical-align:middle; } .skill-row output,.custom-skill-row output { display:grid; place-items:center; min-height:28px; } .skill-head { color:var(--muted); font-size:9px; text-transform:uppercase; } -.skill-category { margin-top:9px; padding:6px 9px; color:var(--blood); border-bottom:1px solid var(--gold); background:var(--accent); font:700 12px "Cinzel",Georgia,serif; } -.skill-category span { margin-right:7px; color:var(--gold); } -.skill-row:nth-of-type(even) { background:rgba(var(--accent-rgb),.52); } +.skill-subtabs { margin:9px 0 6px; } +.skill-subtab-bar { display:grid; grid-auto-flow:column; grid-auto-columns:minmax(105px,1fr); gap:3px; overflow-x:auto; border-bottom:1px solid var(--gold); } +.skill-subtab-state { position:absolute; width:1px !important; height:1px; opacity:0; pointer-events:none; } +.ravenous-sheet .skill-subtab { display:grid; place-items:center; width:100% !important; min-width:105px; height:28px; margin:0 !important; padding:4px 6px; color:var(--blood); background:var(--accent); font:700 9px/16px "Cinzel",Georgia,serif !important; text-align:center; cursor:pointer; white-space:nowrap; } +.skill-category-panel { display:none; } +.skill-category-panel .skill-row:nth-child(even) { background:rgba(var(--accent-rgb),.52); } +{{SKILL_CATEGORY_CSS}} .skill-roll,.attack-roll,.use-effect,.activate-technique,.combat-card button[type=roll] { display:grid; place-items:center; width:28px; min-width:28px; height:28px; margin:0; padding:0; border:1px solid var(--dark-gold); border-radius:50%; background:var(--blood); color:var(--light); font-size:0; line-height:1; box-shadow:none; appearance:none; } .ravenous-sheet .skill-roll::before,.ravenous-sheet .attack-roll::before,.ravenous-sheet button[type=roll].use-effect::before,.ravenous-sheet button[type=roll].activate-technique::before,.ravenous-sheet .combat-card button[type=roll]::before { content:"◆" !important; color:var(--light); font:10px/1 Georgia,serif !important; margin:0; } .skill-roll:hover,.skill-roll:focus,.attack-roll:hover,.attack-roll:focus,.use-effect:hover,.use-effect:focus,.activate-technique:hover,.activate-technique:focus { border-color:var(--blood); background:var(--dark-gold); outline:2px solid rgba(var(--gold-rgb),.3); } @@ -89,7 +95,7 @@ .combat-card>label.grow { width:auto; min-width:190px; } .combat-card .attack-followup { display:none; } .combat-card textarea,.consumable-card textarea { flex-basis:100%; } -.attack-card { display:grid; grid-template-columns:28px minmax(150px,1fr) repeat(7,minmax(45px,55px)); gap:7px; } +.attack-card { display:grid; grid-template-columns:28px minmax(150px,1fr) repeat(6,minmax(45px,55px)); gap:7px; } .attack-card>.attack-roll { align-self:end; } .attack-card>label,.attack-card>label.grow { width:auto; min-width:0; margin:0 !important; } .attack-card>textarea,.attack-card>.attack-thresholds { grid-column:1/-1; } diff --git a/src/ravenous.html b/src/ravenous.html index 4b565e9..4da6b1d 100644 --- a/src/ravenous.html +++ b/src/ravenous.html @@ -108,7 +108,6 @@
-
CompétenceCaractéristiqueBaseTemp.Total
{{SKILL_ROWS}}
◆

Compétences maison

@@ -132,7 +131,6 @@ - @@ -318,7 +316,8 @@ on("clicked:repeating_attacks:attack", event => { const fields = ["name","dice","threshold","temp","base_damage","damage_per_success","break_damage","rmax","dodge_threshold","parry_threshold","reposition_threshold","notes"]; getAttrs(["character_name","roll_whisper", ...fields.map(field => prefix + field)], values => { const get = field => values[prefix + field]; - const command = `&{template:ravenous} {{title=${templateText(get("name") || "Attaque")}}} {{subtitle=Attaque · ${templateText(values.character_name)}}} {{attackcheck=1}} {{attack_successes=[[0]]}} {{attack_roll=[[${number(get("dice"))}d10<${number(get("threshold")) + number(get("temp"))}]]}} {{pool=[[${number(get("dice"))}]]d10}} {{threshold=[[${number(get("threshold"))}+${number(get("temp"))}]]}} {{damage=${number(get("base_damage"))} + ${number(get("damage_per_success"))}/R}} {{breakdamage=${number(get("break_damage"))}}} {{thresholds=Esq. ${number(get("dodge_threshold"))} · Par. ${number(get("parry_threshold"))} · Repos. ${number(get("reposition_threshold"))}}} {{buttons=[Défendre](~${prefix}defend) [Dégâts](~${prefix}damage) [Subir](~${prefix}take_damage)}} {{details=RMax ${number(get("rmax"))} · ${templateText(get("notes"))}}}`; + const diceQuery = `?{Nombre de dés|${Math.max(1, Math.floor(number(get("dice")) || 1))}}`; + const command = `&{template:ravenous} {{title=${templateText(get("name") || "Attaque")}}} {{subtitle=Attaque · ${templateText(values.character_name)}}} {{attackcheck=1}} {{attack_successes=[[0]]}} {{attack_roll=[[${diceQuery}d10<${number(get("threshold")) + number(get("temp"))}]]}} {{pool=[[${diceQuery}]]d10}} {{threshold=[[${number(get("threshold"))}+${number(get("temp"))}]]}} {{damage=${number(get("base_damage"))} + ${number(get("damage_per_success"))}/R}} {{breakdamage=${number(get("break_damage"))}}} {{thresholds=Esq. ${number(get("dodge_threshold"))} · Par. ${number(get("parry_threshold"))} · Repos. ${number(get("reposition_threshold"))}}} {{buttons=[Défendre](~${prefix}defend) [Dégâts](~${prefix}damage) [Subir](~${prefix}take_damage)}} {{details=RMax ${number(get("rmax"))} · ${templateText(get("notes"))}}}`; startRoll(`${values.roll_whisper || ""}${command}`, results => { const successes = results.results.attack_roll.result; attackRolls[results.rollId] = {successes, baseDamage: number(get("base_damage")), damagePerSuccess: number(get("damage_per_success")), breakDamage: number(get("break_damage")), rmax: number(get("rmax"))}; diff --git a/tests/test_build.py b/tests/test_build.py index 7c5a04f..27dfdc3 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -149,8 +149,11 @@ class BuildTests(unittest.TestCase): def test_skills_are_categorized_single_roll_checks(self): sheet = (ROOT / "build/ravenous.html").read_text() - for category in ("Résistances", "Martial", "Généralistes", "Athlétisme", "Artisanat", "Connaissances", "Langues"): - self.assertIn(f'>{category}', sheet) + for category in ("Martial", "Généralistes", "Athlétisme", "Artisanat", "Connaissances", "Langues"): + self.assertIn(f'role="tab">{category}', sheet) + self.assertNotIn('role="tab">Résistances', sheet) + self.assertEqual(7, sheet.count('class="skill-subtab-state"')) + self.assertEqual(7, sheet.count('role="tabpanel"')) self.assertIn("startRoll(command", sheet) self.assertIn("const margin = target - rolled", sheet) self.assertIn('rolled === 1 ? "Réussite critique"', sheet) @@ -192,6 +195,9 @@ class BuildTests(unittest.TestCase): self.assertIn(".ravenous-sheet {", css) self.assertNotIn(".sheet-ravenous-sheet {", css) self.assertIn(".skill-row select,.skill-row input", css) + self.assertIn(".location-row input { width:100% !important;", css) + self.assertIn(".skill-subtab-bar { display:grid; grid-auto-flow:column;", css) + self.assertIn(".ravenous-sheet .skill-subtab { display:grid; place-items:center; width:100% !important;", css) self.assertIn("height:28px; margin:0; vertical-align:middle", css) self.assertIn(".resource-blood label:last-child { grid-column:3/-1; }", css) self.assertIn(".stat input { height:32px; margin:0;", css) diff --git a/tests/test_craft_import.mjs b/tests/test_craft_import.mjs new file mode 100644 index 0000000..4496e2f --- /dev/null +++ b/tests/test_craft_import.mjs @@ -0,0 +1,98 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import vm from 'node:vm'; + +const script = readFileSync(new URL('../roll20_mod/ravenous_craft_import.js', import.meta.url), 'utf8'); + +function session() { + const objects = new Map(); + const chat = []; + let nextId = 0; + let handler; + const createObj = (type, fields) => { + const data = { ...fields }; + const object = { + id: `id${++nextId}`, type, + get(key, callback) { const value = data[key] ?? ''; if (callback) callback(value); else return value; }, + set(key, value) { data[key] = value; }, data, + }; + objects.set(object.id, object); + return object; + }; + vm.runInNewContext(script, { + on(event, callback) { assert.equal(event, 'chat:message'); handler = callback; }, + playerIsGM: id => id === 'gm', createObj, + getObj: (type, id) => objects.get(id)?.type === type ? objects.get(id) : undefined, + sendChat: (speaker, content) => chat.push({ speaker, content }), + Date, Math, isFinite, + }); + const send = (content, playerid = 'gm', selected = []) => handler({ type: 'api', playerid, content, selected }); + return { createObj, objects, chat, send }; +} + +function attributes(game, characterId) { + return [...game.objects.values()].filter(object => object.type === 'attribute' && + object.get('characterid') === characterId); +} + +test('imports all supported craft item types into a selected character', () => { + const game = session(); + const character = game.createObj('character', { name: 'Ariane' }); + const token = game.createObj('graphic', { represents: character.id }); + const data = { format: 'ravenous-roll20-craft', version: 1, + craft: { name: 'Lot ardent', discipline: 'forge', element: 'Feu', level: 3 }, + items: [ + { type: 'attack', name: 'Lame', dice: 5, base_damage: 8, notes: 'Feu' }, + { type: 'protection', name: 'Targe', protection: 3, integrity: 2, integrity_max: 2 }, + { type: 'consumable', name: 'Huile', kind: 'Autre', quantity: 2 }, + { type: 'modifier', name: 'Piège', duration: '1 tour', description: 'Entrave' }, + ] }; + game.send(`!ravenous-import-craft ${JSON.stringify(data)}`, 'gm', + [{ _type: 'graphic', _id: token.id }]); + const attrs = attributes(game, character.id); + assert.equal(attrs.filter(attr => attr.get('name').endsWith('_name')).length, 4); + assert.ok(attrs.some(attr => /^repeating_attacks_.*_base_damage$/.test(attr.get('name')) && attr.get('current') === '8')); + assert.ok(attrs.some(attr => /^repeating_protections_.*_integrity_max$/.test(attr.get('name')))); + assert.ok(attrs.some(attr => /^repeating_consumables_.*_kind$/.test(attr.get('name')) && attr.get('current') === 'Autre')); + assert.ok(attrs.some(attr => /^repeating_modifiers_.*_description$/.test(attr.get('name')))); + assert.match(game.chat.at(-1).content, /Imported 4 craft item/); +}); + +test('supports explicit character and HTML-escaped handout JSON', () => { + const game = session(); + const character = game.createObj('character', { name: 'Arangar' }); + const data = { format: 'ravenous-roll20-craft', version: 1, + items: [{ type: 'consumable', name: 'A & B', kind: 'Potion', quantity: 1 }] }; + const escaped = JSON.stringify(data).replace(/&/g, '&').replace(//g, '>'); + const handout = game.createObj('handout', { gmnotes: `
${escaped}
` }); + game.send(`!ravenous-import-craft --id ${character.id} --handout ${handout.id}`); + assert.ok(attributes(game, character.id).some(attr => attr.get('current') === 'A & B')); +}); + +test('rejects unauthorized players, unknown fields, invalid kinds, malformed JSON, and missing targets', () => { + const game = session(); + const character = game.createObj('character', { name: 'Ariane' }); + const valid = { format: 'ravenous-roll20-craft', version: 1, + items: [{ type: 'consumable', name: 'Potion', kind: 'Potion' }] }; + game.send(`!ravenous-import-craft --id ${character.id} ${JSON.stringify(valid)}`, 'player'); + game.send(`!ravenous-import-craft --id ${character.id} {bad}`); + game.send(`!ravenous-import-craft --id ${character.id} ${JSON.stringify({ ...valid, + items: [{ type: 'consumable', name: 'Potion', kind: 'Weapon' }] })}`); + game.send(`!ravenous-import-craft --id ${character.id} ${JSON.stringify({ ...valid, extra: true })}`); + game.send(`!ravenous-import-craft ${JSON.stringify(valid)}`); + assert.equal(attributes(game, character.id).length, 0); + assert.match(game.chat.at(-1).content, /Select one token/); +}); + +test('a player can import into a controlled character from an accessible handout', () => { + const game = session(); + const character = game.createObj('character', { name: 'Ariane', controlledby: 'player' }); + const token = game.createObj('graphic', { represents: character.id }); + const data = { format: 'ravenous-roll20-craft', version: 1, + items: [{ type: 'consumable', name: 'Potion', kind: 'Potion' }] }; + const handout = game.createObj('handout', { controlledby: 'player', gmnotes: JSON.stringify(data) }); + game.send(`!ravenous-import-craft --handout ${handout.id}`, 'player', + [{ _type: 'graphic', _id: token.id }]); + assert.ok(attributes(game, character.id).some(attr => attr.get('current') === 'Potion')); +}); diff --git a/tests/test_worker.mjs b/tests/test_worker.mjs index 48627a8..67c93b3 100644 --- a/tests/test_worker.mjs +++ b/tests/test_worker.mjs @@ -133,6 +133,7 @@ test('attack and defense cap remaining successes at RMax', () => { sheetWorker.queueRoll('attack1', { attack_roll: 4 }); sheetWorker.fire('clicked:repeating_attacks:attack', { sourceAttribute: prefix + 'attack' }); assert.equal(sheetWorker.rolls[0].computed.attack_successes, 4); + assert.match(sheetWorker.rolls[0].command, /\?\{Nombre de dés\|5\}d10/); sheetWorker.queueRoll('defense1', { defense_roll: 1 }); sheetWorker.fire('clicked:repeating_attacks:defend', { sourceAttribute: prefix + 'defend', originalRollId: 'attack1', diff --git a/tools/build.py b/tools/build.py index 2b81974..2956291 100644 --- a/tools/build.py +++ b/tools/build.py @@ -215,8 +215,8 @@ def theme_variables(palette: dict[str, str]) -> str: return " ".join(values) -def skills_from_data(data: dict) -> list[dict[str, str]]: - skills: list[dict[str, str]] = [] +def skills_from_data(data: dict) -> list[dict]: + skills: list[dict] = [] defaults = { "Parade": "force", "Esquive": "agilite", "Encaissement": "force", "Initiative": "perception", "Sens commun": "charisme", @@ -224,13 +224,17 @@ def skills_from_data(data: dict) -> list[dict[str, str]]: "Dépeçage": "intelligence", "Médecine": "intelligence", } for category in data["competences"]: + if not category.get("sheet", {}).get("visible", True): + continue + def add_entry(entry: dict, parent_id: str = "", parent_name: str = "", inherited: str = "", depth: int = 0) -> None: name = entry["name"] key = f"{parent_id}_{slug(name)}" if parent_id else slug(name) label = f"{parent_name} — {name}" if parent_name else name characteristic = inherited or defaults.get(name, "agilite" if category["name"] == "Athlétisme" else "intelligence") skills.append({"id": key, "name": label, "display_name": name, "depth": depth, - "category": category["name"], "characteristic": characteristic, + "category": category["name"], + "characteristic": characteristic, "description": entry.get("description", "")}) for child in entry.get("subskills", []): add_entry(child, key, label, characteristic, depth + 1) @@ -240,14 +244,19 @@ def skills_from_data(data: dict) -> list[dict[str, str]]: return skills -def skill_rows(skills: list[dict[str, str]]) -> str: - rows = [] - category = None - for skill in skills: - if skill["category"] != category: - category = skill["category"] - rows.append(f'
◆{html.escape(category)}
') - rows.append(f'''
+def skill_rows(skills: list[dict]) -> str: + categories = list(dict.fromkeys(skill["category"] for skill in skills)) + tabs = ['
'] + labels = ['
'] + panels = ['
'] + for index, category in enumerate(categories): + key = slug(category) + checked = " checked" if index == 0 else "" + tabs.append(f'') + labels.append(f'') + panels.append(f'
') + for skill in (item for item in skills if item["category"] == category): + panels.append(f'''
{html.escape(skill['display_name'])} @@ -255,7 +264,22 @@ def skill_rows(skills: list[dict[str, str]]) -> str: 0
''') - return "\n".join(rows) + panels.append('
') + labels.append('
') + labels.append('
CompétenceCaractéristiqueBaseTemp.Total
') + panels.append('
') + return "\n".join(tabs + labels + panels + ['
']) + + +def skill_category_css(skills: list[dict]) -> str: + categories = dict.fromkeys(skill["category"] for skill in skills) + return "\n".join( + f'.skill-subtab-state[value="{slug(category)}"]:checked~.skill-subtab-bar label[for="skill-tab-{slug(category)}"]' + f'{{ color:var(--light); background:var(--blood); }}\n' + f'.skill-subtab-state[value="{slug(category)}"]:checked~.skill-category-panels ' + f'.skill-category-panel-{slug(category)}{{ display:block; }}' + for category in categories + ) def technique_options(schools: dict[str, list[dict[str, str]]], trigrams: dict[str, str]) -> tuple[str, dict[str, dict[str, str]]]: @@ -355,7 +379,8 @@ def main() -> None: "SKILLS_JSON": javascript_data(skills), }), "ravenous.css": render((TEMPLATES / "ravenous.css").read_text(encoding="utf-8"), - {"THEME_VARS": theme_variables(palettes[theme])}), + {"THEME_VARS": theme_variables(palettes[theme]), + "SKILL_CATEGORY_CSS": skill_category_css(skills)}), "translation.json": (TEMPLATES / "translation.json").read_text(encoding="utf-8"), "sheet.json": (TEMPLATES / "sheet.json").read_text(encoding="utf-8"), }