From 3aea8c9e0fc3da7124a579cdf2d8ae33d0cc4303 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 19 Sep 2026 22:15:00 +0200 Subject: [PATCH] feat: add persistent custom craft ingredients --- craft_web/TASKS.md | 2 + craft_web/src/app.js | 73 ++++++++++++++++++++++++++++-------- craft_web/src/index.html | 12 +++++- craft_web/src/styles.css | 1 + craft_web/tests/test_site.py | 4 ++ 5 files changed, 76 insertions(+), 16 deletions(-) diff --git a/craft_web/TASKS.md b/craft_web/TASKS.md index 6fe0b73..eaa28b2 100644 --- a/craft_web/TASKS.md +++ b/craft_web/TASKS.md @@ -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/`. diff --git a/craft_web/src/app.js b/craft_web/src/app.js index 07236ee..2283877 100644 --- a/craft_web/src/app.js +++ b/craft_web/src/app.js @@ -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 = `
${item.discipline}${item.stage}

`; + card.innerHTML = '

'; + 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='
'; 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='
'; 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='

';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='

';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(); })(); diff --git a/craft_web/src/index.html b/craft_web/src/index.html index 95905d8..f198763 100644 --- a/craft_web/src/index.html +++ b/craft_web/src/index.html @@ -31,6 +31,16 @@
+
+ + Ingrédient personnel +
+ +
+
+ + +
+
Source de vérité

TSV, SQLite, glossaires et thèmes du livre Typst épinglé.

@@ -47,7 +57,7 @@
++8
-
◆
Ajoutez des composants depuis le catalogue

Le glisser-déposer viendra ensuite. Pour ce prototype, utilisez le bouton « Ajouter ».

+
◆
Une seule discipline par recette

Le premier composant verrouille la discipline. Retirez tous les composants pour en changer.

Aucun composant sélectionné.