feat: add persistent custom craft ingredients
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:
Dandaedre 2026-09-19 22:15:00 +02:00
parent 436646bb01
commit 3aea8c9e0f
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
5 changed files with 76 additions and 16 deletions

View File

@ -12,6 +12,8 @@ before implementation because they affect saved data, URLs, and deployment.
- [x] Let players add/remove components and display live tier, cost, difficulty,
toxicity, artisan level, and a simple difficulty warning.
- [x] Demonstrate local browser saving and a provisional Roll20 JSON download.
- [x] Enforce one craft discipline per recipe and lock it from the first component.
- [x] Let players create and remove persistent personal ingredients in local storage.
- [x] Add deterministic Python tests and a `--check` build mode.
- [x] Build, archive, and deploy the prototype through Jenkins below `RPG/`.

View File

@ -2,71 +2,114 @@
'use strict';
const data = window.RAVENOUS_CRAFT_CATALOG || { entries: [], themes: [] };
const $ = id => document.getElementById(id);
const state = { shown: 30, selected: [] };
const CUSTOM_KEY = 'ravenous-craft-custom-ingredients';
const RECIPES_KEY = 'ravenous-craft-recipes';
const state = { shown: 30, selected: [], custom: readLocal(CUSTOM_KEY, []) };
let catalog = [...data.entries, ...state.custom];
const numeric = value => value == null ? 0 : Number(value) || 0;
const fold = value => String(value || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
const stars = value => { const n = numeric(value), a = Math.abs(n); return `${n < 0 ? '-' : ''}${a > 3 ? a : '★'.repeat(a)}${a === 0 || a > 3 ? '★' : ''}`; };
const text = item => Object.values(item.fields || {}).join(' ');
function readLocal(key, fallback) {
try { const value = JSON.parse(localStorage.getItem(key) || 'null'); return Array.isArray(value) ? value : fallback; }
catch (_) { return fallback; }
}
function writeLocal(key, value) {
try { localStorage.setItem(key, JSON.stringify(value)); return true; }
catch (_) { return false; }
}
function effect(item) {
const entries = Object.entries(item.fields || {}).filter(([key]) => !/^(Nom|Matériau|Réagents|Solvants|Type)$/i.test(key));
return entries.slice(-2).map(([key, value]) => `${key} : ${value}`).join(' · ') || 'Détails disponibles dans la source.';
}
function selectedDiscipline() { return state.selected[0]?.discipline || ''; }
function filtered() {
const query = fold($('search').value), discipline = $('discipline').value, stage = $('stage').value;
const limits = [['tier','tier'],['difficulty','difficulty'],['toxicity','toxicity']];
let entries = data.entries.filter(item => (!discipline || item.discipline === discipline) && (!stage || item.stage === stage) &&
(!query || fold(`${item.name} ${item.stage} ${text(item)}`).includes(query)) && limits.every(([id,key]) => !$ (id).value || item[key] == null || numeric(item[key]) <= numeric($(id).value)));
const entries = catalog.filter(item => (!discipline || item.discipline === discipline) && (!stage || item.stage === stage) &&
(!query || fold(`${item.name} ${item.stage} ${text(item)}`).includes(query)) && limits.every(([id,key]) => !$(id).value || item[key] == null || numeric(item[key]) <= numeric($(id).value)));
const sort = $('sort').value;
entries.sort((a,b) => sort === 'name' ? a.name.localeCompare(b.name, 'fr') : numeric(a[sort]) - numeric(b[sort]) || a.name.localeCompare(b.name, 'fr'));
return entries;
}
function renderStages() {
const current = $('stage').value, discipline = $('discipline').value;
const stages = [...new Set(data.entries.filter(i => !discipline || i.discipline === discipline).map(i => i.stage))].sort();
const stages = [...new Set(catalog.filter(i => !discipline || i.discipline === discipline).map(i => i.stage))].sort();
$('stage').replaceChildren(new Option('Toutes les étapes', ''), ...stages.map(value => new Option(value, value)));
if (stages.includes(current)) $('stage').value = current;
}
function addItem(item) {
const locked = selectedDiscipline();
if (locked && item.discipline !== locked) return;
state.selected.push(item); renderSelection(); location.hash = 'atelier';
}
function removeCustom(item) {
if (!confirm(`Supprimer « ${item.name} » de vos ingrédients personnels ?`)) return;
state.custom = state.custom.filter(entry => entry.id !== item.id);
state.selected = state.selected.filter(entry => entry.id !== item.id);
catalog = [...data.entries, ...state.custom]; writeLocal(CUSTOM_KEY, state.custom);
refreshCatalog(); renderSelection();
}
function renderCards() {
const entries = filtered();
const entries = filtered(), locked = selectedDiscipline();
$('result-count').textContent = `${entries.length} résultat${entries.length > 1 ? 's' : ''}`;
$('cards').replaceChildren(...entries.slice(0, state.shown).map(item => {
const card = document.createElement('article'); card.className = 'card';
const card = document.createElement('article'); card.className = `card${item.custom ? ' custom-card' : ''}`;
const metrics = [['T',item.tier],['Coût',item.cost],['Diff.',item.difficulty],['Tox.',item.toxicity]].filter(([,v]) => v != null);
card.innerHTML = `<div class="card-meta"><span>${item.discipline}</span><span>${item.stage}</span></div><h3></h3><p class="effect"></p><div class="metrics"></div><button type="button">Ajouter</button>`;
card.innerHTML = '<div class="card-meta"><span></span><span></span></div><h3></h3><p class="effect"></p><div class="metrics"></div><div class="card-actions"><button class="add-item" type="button">Ajouter</button></div>';
const meta=card.querySelectorAll('.card-meta span'); meta[0].textContent=item.discipline; meta[1].textContent=`${item.custom ? 'Personnel · ' : ''}${item.stage}`;
card.querySelector('h3').textContent = item.name; card.querySelector('.effect').textContent = effect(item);
const box = card.querySelector('.metrics'); metrics.forEach(([k,v]) => { const span=document.createElement('span'); span.textContent=`${k} ${k==='T'?v:stars(v)}`; box.append(span); });
card.querySelector('button').addEventListener('click', () => { state.selected.push(item); renderSelection(); location.hash='atelier'; });
const add = card.querySelector('.add-item'), incompatible = locked && item.discipline !== locked;
add.disabled = Boolean(incompatible); add.textContent = incompatible ? `Réservé : ${locked}` : 'Ajouter';
add.title = incompatible ? `Cette recette utilise déjà l'artisanat ${locked}.` : '';
add.addEventListener('click', () => addItem(item));
if (item.custom) { const remove=document.createElement('button'); remove.type='button'; remove.className='delete-custom'; remove.textContent='Supprimer'; remove.onclick=()=>removeCustom(item); card.querySelector('.card-actions').append(remove); }
return card;
}));
$('more').hidden = entries.length <= state.shown;
}
function renderSelection() {
const box = $('selection'); box.replaceChildren();
const box = $('selection'), locked = selectedDiscipline(); box.replaceChildren();
$('recipe-discipline').disabled = Boolean(locked); if (locked) $('recipe-discipline').value = locked;
if (!state.selected.length) { const p=document.createElement('p'); p.className='empty'; p.textContent='Aucun composant sélectionné.'; box.append(p); }
state.selected.forEach((item,index) => { const row=document.createElement('div'); row.className='selected-item'; row.innerHTML='<div><b></b><small></small></div><button aria-label="Retirer">×</button>'; row.querySelector('b').textContent=item.name; row.querySelector('small').textContent=`${item.discipline} · ${item.stage}`; row.querySelector('button').onclick=()=>{state.selected.splice(index,1);renderSelection();}; box.append(row); });
state.selected.forEach((item,index) => { const row=document.createElement('div'); row.className='selected-item'; row.innerHTML='<div><b></b><small></small></div><button aria-label="Retirer">×</button>'; row.querySelector('b').textContent=item.name; row.querySelector('small').textContent=`${item.discipline} · ${item.stage}${item.custom?' · personnel':''}`; row.querySelector('button').onclick=()=>{state.selected.splice(index,1);renderSelection();}; box.append(row); });
const sum = key => state.selected.reduce((total,item)=>total+numeric(item[key]),0);
$('sum-tier').textContent = Math.max(0,...state.selected.map(i=>numeric(i.tier)));
$('sum-cost').textContent=stars(sum('cost')); $('sum-difficulty').textContent=stars(sum('difficulty')); $('sum-toxicity').textContent=stars(sum('toxicity'));
const level=numeric($('intelligence').value)+numeric($('skill').value)+numeric($('excellence').value); $('craft-level').textContent=level;
const invalid=sum('difficulty')>level, validity=$('validity'); validity.className=`validity ${invalid?'bad':'good'}`; validity.firstElementChild.textContent=invalid?'Niveau dépassé':'Recette possible'; validity.lastElementChild.textContent=invalid?`Difficulté ${sum('difficulty')} pour un niveau ${level}.`:`Niveau ${level} · ${state.selected.length} composant(s).`;
const invalid=sum('difficulty')>level, validity=$('validity'); validity.className=`validity ${invalid?'bad':'good'}`; validity.firstElementChild.textContent=invalid?'Niveau dépassé':'Recette possible'; validity.lastElementChild.textContent=invalid?`Difficulté ${sum('difficulty')} pour un niveau ${level}.`:`${locked || 'Discipline libre'} · niveau ${level} · ${state.selected.length} composant(s).`;
renderCards();
}
function addCustom(event) {
event.preventDefault();
const name=$('custom-name').value.trim(), stage=$('custom-stage').value.trim(), status=$('custom-status');
if (!name || !stage) { status.textContent='Le nom et l’étape sont requis.'; return; }
const optional = id => $(id).value === '' ? null : numeric($(id).value);
const item={id:`custom:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,8)}`,custom:true,name,discipline:$('custom-discipline').value,stage,tier:optional('custom-tier'),cost:optional('custom-cost'),difficulty:optional('custom-difficulty'),toxicity:optional('custom-toxicity'),finishing:null,source:'local',fields:{Effet:$('custom-effect').value.trim() || 'Ingrédient personnel'}};
state.custom.unshift(item);
if (!writeLocal(CUSTOM_KEY,state.custom)) { state.custom.shift(); status.textContent='Stockage local indisponible : ingrédient non enregistré.'; return; }
catalog=[...data.entries,...state.custom]; event.target.reset(); $('custom-discipline').value=item.discipline; status.textContent=`« ${name} » est enregistré sur cet appareil.`; refreshCatalog();
}
function refreshCatalog() { $('catalog-count').textContent=catalog.length; renderStages(); renderCards(); }
function saveRecipe() {
const recipes=JSON.parse(localStorage.getItem('ravenous-craft-recipes')||'[]'); recipes.unshift({name:$('recipe-name').value||'Sans nom', discipline:$('recipe-discipline').value, saved:new Date().toISOString(), items:state.selected.map(i=>i.id)}); localStorage.setItem('ravenous-craft-recipes',JSON.stringify(recipes.slice(0,50))); renderLibrary();
const recipes=readLocal(RECIPES_KEY,[]); recipes.unshift({name:$('recipe-name').value||'Sans nom',discipline:$('recipe-discipline').value,saved:new Date().toISOString(),items:state.selected.map(i=>i.id)}); writeLocal(RECIPES_KEY,recipes.slice(0,50)); renderLibrary();
}
function renderLibrary() {
const box=$('saved-recipes'), recipes=JSON.parse(localStorage.getItem('ravenous-craft-recipes')||'[]'); box.replaceChildren(); if(!recipes.length){const p=document.createElement('p');p.className='empty';p.textContent='Aucune recette sauvegardée pour le moment.';box.append(p);return;} recipes.forEach(recipe=>{const card=document.createElement('article');card.className='saved-card';card.innerHTML='<h3></h3><p></p>';card.querySelector('h3').textContent=recipe.name;card.querySelector('p').textContent=`${recipe.discipline} · ${recipe.items.length} composant(s) · sauvegarde locale`;box.append(card);});
const box=$('saved-recipes'), recipes=readLocal(RECIPES_KEY,[]); box.replaceChildren(); if(!recipes.length){const p=document.createElement('p');p.className='empty';p.textContent='Aucune recette sauvegardée pour le moment.';box.append(p);return;} recipes.forEach(recipe=>{const card=document.createElement('article');card.className='saved-card';card.innerHTML='<h3></h3><p></p>';card.querySelector('h3').textContent=recipe.name;card.querySelector('p').textContent=`${recipe.discipline} · ${recipe.items.length} composant(s) · sauvegarde locale`;box.append(card);});
}
function exportJson() {
const payload={format:'ravenous-roll20-craft',version:1,craft:{name:$('recipe-name').value,discipline:$('recipe-discipline').value,recipe:state.selected.map(i=>i.name).join('; '),level:numeric($('craft-level').textContent),difficulty:state.selected.reduce((n,i)=>n+numeric(i.difficulty),0)},items:[{type:'consumable',name:$('recipe-name').value||'Création artisanale',kind:'Autre',quantity:1,description:state.selected.map(i=>`${i.name}: ${effect(i)}`).join('\n')}]};
const blob=new Blob([JSON.stringify(payload,null,2)+'\n'],{type:'application/json'}), link=document.createElement('a');link.href=URL.createObjectURL(blob);link.download='ravenous-craft.json';link.click();URL.revokeObjectURL(link.href);
}
function setTheme(value){ document.documentElement.dataset.theme=value; localStorage.setItem('ravenous-craft-theme',value); $('theme').value=value; }
$('catalog-count').textContent=data.entries.length; setTheme(localStorage.getItem('ravenous-craft-theme')||'warm');
setTheme(localStorage.getItem('ravenous-craft-theme')||'warm');
['search','stage','tier','difficulty','toxicity','sort'].forEach(id => $(id).addEventListener('input',()=>{state.shown=30;renderCards();}));
$('discipline').addEventListener('change',()=>{renderStages();renderCards();document.querySelectorAll('#discipline-tabs button').forEach(b=>b.classList.toggle('active',b.dataset.value===$('discipline').value));});
$('discipline-tabs').addEventListener('click',event=>{if(!event.target.dataset.value&&event.target.tagName!=='BUTTON')return;$('discipline').value=event.target.dataset.value;renderStages();renderCards();document.querySelectorAll('#discipline-tabs button').forEach(b=>b.classList.toggle('active',b===event.target));});
$('clear').onclick=()=>{['search','discipline','stage','tier','difficulty','toxicity'].forEach(id=>$(id).value='');renderStages();renderCards();}; $('more').onclick=()=>{state.shown+=30;renderCards();}; $('theme').onchange=event=>setTheme(event.target.value);
$('custom-form').addEventListener('submit',addCustom);
['recipe-name','intelligence','skill','excellence'].forEach(id=>$(id).addEventListener('input',()=>{ $('summary-name').textContent=$('recipe-name').value||'Sans nom';renderSelection();})); $('save').onclick=saveRecipe; $('export-json').onclick=exportJson;
renderStages();renderCards();renderSelection();renderLibrary();
refreshCatalog(); renderSelection(); renderLibrary();
})();

View File

@ -31,6 +31,16 @@
<div class="range-row"><label>Tier max.<input id="tier" type="number" min="0" placeholder="∞"></label><label>Difficulté max.<input id="difficulty" type="number" placeholder="∞"></label></div>
<label>Toxicité max.<input id="toxicity" type="number" placeholder="∞"></label>
<div class="filter-actions"><button id="clear" class="quiet">Effacer</button><span id="result-count" aria-live="polite"></span></div>
<details class="custom-editor">
<summary>+ Ingrédient personnel</summary>
<form id="custom-form">
<label>Nom<input id="custom-name" required maxlength="80" placeholder="Ex. Pollen de lune"></label>
<div class="range-row"><label>Discipline<select id="custom-discipline"><option>Alchimie</option><option>Brasserie</option><option>Forge</option><option>Restauration</option><option>Pièges</option></select></label><label>Étape<input id="custom-stage" required maxlength="50" placeholder="Réactif"></label></div>
<div class="custom-numbers"><label>Tier<input id="custom-tier" type="number" min="0"></label><label>Coût<input id="custom-cost" type="number"></label><label>Difficulté<input id="custom-difficulty" type="number"></label><label>Toxicité<input id="custom-toxicity" type="number"></label></div>
<label>Effet<textarea id="custom-effect" rows="3" maxlength="500" placeholder="Propriétés et notes de jeu"></textarea></label>
<button type="submit">Enregistrer localement</button><output id="custom-status" class="custom-status" aria-live="polite"></output>
</form>
</details>
<div class="source-note"><b>Source de vérité</b><p>TSV, SQLite, glossaires et thèmes du livre Typst épinglé.</p></div>
</aside>
@ -47,7 +57,7 @@
<div class="recipe-form">
<div class="field-pair"><label>Nom de la création<input id="recipe-name" value="Prototype de chasse"></label><label>Discipline<select id="recipe-discipline"><option>Alchimie</option><option>Brasserie</option><option>Forge</option><option>Restauration</option><option>Pièges</option></select></label></div>
<div class="artisan-levels"><label>Intelligence<input id="intelligence" type="number" value="3"></label><span>+</span><label>Compétence<input id="skill" type="number" value="4"></label><span>+</span><label>Excellence<input id="excellence" type="number" value="1"></label><output id="craft-level">8</output></div>
<div class="drop-zone"><span>◆</span><div><b>Ajoutez des composants depuis le catalogue</b><p>Le glisser-déposer viendra ensuite. Pour ce prototype, utilisez le bouton « Ajouter ».</p></div></div>
<div class="drop-zone"><span>◆</span><div><b>Une seule discipline par recette</b><p>Le premier composant verrouille la discipline. Retirez tous les composants pour en changer.</p></div></div>
<div id="selection" class="selection"><p class="empty">Aucun composant sélectionné.</p></div>
</div>
<aside class="recipe-summary">

File diff suppressed because one or more lines are too long

View File

@ -22,6 +22,10 @@ class CraftSiteTests(unittest.TestCase):
html = (one / "index.html").read_text(encoding="utf-8")
self.assertNotIn("{{", html)
self.assertIn("catalog.js", html)
self.assertIn('id="custom-form"', html)
app = (one / "app.js").read_text(encoding="utf-8")
self.assertIn("ravenous-craft-custom-ingredients", app)
self.assertIn("item.discipline !== locked", app)
for path in one.iterdir():
if path.suffix in {".html", ".css", ".js"}:
content = path.read_text(encoding="utf-8")