fix(hk): protect unsaved editors and await prefix save results
CI / check (push) Successful in 2m34s
CI / deploy (push) Successful in 19s
CI / publish-container (push) Successful in 1m24s

This commit is contained in:
Simo committed 2026-09-11 10:48:34 +02:00
1 parent 89af4eb1f6
commit d5091d1a73
11 files changed
+602 -231

No files matched your search

+1
View File
@@ -197,6 +197,7 @@ const server = createServer(async (req, res) => {
} }
if ( if (
[ [
"/admin/unsaved-harness",
"/admin/attachment-harness", "/admin/attachment-harness",
"/admin/studio-harness", "/admin/studio-harness",
"/admin/jobs-harness", "/admin/jobs-harness",
+4 -1
View File
@@ -16,6 +16,7 @@ import messages from "@/messages/en.json";
import { AttachmentHarness } from "./attachment-harness"; import { AttachmentHarness } from "./attachment-harness";
import { FurnitureJobsHarness } from "./furniture-jobs-harness"; import { FurnitureJobsHarness } from "./furniture-jobs-harness";
import { fixtureAction } from "./server-actions"; import { fixtureAction } from "./server-actions";
import { UnsavedHarness } from "./unsaved-harness";
const theme = document.createElement("style"); const theme = document.createElement("style");
theme.textContent = themePaletteCss( theme.textContent = themePaletteCss(
@@ -105,7 +106,9 @@ createRoot(root).render(
? "News editor" ? "News editor"
: "Furniture synchronization"} : "Furniture synchronization"}
</h1> </h1>
{route.includes("studio-harness") ? ( {route.includes("unsaved-harness") ? (
<UnsavedHarness />
) : route.includes("studio-harness") ? (
<StudioClient <StudioClient
source={buildFurniImportSource("it")} source={buildFurniImportSource("it")}
initialTree={[]} initialTree={[]}
+70
View File
@@ -0,0 +1,70 @@
import { useState } from "react";
import { PrefixDialog } from "@/app/admin/prefixes/prefix-dialog";
import {
confirmUnsavedNavigation,
useUnsavedChanges,
} from "@/hooks/use-unsaved-changes";
export function UnsavedHarness() {
const [value, setValue] = useState("");
const [open, setOpen] = useState(false);
const [failSave, setFailSave] = useState(false);
const [saved, setSaved] = useState(false);
const [navigated, setNavigated] = useState(false);
const guard = useUnsavedChanges(value !== "", "Discard unsaved changes?");
return (
<>
<label>
Working value
<input
aria-label="Working value"
value={value}
onChange={(event) => setValue(event.target.value)}
/>
</label>
<a href="/admin/unsaved-destination">Leave editor</a>
<a href="#same-page">Same page</a>
<a href="mailto:[email protected]">Email</a>
<button
type="button"
onClick={() => {
if (confirmUnsavedNavigation()) setNavigated(true);
}}
>
Programmatic navigation
</button>
<button
type="button"
onClick={() => {
guard.markSaved();
setValue("");
setSaved(true);
}}
>
Save working value
</button>
{saved && <p>Working value saved</p>}
{navigated && <p>Navigation allowed</p>}
<button type="button" onClick={() => setOpen(true)}>
Open prefix
</button>
<label>
<input
type="checkbox"
checked={failSave}
onChange={(event) => setFailSave(event.target.checked)}
/>
Fail prefix save
</label>
<PrefixDialog
isOpen={open}
onClose={() => setOpen(false)}
editPrefix={null}
onSave={async () => {
if (failSave) return false;
setSaved(true);
return true;
}}
/>
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,7 @@
"use client"; "use client";
import { Loader2 } from "lucide-react"; import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { getBadgeData, updateBadge } from "@/actions/badges"; import { getBadgeData, updateBadge } from "@/actions/badges";
@@ -15,6 +16,7 @@ import {
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { useServerAction } from "@/hooks/use-server-action"; import { useServerAction } from "@/hooks/use-server-action";
import { useUnsavedChanges } from "@/hooks/use-unsaved-changes";
interface BadgeEditorDialogProps { interface BadgeEditorDialogProps {
code: string; code: string;
@@ -34,23 +36,39 @@ export function BadgeEditorDialog({
const [desc, setDesc] = useState(""); const [desc, setDesc] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const { run, isPending: saving } = useServerAction(); const { run, isPending: saving } = useServerAction();
const [saved, setSaved] = useState({ name: "", desc: "" });
const tAction = useTranslations("pages.admin.actions");
const { confirmLeave, markSaved } = useUnsavedChanges(
open && !loading && (name !== saved.name || desc !== saved.desc),
tAction("leaveUnsaved"),
);
function requestOpenChange(next: boolean) {
if (next || (!saving && confirmLeave())) onOpenChange(next);
}
// Fetch current values when dialog opens // Fetch current values when dialog opens
useEffect(() => { useEffect(() => {
if (!open || !code) return; if (!open || !code) return;
let active = true;
setLoading(true); setLoading(true);
getBadgeData({ code }) getBadgeData({ code })
.then((result) => { .then((result) => {
if (result.ok) { if (active && result.ok) {
const data = result.data as { name: string; desc: string }; const data = result.data as { name: string; desc: string };
setName(data.name ?? ""); setName(data.name ?? "");
setDesc(data.desc ?? ""); setDesc(data.desc ?? "");
setSaved({ name: data.name ?? "", desc: data.desc ?? "" });
} }
}) })
.catch(() => { .catch(() => {
toast.error("Failed to load badge data"); if (active) toast.error("Failed to load badge data");
}) })
.finally(() => setLoading(false)); .finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [open, code]); }, [open, code]);
function handleSave() { function handleSave() {
@@ -58,6 +76,8 @@ export function BadgeEditorDialog({
successMessage: `Badge ${code} updated`, successMessage: `Badge ${code} updated`,
errorMessage: "Save failed", errorMessage: "Save failed",
onSuccess: () => { onSuccess: () => {
markSaved();
setSaved({ name, desc });
onSaved?.(); onSaved?.();
onOpenChange(false); onOpenChange(false);
}, },
@@ -65,7 +85,7 @@ export function BadgeEditorDialog({
} }
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={requestOpenChange}>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
@@ -78,7 +98,7 @@ export function BadgeEditorDialog({
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /> <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div> </div>
) : ( ) : (
<div className="space-y-4"> <fieldset disabled={saving} className="space-y-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="badge-name">Name</Label> <Label htmlFor="badge-name">Name</Label>
<Input <Input
@@ -97,13 +117,13 @@ export function BadgeEditorDialog({
placeholder="Badge description" placeholder="Badge description"
/> />
</div> </div>
</div> </fieldset>
)} )}
<DialogFooter> <DialogFooter>
<Button <Button
variant="outline" variant="outline"
onClick={() => onOpenChange(false)} onClick={() => requestOpenChange(false)}
disabled={saving} disabled={saving}
> >
Cancel Cancel
File diff suppressed because it is too large. Load diff
+21 -31
View File
@@ -107,44 +107,34 @@ export function PrefixesClient({ canEdit }: { canEdit: boolean }) {
}); });
}; };
const handleSavePrefix = async (data: PrefixFormData, editId?: number) => { const handleSavePrefix = (
if (editId) { data: PrefixFormData,
editId?: number,
): Promise<boolean> => {
if (isPending) return Promise.resolve(false);
return new Promise((resolve) => {
const fields = {
text: data.text,
color: data.color,
icon: data.icon,
effect: data.effect,
active: data.active ? 1 : 0,
};
run( run(
() => () =>
updatePrefix({ editId
id: editId, ? updatePrefix({ id: editId, ...fields })
text: data.text, : createPrefix({ username: data.username, ...fields }),
color: data.color,
icon: data.icon,
effect: data.effect,
active: data.active ? 1 : 0,
}),
{ {
successMessage: "Prefix updated!", successMessage: editId ? "Prefix updated!" : "Prefix created!",
onSuccess: () => { onSuccess: () => {
fetchPrefixes(); void fetchPrefixes();
resolve(true);
}, },
onError: () => resolve(false),
}, },
); );
} else { });
run(
() =>
createPrefix({
username: data.username,
text: data.text,
color: data.color,
icon: data.icon,
effect: data.effect,
active: data.active ? 1 : 0,
}),
{
successMessage: "Prefix created!",
onSuccess: () => {
fetchPrefixes();
},
},
);
}
}; };
const openAddDialog = () => { const openAddDialog = () => {
@@ -1,5 +1,6 @@
"use client"; "use client";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { updateRoomItem } from "@/actions/rooms"; import { updateRoomItem } from "@/actions/rooms";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -15,6 +16,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea"; import { Textarea } from "@/components/ui/textarea";
import { useServerAction } from "@/hooks/use-server-action"; import { useServerAction } from "@/hooks/use-server-action";
import { useUnsavedChanges } from "@/hooks/use-unsaved-changes";
interface EditItem { interface EditItem {
id: number; id: number;
@@ -45,9 +47,26 @@ export function EditItemDialog({ roomId, item, open, onOpenChange }: Props) {
const [extraData, setExtraData] = useState(""); const [extraData, setExtraData] = useState("");
const isWall = item?.type === "i"; const isWall = item?.type === "i";
const tAction = useTranslations("pages.admin.actions");
const dirty =
!!item &&
(extraData !== item.extraData ||
(isWall
? wallPos !== item.wallPos
: x !== String(item.x) ||
y !== String(item.y) ||
z !== String(item.z) ||
rot !== String(item.rot)));
const { confirmLeave, markSaved } = useUnsavedChanges(
open && dirty,
tAction("leaveUnsaved"),
);
function requestOpenChange(next: boolean) {
if (next || (!isPending && confirmLeave())) onOpenChange(next);
}
useEffect(() => { useEffect(() => {
if (item) { if (item && open) {
setX(String(item.x)); setX(String(item.x));
setY(String(item.y)); setY(String(item.y));
setZ(String(item.z)); setZ(String(item.z));
@@ -55,7 +74,7 @@ export function EditItemDialog({ roomId, item, open, onOpenChange }: Props) {
setWallPos(item.wallPos); setWallPos(item.wallPos);
setExtraData(item.extraData); setExtraData(item.extraData);
} }
}, [item]); }, [item, open]);
function handleSave() { function handleSave() {
if (!item) return; if (!item) return;
@@ -72,12 +91,15 @@ export function EditItemDialog({ roomId, item, open, onOpenChange }: Props) {
}; };
run(() => updateRoomItem(payload), { run(() => updateRoomItem(payload), {
successMessage: "Item updated and room reloaded", successMessage: "Item updated and room reloaded",
onSuccess: () => onOpenChange(false), onSuccess: () => {
markSaved();
onOpenChange(false);
},
}); });
} }
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={requestOpenChange}>
<DialogContent className="sm:max-w-[480px]"> <DialogContent className="sm:max-w-[480px]">
<DialogHeader> <DialogHeader>
<DialogTitle>Edit furniture</DialogTitle> <DialogTitle>Edit furniture</DialogTitle>
@@ -86,7 +108,7 @@ export function EditItemDialog({ roomId, item, open, onOpenChange }: Props) {
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div className="space-y-4"> <fieldset disabled={isPending} className="space-y-4">
{isWall ? ( {isWall ? (
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="wallPos">Wall position</Label> <Label htmlFor="wallPos">Wall position</Label>
@@ -165,12 +187,12 @@ export function EditItemDialog({ roomId, item, open, onOpenChange }: Props) {
Item state/data (e.g. dice value, sticky note text, color) Item state/data (e.g. dice value, sticky note text, color)
</p> </p>
</div> </div>
</div> </fieldset>
<DialogFooter> <DialogFooter>
<Button <Button
variant="outline" variant="outline"
onClick={() => onOpenChange(false)} onClick={() => requestOpenChange(false)}
disabled={isPending} disabled={isPending}
> >
Cancel Cancel
+2
View File
@@ -21,6 +21,7 @@ import {
DialogTrigger, DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { useDebounce } from "@/hooks/use-debounce"; import { useDebounce } from "@/hooks/use-debounce";
import { confirmUnsavedNavigation } from "@/hooks/use-unsaved-changes";
import { import {
type AdminNavigationOptions, type AdminNavigationOptions,
visibleAdminNavigation, visibleAdminNavigation,
@@ -152,6 +153,7 @@ export function SearchDialog({
} }
function handleSelect(url: string) { function handleSelect(url: string) {
if (!confirmUnsavedNavigation()) return;
handleOpenChange(false); handleOpenChange(false);
setQuery(""); setQuery("");
setResults([]); setResults([]);
+57
View File
@@ -0,0 +1,57 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
const cleanup = vi.hoisted(() => [] as Array<() => void>);
vi.mock("react", () => ({
useRef: (value: unknown) => ({ current: value }),
useCallback: (callback: unknown) => callback,
useEffect: (effect: () => (() => void) | undefined) => {
const dispose = effect();
if (dispose) cleanup.push(dispose);
},
}));
import {
confirmUnsavedNavigation,
useUnsavedChanges,
} from "./use-unsaved-changes";
let confirm: ReturnType<typeof vi.fn>;
beforeEach(() => {
confirm = vi.fn().mockReturnValue(false);
vi.stubGlobal("window", Object.assign(new EventTarget(), { confirm }));
vi.stubGlobal("document", new EventTarget());
vi.stubGlobal("location", new URL("https://hotel.test/admin/editor"));
});
afterEach(() => {
for (const dispose of cleanup.splice(0)) dispose();
vi.unstubAllGlobals();
});
it("asks once for several dirty forms and allows clean navigation", () => {
useUnsavedChanges(true, "Discard changes?");
useUnsavedChanges(true, "Other changes?");
expect(confirmUnsavedNavigation()).toBe(false);
expect(confirm).toHaveBeenCalledTimes(1);
confirm.mockReturnValue(true);
expect(confirmUnsavedNavigation()).toBe(true);
});
it("removes unmounted forms from navigation protection", () => {
useUnsavedChanges(true, "Discard changes?");
for (const dispose of cleanup.splice(0)) dispose();
expect(confirmUnsavedNavigation()).toBe(true);
expect(confirm).not.toHaveBeenCalled();
});
it("protects explicit close but clears synchronously after successful save", () => {
const guard = useUnsavedChanges(true, "Discard changes?");
expect(guard.confirmLeave()).toBe(false);
guard.markSaved();
expect(guard.confirmLeave()).toBe(true);
expect(confirmUnsavedNavigation()).toBe(true);
expect(confirm).toHaveBeenCalledTimes(1);
});
it("keeps reload protected after cancelled navigation", () => {
useUnsavedChanges(true, "Discard changes?");
confirmUnsavedNavigation();
const event = new Event("beforeunload", { cancelable: true });
window.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
});
File diff suppressed because it is too large. Load diff