forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

side-panel.tsx267 lines, 12.3 KiBHistoryRawDownload
1import { Dialog as DialogPrimitive } from "@kobalte/core/dialog";
2import { createEffect, createSignal, onCleanup, type ParentProps } from "solid-js";
3import { ConfirmDialog } from "@/components/ui/confirm-dialog";
4import { IconAlert, IconMaximize, IconMinimize, IconX } from "@/components/ui/icons";
5import { cn } from "@/lib/cn";
6import { useT } from "@/stores/preferences-context";
7
8let openPanelCount = 0;
9
10/** Width the user dragged or expanded a panel to; one value for every panel. */
11const WIDTH_KEY = "hezarfen.sidePanel.width";
12const MIN_WIDTH = 360;
13/** Room kept free on the left so the page behind still reads as "behind". */
14const PAGE_GUTTER = 64;
15const EXPANDED_WIDTH = 1120;
16
17const maxPanelWidth = () => (typeof window === "undefined" ? EXPANDED_WIDTH : Math.max(MIN_WIDTH, window.innerWidth - PAGE_GUTTER));
18const clampWidth = (value: number) => Math.round(Math.min(Math.max(value, MIN_WIDTH), maxPanelWidth()));
19const readStoredWidth = (): number | null => {
20 try {
21 const value = Number(localStorage.getItem(WIDTH_KEY));
22 return Number.isFinite(value) && value > 0 ? value : null;
23 } catch {
24 return null;
25 }
26};
27const storeWidth = (value: number | null) => {
28 try {
29 if (value == null) localStorage.removeItem(WIDTH_KEY);
30 else localStorage.setItem(WIDTH_KEY, String(value));
31 } catch {
32 // Private mode: the width lasts for this page only.
33 }
34};
35
36export function SidePanel(
37 props: ParentProps<{
38 open: boolean;
39 onOpenChange: (open: boolean) => void;
40 title: string;
41 description?: string;
42 class?: string;
43 /** default ~34rem, wide ~42rem, xl ~48rem — for report tables */
44 size?: "default" | "wide" | "xl";
45 bodyClass?: string;
46 /**
47 * The form inside holds unsaved input. Escape, an outside click or the
48 * close button then ask before discarding it; a submit or an explicit
49 * Cancel that sets `open` directly is not asked.
50 */
51 dirty?: boolean;
52 /**
53 * Treat any input or change inside the panel as unsaved work, for forms
54 * that keep their state to themselves. Ignored when `dirty` is given.
55 * Leave it off for panels whose controls save as you go.
56 */
57 guardUnsaved?: boolean;
58 }>,
59) {
60 const t = useT();
61 const [confirmDiscard, setConfirmDiscard] = createSignal(false);
62 const [touched, setTouched] = createSignal(false);
63 createEffect(() => {
64 if (props.open) setTouched(false);
65 });
66 const isDirty = () => props.dirty ?? (!!props.guardUnsaved && touched());
67 const markTouched = () => {
68 if (props.guardUnsaved) setTouched(true);
69 };
70 const requestOpenChange = (open: boolean) => {
71 // A press inside the confirm dialog reads as an outside interaction to
72 // this non-modal panel; while the dialog is up it owns the decision.
73 if (!open && confirmDiscard()) return;
74 if (!open && isDirty()) return setConfirmDiscard(true);
75 props.onOpenChange(open);
76 };
77
78 // Kobalte's modal Dialog hides the app with aria-hidden before its focus
79 // scope can move focus into this portalled panel. Chromium correctly blocks
80 // that transition when the opener still owns focus. `inert` makes the app
81 // unfocusable as well as hidden to assistive tech, while the portal remains
82 // interactive outside #root.
83 createEffect(() => {
84 if (!props.open || typeof document === "undefined") return;
85 const root = document.getElementById("root");
86 openPanelCount += 1;
87 root?.setAttribute("inert", "");
88 onCleanup(() => {
89 openPanelCount -= 1;
90 if (openPanelCount === 0) root?.removeAttribute("inert");
91 });
92 });
93
94 const width = () => {
95 if (props.size === "xl") return "max-w-[min(48rem,100vw)]";
96 if (props.size === "wide") return "max-w-[min(42rem,100vw)]";
97 return "max-w-[min(34rem,100vw)]";
98 };
99
100 // A user-chosen width, dragged from the left edge or set by the expand
101 // button, overrides the size preset on screens wide enough to have a page
102 // beside the panel. Phones keep the full-screen panel.
103 const [customWidth, setCustomWidth] = createSignal<number | null>(readStoredWidth());
104 const roomyQuery = () =>
105 typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia("(min-width: 640px)") : null;
106 const [roomy, setRoomy] = createSignal(roomyQuery()?.matches ?? false);
107 createEffect(() => {
108 if (!props.open) return;
109 const query = roomyQuery();
110 if (!query) return;
111 const sync = () => setRoomy(query.matches);
112 sync();
113 query.addEventListener("change", sync);
114 onCleanup(() => query.removeEventListener("change", sync));
115 });
116 const appliedWidth = () => {
117 const value = customWidth();
118 return roomy() && value != null ? clampWidth(value) : null;
119 };
120 const expanded = () => (appliedWidth() ?? 0) >= clampWidth(EXPANDED_WIDTH) - 8;
121 const setWidth = (value: number | null) => {
122 setCustomWidth(value == null ? null : clampWidth(value));
123 storeWidth(value == null ? null : clampWidth(value));
124 };
125 const toggleExpanded = () => setWidth(expanded() ? null : EXPANDED_WIDTH);
126 const startResize = (event: PointerEvent) => {
127 if (event.button !== 0) return;
128 event.preventDefault();
129 const handle = event.currentTarget as HTMLElement;
130 try {
131 handle.setPointerCapture(event.pointerId);
132 } catch {
133 // No active pointer to capture (synthetic events); moves still arrive.
134 }
135 const previousCursor = document.body.style.cursor;
136 document.body.style.cursor = "col-resize";
137 const move = (moveEvent: PointerEvent) => setCustomWidth(clampWidth(window.innerWidth - moveEvent.clientX));
138 const stop = () => {
139 handle.removeEventListener("pointermove", move);
140 handle.removeEventListener("pointerup", stop);
141 handle.removeEventListener("pointercancel", stop);
142 document.body.style.cursor = previousCursor;
143 storeWidth(customWidth());
144 };
145 handle.addEventListener("pointermove", move);
146 handle.addEventListener("pointerup", stop);
147 handle.addEventListener("pointercancel", stop);
148 };
149 const resizeByKey = (event: KeyboardEvent) => {
150 const step = event.shiftKey ? 80 : 24;
151 const current = appliedWidth() ?? (event.currentTarget as HTMLElement).parentElement?.getBoundingClientRect().width ?? MIN_WIDTH;
152 if (event.key === "ArrowLeft") setWidth(current + step);
153 else if (event.key === "ArrowRight") setWidth(current - step);
154 else if (event.key === "Home") setWidth(null);
155 else return;
156 event.preventDefault();
157 };
158
159 return (
160 <>
161 <DialogPrimitive open={props.open} onOpenChange={requestOpenChange} modal={false} preventScroll>
162 <DialogPrimitive.Portal>
163 {/* z-[70]: above the mobile nav sheet (z-60) and tab bar (z-40). */}
164 <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" />
165 <DialogPrimitive.Content
166 // Explicit: with any AlertDialog in the tree (the discard confirm
167 // below), Kobalte hands plain dialogs its "alertdialog" role too.
168 role="dialog"
169 // A row-actions menu that opened this panel is still animating out
170 // when the panel mounts, and focus passing through it (or back to
171 // its trigger in the inert app) read as leaving the panel, which
172 // closed it at once — "Notlandır"/"Görüntüle" seemed to do nothing.
173 // Focus moving to another dialog still closes the panel, which the
174 // edit/delete flows opened from inside a panel rely on.
175 onFocusOutside={(event) => {
176 const target = (event as CustomEvent<{ originalEvent?: FocusEvent }>).detail?.originalEvent?.target;
177 if (!(target instanceof Element)) return;
178 if (target.closest('[role="menu"]') || document.getElementById("root")?.contains(target)) event.preventDefault();
179 }}
180 class={cn(
181 "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",
182 // The panel spans the whole display, so it has to keep its own
183 // header out from under the status bar and its footer off the
184 // gesture bar. Both insets are 0 in a desktop browser.
185 "pt-[env(safe-area-inset-top)] pb-[max(env(safe-area-inset-bottom),var(--android-nav-inset,0px))]",
186 "transition-[transform,opacity] duration-200 ease-out data-closed:translate-x-full data-closed:opacity-0 data-expanded:translate-x-0 data-expanded:opacity-100",
187 width(),
188 props.class,
189 )}
190 style={appliedWidth() != null ? { width: `${appliedWidth()}px`, "max-width": "100vw" } : undefined}
191 >
192 <div class="flex shrink-0 items-start justify-between gap-2 border-b border-border-hairline px-5 py-4">
193 <div class="min-w-0 flex-1 space-y-1">
194 <DialogPrimitive.Title class="truncate text-base font-semibold leading-6 tracking-tight">
195 {props.title}
196 </DialogPrimitive.Title>
197 {props.description && (
198 <DialogPrimitive.Description class="line-clamp-2 text-sm leading-5 text-muted-foreground">
199 {props.description}
200 </DialogPrimitive.Description>
201 )}
202 </div>
203 <button
204 type="button"
205 aria-label={expanded() ? t("sidePanel.collapse") : t("sidePanel.expand")}
206 title={expanded() ? t("sidePanel.collapse") : t("sidePanel.expand")}
207 class="hidden 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 sm:inline-flex"
208 onClick={toggleExpanded}
209 >
210 {expanded() ? <IconMinimize class="h-4 w-4" /> : <IconMaximize class="h-4 w-4" />}
211 </button>
212 <DialogPrimitive.CloseButton
213 type="button"
214 aria-label={t("common.close")}
215 class="inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-md text-muted-foreground sm:h-9 sm:w-9 touch:h-10 touch:w-10 transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
216 >
217 <IconX class="h-4 w-4" />
218 </DialogPrimitive.CloseButton>
219 </div>
220 <div
221 class={cn(
222 "side-panel-body min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain px-5 py-5",
223 // Short forms should still use the full panel height so their
224 // actions settle at the bottom instead of floating above empty space.
225 "[&>form]:flex [&>form]:min-h-full [&>form]:flex-col [&>form>div:last-child]:mt-auto",
226 props.bodyClass,
227 )}
228 onInput={markTouched}
229 onChange={markTouched}
230 >
231 {props.children}
232 </div>
233 {/* Drag the left edge to resize; double-click or Home resets. Last in
234 the DOM so opening the panel does not focus it first. */}
235 <div
236 role="separator"
237 aria-orientation="vertical"
238 aria-label={t("sidePanel.resize")}
239 aria-valuemin={MIN_WIDTH}
240 aria-valuemax={maxPanelWidth()}
241 aria-valuenow={appliedWidth() ?? undefined}
242 tabIndex={0}
243 class="group/resize absolute inset-y-0 -left-1.5 z-10 hidden w-3 cursor-col-resize touch-none outline-hidden sm:block"
244 onPointerDown={startResize}
245 onDblClick={() => setWidth(null)}
246 onKeyDown={resizeByKey}
247 >
248 <span class="absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-transparent transition-colors group-hover/resize:bg-primary/60 group-focus-visible/resize:bg-primary" />
249 </div>
250 </DialogPrimitive.Content>
251 </DialogPrimitive.Portal>
252 </DialogPrimitive>
253 <ConfirmDialog
254 open={confirmDiscard()}
255 onOpenChange={setConfirmDiscard}
256 title={t("sidePanel.discardTitle")}
257 summary={t("sidePanel.discardSummary")}
258 confirmLabel={t("sidePanel.discard")}
259 cancelLabel={t("sidePanel.keepEditing")}
260 variant="destructive"
261 // Discarding a draft is not deleting a record: no trash can.
262 icon={<IconAlert class="h-4 w-4" />}
263 onConfirm={() => props.onOpenChange(false)}
264 />
265 </>
266 );
267}