tobogganSe connecter

starfleet-ui

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

169 lignes · 5946 octetsBrut · Historique
1<script lang="ts">
2 import { untrack } from 'svelte';
3 import { CORE_SHIP_ACTIONS, specFor, whyUnavailable, type ActionGroup } from '$lib/game/actions';
4 import { fixFor } from '$lib/game/errors';
5 import type { FormContext } from '$lib/game/forms';
6 import Button from '$lib/ui/Button.svelte';
7 import type { ActiveShip, ApiErrorBody, GameAction, Waypoint, WaypointKind } from '$lib/types';
8 import ActionForm from './ActionForm.svelte';
9 import { runAction } from './run';
10
11 interface Props {
12 actions: GameAction[];
13 ctx?: FormContext & { waypoints?: readonly Waypoint[] };
14 /** Ship console mode: hotkeys, previews, and greyed-out core actions with reasons. */
15 ship?: { ship: ActiveShip; here: WaypointKind | null } | null;
16 /** Ask to open a specific action's form (e.g. from a hint button). */
17 requested?: { name: string; initial?: Record<string, string>; seq: number } | null;
18 size?: 'sm' | 'md';
19 /** Called after an action succeeds for real, with the API's response data. */
20 onResult?: (action: GameAction, data: unknown) => void;
21 }
22
23 let { actions, ctx = {}, ship = null, requested = null, size = 'md', onResult }: Props = $props();
24
25 const GROUPS: ActionGroup[] = ['flight', 'trade', 'ship', 'social'];
26 const GROUP_TINT: Record<ActionGroup, string> = {
27 flight: 'border-l-cyan-400/70',
28 trade: 'border-l-amber-400/70',
29 ship: 'border-l-emerald-400/70',
30 social: 'border-l-violet-400/70'
31 };
32
33 let open = $state<{ name: string; initial: Record<string, string> } | null>(null);
34 let pending = $state<string | null>(null);
35 let confirming = $state<string | null>(null);
36 let lastError = $state<ApiErrorBody | null>(null);
37
38 const byName = $derived(new Map(actions.map((a) => [a.name, a])));
39 const openAction = $derived(open ? (byName.get(open.name) ?? null) : null);
40
41 /** Core actions that aren't on offer, with the reason, shown greyed out. */
42 const unavailable = $derived(
43 ship
44 ? CORE_SHIP_ACTIONS.filter((n) => !byName.has(n)).map((n) => ({ name: n, reason: whyUnavailable(n, ship.ship, ship.here) }))
45 : []
46 );
47
48 const grouped = $derived(
49 GROUPS.map((g) => ({ group: g, items: actions.filter((a) => specFor(a).group === g) })).filter((g) => g.items.length)
50 );
51
52 const fix = $derived.by(() => {
53 const name = lastError ? fixFor(lastError.code) : null;
54 return name ? (byName.get(name) ?? null) : null;
55 });
56
57 // React to a new request only (its seq), not to this component's own state.
58 $effect(() => {
59 const r = requested;
60 if (!r) return;
61 void r.seq;
62 untrack(() => {
63 const action = byName.get(r.name);
64 if (action) trigger(action, r.initial);
65 });
66 });
67
68 async function trigger(action: GameAction, initial: Record<string, string> = {}) {
69 lastError = null;
70 if (action.fields.length) {
71 open = open?.name === action.name && !Object.keys(initial).length ? null : { name: action.name, initial };
72 return;
73 }
74 if (specFor(action).confirm && confirming !== action.name) {
75 confirming = action.name;
76 return;
77 }
78 confirming = null;
79 pending = action.name;
80 const res = await runAction(action, undefined);
81 pending = null;
82 if (!res.ok) lastError = res.error;
83 else onResult?.(action, res.data);
84 }
85
86 function onKey(e: KeyboardEvent) {
87 if (!ship || e.ctrlKey || e.metaKey || e.altKey) return;
88 const t = e.target as HTMLElement | null;
89 if (t && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName))) return;
90 if (e.key === 'Escape') {
91 open = null;
92 confirming = null;
93 return;
94 }
95 const action = actions.find((a) => specFor(a).hotkey === e.key.toLowerCase());
96 if (action) {
97 e.preventDefault();
98 trigger(action);
99 }
100 }
101</script>
102
103<svelte:window onkeydown={onKey} />
104
105<div class="space-y-3">
106 {#if openAction}
107 {#key `${openAction.name}:${JSON.stringify(open?.initial)}`}
108 <div class="hud-panel border-cyan-400/40! p-4">
109 <ActionForm
110 action={openAction}
111 {ctx}
112 preview={!!ship}
113 initial={open?.initial}
114 onDone={(res) => {
115 onResult?.(openAction, res.data);
116 open = null;
117 }}
118 onCancel={() => (open = null)}
119 />
120 </div>
121 {/key}
122 {/if}
123
124 <div class="flex flex-wrap gap-2" role="toolbar" aria-label="Commands">
125 {#each grouped as g (g.group)}
126 {#each g.items as action (action.name)}
127 {@const spec = specFor(action)}
128 <Button
129 size={size === 'sm' ? 'sm' : 'md'}
130 variant={confirming === action.name ? 'confirm' : open?.name === action.name ? 'primary' : 'secondary'}
131 kbd={ship ? spec.hotkey : undefined}
132 busy={pending === action.name}
133 disabled={pending !== null}
134 title={spec.help}
135 class="border-l-2 {GROUP_TINT[g.group]}"
136 onclick={() => trigger(action)}
137 >
138 {confirming === action.name ? `Confirm ${spec.label.toLowerCase()}?` : spec.label}{action.fields.length ? '…' : ''}
139 </Button>
140 {/each}
141 {/each}
142 {#each unavailable as u (u.name)}
143 <span class="group relative">
144 <Button size={size === 'sm' ? 'sm' : 'md'} variant="ghost" disabled aria-describedby="why-{u.name}" class="border-slate-700/60!">
145 {specFor(u.name).label}
146 </Button>
147 {#if u.reason}
148 <span
149 id="why-{u.name}"
150 role="tooltip"
151 class="pointer-events-none absolute bottom-full left-1/2 z-20 mb-1.5 hidden w-max max-w-56 -translate-x-1/2 rounded-md border border-slate-700 bg-slate-950 px-2 py-1 text-xs text-slate-300 shadow-xl group-hover:block"
152 >
153 {u.reason}
154 </span>
155 {/if}
156 </span>
157 {/each}
158 </div>
159
160 {#if lastError}
161 <div role="alert" class="flex flex-wrap items-center gap-2 rounded-lg border border-red-500/40 bg-red-950/50 px-3 py-2 text-sm text-red-100">
162 <span class="flex-1">{lastError.message}</span>
163 {#if fix}
164 <Button size="sm" variant="primary" onclick={() => fix && trigger(fix)}>{specFor(fix).label} first</Button>
165 {/if}
166 <button onclick={() => (lastError = null)} class="text-red-300/70 hover:text-red-100" aria-label="Dismiss">✕</button>
167 </div>
168 {/if}
169</div>