diff --git a/src/components/Schedule/AlarmEditor.tsx b/src/components/Schedule/AlarmEditor.tsx index 2fd91c060..1673738aa 100644 --- a/src/components/Schedule/AlarmEditor.tsx +++ b/src/components/Schedule/AlarmEditor.tsx @@ -90,8 +90,39 @@ 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. Saving an edit turns a paused alarm back on. */ +/** Quiet time after the last change before it is saved. */ +export const SAVE_DELAY_MS = 600 + +type SaveState = 'idle' | 'pending' | 'saving' | 'saved' | 'error' + +/** One opened alarm's saves. Each load starts a new one, so a save still + * running for the previous alarm can't touch the rows of the next. */ +interface SaveSession { + /** Rows the alarm has now: the group's when opened, then whatever the + * last save created. Every save replaces exactly these. */ + rowIds: number[] + /** Days those rows are on, for the delete confirmation. */ + days: DayOfWeek[] + /** Every row this session created, so a refetch still showing an earlier + * save's rows, or only this side's rows of a "Both" save, isn't taken for a + * different alarm. */ + ownIds: Set + /** The draft last saved (JSON), so an unchanged form isn't saved again. */ + saved: string | null + /** The draft last queued (JSON), so a change isn't queued twice. */ + queued: string | null + failed: boolean +} + +const rowKey = (ids: number[]) => `edit:${[...ids].sort((a, b) => a - b).join(',')}` +const newSession = (rowIds: number[], days: DayOfWeek[]): SaveSession => ({ rowIds, days, ownIds: new Set(), saved: null, queued: null, failed: false }) + export function AlarmEditor({ open, onClose, @@ -123,19 +154,43 @@ 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) + // Done was pressed on a saved alarm with every day cleared. + const [needsDay, setNeedsDay] = useState(false) + + const session = useRef(newSession([], [])) + // The alarm has saved rows (opened on them, or a save created them), so it + // can be deleted. + const [hasRows, setHasRows] = useState(false) + // Saves run one at a time, in order. + const queue = useRef>(Promise.resolve()) + // 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) // 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 (only this + // side's, after a "Both" save) — neither may reset an edit in progress. const loadedFrom = useRef(null) useEffect(() => { - const source = !open ? null : existingGroup ? `edit:${existingGroup.ids.join(',')}` : 'new' + const source = !open ? null : existingGroup ? rowKey(existingGroup.ids) : 'new' if (source === loadedFrom.current) return + const own = session.current.ownIds + if (source !== null && existingGroup && loadedFrom.current !== null && existingGroup.ids.length > 0 && existingGroup.ids.every(id => own.has(id))) { + loadedFrom.current = source + return + } loadedFrom.current = source if (source === null) return + session.current = newSession(existingGroup?.ids ?? [], existingGroup?.days ?? []) /* eslint-disable react-hooks/set-state-in-effect */ + setLoadGeneration(g => g + 1) + setHasRows((existingGroup?.ids.length ?? 0) > 0) if (existingGroup) { setDays(new Set(existingGroup.days)) setTime(existingGroup.time) @@ -161,7 +216,9 @@ export function AlarmEditor({ setSnoozeTaper(0) } setSaveError(null) + setSaveState('idle') setTesting(false) + setNeedsDay(false) /* eslint-enable react-hooks/set-state-in-effect */ }, [open, existingGroup, side, defaultSide, unit, defaultDisplayTemp]) @@ -170,7 +227,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 +247,13 @@ 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 => ({ + // Week order, whatever order the days were picked in, so the same days + // always make the same draft. + return sides.flatMap(s => DAY_ORDER.filter(d => days.has(d)).map(dayOfWeek => ({ side: s, dayOfWeek, time, @@ -213,23 +264,150 @@ 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() + const { mutateAsync } = batchUpdate + + const save = useCallback((rows: NonNullable) => { + const saving = session.current + const isCurrent = () => saving === session.current + const snapshot = JSON.stringify(rows) + saving.queued = snapshot + queue.current = queue.current.then(async () => { + // Compared when its turn comes, after the saves queued before it. + if (snapshot === saving.saved) { + // Back to what is saved: nothing is left unsaved, even if a save in + // between failed. + saving.failed = false + if (isCurrent()) { + setSaveError(null) + setSaveState(state => (state === 'idle' ? state : 'saved')) + } + return + } + if (isCurrent()) setSaveState('saving') + try { + const result = await mutateAsync({ + deletes: { alarm: saving.rowIds }, + // Changing a paused alarm means it should ring again. + creates: { alarm: rows.map(r => ({ ...r, enabled: true })) }, + }) + saving.rowIds = result?.created?.alarm ?? [] + saving.days = DAY_ORDER.filter(d => rows.some(r => r.dayOfWeek === d)) + for (const id of saving.rowIds) saving.ownIds.add(id) + saving.saved = snapshot + saving.failed = false + if (isCurrent()) { + setSaveError(null) + setSaveState('saved') + setHasRows(saving.rowIds.length > 0) + } + void utils.schedules.getAll.invalidate() + void utils.schedules.getByDay.invalidate() + onSaved?.() + } + catch (err) { + saving.failed = true + if (isCurrent()) { + 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 + const baseline = existingGroup && draft ? JSON.stringify(draft) : null + session.current.saved = baseline + session.current.queued = baseline + return + } + if (!draft || JSON.stringify(draft) === session.current.queued) return + + setSaveState('pending') + clearTimeout(timer.current) + timer.current = setTimeout(() => { + void save(draft) + }, SAVE_DELAY_MS) + return () => clearTimeout(timer.current) + }, [open, draft, save, existingGroup, loadGeneration]) + + // The latest draft, for saves that wait on earlier ones. + const latestDraft = useRef(draft) + useEffect(() => { + latestDraft.current = draft + }, [draft]) + + /** Wait for every queued save, including any queued while waiting. */ + const settle = useCallback(async () => { + let pending: Promise + do { + pending = queue.current + await pending + } while (pending !== queue.current) + }, []) + + /** + * Save the form now (Done, close, delete): once the queue settles, save + * again while the form differs from what is saved, including changes made + * while it saves. Stops at a failed save, which keeps its error. + */ + const flush = useCallback(async () => { + for (;;) { + clearTimeout(timer.current) + await settle() + const rows = latestDraft.current + if (!rows) return + if (JSON.stringify(rows) === session.current.saved && !session.current.failed) return + await save(rows) + if (session.current.failed) return } - catch (err) { - setSaveError(err instanceof Error ? err.message : 'Failed to save alarm') + }, [save, settle]) + + // Closing saves the form first. A failed save keeps the editor open with + // its error rather than dropping the change, and a saved alarm can't be + // left with no day (it would keep its old days without saying so). + const handleClose = useCallback(async () => { + await flush() + // An alarm that never saved and now has no day has nothing to lose. + const abandoned = !latestDraft.current && session.current.rowIds.length === 0 + if (session.current.failed && !abandoned) return + if (!latestDraft.current && session.current.rowIds.length > 0) { + setNeedsDay(true) + return } - }, [days, sides, time, intensity, pattern, duration, displayTemperature, wakeWindow, snoozeDuration, snoozeTaper, unit, existingGroup, batchUpdate, utils, onSaved, onClose]) + onClose() + }, [flush, onClose]) + + // Deletes the rows the alarm has now, on the days they're on (a new alarm + // has no group yet, so it is described by the form). + const handleDelete = useCallback(async () => { + if (!onRequestDelete) return + await flush() + const { rowIds, days: savedDays } = session.current + onRequestDelete({ + ...(existingGroup ?? { + time, + vibrationIntensity: intensity, + vibrationPattern: pattern, + duration, + alarmTemperature: Math.round(displayToSetpointF(displayTemperature, unit) ?? DEFAULT_TEMP), + wakeWindow, + snoozeDuration, + snoozeTaper, + enabled: true, + }), + ids: rowIds, + days: savedDays, + }) + }, [existingGroup, onRequestDelete, flush, time, intensity, pattern, duration, displayTemperature, unit, wakeWindow, snoozeDuration, snoozeTaper]) const clock = formatTime(time) const [clockDigits, clockPeriod] = clock.split(' ') @@ -237,7 +415,7 @@ export function AlarmEditor({ return ( void handleClose()} title={isEdit ? 'Edit alarm' : 'New alarm'} icon={Bell} iconClassName="text-warn" @@ -251,24 +429,30 @@ export function AlarmEditor({ : ( )} - {isEdit && existingGroup && onRequestDelete && ( - )} -
- - +
+ + {saveState === 'saving' || saveState === 'pending' + ? ( + <> + + Saving… + + ) + : saveState === 'saved' ? 'Saved' : days.size === 0 ? 'Pick a day to save' : ''} + +
)} >
{timeFormat === '24h' - ? + ? : (