diff --git a/drizzle/0004_striped_exiles.sql b/drizzle/0004_striped_exiles.sql new file mode 100644 index 0000000..53f293a --- /dev/null +++ b/drizzle/0004_striped_exiles.sql @@ -0,0 +1 @@ +ALTER TABLE `alarm_registrations` ADD `generation` integer DEFAULT 0 NOT NULL; \ No newline at end of file diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..202fd65 --- /dev/null +++ b/drizzle/meta/0004_snapshot.json @@ -0,0 +1,190 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "dcab48f9-720d-491d-9c88-0ef7fcbfeb3a", + "prevId": "c3f2a9e1-4d5b-48f6-a7c8-9b0d1e2f3a4b", + "tables": { + "active_alarm": { + "name": "active_alarm", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "payload": { + "name": "payload", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alarm_registrations": { + "name": "alarm_registrations", + "columns": { + "alarm_id": { + "name": "alarm_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": { + "alarm_registrations_alarm_id_type_pk": { + "columns": [ + "alarm_id", + "type" + ], + "name": "alarm_registrations_alarm_id_type_pk" + } + }, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "alarms": { + "name": "alarms", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "days": { + "name": "days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hour": { + "name": "hour", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "minute": { + "name": "minute", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "task": { + "name": "task", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "rounds": { + "name": "rounds", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "difficulty": { + "name": "difficulty", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "sound": { + "name": "sound", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_snooze": { + "name": "is_snooze", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_enabled": { + "name": "is_enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 3f8259a..6fe5407 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1785933857428, "tag": "0003_misty_moon", "breakpoints": true + }, + { + "idx": 4, + "version": "6", + "when": 1786532266738, + "tag": "0004_striped_exiles", + "breakpoints": true } ] } \ No newline at end of file diff --git a/drizzle/migrations.js b/drizzle/migrations.js index c344646..7be1ebf 100644 --- a/drizzle/migrations.js +++ b/drizzle/migrations.js @@ -5,6 +5,7 @@ import m0000 from "./0000_large_vulture.sql"; import m0001 from "./0001_equal_jetstream.sql"; import m0002 from "./0002_bent_zemo.sql"; import m0003 from "./0003_misty_moon.sql"; +import m0004 from "./0004_striped_exiles.sql"; export default { journal, @@ -13,5 +14,6 @@ export default { m0001, m0002, m0003, + m0004, }, }; diff --git a/src/app/(alarm)/alarm.tsx b/src/app/(alarm)/alarm.tsx index 566e735..5c72852 100644 --- a/src/app/(alarm)/alarm.tsx +++ b/src/app/(alarm)/alarm.tsx @@ -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"; @@ -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 ( @@ -102,9 +111,7 @@ export default function AlarmDisplay() { return ( - - {formatTime(effectiveSnapshot.hour, effectiveSnapshot.minute)} - + {currentTime} {effectiveSnapshot.isSnoozed ? "Snoozed alarm" : "Alarm"} diff --git a/src/app/(main)/index.tsx b/src/app/(main)/index.tsx index 54b536b..fdff262 100644 --- a/src/app/(main)/index.tsx +++ b/src/app/(main)/index.tsx @@ -28,6 +28,8 @@ export default function Home() { const [selectedIds, setSelectedIds] = useState>(() => new Set()); const [now, setNow] = useState(() => new Date()); + const snoozedCount = useAlarmStore((s) => s.snoozedCount); + useEffect(() => { useAlarmStore.getState().loadAlarms(); }, []); @@ -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); @@ -199,6 +229,24 @@ export default function Home() { {countdown} + {snoozedCount > 0 ? ( + [ + styles.snoozedBadge, + pressed && styles.snoozedBadgePressed, + ]} + accessibilityRole="button" + accessibilityLabel={`${snoozedCount} snoozed alarm${snoozedCount > 1 ? "s" : ""}`} + onPress={dismissSnoozed} + > + + + {snoozedCount} snoozed alarm{snoozedCount > 1 ? "s" : ""} + + + + ) : null} + [styles.card, pressed && styles.cardPressed]} onPress={() => onPress(alarm)} onLongPress={() => onLongPress(alarm)} + accessibilityLabel={`${formatTime(alarm.hour, alarm.minute)} alarm, ${alarm.task} task, ${getDaysString(alarm.days)}`} > {formatTime(alarm.hour, alarm.minute)} - {getDaysString(alarm.days)} + + + {getDaysString(alarm.days)} + {editEnabled ? ( @@ -82,6 +97,11 @@ const styles = StyleSheet.create({ flexDirection: "column", gap: spacing.xs, }, + row: { + flexDirection: "row", + alignItems: "center", + gap: 4, + }, time: { ...typography.numeric, color: colors.text, diff --git a/src/data/schema.ts b/src/data/schema.ts index da2a0f0..5c50409 100644 --- a/src/data/schema.ts +++ b/src/data/schema.ts @@ -26,6 +26,7 @@ export const alarmRegistrationsTable = sqliteTable( { alarmId: text("alarm_id").notNull(), type: text("type").notNull(), + generation: integer("generation").notNull().default(0), }, (table) => ({ pk: primaryKey({ columns: [table.alarmId, table.type] }), diff --git a/src/store/alarmRegistrationsStore.ts b/src/store/alarmRegistrationsStore.ts index 9f70b56..a6b790c 100644 --- a/src/store/alarmRegistrationsStore.ts +++ b/src/store/alarmRegistrationsStore.ts @@ -1,5 +1,5 @@ import * as SQLite from "expo-sqlite"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { create } from "zustand"; import { db, dbReady } from "@/data/db"; import { alarmRegistrationsTable } from "@/data/schema"; @@ -9,6 +9,7 @@ export type RegistrationType = "weekly" | "snooze"; export interface RegistrationRecord { alarmId: string; type: RegistrationType; + generation: number; } interface AlarmRegistrationsStoreState { @@ -36,6 +37,7 @@ export const useAlarmRegistrationsStore = create( records: rows.map((r) => ({ alarmId: r.alarmId, type: r.type as RegistrationType, + generation: r.generation, })), loaded: true, loading: false, @@ -91,20 +93,30 @@ export const useAlarmRegistrationsStore = create( upsert: async (alarmId, type) => { await dbReady; - await db + const [returned] = await db .insert(alarmRegistrationsTable) - .values({ alarmId, type }) + .values({ alarmId, type, generation: 0 }) .onConflictDoUpdate({ target: [ alarmRegistrationsTable.alarmId, alarmRegistrationsTable.type, ], - set: { alarmId, type }, - }); - const records = get().records; - if (!records.some((r) => r.alarmId === alarmId && r.type === type)) { - set({ records: [...records, { alarmId, type }] }); - } + set: { generation: sql`generation + 1` }, + }) + .returning(); + const generation = returned.generation; + const exists = get().records.some( + (r) => r.alarmId === alarmId && r.type === type, + ); + set({ + records: exists + ? get().records.map((r) => + r.alarmId === alarmId && r.type === type + ? { ...r, generation } + : r, + ) + : [...get().records, { alarmId, type, generation }], + }); }, remove: async (alarmId, type) => { diff --git a/src/store/alarmStore.ts b/src/store/alarmStore.ts index 5ee62dc..3dd8da1 100644 --- a/src/store/alarmStore.ts +++ b/src/store/alarmStore.ts @@ -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; @@ -25,6 +29,7 @@ interface AlarmStoreState { deleteAlarm: (alarm: { id: string }) => Promise; getAlarmById: (id: string) => Promise; getAllAlarms: () => Alarm[]; + dismissAllSnoozedAlarms: () => Promise; } export const useAlarmStore = create((set, get) => { @@ -36,11 +41,20 @@ export const useAlarmStore = create((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, @@ -60,10 +74,31 @@ export const useAlarmStore = create((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({ @@ -112,5 +147,43 @@ export const useAlarmStore = create((set, get) => { }, getAllAlarms: () => get().alarms, + + dismissAllSnoozedAlarms: async () => { + const registryStore = useAlarmRegistrationsStore.getState(); + const snoozed = registryStore.records + .filter((r) => r.type === "snooze") + .map((r) => ({ alarmId: r.alarmId, generation: r.generation })); + + if (snoozed.length === 0) return 0; + + const native = getAlarmScheduler(); + + const results = await Promise.allSettled( + snoozed.map(async ({ alarmId, generation }) => { + const current = useAlarmRegistrationsStore + .getState() + .records.find((r) => r.alarmId === alarmId && r.type === "snooze"); + if (!current || current.generation !== generation) { + return; + } + await native.cancel(snoozeIdentifierFor(alarmId)); + await registryStore.remove(alarmId, "snooze"); + }), + ); + + const rejected = results.filter((r) => r.status === "rejected"); + const failed = rejected.length; + if (failed > 0) { + const reasons = rejected.map( + (r) => (r as PromiseRejectedResult).reason, + ); + console.error(`Failed to dismiss ${failed} snoozed alarm(s)`, reasons); + throw new Error( + `Failed to dismiss ${failed} snoozed alarm(s): ${reasons.join(", ")}`, + ); + } + + return results.filter((r) => r.status === "fulfilled").length; + }, }; }); diff --git a/src/utils/time.ts b/src/utils/time.ts index 9735790..fce67df 100644 --- a/src/utils/time.ts +++ b/src/utils/time.ts @@ -60,7 +60,7 @@ export function computeNextAlarm( .second(0) .millisecond(0); const adjusted = - candidate.valueOf() < nowDayjs.valueOf() + candidate.valueOf() <= nowDayjs.valueOf() ? candidate.add(7, "day") : candidate; const ms = adjusted.valueOf() - nowDayjs.valueOf(); diff --git a/test/unit/utils/time.test.ts b/test/unit/utils/time.test.ts new file mode 100644 index 0000000..7e86d77 --- /dev/null +++ b/test/unit/utils/time.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "@jest/globals"; +import type { Alarm } from "@/data/types"; +import { computeNextAlarm } from "@/utils/time"; + +function baseAlarm(over: Partial = {}): Alarm { + return { + id: "alarm-1", + days: [], + hour: 8, + minute: 0, + task: "Memory", + rounds: 1, + difficulty: "Easy", + sound: null, + snooze: true, + enabled: true, + ...over, + }; +} + +describe("computeNextAlarm", () => { + it("returns null when no alarms are enabled", () => { + const now = new Date(2024, 0, 3, 10, 0, 0, 0); + expect(computeNextAlarm([baseAlarm({ enabled: false })], now)).toBeNull(); + }); + + it("returns null when alarms list is empty", () => { + const now = new Date(2024, 0, 3, 10, 0, 0, 0); + expect(computeNextAlarm([], now)).toBeNull(); + }); + + describe("boundary conditions", () => { + const now = new Date(2024, 0, 3, 10, 0, 0, 0); + + it("rolls forward one week when candidate equals now", () => { + const result = computeNextAlarm( + [baseAlarm({ days: ["Wed"], hour: 10, minute: 0 })], + now, + ); + expect(result).toEqual({ days: 7, hours: 0, minutes: 0 }); + }); + + it("does not roll forward when candidate is one minute after now", () => { + const result = computeNextAlarm( + [baseAlarm({ days: ["Wed"], hour: 10, minute: 1 })], + now, + ); + expect(result).toEqual({ days: 0, hours: 0, minutes: 1 }); + }); + + it("rolls forward one week when candidate is one minute before now", () => { + const result = computeNextAlarm( + [baseAlarm({ days: ["Wed"], hour: 9, minute: 59 })], + now, + ); + expect(result).toEqual({ days: 6, hours: 23, minutes: 59 }); + }); + }); +});