Skip to content
TypeScript

feat: add custom snooze dates and durations (#11800)

Julius Marminge3be02ae57914
diff --git a/apps/mobile/src/components/SegmentedControl.tsx b/apps/mobile/src/components/SegmentedControl.tsx
new file mode 100644
index 00000000000..04a562956c4
--- /dev/null
+++ b/apps/mobile/src/components/SegmentedControl.tsx
@@ -0,0 +1,74 @@
+import { Platform, Pressable, View } from "react-native";
+import Animated, { Easing, LinearTransition, ReduceMotion } from "react-native-reanimated";
+import { AppText as Text } from "./AppText";
+import { cn } from "../lib/cn";
+
+export function SegmentedControl<Value extends number | string>(props: {
+ readonly options: readonly {
+ readonly value: Value;
+ readonly label: string;
+ readonly accessibilityLabel?: string;
+ }[];
+ readonly selected: Value;
+ readonly onSelect: (value: Value) => void;
+ /** The tab bar is full height; filters under it are shorter so it stays primary. */
+ readonly size?: "default" | "compact";
+ /** "tab" for the view switcher; filters stay plain buttons. */
+ readonly role?: "tab" | "button";
+ readonly className?: string;
+}) {
+ const compact = props.size === "compact";
+ return (
+ <View
+ accessible={false}
+ className={cn(
+ "flex-row overflow-hidden rounded-full border-continuous bg-card",
+ props.className,
+ )}
+ >
+ <Animated.View
+ pointerEvents="none"
+ layout={LinearTransition.duration(200)
+ .easing(Easing.out(Easing.cubic))
+ .reduceMotion(ReduceMotion.System)}
+ className="absolute bottom-0 top-0 rounded-full bg-subtle-strong"
+ style={{
+ width: `${100 / props.options.length}%`,
+ start: `${
+ (Math.max(
+ 0,
+ props.options.findIndex((option) => option.value === props.selected),
+ ) *
+ 100) /
+ props.options.length
+ }%`,
+ }}
+ />
+ {props.options.map((option) => {
+ const active = option.value === props.selected;
+ return (
+ <Pressable
+ key={String(option.value)}
+ accessibilityRole={Platform.OS === "ios" ? "button" : (props.role ?? "button")}
+ accessibilityLabel={option.accessibilityLabel ?? option.label}
+ accessibilityState={{ selected: active }}
+ onPress={() => props.onSelect(option.value)}
+ className={cn(
+ "flex-1 items-center justify-center rounded-full",
+ compact ? "h-9" : "h-11",
+ )}
+ >
+ <Text
+ className={cn(
+ compact ? "text-xs" : "text-sm",
+ active ? "font-t3-medium text-foreground" : "text-foreground-muted",
+ )}
+ >
+ {option.label}
+ </Text>
+ </Pressable>
+ );
+ })}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/threads/CustomSnoozeSheet.ios.tsx b/apps/mobile/src/features/threads/CustomSnoozeSheet.ios.tsx
new file mode 100644
index 00000000000..7f5b69ed224
--- /dev/null
+++ b/apps/mobile/src/features/threads/CustomSnoozeSheet.ios.tsx
@@ -0,0 +1,268 @@
+import {
+ Button,
+ DatePicker,
+ Host,
+ HStack,
+ Menu,
+ Picker,
+ Popover,
+ Spacer,
+ Text,
+ VStack,
+} from "@expo/ui/swift-ui";
+import {
+ background,
+ buttonStyle,
+ datePickerStyle,
+ font,
+ foregroundStyle,
+ frame,
+ padding,
+ pickerStyle,
+ presentationBackground,
+ shapes,
+ tag,
+} from "@expo/ui/swift-ui/modifiers";
+import {
+ localSnoozeDate,
+ localSnoozeTime,
+ resolveCustomSnooze,
+ type CustomSnoozeInput,
+} from "@t3tools/client-runtime/state/thread-settled";
+import { useState } from "react";
+import { Modal, Pressable, ScrollView, View } from "react-native";
+import { AppText } from "../../components/AppText";
+import { SegmentedControl } from "../../components/SegmentedControl";
+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
+
+const durationAmounts = Array.from({ length: 99 }, (_, index) => index + 1);
+const modes = [
+ { value: "date", label: "Date and time" },
+ { value: "duration", label: "Duration" },
+] as const;
+const units = [
+ { value: "minutes", label: "Minutes" },
+ { value: "hours", label: "Hours" },
+ { value: "days", label: "Days" },
+] as const;
+
+export function CustomSnoozeSheet(props: {
+ readonly onClose: () => void;
+ readonly onSnooze: (snoozedUntil: string) => void;
+}) {
+ const [mode, setMode] = useState<CustomSnoozeInput["mode"]>("date");
+ const [date, setDate] = useState(() => new Date(Date.now() + 3_600_000));
+ const [amount, setAmount] = useState(2);
+ const [amountOpen, setAmountOpen] = useState(false);
+ const [unit, setUnit] = useState<"minutes" | "hours" | "days">("hours");
+ const [error, setError] = useState<string | null>(null);
+ const { themeVariables: colors, themeAppearance, appearance } = useAppearancePreferences();
+ const updateDate = (value: Date) => {
+ setDate(value);
+ setError(null);
+ };
+
+ const submit = () => {
+ const input: CustomSnoozeInput =
+ mode === "date"
+ ? { mode, date: localSnoozeDate(date), time: localSnoozeTime(date) }
+ : { mode, amount: String(amount), unit };
+ const snoozedUntil = resolveCustomSnooze(input, new Date());
+ if (!snoozedUntil) {
+ setError(
+ mode === "date" ? "Choose a date and time in the future." : "Enter a positive duration.",
+ );
+ return;
+ }
+ props.onSnooze(snoozedUntil);
+ props.onClose();
+ };
+
+ return (
+ <Modal visible transparent animationType="fade" onRequestClose={props.onClose}>
+ <View className="flex-1 items-center justify-center bg-black/40 px-6">
+ <ScrollView
+ className="max-h-[80%] w-full max-w-sm grow-0 rounded-3xl border border-border bg-sheet-solid"
+ contentContainerStyle={{ padding: 20, gap: 16 }}
+ >
+ <View className="flex-row items-center justify-between gap-2">
+ <Pressable accessibilityRole="button" onPress={props.onClose} hitSlop={10}>
+ <AppText className="text-base">Cancel</AppText>
+ </Pressable>
+ <AppText accessibilityRole="header" className="text-base font-t3-semibold">
+ Custom snooze
+ </AppText>
+ <Pressable accessibilityRole="button" onPress={submit} hitSlop={10}>
+ <AppText className="text-base text-primary">Snooze</AppText>
+ </Pressable>
+ </View>
+ <SegmentedControl
+ options={modes}
+ selected={mode}
+ onSelect={(value) => {
+ setMode(value);
+ setError(null);
+ }}
+ role="tab"
+ />
+ <Host
+ matchContents={{ vertical: true }}
+ style={{ width: "100%" }}
+ colorScheme={themeAppearance}
+ seedColor={colors["--color-primary"]}
+ >
+ <HStack
+ spacing={6}
+ modifiers={[
+ frame({ minHeight: 44 }),
+ foregroundStyle(colors["--color-foreground"]),
+ font({ size: appearance.baseFontSize }),
+ ]}
+ >
+ <Text>{mode === "date" ? "Until" : "Snooze for"}</Text>
+ <Spacer />
+ {mode === "date" ? (
+ <>
+ <SnoozeDateField date={date} component="date" onChange={updateDate} />
+ <SnoozeDateField date={date} component="hourAndMinute" onChange={updateDate} />
+ </>
+ ) : (
+ <>
+ <Popover isPresented={amountOpen} onIsPresentedChange={setAmountOpen}>
+ <Popover.Trigger>
+ <Button
+ onPress={() => setAmountOpen(true)}
+ modifiers={[buttonStyle("plain")]}
+ >
+ <FieldLabel label={String(amount)} />
+ </Button>
+ </Popover.Trigger>
+ <Popover.Content>
+ <VStack
+ modifiers={[
+ padding({ all: 12 }),
+ frame({ width: 180 }),
+ presentationBackground(colors["--color-sheet-solid"]),
+ ]}
+ >
+ <Picker
+ label="Duration"
+ selection={amount}
+ onSelectionChange={(value: number) => {
+ setAmount(value);
+ setError(null);
+ }}
+ modifiers={[pickerStyle("wheel"), frame({ height: 160 })]}
+ >
+ {durationAmounts.map((value) => (
+ <Text
+ key={value}
+ modifiers={[
+ tag(value),
+ foregroundStyle(colors["--color-foreground"]),
+ ]}
+ >
+ {String(value)}
+ </Text>
+ ))}
+ </Picker>
+ <Button
+ label="Done"
+ onPress={() => setAmountOpen(false)}
+ modifiers={[foregroundStyle(colors["--color-primary"])]}
+ />
+ </VStack>
+ </Popover.Content>
+ </Popover>
+ <Menu
+ label={
+ <FieldLabel
+ label={unit === "minutes" ? "Minutes" : unit === "hours" ? "Hours" : "Days"}
+ />
+ }
+ >
+ {units.map((option) => (
+ <Button
+ key={option.value}
+ label={option.label}
+ onPress={() => {
+ setUnit(option.value);
+ setError(null);
+ }}
+ />
+ ))}
+ </Menu>
+ </>
+ )}
+ </HStack>
+ </Host>
+ {error && <AppText className="text-sm text-danger-foreground">{error}</AppText>}
+ </ScrollView>
+ </View>
+ </Modal>
+ );
+}
+
+function FieldLabel(props: { readonly label: string }) {
+ const { themeVariables: colors } = useAppearancePreferences();
+ return (
+ <Text
+ modifiers={[
+ padding({ horizontal: 12, vertical: 8 }),
+ foregroundStyle(colors["--color-foreground"]),
+ background(colors["--color-card"], shapes.capsule()),
+ ]}
+ >
+ {props.label}
+ </Text>
+ );
+}
+
+function SnoozeDateField(props: {
+ readonly date: Date;
+ readonly component: "date" | "hourAndMinute";
+ readonly onChange: (date: Date) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const { themeVariables: colors } = useAppearancePreferences();
+ return (
+ <Popover isPresented={open} onIsPresentedChange={setOpen}>
+ <Popover.Trigger>
+ <Button onPress={() => setOpen(true)} modifiers={[buttonStyle("plain")]}>
+ <FieldLabel
+ label={
+ props.component === "date"
+ ? props.date.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })
+ : props.date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })
+ }
+ />
+ </Button>
+ </Popover.Trigger>
+ <Popover.Content>
+ <VStack
+ modifiers={[
+ padding({ all: 12 }),
+ frame({ width: props.component === "date" ? 340 : 300 }),
+ presentationBackground(colors["--color-sheet-solid"]),
+ ]}
+ >
+ <DatePicker
+ selection={props.date}
+ displayedComponents={[props.component]}
+ onDateChange={props.onChange}
+ modifiers={[datePickerStyle(props.component === "date" ? "graphical" : "wheel")]}
+ />
+ <Button
+ label="Done"
+ onPress={() => setOpen(false)}
+ modifiers={[foregroundStyle(colors["--color-primary"])]}
+ />
+ </VStack>
+ </Popover.Content>
+ </Popover>
+ );
+}
diff --git a/apps/mobile/src/features/threads/CustomSnoozeSheet.tsx b/apps/mobile/src/features/threads/CustomSnoozeSheet.tsx
new file mode 100644
index 00000000000..6d35adb0624
--- /dev/null
+++ b/apps/mobile/src/features/threads/CustomSnoozeSheet.tsx
@@ -0,0 +1,182 @@
+import { DateTimePicker } from "@expo/ui/community/datetime-picker";
+import {
+ localSnoozeDate,
+ localSnoozeTime,
+ resolveCustomSnooze,
+ type CustomSnoozeInput,
+} from "@t3tools/client-runtime/state/thread-settled";
+import { useState } from "react";
+import {
+ KeyboardAvoidingView,
+ Modal,
+ Platform,
+ Pressable,
+ ScrollView,
+ TextInput,
+ View,
+} from "react-native";
+import { AppText } from "../../components/AppText";
+import { SegmentedControl } from "../../components/SegmentedControl";
+
+export function CustomSnoozeSheet(props: {
+ readonly onClose: () => void;
+ readonly onSnooze: (snoozedUntil: string) => void;
+}) {
+ const [mode, setMode] = useState<CustomSnoozeInput["mode"]>("date");
+ const [date, setDate] = useState(() => new Date(Date.now() + 3_600_000));
+ const [picker, setPicker] = useState<"date" | "time" | null>(null);
+ const [amount, setAmount] = useState("2");
+ const [unit, setUnit] = useState<"minutes" | "hours" | "days">("hours");
+ const [error, setError] = useState<string | null>(null);
+ return (
+ <Modal visible transparent animationType="fade" onRequestClose={props.onClose}>
+ <KeyboardAvoidingView
+ className="flex-1 items-center justify-center bg-black/40 px-6"
+ behavior={Platform.OS === "ios" ? "padding" : undefined}
+ >
+ <ScrollView
+ className="max-h-[80%] w-full max-w-md grow-0 rounded-3xl bg-screen"
+ keyboardShouldPersistTaps="handled"
+ contentInsetAdjustmentBehavior="automatic"
+ contentContainerStyle={{ padding: 24, paddingBottom: 24, gap: 20 }}
+ >
+ <AppText accessibilityRole="header" className="text-xl font-t3-semibold">
+ Custom snooze
+ </AppText>
+ <AppText className="text-base text-foreground-secondary">
+ Choose when snoozed threads return to your inbox.
+ </AppText>
+ <SegmentedControl
+ options={
+ [
+ { value: "date", label: "Date and time" },
+ { value: "duration", label: "Duration" },
+ ] as const
+ }
+ selected={mode}
+ onSelect={(value) => {
+ setMode(value);
+ setPicker(null);
+ setError(null);
+ }}
+ role="tab"
+ />
+ {mode === "date" ? (
+ <View className="gap-3">
+ {(["date", "time"] as const).map((value) => (
+ <Pressable
+ key={value}
+ accessibilityRole="button"
+ accessibilityLabel={value === "date" ? "Choose date" : "Choose time"}
+ className="min-h-12 flex-row items-center justify-between rounded-xl bg-subtle px-3"
+ onPress={() => setPicker(value)}
+ >
+ <AppText>{value === "date" ? "Date" : "Time"}</AppText>
+ <AppText>
+ {value === "date"
+ ? date.toLocaleDateString()
+ : date.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}
+ </AppText>
+ </Pressable>
+ ))}
+ {picker && (
+ <DateTimePicker
+ value={date}
+ mode={picker}
+ display={Platform.OS === "ios" ? "spinner" : "default"}
+ onDismiss={() => setPicker(null)}
+ onValueChange={(_, selected) => {
+ const next = new Date(date);
+ if (picker === "date")
+ next.setFullYear(
+ selected.getFullYear(),
+ selected.getMonth(),
+ selected.getDate(),
+ );
+ else next.setHours(selected.getHours(), selected.getMinutes(), 0, 0);
+ setDate(next);
+ setError(null);
+ if (Platform.OS === "android") setPicker(null);
+ }}
+ />
+ )}
+ </View>
+ ) : (
+ <View className="gap-3">
+ <AppText>Snooze for</AppText>
+ <TextInput
+ accessibilityLabel="Duration"
+ className="min-h-12 rounded-xl bg-subtle px-3 text-base text-foreground"
+ keyboardType="decimal-pad"
+ value={amount}
+ onChangeText={(value) => {
+ setAmount(value);
+ setError(null);
+ }}
+ />
+ <View className="flex-row gap-2">
+ {(["minutes", "hours", "days"] as const).map((value) => (
+ <Pressable
+ key={value}
+ accessibilityRole="radio"
+ accessibilityState={{ checked: unit === value }}
+ className={
+ unit === value
+ ? "min-h-12 flex-1 items-center justify-center rounded-xl bg-subtle"
+ : "min-h-12 flex-1 items-center justify-center rounded-xl"
+ }
+ onPress={() => {
+ setUnit(value);
+ setError(null);
+ }}
+ >
+ <AppText>
+ {value === "minutes" ? "Minutes" : value === "hours" ? "Hours" : "Days"}
+ </AppText>
+ </Pressable>
+ ))}
+ </View>
+ </View>
+ )}
+ {error && (
+ <AppText accessibilityRole="alert" className="text-danger-foreground">
+ {error}
+ </AppText>
+ )}
+ <View className="flex-row justify-end gap-3">
+ <Pressable
+ accessibilityRole="button"
+ className="min-h-12 justify-center px-3"
+ onPress={props.onClose}
+ >
+ <AppText>Cancel</AppText>
+ </Pressable>
+ <Pressable
+ accessibilityRole="button"
+ className="min-h-12 justify-center rounded-xl bg-primary px-3"
+ onPress={() => {
+ const input: CustomSnoozeInput =
+ mode === "date"
+ ? { mode, date: localSnoozeDate(date), time: localSnoozeTime(date) }
+ : { mode, amount: amount.replace(",", "."), unit };
+ const snoozedUntil = resolveCustomSnooze(input, new Date());
+ if (!snoozedUntil) {
+ setError(
+ mode === "date"
+ ? "Choose a date and time in the future."
+ : "Enter a positive duration.",
+ );
+ return;
+ }
+ props.onSnooze(snoozedUntil);
+ props.onClose();
+ }}
+ >
+ <AppText className="text-primary-foreground">Snooze</AppText>
+ </Pressable>
+ </View>
+ </ScrollView>
+ </KeyboardAvoidingView>
+ </Modal>
+ );
+}
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index a234147471c..548080389d4 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -1,3 +1,4 @@
+import { CustomSnoozeSheet } from "./CustomSnoozeSheet";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
import { appAtomRegistry } from "../../state/atom-registry";
import { threadArrangementOpenAtom } from "../../state/thread-order";
@@ -471,6 +472,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[onRegenerateThreadTitle, thread],
);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
+ const [customSnoozeOpen, setCustomSnoozeOpen] = useState(false);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
[onSnoozeThread, thread],
@@ -508,12 +510,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[props.snoozePresetMinute, swipeActions.secondary],
);
const snoozePresetActions = useMemo<MenuAction[]>(
- () =>
- snoozePresets.map((preset) => ({
+ () => [
+ ...snoozePresets.map((preset) => ({
id: `snooze:${preset.id}`,
title: preset.label,
subtitle: preset.whenLabel,
})),
+ { id: "snooze:custom", title: "Custom…" },
+ ],
[snoozePresets],
);
// Pinned cards keep the full lifecycle menu; only the pin item flips to
@@ -625,6 +629,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
+ if (nativeEvent.event === "snooze:custom") {
+ setCustomSnoozeOpen(true);
+ return;
+ }
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
displayedPresets: snoozePresets,
@@ -1056,6 +1064,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
return (
<>
+ {customSnoozeOpen && (
+ <CustomSnoozeSheet onClose={() => setCustomSnoozeOpen(false)} onSnooze={handleSnooze} />
+ )}
<ThreadSwipeable
threadKey={`${thread.environmentId}:${thread.id}`}
backgroundColor={sidebarPane ? drawerColor : screenColor}
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index 04d9a4bee6c..59910c29554 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -19,9 +19,10 @@ import {
} from "@t3tools/shared/usageFormat";
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
-import Animated, { Easing, FadeIn, LinearTransition, ReduceMotion } from "react-native-reanimated";
+import Animated, { FadeIn, ReduceMotion } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
+import { SegmentedControl } from "../../components/SegmentedControl";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
@@ -332,76 +333,6 @@ export function UsageRouteScreen() {
);
}
-function SegmentedControl<Value extends number | string>(props: {
- readonly options: readonly {
- readonly value: Value;
- readonly label: string;
- readonly accessibilityLabel?: string;
- }[];
- readonly selected: Value;
- readonly onSelect: (value: Value) => void;
- /** The tab bar is full height; filters under it are shorter so it stays primary. */
- readonly size?: "default" | "compact";
- /** "tab" for the view switcher; filters stay plain buttons. */
- readonly role?: "tab" | "button";
- readonly className?: string;
-}) {
- const compact = props.size === "compact";
- return (
- <View
- accessible={false}
- className={cn(
- "flex-row overflow-hidden rounded-full border-continuous bg-card",
- props.className,
- )}
- >
- <Animated.View
- pointerEvents="none"
- layout={LinearTransition.duration(200)
- .easing(Easing.out(Easing.cubic))
- .reduceMotion(ReduceMotion.System)}
- className="absolute bottom-0 top-0 rounded-full bg-subtle-strong"
- style={{
- width: `${100 / props.options.length}%`,
- start: `${
- (Math.max(
- 0,
- props.options.findIndex((option) => option.value === props.selected),
- ) *
- 100) /
- props.options.length
- }%`,
- }}
- />
- {props.options.map((option) => {
- const active = option.value === props.selected;
- return (
- <Pressable
- key={String(option.value)}
- accessibilityRole={Platform.OS === "ios" ? "button" : (props.role ?? "button")}
- accessibilityLabel={option.accessibilityLabel ?? option.label}
- accessibilityState={{ selected: active }}
- onPress={() => props.onSelect(option.value)}
- className={cn(
- "flex-1 items-center justify-center rounded-full",
- compact ? "h-9" : "h-11",
- )}
- >
- <Text
- className={cn(
- compact ? "text-xs" : "text-sm",
- active ? "font-t3-medium text-foreground" : "text-foreground-muted",
- )}
- >
- {option.label}
- </Text>
- </Pressable>
- );
- })}
- </View>
- );
-}
-
/** Headline figure, the animated daily chart, and its legend, in one card. */
function ChartCard(props: {
readonly merged: MergedUsage;
diff --git a/apps/web/package.json b/apps/web/package.json
index 16579e730f1..53dc91214dd 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -15,6 +15,7 @@
"@base-ui/react": "^1.4.1",
"@clerk/electron": "catalog:",
"@clerk/react": "catalog:",
+ "@daypicker/react": "^10.0.1",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx
new file mode 100644
index 00000000000..d80ebf0d36f
--- /dev/null
+++ b/apps/web/src/components/CustomSnoozeDialog.tsx
@@ -0,0 +1,245 @@
+import { useEffect, useId, useState } from "react";
+import { Tabs } from "@base-ui/react/tabs";
+import { create } from "zustand";
+import {
+ localSnoozeDate,
+ localSnoozeTime,
+ resolveCustomSnooze,
+ type CustomSnoozeInput,
+} from "@t3tools/client-runtime/state/thread-settled";
+import { Button } from "./ui/button";
+import { CalendarIcon } from "lucide-react";
+import { Calendar } from "./ui/calendar";
+import { Popover, PopoverTrigger, PopoverPopup } from "./ui/popover";
+import { Input } from "./ui/input";
+import { Label } from "./ui/label";
+import { toggleVariants } from "./ui/toggle";
+import { Select, SelectTrigger, SelectValue, SelectPopup, SelectItem } from "./ui/select";
+import {
+ NumberField,
+ NumberFieldGroup,
+ NumberFieldInput,
+ NumberFieldDecrement,
+ NumberFieldIncrement,
+} from "./ui/number-field";
+import {
+ Dialog,
+ DialogPopup,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogPanel,
+ DialogFooter,
+} from "./ui/dialog";
+
+type SnoozeChoice = { readonly snoozedUntil: string };
+type Request = { readonly resolve: (choice: SnoozeChoice | null) => void };
+const useRequest = create<{ request: Request | null }>(() => ({ request: null }));
+
+export function requestCustomSnooze(): Promise<SnoozeChoice | null> {
+ useRequest.getState().request?.resolve(null);
+ return new Promise((resolve) => useRequest.setState({ request: { resolve } }));
+}
+
+function finish(choice: SnoozeChoice | null) {
+ const request = useRequest.getState().request;
+ useRequest.setState({ request: null });
+ request?.resolve(choice);
+}
+
+export function CustomSnoozeDialogHost() {
+ const request = useRequest((state) => state.request);
+ useEffect(() => () => finish(null), []);
+ return request ? <CustomSnoozeDialog /> : null;
+}
+
+function CustomSnoozeDialog() {
+ const id = useId();
+ const [initial] = useState(() => new Date(Date.now() + 3_600_000));
+ const [mode, setMode] = useState<CustomSnoozeInput["mode"]>("date");
+ const [date, setDate] = useState(initial);
+ const [calendarOpen, setCalendarOpen] = useState(false);
+ const [time, setTime] = useState(localSnoozeTime(initial));
+ const [amount, setAmount] = useState("2");
+ const [unit, setUnit] = useState<"minutes" | "hours" | "days">("hours");
+ const [error, setError] = useState<string | null>(null);
+ const input: CustomSnoozeInput =
+ mode === "date" ? { mode, date: localSnoozeDate(date), time } : { mode, amount, unit };
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) finish(null);
+ }}
+ >
+ <DialogPopup className="sm:max-w-sm">
+ <form
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault();
+ const snoozedUntil = resolveCustomSnooze(input, new Date());
+ if (!snoozedUntil) {
+ setError(
+ mode === "date"
+ ? "Choose a valid date and time in the future."
+ : "Enter a positive duration.",
+ );
+ return;
+ }
+ finish({ snoozedUntil });
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>Custom snooze</DialogTitle>
+ <DialogDescription>Choose when snoozed threads return to your inbox.</DialogDescription>
+ </DialogHeader>
+ <DialogPanel className="flex flex-col gap-4 text-base sm:text-sm">
+ <Tabs.Root
+ value={mode}
+ onValueChange={(value) => {
+ if (value === "date" || value === "duration") setMode(value);
+ setError(null);
+ }}
+ className="flex flex-col gap-4"
+ >
+ <Tabs.List
+ aria-label="Schedule type"
+ className="flex gap-0.5 rounded-lg bg-input/40 p-0.5"
+ >
+ {(["date", "duration"] as const).map((value) => (
+ <Tabs.Tab
+ key={value}
+ value={value}
+ data-pressed={mode === value ? "" : undefined}
+ className={toggleVariants({
+ variant: "segmented",
+ size: "sm",
+ className: "flex-1",
+ })}
+ >
+ {value === "date" ? "Date and time" : "Duration"}
+ </Tabs.Tab>
+ ))}
+ </Tabs.List>
+ <Tabs.Panel value={mode} className="flex flex-col gap-4">
+ {mode === "date" ? (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <div className="flex min-w-0 flex-col gap-1.5">
+ <Label htmlFor={`${id}-date`}>Date</Label>
+ <Popover open={calendarOpen} onOpenChange={setCalendarOpen}>
+ <PopoverTrigger
+ render={
+ <Button
+ id={`${id}-date`}
+ variant="outline"
+ className="w-full justify-between font-normal"
+ />
+ }
+ >
+ {date.toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ })}
+ <CalendarIcon className="size-4 text-muted-foreground" />
+ </PopoverTrigger>
+ <PopoverPopup align="start" aria-label="Choose snooze date">
+ <Calendar
+ mode="single"
+ required
+ selected={date}
+ defaultMonth={date}
+ disabled={{ before: new Date(new Date().setHours(0, 0, 0, 0)) }}
+ onSelect={(selected) => {
+ setDate(selected);
+ setCalendarOpen(false);
+ setError(null);
+ }}
+ />
+ </PopoverPopup>
+ </Popover>
+ </div>
+ <Label
+ className="flex min-w-0 flex-col items-stretch gap-1.5"
+ htmlFor={`${id}-time`}
+ >
+ Time
+ <Input
+ nativeInput
+ id={`${id}-time`}
+ className="h-9 sm:h-8"
+ type="time"
+ required
+ value={time}
+ onChange={(event) => {
+ setTime(event.target.value);
+ setError(null);
+ }}
+ />
+ </Label>
+ </div>
+ ) : (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ <NumberField
+ className="gap-1.5"
+ id={`${id}-amount`}
+ min={0}
+ step="any"
+ value={amount === "" ? null : Number(amount)}
+ onValueChange={(value) => {
+ setAmount(value === null ? "" : String(value));
+ setError(null);
+ }}
+ >
+ <Label htmlFor={`${id}-amount`}>Snooze for</Label>
+ <NumberFieldGroup>
+ <NumberFieldDecrement aria-label="Decrease duration" />
+ <NumberFieldInput required />
+ <NumberFieldIncrement aria-label="Increase duration" />
+ </NumberFieldGroup>
+ </NumberField>
+ <Label
+ className="flex min-w-0 flex-col items-stretch gap-1.5"
+ htmlFor={`${id}-unit`}
+ >
+ Unit
+ <Select
+ value={unit}
+ items={{ minutes: "Minutes", hours: "Hours", days: "Days" }}
+ onValueChange={(value) => {
+ if (value === "minutes" || value === "hours" || value === "days")
+ setUnit(value);
+ setError(null);
+ }}
+ >
+ <SelectTrigger id={`${id}-unit`} className="min-w-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectPopup>
+ <SelectItem value="minutes">Minutes</SelectItem>
+ <SelectItem value="hours">Hours</SelectItem>
+ <SelectItem value="days">Days</SelectItem>
+ </SelectPopup>
+ </Select>
+ </Label>
+ </div>
+ )}
+ </Tabs.Panel>
+ </Tabs.Root>
+ {error && (
+ <p role="alert" className="text-destructive">
+ {error}
+ </p>
+ )}
+ </DialogPanel>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => finish(null)}>
+ Cancel
+ </Button>
+ <Button type="submit">Snooze</Button>
+ </DialogFooter>
+ </form>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index cc3487b595e..6b0f3d7c11e 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -1,3 +1,4 @@
+import { requestCustomSnooze } from "./CustomSnoozeDialog";
import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
import { resolveThreadCurrentPullRequestLink } from "@t3tools/shared/threadPullRequests";
import { useAtomValue } from "@effect/atom-react";
@@ -439,7 +440,7 @@ function SidebarThreadTooltip({
function SnoozePopoverButton(props: {
open: boolean;
onOpenChange: (open: boolean) => void;
- onSnooze: (preset: SnoozePreset) => void;
+ onSnooze: (preset: Pick<SnoozePreset, "snoozedUntil">) => void;
timestampFormat: TimestampFormat;
}) {
const { open, onOpenChange, onSnooze, timestampFormat } = props;
@@ -489,6 +490,19 @@ function SnoozePopoverButton(props: {
</span>
</button>
))}
+ <div className="my-1 border-t border-border/60" />
+ <button
+ type="button"
+ className="flex w-full cursor-pointer rounded-md px-2 py-1.5 text-left text-xs text-foreground/90 hover:bg-accent hover:text-foreground"
+ onClick={async (event) => {
+ event.stopPropagation();
+ onOpenChange(false);
+ const choice = await requestCustomSnooze();
+ if (choice) onSnooze(choice);
+ }}
+ >
+ Custom…
+ </button>
</PopoverPopup>
</Popover>
);
@@ -999,7 +1013,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void;
onSettle: (threadRef: ScopedThreadRef) => void;
onUnsettle: (threadRef: ScopedThreadRef) => void;
- onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void;
+ onSnooze: (threadRef: ScopedThreadRef, preset: Pick<SnoozePreset, "snoozedUntil">) => void;
onUnsnooze: (threadRef: ScopedThreadRef) => void;
onUnpin: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
@@ -1333,7 +1347,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
[onUnpin, threadRef],
);
const handleSnoozePreset = useCallback(
- (preset: SnoozePreset) => {
+ (preset: Pick<SnoozePreset, "snoozedUntil">) => {
onSnooze(threadRef, preset);
},
[onSnooze, threadRef],
@@ -3644,7 +3658,7 @@ export default function Sidebar() {
const performSnooze = useCallback(
async (
threadRef: ScopedThreadRef,
- preset: SnoozePreset,
+ preset: Pick<SnoozePreset, "snoozedUntil">,
opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
) => {
const threadKey = scopedThreadKey(threadRef);
@@ -3678,7 +3692,7 @@ export default function Sidebar() {
const attemptSnooze = useCallback(
(
threadRef: ScopedThreadRef,
- preset: SnoozePreset,
+ preset: Pick<SnoozePreset, "snoozedUntil">,
opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
) => {
void (async () => {
@@ -3774,10 +3788,13 @@ export default function Sidebar() {
{
id: "snooze",
label: `Snooze (${count})`,
- children: snoozePresets.map((preset) => ({
- id: `snooze:${preset.id}`,
- label: `${preset.label} (${preset.whenLabel})`,
- })),
+ children: [
+ ...snoozePresets.map((preset) => ({
+ id: `snooze:${preset.id}`,
+ label: `${preset.label} (${preset.whenLabel})`,
+ })),
+ { id: "snooze:custom", label: "Custom…", separatorBefore: true },
+ ],
},
]
: []),
@@ -3790,9 +3807,10 @@ export default function Sidebar() {
);
if (clicked._tag === "Failure") return;
if (clicked.value?.startsWith("snooze:")) {
- const preset = snoozePresets.find(
- (candidate) => `snooze:${candidate.id}` === clicked.value,
- );
+ const preset =
+ clicked.value === "snooze:custom"
+ ? await requestCustomSnooze()
+ : snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value);
if (preset) {
// Post-snooze navigation must skip threads snoozing in this same
// batch — they are all leaving the card block together.
@@ -4019,9 +4037,10 @@ export default function Sidebar() {
);
if (clicked._tag === "Failure") return;
if (clicked.value?.startsWith("snooze:")) {
- const preset = snoozePresets.find(
- (candidate) => `snooze:${candidate.id}` === clicked.value,
- );
+ const preset =
+ clicked.value === "snooze:custom"
+ ? await requestCustomSnooze()
+ : snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value);
if (preset) attemptSnooze(threadRef, preset);
return;
}
diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts
index 1bdd0469375..783453ac008 100644
--- a/apps/web/src/components/threadActionMenu.logic.test.ts
+++ b/apps/web/src/components/threadActionMenu.logic.test.ts
@@ -67,7 +67,7 @@ describe("buildThreadActionMenuItems", () => {
(item) => item.id === "snooze",
);
expect(snooze?.disabled).toBe(true);
- expect(snooze?.children?.map((child) => child.id)).toEqual(["snooze:hour"]);
+ expect(snooze?.children?.map((child) => child.id)).toEqual(["snooze:hour", "snooze:custom"]);
});
it("disables title regeneration while one is in flight", () => {
diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts
index 5ba266f7709..35b14ec4439 100644
--- a/apps/web/src/components/threadActionMenu.logic.ts
+++ b/apps/web/src/components/threadActionMenu.logic.ts
@@ -88,10 +88,13 @@ export function buildThreadActionMenuItems(
label: "Snooze",
icon: "clock",
disabled: !state.canSnoozeNow,
- children: state.snoozePresets.map((preset) => ({
- id: `snooze:${preset.id}` as const,
- label: `${preset.label} (${preset.whenLabel})`,
- })),
+ children: [
+ ...state.snoozePresets.map((preset) => ({
+ id: `snooze:${preset.id}` as const,
+ label: `${preset.label} (${preset.whenLabel})`,
+ })),
+ { id: "snooze:custom" as const, label: "Custom…", separatorBefore: true },
+ ],
},
]
: []),
diff --git a/apps/web/src/components/ui/calendar.tsx b/apps/web/src/components/ui/calendar.tsx
new file mode 100644
index 00000000000..8488fd9ac6d
--- /dev/null
+++ b/apps/web/src/components/ui/calendar.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { DayPicker } from "@daypicker/react";
+import { ChevronLeftIcon, ChevronRightIcon, ChevronsUpDownIcon } from "lucide-react";
+import type * as React from "react";
+import { cn } from "~/lib/utils";
+
+const buttonClassNames =
+ "relative flex size-(--cell-size) text-base sm:text-sm items-center justify-center rounded-lg text-foreground not-in-data-selected:hover:bg-accent disabled:pointer-events-none disabled:opacity-64 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0";
+
+const defaultComponents = {
+ Chevron: ({
+ className,
+ orientation,
+ ...props
+ }: {
+ className?: string;
+ orientation?: "left" | "right" | "up" | "down";
+ }): React.ReactElement => {
+ if (orientation === "left") {
+ return (
+ <ChevronLeftIcon
+ className={cn(className, "rtl:rotate-180")}
+ {...props}
+ aria-hidden="true"
+ />
+ );
+ }
+
+ if (orientation === "right") {
+ return (
+ <ChevronRightIcon
+ className={cn(className, "rtl:rotate-180")}
+ {...props}
+ aria-hidden="true"
+ />
+ );
+ }
+
+ return <ChevronsUpDownIcon className={className} {...props} aria-hidden="true" />;
+ },
+};
+
+export function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ components: userComponents,
+ mode = "single",
+ ...props
+}: React.ComponentProps<typeof DayPicker>): React.ReactElement {
+ const defaultClassNames = {
+ button_next: buttonClassNames,
+ button_previous: buttonClassNames,
+ caption_label: "text-base sm:text-sm font-medium flex items-center gap-2 h-full",
+ day: "size-(--cell-size) text-sm py-px",
+ day_button: cn(
+ buttonClassNames,
+ "in-data-disabled:pointer-events-none in-[.range-middle]:rounded-none in-[.range-end:not(.range-start)]:rounded-s-none in-[.range-start:not(.range-end)]:rounded-e-none in-[.range-middle]:in-data-selected:bg-accent in-data-selected:bg-primary in-[.range-middle]:in-data-selected:text-foreground in-data-disabled:text-muted-foreground/72 in-data-outside:text-muted-foreground/72 in-data-selected:in-data-outside:text-primary-foreground in-data-selected:text-primary-foreground in-data-disabled:line-through outline-none in-[[data-selected]:not(.range-middle)]:transition-[border-radius,box-shadow] focus-visible:z-1 focus-visible:ring-[3px] focus-visible:ring-ring/50",
+ ),
+ dropdown: "absolute bg-popover inset-0 opacity-0",
+ dropdown_root:
+ "relative has-focus:border-ring has-focus:ring-ring/50 has-focus:ring-[3px] border border-input shadow-xs/5 rounded-lg px-[calc(--spacing(3)-1px)] h-9 sm:h-8 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:-me-1",
+ dropdowns:
+ "w-full flex items-center text-base sm:text-sm justify-center h-(--cell-size) gap-1.5 *:[span]:font-medium",
+ hidden: "invisible",
+ month: "w-full",
+ month_caption:
+ "relative mx-(--cell-size) px-1 mb-1 flex h-(--cell-size) items-center justify-center z-2",
+ months: "relative flex flex-col sm:flex-row gap-2",
+ nav: "absolute top-0 flex w-full justify-between z-1",
+ outside: "text-muted-foreground data-selected:bg-accent/50 data-selected:text-muted-foreground",
+ range_end: "range-end",
+ range_middle: "range-middle",
+ range_start: "range-start",
+ today:
+ "*:after:pointer-events-none *:after:absolute *:after:bottom-1 *:after:start-1/2 *:after:z-1 *:after:size-[3px] *:after:-translate-x-1/2 *:after:rounded-full *:after:bg-primary [&[data-selected]:not(.range-middle)>*]:after:bg-background [&[data-disabled]>*]:after:bg-foreground/30",
+ week_number: "size-(--cell-size) p-0 text-xs font-medium text-muted-foreground/72",
+ weekday: "size-(--cell-size) p-0 text-xs font-medium text-muted-foreground/72",
+ };
+ const mergedClassNames: typeof defaultClassNames = Object.keys(defaultClassNames).reduce(
+ (acc, key) => {
+ const userClass = classNames?.[key as keyof typeof classNames];
+ const baseClass = defaultClassNames[key as keyof typeof defaultClassNames];
+
+ acc[key as keyof typeof defaultClassNames] = userClass ? cn(baseClass, userClass) : baseClass;
+
+ return acc;
+ },
+ { ...defaultClassNames } as typeof defaultClassNames,
+ );
+
+ const mergedComponents = {
+ ...defaultComponents,
+ ...userComponents,
+ };
+
+ const dayPickerProps = {
+ className: cn("w-fit [--cell-size:--spacing(10)] sm:[--cell-size:--spacing(9)]", className),
+ classNames: mergedClassNames,
+ components: mergedComponents,
+ "data-slot": "calendar",
+ formatters: {
+ formatMonthDropdown: (date: Date) => date.toLocaleString("default", { month: "short" }),
+ } as React.ComponentProps<typeof DayPicker>["formatters"],
+ mode,
+ showOutsideDays,
+ ...props,
+ };
+
+ return <DayPicker {...(dayPickerProps as React.ComponentProps<typeof DayPicker>)} />;
+}
diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts
index a66ea21b989..7a33b336839 100644
--- a/apps/web/src/hooks/useThreadActionMenu.ts
+++ b/apps/web/src/hooks/useThreadActionMenu.ts
@@ -1,3 +1,4 @@
+import { requestCustomSnooze } from "../components/CustomSnoozeDialog";
import { scopeProjectRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
import {
type AtomCommandResult,
@@ -152,7 +153,10 @@ export function useThreadActionMenu(input: {
if (clicked._tag === "Failure" || clicked.value === null) return;
const action: ThreadActionMenuId = clicked.value;
if (action.startsWith("snooze:")) {
- const preset = snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
+ const preset =
+ action === "snooze:custom"
+ ? await requestCustomSnooze()
+ : snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);
if (!preset) return;
const result = await snoozeThread(threadRef, preset.snoozedUntil);
if (result._tag === "Failure") {
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 165f475c8f2..42e40842a72 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -18,6 +18,7 @@ import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL, APP_VERSION } from ".
import { resolveServerBackedAppDisplayName } from "../branding.logic";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
+import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
import { FirstRunGate } from "../components/onboarding/FirstRunGate";
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
@@ -171,6 +172,7 @@ function RootRouteView() {
<EnvironmentThemeSync />
<GlassAppearanceSync />
<FontAppearanceSync />
+ <CustomSnoozeDialogHost />
<CommandPalette>
<AppSidebarLayout>
<Outlet />
@@ -222,6 +224,7 @@ function RootRouteView() {
<SnapShotCoordinator />
<ThreadNotificationCoordinator />
<ConfirmDialogHost />
+ <CustomSnoozeDialogHost />
<SlowRpcRequestToastCoordinator />
<ProjectCloneToastCoordinator />
<HostedStaticEnvironmentBootstrap />
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index 9434e599661..67574f0b028 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -125,3 +125,10 @@ On web and desktop, use **Agents** to follow work delegated to subagents.
Expand a tool call in the conversation to see its full command and output.
Summaries shorten shell wrappers and can still describe the latest call after it
finishes; the call's own result shows its status.
+
+## Snooze until later
+
+Choose **Snooze → Custom…** from a thread's menu to pick a date and time in your
+local time zone, or a duration in minutes, hours, or days. Durations start when
+you confirm; one day means 24 hours. On web and desktop, you can also snooze
+several selected threads together. Choose **Wake thread** to bring a thread back early.
diff --git a/packages/client-runtime/src/state/customSnooze.test.ts b/packages/client-runtime/src/state/customSnooze.test.ts
new file mode 100644
index 00000000000..13117d45058
--- /dev/null
+++ b/packages/client-runtime/src/state/customSnooze.test.ts
@@ -0,0 +1,66 @@
+// @effect-diagnostics globalDate:off -- Tests exercise local calendar and elapsed-time snooze input.
+import { afterEach, describe, expect, it, vi } from "vite-plus/test";
+import { localSnoozeDate, localSnoozeTime, resolveCustomSnooze } from "./threadSettled.ts";
+
+const now = new Date(2026, 8, 14, 14, 30);
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe("custom snooze", () => {
+ it("converts local date and time to an absolute wake time", () => {
+ expect(resolveCustomSnooze({ mode: "date", date: "2026-09-15", time: "09:15" }, now)).toBe(
+ new Date(2026, 8, 15, 9, 15).toISOString(),
+ );
+ });
+
+ it.each([
+ ["2026-09-14", "14:30"],
+ ["2026-09-13", "09:00"],
+ ["2027-02-29", "09:00"],
+ ["2026-13-01", "09:00"],
+ ["2026-09-15", "24:00"],
+ ["2026-09-15", "09:60"],
+ ["", "09:00"],
+ ["2026-09-15", ""],
+ ])("rejects invalid or non-future calendar input %s %s", (date, time) => {
+ expect(resolveCustomSnooze({ mode: "date", date, time }, now)).toBeNull();
+ });
+
+ it.each([
+ ["minutes", "45", 45 * 60_000],
+ ["hours", "1.5", 90 * 60_000],
+ ["days", "2", 48 * 3_600_000],
+ ] as const)("resolves %s from the confirmation time", (unit, amount, elapsed) => {
+ const confirmedAt = new Date(now.getTime() + 5 * 60_000);
+ expect(resolveCustomSnooze({ mode: "duration", amount, unit }, confirmedAt)).toBe(
+ new Date(confirmedAt.getTime() + elapsed).toISOString(),
+ );
+ });
+
+ it.each(["", "0", "-1", "NaN", "Infinity", "1e300"])("rejects invalid duration %s", (amount) => {
+ expect(resolveCustomSnooze({ mode: "duration", amount, unit: "hours" }, now)).toBeNull();
+ });
+
+ it("rejects nonexistent local times at the spring DST transition", () => {
+ vi.stubEnv("TZ", "America/Los_Angeles");
+ expect(
+ resolveCustomSnooze(
+ { mode: "date", date: "2027-03-14", time: "02:30" },
+ new Date("2027-03-01T00:00:00Z"),
+ ),
+ ).toBeNull();
+ });
+
+ it("treats duration days as 24 hours across DST", () => {
+ vi.stubEnv("TZ", "America/Los_Angeles");
+ const before = new Date(2027, 2, 13, 12);
+ const wake = resolveCustomSnooze({ mode: "duration", amount: "1", unit: "days" }, before);
+ expect(wake).toBe(new Date(2027, 2, 14, 13).toISOString());
+ });
+
+ it("formats local input values without converting to UTC", () => {
+ const date = new Date(2026, 0, 2, 3, 4);
+ expect(localSnoozeDate(date)).toBe("2026-01-02");
+ expect(localSnoozeTime(date)).toBe("03:04");
+ });
+});
diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts
index f5209a09e49..9ea10cab72d 100644
--- a/packages/client-runtime/src/state/threadSettled.ts
+++ b/packages/client-runtime/src/state/threadSettled.ts
@@ -274,3 +274,38 @@ export function snoozeWakeLabel(snoozedUntil: string, options: { readonly now: s
if (remainingMs < DAY_MS) return `${Math.ceil(remainingMs / HOUR_MS)}h`;
return `${Math.ceil(remainingMs / DAY_MS)}d`;
}
+
+export type CustomSnoozeInput =
+ | { readonly mode: "date"; readonly date: string; readonly time: string }
+ | {
+ readonly mode: "duration";
+ readonly amount: string;
+ readonly unit: "minutes" | "hours" | "days";
+ };
+
+/** Resolve local calendar input or elapsed time, rejecting past and invalid dates. */
+export function resolveCustomSnooze(input: CustomSnoozeInput, now: Date): string | null {
+ let wake: Date;
+ if (input.mode === "duration") {
+ const amount = Number(input.amount);
+ if (!Number.isFinite(amount) || amount <= 0) return null;
+ const unitMs = { minutes: 60_000, hours: HOUR_MS, days: 24 * HOUR_MS }[input.unit];
+ wake = new Date(now.getTime() + amount * unitMs);
+ } else {
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date) || !/^\d{2}:\d{2}$/.test(input.time)) return null;
+ wake = new Date(`${input.date}T${input.time}:00`);
+ // Reject rolled-over dates and nonexistent local times during DST changes.
+ if (localSnoozeDate(wake) !== input.date || localSnoozeTime(wake) !== input.time) return null;
+ }
+ return Number.isFinite(wake.getTime()) && wake.getTime() > now.getTime()
+ ? wake.toISOString()
+ : null;
+}
+
+export function localSnoozeDate(date: Date): string {
+ return `${String(date.getFullYear()).padStart(4, "0")}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+}
+
+export function localSnoozeTime(date: Date): string {
+ return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 47f1ae85ea2..7254a454328 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -569,13 +569,16 @@ importers:
dependencies:
'@base-ui/react':
specifier: ^1.4.1
'@clerk/electron':
specifier: 0.0.42
'@clerk/react':
specifier: 6.15.2
+ '@daypicker/react':
+ specifier: ^10.0.1
+ version: 10.0.1(@types/[email protected])([email protected])
'@dnd-kit/core':
specifier: ^6.3.1
@@ -774,7 +777,7 @@ importers:
version: link:../../packages/shared
alchemy:
specifier: 2.0.0-beta.76
- version: 2.0.0-beta.76(197b68e0d20fdf20cf352009eca17c9f)
+ version: 2.0.0-beta.76(b3825b36417e56a486ccb5f22a7f3d7e)
drizzle-orm:
specifier: 1.0.0-rc.5-ab785fc
version: 1.0.0-rc.5-ab785fc(8ab70e2706da13c78d64d8a92fef1884)
@@ -1992,6 +1995,19 @@ packages:
resolution: {integrity: sha512-WTYHwlBhImGmmMt81crxaRvNdZXlBNemFyrP5GGHj2WeDTJMBrHgHTaladTypXHXrviFFBBGROl5moijRQ4ODA==}
engines: {node: '>=18'}
+ '@date-fns/[email protected]':
+ resolution: {integrity: sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==}
+
+ '@daypicker/[email protected]':
+ resolution: {integrity: sha512-lH4YQz4iMBWP8hsI1bD9Eg0T7t503IkSUR/WDGGkV5mKZvwVv+ukCkJz7yN+uVFBv7vHTK+ww7a5EvlkeFwPYQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/react': '>=16.8.0'
+ react: '>=16.8.0'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
'@distilled.cloud/[email protected]':
resolution: {integrity: sha512-eL4tRACU4TSykk/6+ItwUTZs93r3tRlrBn36ohqaUxqYYOfmssYlt/SLCzos4nlLgCxb+1T6BAstgYC848v1EQ==}
peerDependencies:
@@ -6792,6 +6808,9 @@ packages:
resolution: {integrity: sha512-1+BhOB8ahCn4O0cep0Sh2l9KCOfOdY+BXJnKMHFFzDEouSr/el18QwXEMRlOj9UY5nCeA8UN3a/82rUWRBeyBw==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
+ resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==}
+
resolution: {integrity: sha512-kLNQoadPstLgKKGIXKrnRsMgtAK/o+ix3ZmcfTfvBHzghiO9yHXpoKImGnB50EXwnfSFaSAullW/7UrSkAISSQ==}
@@ -9640,6 +9659,16 @@ packages:
resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}
engines: {node: '>= 0.10'}
+ resolution: {integrity: sha512-eNh6BlwcYInWaJtRv18mXQ06Ys/H6rdTZAnTaSdOYJuTpwP1JMCHNd1FDRadA+gbeinq+psdULN5Xnowy9mV8w==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/react': '>=16.8.0'
+ react: '>=16.8.0'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+
resolution: {integrity: sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA==}
@@ -12263,7 +12292,7 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
dependencies:
'@babel/runtime': 7.29.7
@@ -12273,7 +12302,9 @@ snapshots:
react-dom: 19.2.6([email protected])
use-sync-external-store: 1.6.0([email protected])
optionalDependencies:
+ '@date-fns/tz': 1.5.0
'@types/react': 19.2.16
+ date-fns: 4.4.0
dependencies:
@@ -12546,6 +12577,15 @@ snapshots:
'@crowecawcaw/xa11y-win32-arm64-msvc': 0.13.0
'@crowecawcaw/xa11y-win32-x64-msvc': 0.13.0
+ '@date-fns/[email protected]': {}
+
+ dependencies:
+ react: 19.2.6
+ react-day-picker: 10.0.1(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.16
+
'@distilled.cloud/[email protected]([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))':
dependencies:
'@aws-crypto/crc32': 5.2.0
@@ -16445,7 +16485,7 @@ snapshots:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
- [email protected](197b68e0d20fdf20cf352009eca17c9f):
+ [email protected](b3825b36417e56a486ccb5f22a7f3d7e):
dependencies:
'@alchemy.run/cloudflare-runtime': 2.0.0-beta.76(@distilled.cloud/[email protected]([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2)))(@effect/[email protected]([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected]))(@effect/[email protected]([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])([email protected]))(@types/[email protected])(@voidzero-dev/[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])([email protected])
'@alchemy.run/floci': 2.0.0-beta.76([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))
@@ -17337,6 +17377,8 @@ snapshots:
+
[email protected](patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4):
dependencies:
'@nornagon/put': 0.0.8
@@ -20868,6 +20910,14 @@ snapshots:
iconv-lite: 0.7.2
unpipe: 1.0.0
+ dependencies:
+ '@date-fns/tz': 1.5.0
+ date-fns: 4.4.0
+ react: 19.2.6
+ optionalDependencies:
+ '@types/react': 19.2.16
+
dependencies:
shell-quote: 1.8.4