sokko-g/website/src/features/cards/admin/ExpeditionSettings.jsx
Shinuwa 22b397ebfa Document Sokko G's architecture and folders, and move JavaScript file headers to JSDoc @file blocks
Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md
(setup and step-by-step recipes) and a README in each main folder, with an
index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to
JSDoc @file blocks, define a three-level header template in website/AGENTS.md
and check the header in tests/file-headers.test.mjs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:42:13 +01:00

125 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @file Règle les Expéditions depuis Administration › Guilde › Expéditions : en-tête (ouverture, suivi du
* jour, expéditions en route), puis les réglages rangés en onglets thématiques, avec un seul brouillon
* et une barre d'application commune.
*/
import { useState } from "react";
import { Tabs } from "../../../components/Tabs.jsx";
import { ConfirmModal } from "../../../components/ToolboxModals.jsx";
import { cancelExpedition, updateExpeditionSettings } from "../cardsApi.js";
import { DATE_FORMATTER } from "./adminFormat.js";
import { EXPEDITION_OPEN_PATH, EXPEDITION_SETTING_GROUPS, EXPEDITION_SETTING_THEMES, expeditionSettingLabel, formatSettingValue } from "./expeditionSettingFields.js";
import { GuildQuestHeader } from "./GuildQuestHeader.jsx";
import { guildQuest, questFigures, questStatus } from "./guildQuests.js";
import { ApplyBar, DefaultHint, NumberInput, SettingsGroup, SettingsSection } from "./SettingFields.jsx";
import { readPath, same, toDraft, useSettingsDraft, writePath } from "./settingsDraft.js";
const DESTINATION_WEIGHT = { min: 0, max: 100 };
// Tous les réglages modifiables ici : ceux des groupes rangés dans un onglet (bornes du schéma) et ceux de chaque destination.
// L'ouverture (bandeau d'état) et le prix d'un Éclat (Boutique) se règlent ailleurs.
function editableFields(schema, destinations) {
const fromGroups = EXPEDITION_SETTING_GROUPS.filter((group) => PANEL_THEME.has(group.id)).flatMap((group) => group.fields
.map((field) => ({ ...field, ...schema.find((item) => item.path === field.path), panel: group.id })));
const fromDestinations = destinations.flatMap((destination) => [
{ path: `destinations.${destination.id}.active`, kind: "bool", panel: "destinations" },
{ path: `destinations.${destination.id}.weight`, kind: "int", ...DESTINATION_WEIGHT, panel: "destinations" }
]);
return [...fromGroups, ...fromDestinations];
}
const PANEL_THEME = new Map(EXPEDITION_SETTING_THEMES.flatMap((theme) => theme.panels.map((panel) => [panel, theme.id])));
// Destinations : proposées ou non, et poids dans le tirage du jour, une ligne alignée par destination. Leurs textes vivent dans le
// fichier du serveur.
function DestinationSettings({ destinations, draft, settings, defaults, busy }) {
return <SettingsSection id="destinations" title="Destinations" help="Une destination retirée n’est plus tirée ; le poids règle sa fréquence parmi les destinations proposées. Les destinations cachées ne sont jamais tirées. Le changement vaut pour les prochains tirages : celles déjà proposées aujourd’hui restent jusqu’à minuit.">
<ul className="nebula-admin-expedition-destinations">{destinations.map((destination) => {
const activePath = `destinations.${destination.id}.active`;
const weightField = { path: `destinations.${destination.id}.weight`, ...DESTINATION_WEIGHT };
const active = draft.raw(activePath);
const weight = draft.raw(weightField.path);
const changed = !same(draft.value(activePath), readPath(settings, activePath)) || !same(draft.value(weightField.path), readPath(settings, weightField.path));
return <li key={destination.id} className="nds-list-row" data-changed={changed || undefined} data-active={active || undefined}>
<button className="nds-switch" type="button" aria-pressed={active} aria-label={`${destination.name} proposée`} disabled={busy} onClick={() => draft.set(activePath, !active)}><i aria-hidden="true" /></button>
<strong>{destination.name}</strong>
{destination.hidden ? <span className="nds-badge" data-variant="neutral">Cachée</span> : <span />}
<label><span>Poids</span><NumberInput field={weightField} value={weight} label={`Poids de ${destination.name}`} busy={busy} onChange={(next) => draft.set(weightField.path, next)} /></label>
<DefaultHint field={weightField} value={draft.value(weightField.path)} defaults={defaults} busy={busy} onReset={() => draft.set(weightField.path, toDraft(readPath(defaults, weightField.path)))} />
</li>;
})}</ul>
</SettingsSection>;
}
// Expéditions en route, chacune annulable après confirmation : sous les chiffres de l'en-tête.
function RunningExpeditions({ list, destinations, busy, onCancel }) {
const [confirming, setConfirming] = useState(null);
const name = (id) => destinations.find((destination) => destination.id === id)?.name || id;
if (!list.length) return null;
return <>
<ul className="nebula-admin-expedition-running" aria-label="Expéditions en route">{list.map((expedition) => <li key={expedition.id} className="nds-list-row">
<strong>{name(expedition.destinationId)} · {"★".repeat(expedition.stars)}</strong>
<span>{expedition.creatorName} · retour le {DATE_FORMATTER.format(expedition.returnsAt)}</span>
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={() => setConfirming(expedition)}>Annuler</button>
</li>)}</ul>
{confirming && <ConfirmModal
title="Annuler cette expédition ?"
message={`L’expédition vers ${name(confirming.destinationId)} de ${confirming.creatorName} s’arrête : les cartes sont libérées, sans butin.`}
confirmLabel="Annuler l’expédition"
onClose={async (confirmed) => {
const target = confirming;
setConfirming(null);
if (confirmed) await onCancel(target.id);
}}
/>}
</>;
}
export function ExpeditionSettings({ dashboard, busy, runMutation, refreshDashboard }) {
const { settings, defaults, schema, destinations } = dashboard.expeditionSettings;
const [themeId, setThemeId] = useState(EXPEDITION_SETTING_THEMES[0].id);
const fields = editableFields(schema, destinations);
const draft = useSettingsDraft(settings, fields);
const save = async (apply) => {
const next = structuredClone(settings);
apply(next);
const saved = await runMutation(() => updateExpeditionSettings(next));
if (saved) await refreshDashboard();
return saved;
};
const apply = async () => {
if (await save((next) => draft.changes.forEach((field) => writePath(next, field.path, draft.value(field.path))))) draft.reset();
};
const cancel = async (id) => {
if (await runMutation(() => cancelExpedition(id))) await refreshDashboard();
};
const pendingIn = (theme) => [...draft.changes, ...draft.invalid].filter((field) => PANEL_THEME.get(field.panel) === theme.id).length;
const theme = EXPEDITION_SETTING_THEMES.find((item) => item.id === themeId);
const props = { draft, settings, defaults, busy };
return <div className="nebula-admin-expeditions">
<GuildQuestHeader quest={guildQuest("expeditions")} status={questStatus("expeditions", dashboard)} figures={questFigures("expeditions", dashboard)} busy={busy} toggle={{
open: settings[EXPEDITION_OPEN_PATH],
openLabel: "Ouvrir les Expéditions",
closeLabel: "Fermer les Expéditions",
openMessage: "La tuile des Expéditions apparaît dans la Guilde et les joueurs peuvent partir dès maintenant.",
closeMessage: "Plus aucun départ ni inscription à un groupe. Les expéditions en route reviennent normalement et leur butin reste à récupérer.",
onToggle: (open) => save((next) => { next[EXPEDITION_OPEN_PATH] = open; })
}}>
<RunningExpeditions list={dashboard.expeditionsToday.runningList} destinations={destinations} busy={busy} onCancel={cancel} />
</GuildQuestHeader>
<Tabs
className="nebula-admin-expedition-themes"
tabs={EXPEDITION_SETTING_THEMES.map((item) => {
const pending = pendingIn(item);
return { id: item.id, label: pending ? `${item.title} (${pending})` : item.title };
})}
activeTab={themeId}
onChange={setThemeId}
/>
{theme.panels.map((panel) => (panel === "destinations"
? <DestinationSettings key={panel} destinations={destinations} {...props} />
: <SettingsGroup key={panel} group={EXPEDITION_SETTING_GROUPS.find((group) => group.id === panel)} fields={fields.filter((field) => field.panel === panel)} {...props} />))}
<ApplyBar draft={draft} settings={settings} busy={busy} onApply={apply} message="Les nouveaux réglages s’appliquent aux prochains départs. Les expéditions en route gardent ceux de leur départ." labelOf={(path) => expeditionSettingLabel(path, destinations)} formatValue={formatSettingValue} />
</div>;
}