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