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