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.

247 lignes · 8950 octetsBrut · Historique
1<script lang="ts">
2 import { untrack } from 'svelte';
3 import { fieldSpec, specFor } from '$lib/game/actions';
4 import { fieldFromPath } from '$lib/game/errors';
5 import { buildBody, describeOutcome, maxFor, type FormContext } from '$lib/game/forms';
6 import { buyCost, sellRevenue } from '$lib/game/trade';
7 import { toast } from '$lib/stores/toasts.svelte';
8 import Button from '$lib/ui/Button.svelte';
9 import { systemOf, type ActionField, type GameAction, type Waypoint } from '$lib/types';
10 import { canPreview, runAction, type RunResult } from './run';
11
12 interface Props {
13 action: GameAction;
14 ctx?: FormContext & { waypoints?: readonly Waypoint[] };
15 /** Offer a dry-run preview (ship actions only). */
16 preview?: boolean;
17 /** Prefilled inputs, e.g. a destination picked on the map. */
18 initial?: Record<string, string>;
19 onDone?: (result: Extract<RunResult, { ok: true }>) => void;
20 onCancel?: () => void;
21 }
22
23 let { action, ctx = {}, preview = false, initial = {}, onDone, onCancel }: Props = $props();
24
25 const spec = $derived(specFor(action));
26 const MODULES = ['mining_laser', 'cargo_pod', 'fuel_tank', 'drive'];
27
28 // Prefill once: the parent re-creates the form for each new request.
29 let values = $state<Record<string, string>>({ ...untrack(() => initial) });
30 let busy = $state<'preview' | 'run' | null>(null);
31 let confirming = $state(false);
32 let outcome = $state<string[] | null>(null);
33 let error = $state<{ message: string; field: string | null } | null>(null);
34
35 interface Choice {
36 value: string;
37 label: string;
38 }
39
40 /** Choices for a field: API options first, then what the context knows. */
41 function choices(f: ActionField): Choice[] | null {
42 const input = fieldSpec(action, f.name).input;
43 if (f.options?.length) {
44 return f.options.map((o) => ({ value: o, label: input === 'gate' ? `${systemOf(o)} (${o})` : o.replaceAll('_', ' ') }));
45 }
46 const ship = ctx.ship;
47 switch (input) {
48 case 'waypoint':
49 return (ctx.waypoints ?? [])
50 .filter((w) => w.symbol !== ship?.waypoint)
51 .map((w) => ({ value: w.symbol, label: `${w.symbol} · ${w.kind.replaceAll('_', ' ')}` }));
52 case 'good':
53 if (action.name === 'buy' && ctx.market)
54 return ctx.market.map((g) => ({ value: g.good, label: `${g.good} · ${g.buy} cr` }));
55 if (ship?.cargo.items.length)
56 return ship.cargo.items.map((i) => {
57 const price = ctx.market?.find((g) => g.good === i.good)?.sell;
58 return { value: i.good, label: `${i.good} · ${i.units} held${price ? ` · ${price} cr` : ''}` };
59 });
60 return ['iron', 'copper', 'ice', 'fuel', 'alloy'].map((g) => ({ value: g, label: g }));
61 case 'contract':
62 return (ctx.contracts ?? [])
63 .filter((c) => c.status === 'open')
64 .map((c) => ({ value: c.id, label: `${c.units - c.delivered} ${c.good} → ${c.station}` }));
65 case 'module':
66 if (action.name === 'strip' && ship) return ship.modules.map((m) => ({ value: m.module, label: m.module.replaceAll('_', ' ') }));
67 return MODULES.map((m) => ({ value: m, label: m.replaceAll('_', ' ') }));
68 default:
69 return null;
70 }
71 }
72
73 // Default each select to its first choice so a two-click flow stays two clicks.
74 $effect(() => {
75 for (const f of action.fields) {
76 if (values[f.name]) continue;
77 const first = choices(f)?.[0];
78 if (first) values[f.name] = first.value;
79 }
80 });
81
82 const max = (f: ActionField) => maxFor(action.name, f.name, ctx, values);
83
84 /** A line estimating what this will cost or earn, when we can tell. */
85 const estimate = $derived.by(() => {
86 const n = Number(values.units);
87 if (!n || !ctx.market) return null;
88 const g = ctx.market.find((m) => m.good === (action.name === 'refuel' ? 'fuel' : values.good));
89 if (!g) return null;
90 if (action.name === 'buy' || action.name === 'refuel') return `≈ ${Math.round(buyCost(g, n)).toLocaleString('en-US')} cr`;
91 if (action.name === 'sell') return `≈ +${Math.round(sellRevenue(g, n)).toLocaleString('en-US')} cr`;
92 return null;
93 });
94
95 function set(name: string, v: string) {
96 values[name] = v;
97 outcome = null;
98 confirming = false;
99 if (error?.field === name) error = null;
100 }
101
102 async function submit(dryRun: boolean) {
103 if (!dryRun && spec.confirm && !confirming) {
104 confirming = true;
105 return;
106 }
107 busy = dryRun ? 'preview' : 'run';
108 error = null;
109 const res = await runAction(action, action.fields.length ? buildBody(action.fields, values) : undefined, { dryRun });
110 busy = null;
111 confirming = false;
112 if (!res.ok) {
113 if (res.error.code === 'no_dry_run') {
114 toast(`${spec.label} can't be previewed — it's decided when you do it.`, 'info');
115 return;
116 }
117 error = { message: res.error.message, field: fieldFromPath(res.error.path) };
118 return;
119 }
120 if (dryRun) {
121 const lines = describeOutcome(ctx.ship, res.data);
122 outcome = lines.length ? lines : ['Would succeed.'];
123 } else {
124 onDone?.(res);
125 }
126 }
127
128 const inputCls =
129 'w-full rounded-md border bg-slate-950/80 px-2.5 py-1.5 text-sm text-slate-100 focus:border-cyan-400 focus:outline-none';
130</script>
131
132<form
133 class="animate-rise space-y-3"
134 onsubmit={(e) => {
135 e.preventDefault();
136 submit(false);
137 }}
138>
139 <header>
140 <h3 class="font-display text-base font-bold tracking-wide text-cyan-100">{spec.label}</h3>
141 {#if spec.help}<p class="text-xs text-slate-400">{spec.help}</p>{/if}
142 </header>
143
144 {#each action.fields as f (f.name)}
145 {@const fs = fieldSpec(action, f.name)}
146 {@const opts = choices(f)}
147 {@const hi = fs.input === 'quantity' ? (max(f) ?? fs.max ?? null) : null}
148 {@const bad = error?.field === f.name}
149 <label class="block">
150 <span class="mb-1 flex justify-between text-xs text-slate-300">
151 <span>{fs.label}{f.required ? '' : ' (optional)'}</span>
152 {#if hi !== null}<span class="text-slate-500">max {hi}</span>{/if}
153 </span>
154 {#if opts}
155 <select
156 required={f.required}
157 value={values[f.name] ?? ''}
158 onchange={(e) => set(f.name, e.currentTarget.value)}
159 aria-invalid={bad}
160 class="{inputCls} {bad ? 'border-red-500' : 'border-slate-700'}"
161 >
162 {#if !f.required}<option value="">—</option>{/if}
163 {#each opts as o (o.value)}
164 <option value={o.value}>{o.label}</option>
165 {/each}
166 </select>
167 {:else if fs.input === 'longtext'}
168 <textarea
169 required={f.required}
170 rows="3"
171 maxlength="500"
172 value={values[f.name] ?? ''}
173 oninput={(e) => set(f.name, e.currentTarget.value)}
174 aria-invalid={bad}
175 class="{inputCls} {bad ? 'border-red-500' : 'border-slate-700'}"
176 ></textarea>
177 {:else if f.type === 'integer'}
178 <div class="flex items-center gap-2">
179 {#if hi !== null && hi > 0}
180 <input
181 type="range"
182 min={fs.min ?? 1}
183 max={hi}
184 value={values[f.name] || 0}
185 oninput={(e) => set(f.name, e.currentTarget.value)}
186 class="flex-1 accent-cyan-400"
187 aria-label="{fs.label} slider"
188 />
189 {/if}
190 <input
191 type="number"
192 required={f.required}
193 min={fs.min ?? 1}
194 max={hi ?? undefined}
195 value={values[f.name] ?? ''}
196 oninput={(e) => set(f.name, e.currentTarget.value)}
197 aria-invalid={bad}
198 class="{inputCls} {hi !== null && hi > 0 ? 'w-24' : ''} {bad ? 'border-red-500' : 'border-slate-700'}"
199 />
200 {#if hi !== null && hi > 0}
201 <button type="button" onclick={() => set(f.name, String(hi))} class="text-xs text-cyan-300 hover:text-cyan-100">
202 Max
203 </button>
204 {/if}
205 </div>
206 {:else}
207 <input
208 type="text"
209 required={f.required}
210 value={values[f.name] ?? ''}
211 oninput={(e) => set(f.name, e.currentTarget.value)}
212 aria-invalid={bad}
213 class="{inputCls} {bad ? 'border-red-500' : 'border-slate-700'}"
214 />
215 {/if}
216 {#if fs.help}<span class="mt-1 block text-[11px] text-slate-500">{fs.help}</span>{/if}
217 {#if bad}<span class="mt-1 block text-xs text-red-300">{error?.message}</span>{/if}
218 </label>
219 {/each}
220
221 {#if estimate}
222 <p class="font-mono text-sm text-amber-200">{estimate}</p>
223 {/if}
224 {#if outcome}
225 <ul class="space-y-0.5 rounded-md border border-cyan-500/30 bg-cyan-950/30 px-3 py-2 text-xs text-cyan-100">
226 <li class="hud-label text-cyan-300!">Preview</li>
227 {#each outcome as line (line)}<li>{line}</li>{/each}
228 </ul>
229 {/if}
230 {#if error && !error.field}
231 <p role="alert" class="rounded-md border border-red-500/40 bg-red-950/40 px-3 py-2 text-xs text-red-200">{error.message}</p>
232 {/if}
233
234 <div class="flex items-center justify-end gap-2">
235 {#if onCancel}
236 <Button type="button" variant="ghost" size="sm" onclick={onCancel}>Cancel</Button>
237 {/if}
238 {#if preview && canPreview(action.name)}
239 <Button type="button" size="sm" busy={busy === 'preview'} disabled={busy !== null} onclick={() => submit(true)}>
240 Preview
241 </Button>
242 {/if}
243 <Button type="submit" size="sm" variant={confirming ? 'confirm' : 'primary'} busy={busy === 'run'} disabled={busy !== null}>
244 {confirming ? 'Confirm' : spec.label}
245 </Button>
246 </div>
247</form>