Skip to content
Merged
17 changes: 12 additions & 5 deletions src/app/(alarm)/alarm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import { useAlarmDismissal } from "@/hooks/useAlarmDismissal";
import { useAlarmFiringStore } from "@/store/alarmFiringStore";
import { useAlarmStore } from "@/store/alarmStore";
import { colors, radii, spacing, typography } from "@/theme";
import { formatTime } from "@/utils/time";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useEffect, useMemo } from "react";
import dayjs from "dayjs";
import { useEffect, useMemo, useState } from "react";
import { BackHandler, Pressable, StyleSheet, Text, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

Expand Down Expand Up @@ -54,6 +54,15 @@ export default function AlarmDisplay() {
return () => backSub.remove();
}, []);

const [currentTime, setCurrentTime] = useState(() => dayjs().format("HH:mm"));

useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(dayjs().format("HH:mm"));
}, 1000);
return () => clearInterval(timer);
}, []);

if (!effectiveSnapshot) {
return (
<SafeAreaView style={styles.container}>
Expand Down Expand Up @@ -102,9 +111,7 @@ export default function AlarmDisplay() {
return (
<SafeAreaView style={styles.container}>
<View style={styles.content}>
<Text style={styles.time}>
{formatTime(effectiveSnapshot.hour, effectiveSnapshot.minute)}
</Text>
<Text style={styles.time}>{currentTime}</Text>
<Text style={styles.label}>
{effectiveSnapshot.isSnoozed ? "Snoozed alarm" : "Alarm"}
</Text>
Expand Down
71 changes: 71 additions & 0 deletions src/app/(main)/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export default function Home() {
const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());
const [now, setNow] = useState<Date>(() => new Date());

const snoozedCount = useAlarmStore((s) => s.snoozedCount);

useEffect(() => {
useAlarmStore.getState().loadAlarms();
}, []);
Expand All @@ -42,6 +44,34 @@ export default function Home() {
[alarms, now],
);

const dismissSnoozed = () => {
Alert.alert(
"Dismiss snoozed alarms?",
`${snoozedCount} snoozed alarm${snoozedCount > 1 ? "s" : ""} will be dismissed.`,
[
{ text: "Cancel", style: "cancel" },
{
text: "Dismiss all",
style: "destructive",
onPress: () => {
void (async () => {
try {
await useAlarmStore.getState().dismissAllSnoozedAlarms();
} catch (e) {
console.error("dismissSnoozed failed", e);
Alert.alert(
"Error",
"Could not dismiss snoozed alarms. Please try again.",
);
}
})();
},
},
],
{ cancelable: true },
);
};

const toggleEnabled = (alarm: Alarm) => {
if (!alarm.enabled) {
const conflict = findConflictingAlarm(alarms, alarm, alarm.id);
Expand Down Expand Up @@ -199,6 +229,24 @@ export default function Home() {
<Text style={styles.countdown}>{countdown}</Text>
</View>

{snoozedCount > 0 ? (
<Pressable
style={({ pressed }) => [
styles.snoozedBadge,
pressed && styles.snoozedBadgePressed,
]}
accessibilityRole="button"
accessibilityLabel={`${snoozedCount} snoozed alarm${snoozedCount > 1 ? "s" : ""}`}
onPress={dismissSnoozed}
>
<Lucide name="bell" size={16} color={colors.accent} />
<Text style={styles.snoozedBadgeText}>
{snoozedCount} snoozed alarm{snoozedCount > 1 ? "s" : ""}
</Text>
<Lucide name="x" size={16} color={colors.accent} />
</Pressable>
) : null}

<View style={styles.listContainer}>
<View
style={[styles.actionsRow, editEnabled && styles.actionsRowEditing]}
Expand Down Expand Up @@ -515,4 +563,27 @@ const styles = StyleSheet.create({
color: colors.danger,
fontWeight: "600",
},
snoozedBadge: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
marginHorizontal: spacing.lg,
marginBottom: spacing.sm,
paddingVertical: spacing.sm,
paddingHorizontal: spacing.md,
backgroundColor: colors.surface,
borderRadius: radii.md,
borderWidth: 1,
borderColor: colors.accent,
},
snoozedBadgePressed: {
backgroundColor: colors.surfaceElevated,
},
snoozedBadgeText: {
...typography.caption,
color: colors.accent,
fontWeight: "600",
flex: 1,
marginLeft: spacing.sm,
},
});
21 changes: 20 additions & 1 deletion src/components/AlarmCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ import type { Alarm } from "@/data/types";
import { colors, radii, spacing, typography } from "@/theme";
import { formatTime, getDaysString } from "@/utils/time";

const taskIcons = {
Math: "sigma",
Memory: "brain",
"Shake phone": "vibrate",
None: "alarm-clock",
} as const;

interface AlarmCardProps {
alarm: Alarm;
editEnabled: boolean;
Expand All @@ -36,7 +43,14 @@ export function AlarmCard({
>
<View style={styles.left}>
<Text style={styles.time}>{formatTime(alarm.hour, alarm.minute)}</Text>
<Text style={styles.days}>{getDaysString(alarm.days)}</Text>
<View style={styles.row}>
<Lucide
name={taskIcons[alarm.task]}
size={14}
color={colors.textMuted}
/>
<Text style={styles.days}>{getDaysString(alarm.days)}</Text>
</View>
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
</View>
{editEnabled ? (
<View style={[styles.checkbox, selected && styles.checkboxSelected]}>
Expand Down Expand Up @@ -82,6 +96,11 @@ const styles = StyleSheet.create({
flexDirection: "column",
gap: spacing.xs,
},
row: {
flexDirection: "row",
alignItems: "center",
gap: 4,
},
time: {
...typography.numeric,
color: colors.text,
Expand Down
69 changes: 67 additions & 2 deletions src/store/alarmStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ import {
import { db, dbReady } from "@/data/db";
import { alarmsTable } from "@/data/schema";
import type { Alarm } from "@/data/types";
import { getAlarmScheduler } from "@/alarms/AlarmScheduler";
import { snoozeIdentifierFor } from "@/alarms/weeklyTrigger";
import { useAlarmRegistrationsStore } from "@/store/alarmRegistrationsStore";

interface AlarmStoreState {
alarms: Alarm[];
loaded: boolean;
loading: boolean;
initError: string | null;
snoozedCount: number;
_disposer: (() => void) | null;
_initializing: boolean;
init: () => void;
Expand All @@ -25,6 +29,7 @@ interface AlarmStoreState {
deleteAlarm: (alarm: { id: string }) => Promise<void>;
getAlarmById: (id: string) => Promise<Alarm | null>;
getAllAlarms: () => Alarm[];
dismissAllSnoozedAlarms: () => Promise<number>;
}

export const useAlarmStore = create<AlarmStoreState>((set, get) => {
Expand All @@ -36,11 +41,20 @@ export const useAlarmStore = create<AlarmStoreState>((set, get) => {
set({ alarms: rows.map(rowToAlarm), loaded: true, loading: false });
};

const syncSnoozedCount = () => {
const registryState = useAlarmRegistrationsStore.getState();
const count = registryState.records.filter(
(r) => r.type === "snooze",
).length;
set({ snoozedCount: count });
};

return {
alarms: [],
loaded: false,
loading: false,
initError: null,
snoozedCount: 0,
_disposer: null,
_initializing: false,

Expand All @@ -60,10 +74,31 @@ export const useAlarmStore = create<AlarmStoreState>((set, get) => {
try {
await dbReady;
await fetchAlarms();
const subscription = SQLite.addDatabaseChangeListener((event) => {

const registryStore = useAlarmRegistrationsStore.getState();
if (!registryStore._disposer || !registryStore.loaded) {
registryStore.init();
}

syncSnoozedCount();

const dbSubscription = SQLite.addDatabaseChangeListener((event) => {
if (event.tableName === "alarms") void fetchAlarms();
});
set({ _disposer: () => subscription.remove() });

const unsubReg = useAlarmRegistrationsStore.subscribe((state) => {
const count = state.records.filter(
(r) => r.type === "snooze",
).length;
set({ snoozedCount: count });
});

set({
_disposer: () => {
dbSubscription.remove();
unsubReg();
},
});
} catch (e) {
console.error("alarmStore.init failed", e);
set({
Expand Down Expand Up @@ -112,5 +147,35 @@ export const useAlarmStore = create<AlarmStoreState>((set, get) => {
},

getAllAlarms: () => get().alarms,

dismissAllSnoozedAlarms: async () => {
const registryStore = useAlarmRegistrationsStore.getState();
const snoozedIds = registryStore.records
.filter((r) => r.type === "snooze")
.map((r) => r.alarmId);

if (snoozedIds.length === 0) return 0;

const native = getAlarmScheduler();

const results = await Promise.allSettled(
snoozedIds.map(async (alarmId) => {
await native.cancel(snoozeIdentifierFor(alarmId));
await registryStore.remove(alarmId, "snooze");
}),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
);

const failed = results.filter((r) => r.status === "rejected").length;
if (failed > 0) {
console.error(
`Failed to dismiss ${failed} snoozed alarm(s)`,
results
.filter((r) => r.status === "rejected")
.map((r) => (r as PromiseRejectedResult).reason),
);
}

return snoozedIds.length - failed;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
};
});