feat: add static effects library helper
Roll20 Sheet Build Successful The Ravenous Roll20 sheet was generated and validated successfully.
Ravenous/ravenous_roll20/pipeline/head This commit looks good
Details
Roll20 Sheet Build Successful The Ravenous Roll20 sheet was generated and validated successfully.
Ravenous/ravenous_roll20/pipeline/head This commit looks good
Details
This commit is contained in:
parent
7b3b7a851d
commit
0e4912c5c9
|
|
@ -4,4 +4,5 @@ __pycache__/
|
|||
build/
|
||||
build-*/
|
||||
/craft_web/build/
|
||||
/effects_web/build/
|
||||
/local_exports/
|
||||
|
|
|
|||
|
|
@ -112,6 +112,9 @@ the attack card's **Défendre** and **Subir** actions.
|
|||
open and reopen the sheet, change inputs, add and reorder repeating rows,
|
||||
roll from chat, and check results on a targeted defender token. Record what
|
||||
was actually tested and what could not be tested.
|
||||
5. Commit coherent, verified increments regularly. Small checkpoints are
|
||||
highly encouraged during longer work so progress is reviewable and easy to
|
||||
recover; do not bundle unrelated user changes into those commits.
|
||||
|
||||
## Known gaps and priorities
|
||||
|
||||
|
|
|
|||
|
|
@ -8,9 +8,11 @@ pipeline {
|
|||
UV_CACHE_DIR = "${WORKSPACE}/.uv-cache"
|
||||
BUILD_DIR = 'build'
|
||||
CRAFT_BUILD_DIR = 'craft_web/build'
|
||||
EFFECTS_BUILD_DIR = 'effects_web/build'
|
||||
DEPLOY_ROOT = '/mnt/books/RPG'
|
||||
SHEET_DIR = 'ravenous_sheet'
|
||||
CRAFT_DIR = 'ravenous_craft'
|
||||
EFFECTS_DIR = 'ravenous_effects'
|
||||
LEGACY_DEPLOY_DIR = '/mnt/books/ravenous_sheet'
|
||||
}
|
||||
|
||||
|
|
@ -85,10 +87,12 @@ pipeline {
|
|||
uv sync --frozen
|
||||
./scripts/build.sh
|
||||
uv run python craft_web/tools/build.py --output "${CRAFT_BUILD_DIR}"
|
||||
uv run python effects_web/tools/build.py --output "${EFFECTS_BUILD_DIR}"
|
||||
uv run python tools/export_monsters.py --id 2 --output "${BUILD_DIR}/example-monster-2.json"
|
||||
uv run python tools/export_monsters.py --id 5 --output "${BUILD_DIR}/example-monster-5.json"
|
||||
uv run python -m unittest discover -s tests -v
|
||||
uv run python -m unittest discover -s craft_web/tests -v
|
||||
uv run python -m unittest discover -s effects_web/tests -v
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
RAVENOUS_CHARACTER_JSON="${BUILD_DIR}/example-character.json" \
|
||||
RAVENOUS_MONSTER_JSON="${BUILD_DIR}/example-monster-2.json" \
|
||||
|
|
@ -96,11 +100,13 @@ pipeline {
|
|||
RAVENOUS_MONSTER_JSON="${BUILD_DIR}/example-monster-5.json" \
|
||||
node tests/test_character_io.mjs
|
||||
node tests/test_craft_import.mjs
|
||||
node tests/test_effects_import.mjs
|
||||
else
|
||||
echo 'Node is not installed on this agent; skipping the optional Roll20 Mod simulator tests.'
|
||||
fi
|
||||
./scripts/build.sh --check
|
||||
uv run python craft_web/tools/build.py --output "${CRAFT_BUILD_DIR}" --check
|
||||
uv run python effects_web/tools/build.py --output "${EFFECTS_BUILD_DIR}" --check
|
||||
|
||||
test -f "${BUILD_DIR}/ravenous.html"
|
||||
test -f "${BUILD_DIR}/ravenous.css"
|
||||
|
|
@ -117,11 +123,19 @@ pipeline {
|
|||
test -f "${CRAFT_BUILD_DIR}/app.js"
|
||||
test -f "${CRAFT_BUILD_DIR}/catalog.js"
|
||||
test -f "${CRAFT_BUILD_DIR}/build-info.json"
|
||||
test -f "${EFFECTS_BUILD_DIR}/index.html"
|
||||
test -f "${EFFECTS_BUILD_DIR}/styles.css"
|
||||
test -f "${EFFECTS_BUILD_DIR}/app.js"
|
||||
test -f "${EFFECTS_BUILD_DIR}/catalog.js"
|
||||
test -f "${EFFECTS_BUILD_DIR}/build-info.json"
|
||||
test -f "${EFFECTS_BUILD_DIR}/ravenous-effects-v1.schema.json"
|
||||
|
||||
echo "Roll20 sheet build complete:"
|
||||
ls -lh "${BUILD_DIR}"
|
||||
echo "Craft workshop build complete:"
|
||||
ls -lh "${CRAFT_BUILD_DIR}"
|
||||
echo "Effects library build complete:"
|
||||
ls -lh "${EFFECTS_BUILD_DIR}"
|
||||
'''
|
||||
}
|
||||
}
|
||||
|
|
@ -129,7 +143,7 @@ pipeline {
|
|||
stage('Archive sheet') {
|
||||
steps {
|
||||
archiveArtifacts(
|
||||
artifacts: 'build/**,craft_web/build/**',
|
||||
artifacts: 'build/**,craft_web/build/**,effects_web/build/**',
|
||||
fingerprint: true
|
||||
)
|
||||
}
|
||||
|
|
@ -144,19 +158,23 @@ pipeline {
|
|||
def targetDir
|
||||
def legacyDir
|
||||
def craftTargetDir
|
||||
def effectsTargetDir
|
||||
|
||||
if (reviewBranches.contains(env.BRANCH_NAME)) {
|
||||
targetDir = "${DEPLOY_ROOT}/${SHEET_DIR}_lighthouse"
|
||||
legacyDir = "${LEGACY_DEPLOY_DIR}_lighthouse"
|
||||
craftTargetDir = "${DEPLOY_ROOT}/${CRAFT_DIR}_lighthouse"
|
||||
effectsTargetDir = "${DEPLOY_ROOT}/${EFFECTS_DIR}_lighthouse"
|
||||
} else if (devBranches.contains(env.BRANCH_NAME)) {
|
||||
targetDir = "${DEPLOY_ROOT}/${SHEET_DIR}_candlelight"
|
||||
legacyDir = "${LEGACY_DEPLOY_DIR}_candlelight"
|
||||
craftTargetDir = "${DEPLOY_ROOT}/${CRAFT_DIR}_candlelight"
|
||||
effectsTargetDir = "${DEPLOY_ROOT}/${EFFECTS_DIR}_candlelight"
|
||||
} else if (productionBranches.contains(env.BRANCH_NAME)) {
|
||||
targetDir = "${DEPLOY_ROOT}/${SHEET_DIR}"
|
||||
legacyDir = LEGACY_DEPLOY_DIR
|
||||
craftTargetDir = "${DEPLOY_ROOT}/${CRAFT_DIR}"
|
||||
effectsTargetDir = "${DEPLOY_ROOT}/${EFFECTS_DIR}"
|
||||
} else {
|
||||
echo "Branch '${env.BRANCH_NAME}' is not a publication branch — skipping deployment."
|
||||
return
|
||||
|
|
@ -164,6 +182,7 @@ pipeline {
|
|||
|
||||
deployTo(targetDir, legacyDir)
|
||||
deployCraftTo(craftTargetDir)
|
||||
deployEffectsTo(effectsTargetDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -175,7 +194,7 @@ pipeline {
|
|||
conclusion: 'SUCCESS',
|
||||
name: 'Roll20 Sheet Build Successful',
|
||||
summary: 'The Ravenous Roll20 sheet was generated and validated successfully.',
|
||||
text: 'The Roll20 bundle and static craft workshop are available as Jenkins artifacts.',
|
||||
text: 'The Roll20 bundle and static craft and effects helpers are available as Jenkins artifacts.',
|
||||
title: 'Roll20 Sheet Build Successful'
|
||||
)
|
||||
echo '✅ Ravenous Roll20 sheet built successfully!'
|
||||
|
|
@ -205,6 +224,25 @@ pipeline {
|
|||
}
|
||||
}
|
||||
|
||||
/** Publish the static reusable-effects library below the shared RPG root. */
|
||||
def deployEffectsTo(String targetDir) {
|
||||
def allowedDirs = [
|
||||
'/mnt/books/RPG/ravenous_effects',
|
||||
'/mnt/books/RPG/ravenous_effects_candlelight',
|
||||
'/mnt/books/RPG/ravenous_effects_lighthouse'
|
||||
]
|
||||
if (!allowedDirs.contains(targetDir)) {
|
||||
error("Refusing to publish effects library to unexpected path: ${targetDir}")
|
||||
}
|
||||
|
||||
sh """
|
||||
set -e
|
||||
echo "Publishing Ravenous effects library to ${targetDir}"
|
||||
mkdir -p "${targetDir}"
|
||||
rsync -a --delete "${env.EFFECTS_BUILD_DIR}/" "${targetDir}/"
|
||||
"""
|
||||
}
|
||||
|
||||
/** Publish the static craft workshop below the shared RPG root. */
|
||||
def deployCraftTo(String targetDir) {
|
||||
def allowedDirs = [
|
||||
|
|
|
|||
29
README.md
29
README.md
|
|
@ -137,6 +137,27 @@ d'écrire sur un personnage que le joueur ne contrôle pas. Vérification locale
|
|||
node tests/test_shared_effects.mjs
|
||||
```
|
||||
|
||||
La bibliothèque statique d'effets exporte aussi une sélection complète au
|
||||
format versionné `ravenous-roll20-effects` v1. Installez
|
||||
`roll20_mod/ravenous_effects_import.js`, puis sélectionnez le token du
|
||||
personnage destinataire ou indiquez son ID :
|
||||
|
||||
```text
|
||||
!ravenous-import-effects {"format":"ravenous-roll20-effects","version":1,"effects":[{"effect_id":"combustion","type":"dot","name":"Combustion"}]}
|
||||
!ravenous-import-effects --handout ID_DU_HANDOUT
|
||||
!ravenous-import-effects --id ID_DU_PERSONNAGE --handout ID_DU_HANDOUT
|
||||
```
|
||||
|
||||
Chaque entrée est ajoutée à **DoT & effets** avec son ID, son type, sa durée
|
||||
structurée et ses rappels. Le script refuse les champs inconnus, les valeurs
|
||||
hors limites, les personnages non contrôlés et les handouts inaccessibles. Le
|
||||
JSON exporté prépare une bibliothèque réutilisable ; il n'active pas les effets
|
||||
dans le suivi des tours. Vérification locale :
|
||||
|
||||
```sh
|
||||
node tests/test_effects_import.mjs
|
||||
```
|
||||
|
||||
## Sauvegarde et import de personnages et de créatures
|
||||
|
||||
`roll20_mod/ravenous_character_io.js` est le script Mod d'échange de personnages.
|
||||
|
|
@ -351,6 +372,14 @@ statique depuis `craft_web/`. Elle est publiée dans
|
|||
`_candlelight` et `_lighthouse`. Le site ne requiert ni Node.js ni serveur
|
||||
applicatif : Python génère ses fichiers HTML, CSS, JavaScript et son catalogue.
|
||||
|
||||
La bibliothèque statique d'altérations et d'effets de `effects_web/` suit le
|
||||
même cycle de construction, de test déterministe, d'archivage et de
|
||||
publication. La production est disponible sous
|
||||
`https://books.dandaedre.com/RPG/ravenous_effects/`; les branches de
|
||||
développement et de revue utilisent respectivement les suffixes `_candlelight`
|
||||
et `_lighthouse`. Son catalogue, ses thèmes et son schéma JSON sont générés à
|
||||
partir de la même révision épinglée du livre.
|
||||
|
||||
## Notes Roll20
|
||||
|
||||
Dans une partie utilisant une feuille personnalisée, copiez le contenu des
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
# Agent guide: Ravenous Effects Library
|
||||
|
||||
This folder builds a dependency-free static helper for browsing Ravenous
|
||||
alterations, assembling reusable effect libraries, and exporting them for the
|
||||
Roll20 sheet. The pinned `ravenous_typst/data/src/glossaries/alterations.yaml`
|
||||
file is authoritative. Do not hand-edit generated files in `build/`.
|
||||
|
||||
The site is generated with Python 3.11+, uses no runtime services or CDN, and
|
||||
stores private sets and custom effects only in browser local storage. Render
|
||||
imported/user text with DOM text APIs. Keep the `ravenous-roll20-effects` v1
|
||||
contract backward compatible and target `repeating_sharedeffects`, not active
|
||||
`repeating_modifiers` rows.
|
||||
|
||||
Build and verify with:
|
||||
|
||||
```sh
|
||||
uv run python effects_web/tools/build.py
|
||||
uv run python -m unittest discover -s effects_web/tests -v
|
||||
uv run python effects_web/tools/build.py --check
|
||||
```
|
||||
|
||||
Reuse the sheet's theme parser, Typst translator, and conservative reminder
|
||||
inference. Unknown durations remain manual; never invent a game rule.
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
# Ravenous Effects Library
|
||||
|
||||
A small static companion site for finding Ravenous alterations, preparing a
|
||||
personal reusable effects library, saving named selections locally, and
|
||||
exporting strict `ravenous-roll20-effects` version 1 JSON.
|
||||
|
||||
```sh
|
||||
uv run python effects_web/tools/build.py
|
||||
uv run python -m unittest discover -s effects_web/tests -v
|
||||
uv run python effects_web/tools/build.py --check
|
||||
```
|
||||
|
||||
The generated site is in `effects_web/build/`. It has no backend, account,
|
||||
tracking, or runtime network dependency. Browser-local data should be backed up
|
||||
with JSON export before clearing site data.
|
||||
|
||||
The exported effects are reusable library definitions intended for the
|
||||
sheet's `repeating_sharedeffects` section. They are not activated in the turn
|
||||
tracker by the website.
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
# Effects helper tasks
|
||||
|
||||
- [x] Generate alterations and themes from the pinned rulebook sources.
|
||||
- [x] Add accent-insensitive search and combinable group, resistance,
|
||||
difficulty, and category filters.
|
||||
- [x] Select effects, edit timing/reminders, and export strict versioned JSON.
|
||||
- [x] Save named sets and custom effects locally with library backup/restore.
|
||||
- [x] Add deterministic build tests and `--check`.
|
||||
- [x] Add a separately reviewed Roll20 Mod importer for the exported format.
|
||||
- [x] Wire build, archive, and guarded branch deployment into Jenkins.
|
||||
- [ ] Manually verify keyboard, mobile, print, and current Roll20 behavior.
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://ravenous.invalid/schemas/ravenous-effects-v1.schema.json",
|
||||
"title": "Ravenous Roll20 reusable effects library",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["format", "version", "effects"],
|
||||
"properties": {
|
||||
"format": {"const": "ravenous-roll20-effects"},
|
||||
"version": {"const": 1},
|
||||
"name": {"type": "string", "maxLength": 150},
|
||||
"catalog": {"type": "string", "maxLength": 64},
|
||||
"effects": {
|
||||
"type": "array", "minItems": 1, "maxItems": 100,
|
||||
"items": {"$ref": "#/$defs/effect"}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"effect": {
|
||||
"type": "object", "additionalProperties": false,
|
||||
"required": ["effect_id", "type", "name"],
|
||||
"properties": {
|
||||
"effect_id": {"type": "string", "minLength": 1, "maxLength": 80},
|
||||
"type": {"enum": ["alteration", "dot", "hot", "bonus", "malus", "other"]},
|
||||
"name": {"type": "string", "minLength": 1, "maxLength": 120},
|
||||
"enabled": {"type": "boolean"},
|
||||
"duration": {"type": "string", "maxLength": 120},
|
||||
"description": {"type": "string", "maxLength": 1000},
|
||||
"duration_type": {"enum": ["manual", "turns", "until_start", "until_end", "combat"]},
|
||||
"remaining": {"type": "integer", "minimum": 0, "maximum": 999},
|
||||
"countdown_phase": {"enum": ["start", "end"]},
|
||||
"start_reminder": {"type": "string", "maxLength": 500},
|
||||
"end_reminder": {"type": "string", "maxLength": 500},
|
||||
"apply_reminder": {"type": "string", "maxLength": 500},
|
||||
"removal_reminder": {"type": "string", "maxLength": 500}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
(()=>{'use strict';
|
||||
const D=window.RAVENOUS_EFFECTS_CATALOG||{effects:[],themes:[]},$=x=>document.getElementById(x),HASH='{{CATALOG_HASH}}',CK='ravenous-effects-custom',SK='ravenous-effects-sets',TK='ravenous-effects-theme';
|
||||
const TYPES=['alteration','dot','hot','bonus','malus','other'],DUR=['manual','turns','until_start','until_end','combat'],PH=['start','end'],fold=x=>String(x||'').normalize('NFD').replace(/[\u0300-\u036f]/g,'').toLowerCase();
|
||||
function read(k){try{let v=JSON.parse(localStorage.getItem(k)||'[]');return Array.isArray(v)?v:[]}catch(_){return[]}}function write(k,v){try{localStorage.setItem(k,JSON.stringify(v));return true}catch(_){status('Stockage local indisponible.',1);return false}}function status(s,b=0){$('status').textContent=s;$('status').classList.toggle('bad',!!b)}
|
||||
let custom=read(CK),catalog=[...D.effects,...custom],chosen=new Map();const opt=(v,l=v)=>{let o=document.createElement('option');o.value=v;o.textContent=l;return o};
|
||||
function initFilters(){for(const [id,key] of [['group','group'],['resistance','resisted_by'],['difficulty','difficulty']])$(''+id).append(...[...new Set(catalog.map(x=>String(x[key]??'')).filter(Boolean))].sort((a,b)=>a.localeCompare(b,'fr')).map(opt))}
|
||||
function filtered(){let q=fold($('search').value),cat=fold($('category').value),g=$('group').value,r=$('resistance').value,d=$('difficulty').value,a=catalog.filter(x=>(!q||fold(`${x.name} ${x.description} ${x.category}`).includes(q))&&(!cat||fold(x.category).includes(cat))&&(!g||x.group===g)&&(!r||x.resisted_by===r)&&(!d||String(x.difficulty)===d)),s=$('sort').value;a.sort((x,y)=>s==='difficulty'?(Number(x.difficulty)||999)-(Number(y.difficulty)||999)||x.name.localeCompare(y.name,'fr'):String(x[s]||'').localeCompare(String(y[s]||''),'fr')||x.name.localeCompare(y.name,'fr'));return a}
|
||||
function renderCards(){let a=filtered(),box=$('cards');$('result-count').textContent=`${a.length} résultat${a.length>1?'s':''}`;box.replaceChildren();for(const x of a){let card=document.createElement('article'),check=document.createElement('input'),body=document.createElement('div'),h=document.createElement('h3'),m=document.createElement('div'),p=document.createElement('p');card.className='card'+(x.custom?' custom':'');check.type='checkbox';check.checked=chosen.has(x.id);check.ariaLabel=`Sélectionner ${x.name}`;check.onchange=()=>{check.checked?chosen.set(x.id,{...x}):chosen.delete(x.id);renderSelected()};h.textContent=x.name;m.className='meta';m.textContent=[x.group,x.resisted_by&&`Résiste : ${x.resisted_by}`,x.difficulty!==''&&`Difficulté ${x.difficulty}`,x.category].filter(Boolean).join(' · ');p.textContent=x.description;body.append(h,m,p);if(x.custom){let b=document.createElement('button');b.className='delete';b.textContent='Supprimer';b.onclick=()=>{if(confirm(`Supprimer « ${x.name} » ?`)){custom=custom.filter(y=>y.id!==x.id);chosen.delete(x.id);write(CK,custom);catalog=[...D.effects,...custom];renderCards();renderSelected()}};body.append(b)}card.append(check,body);box.append(card)}}
|
||||
function field(label,value,fn,tag='input',values=[]){let w=document.createElement('label'),i=document.createElement(tag);w.textContent=label;if(tag==='select')i.append(...values.map(opt));if(tag==='textarea')i.rows=2;i.value=value??'';i.oninput=()=>fn(i.value);w.append(i);return w}
|
||||
function renderSelected(){let box=$('selected');box.replaceChildren();if(!chosen.size){let p=document.createElement('p');p.textContent='Aucun effet sélectionné.';box.append(p)}for(const [id,x] of chosen){let d=document.createElement('details'),s=document.createElement('summary'),g=document.createElement('div'),set=(k,v)=>{x[k]=k==='remaining'?Math.max(0,Math.min(999,Math.floor(Number(v)||0))):v;chosen.set(id,x)};d.className='selected-row';s.textContent=x.name;g.className='edit-grid';g.append(field('Nom',x.name,v=>set('name',v)),field('Type',x.type,v=>set('type',v),'select',TYPES),field('Durée affichée',x.duration,v=>set('duration',v)),field('Durée structurée',x.duration_type,v=>set('duration_type',v),'select',DUR),field('Restant',x.remaining,v=>set('remaining',v)),field('Décompte',x.countdown_phase,v=>set('countdown_phase',v),'select',PH));for(const [l,k] of [['Description','description'],['Début du tour','start_reminder'],['Fin du tour','end_reminder'],["À l’application",'apply_reminder'],['Au retrait','removal_reminder']]){let c=field(l,x[k],v=>set(k,v),'textarea');c.className='wide';g.append(c)}d.append(s,g);box.append(d)}renderCards()}
|
||||
function clean(x){let e={effect_id:String(x.effect_id||x.id).slice(0,80),type:TYPES.includes(x.type)?x.type:'other',name:String(x.name||'Effet').slice(0,120),enabled:x.enabled!==false,duration:String(x.duration||'').slice(0,120),description:String(x.description||'').slice(0,1000),duration_type:DUR.includes(x.duration_type)?x.duration_type:'manual',remaining:Math.max(0,Math.min(999,Math.floor(Number(x.remaining)||0))),countdown_phase:PH.includes(x.countdown_phase)?x.countdown_phase:'end'};for(const k of ['start_reminder','end_reminder','apply_reminder','removal_reminder'])e[k]=String(x[k]||'').slice(0,500);return e}function payload(){return{format:'ravenous-roll20-effects',version:1,name:($('set-name').value||'Mes effets').trim().slice(0,150),catalog:HASH,effects:[...chosen.values()].slice(0,100).map(clean)}}
|
||||
function valid(v){if(!v||v.format!=='ravenous-roll20-effects'||v.version!==1||!Array.isArray(v.effects)||v.effects.length>100)throw Error('Format non reconnu.');for(const x of v.effects)if(!x||!x.effect_id||!x.name||!TYPES.includes(x.type))throw Error('Effet invalide.');return v}function download(v,n){let b=new Blob([JSON.stringify(v,null,2)+'\n'],{type:'application/json'}),a=document.createElement('a');a.href=URL.createObjectURL(b);a.download=n;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),0)}function filename(n){return(fold(n).replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,60)||'effets')+'.ravenous-effects.json'}
|
||||
function load(v){valid(v);chosen.clear();for(const x of v.effects)chosen.set(x.effect_id,{...x,id:x.effect_id,group:'Bibliothèque'});$('set-name').value=v.name||'Mes effets';renderSelected();location.hash='selection';status('Bibliothèque chargée.')}function save(){let v=payload();if(!v.effects.length)return status('Sélectionnez au moins un effet.',1);let a=read(SK),i=a.findIndex(x=>x.name===v.name);v.updated=new Date().toISOString();i<0?a.unshift(v):a[i]=v;if(write(SK,a.slice(0,100))){renderLibrary();status('Bibliothèque sauvegardée localement.')}}
|
||||
function renderLibrary(){let q=fold($('library-search').value),box=$('saved'),a=read(SK).filter(x=>!q||fold(x.name).includes(q));box.replaceChildren();if(!a.length){let p=document.createElement('p');p.textContent='Aucune bibliothèque sauvegardée.';box.append(p)}for(const x of a){let c=document.createElement('article'),h=document.createElement('h3'),p=document.createElement('p'),z=document.createElement('div');c.className='saved-card';z.className='actions';h.textContent=x.name;p.textContent=`${x.effects.length} effet(s)`;for(const [l,f] of [['Ouvrir',()=>load(x)],['Dupliquer',()=>{let v=read(SK);v.unshift({...x,name:`${x.name} — copie`});write(SK,v);renderLibrary()}],['Supprimer',()=>{if(confirm(`Supprimer « ${x.name} » ?`)){write(SK,read(SK).filter(y=>y.name!==x.name));renderLibrary()}}]]){let b=document.createElement('button');b.textContent=l;b.onclick=f;z.append(b)}c.append(h,p,z);box.append(c)}}
|
||||
function addCustom(e){e.preventDefault();let name=$('custom-name').value.trim(),id='custom:'+Date.now().toString(36);if(!name)return;let x={id,effect_id:id,custom:true,type:$('custom-type').value,name,group:'Effets personnels',description:$('custom-description').value,resisted_by:'',difficulty:'',category:'',enabled:true,duration:'',duration_type:'manual',remaining:0,countdown_phase:'end',start_reminder:'',end_reminder:'',apply_reminder:'',removal_reminder:''};custom.unshift(x);write(CK,custom);catalog=[...D.effects,...custom];chosen.set(id,{...x});e.target.reset();renderSelected()}
|
||||
async function copy(){let v=payload();if(!v.effects.length)return status('Sélectionnez au moins un effet.',1);let s=JSON.stringify(v,null,2);try{await navigator.clipboard.writeText(s);status('JSON copié.')}catch(_){let t=document.createElement('textarea');t.value=s;document.body.append(t);t.select();let ok=document.execCommand('copy');t.remove();status(ok?'JSON copié.':'Copie impossible.',!ok)}}function restore(e){let f=e.target.files[0];if(!f||f.size>2e6)return;let r=new FileReader;r.onload=()=>{try{let v=JSON.parse(r.result);if(v.format==='ravenous-effects-library'&&v.version===1&&Array.isArray(v.sets)){v.sets.forEach(valid);write(SK,v.sets);renderLibrary();status('Sauvegarde restaurée.')}else load(v)}catch(x){status(`Import impossible : ${x.message}`,1)}};r.readAsText(f,'utf-8')}
|
||||
initFilters();let theme='warm';try{theme=localStorage.getItem(TK)||'warm'}catch(_){}if(!D.themes.includes(theme))theme='warm';document.documentElement.dataset.theme=theme;$('theme').value=theme;$('theme').onchange=e=>{document.documentElement.dataset.theme=e.target.value;try{localStorage.setItem(TK,e.target.value)}catch(_){}};for(const id of ['search','group','resistance','difficulty','category','sort'])$(id).addEventListener('input',renderCards);$('clear').onclick=()=>{for(const id of ['search','group','resistance','difficulty','category'])$(id).value='';renderCards()};$('custom-form').onsubmit=addCustom;$('clear-selection').onclick=()=>{chosen.clear();renderSelected()};$('save-set').onclick=save;$('download').onclick=()=>{let v=payload();if(!v.effects.length)return status('Sélectionnez au moins un effet.',1);download(v,filename(v.name));status('JSON téléchargé.')};$('copy').onclick=copy;$('library-search').oninput=renderLibrary;$('backup').onclick=()=>download({format:'ravenous-effects-library',version:1,sets:read(SK)},'ravenous-effects-library.json');$('restore').onclick=()=>$('file').click();$('file').onchange=restore;renderCards();renderSelected();renderLibrary();
|
||||
})();
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
<!doctype html>
|
||||
<html lang="fr" data-theme="warm">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="theme-color" content="#7a2424"><title>Ravenous · Effets</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar"><a class="brand" href="#catalogue"><span>R</span><b>Ravenous <small>Effets & tours</small></b></a><nav><a href="#catalogue">Catalogue</a><a href="#selection">Sélection</a><a href="#bibliotheque">Bibliothèque</a></nav><label>Thème <select id="theme">{{THEME_OPTIONS}}</select></label></header>
|
||||
<main>
|
||||
<section class="hero"><p class="eyebrow">Données du livre · {{CATALOG_HASH}}</p><h1>Les altérations, prêtes pour la chasse.</h1><p>Recherchez les règles, cochez les effets utiles et préparez une bibliothèque réutilisable pour votre personnage.</p></section>
|
||||
<section class="workspace" id="catalogue">
|
||||
<aside class="filters" aria-label="Filtres"><h2>Explorer</h2>
|
||||
<label>Recherche<input id="search" type="search" placeholder="Nom, description, catégorie…"></label>
|
||||
<label>Groupe<select id="group"><option value="">Tous</option></select></label>
|
||||
<label>Résistance<select id="resistance"><option value="">Toutes</option></select></label>
|
||||
<label>Difficulté<select id="difficulty"><option value="">Toutes</option></select></label>
|
||||
<label>Catégorie<input id="category" type="search" placeholder="Feu, mentale, marque…"></label>
|
||||
<button id="clear" class="quiet" type="button">Effacer les filtres</button>
|
||||
<details><summary>Créer un effet personnel</summary><form id="custom-form"><label>Nom<input id="custom-name" required maxlength="120"></label><label>Type<select id="custom-type"><option value="alteration">Altération</option><option value="dot">Dégâts sur la durée</option><option value="hot">Soin sur la durée</option><option value="bonus">Bonus</option><option value="malus">Malus</option><option value="other">Autre</option></select></label><label>Description<textarea id="custom-description" maxlength="1000" rows="4"></textarea></label><button type="submit">Ajouter localement</button></form></details>
|
||||
</aside>
|
||||
<div class="catalog"><div class="catalog-head"><div><h2>Catalogue</h2><output id="result-count" aria-live="polite"></output></div><label>Trier <select id="sort"><option value="name">Nom</option><option value="group">Groupe</option><option value="difficulty">Difficulté</option></select></label></div><div id="cards" class="cards"></div></div>
|
||||
</section>
|
||||
<section class="selection-panel" id="selection"><div class="section-head"><div><p class="eyebrow">Votre paquet</p><h2>Effets sélectionnés</h2></div><button id="clear-selection" class="quiet" type="button">Tout décocher</button></div><label>Nom de la bibliothèque<input id="set-name" maxlength="150" value="Mes effets"></label><div id="selected" class="selected"></div><div class="actions"><button id="save-set">Sauvegarder</button><button id="download">Télécharger JSON</button><button id="copy" class="quiet">Copier JSON</button></div><output id="status" aria-live="polite"></output></section>
|
||||
<section class="library" id="bibliotheque"><div class="section-head"><div><p class="eyebrow">Sur cet appareil</p><h2>Bibliothèque locale</h2></div><div class="actions"><button id="backup" class="quiet">Sauvegarder tout</button><button id="restore" class="quiet">Restaurer</button><input id="file" class="visually-hidden" type="file" accept="application/json,.json"></div></div><label>Rechercher<input id="library-search" type="search" placeholder="Nom de bibliothèque…"></label><div id="saved" class="saved"></div></section>
|
||||
</main>
|
||||
<footer>Aucun compte · aucune télémétrie · vos sélections restent dans ce navigateur</footer>
|
||||
<noscript>JavaScript est nécessaire pour filtrer et exporter les effets.</noscript>
|
||||
<script src="catalog.js"></script><script src="app.js"></script>
|
||||
</body></html>
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
:root{--ink:#302c26;--muted:#716957;--gold:#9b8050;--dark-gold:#70582f;--paper:#f4ebd8;--surface:#fbf9f3;--accent:#ede1c8;--border:#c9bda4;--blood:#7a2424;--shadow:0 16px 45px #302c2620}{{THEME_CSS}}
|
||||
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;color:var(--ink);background:var(--paper);font:14px/1.5 Georgia,serif;background-image:radial-gradient(circle at 12% 4%,color-mix(in srgb,var(--gold) 12%,transparent),transparent 30%)}button,input,select,textarea{font:inherit}button,select{cursor:pointer}button{padding:9px 13px;border:0;background:var(--blood);color:var(--surface)}input,select,textarea{width:100%;padding:8px;border:1px solid var(--border);background:var(--surface);color:var(--ink)}label{display:block;color:var(--muted);font-size:11px}.topbar{position:sticky;z-index:10;top:0;display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:24px;padding:10px max(22px,calc((100vw - 1200px)/2));border-bottom:1px solid var(--border);background:color-mix(in srgb,var(--surface) 92%,transparent);backdrop-filter:blur(12px)}.brand{display:flex;gap:12px;align-items:center;color:var(--ink);text-decoration:none}.brand>span{display:grid;place-items:center;width:38px;height:38px;background:var(--blood);color:var(--surface);font-size:22px;transform:rotate(45deg)}.brand b{font-family:Georgia,serif}.brand small{display:block;color:var(--muted);font-size:9px;text-transform:uppercase}.topbar nav{display:flex}.topbar nav a{padding:8px;color:var(--muted);text-decoration:none}.topbar>label{justify-self:end;display:flex;align-items:center;gap:8px}.topbar select{width:auto}main{max-width:1200px;margin:auto;padding:0 20px}.hero{padding:70px 20px 45px}.eyebrow{margin:0;color:var(--dark-gold);font-size:10px;text-transform:uppercase;letter-spacing:.12em}.hero h1{max-width:800px;margin:8px 0;color:var(--blood);font-size:clamp(34px,6vw,66px);line-height:1}.hero>p:last-child{max-width:650px;color:var(--muted);font-size:17px}.workspace{display:grid;grid-template-columns:260px 1fr;border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow)}.filters{padding:22px;border-right:1px solid var(--border);background:var(--accent)}.filters h2,.catalog h2,.selection-panel h2,.library h2{margin:0;color:var(--blood)}.filters label{margin:12px 0}.filters details{margin-top:24px}.filters summary{color:var(--dark-gold);cursor:pointer}.filters form{margin-top:10px}.quiet{border:1px solid var(--gold);background:transparent;color:var(--dark-gold)}.catalog{min-width:0;padding:22px}.catalog-head,.section-head{display:flex;justify-content:space-between;align-items:end;gap:15px}.catalog-head label{display:flex;gap:8px;align-items:center}.catalog-head select{width:auto}.cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:18px}.card{display:grid;grid-template-columns:auto 1fr;gap:12px;padding:15px;border:1px solid var(--border);border-top:3px solid var(--gold);background:var(--paper)}.card input{width:20px;height:20px}.card h3{margin:0;color:var(--blood)}.card p{margin:5px 0;color:var(--muted);font-size:12px}.meta{color:var(--dark-gold);font-size:10px}.card.custom{border-color:var(--blood)}.card .delete{margin-top:8px;padding:4px 7px}.selection-panel,.library{margin:55px 0;padding:25px;border:1px solid var(--border);background:var(--surface);box-shadow:var(--shadow)}.selection-panel>label,.library>label{max-width:420px;margin:15px 0}.selected,.saved{display:grid;gap:8px;margin:16px 0}.selected-row,.saved-card{padding:12px;border-left:3px solid var(--gold);background:var(--accent)}.selected-row summary{cursor:pointer;color:var(--blood);font-weight:bold}.edit-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-top:10px}.edit-grid .wide{grid-column:1/-1}.actions{display:flex;flex-wrap:wrap;gap:7px}.saved-card h3{margin:0;color:var(--blood)}.saved-card p{margin:4px 0;color:var(--muted)}#status{display:block;min-height:20px;margin-top:10px;color:var(--dark-gold)}footer{padding:35px;text-align:center;color:var(--muted)}.visually-hidden{position:absolute!important;width:1px!important;height:1px!important;overflow:hidden!important;clip:rect(0,0,0,0)!important}:focus-visible{outline:3px solid var(--gold);outline-offset:2px}@media(max-width:760px){.topbar{grid-template-columns:1fr auto}.topbar nav{display:none}.workspace{grid-template-columns:1fr}.filters{border:0;border-bottom:1px solid var(--border)}.cards{grid-template-columns:1fr}.edit-grid{grid-template-columns:1fr}.edit-grid .wide{grid-column:auto}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}}@media print{.topbar,.filters,.actions,.library{display:none}.workspace{display:block;border:0}.cards{grid-template-columns:1fr 1fr}.selection-panel{box-shadow:none}}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class EffectsSiteTests(unittest.TestCase):
|
||||
def test_static_build_is_complete_and_deterministic(self):
|
||||
with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
|
||||
for target in (first, second):
|
||||
subprocess.run(["python", "effects_web/tools/build.py", "--output", target], cwd=ROOT, check=True)
|
||||
one, two = Path(first), Path(second)
|
||||
expected = {"index.html", "styles.css", "app.js", "catalog.js", "build-info.json", "ravenous-effects-v1.schema.json"}
|
||||
self.assertEqual({p.name for p in one.iterdir()}, expected)
|
||||
for path in one.iterdir():
|
||||
self.assertEqual(path.read_bytes(), (two / path.name).read_bytes())
|
||||
info = json.loads((one / "build-info.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(info["effects"], 81)
|
||||
self.assertGreaterEqual(len(info["themes"]), 10)
|
||||
for path in one.iterdir():
|
||||
if path.suffix in {".html", ".css", ".js"}:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
self.assertNotIn("{{", text)
|
||||
self.assertNotIn("http://", text)
|
||||
self.assertNotIn("https://", text)
|
||||
|
||||
def test_catalog_translation_and_export_contract(self):
|
||||
with tempfile.TemporaryDirectory() as target:
|
||||
subprocess.run(["python", "effects_web/tools/build.py", "--output", target], cwd=ROOT, check=True)
|
||||
raw = (Path(target) / "catalog.js").read_text(encoding="utf-8")
|
||||
catalog = json.loads(raw.removeprefix("window.RAVENOUS_EFFECTS_CATALOG=").removesuffix(";\n"))
|
||||
effects = {item["id"]: item for item in catalog["effects"]}
|
||||
self.assertEqual(effects["al_saignement"]["effect_id"], "al_saignement")
|
||||
self.assertIn("Chaque marque dure 2 tours", effects["al_saignement"]["description"])
|
||||
self.assertIn("premiers secours", effects["al_saignement"]["description"])
|
||||
self.assertIn("réinitialisez la durée", effects["al_poison"]["description"])
|
||||
self.assertIn("15 marques Poison maximum", effects["al_poison"]["description"])
|
||||
self.assertIn("Peur", effects["al_peur"]["description"])
|
||||
for item in effects.values():
|
||||
self.assertNotRegex(item["description"], r"(?:#(?:alteration-mark|reference)|@[A-Za-z_])")
|
||||
schema = json.loads((Path(target) / "ravenous-effects-v1.schema.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(schema["properties"]["format"]["const"], "ravenous-roll20-effects")
|
||||
self.assertEqual(schema["$defs"]["effect"]["required"], ["effect_id", "type", "name"])
|
||||
app = (Path(target) / "app.js").read_text(encoding="utf-8")
|
||||
self.assertIn("ravenous-roll20-effects", app)
|
||||
self.assertIn("ravenous-effects-sets", app)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Build the dependency-free Ravenous Effects Library static site."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
WEB = ROOT / "effects_web"
|
||||
SRC = WEB / "src"
|
||||
SOURCE = ROOT / "ravenous_typst/data/src/glossaries/alterations.yaml"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.build import (_replace_balanced_calls, effect_reminder_metadata, # noqa: E402
|
||||
read_glossary_labels, read_theme_palettes, translate_typst)
|
||||
|
||||
|
||||
def translate_alteration(text: str, glossary: dict[str, str]) -> str:
|
||||
"""Render alteration-only macros before the shared conservative translator."""
|
||||
text = re.sub(r'#reference\(<[^>]+>,\s*fallback:\s*\[([^]]+)]\)', r'\1', text)
|
||||
|
||||
def alteration_mark(arguments: str) -> str:
|
||||
positional = re.findall(r'(?<!:\s)\[([^]]*)]', arguments)
|
||||
if len(positional) < 4:
|
||||
raise ValueError("alteration-mark requires four positional arguments")
|
||||
recovery = re.search(r'recovery\s*:\s*\[([^]]*)]', arguments)
|
||||
trigger = re.search(r'trigger\s*:\s*"([^"]*)"', arguments)
|
||||
duration = re.search(r'duration\s*:\s*(\d+)', arguments)
|
||||
cumulative = re.search(r'cumulative\s*:\s*true', arguments)
|
||||
maximum = re.search(r'maximum\s*:\s*(\d+)', arguments)
|
||||
name, mark_type, placement, effect = positional[:4]
|
||||
trigger_text = trigger.group(1) if trigger else "subissez"
|
||||
duration_value = int(duration.group(1)) if duration else 2
|
||||
turn_word = "tour" if duration_value == 1 else "tours"
|
||||
parts = [
|
||||
mark_type,
|
||||
f"À chaque fois que vous {trigger_text} un effet de {name}, placez une marque {name} {placement}.",
|
||||
f"À la fin de votre tour, {effect}",
|
||||
f"Chaque marque dure {duration_value} {turn_word}.",
|
||||
]
|
||||
if recovery:
|
||||
parts.append(f"Vous perdez cette altération {recovery.group(1)}.")
|
||||
if cumulative:
|
||||
parts.append(f"À chaque fois que vous gagnez une nouvelle marque {name}, réinitialisez la durée de cette altération.")
|
||||
if maximum:
|
||||
parts.append(f"Vous pouvez posséder jusqu'à {maximum.group(1)} marques {name} maximum.")
|
||||
return " ".join(parts)
|
||||
|
||||
return translate_typst(_replace_balanced_calls(text, "alteration-mark", alteration_mark), glossary)
|
||||
|
||||
|
||||
def effects_catalog() -> list[dict]:
|
||||
glossary = read_glossary_labels()
|
||||
rows = yaml.safe_load(SOURCE.read_text(encoding="utf-8")) or []
|
||||
effects = []
|
||||
for row in rows:
|
||||
key = str(row.get("key", "")).strip()
|
||||
if not key.startswith("al_") or row.get("group") == "Types d'altérations":
|
||||
continue
|
||||
custom = row.get("custom") if isinstance(row.get("custom"), dict) else {}
|
||||
raw_description = str(row.get("description", ""))
|
||||
description = translate_alteration(raw_description, glossary)
|
||||
category = translate_typst(str(custom.get("category", "")), glossary)
|
||||
timing = effect_reminder_metadata(description)
|
||||
effects.append({
|
||||
"id": key, "effect_id": key, "name": str(row.get("short") or key),
|
||||
"group": str(row.get("group") or "Altérations"),
|
||||
"description": description, "resisted_by": str(custom.get("resisted_by", "")),
|
||||
"difficulty": custom.get("difficulty", ""), "category": category,
|
||||
"type": "alteration", "enabled": True,
|
||||
"duration": "", "duration_type": timing.get("duration_type", "manual"),
|
||||
"remaining": timing.get("remaining", 0),
|
||||
"countdown_phase": timing.get("countdown_phase", "end"),
|
||||
"start_reminder": timing.get("start_reminder", ""),
|
||||
"end_reminder": timing.get("end_reminder", ""),
|
||||
"apply_reminder": "", "removal_reminder": "",
|
||||
})
|
||||
return effects
|
||||
|
||||
|
||||
def theme_css(palettes: dict[str, dict[str, str]]) -> str:
|
||||
keys = {"ink": "ink", "muted": "muted-ink", "gold": "gold", "dark-gold": "dark-gold",
|
||||
"paper": "parchment", "surface": "parchment-light", "accent": "parchment-accent",
|
||||
"border": "border", "blood": "blood"}
|
||||
return "\n".join(
|
||||
f'[data-theme="{name}"]{{' + "".join(f"--{css}:{palette[source].lower()};" for css, source in keys.items()) + "}"
|
||||
for name, palette in palettes.items()
|
||||
)
|
||||
|
||||
|
||||
def generated_files() -> dict[str, str]:
|
||||
effects = effects_catalog()
|
||||
palettes = read_theme_palettes()
|
||||
packed = json.dumps({"version": 1, "effects": effects, "themes": list(palettes)},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
digest = hashlib.sha256(packed.encode("utf-8")).hexdigest()[:12]
|
||||
replacements = {
|
||||
"{{THEME_OPTIONS}}": "".join(f'<option value="{name}">{name.replace("-", " ").title()}</option>' for name in palettes),
|
||||
"{{THEME_CSS}}": theme_css(palettes), "{{CATALOG_HASH}}": digest,
|
||||
}
|
||||
files = {}
|
||||
for name in ("index.html", "styles.css", "app.js"):
|
||||
content = (SRC / name).read_text(encoding="utf-8")
|
||||
for marker, value in replacements.items():
|
||||
content = content.replace(marker, value)
|
||||
files[name] = content
|
||||
files["catalog.js"] = "window.RAVENOUS_EFFECTS_CATALOG=" + packed + ";\n"
|
||||
files["ravenous-effects-v1.schema.json"] = (WEB / "schemas/ravenous-effects-v1.schema.json").read_text(encoding="utf-8")
|
||||
files["build-info.json"] = json.dumps({"catalog_hash": digest, "effects": len(effects),
|
||||
"groups": sorted({item["group"] for item in effects}), "themes": list(palettes)},
|
||||
ensure_ascii=False, indent=2) + "\n"
|
||||
return files
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--output", type=Path, default=WEB / "build")
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
files = generated_files()
|
||||
if args.check:
|
||||
stale = [name for name, content in files.items()
|
||||
if not (args.output / name).is_file() or (args.output / name).read_text(encoding="utf-8") != content]
|
||||
if stale:
|
||||
raise SystemExit("Effects website files are stale: " + ", ".join(stale))
|
||||
print(f"Effects website is current ({len(files)} files).")
|
||||
return
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
for old in args.output.iterdir():
|
||||
if old.is_file():
|
||||
old.unlink()
|
||||
elif old.is_dir():
|
||||
shutil.rmtree(old)
|
||||
for name, content in files.items():
|
||||
(args.output / name).write_text(content, encoding="utf-8")
|
||||
print(f"Built effects website: {len(files)} files, {len(effects_catalog())} effects.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,163 @@
|
|||
/* Ravenous reusable-effects importer for Roll20 Mod. Commands:
|
||||
* !ravenous-import-effects JSON
|
||||
* !ravenous-import-effects --id CHARACTER_ID JSON
|
||||
* !ravenous-import-effects --handout HANDOUT_ID
|
||||
* !ravenous-import-effects --id CHARACTER_ID --handout HANDOUT_ID
|
||||
*
|
||||
* Without --id, exactly one token representing the destination character must
|
||||
* be selected. Players may only use characters they control and handouts they
|
||||
* can read.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
var COMMAND = '!ravenous-import-effects';
|
||||
var FORMAT = 'ravenous-roll20-effects';
|
||||
var VERSION = 1;
|
||||
var LIMITS = { effects: 100, id: 80, name: 120, duration: 120, description: 1000, reminder: 500 };
|
||||
var TYPES = ['alteration', 'dot', 'hot', 'bonus', 'malus', 'other'];
|
||||
var DURATION_TYPES = ['manual', 'turns', 'until_start', 'until_end', 'combat'];
|
||||
var PHASES = ['start', 'end'];
|
||||
var FIELDS = ['enabled', 'effect_id', 'type', 'name', 'duration', 'description', 'duration_type',
|
||||
'remaining', 'countdown_phase', 'start_reminder', 'end_reminder', 'apply_reminder', 'removal_reminder'];
|
||||
var TOP_LEVEL_FIELDS = ['format', 'version', 'name', 'catalog', 'effects'];
|
||||
var TEXT_LIMITS = {
|
||||
effect_id: LIMITS.id, name: LIMITS.name, duration: LIMITS.duration,
|
||||
description: LIMITS.description, start_reminder: LIMITS.reminder,
|
||||
end_reminder: LIMITS.reminder, apply_reminder: LIMITS.reminder,
|
||||
removal_reminder: LIMITS.reminder
|
||||
};
|
||||
|
||||
function whisper(message, playerId) {
|
||||
if (!playerId || playerIsGM(playerId)) return sendChat('Ravenous Effects', '/w gm ' + message);
|
||||
var player = getObj('player', playerId);
|
||||
var name = String(player && player.get('_displayname') || 'player').replace(/"/g, '');
|
||||
sendChat('Ravenous Effects', '/w "' + name + '" ' + 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 validText(effect, field) {
|
||||
return effect[field] === undefined ||
|
||||
(typeof effect[field] === 'string' && effect[field].length <= TEXT_LIMITS[field]);
|
||||
}
|
||||
function validEffect(effect) {
|
||||
if (!plainObject(effect) || Object.keys(effect).some(function (key) { return FIELDS.indexOf(key) < 0; })) return false;
|
||||
if (typeof effect.effect_id !== 'string' || !effect.effect_id.trim() || effect.effect_id.length > LIMITS.id ||
|
||||
typeof effect.name !== 'string' || !effect.name.trim() || effect.name.length > LIMITS.name ||
|
||||
TYPES.indexOf(effect.type) < 0 ||
|
||||
(effect.enabled !== undefined && typeof effect.enabled !== 'boolean') ||
|
||||
(effect.duration_type !== undefined && DURATION_TYPES.indexOf(effect.duration_type) < 0) ||
|
||||
(effect.countdown_phase !== undefined && PHASES.indexOf(effect.countdown_phase) < 0) ||
|
||||
(effect.remaining !== undefined && (!Number.isInteger(effect.remaining) || effect.remaining < 0 || effect.remaining > 999))) return false;
|
||||
return Object.keys(TEXT_LIMITS).every(function (field) { return validText(effect, field); });
|
||||
}
|
||||
function validPayload(data) {
|
||||
return plainObject(data) && data.format === FORMAT && data.version === VERSION &&
|
||||
!Object.keys(data).some(function (key) { return TOP_LEVEL_FIELDS.indexOf(key) < 0; }) &&
|
||||
(data.name === undefined || (typeof data.name === 'string' && data.name.length <= 150)) &&
|
||||
(data.catalog === undefined || (typeof data.catalog === 'string' && data.catalog.length <= 64)) &&
|
||||
Array.isArray(data.effects) && data.effects.length > 0 && data.effects.length <= LIMITS.effects &&
|
||||
data.effects.every(validEffect);
|
||||
}
|
||||
function decodeHandout(raw) {
|
||||
var text = String(raw || '');
|
||||
text = text.replace(/<br\s*\/?\s*>/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 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 'effect' + Date.now().toString(36) + index.toString(36) +
|
||||
Math.floor(Math.random() * 1679616).toString(36);
|
||||
}
|
||||
function valuesFor(effect) {
|
||||
return {
|
||||
enabled: effect.enabled === false ? '0' : '1', effect_id: effect.effect_id.trim(), type: effect.type,
|
||||
name: effect.name.trim(), duration: effect.duration || '', description: effect.description || '',
|
||||
duration_type: effect.duration_type || 'manual', remaining: String(effect.remaining || 0),
|
||||
countdown_phase: effect.countdown_phase || 'end', start_reminder: effect.start_reminder || '',
|
||||
end_reminder: effect.end_reminder || '', apply_reminder: effect.apply_reminder || '',
|
||||
removal_reminder: effect.removal_reminder || ''
|
||||
};
|
||||
}
|
||||
function importEffects(characterId, data, playerId) {
|
||||
if (!validPayload(data)) return whisper('Invalid or unsupported Ravenous effects JSON.', playerId);
|
||||
var character = getObj('character', characterId);
|
||||
if (!character) return whisper('Character not found. Select a linked token or use --id CHARACTER_ID.', playerId);
|
||||
data.effects.forEach(function (effect, index) {
|
||||
var prefix = 'repeating_sharedeffects_' + rowId(index) + '_';
|
||||
var values = valuesFor(effect);
|
||||
FIELDS.forEach(function (field) {
|
||||
createObj('attribute', { characterid: characterId, name: prefix + field, current: values[field], max: '' });
|
||||
});
|
||||
});
|
||||
whisper('Imported ' + data.effects.length + ' reusable effect(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.', 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.', message.playerid);
|
||||
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.', 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.', message.playerid);
|
||||
if (args.handout) {
|
||||
var handout = getObj('handout', args.handout);
|
||||
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 { importEffects(characterId, decodeHandout(notes), message.playerid); }
|
||||
catch (error) { whisper('Handout does not contain valid Ravenous effects JSON.', message.playerid); }
|
||||
});
|
||||
}
|
||||
try { importEffects(characterId, JSON.parse(args.json), message.playerid); }
|
||||
catch (error) { whisper('Invalid JSON.', message.playerid); }
|
||||
});
|
||||
}());
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
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_effects_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, Number, parseInt, String,
|
||||
});
|
||||
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);
|
||||
}
|
||||
|
||||
function payload(effects) {
|
||||
return { format: 'ravenous-roll20-effects', version: 1, effects };
|
||||
}
|
||||
|
||||
test('imports complete reusable effect rows into a selected character', () => {
|
||||
const game = session();
|
||||
const character = game.createObj('character', { name: 'Ariane' });
|
||||
const token = game.createObj('graphic', { represents: character.id });
|
||||
const effect = {
|
||||
enabled: false, effect_id: 'combustion', type: 'dot', name: 'Combustion', duration: '3 tours',
|
||||
description: 'Perdez quatre points de vie.', duration_type: 'turns', remaining: 3,
|
||||
countdown_phase: 'start', start_reminder: 'Subissez 4 dégâts.', end_reminder: 'Testez la résistance.',
|
||||
apply_reminder: 'La cible prend feu.', removal_reminder: 'Les flammes cessent.'
|
||||
};
|
||||
const library = { ...payload([effect]), name: 'Feux favoris', catalog: '0123456789ab' };
|
||||
game.send(`!ravenous-import-effects ${JSON.stringify(library)}`, 'gm',
|
||||
[{ _type: 'graphic', _id: token.id }]);
|
||||
|
||||
const attrs = attributes(game, character.id);
|
||||
assert.equal(attrs.length, 13, JSON.stringify(game.chat));
|
||||
const values = Object.fromEntries(attrs.map(attribute => [
|
||||
attribute.get('name').replace(/^repeating_sharedeffects_[^_]+_/, ''), attribute.get('current')
|
||||
]));
|
||||
assert.deepEqual(values, {
|
||||
enabled: '0', effect_id: 'combustion', type: 'dot', name: 'Combustion', duration: '3 tours',
|
||||
description: 'Perdez quatre points de vie.', duration_type: 'turns', remaining: '3',
|
||||
countdown_phase: 'start', start_reminder: 'Subissez 4 dégâts.', end_reminder: 'Testez la résistance.',
|
||||
apply_reminder: 'La cible prend feu.', removal_reminder: 'Les flammes cessent.'
|
||||
});
|
||||
assert.match(game.chat.at(-1).content, /Imported 1 reusable effect/);
|
||||
});
|
||||
|
||||
test('fills every sheet field with safe defaults', () => {
|
||||
const game = session();
|
||||
const character = game.createObj('character', { name: 'Ariane' });
|
||||
game.send(`!ravenous-import-effects --id ${character.id} ${JSON.stringify(payload([
|
||||
{ effect_id: 'inspiration', type: 'bonus', name: 'Inspiration' }
|
||||
]))}`);
|
||||
const attrs = attributes(game, character.id);
|
||||
assert.equal(attrs.length, 13);
|
||||
const values = attrs.map(attribute => attribute.get('current'));
|
||||
assert.ok(values.includes('manual'));
|
||||
assert.ok(values.includes('end'));
|
||||
assert.ok(values.includes('1'));
|
||||
assert.ok(values.includes('0'));
|
||||
});
|
||||
|
||||
test('a player can import an HTML-escaped accessible handout into a controlled character', () => {
|
||||
const game = session();
|
||||
const player = game.createObj('player', { _displayname: 'Alice' });
|
||||
const character = game.createObj('character', { name: 'Ariane', controlledby: player.id });
|
||||
const data = payload([{ effect_id: 'a-b', type: 'alteration', name: 'A & B', description: '<rare>' }]);
|
||||
const escaped = JSON.stringify(data).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const handout = game.createObj('handout', { inplayerjournals: player.id, notes: `<pre>${escaped}</pre>` });
|
||||
game.send(`!ravenous-import-effects --id ${character.id} --handout ${handout.id}`, player.id);
|
||||
assert.ok(attributes(game, character.id).some(attribute => attribute.get('current') === 'A & B'), JSON.stringify(game.chat));
|
||||
assert.ok(attributes(game, character.id).some(attribute => attribute.get('current') === '<rare>'));
|
||||
});
|
||||
|
||||
test('rejects unauthorized, malformed, unknown, oversized, and out-of-range payloads', () => {
|
||||
const invalidEffects = [
|
||||
{ effect_id: 'bad', type: 'unknown', name: 'Bad' },
|
||||
{ effect_id: 'bad', type: 'dot', name: 'Bad', remaining: 1000 },
|
||||
{ effect_id: 'bad', type: 'dot', name: 'Bad', enabled: 'yes' },
|
||||
{ effect_id: 'bad', type: 'dot', name: 'Bad', extra: true },
|
||||
{ effect_id: '', type: 'dot', name: 'Bad' },
|
||||
];
|
||||
for (const effect of invalidEffects) {
|
||||
const game = session();
|
||||
const character = game.createObj('character', { name: 'Ariane' });
|
||||
game.send(`!ravenous-import-effects --id ${character.id} ${JSON.stringify(payload([effect]))}`);
|
||||
assert.equal(attributes(game, character.id).length, 0);
|
||||
assert.match(game.chat.at(-1).content, /Invalid or unsupported/);
|
||||
}
|
||||
|
||||
const game = session();
|
||||
const character = game.createObj('character', { name: 'Ariane' });
|
||||
game.send(`!ravenous-import-effects --id ${character.id} ${JSON.stringify(payload([
|
||||
{ effect_id: 'ok', type: 'other', name: 'Okay' }
|
||||
]))}`, 'intruder');
|
||||
game.send(`!ravenous-import-effects --id ${character.id} {bad}`);
|
||||
game.send(`!ravenous-import-effects --id ${character.id} ${JSON.stringify({ ...payload([
|
||||
{ effect_id: 'ok', type: 'other', name: 'Okay' }
|
||||
]), extra: true })}`);
|
||||
assert.equal(attributes(game, character.id).length, 0);
|
||||
});
|
||||
|
||||
test('rejects a handout the player cannot read and a character they cannot control', () => {
|
||||
const game = session();
|
||||
const player = game.createObj('player', { _displayname: 'Alice' });
|
||||
const own = game.createObj('character', { name: 'Ariane', controlledby: player.id });
|
||||
const other = game.createObj('character', { name: 'Autre' });
|
||||
const handout = game.createObj('handout', { notes: JSON.stringify(payload([
|
||||
{ effect_id: 'ok', type: 'other', name: 'Okay' }
|
||||
])) });
|
||||
game.send(`!ravenous-import-effects --id ${own.id} --handout ${handout.id}`, player.id);
|
||||
game.send(`!ravenous-import-effects --id ${other.id} ${handout.get('notes')}`, player.id);
|
||||
assert.equal(attributes(game, own.id).length, 0);
|
||||
assert.equal(attributes(game, other.id).length, 0);
|
||||
assert.match(game.chat.at(-1).content, /Permission denied/);
|
||||
});
|
||||
Loading…
Reference in New Issue