54 lines
2.3 KiB
TypeScript
54 lines
2.3 KiB
TypeScript
'use client';
|
|
|
|
import { useCallback, useEffect, useState } from 'react';
|
|
import type { StateSnapshot } from '@/lib/game/state';
|
|
|
|
// ISS-021 (v0.20.0) — shared action runner for the side panes (extracted verbatim from
|
|
// RightPane.runAction when the On board section moved to LeftPane). POSTs an action endpoint;
|
|
// every success returns the FULL post-action snapshot (v0.8.0 convention), pushed into the
|
|
// shared shell state immediately via applySnapshot so the UI updates without waiting for the
|
|
// next poll tick. A non-2xx {error} body becomes the pane's inline error AND is mirrored to
|
|
// the shell as a bottom-right toast via onError (ISS-008 — both surfaces by design). Buttons
|
|
// are disabled while a request is in flight, so at most one action runs per pane at a time.
|
|
export function useGameAction(
|
|
state: StateSnapshot | null,
|
|
applySnapshot: (snapshot: StateSnapshot) => void,
|
|
onError?: (message: string) => void,
|
|
): { runAction: (path: string, body?: unknown) => Promise<void>; busy: boolean; actionError: string | null } {
|
|
const [busy, setBusy] = useState(false);
|
|
// Inline error from a failed action — auto-clears on the next successful poll (the shell's
|
|
// snapshot prop changes every tick) or the next successful action.
|
|
const [actionError, setActionError] = useState<string | null>(null);
|
|
useEffect(() => {
|
|
if (state !== null) setActionError(null);
|
|
}, [state]);
|
|
|
|
const runAction = useCallback(
|
|
async (path: string, body?: unknown) => {
|
|
if (busy) return;
|
|
setBusy(true);
|
|
try {
|
|
const res = await fetch(path, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
cache: 'no-store',
|
|
});
|
|
const data = (await res.json()) as StateSnapshot & { error?: string };
|
|
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
setActionError(null);
|
|
applySnapshot(data);
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
setActionError(message); // inline pane error stays…
|
|
onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008)
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
},
|
|
[applySnapshot, busy, onError],
|
|
);
|
|
|
|
return { runAction, busy, actionError };
|
|
}
|