sokko-g/website/src/features/games/guideChecklist.js
Shinuwa 07a43ef848
All checks were successful
Validate and deploy Sokko G / validate (push) Successful in 24m18s
Validate and deploy Sokko G / deploy (push) Successful in 18s
Let a guide checklist update from its page filters without losing checks, and optionally limit the page to what the checklist contains
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 17:39:00 +01:00

194 lines
10 KiB
JavaScript

/**
* @file Reconnaît les lignes de checklist, met une checklist à jour depuis les filtres d'un guide
* et valide les associations persistantes des guides.
*
* Utilisé par : useGuideChecklist.js (page et tiroir de toolbox), useGuideChecklistStorage.js.
* Attention : la correspondance se fait par libellé normalisé (accents, casse, espaces, français ou anglais),
* jamais par identifiant : une ligne renommée dans les données du jeu n'est plus reconnue.
*/
import { aniimoLabel, filterAniimoVariants, groupAniimoVariants } from "./aniimo/utils.js";
import { getFilteredDiablo4Affixes } from "./diablo4/utils.js";
import { getFilteredMhwildsItems, getMhwildsFilterKey } from "./mhwilds/utils.js";
export const GUIDE_CHECKLIST_STORAGE_KEY = "sokkog:guide-checklists";
const GUIDES = new Set(["aniimo/aniimos", "mhwilds/monsters", "mhwilds/endemic", "diablo4/affixes"]);
export function normalizeGuideLabel(value) {
return String(value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "")
.toLocaleLowerCase("fr").replace(/œ/g, "oe").replace(/æ/g, "ae").trim().replace(/\s+/g, " ");
}
export function matchGuideChecklist(entries, data) {
const rows = Array.isArray(data?.sections) ? data.sections.flatMap((section) => section.items || []) : data?.items || [];
const byLabel = new Map();
for (const row of rows) {
const label = normalizeGuideLabel(row.label);
if (!label) continue;
if (!byLabel.has(label)) byLabel.set(label, []);
byLabel.get(label).push(row);
}
const findRows = (labels = []) => [...new Set(labels.map(normalizeGuideLabel))].flatMap((label) => byLabel.get(label) || []);
const matched = new Set();
const completed = new Set();
const rowIds = new Map();
for (const entry of entries) {
const specific = findRows(entry.labels);
const matches = specific.length ? specific : findRows(entry.fallbackLabels);
if (!matches.length) continue;
matched.add(entry.key);
rowIds.set(entry.key, [...new Set(matches.map((row) => row.id).filter(Boolean))]);
if (matches.every((row) => Number(row.qtyCurrent || 0) >= Math.max(1, Number(row.qtyTarget || 1)))) completed.add(entry.key);
}
return { count: matched.size, completed, rowIds };
}
export function toggleGuideChecklistRows(data, ids, completed) {
const targetIds = new Set(ids || []);
if (!targetIds.size) return data;
const update = (items = []) => items.map((item) => targetIds.has(item.id)
? { ...item, qtyCurrent: completed ? Math.max(1, Number(item.qtyTarget || 1)) : 0 }
: item);
return {
...data,
...(Array.isArray(data?.items) ? { items: update(data.items) } : {}),
...(Array.isArray(data?.sections) ? { sections: data.sections.map((section) => ({ ...section, items: update(section.items) })) } : {})
};
}
/**
* Associations `{ toolboxId, moduleId, hideCompleted, onlyListed }` encore valides, indexées par guide ;
* écarte les guides inconnus, les toolboxes qui ne sont plus liées au jeu et les modules disparus.
*/
export function validGuideAssociations(value, toolboxes, links) {
return Object.fromEntries(Object.entries(value || {}).filter(([guideId, association]) => {
if (!GUIDES.has(guideId) || !association || typeof association !== "object") return false;
const toolbox = toolboxes.find((item) => item.id === association.toolboxId && item.id === links[guideId.split("/")[0]]);
return toolbox?.modules.some((module) => module.id === association.moduleId && module.type === "checklist");
}).map(([key, association]) => [key, {
toolboxId: association.toolboxId, moduleId: association.moduleId, hideCompleted: association.hideCompleted === true,
onlyListed: association.onlyListed === true
}]));
}
export function aniimoChecklistEntries(variants, translations, englishTranslations) {
return variants.map((variant) => {
const names = [translations[variant.name], englishTranslations[variant.name]].filter(Boolean);
const forms = [translations[variant.form], englishTranslations[variant.form]].filter(Boolean);
return { key: variant.key, labels: names.flatMap((name) => forms.map((form) => `${name} — ${form}`)), fallbackLabels: names };
});
}
export function getGuideChecklistEntries(guideId, { aniimo, mhwilds, diablo4 }) {
if (!GUIDES.has(guideId)) return null;
if (guideId === "aniimo/aniimos") return aniimo.loaded ? aniimoChecklistEntries(aniimo.variants, aniimo.translations, aniimo.englishTranslations) : null;
if (guideId === "diablo4/affixes") return diablo4.loaded ? diablo4.affixes.map((affix) => ({ key: affix.id, labels: [affix.label] })) : null;
if (!mhwilds.loaded) return null;
return (guideId === "mhwilds/monsters" ? mhwilds.monsters : mhwilds.endemic).map((item) => ({
key: item.name, labels: [mhwilds.translations[item.name] || item.name.replace(/_/g, " ")]
}));
}
/**
* Éléments d'un guide qui passent les filtres courants, avant le masquage des éléments cochés.
* Renvoie null quand le guide n'est pas compatible ou que ses données ne sont pas encore chargées.
*/
export function filterGuideItems(guideId, { aniimo, mhwilds, diablo4, filters, t }) {
if (!GUIDES.has(guideId)) return null;
if (guideId === "aniimo/aniimos") return aniimo.loaded ? filterAniimoVariants(aniimo.variants, filters.aniimo) : null;
if (guideId === "diablo4/affixes") return diablo4.loaded ? getFilteredDiablo4Affixes({ affixes: diablo4.affixes, filters: filters.diablo4 }) : null;
if (!mhwilds.loaded) return null;
const category = guideId.split("/")[1];
return getFilteredMhwildsItems({ category, filterKey: getMhwildsFilterKey(category, mhwilds), mhwilds, filters, t });
}
/**
* Lignes de checklist `{ key, label, labels }` produites par des éléments de guide, dans l'ordre de la page.
* `label` nomme une nouvelle ligne ; `labels` liste les libellés (français, anglais) qui reconnaissent une ligne existante.
* Aniimo suit le regroupement de la page : une ligne par espèce, ou une par variante « Nom — Forme ».
*/
export function toGuideChecklistResults(guideId, items, { aniimo, filters, t }) {
if (guideId === "aniimo/aniimos") {
const french = (key) => aniimoLabel(aniimo.translations, key);
const english = (key) => aniimo.englishTranslations?.[key] || "";
if (filters.aniimo.grouped) {
return groupAniimoVariants(items).map(([variant]) => ({
key: variant.aniimoUid, label: french(variant.name), labels: [french(variant.name), english(variant.name)].filter(Boolean)
}));
}
return items.map((variant) => {
const label = `${french(variant.name)} — ${french(variant.form)}`;
const englishLabel = english(variant.name) && english(variant.form) ? `${english(variant.name)} — ${english(variant.form)}` : "";
return { key: variant.key, label, labels: [label, englishLabel].filter(Boolean) };
});
}
if (guideId === "diablo4/affixes") return items.map((affix) => ({ key: affix.id, label: affix.label, labels: [affix.label] }));
return items.map((item) => ({ key: item.name, label: t(item.name, { capitalize: true }), labels: [t(item.name)] }));
}
function isChecklistRowComplete(row) {
return Number(row.qtyCurrent || 0) >= Math.max(1, Number(row.qtyTarget || 1));
}
/**
* Fusionne les résultats d'une page de guide dans une checklist, sans modifier `data`.
* Une ligne reconnue garde son identifiant, sa cible et sa progression ; un résultat inconnu devient une ligne non cochée,
* insérée après la ligne du résultat précédent pour suivre l'ordre de la page. Les lignes absentes des résultats
* restent, sauf avec `removeMissing`. Renvoie `{ data, summary }`, où `summary` compte les lignes ajoutées,
* conservées (`kept`, dont `completed` cochées), absentes (`missing`, dont `missingCompleted` cochées) et retirées.
*/
export function mergeGuideChecklistResults(data, results, { removeMissing = false, uid }) {
const sourceSections = Array.isArray(data?.sections) && data.sections.length
? data.sections
: data?.items?.length ? [{ id: uid("section"), title: "", items: data.items }] : [];
const sections = sourceSections.map((section) => ({ ...section, items: [...(section.items || [])] }));
const byLabel = new Map();
const register = (label, row) => {
const key = normalizeGuideLabel(label);
if (!key) return;
if (!byLabel.has(key)) byLabel.set(key, []);
byLabel.get(key).push(row);
};
sections.forEach((section) => section.items.forEach((item) => register(item.label, { section, item })));
const matched = new Set();
const added = new Set();
let anchor = null;
for (const result of results) {
const labels = [...new Set((result.labels?.length ? result.labels : [result.label]).map(normalizeGuideLabel))];
const rows = labels.flatMap((label) => byLabel.get(label) || []);
if (rows.length) {
rows.forEach((row) => { if (!added.has(row.item)) matched.add(row.item); });
anchor = rows.at(-1);
continue;
}
const label = String(result.label || "").trim();
if (!label) continue;
const item = { id: uid("item"), label, qtyTarget: 1, qtyCurrent: 0 };
if (!sections.length) sections.push({ id: uid("section"), title: "", items: [] });
const section = anchor?.section || sections[0];
section.items.splice(anchor ? section.items.indexOf(anchor.item) + 1 : 0, 0, item);
added.add(item);
anchor = { section, item };
labels.forEach((key) => register(key, anchor));
}
const rows = sections.flatMap((section) => section.items).filter((item) => !added.has(item));
const missing = rows.filter((item) => !matched.has(item));
const nextSections = sections
.map((section) => removeMissing ? { ...section, items: section.items.filter((item) => added.has(item) || matched.has(item)) } : section)
.filter((section) => section.items.length);
const next = { ...data, sections: nextSections };
delete next.items;
return {
data: next,
summary: {
added: added.size,
kept: matched.size,
completed: rows.filter((item) => matched.has(item) && isChecklistRowComplete(item)).length,
missing: missing.length,
missingCompleted: missing.filter(isChecklistRowComplete).length,
removed: removeMissing ? missing.length : 0
}
};
}