forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

date-picker.tsx232 lines, 10.4 KiBHistoryRawDownload
1import { For, Show, createEffect, createMemo, createSignal, onCleanup } from "solid-js";
2import { Portal } from "solid-js/web";
3import { IconCalendar, IconChevronLeft, IconChevronRight } from "@/components/ui/icons";
4import { Input } from "@/components/ui/input";
5import { cn } from "@/lib/cn";
6import { usePreferences } from "@/stores/preferences-context";
7
8function pad(value: number): string {
9 return String(value).padStart(2, "0");
10}
11
12function formatDate(date: Date): string {
13 return `${pad(date.getDate())}/${pad(date.getMonth() + 1)}/${date.getFullYear()}`;
14}
15
16function parseDate(value: string): Date | null {
17 const match = value.trim().match(/^(\d{1,2})[./-](\d{1,2})[./-](\d{4})$/);
18 if (!match) return null;
19 const [, dayRaw, monthRaw, yearRaw] = match;
20 const day = Number(dayRaw);
21 const month = Number(monthRaw);
22 const year = Number(yearRaw);
23 const date = new Date(year, month - 1, day);
24 if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null;
25 return date;
26}
27
28function sameDay(a: Date | null, b: Date): boolean {
29 return !!a && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
30}
31
32function isSameDay(a: Date, b: Date): boolean {
33 return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
34}
35
36function monthDays(month: Date): Array<Date | null> {
37 const year = month.getFullYear();
38 const monthIndex = month.getMonth();
39 const first = new Date(year, monthIndex, 1);
40 const days = new Date(year, monthIndex + 1, 0).getDate();
41 const blanks = (first.getDay() + 6) % 7;
42 const cells: Array<Date | null> = Array.from({ length: blanks }, () => null);
43 for (let day = 1; day <= days; day += 1) cells.push(new Date(year, monthIndex, day));
44 return cells;
45}
46
47export function DatePicker(props: {
48 id: string;
49 value: string;
50 placeholder: string;
51 required?: boolean;
52 class?: string;
53 onChange: (value: string) => void;
54}) {
55 const { locale, t } = usePreferences();
56 let root: HTMLDivElement | undefined;
57 let panel: HTMLDivElement | undefined;
58 const [open, setOpen] = createSignal(false);
59 const [position, setPosition] = createSignal({ left: 0, top: 0, width: 288 });
60 const selected = createMemo(() => parseDate(props.value));
61 const [month, setMonth] = createSignal(selected() ?? new Date());
62 const today = new Date();
63 const days = createMemo(() => monthDays(month()));
64 const monthNames = createMemo(() => Array.from({ length: 12 }, (_, index) =>
65 new Intl.DateTimeFormat(locale(), { month: "long" }).format(new Date(2024, index, 1)),
66 ));
67 const yearOptions = createMemo(() => {
68 const currentYear = new Date().getFullYear();
69 return Array.from({ length: 121 }, (_, index) => currentYear - 100 + index);
70 });
71 const todayLabel = createMemo(() => t("calendar.today"));
72 const dayHeaders = createMemo(() => {
73 const base = new Date(2024, 0, 1);
74 return Array.from({ length: 7 }, (_, i) => {
75 const d = new Date(base);
76 d.setDate(base.getDate() + i);
77 return new Intl.DateTimeFormat(locale(), { weekday: "short" }).format(d);
78 });
79 });
80
81 createEffect(() => {
82 const date = selected();
83 if (date) setMonth(date);
84 });
85
86 createEffect(() => {
87 if (!open()) return;
88 const updatePosition = () => {
89 if (!root) return;
90 const rect = root.getBoundingClientRect();
91 const panelWidth = Math.min(288, Math.max(240, window.innerWidth - 24));
92 const left = Math.min(Math.max(12, rect.left), window.innerWidth - panelWidth - 12);
93 const estimatedHeight = 300;
94 const viewportPadding = 12;
95 const availableBelow = window.innerHeight - rect.bottom - viewportPadding;
96 const availableAbove = rect.top - viewportPadding;
97 const opensAbove = availableBelow < estimatedHeight && availableAbove > availableBelow;
98 const rawTop = opensAbove ? rect.top - estimatedHeight - 8 : rect.bottom + 8;
99 const maxTop = Math.max(viewportPadding, window.innerHeight - estimatedHeight - viewportPadding);
100 const top = Math.min(Math.max(viewportPadding, rawTop), maxTop);
101 setPosition({ left, top, width: panelWidth });
102 };
103 updatePosition();
104 const closeOnOutside = (event: PointerEvent) => {
105 if (root && !root.contains(event.target as Node) && panel && !panel.contains(event.target as Node)) setOpen(false);
106 };
107 window.addEventListener("resize", updatePosition);
108 window.addEventListener("scroll", updatePosition, true);
109 document.addEventListener("pointerdown", closeOnOutside);
110 onCleanup(() => {
111 window.removeEventListener("resize", updatePosition);
112 window.removeEventListener("scroll", updatePosition, true);
113 document.removeEventListener("pointerdown", closeOnOutside);
114 });
115 });
116
117 const moveMonth = (delta: number) => {
118 setMonth((current) => new Date(current.getFullYear(), current.getMonth() + delta, 1));
119 };
120
121 const setMonthPart = (value: string) => {
122 setMonth((current) => new Date(current.getFullYear(), Number(value), 1));
123 };
124
125 const setYearPart = (value: string) => {
126 setMonth((current) => new Date(Number(value), current.getMonth(), 1));
127 };
128
129 const pick = (date: Date) => {
130 props.onChange(formatDate(date));
131 setOpen(false);
132 };
133
134 return (
135 <div ref={root} class="relative">
136 <div class="relative">
137 <Input
138 id={props.id}
139 class={cn("pr-9 placeholder:text-muted-foreground/45", props.class)}
140 inputMode="numeric"
141 placeholder={props.placeholder}
142 pattern="\d{1,2}[./-]\d{1,2}[./-]\d{4}"
143 value={props.value}
144 required={props.required}
145 onFocus={() => setOpen(true)}
146 onClick={() => setOpen(true)}
147 onInput={(e) => props.onChange(e.currentTarget.value)}
148 onBlur={() => {
149 const date = parseDate(props.value);
150 if (date) props.onChange(formatDate(date));
151 }}
152 />
153 <IconCalendar class="pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
154 </div>
155 <Show when={open()}>
156 <Portal>
157 <div
158 ref={panel}
159 data-kb-top-layer=""
160 class="pointer-events-auto fixed z-80 rounded-md border border-border/80 bg-popover p-2.5 text-popover-foreground shadow-xl shadow-black/10"
161 style={{ left: `${position().left}px`, top: `${position().top}px`, width: `${position().width}px` }}
162 on:pointerdown={(e) => e.stopPropagation()}
163 >
164 <div class="mb-3 flex items-center justify-between gap-2">
165 <button type="button" class="inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring" onClick={() => moveMonth(-1)} aria-label={t("common.prev")}>
166 <IconChevronLeft class="h-4 w-4" />
167 </button>
168 <div class="flex min-w-0 items-center gap-1">
169 <select
170 aria-label={t("calendar.month")}
171 class="h-8 min-w-0 max-w-36 rounded-md border-0 bg-transparent px-1 text-sm font-semibold capitalize outline-hidden hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
172 value={month().getMonth()}
173 onChange={(event) => setMonthPart(event.currentTarget.value)}
174 >
175 <For each={monthNames()}>{(name, index) => <option value={index()}>{name}</option>}</For>
176 </select>
177 <select
178 aria-label={t("calendar.year")}
179 class="h-8 w-20 rounded-md border-0 bg-transparent px-1 text-sm font-semibold outline-hidden hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"
180 value={month().getFullYear()}
181 onChange={(event) => setYearPart(event.currentTarget.value)}
182 >
183 <For each={yearOptions()}>{(year) => <option value={year}>{year}</option>}</For>
184 </select>
185 </div>
186 <button type="button" class="inline-flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring" onClick={() => moveMonth(1)} aria-label={t("common.next")}>
187 <IconChevronRight class="h-4 w-4" />
188 </button>
189 </div>
190 <div class="grid grid-cols-7 gap-1 text-center text-[11px] font-medium text-muted-foreground">
191 <For each={dayHeaders()}>{(day) => <span>{day}</span>}</For>
192 </div>
193 <div class="mt-1 grid grid-cols-7 gap-0.5">
194 <For each={days()}>
195 {(date) => (
196 <Show when={date} fallback={<span class="h-9" />}>
197 {(day) => (
198 <button
199 type="button"
200 class={cn(
201 "inline-flex h-9 items-center justify-center rounded-md border border-transparent p-0 text-xs font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring",
202 isSameDay(today, day()) && "border-primary/50 text-primary-text",
203 sameDay(selected(), day()) && "border-primary bg-primary text-primary-foreground shadow-xs hover:bg-primary/90 hover:text-primary-foreground",
204 )}
205 onClick={(event) => {
206 event.stopPropagation();
207 pick(day());
208 }}
209 >
210 {day().getDate()}
211 </button>
212 )}
213 </Show>
214 )}
215 </For>
216 </div>
217 <button
218 type="button"
219 class="mt-2 inline-flex h-9 w-full items-center justify-center rounded-md border bg-background px-3 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
220 onClick={(event) => {
221 event.stopPropagation();
222 pick(today);
223 }}
224 >
225 {todayLabel()}
226 </button>
227 </div>
228 </Portal>
229 </Show>
230 </div>
231 );
232}