forge
Explore
Log in

Don't you dare go Hollow

🛟 side panels ask before throwing input away

Browse files at this commit

a69482ee612f1ff689d4fbc5a259b5b6d1f77c9eBurak BoduroğluParent: 391e238
  • feat
    • 🛟 side panels ask before throwing input away
Show full message
feat: 🛟 side panels ask before throwing input away
- SidePanel takes dirty (explicit) or guardUnsaved (any input or change
  inside counts); Escape, an outside click or the close button then open a
  discard confirm, while a submit or explicit Cancel still closes directly
- pilot: class create, meal publish and the exam create details step
- fix: a press inside the confirm read as an outside click to the
  non-modal panel and reopened the confirm
- fix: Kobalte hands plain dialogs the alertdialog role whenever an
  AlertDialog is in the tree; SidePanel and Dialog set role=dialog
- fix: ConfirmDialog's cancel button was announced as an English
  "Dismiss"; it now carries its visible label
- SidePanel close button label moves into i18n
- tests for the guard, the role and guardUnsaved
src/components/ui/confirm-dialog.tsxmodified+3 -0
@@ -134,6 +134,9 @@ export function ConfirmDialog(props: ConfirmDialogProps) {
134 "hover:bg-accent hover:text-accent-foreground disabled:opacity-50",134 "hover:bg-accent hover:text-accent-foreground disabled:opacity-50",
135 )}135 )}
136 disabled={pending()}136 disabled={pending()}
137+ // Kobalte's close button defaults its accessible name to an English
138+ // "Dismiss", which overrides the visible text.
139+ aria-label={props.cancelLabel ?? t("common.cancel")}
137 >140 >
138 {props.cancelLabel ?? t("common.cancel")}141 {props.cancelLabel ?? t("common.cancel")}
139 </AlertDialogCancel>142 </AlertDialogCancel>
src/components/ui/dialog.tsxmodified+3 -0
@@ -25,6 +25,9 @@ export function DialogContent<T extends ValidComponent = "div">(
25 never clipped by the status bar or the gesture bar. */}25 never clipped by the status bar or the gesture bar. */}
26 <div class="pointer-events-none fixed inset-0 z-[70] flex items-center justify-center p-3 pb-[calc(0.75rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] pt-[calc(0.75rem+env(safe-area-inset-top))] sm:p-4">26 <div class="pointer-events-none fixed inset-0 z-[70] flex items-center justify-center p-3 pb-[calc(0.75rem+max(env(safe-area-inset-bottom),var(--android-nav-inset,0px)))] pt-[calc(0.75rem+env(safe-area-inset-top))] sm:p-4">
27 <DialogPrimitive.Content27 <DialogPrimitive.Content
28+ // Explicit: with any AlertDialog in the tree, Kobalte hands plain
29+ // dialogs its "alertdialog" role too.
30+ role="dialog"
28 class={cn(31 class={cn(
29 "pointer-events-auto relative flex max-h-[min(100%,48rem)] w-full max-w-[480px] flex-col overflow-hidden border border-border-line bg-surface-base text-foreground shadow-[0_16px_40px_rgba(0,0,0,0.16)] outline-hidden animate-fade-up sm:rounded-2xl",32 "pointer-events-auto relative flex max-h-[min(100%,48rem)] w-full max-w-[480px] flex-col overflow-hidden border border-border-line bg-surface-base text-foreground shadow-[0_16px_40px_rgba(0,0,0,0.16)] outline-hidden animate-fade-up sm:rounded-2xl",
30 local.class,33 local.class,
src/components/ui/side-panel.test.tsxadded+71 -0
@@ -0,0 +1,71 @@
1+import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library";
2+import { createSignal } from "solid-js";
3+import { afterEach, beforeEach, expect, test, vi } from "vitest";
4+import { SidePanel } from "@/components/ui/side-panel";
5+import { PreferencesProvider } from "@/stores/preferences-context";
6+
7+beforeEach(() => vi.spyOn(window, "scrollTo").mockImplementation(() => {}));
8+afterEach(() => {
9+ cleanup();
10+ vi.restoreAllMocks();
11+});
12+
13+function mount(dirty: boolean) {
14+ const [open, setOpen] = createSignal(true);
15+ render(() => (
16+ <PreferencesProvider>
17+ <span data-testid="state">{open() ? "open" : "closed"}</span>
18+ <SidePanel open={open()} onOpenChange={setOpen} title="New class" dirty={dirty}>
19+ <input aria-label="Name" />
20+ </SidePanel>
21+ </PreferencesProvider>
22+ ));
23+}
24+
25+const confirmTitle = /Discard your changes\?|Değişiklikler silinsin mi\?/;
26+const closeButton = () => screen.getAllByRole("button", { name: /^(Close|Kapat)$/ })[0];
27+
28+test("a clean panel closes straight away", async () => {
29+ mount(false);
30+ fireEvent.click(closeButton());
31+ await waitFor(() => expect(screen.getByTestId("state").textContent).toBe("closed"));
32+});
33+
34+test("a dirty panel asks before discarding, and stays open on Keep editing", async () => {
35+ mount(true);
36+ fireEvent.click(closeButton());
37+
38+ expect(await screen.findByText(confirmTitle)).toBeTruthy();
39+ expect(screen.getByTestId("state").textContent).toBe("open");
40+
41+ fireEvent.click(screen.getByRole("button", { name: /Keep editing|Düzenlemeye devam et/ }));
42+ await waitFor(() => expect(screen.queryByText(confirmTitle)).toBeNull());
43+ expect(screen.getByTestId("state").textContent).toBe("open");
44+
45+ fireEvent.click(closeButton());
46+ fireEvent.click(await screen.findByRole("button", { name: /^(Discard|Sil ve kapat)$/ }));
47+ await waitFor(() => expect(screen.getByTestId("state").textContent).toBe("closed"));
48+});
49+
50+test("the panel is announced as a dialog, not an alert dialog", () => {
51+ mount(false);
52+ expect(screen.getByRole("dialog")).toBeTruthy();
53+ expect(screen.queryByRole("alertdialog")).toBeNull();
54+});
55+
56+test("guardUnsaved asks only once something was typed", async () => {
57+ const [open, setOpen] = createSignal(true);
58+ render(() => (
59+ <PreferencesProvider>
60+ <span data-testid="state">{open() ? "open" : "closed"}</span>
61+ <SidePanel open={open()} onOpenChange={setOpen} title="New meal" guardUnsaved>
62+ <input aria-label="Slot" />
63+ </SidePanel>
64+ </PreferencesProvider>
65+ ));
66+
67+ fireEvent.input(screen.getByLabelText("Slot"), { target: { value: "Lunch" } });
68+ fireEvent.click(closeButton());
69+ expect(await screen.findByText(confirmTitle)).toBeTruthy();
70+ expect(screen.getByTestId("state").textContent).toBe("open");
71+});
src/components/ui/side-panel.tsxmodified+55 -4
@@ -1,7 +1,9 @@
1 import { Dialog as DialogPrimitive } from "@kobalte/core/dialog";1 import { Dialog as DialogPrimitive } from "@kobalte/core/dialog";
2-import { createEffect, onCleanup, type ParentProps } from "solid-js";2+import { createEffect, createSignal, onCleanup, type ParentProps } from "solid-js";
3+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
3 import { IconX } from "@/components/ui/icons";4 import { IconX } from "@/components/ui/icons";
4 import { cn } from "@/lib/cn";5 import { cn } from "@/lib/cn";
6+import { useT } from "@/stores/preferences-context";
5 7
6 let openPanelCount = 0;8 let openPanelCount = 0;
7 9
@@ -15,8 +17,38 @@ export function SidePanel(
15 /** default ~34rem, wide ~42rem, xl ~48rem — for report tables */17 /** default ~34rem, wide ~42rem, xl ~48rem — for report tables */
16 size?: "default" | "wide" | "xl";18 size?: "default" | "wide" | "xl";
17 bodyClass?: string;19 bodyClass?: string;
20+ /**
21+ * The form inside holds unsaved input. Escape, an outside click or the
22+ * close button then ask before discarding it; a submit or an explicit
23+ * Cancel that sets `open` directly is not asked.
24+ */
25+ dirty?: boolean;
26+ /**
27+ * Treat any input or change inside the panel as unsaved work, for forms
28+ * that keep their state to themselves. Ignored when `dirty` is given.
29+ * Leave it off for panels whose controls save as you go.
30+ */
31+ guardUnsaved?: boolean;
18 }>,32 }>,
19 ) {33 ) {
34+ const t = useT();
35+ const [confirmDiscard, setConfirmDiscard] = createSignal(false);
36+ const [touched, setTouched] = createSignal(false);
37+ createEffect(() => {
38+ if (props.open) setTouched(false);
39+ });
40+ const isDirty = () => props.dirty ?? (!!props.guardUnsaved && touched());
41+ const markTouched = () => {
42+ if (props.guardUnsaved) setTouched(true);
43+ };
44+ const requestOpenChange = (open: boolean) => {
45+ // A press inside the confirm dialog reads as an outside interaction to
46+ // this non-modal panel; while the dialog is up it owns the decision.
47+ if (!open && confirmDiscard()) return;
48+ if (!open && isDirty()) return setConfirmDiscard(true);
49+ props.onOpenChange(open);
50+ };
51+
20 // Kobalte's modal Dialog hides the app with aria-hidden before its focus52 // Kobalte's modal Dialog hides the app with aria-hidden before its focus
21 // scope can move focus into this portalled panel. Chromium correctly blocks53 // scope can move focus into this portalled panel. Chromium correctly blocks
22 // that transition when the opener still owns focus. `inert` makes the app54 // that transition when the opener still owns focus. `inert` makes the app
@@ -40,11 +72,15 @@ export function SidePanel(
40 };72 };
41 73
42 return (74 return (
43- <DialogPrimitive open={props.open} onOpenChange={props.onOpenChange} modal={false} preventScroll>75+ <>
76+ <DialogPrimitive open={props.open} onOpenChange={requestOpenChange} modal={false} preventScroll>
44 <DialogPrimitive.Portal>77 <DialogPrimitive.Portal>
45 {/* z-[70]: above the mobile nav sheet (z-60) and tab bar (z-40). */}78 {/* z-[70]: above the mobile nav sheet (z-60) and tab bar (z-40). */}
46 <DialogPrimitive.Overlay class="fixed inset-0 z-[70] bg-[rgba(13,15,23,0.55)] transition-opacity duration-200 data-closed:opacity-0 data-expanded:opacity-100" />79 <DialogPrimitive.Overlay class="fixed inset-0 z-[70] bg-[rgba(13,15,23,0.55)] transition-opacity duration-200 data-closed:opacity-0 data-expanded:opacity-100" />
47 <DialogPrimitive.Content80 <DialogPrimitive.Content
81+ // Explicit: with any AlertDialog in the tree (the discard confirm
82+ // below), Kobalte hands plain dialogs its "alertdialog" role too.
83+ role="dialog"
48 class={cn(84 class={cn(
49 "fixed inset-y-0 right-0 z-[70] flex h-full w-full flex-col border-l border-border-line bg-surface-base text-foreground shadow-[0_16px_40px_rgba(0,0,0,0.16)] outline-hidden",85 "fixed inset-y-0 right-0 z-[70] flex h-full w-full flex-col border-l border-border-line bg-surface-base text-foreground shadow-[0_16px_40px_rgba(0,0,0,0.16)] outline-hidden",
50 // The panel spans the whole display, so it has to keep its own86 // The panel spans the whole display, so it has to keep its own
@@ -69,17 +105,32 @@ export function SidePanel(
69 </div>105 </div>
70 <DialogPrimitive.CloseButton106 <DialogPrimitive.CloseButton
71 type="button"107 type="button"
72- aria-label="Close"108+ aria-label={t("common.close")}
73 class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"109 class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
74 >110 >
75 <IconX class="h-4 w-4" />111 <IconX class="h-4 w-4" />
76 </DialogPrimitive.CloseButton>112 </DialogPrimitive.CloseButton>
77 </div>113 </div>
78- <div class={cn("side-panel-body min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain px-5 py-5", props.bodyClass)}>114+ <div
115+ class={cn("side-panel-body min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain px-5 py-5", props.bodyClass)}
116+ onInput={markTouched}
117+ onChange={markTouched}
118+ >
79 {props.children}119 {props.children}
80 </div>120 </div>
81 </DialogPrimitive.Content>121 </DialogPrimitive.Content>
82 </DialogPrimitive.Portal>122 </DialogPrimitive.Portal>
83 </DialogPrimitive>123 </DialogPrimitive>
124+ <ConfirmDialog
125+ open={confirmDiscard()}
126+ onOpenChange={setConfirmDiscard}
127+ title={t("sidePanel.discardTitle")}
128+ summary={t("sidePanel.discardSummary")}
129+ confirmLabel={t("sidePanel.discard")}
130+ cancelLabel={t("sidePanel.keepEditing")}
131+ variant="destructive"
132+ onConfirm={() => props.onOpenChange(false)}
133+ />
134+ </>
84 );135 );
85 }136 }
src/i18n/messages.tsmodified+18 -0
@@ -616,6 +616,12 @@ export type MessageKey =
616 | "common.deleted"616 | "common.deleted"
617 | "common.saved"617 | "common.saved"
618 | "common.loadAll"618 | "common.loadAll"
619+ | "common.close"
620+ | "common.dismiss"
621+ | "sidePanel.discardTitle"
622+ | "sidePanel.discardSummary"
623+ | "sidePanel.discard"
624+ | "sidePanel.keepEditing"
619 | "dashboard.partialError"625 | "dashboard.partialError"
620 | "common.breadcrumb"626 | "common.breadcrumb"
621 | "common.truncatedNotice"627 | "common.truncatedNotice"
@@ -2751,6 +2757,12 @@ const en: Dict = {
2751 "common.deleted": "Deleted.",2757 "common.deleted": "Deleted.",
2752 "common.saved": "Saved successfully.",2758 "common.saved": "Saved successfully.",
2753 "common.loadAll": "Load all",2759 "common.loadAll": "Load all",
2760+ "common.close": "Close",
2761+ "common.dismiss": "Dismiss",
2762+ "sidePanel.discardTitle": "Discard your changes?",
2763+ "sidePanel.discardSummary": "What you entered in this form has not been saved and will be lost.",
2764+ "sidePanel.discard": "Discard",
2765+ "sidePanel.keepEditing": "Keep editing",
2754 "dashboard.partialError": "Some panels could not load and show no data.",2766 "dashboard.partialError": "Some panels could not load and show no data.",
2755 "common.breadcrumb": "Breadcrumb",2767 "common.breadcrumb": "Breadcrumb",
2756 "common.truncatedNotice": "Showing the first {shown} of {total} records.",2768 "common.truncatedNotice": "Showing the first {shown} of {total} records.",
@@ -4888,6 +4900,12 @@ const tr: Dict = {
4888 "common.deleted": "Silindi.",4900 "common.deleted": "Silindi.",
4889 "common.saved": "Başarıyla kaydedildi.",4901 "common.saved": "Başarıyla kaydedildi.",
4890 "common.loadAll": "Tümünü yükle",4902 "common.loadAll": "Tümünü yükle",
4903+ "common.close": "Kapat",
4904+ "common.dismiss": "Gizle",
4905+ "sidePanel.discardTitle": "Değişiklikler silinsin mi?",
4906+ "sidePanel.discardSummary": "Bu forma girdikleriniz kaydedilmedi ve kaybolacak.",
4907+ "sidePanel.discard": "Sil ve kapat",
4908+ "sidePanel.keepEditing": "Düzenlemeye devam et",
4891 "dashboard.partialError": "Bazı bölümler yüklenemedi ve veri göstermiyor.",4909 "dashboard.partialError": "Bazı bölümler yüklenemedi ve veri göstermiyor.",
4892 "common.breadcrumb": "Sayfa konumu",4910 "common.breadcrumb": "Sayfa konumu",
4893 "common.truncatedNotice": "{total} kayıttan ilk {shown} tanesi gösteriliyor.",4911 "common.truncatedNotice": "{total} kayıttan ilk {shown} tanesi gösteriliyor.",
src/pages/classes-page.tsxmodified+1 -1
@@ -173,7 +173,7 @@ function ClassesContent() {
173 173
174 return (174 return (
175 <div class="space-y-5">175 <div class="space-y-5">
176- <SidePanel open={canManage() && showForm()} onOpenChange={setShowForm} title={t("classGroups.newClass")} description={t("classGroups.subtitle")}>176+ <SidePanel open={canManage() && showForm()} onOpenChange={setShowForm} guardUnsaved title={t("classGroups.newClass")} description={t("classGroups.subtitle")}>
177 <form class="space-y-4" onSubmit={createClass}>177 <form class="space-y-4" onSubmit={createClass}>
178 <div class="space-y-3">178 <div class="space-y-3">
179 <div class="space-y-1.5"><Label for="class-name">{t("classGroups.className")}<span class="ml-0.5 text-destructive">*</span></Label><Input id="class-name" required maxlength={limits.latest?.course.max_class_name_len} value={name()} onInput={(e) => setName(e.currentTarget.value)} /></div>179 <div class="space-y-1.5"><Label for="class-name">{t("classGroups.className")}<span class="ml-0.5 text-destructive">*</span></Label><Input id="class-name" required maxlength={limits.latest?.course.max_class_name_len} value={name()} onInput={(e) => setName(e.currentTarget.value)} /></div>
src/pages/exams-page.tsxmodified+3 -0
@@ -388,6 +388,9 @@ function ExamsContent() {
388 388
389 <SidePanel389 <SidePanel
390 open={createOpen()}390 open={createOpen()}
391+ // Only the details step holds unsaved input; once the exam exists the
392+ // questions step saves each question itself.
393+ guardUnsaved={createStep() === "details"}
391 onOpenChange={(open) => {394 onOpenChange={(open) => {
392 setCreateOpen(open);395 setCreateOpen(open);
393 if (!open) {396 if (!open) {
src/pages/meals-page.tsxmodified+1 -1
@@ -91,7 +91,7 @@ function MealsContent() {
91 91
92 return (92 return (
93 <div class="space-y-5">93 <div class="space-y-5">
94- <SidePanel open={showCreate()} onOpenChange={setShowCreate} title={t("meals.publish")} description={t("meals.publishHelp")}>94+ <SidePanel open={showCreate()} onOpenChange={setShowCreate} guardUnsaved title={t("meals.publish")} description={t("meals.publishHelp")}>
95 <form class="space-y-4" onSubmit={publish}>95 <form class="space-y-4" onSubmit={publish}>
96 <Show when={limits.error}><ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} /></Show>96 <Show when={limits.error}><ErrorAlert message={formatApiError(limits.error)} onRetry={() => void refetchLimits()} /></Show>
97 <div class="space-y-1.5"><Label for="meal-date">{t("meals.date")}</Label><DatePicker id="meal-date" required placeholder={t("form.datePlaceholder")} value={isoDateToInput(date())} onChange={(value) => setDate(inputDateToIso(value))} /></div>97 <div class="space-y-1.5"><Label for="meal-date">{t("meals.date")}</Label><DatePicker id="meal-date" required placeholder={t("form.datePlaceholder")} value={isoDateToInput(date())} onChange={(value) => setDate(inputDateToIso(value))} /></div>