settings overhaul and reset

This commit is contained in:
makearmy 2025-10-05 17:45:09 -04:00
parent 4ef3160515
commit 3195ff5d74
6 changed files with 904 additions and 1651 deletions

View file

@ -2,8 +2,6 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import SettingsSubmit from "@/components/forms/SettingsSubmit";
type Rec = {
submission_id: string | number;
@ -13,25 +11,23 @@ type Rec = {
photo?: { id?: string } | string | null;
screen?: { id?: string } | string | null;
// ids & readable fields
mat?: { id?: string | number; name?: string | null } | null;
mat_coat?: { id?: string | number; name?: string | null } | null;
mat_color?: { id?: string | number; name?: string | null } | null;
mat_opacity?: { id?: string | number; opacity?: string | number | null } | null;
mat_thickness?: number | null;
laser_soft?: { id?: string | number; name?: string | null } | string | number | null;
source?: { submission_id?: string | number; make?: string | null; model?: string | null; nm?: string | null } | null;
lens?: { id?: string | number; field_size?: string | number | null; focal_length?: string | number | null } | null;
focus?: number | null;
laser_soft?: { id?: string | number; name?: string | null } | string | number | null;
repeat_all?: number | null;
// CO₂ Galvo extras (M2O)
lens_conf?: { id?: string | number; name?: string | null } | null;
lens_apt?: { id?: string | number; name?: string | null } | null;
lens_exp?: { id?: string | number; name?: string | null } | null;
repeat_all?: number | null;
fill_settings?: any[] | null;
line_settings?: any[] | null;
raster_settings?: any[] | null;
@ -42,308 +38,110 @@ type Rec = {
last_modified_date?: string | null;
};
async function readJson(res: Response) {
const text = await res.text();
const API = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
const asset = (id?: string | number) => (id ? `${API}/assets/${id}` : "");
async function readJson(r: Response) {
const t = await r.text();
try {
return text ? JSON.parse(text) : null;
return t ? JSON.parse(t) : null;
} catch {
throw new Error(`Unexpected response (HTTP ${res.status})`);
return null;
}
}
function ownerLabel(o: Rec["owner"]) {
if (!o) return "—";
if (typeof o === "string" || typeof o === "number") return String(o);
return o.username || String(o.id ?? "—");
}
// Prefer public assets if available (avoids auth cookie issues in <img>)
const API_BASE = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
function fileUrl(id?: string) {
if (!id) return "";
return API_BASE ? `${API_BASE}/assets/${id}` : `/api/dx/assets/${id}`;
}
function ZoomableSquareImage(props: { src: string; alt: string; onOpen: () => void }) {
const { src, alt, onOpen } = props;
return (
<div className="border rounded overflow-hidden" style={{ aspectRatio: "1 / 1" }}>
<img
src={src}
alt={alt}
className="w-full h-full object-cover cursor-zoom-in"
loading="lazy"
onClick={onOpen}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
}}
/>
</div>
);
}
export default function CO2GalvoDetail({
id,
mode,
onSaved,
onBack,
showOwnerEdit = true,
}: {
id: string | number;
mode?: "view" | "edit";
onSaved?: (submission_id: string | number) => void;
onBack?: () => void;
showOwnerEdit?: boolean;
}) {
const sp = useSearchParams();
const router = useRouter();
const editParam = sp.get("edit") === "1";
const editMode = mode ? mode === "edit" : editParam;
export default function CO2GalvoDetail({ id, editable = true }: { id: string | number; editable?: boolean }) {
const [rec, setRec] = useState<Rec | null>(null);
const [loading, setLoading] = useState(true);
const [err, setErr] = useState<string | null>(null);
// Current user id to gate the Edit button
const [meId, setMeId] = useState<string | null>(null);
useEffect(() => {
let dead = false;
let live = true;
(async () => {
try {
const r = await fetch(`/api/dx/users/me?fields=id`, { cache: "no-store", credentials: "include" });
if (!r.ok) return;
const j = await readJson(r);
const id = j?.data?.id ?? j?.id ?? null;
if (!dead) setMeId(id ? String(id) : null);
} catch {
/* ignore */
setLoading(true);
setErr(null);
const fields = [
"submission_id",
"setting_title",
"setting_notes",
"photo.id",
"screen.id",
"mat.id",
"mat.name",
"mat_coat.id",
"mat_coat.name",
"mat_color.id",
"mat_color.name",
"mat_opacity.id",
"mat_opacity.opacity",
"mat_thickness",
"laser_soft.id",
"laser_soft.name",
"source.submission_id",
"source.make",
"source.model",
"source.nm",
"lens.id",
"lens.field_size",
"lens.focal_length",
"focus",
"lens_conf.id",
"lens_conf.name",
"lens_apt.id",
"lens_apt.name",
"lens_exp.id",
"lens_exp.name",
"repeat_all",
"fill_settings",
"line_settings",
"raster_settings",
"owner.id",
"owner.username",
"uploader",
"last_modified_date",
].join(",");
const url = `${API}/items/settings_co2gal?fields=${encodeURIComponent(fields)}&filter[submission_id][_eq]=${encodeURIComponent(
String(id)
)}&limit=1`;
const res = await fetch(url, { credentials: "include", cache: "no-store" });
if (!res.ok) {
const j = await readJson(res);
throw new Error(j?.errors?.[0]?.message || `HTTP ${res.status}`);
}
})();
const j = await res.json();
const row = Array.isArray(j?.data) ? j.data[0] : null;
if (!row) throw new Error("Not found");
if (live) setRec(row);
})()
.catch((e: any) => live && setErr(e?.message || "Failed"))
.finally(() => live && setLoading(false));
return () => {
dead = true;
};
}, []);
// lightbox
const [viewerSrc, setViewerSrc] = useState<string | null>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setViewerSrc(null);
};
if (viewerSrc) window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [viewerSrc]);
// load record (with human-readable fields, +laser_soft.name)
useEffect(() => {
if (!id) return;
let dead = false;
(async () => {
try {
setLoading(true);
setErr(null);
const fields = [
"submission_id",
"setting_title",
"setting_notes",
"photo.id",
"screen.id",
"mat.id",
"mat.name",
"mat_coat.id",
"mat_coat.name",
"mat_color.id",
"mat_color.name",
"mat_opacity.id",
"mat_opacity.opacity",
"mat_thickness",
"source.submission_id",
"source.make",
"source.model",
"source.nm",
"lens.id",
"lens.field_size",
"lens.focal_length",
// CO₂ Galvo extras
"lens_conf.id",
"lens_conf.name",
"lens_apt.id",
"lens_apt.name",
"lens_exp.id",
"lens_exp.name",
"focus",
"laser_soft.id",
"laser_soft.name",
"repeat_all",
"fill_settings",
"line_settings",
"raster_settings",
"owner.id",
"owner.username",
"uploader",
"last_modified_date",
].join(",");
const url = `/api/dx/items/settings_co2gal?fields=${encodeURIComponent(
fields
)}&filter[submission_id][_eq]=${encodeURIComponent(String(id))}&limit=1`;
const r = await fetch(url, { cache: "no-store", credentials: "include" });
if (!r.ok) {
const j = await readJson(r).catch(() => null);
throw new Error(j?.errors?.[0]?.message || `HTTP ${r.status}`);
}
const j = await readJson(r);
const row: Rec | null = Array.isArray(j?.data) ? j.data[0] || null : null;
if (!row) throw new Error("Setting not found.");
if (!dead) setRec(row);
} catch (e: any) {
if (!dead) setErr(e?.message || String(e));
} finally {
if (!dead) setLoading(false);
}
})();
return () => {
dead = true;
live = false;
};
}, [id]);
const initialValues = useMemo(() => {
if (!rec) return null;
const toId = (v: any) => (v == null ? null : typeof v === "object" ? v.id ?? v.submission_id ?? null : v);
const photoId = typeof rec?.photo === "object" ? rec?.photo?.id : (rec?.photo as any);
const screenId = typeof rec?.screen === "object" ? rec?.screen?.id : (rec?.screen as any);
const photoId = typeof rec.photo === "string" || typeof rec.photo === "number" ? String(rec.photo) : rec.photo?.id ?? null;
const screenId =
typeof rec.screen === "string" || typeof rec.screen === "number" ? String(rec.screen) : rec.screen?.id ?? null;
const matId = toId(rec.mat);
const coatId = toId(rec.mat_coat);
const colorId = toId(rec.mat_color);
const opacityId = toId(rec.mat_opacity);
const lensId = toId(rec.lens);
const sourceId =
rec.source && typeof rec.source === "object" ? rec.source.submission_id ?? null : (rec.source as any) ?? null;
// CO₂ Galvo M2O ids
const lensConfId = toId(rec.lens_conf);
const lensAptId = toId(rec.lens_apt);
const lensExpId = toId(rec.lens_exp);
return {
submission_id: rec.submission_id, // keep for edit mode parity
setting_title: rec.setting_title ?? "",
setting_notes: rec.setting_notes ?? "",
photo: photoId,
screen: screenId,
mat: matId ? String(matId) : null,
mat_coat: coatId ? String(coatId) : null,
mat_color: colorId ? String(colorId) : null,
mat_opacity: opacityId ? String(opacityId) : null,
mat_thickness: rec.mat_thickness ?? null,
source: sourceId != null ? String(sourceId) : null,
lens: lensId != null ? String(lensId) : null,
focus: rec.focus ?? null,
laser_soft: (typeof rec.laser_soft === "object" ? rec.laser_soft?.id : (rec.laser_soft as any)) ?? null,
repeat_all: rec.repeat_all ?? null,
// pass through for prefill
lens_conf: lensConfId != null ? String(lensConfId) : null,
lens_apt: lensAptId != null ? String(lensAptId) : null,
lens_exp: lensExpId != null ? String(lensExpId) : null,
fill_settings: rec.fill_settings ?? [],
line_settings: rec.line_settings ?? [],
raster_settings: rec.raster_settings ?? [],
};
}, [rec]);
function clearEditParam() {
const params = new URLSearchParams(sp.toString());
params.delete("edit");
router.replace(`?${params.toString()}`);
}
if (loading) return <p className="p-6">Loading setting</p>;
if (err)
return (
<div className="p-6">
<div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700">{err}</div>
</div>
);
if (!rec) return <p className="p-6">Setting not found.</p>;
// ── EDIT MODE ───────────────────────────────────────────────
if (editMode && initialValues) {
return (
<main className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl lg:text-2xl font-semibold">Edit CO Galvo Setting</h1>
<button className="px-2 py-1 border rounded" onClick={() => (onBack ? onBack() : clearEditParam())}>
Cancel
</button>
</div>
<SettingsSubmit
mode="edit"
initialTarget="settings_co2gal"
submissionId={rec.submission_id}
initialValues={initialValues}
/>
</main>
);
}
// ── VIEW MODE (readable) ───────────────────────────────────
const ownerDisplay = ownerLabel(rec.owner);
const ownerId =
typeof rec.owner === "object"
? rec.owner?.id != null
? String(rec.owner.id)
: null
: rec.owner != null
? String(rec.owner)
: null;
const isMine = meId && ownerId ? meId === ownerId : false;
const photoId = typeof rec.photo === "object" ? rec.photo?.id : (rec.photo as any);
const screenId = typeof rec.screen === "object" ? rec.screen?.id : (rec.screen as any);
const photoSrc = photoId ? fileUrl(String(photoId)) : "";
const screenSrc = screenId ? fileUrl(String(screenId)) : "";
if (loading) return <p className="p-4">Loading</p>;
if (err) return <div className="p-4 border border-red-300 bg-red-50 text-red-700 rounded">{err}</div>;
if (!rec) return <p className="p-4">Not found.</p>;
const softName = typeof rec.laser_soft === "object" ? rec.laser_soft?.name ?? "—" : "—";
function openEdit() {
const q = new URLSearchParams(sp.toString());
q.set("edit", "1");
router.replace(`?${q.toString()}`, { scroll: false });
}
return (
<div className="space-y-6">
<header className="space-y-1">
<h1 className="text-2xl font-bold break-words">{rec.setting_title || "Untitled"}</h1>
<h1 className="text-2xl font-bold">{rec.setting_title || "Untitled"}</h1>
<div className="text-sm text-muted-foreground">Last modified: {rec.last_modified_date || "—"}</div>
</header>
<section className="grid md:grid-cols-2 gap-6">
<div className="space-y-2">
<div className="text-sm">
<div className="space-y-2 text-sm">
<div>
<span className="font-medium">Owner:</span> {ownerDisplay}
<span className="font-medium">Owner:</span> {typeof rec.owner === "object" ? rec.owner?.username || rec.owner?.id : rec.owner || "—"}
</div>
<div>
<span className="font-medium">Uploader:</span> {rec.uploader || "—"}
@ -379,161 +177,100 @@ export default function CO2GalvoDetail({
<span className="font-medium">Software:</span> {softName}
</div>
<div>
<span className="font-medium">Repeat All:</span> {rec.repeat_all ?? "—"}
<span className="font-medium">Lens Config:</span> {rec.lens_conf?.name || "—"}
</div>
<div>
<span className="font-medium">Scan Head Aperture:</span> {rec.lens_apt?.name || "—"}
</div>
<div>
<span className="font-medium">Beam Expander:</span> {rec.lens_exp?.name || "—"}
</div>
<div>
<span className="font-medium">Repeat All:</span> {rec.repeat_all ?? "—"}
</div>
{rec.setting_notes ? (
<div>
<div className="pt-2">
<div className="text-sm font-medium mb-1">Notes</div>
<p className="text-sm whitespace-pre-wrap">{rec.setting_notes}</p>
<p className="whitespace-pre-wrap">{rec.setting_notes}</p>
</div>
) : null}
{showOwnerEdit && isMine && (
<div className="pt-2">
<button onClick={openEdit} className="px-2 py-1 border rounded text-sm">
Edit
</button>
</div>
)}
</div>
<div className="grid grid-cols-2 gap-4">
{photoSrc ? (
<figure className="space-y-1">
<ZoomableSquareImage src={photoSrc} alt="Result" onOpen={() => setViewerSrc(photoSrc)} />
<figcaption className="text-xs text-muted-foreground">Result</figcaption>
<div className="grid grid-cols-2 gap-3">
{photoId ? (
<figure>
<img className="w-full rounded border" src={asset(photoId)} alt="Result" />
<figcaption className="text-xs text-muted-foreground mt-1">Result</figcaption>
</figure>
) : null}
{screenSrc ? (
<figure className="space-y-1">
<ZoomableSquareImage src={screenSrc} alt="Settings Screenshot" onOpen={() => setViewerSrc(screenSrc)} />
<figcaption className="text-xs text-muted-foreground">Settings Screenshot</figcaption>
{screenId ? (
<figure>
<img className="w-full rounded border" src={asset(screenId)} alt="Settings Screenshot" />
<figcaption className="text-xs text-muted-foreground mt-1">Settings</figcaption>
</figure>
) : null}
</div>
</section>
{(rec.fill_settings?.length ?? 0) > 0 && (
<section className="space-y-2">
<h2 className="text-lg font-semibold">Fill Settings</h2>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b">
<tr>
<th className="px-2 py-1 text-left">Name</th>
<th className="px-2 py-1 text-left">Type</th>
<th className="px-2 py-1 text-left">Power (%)</th>
<th className="px-2 py-1 text-left">Speed (mm/s)</th>
<th className="px-2 py-1 text-left">Interval</th>
<th className="px-2 py-1 text-left">Angle</th>
<th className="px-2 py-1 text-left">Pass</th>
<th className="px-2 py-1 text-left">Freq (kHz)</th>
<th className="px-2 py-1 text-left">Pulse (ns)</th>
</tr>
</thead>
<tbody className="divide-y">
{rec.fill_settings!.map((r: any, i: number) => (
<tr key={i}>
<td className="px-2 py-1">{r.name || "—"}</td>
<td className="px-2 py-1">{r.type || "—"}</td>
<td className="px-2 py-1">{r.power ?? "—"}</td>
<td className="px-2 py-1">{r.speed ?? "—"}</td>
<td className="px-2 py-1">{r.interval ?? "—"}</td>
<td className="px-2 py-1">{r.angle ?? "—"}</td>
<td className="px-2 py-1">{r.pass ?? "—"}</td>
<td className="px-2 py-1">{r.frequency ?? "—"}</td>
<td className="px-2 py-1">{r.pulse ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
{/* Tables */}
{Array.isArray(rec.fill_settings) && rec.fill_settings.length > 0 && (
<Table title="Fill Settings" cols={["Name", "Type", "Power", "Speed", "Interval", "Angle", "Pass", "Freq", "Pulse"]} rows={rec.fill_settings.map((r) => [
r.name ?? "—",
r.type ?? "—",
r.power ?? "—",
r.speed ?? "—",
r.interval ?? "—",
r.angle ?? "—",
r.pass ?? "—",
r.frequency ?? "—",
r.pulse ?? "—",
])} />
)}
{(rec.line_settings?.length ?? 0) > 0 && (
<section className="space-y-2">
<h2 className="text-lg font-semibold">Line Settings</h2>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b">
<tr>
<th className="px-2 py-1 text-left">Name</th>
<th className="px-2 py-1 text-left">Power</th>
<th className="px-2 py-1 text-left">Speed</th>
<th className="px-2 py-1 text-left">Freq</th>
<th className="px-2 py-1 text-left">Pulse</th>
<th className="px-2 py-1 text-left">Pass</th>
<th className="px-2 py-1 text-left">Air</th>
</tr>
</thead>
<tbody className="divide-y">
{rec.line_settings!.map((r: any, i: number) => (
<tr key={i}>
<td className="px-2 py-1">{r.name || "—"}</td>
<td className="px-2 py-1">{r.power ?? "—"}</td>
<td className="px-2 py-1">{r.speed ?? "—"}</td>
<td className="px-2 py-1">{r.frequency ?? "—"}</td>
<td className="px-2 py-1">{r.pulse ?? "—"}</td>
<td className="px-2 py-1">{r.pass ?? "—"}</td>
<td className="px-2 py-1">{r.air ? "Yes" : "No"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
{Array.isArray(rec.line_settings) && rec.line_settings.length > 0 && (
<Table title="Line Settings" cols={["Name", "Power", "Speed", "Freq", "Pulse", "Pass", "Air"]} rows={rec.line_settings.map((r) => [
r.name ?? "—",
r.power ?? "—",
r.speed ?? "—",
r.frequency ?? "—",
r.pulse ?? "—",
r.pass ?? "—",
r.air ? "Yes" : "No",
])} />
)}
{(rec.raster_settings?.length ?? 0) > 0 && (
<section className="space-y-2">
<h2 className="text-lg font-semibold">Raster Settings</h2>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b">
<tr>
<th className="px-2 py-1 text-left">Name</th>
<th className="px-2 py-1 text-left">Type</th>
<th className="px-2 py-1 text-left">Dither</th>
<th className="px-2 py-1 text-left">Power</th>
<th className="px-2 py-1 text-left">Speed</th>
<th className="px-2 py-1 text-left">Interval</th>
<th className="px-2 py-1 text-left">Pass</th>
</tr>
</thead>
<tbody className="divide-y">
{rec.raster_settings!.map((r: any, i: number) => (
<tr key={i}>
<td className="px-2 py-1">{r.name || "—"}</td>
<td className="px-2 py-1">{r.type || "—"}</td>
<td className="px-2 py-1">{r.dither || "—"}</td>
<td className="px-2 py-1">{r.power ?? "—"}</td>
<td className="px-2 py-1">{r.speed ?? "—"}</td>
<td className="px-2 py-1">{r.interval ?? "—"}</td>
<td className="px-2 py-1">{r.pass ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
)}
{viewerSrc && (
<div
className="fixed inset-0 z-50 bg-black/80 p-4 flex items-center justify-center"
onClick={() => setViewerSrc(null)}
>
<img
src={viewerSrc}
alt=""
className="max-w-full max-h-full cursor-zoom-out"
onClick={(e) => e.stopPropagation()}
/>
</div>
{Array.isArray(rec.raster_settings) && rec.raster_settings.length > 0 && (
<Table title="Raster Settings" cols={["Name", "Type", "Dither", "Power", "Speed", "Interval", "Pass"]} rows={rec.raster_settings.map((r) => [
r.name ?? "—",
r.type ?? "—",
r.dither ?? "—",
r.power ?? "—",
r.speed ?? "—",
r.interval ?? "—",
r.pass ?? "—",
])} />
)}
</div>
);
}
function Table({ title, cols, rows }: { title: string; cols: string[]; rows: any[][] }) {
return (
<section className="space-y-2">
<h2 className="text-lg font-semibold">{title}</h2>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="border-b">
<tr>{cols.map((c) => <th key={c} className="px-2 py-1 text-left">{c}</th>)}</tr>
</thead>
<tbody className="divide-y">
{rows.map((r, i) => (
<tr key={i}>{r.map((v, j) => <td key={j} className="px-2 py-1">{String(v)}</td>)}</tr>
))}
</tbody>
</table>
</div>
</section>
);
}