feat: add sheet craft import and export controls

This commit is contained in:
Dandaedre 2026-09-19 21:20:12 +02:00
parent 3525f1f8b9
commit ab97605ac3
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
6 changed files with 109 additions and 19 deletions

View File

@ -269,6 +269,12 @@ utilisez un JSON direct ou les GM Notes d'un handout privé :
!ravenous-import-craft --id ID_DU_PERSONNAGE --handout ID_DU_HANDOUT
```
Les boutons **Export artisanat** et **Import artisanat** de l'en-tête ciblent
directement le personnage courant. L'export regroupe ses attaques, protections,
consommables et effets temporaires compatibles dans un handout. Pour un joueur,
ce handout lui est attribué et le JSON se trouve dans ses Notes visibles ; le
bouton d'import peut ensuite le charger dans un autre personnage qu'il contrôle.
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

View File

@ -3,12 +3,14 @@
* !ravenous-import-craft --id CHARACTER_ID JSON
* !ravenous-import-craft --handout HANDOUT_ID (selected token)
* !ravenous-import-craft --id CHARACTER_ID --handout HANDOUT_ID
* !ravenous-export-craft --id CHARACTER_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 EXPORT_COMMAND = '!ravenous-export-craft';
var FORMAT = 'ravenous-roll20-craft';
var VERSION = 1;
var LIMITS = { items: 100, text: 10000, name: 150 };
@ -25,7 +27,12 @@
attack: ['name'], protection: ['name'], consumable: ['name'], modifier: ['name']
};
function whisper(message) { sendChat('Ravenous Craft', '/w gm ' + message); }
function whisper(message, playerId) {
if (!playerId || playerIsGM(playerId)) return sendChat('Ravenous Craft', '/w gm ' + message);
var player = getObj('player', playerId);
var name = String(player && player.get('_displayname') || 'player').replace(/"/g, '');
sendChat('Ravenous Craft', '/w "' + name + '" ' + message);
}
function grantsAccess(list, playerId) {
return String(list || '').split(',').some(function (id) { return id === 'all' || id === playerId; });
}
@ -75,14 +82,21 @@
}).replace(/&/g, '&').replace(/ /g, ' ').trim();
return JSON.parse(text);
}
function readHandout(handout, isGM, callback) {
if (!isGM) return handout.get('notes', callback);
handout.get('gmnotes', function (gmnotes) {
if (String(gmnotes || '').trim()) return callback(gmnotes);
handout.get('notes', callback);
});
}
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.');
function importCraft(characterId, data, playerId) {
if (!validPayload(data)) return whisper('Invalid or unsupported Ravenous craft JSON.', playerId);
var character = getObj('character', characterId);
if (!character) return whisper('Character not found. Select a linked token or use --id CHARACTER_ID.');
if (!character) return whisper('Character not found. Select a linked token or use --id CHARACTER_ID.', playerId);
data.items.forEach(function (item, index) {
var section = item.type === 'attack' ? 'attacks' : item.type === 'protection' ? 'protections' :
item.type === 'consumable' ? 'consumables' : 'modifiers';
@ -93,17 +107,17 @@
current: String(item[field]), max: '' });
});
});
whisper('Imported ' + data.items.length + ' craft item(s) into ' + character.get('name') + '.');
whisper('Imported ' + data.items.length + ' craft item(s) into ' + character.get('name') + '.', playerId);
}
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.');
whisper('Select one token representing the destination character, or use --id CHARACTER_ID.', message.playerid);
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.');
if (!id) whisper('The selected token does not represent a character.', message.playerid);
return id || '';
}
function argumentsFrom(input) {
@ -120,26 +134,67 @@
return result;
}
function exportCraft(characterId, playerId) {
var character = getObj('character', characterId);
if (!character) return whisper('Character not found.', playerId);
if (!canControl(character, playerId)) return whisper('Permission denied: the player does not control the source character.', playerId);
var sections = { attack: 'attacks', protection: 'protections', consumable: 'consumables', modifier: 'modifiers' };
var items = [];
Object.keys(sections).forEach(function (type) {
var prefix = 'repeating_' + sections[type] + '_';
var rows = {};
findObjs({ type: 'attribute', characterid: characterId }).forEach(function (attribute) {
var name = String(attribute.get('name') || '');
if (name.indexOf(prefix) !== 0) return;
FIELDS[type].forEach(function (field) {
var suffix = '_' + field;
if (name.slice(-suffix.length) !== suffix) return;
var row = name.slice(prefix.length, -suffix.length);
if (!row) return;
if (!rows[row]) rows[row] = { type: type };
rows[row][field] = String(attribute.get('current') == null ? '' : attribute.get('current'));
});
});
Object.keys(rows).sort().forEach(function (row) {
if (String(rows[row].name || '').trim()) items.push(rows[row]);
});
});
if (!items.length) return whisper('No craft-compatible rows found on ' + character.get('name') + '.', playerId);
var payload = { format: FORMAT, version: VERSION,
craft: { name: 'Export de ' + character.get('name') }, items: items };
var isGM = playerIsGM(playerId);
var handout = createObj('handout', { name: 'Ravenous craft - ' + character.get('name'),
inplayerjournals: isGM ? '' : playerId, controlledby: isGM ? '' : playerId });
if (!handout) return whisper('Roll20 could not create the craft handout.', playerId);
var readable = JSON.stringify(payload, null, 2).replace(/&/g, '&')
.replace(/</g, '&lt;').replace(/>/g, '&gt;');
handout.set(isGM ? 'gmnotes' : 'notes', '<pre>' + readable + '</pre>');
whisper('Exported ' + items.length + ' craft item(s) to handout ' + handout.id + '.', playerId);
}
on('chat:message', function (message) {
if (message.type !== 'api') return;
var content = message.content.trim();
if (content.indexOf(EXPORT_COMMAND + ' --id ') === 0) {
return exportCraft(content.slice((EXPORT_COMMAND + ' --id ').length).trim(), message.playerid);
}
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.');
if (!args) return whisper('Usage: ' + COMMAND + ' [--id CHARACTER_ID] JSON or --handout HANDOUT_ID.', message.playerid);
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.');
return whisper('Permission denied: the player does not control the destination character.', message.playerid);
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.'); }
if (!handout) return whisper('Handout not found.', message.playerid);
if (!canReadHandout(handout, message.playerid)) return whisper('Permission denied for that handout.', message.playerid);
return readHandout(handout, playerIsGM(message.playerid), function (notes) {
try { importCraft(characterId, decodeHandout(notes), message.playerid); }
catch (error) { whisper('Handout does not contain valid Ravenous craft JSON.', message.playerid); }
});
}
try { importCraft(characterId, JSON.parse(args.json)); }
catch (error) { whisper('Invalid JSON.'); }
try { importCraft(characterId, JSON.parse(args.json), message.playerid); }
catch (error) { whisper('Invalid JSON.', message.playerid); }
});
}());

View File

@ -19,7 +19,7 @@
.identity-grid { display:grid; grid-template-columns:2fr 2fr 1.5fr 1fr; gap:8px; margin-top:6px; }
.identity-grid label,.ravenous-sheet label { color:var(--muted); font-size:10px; text-transform:uppercase; letter-spacing:.05em; }
.motto { color:var(--dark-gold); font-style:italic; text-align:center; }
.character-io-actions { display:flex; gap:5px; justify-content:center; }
.character-io-actions { display:flex; flex-wrap:wrap; gap:5px; justify-content:center; }
.ravenous-sheet .character-io-actions button[type=roll] { width:auto; margin:0; padding:4px 7px; color:var(--light); border:1px solid var(--dark-gold); border-radius:2px; background:var(--blood); font:700 9px "Cinzel",Georgia,serif; box-shadow:none; }
.ravenous-sheet .character-io-actions button[type=roll]::before { content:""; margin:0; }
.secret-rolls { display:flex; justify-content:center; align-items:center; gap:6px; margin-top:7px; color:var(--blood)!important; font-style:normal; }
@ -178,4 +178,4 @@
.sheet-rolltemplate-ravenous .sheet-template-row b { color:var(--blood); }
.sheet-rolltemplate-ravenous .sheet-template-notes { color:var(--muted); font-style:italic; }
@media (max-width:760px) { .ravenous-sheet { min-width:0; padding:9px; }.hero { grid-template-columns:60px 1fr; }.motto { display:none; }.stat-grid { grid-template-columns:repeat(2,1fr); }.dashboard { grid-template-columns:repeat(2,1fr); }.derived-grid { grid-template-columns:repeat(3,1fr); }.tabs { flex-wrap:wrap; }.tabs button { flex-basis:33%; }.skill-head { display:none; }.skill-row,.custom-skill-row { grid-template-columns:28px 1fr 70px 45px 45px 45px; }.skill-row select,.custom-skill-row select { max-width:70px; }.location-head,.location-row { grid-template-columns:minmax(105px,1.5fr) repeat(5,minmax(54px,1fr)); gap:3px; }.resistance-grid,.damage-resistance-grid { grid-template-columns:repeat(2,1fr); } }
@media (max-width:760px) { .ravenous-sheet { min-width:0; padding:9px; }.hero { grid-template-columns:60px 1fr; }.motto { grid-column:1/-1; }.stat-grid { grid-template-columns:repeat(2,1fr); }.dashboard { grid-template-columns:repeat(2,1fr); }.derived-grid { grid-template-columns:repeat(3,1fr); }.tabs { flex-wrap:wrap; }.tabs button { flex-basis:33%; }.skill-head { display:none; }.skill-row,.custom-skill-row { grid-template-columns:28px 1fr 70px 45px 45px 45px; }.skill-row select,.custom-skill-row select { max-width:70px; }.location-head,.location-row { grid-template-columns:minmax(105px,1.5fr) repeat(5,minmax(54px,1fr)); gap:3px; }.resistance-grid,.damage-resistance-grid { grid-template-columns:repeat(2,1fr); } }

View File

@ -18,6 +18,8 @@
<div class="character-io-actions">
<button type="roll" name="roll_export_character" value="!ravenous-export --id @{character_id}">Exporter</button>
<button type="roll" name="roll_replace_character" value="!ravenous-import --replace --id @{character_id} --handout ?{ID du handout personnage}">Restaurer</button>
<button type="roll" name="roll_export_craft" value="!ravenous-export-craft --id @{character_id}">Export artisanat</button>
<button type="roll" name="roll_import_craft" value="!ravenous-import-craft --id @{character_id} --handout ?{ID du handout artisanat}">Import artisanat</button>
</div>
<label class="secret-rolls">Jets secrets<input type="checkbox" name="attr_secret_rolls" value="1"></label>
</div>

View File

@ -37,6 +37,8 @@ class BuildTests(unittest.TestCase):
self.assertIn(f'class="repeating_{section}"', sheet)
self.assertIn('value="!ravenous-export --id @{character_id}"', sheet)
self.assertIn('value="!ravenous-import --replace --id @{character_id} --handout ?{ID du handout personnage}"', sheet)
self.assertIn('value="!ravenous-export-craft --id @{character_id}"', sheet)
self.assertIn('value="!ravenous-import-craft --id @{character_id} --handout ?{ID du handout artisanat}"', sheet)
def test_origins_and_powers_are_imported(self):
from tools.build import read_glossary_labels, read_origins

View File

@ -26,6 +26,8 @@ function session() {
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,
findObjs: query => [...objects.values()].filter(object => object.type === query.type &&
object.get('characterid') === query.characterid),
sendChat: (speaker, content) => chat.push({ speaker, content }),
Date, Math, isFinite,
});
@ -61,6 +63,29 @@ test('imports all supported craft item types into a selected character', () => {
assert.match(game.chat.at(-1).content, /Imported 4 craft item/);
});
test('a player can export craft rows and import the resulting handout', () => {
const game = session();
const player = game.createObj('player', { _displayname: 'Alice' });
const source = game.createObj('character', { name: 'Artisane', controlledby: player.id });
game.createObj('attribute', { characterid: source.id, name: 'repeating_attacks_row_name', current: 'Lame', max: '' });
game.createObj('attribute', { characterid: source.id, name: 'repeating_attacks_row_base_damage', current: '8', max: '' });
game.createObj('attribute', { characterid: source.id, name: 'repeating_attacks_row_unrelated', current: 'ignore', max: '' });
game.createObj('attribute', { characterid: source.id, name: 'repeating_consumables_food_name', current: 'Soupe', max: '' });
game.createObj('attribute', { characterid: source.id, name: 'repeating_consumables_food_kind', current: 'Nourriture', max: '' });
game.send(`!ravenous-export-craft --id ${source.id}`, player.id);
const handout = [...game.objects.values()].find(object => object.type === 'handout');
assert.equal(handout.get('controlledby'), player.id);
assert.match(handout.get('notes'), /"name": "Lame"/);
assert.doesNotMatch(handout.get('notes'), /unrelated/);
const destination = game.createObj('character', { name: 'Destination', controlledby: player.id });
game.send(`!ravenous-import-craft --id ${destination.id} --handout ${handout.id}`, player.id);
const imported = attributes(game, destination.id);
assert.ok(imported.some(attribute => attribute.get('current') === 'Lame'));
assert.ok(imported.some(attribute => attribute.get('current') === 'Soupe'));
assert.match(game.chat.at(-1).content, /Imported 2 craft item/);
});
test('generated craft fixtures import into all supported repeating sections', () => {
const game = session();
const character = game.createObj('character', { name: 'Fixture' });
@ -107,7 +132,7 @@ test('a player can import into a controlled character from an accessible handout
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) });
const handout = game.createObj('handout', { controlledby: 'player', notes: 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'));