feat: build craft workshop prototype
This commit is contained in:
parent
165da4d20a
commit
da4463aba8
|
|
@ -3,4 +3,5 @@ __pycache__/
|
|||
*.pyc
|
||||
build/
|
||||
build-*/
|
||||
/craft_web/build/
|
||||
/local_exports/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
(() => {
|
||||
'use strict';
|
||||
const data = window.RAVENOUS_CRAFT_CATALOG || { entries: [], themes: [] };
|
||||
const $ = id => document.getElementById(id);
|
||||
const state = { shown: 30, selected: [] };
|
||||
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 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 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 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();
|
||||
$('stage').replaceChildren(new Option('Toutes les étapes', ''), ...stages.map(value => new Option(value, value)));
|
||||
if (stages.includes(current)) $('stage').value = current;
|
||||
}
|
||||
function renderCards() {
|
||||
const entries = filtered();
|
||||
$('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 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.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'; });
|
||||
return card;
|
||||
}));
|
||||
$('more').hidden = entries.length <= state.shown;
|
||||
}
|
||||
function renderSelection() {
|
||||
const box = $('selection'); box.replaceChildren();
|
||||
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); });
|
||||
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).`;
|
||||
}
|
||||
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();
|
||||
}
|
||||
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);});
|
||||
}
|
||||
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');
|
||||
['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);
|
||||
['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();
|
||||
})();
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
<!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>Atelier Ravenous</title>
|
||||
<link rel="stylesheet" href="styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<a class="brand" href="#catalogue" aria-label="Atelier Ravenous, accueil"><span class="brand-mark">R</span><span><b>Atelier Ravenous</b><small>Composer · calculer · partager</small></span></a>
|
||||
<nav aria-label="Navigation principale">
|
||||
<a href="#catalogue">Catalogue</a><a href="#atelier">Atelier</a><a href="#bibliotheque">Recettes</a>
|
||||
</nav>
|
||||
<label class="theme-picker">Thème<select id="theme">{{THEME_OPTIONS}}</select></label>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section class="hero" id="catalogue">
|
||||
<div><p class="eyebrow">Données du livre · {{CATALOG_HASH}}</p><h1>L'artisanat, sans feuille volante.</h1><p>Explorez toutes les ressources Ravenous, assemblez une recette et préparez son export Roll20 ou papier.</p></div>
|
||||
<div class="hero-stats"><div><strong id="catalog-count">—</strong><span>éléments</span></div><div><strong>5</strong><span>disciplines</span></div><div><strong>100%</strong><span>local</span></div></div>
|
||||
</section>
|
||||
|
||||
<section class="workspace">
|
||||
<aside class="filters" aria-label="Filtres du catalogue">
|
||||
<div class="section-heading"><span>01</span><div><h2>Explorer</h2><p>Affinez la matière première.</p></div></div>
|
||||
<label>Recherche<input id="search" type="search" placeholder="Nom, effet, élément…"></label>
|
||||
<label>Discipline<select id="discipline"><option value="">Toutes</option><option>Alchimie</option><option>Brasserie</option><option>Forge</option><option>Restauration</option><option>Pièges</option></select></label>
|
||||
<label>Étape<select id="stage"><option value="">Toutes les étapes</option></select></label>
|
||||
<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>
|
||||
<div class="source-note"><b>Source de vérité</b><p>TSV, SQLite, glossaires et thèmes du livre Typst épinglé.</p></div>
|
||||
</aside>
|
||||
|
||||
<section class="catalog-panel">
|
||||
<div class="catalog-toolbar"><div class="discipline-tabs" id="discipline-tabs"><button class="active" data-value="">Tout</button><button data-value="Alchimie">Alchimie</button><button data-value="Brasserie">Brasserie</button><button data-value="Forge">Forge</button><button data-value="Restauration">Cuisine</button><button data-value="Pièges">Pièges</button></div><label>Trier<select id="sort"><option value="name">Nom</option><option value="tier">Tier</option><option value="difficulty">Difficulté</option><option value="toxicity">Toxicité</option></select></label></div>
|
||||
<div id="cards" class="cards"></div>
|
||||
<button id="more" class="more">Afficher davantage</button>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section class="composer" id="atelier">
|
||||
<div class="section-heading light"><span>02</span><div><h2>Atelier de recette</h2><p>Prototype interactif : les sélections sont déjà calculées en direct.</p></div></div>
|
||||
<div class="composer-grid">
|
||||
<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 id="selection" class="selection"><p class="empty">Aucun composant sélectionné.</p></div>
|
||||
</div>
|
||||
<aside class="recipe-summary">
|
||||
<p class="eyebrow">Aperçu final</p><h3 id="summary-name">Prototype de chasse</h3><div class="summary-metrics"><div><span>Tier</span><strong id="sum-tier">0</strong></div><div><span>Coût</span><strong id="sum-cost">0★</strong></div><div><span>Difficulté</span><strong id="sum-difficulty">0★</strong></div><div><span>Toxicité</span><strong id="sum-toxicity">0★</strong></div></div>
|
||||
<div id="validity" class="validity good"><b>Recette prête</b><span>Ajoutez des composants pour commencer.</span></div>
|
||||
<div class="export-actions"><button id="save">Sauvegarder</button><button id="export-json" class="secondary">Export Roll20</button><button class="quiet" disabled title="Prévu dans la prochaine itération">QR bientôt</button></div>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="library" id="bibliotheque">
|
||||
<div class="section-heading"><span>03</span><div><h2>Bibliothèque locale</h2><p>Vos brouillons restent dans ce navigateur.</p></div></div>
|
||||
<div id="saved-recipes" class="saved-recipes"><p class="empty">Aucune recette sauvegardée pour le moment.</p></div>
|
||||
</section>
|
||||
</main>
|
||||
<footer><span>Atelier Ravenous · preuve de concept</span><span>Aucun compte · aucune télémétrie · aucune donnée envoyée</span></footer>
|
||||
<noscript>Cette application statique nécessite JavaScript pour filtrer le catalogue et composer les recettes.</noscript>
|
||||
<script src="catalog.js"></script><script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,32 @@
|
|||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
class CraftSiteTests(unittest.TestCase):
|
||||
def test_build_is_static_complete_and_deterministic(self):
|
||||
with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
|
||||
for target in (first, second):
|
||||
subprocess.run(["python", "craft_web/tools/build.py", "--output", target], cwd=ROOT, check=True)
|
||||
one, two = Path(first), Path(second)
|
||||
self.assertEqual({p.name for p in one.iterdir()},
|
||||
{"index.html", "styles.css", "app.js", "catalog.js", "build-info.json"})
|
||||
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(set(info["disciplines"]), {"Alchimie", "Brasserie", "Forge", "Pièges", "Restauration"})
|
||||
self.assertGreater(info["entries"], 400)
|
||||
html = (one / "index.html").read_text(encoding="utf-8")
|
||||
self.assertNotIn("{{", html)
|
||||
self.assertIn("catalog.js", html)
|
||||
for path in one.iterdir():
|
||||
if path.suffix in {".html", ".css", ".js"}:
|
||||
content = path.read_text(encoding="utf-8")
|
||||
self.assertNotIn("http://", content)
|
||||
self.assertNotIn("https://", content)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,149 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Build the dependency-free Ravenous Craft Workshop static site."""
|
||||
import argparse
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
WEB = ROOT / "craft_web"
|
||||
SRC = WEB / "src"
|
||||
CRAFT = ROOT / "ravenous_typst/data/src/craft"
|
||||
WEAPONS = ROOT / "ravenous_typst/data/src/db/weapons.db"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.build import read_glossary_labels, read_theme_palettes, translate_typst # noqa: E402
|
||||
|
||||
TABLES = {
|
||||
"alchemy_solvants.tsv": ("Alchimie", "Solvants"),
|
||||
"alchemy_reagents.tsv": ("Alchimie", "Réagents"),
|
||||
"alchemy_transmutations.tsv": ("Alchimie", "Transmutations"),
|
||||
"brewry_ferments.tsv": ("Brasserie", "Ferments"),
|
||||
"brewry_methods.tsv": ("Brasserie", "Méthodes"),
|
||||
"brewry_main_effects.tsv": ("Brasserie", "Effets principaux"),
|
||||
"brewry_secondary_effects.tsv": ("Brasserie", "Effets secondaires"),
|
||||
"brewry_finishing.tsv": ("Brasserie", "Finitions"),
|
||||
"forge_materials.tsv": ("Forge", "Matériaux"),
|
||||
"forge_finishing.tsv": ("Forge", "Finitions"),
|
||||
"restoration_main.tsv": ("Restauration", "Principaux"),
|
||||
"restoration_sides.tsv": ("Restauration", "Accompagnements"),
|
||||
"restoration_seasoning.tsv": ("Restauration", "Assaisonnements"),
|
||||
"traps.tsv": ("Pièges", "Pièges"),
|
||||
}
|
||||
|
||||
def slug(value: str) -> str:
|
||||
plain = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode().lower()
|
||||
return re.sub(r"[^a-z0-9]+", "-", plain).strip("-")
|
||||
|
||||
def number(value: str) -> int | float | None:
|
||||
match = re.fullmatch(r"\s*#(?:dd|tox|wine|time)lvl\(\s*(-?\d+(?:\.\d+)?)\s*(?:,[^)]*)?\)\s*", value)
|
||||
raw = match.group(1) if match else value.strip()
|
||||
if not re.fullmatch(r"-?\d+(?:\.\d+)?", raw):
|
||||
return None
|
||||
return float(raw) if "." in raw else int(raw)
|
||||
|
||||
def metric(headers: list[str], row: list[str], token: str) -> int | float | None:
|
||||
for index, header in enumerate(headers):
|
||||
if token in header.lower() and index < len(row):
|
||||
return number(row[index])
|
||||
return None
|
||||
|
||||
def catalog() -> list[dict]:
|
||||
glossary = read_glossary_labels()
|
||||
entries = []
|
||||
for filename, (discipline, stage) in TABLES.items():
|
||||
path = CRAFT / filename
|
||||
with path.open(encoding="utf-8", newline="") as stream:
|
||||
rows = list(csv.reader(stream, delimiter="\t"))
|
||||
headers = rows[0]
|
||||
for index, row in enumerate(rows[1:], 1):
|
||||
row += [""] * (len(headers) - len(row))
|
||||
name = row[0].strip()
|
||||
raw = {headers[i]: row[i] for i in range(len(headers)) if row[i].strip()}
|
||||
display = {translate_typst(key, glossary): translate_typst(value, glossary)
|
||||
for key, value in raw.items()}
|
||||
entries.append({
|
||||
"id": f"{slug(discipline)}:{slug(stage)}:{slug(name)}",
|
||||
"discipline": discipline, "stage": stage, "name": name,
|
||||
"tier": metric(headers, row, "tier"), "cost": metric(headers, row, "cst"),
|
||||
"difficulty": metric(headers, row, "lvl"), "toxicity": metric(headers, row, "tox"),
|
||||
"finishing": metric(headers, row, "end"), "source": f"craft/{filename}:{index + 1}",
|
||||
"fields": display,
|
||||
})
|
||||
if WEAPONS.is_file():
|
||||
with sqlite3.connect(f"file:{WEAPONS}?mode=ro", uri=True) as db:
|
||||
db.row_factory = sqlite3.Row
|
||||
for row in db.execute("SELECT * FROM Equipements ORDER BY id"):
|
||||
item = dict(row)
|
||||
name = " ".join(filter(None, [str(item.get("name") or ""), str(item.get("adjective") or "")])).strip()
|
||||
entries.append({
|
||||
"id": f"forge:bases:{item['id']}", "discipline": "Forge", "stage": "Bases",
|
||||
"name": name, "tier": item.get("tier"), "cost": item.get("cost"),
|
||||
"difficulty": item.get("difficulty"), "toxicity": None, "finishing": None,
|
||||
"source": f"db/weapons.db:Equipements:{item['id']}",
|
||||
"fields": {key.replace("_", " ").title(): str(value) for key, value in item.items()
|
||||
if value not in (None, "", 0, "0")},
|
||||
})
|
||||
return entries
|
||||
|
||||
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]:
|
||||
entries = catalog()
|
||||
palettes = read_theme_palettes()
|
||||
payload = {"version": 1, "entries": entries, "themes": list(palettes)}
|
||||
packed = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
digest = hashlib.sha256(packed.encode()).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_CRAFT_CATALOG=" + packed + ";\n"
|
||||
files["build-info.json"] = json.dumps({"catalog_hash": digest, "entries": len(entries),
|
||||
"disciplines": sorted({item["discipline"] for item in entries}), "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("Craft website files are stale: " + ", ".join(stale))
|
||||
print(f"Craft 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 craft website: {len(files)} files, {len(catalog())} catalog entries.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue