dropdown fixes

This commit is contained in:
makearmy 2025-09-27 09:21:08 -04:00
parent 7cc6764847
commit f10dc5148f

View file

@ -6,14 +6,14 @@ import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
function handleAuthError(err: any): boolean { function handleAuthError(err: any): boolean {
const status = (err as any)?.status; const status = (err as any)?.status;
const code = (err as any)?.code; const code = (err as any)?.code;
if (status === 401 || code === "TOKEN_EXPIRED") { if (status === 401 || code === "TOKEN_EXPIRED") {
const next = encodeURIComponent(window.location.pathname + window.location.search); const next = encodeURIComponent(window.location.pathname + window.location.search);
window.location.assign(`/auth/sign-in?next=${next}`); window.location.assign(`/auth/sign-in?next=${next}`);
return true; return true;
} }
return false; return false;
} }
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
@ -47,40 +47,43 @@ type RigRow = {
id: number; id: number;
name: string; name: string;
rig_type: number | string | null; rig_type: number | string | null;
rig_type_name?: string; // convenience when our API includes name rig_type_name?: string;
}; };
// ───────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────
// Helpers // Helpers
// ───────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────
const RIG_TARGET_MAP: Record<string, string> = {
fiber: "settings_fiber",
uv: "settings_uv",
co2_galvo: "settings_co2gal",
co2_gantry: "settings_co2gan",
};
// Builder rig_type -> settings form target expected by options API // Builder rig_type -> settings form target expected by options API
const SETTINGS_TARGET_MAP: Record<string, string> = { const SETTINGS_TARGET_MAP: Record<string, string> = {
fiber: "settings_fiber", fiber: "settings_fiber",
co2_gantry: "settings_co2gan", co2_gantry: "settings_co2gan",
co2_galvo: "settings_co2gal", co2_galvo: "settings_co2gal",
uv: "settings_uv", uv: "settings_uv",
}; };
async function apiJson<T>(url: string, init?: RequestInit): Promise<T> { async function apiJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, { const res = await fetch(url, {
...init, ...init,
headers: { "Content-Type": "application/json", ...(init?.headers || {}) }, headers: { "Content-Type": "application/json", ...(init?.headers || {}) },
cache: "no-store", cache: "no-store",
credentials: "include", credentials: "include",
}); });
if (!res.ok) { const txt = await res.text().catch(() => "");
const txt = await res.text(); if (res.ok) {
throw new Error(txt || res.statusText); try { return JSON.parse(txt) as T; } catch { return undefined as T; }
} }
return res.json() as Promise<T>; // try to unwrap nested error format
let body: any = undefined;
try { body = JSON.parse(txt); } catch {}
if (body && typeof body.error === "string") {
try { body = JSON.parse(body.error); } catch {}
}
const err: any = new Error(`HTTP ${res.status} for ${url}`);
err.status = res.status;
err.code = body?.errors?.[0]?.extensions?.code || body?.code;
err.body = body ?? txt;
throw err;
} }
const schema = z.object({ const schema = z.object({
@ -88,7 +91,6 @@ const schema = z.object({
rig_type: z.string().min(1, "Pick a rig type"), rig_type: z.string().min(1, "Pick a rig type"),
laser_source: z.string().optional().nullable(), laser_source: z.string().optional().nullable(),
laser_software: z.string().optional().nullable(), laser_software: z.string().optional().nullable(),
// exactly one of focus OR scan (by rig type). We let the form send nulls.
laser_focus_lens: z.string().optional().nullable(), laser_focus_lens: z.string().optional().nullable(),
laser_scan_lens: z.string().optional().nullable(), laser_scan_lens: z.string().optional().nullable(),
laser_scan_lens_apt: z.string().optional().nullable(), laser_scan_lens_apt: z.string().optional().nullable(),
@ -112,6 +114,8 @@ export default function RigBuilderClient() {
// Options that depend on rig type // Options that depend on rig type
const [sourceOpts, setSourceOpts] = useState<Option[]>([]); const [sourceOpts, setSourceOpts] = useState<Option[]>([]);
const [softwareOpts, setSoftwareOpts] = useState<Option[]>([]); const [softwareOpts, setSoftwareOpts] = useState<Option[]>([]);
const [scanLensOpts, setScanLensOpts] = useState<Option[]>([]);
const [focusLensOpts, setFocusLensOpts] = useState<Option[]>([]);
// Load laser software list once (independent of rig type) // Load laser software list once (independent of rig type)
useEffect(() => { useEffect(() => {
@ -124,14 +128,13 @@ export default function RigBuilderClient() {
setSoftwareOpts(sw); setSoftwareOpts(sw);
} catch (e: any) { } catch (e: any) {
if (!handleAuthError(e)) { if (!handleAuthError(e)) {
console.error('[laser_software] load failed:', e); console.error("[laser_software] load failed:", e);
setSoftwareOpts([]); setSoftwareOpts([]);
} }
} }
})(); })();
}, []); }, []);
// Form // Form
const { const {
register, register,
@ -156,10 +159,8 @@ export default function RigBuilderClient() {
}); });
const rigTypeVal = watch("rig_type"); const rigTypeVal = watch("rig_type");
const rigTarget = RIG_TARGET_MAP[rigTypeVal ?? ""] || ""; const settingsTarget = SETTINGS_TARGET_MAP[rigTypeVal ?? ""] ?? "";
const isGantry = rigTypeVal === "co2_gantry";
const settingsTarget = SETTINGS_TARGET_MAP[rigTypeVal ?? ""] ?? "";const isGantry = rigTypeVal === "co2_gantry";
const isScan = rigTypeVal === "fiber" || rigTypeVal === "uv" || rigTypeVal === "co2_galvo"; const isScan = rigTypeVal === "fiber" || rigTypeVal === "uv" || rigTypeVal === "co2_galvo";
// Initial loads // Initial loads
@ -167,23 +168,25 @@ export default function RigBuilderClient() {
(async () => { (async () => {
try { try {
const [typesRes, rigsRes] = await Promise.all([ const [typesRes, rigsRes] = await Promise.all([
apiJson<{ data: { id: number; name: string }[] }>("/api/options/rig_type"), apiJson<{ data: { id: number; name: string }[] }>(`/api/options/rig_type`),
apiJson<{ data: RigRow[] }>("/api/my/rigs"), apiJson<{ data: RigRow[] }>(`/api/my/rigs`),
]); ]);
setRigTypes(typesRes.data); setRigTypes(typesRes.data ?? []);
setRigs(rigsRes.data); setRigs(rigsRes.data ?? []);
} catch (e: any) { } catch (e: any) {
console.warn("[rigs] initial load failed:", e?.message || e); if (!handleAuthError(e)) {
toast({ console.warn("[rigs] initial load failed:", e?.message || e);
title: "Failed to load", toast({
description: "Could not load your rigs or rig types.", title: "Failed to load",
variant: "destructive", description: "Could not load your rigs or rig types.",
}); variant: "destructive",
});
}
} }
})(); })();
}, [toast]); }, [toast]);
// Load static-ish options that depend on rig type // Load options that depend on rig type
useEffect(() => { useEffect(() => {
// when rig type changes, clear type-specific fields // when rig type changes, clear type-specific fields
setValue("laser_focus_lens", null); setValue("laser_focus_lens", null);
@ -191,35 +194,33 @@ export default function RigBuilderClient() {
setValue("laser_scan_lens_apt", null); setValue("laser_scan_lens_apt", null);
setValue("laser_scan_lens_exp", null); setValue("laser_scan_lens_exp", null);
if (!rigTarget) { if (!settingsTarget) {
setSourceOpts([]); setSourceOpts([]);
setScanLensOpts([]); setScanLensOpts([]);
setFocusLensOpts([]);
return; return;
} }
(async () => { (async () => {
try { try {
// laser sources (by target) // LASER sources by target (matches anonymous form targets)
const src = await apiJson<{ data: Option[] }>(`/api/options/laser_source?target=${settingsTarget}`); const srcJson = await apiJson<{ data: Option[] }>(
setSourceOpts(src.data ?? []); `/api/options/laser_source?target=${encodeURIComponent(settingsTarget)}`
} catch { );
setSourceOpts(srcJson.data ?? []);
} catch (e: any) {
if (!handleAuthError(e)) console.error("[laser_source] load failed:", e);
setSourceOpts([]); setSourceOpts([]);
} }
try {
// software (generic list; if you have target-aware, swap the endpoint)
const soft = await apiJson<{ data: Option[] }>(`/api/options/laser_soft`);
setSoftwareOpts(soft.data ?? []);
} catch {
setSoftwareOpts([]);
}
if (isScan) { if (isScan) {
try { try {
const lenses = await apiJson<{ data: Option[] }>(`/api/options/lens?target=${settingsTarget}`); const lensesJson = await apiJson<{ data: Option[] }>(
// server already formats "110x110mm (F160)"; keep but ensure scroll `/api/options/lens?target=${encodeURIComponent(settingsTarget)}`
setScanLensOpts(lenses.data ?? []); );
} catch { setScanLensOpts(lensesJson.data ?? []);
} catch (e: any) {
if (!handleAuthError(e)) console.error("[scan_lens] load failed:", e);
setScanLensOpts([]); setScanLensOpts([]);
} }
} else { } else {
@ -228,24 +229,23 @@ export default function RigBuilderClient() {
if (isGantry) { if (isGantry) {
try { try {
// focus lenses are just name strings const focusJson = await apiJson<{ data: Option[] }>(`/api/options/laser_focus_lens`);
const focus = await apiJson<{ data: Option[] }>(`/api/options/laser_focus_lens`); setFocusLensOpts(focusJson.data ?? []);
setFocusLensOpts(focus.data ?? []); } catch (e: any) {
} catch { if (!handleAuthError(e)) console.error("[focus_lens] load failed:", e);
setFocusLensOpts([]); setFocusLensOpts([]);
} }
} else { } else {
setFocusLensOpts([]); setFocusLensOpts([]);
} }
})(); })();
}, [rigTarget, isScan, isGantry, setValue]); }, [settingsTarget, isScan, isGantry, setValue]);
async function onSubmit(values: FormValues) { async function onSubmit(values: FormValues) {
try { try {
// shape for API
const payload = { const payload = {
name: values.name, name: values.name,
rig_type: rigTypes.find((t) => String(t.name) === String(values.rig_type))?.id ?? values.rig_type, // allow id or name rig_type: rigTypes.find((t) => String(t.name) === String(values.rig_type))?.id ?? values.rig_type,
laser_source: values.laser_source || null, laser_source: values.laser_source || null,
laser_software: values.laser_software || null, laser_software: values.laser_software || null,
laser_focus_lens: isGantry ? values.laser_focus_lens || null : null, laser_focus_lens: isGantry ? values.laser_focus_lens || null : null,
@ -255,18 +255,16 @@ export default function RigBuilderClient() {
notes: values.notes || null, notes: values.notes || null,
}; };
await apiJson("/api/my/rigs", { await apiJson(`/api/my/rigs`, {
method: "POST", method: "POST",
body: JSON.stringify(payload), body: JSON.stringify(payload),
}); });
toast({ title: "Rig saved", description: "Your rig was added." }); toast({ title: "Rig saved", description: "Your rig was added." });
// refresh list const rigsRes = await apiJson<{ data: RigRow[] }>(`/api/my/rigs`);
const rigsRes = await apiJson<{ data: RigRow[] }>("/api/my/rigs"); setRigs(rigsRes.data ?? []);
setRigs(rigsRes.data);
// keep rig type but clear the rest so it's quick to add another
reset({ reset({
name: "", name: "",
rig_type: values.rig_type, rig_type: values.rig_type,
@ -279,10 +277,14 @@ export default function RigBuilderClient() {
notes: "", notes: "",
}); });
} catch (e: any) { } catch (e: any) {
if (handleAuthError(e)) return;
const message = (() => { const message = (() => {
try { try {
const j = JSON.parse(e?.message || "{}"); const j = typeof e?.body === "object" ? e.body : JSON.parse(e?.message || "{}");
if (j?.errors) return `Directus error ${j.errors?.[0]?.extensions?.code || ""}: ${j.errors?.[0]?.message || "Failed"}`; if (j?.errors) {
const first = j.errors[0];
return `${first?.extensions?.code || "API"}: ${first?.message || "Failed"}`;
}
} catch {} } catch {}
return e?.message || "Failed to save rig"; return e?.message || "Failed to save rig";
})(); })();
@ -301,6 +303,7 @@ export default function RigBuilderClient() {
await apiJson(`/api/my/rigs/${id}`, { method: "DELETE" }); await apiJson(`/api/my/rigs/${id}`, { method: "DELETE" });
setRigs((prev) => prev.filter((r) => r.id !== id)); setRigs((prev) => prev.filter((r) => r.id !== id));
} catch (e: any) { } catch (e: any) {
if (handleAuthError(e)) return;
toast({ toast({
title: "Delete failed", title: "Delete failed",
description: e?.message || "Could not delete rig.", description: e?.message || "Could not delete rig.",
@ -310,8 +313,12 @@ export default function RigBuilderClient() {
} }
const rigTypeItems = useMemo( const rigTypeItems = useMemo(
() => rigTypes.map((t) => ({ value: String(t.name), label: String(t.name).replaceAll("_", " ") })), () =>
[rigTypes] rigTypes.map((t) => ({
value: String(t.name),
label: String(t.name).replaceAll("_", " "),
})),
[rigTypes]
); );
// ───────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────
@ -335,15 +342,11 @@ export default function RigBuilderClient() {
{/* Rig type */} {/* Rig type */}
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium">Rig Type</label> <label className="text-sm font-medium">Rig Type</label>
<Select <Select value={rigTypeVal} onValueChange={(v) => setValue("rig_type", v)}>
value={rigTypeVal}
onValueChange={(v) => setValue("rig_type", v)}
>
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Choose a rig type" /> <SelectValue placeholder="Choose a rig type" />
</SelectTrigger> </SelectTrigger>
{/* add scroll so big lists are usable */} <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border">
{rigTypeItems.map((rt) => ( {rigTypeItems.map((rt) => (
<SelectItem key={rt.value} value={rt.value}> <SelectItem key={rt.value} value={rt.value}>
{rt.label} {rt.label}
@ -353,7 +356,7 @@ export default function RigBuilderClient() {
</Select> </Select>
</div> </div>
{/* Laser Source (optional) */} {/* LASER Source (optional) */}
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium">LASER Source</label> <label className="text-sm font-medium">LASER Source</label>
<Select <Select
@ -363,7 +366,7 @@ export default function RigBuilderClient() {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Optional" /> <SelectValue placeholder="Optional" />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border"> <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectItem value="none"></SelectItem> <SelectItem value="none"></SelectItem>
{sourceOpts.map((o) => ( {sourceOpts.map((o) => (
<SelectItem key={o.id} value={String(o.id)}> <SelectItem key={o.id} value={String(o.id)}>
@ -374,7 +377,7 @@ export default function RigBuilderClient() {
</Select> </Select>
</div> </div>
{/* Laser Software (optional) */} {/* LASER Software (optional) */}
<div className="space-y-2"> <div className="space-y-2">
<label className="text-sm font-medium">LASER Software</label> <label className="text-sm font-medium">LASER Software</label>
<Select <Select
@ -384,7 +387,7 @@ export default function RigBuilderClient() {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Optional" /> <SelectValue placeholder="Optional" />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border"> <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectItem value="none"></SelectItem> <SelectItem value="none"></SelectItem>
{softwareOpts.map((o) => ( {softwareOpts.map((o) => (
<SelectItem key={o.id} value={String(o.id)}> <SelectItem key={o.id} value={String(o.id)}>
@ -413,7 +416,7 @@ export default function RigBuilderClient() {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Optional" /> <SelectValue placeholder="Optional" />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border"> <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectItem value="none"></SelectItem> <SelectItem value="none"></SelectItem>
{focusLensOpts.map((o) => ( {focusLensOpts.map((o) => (
<SelectItem key={o.id} value={String(o.id)}> <SelectItem key={o.id} value={String(o.id)}>
@ -438,7 +441,7 @@ export default function RigBuilderClient() {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Optional" /> <SelectValue placeholder="Optional" />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border"> <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectItem value="none"></SelectItem> <SelectItem value="none"></SelectItem>
{scanLensOpts.map((o) => ( {scanLensOpts.map((o) => (
<SelectItem key={o.id} value={String(o.id)}> <SelectItem key={o.id} value={String(o.id)}>
@ -458,9 +461,9 @@ export default function RigBuilderClient() {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Optional" /> <SelectValue placeholder="Optional" />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border"> <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectItem value="none"></SelectItem> <SelectItem value="none"></SelectItem>
{/* These can be swapped to real options when you expose them as /api/options/... */} {/* Swap to live options if/when exposed by API */}
<SelectItem value="10mm">10 mm</SelectItem> <SelectItem value="10mm">10 mm</SelectItem>
<SelectItem value="14mm">14 mm</SelectItem> <SelectItem value="14mm">14 mm</SelectItem>
<SelectItem value="20mm">20 mm</SelectItem> <SelectItem value="20mm">20 mm</SelectItem>
@ -478,7 +481,7 @@ export default function RigBuilderClient() {
<SelectTrigger> <SelectTrigger>
<SelectValue placeholder="Optional" /> <SelectValue placeholder="Optional" />
</SelectTrigger> </SelectTrigger>
<SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border z-50 bg-background text-foreground border"> <SelectContent position="popper" className="max-h-64 overflow-y-auto z-50 bg-background text-foreground border">
<SelectItem value="none"></SelectItem> <SelectItem value="none"></SelectItem>
<SelectItem value="1.5x">1.5×</SelectItem> <SelectItem value="1.5x">1.5×</SelectItem>
<SelectItem value="2x">2×</SelectItem> <SelectItem value="2x">2×</SelectItem>
@ -504,16 +507,12 @@ export default function RigBuilderClient() {
<div className="space-y-3"> <div className="space-y-3">
<h2 className="text-xl font-semibold">Your Rigs</h2> <h2 className="text-xl font-semibold">Your Rigs</h2>
<div className="divide-y divide-border rounded-md border"> <div className="divide-y divide-border rounded-md border">
{rigs.length === 0 && ( {rigs.length === 0 && <div className="p-4 text-sm opacity-70">No rigs yet.</div>}
<div className="p-4 text-sm opacity-70">No rigs yet.</div>
)}
{rigs.map((r) => ( {rigs.map((r) => (
<div key={r.id} className="flex items-center justify-between p-4"> <div key={r.id} className="flex items-center justify-between p-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className="font-medium">{r.name}</div> <div className="font-medium">{r.name}</div>
{r.rig_type_name && ( {r.rig_type_name && <Badge variant="secondary">{r.rig_type_name}</Badge>}
<Badge variant="secondary">{r.rig_type_name}</Badge>
)}
</div> </div>
<Button variant="destructive" size="sm" onClick={() => deleteRig(r.id)}> <Button variant="destructive" size="sm" onClick={() => deleteRig(r.id)}>
Delete Delete