From bf1e181c9828cb2915e7b0dbe4efceba68106c8f Mon Sep 17 00:00:00 2001 From: Jason LaRue Date: Sat, 7 Nov 2026 10:39:19 -0500 Subject: [PATCH 1/4] feat(alarms): save alarm edits as you make them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changing an alarm only took effect after pressing Save; closing the editor any other way dropped the change, so an alarm moved from 7:30 to 9:30 still went off at 7:30. The editor now saves as you go: an existing alarm saves SAVE_DELAY_MS (600 ms) after the last change, a new one as soon as it has a day, and Done (or closing) saves a waiting change at once. Save and Cancel become a single Done button, with a Saving…/Saved status. Each save replaces the alarm's rows, so batchUpdate now returns the IDs of the rows it created (in input order) and the editor keeps editing those. Saves run one at a time. The alarm coming back from the parent with its new rows doesn't reset an edit in progress, a different alarm still loads, and an alarm opened and closed unchanged isn't saved. If a save fails, closing keeps the editor open with the error instead of dropping the change. Delete waits for a waiting save and deletes the latest rows. Co-Authored-By: Claude Opus 5.5 --- src/components/Schedule/AlarmEditor.tsx | 170 +++++++++++++----- .../Schedule/tests/AlarmEditor.test.tsx | 90 ++++++++-- .../Schedule/tests/AlarmSection.test.tsx | 4 +- src/demo/handlers/schedules.ts | 21 ++- src/demo/tests/schedules.test.ts | 6 +- src/server/routers/schedules.ts | 17 +- src/server/routers/tests/schedules.test.ts | 17 +- 7 files changed, 251 insertions(+), 74 deletions(-) diff --git a/src/components/Schedule/AlarmEditor.tsx b/src/components/Schedule/AlarmEditor.tsx index 2fd91c060..30de4115f 100644 --- a/src/components/Schedule/AlarmEditor.tsx +++ b/src/components/Schedule/AlarmEditor.tsx @@ -90,8 +90,17 @@ function shiftTime(time: string, minutes: number): string { * Alarm editor (Dialog on desktop, Sheet on phones). * - Each saved alarm produces one row per selected day × side (same time/pattern/intensity/duration/temp). * - "Test" fires `device.setAlarm` immediately so the user can feel it; "Stop" clears it. - * - On save, delete-then-create: removes existing rows for this group then writes new ones. + * - Saves as you go: SAVE_DELAY_MS after the last change (at once on Done or + * close), delete-then-create — the previous save's rows are replaced by new + * ones. Saves run one at a time, each replacing the rows the last created, + * so an edit the user never confirms can't be lost. A new alarm is first + * saved once it has a day. */ +/** Quiet time after the last change before it is saved. */ +export const SAVE_DELAY_MS = 600 + +type SaveState = 'idle' | 'pending' | 'saving' | 'saved' | 'error' + export function AlarmEditor({ open, onClose, @@ -123,19 +132,47 @@ export function AlarmEditor({ const snoozeMinutes = snoozeDuration / 60 const [snoozeTaper, setSnoozeTaper] = useState(0) const [saveError, setSaveError] = useState(null) + const [saveState, setSaveState] = useState('idle') const [testing, setTesting] = useState(false) + // Rows this alarm currently has: the group's when opened, then whatever + // the last save created. Every save replaces exactly these. + const rowIds = useRef([]) + // Paused state is kept through edits; new alarms start enabled. + const enabledRef = useRef(true) + // Saves run one at a time, in order. + const queue = useRef>(Promise.resolve()) + // The draft last saved (JSON), so an unchanged form isn't saved again. + const savedDraft = useRef(null) + // Bumped each time the form loads; the render showing that load is the + // saved state, not an edit. + const [loadGeneration, setLoadGeneration] = useState(0) + const baselineGeneration = useRef(0) + const timer = useRef | undefined>(undefined) + const saveFailed = useRef(false) + // Load the form when it opens, or when a different alarm is passed in. Not // on every new `existingGroup` object: callers rebuild it on each render - // (the home screen re-renders with every status update), which reset any - // edit in progress back to the saved values. + // (the home screen re-renders with every status update), and after each + // save the group comes back with the rows that save created — neither may + // reset an edit in progress. const loadedFrom = useRef(null) useEffect(() => { - const source = !open ? null : existingGroup ? `edit:${existingGroup.ids.join(',')}` : 'new' + const key = (ids: number[]) => `edit:${[...ids].sort((a, b) => a - b).join(',')}` + const source = !open ? null : existingGroup ? key(existingGroup.ids) : 'new' if (source === loadedFrom.current) return + if (source !== null && loadedFrom.current !== null && source === key(rowIds.current)) { + loadedFrom.current = source + return + } loadedFrom.current = source if (source === null) return + rowIds.current = existingGroup?.ids ?? [] + enabledRef.current = existingGroup?.enabled ?? true + savedDraft.current = null + saveFailed.current = false /* eslint-disable react-hooks/set-state-in-effect */ + setLoadGeneration(g => g + 1) if (existingGroup) { setDays(new Set(existingGroup.days)) setTime(existingGroup.time) @@ -161,6 +198,7 @@ export function AlarmEditor({ setSnoozeTaper(0) } setSaveError(null) + setSaveState('idle') setTesting(false) /* eslint-enable react-hooks/set-state-in-effect */ }, [open, existingGroup, side, defaultSide, unit, defaultDisplayTemp]) @@ -170,7 +208,6 @@ export function AlarmEditor({ const clearAlarm = trpc.device.clearAlarm.useMutation() const utils = trpc.useUtils() - const isMutating = batchUpdate.isPending const sides = useMemo( () => (singleSleeperSide ? [singleSleeperSide] : targetSide === 'both' ? ['left', 'right'] : [targetSide]), [singleSleeperSide, targetSide], @@ -191,18 +228,11 @@ export function AlarmEditor({ setTesting(false) }, [clearAlarm, sides]) - const handleSave = useCallback(async () => { - if (days.size === 0) { - setSaveError('Pick at least one day') - return - } - setSaveError(null) - - const targetDays = Array.from(days) + // What the form would save now, or null while it has no day to save. + const draft = useMemo(() => { + if (days.size === 0) return null const temperatureF = Math.round(displayToSetpointF(displayTemperature, unit) ?? DEFAULT_TEMP) - // Preserve enabled state when editing a paused alarm; new alarms default to enabled. - const enabled = existingGroup?.enabled ?? true - const creates = sides.flatMap(s => targetDays.map(dayOfWeek => ({ + return sides.flatMap(s => Array.from(days).map(dayOfWeek => ({ side: s, dayOfWeek, time, @@ -213,23 +243,77 @@ export function AlarmEditor({ wakeWindow, snoozeDuration, snoozeTaper, - enabled, }))) + }, [days, sides, time, intensity, pattern, duration, displayTemperature, wakeWindow, snoozeDuration, snoozeTaper, unit]) - try { - await batchUpdate.mutateAsync({ - deletes: { alarm: existingGroup?.ids ?? [] }, - creates: { alarm: creates }, - }) - void utils.schedules.getAll.invalidate() - void utils.schedules.getByDay.invalidate() - onSaved?.() - onClose() - } - catch (err) { - setSaveError(err instanceof Error ? err.message : 'Failed to save alarm') + const { mutateAsync } = batchUpdate + + const save = useCallback((rows: NonNullable) => { + const snapshot = JSON.stringify(rows) + queue.current = queue.current.then(async () => { + if (snapshot === savedDraft.current) return + setSaveState('saving') + try { + const result = await mutateAsync({ + deletes: { alarm: rowIds.current }, + creates: { alarm: rows.map(r => ({ ...r, enabled: enabledRef.current })) }, + }) + rowIds.current = result?.created?.alarm ?? [] + savedDraft.current = snapshot + saveFailed.current = false + setSaveError(null) + setSaveState('saved') + void utils.schedules.getAll.invalidate() + void utils.schedules.getByDay.invalidate() + onSaved?.() + } + catch (err) { + saveFailed.current = true + setSaveError(err instanceof Error ? err.message : 'Failed to save alarm') + setSaveState('error') + } + }) + return queue.current + }, [mutateAsync, utils, onSaved]) + + // Save each change once the user pauses. The first draft after the form + // loads is what an existing alarm already has saved. + useEffect(() => { + if (!open) return + if (baselineGeneration.current !== loadGeneration) { + baselineGeneration.current = loadGeneration + savedDraft.current = existingGroup && draft ? JSON.stringify(draft) : null + return } - }, [days, sides, time, intensity, pattern, duration, displayTemperature, wakeWindow, snoozeDuration, snoozeTaper, unit, existingGroup, batchUpdate, utils, onSaved, onClose]) + if (!draft || JSON.stringify(draft) === savedDraft.current) return + + setSaveState('pending') + clearTimeout(timer.current) + timer.current = setTimeout(() => { + void save(draft) + }, SAVE_DELAY_MS) + return () => clearTimeout(timer.current) + }, [open, draft, save, existingGroup, loadGeneration]) + + /** Save a waiting change now (Done, close, delete). */ + const flush = useCallback(() => { + clearTimeout(timer.current) + if (draft && JSON.stringify(draft) !== savedDraft.current) return save(draft) + return queue.current + }, [draft, save]) + + // Closing saves a waiting change first; a failed save keeps the editor open + // with its error rather than dropping the change. + const handleClose = useCallback(async () => { + await flush() + if (!saveFailed.current) onClose() + }, [flush, onClose]) + + const handleDelete = useCallback(async () => { + if (!existingGroup || !onRequestDelete) return + await flush() + onRequestDelete({ ...existingGroup, ids: rowIds.current }) + }, [existingGroup, onRequestDelete, flush]) const clock = formatTime(time) const [clockDigits, clockPeriod] = clock.split(' ') @@ -237,7 +321,7 @@ export function AlarmEditor({ return ( void handleClose()} title={isEdit ? 'Edit alarm' : 'New alarm'} icon={Bell} iconClassName="text-warn" @@ -252,23 +336,29 @@ export function AlarmEditor({ )} {isEdit && existingGroup && onRequestDelete && ( - )} -
- - +
+ + {saveState === 'saving' || saveState === 'pending' + ? ( + <> + + Saving… + + ) + : saveState === 'saved' ? 'Saved' : days.size === 0 ? 'Pick a day to save' : ''} + +
)} >
{timeFormat === '24h' - ? + ? : (