Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CustomSnoozeDialog.tsx

237 lines9.2 KB

1import { useEffect, useId, useState } from "react";
2import { create } from "zustand";
3import {
4 localSnoozeDate,
5 localSnoozeTime,
6 resolveCustomSnooze,
7 type CustomSnoozeInput,
8} from "@t3tools/client-runtime/state/thread-settled";
9import { Button } from "./ui/button";
10import { CalendarIcon } from "lucide-react";
11import { Calendar } from "./ui/calendar";
12import { weekStartsOn } from "../timestampFormat";
13import { useNowMinute } from "../hooks/useNowMinute";
14import { Popover, PopoverTrigger, PopoverPopup } from "./ui/popover";
15import { Input } from "./ui/input";
16import { Label } from "./ui/label";
17import { Toggle, ToggleGroup } from "./ui/toggle-group";
18import { Select, SelectTrigger, SelectValue, SelectPopup, SelectItem } from "./ui/select";
19import {
20 NumberField,
21 NumberFieldGroup,
22 NumberFieldInput,
23 NumberFieldDecrement,
24 NumberFieldIncrement,
25} from "./ui/number-field";
26import {
27 Dialog,
28 DialogPopup,
29 DialogHeader,
30 DialogTitle,
31 DialogDescription,
32 DialogPanel,
33 DialogFooter,
34} from "./ui/dialog";
35​
36type SnoozeChoice = { readonly snoozedUntil: string };
37type Request = { readonly resolve: (choice: SnoozeChoice | null) => void };
38const useRequest = create<{ request: Request | null }>(() => ({ request: null }));
39​
40export function requestCustomSnooze(): Promise<SnoozeChoice | null> {
41 useRequest.getState().request?.resolve(null);
42 return new Promise((resolve) => useRequest.setState({ request: { resolve } }));
44​
45function finish(choice: SnoozeChoice | null) {
46 const request = useRequest.getState().request;
47 useRequest.setState({ request: null });
48 request?.resolve(choice);
50​
51function startOfLocalDay(ms: number) {
52 const day = new Date(ms);
53 day.setHours(0, 0, 0, 0);
54 return day;
56​
57export function CustomSnoozeDialogHost() {
58 const request = useRequest((state) => state.request);
59 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resolves any pending snooze request promise with null when the dialog host unmounts
60 useEffect(() => () => finish(null), []);
61 return request ? <CustomSnoozeDialog /> : null;
63​
64function CustomSnoozeDialog() {
65 const id = useId();
66 const [initial] = useState(() => new Date(Date.now() + 3_600_000));
67 const nowMinute = useNowMinute();
68 // Follows the clock so a dialog left open past midnight stops offering yesterday.
69 const today = startOfLocalDay(Date.parse(`${nowMinute}Z`));
70 const [mode, setMode] = useState<CustomSnoozeInput["mode"]>("date");
71 const [date, setDate] = useState(initial);
72 const [calendarOpen, setCalendarOpen] = useState(false);
73 const [time, setTime] = useState(localSnoozeTime(initial));
74 const [amount, setAmount] = useState("2");
75 const [unit, setUnit] = useState<"minutes" | "hours" | "days">("hours");
76 const [error, setError] = useState<string | null>(null);
77 const input: CustomSnoozeInput =
78 mode === "date" ? { mode, date: localSnoozeDate(date), time } : { mode, amount, unit };
79 return (
80 <Dialog
81 open
82 onOpenChange={(open) => {
83 if (!open) finish(null);
84 }}
85 >
86 <DialogPopup className="sm:max-w-sm">
87 <form
88 className="flex min-h-0 flex-col"
89 onSubmit={(event) => {
90 event.preventDefault();
91 const snoozedUntil = resolveCustomSnooze(input, new Date());
92 if (!snoozedUntil) {
93 setError(
94 mode === "date"
95 ? "Choose a valid date and time in the future."
96 : "Enter a positive duration.",
97 );
98 return;
99 }
100 finish({ snoozedUntil });
101 }}
102 >
103 <DialogHeader>
104 <DialogTitle>Custom snooze</DialogTitle>
105 <DialogDescription>Choose when snoozed threads return to your inbox.</DialogDescription>
106 </DialogHeader>
107 <DialogPanel>
108 <div className="flex flex-col gap-4">
109 <ToggleGroup
110 aria-label="Schedule type"
111 className="w-full *:flex-1"
112 value={[mode]}
113 onValueChange={(next) => {
114 const value = next[0];
115 if (value === "date" || value === "duration") setMode(value);
116 setError(null);
117 }}
118 >
119 <Toggle value="date">Date and time</Toggle>
120 <Toggle value="duration">Duration</Toggle>
121 </ToggleGroup>
122 <div className="flex flex-col gap-4">
123 {mode === "date" ? (
124 <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
125 <div className="flex min-w-0 flex-col gap-1.5">
126 <Label htmlFor={`${id}-date`}>Date</Label>
127 <Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
128 <PopoverTrigger
129 render={
130 <Button
131 id={`${id}-date`}
132 variant="outline"
133 className="w-full justify-between"
134 />
135 }
136 >
137 {date.toLocaleDateString(undefined, {
138 month: "short",
139 day: "numeric",
140 year: "numeric",
141 })}
142 <CalendarIcon className="size-4 text-muted-foreground" />
143 </PopoverTrigger>
144 <PopoverPopup align="start" aria-label="Choose snooze date">
145 <Calendar
146 mode="single"
147 required
148 selected={date}
149 defaultMonth={date}
150 {...(weekStartsOn === undefined ? {} : { weekStartsOn })}
151 disabled={{ before: today }}
152 onSelect={(selected) => {
153 setDate(selected);
154 setCalendarOpen(false);
155 setError(null);
156 }}
157 />
158 </PopoverPopup>
159 </Popover>
160 </div>
161 <Label className="flex min-w-0 flex-col items-stretch" htmlFor={`${id}-time`}>
162 Time
163 <Input
164 nativeInput
165 id={`${id}-time`}
166 className="h-9 sm:h-8"
167 type="time"
168 required
169 value={time}
170 onChange={(event) => {
171 setTime(event.target.value);
172 setError(null);
173 }}
174 />
175 </Label>
176 </div>
177 ) : (
178 <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
179 <NumberField
180 id={`${id}-amount`}
181 min={0}
182 step="any"
183 value={amount === "" ? null : Number(amount)}
184 onValueChange={(value) => {
185 setAmount(value === null ? "" : String(value));
186 setError(null);
187 }}
188 >
189 <Label htmlFor={`${id}-amount`}>Snooze for</Label>
190 <NumberFieldGroup>
191 <NumberFieldDecrement aria-label="Decrease duration" />
192 <NumberFieldInput required />
193 <NumberFieldIncrement aria-label="Increase duration" />
194 </NumberFieldGroup>
195 </NumberField>
196 <Label className="flex min-w-0 flex-col items-stretch" htmlFor={`${id}-unit`}>
197 Unit
198 <Select
199 value={unit}
200 items={{ minutes: "Minutes", hours: "Hours", days: "Days" }}
201 onValueChange={(value) => {
202 if (value === "minutes" || value === "hours" || value === "days")
203 setUnit(value);
204 setError(null);
205 }}
206 >
207 <SelectTrigger id={`${id}-unit`} className="min-w-0">
208 <SelectValue />
209 </SelectTrigger>
210 <SelectPopup>
211 <SelectItem value="minutes">Minutes</SelectItem>
212 <SelectItem value="hours">Hours</SelectItem>
213 <SelectItem value="days">Days</SelectItem>
214 </SelectPopup>
215 </Select>
216 </Label>
217 </div>
218 )}
219 </div>
220 </div>
221 {error && (
222 <p role="alert" className="text-destructive">
223 {error}
224 </p>
225 )}
226 </DialogPanel>
227 <DialogFooter>
228 <Button type="button" variant="outline" onClick={() => finish(null)}>
229 Cancel
230 </Button>
231 <Button type="submit">Snooze</Button>
232 </DialogFooter>
233 </form>
234 </DialogPopup>
235 </Dialog>
236 );