Files
KCal/public/js/calendar.js
T
ort 1768ce7740 Add per-task timers with milestone audio for ADHD-friendly time awareness
Every task now has a duration (10 min default) and a child-initiated start:
a play icon on the kiosk, alongside the checkbox, begins a server-anchored
countdown for that specific task. Deliberately not a beep-every-minute
alarm -- audio is milestone-only (start/halfway/almost-done/time's-up),
since frequent interrupting alerts can backfire for ADHD kids rather than
help. Countdown is drift-free (recomputed each tick from the fixed
started_at anchor, never decremented), audio is synthesized client-side
via Web Audio (zero external assets, matching this app's existing
hand-rolled-PNG-icon philosophy), and the child's own start tap is what
unlocks audio playback for the rest of the session on iOS.

Two real bugs caught and fixed during design, before they shipped:
- Marking a task done now clears started_at (both the kiosk and parent
  routes) -- without this, unchecking a finished task later would
  resurrect a stale timer and instantly show "time's up" on a task the
  child hasn't touched today.
- The parent editor's poll-pause guard only covered contenteditable
  fields; a plain number input for duration would have been silently
  unprotected from being clobbered by an incoming 4s poll mid-edit.
  Extended the guard to cover it, verified live that the DOM and focus
  both survive a poll while the field is focused.

Schema: calendar_tasks gains duration_minutes (NOT NULL DEFAULT 10) and
started_at (nullable). Verified against a simulated copy of the real
production schema/data that the static DEFAULT backfills every existing
row automatically (no business-logic backfill needed, unlike is_admin),
and that repeated boots stay idempotent. Duplicate-calendar carries
durations forward but always resets started_at, verified end-to-end.

Kiosk countdown/milestone-firing verified live in-browser end-to-end: real
timer start, halfway/almost-done/done firing at the correct proportional
thresholds (not fixed minutes, so it scales from ~1min to 20+min tasks),
and a mid-countdown page reload resuming at the correct remaining time
with already-passed milestones backfilled silently rather than replayed.
2026-08-16 11:29:22 -04:00

163 lines
6.5 KiB
JavaScript

const calendarId = new URLSearchParams(window.location.search).get('calendarId');
let calendar = null;
const weekdayBoard = document.getElementById('weekdayBoard');
const weekendWrap = document.getElementById('weekendWrap');
const legend = document.getElementById('legend');
const toast = document.getElementById('toast');
function showToast(msg) {
toast.textContent = msg;
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 1800);
}
function debounce(fn, ms) {
let t;
return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
const handlers = {
onToggleDone: (taskId, done) => api.patch(`/api/calendars/${calendarId}/tasks/${taskId}`, { done }).catch(() => showToast('Could not save')),
onTextEdit: (taskId, text) => api.patch(`/api/calendars/${calendarId}/tasks/${taskId}`, { text }).catch(() => showToast('Could not save')),
onLabelEdit: (blockKey, label) => api.patch(`/api/calendars/${calendarId}/blocks/${blockKey}`, { label }).catch(() => showToast('Could not save')),
onAddTask: async (dayOfWeek, blockKey, text) => {
const { task } = await api.post(`/api/calendars/${calendarId}/tasks`, { dayOfWeek, blockKey, text });
return task;
},
onDeleteTask: (taskId) => api.del(`/api/calendars/${calendarId}/tasks/${taskId}`).catch(() => showToast('Could not delete')),
onDurationEdit: (taskId, durationMinutes) => api.patch(`/api/calendars/${calendarId}/tasks/${taskId}`, { durationMinutes }).catch(() => showToast('Could not save')),
};
function todayName() {
return new Date().toLocaleDateString('en-US', { weekday: 'long' });
}
function draw() {
const childNameEl = document.getElementById('childName');
if (document.activeElement !== childNameEl) childNameEl.textContent = calendar.childName || '';
const titleEl = document.getElementById('calTitle');
if (document.activeElement !== titleEl) titleEl.textContent = calendar.title;
renderCalendar({
calendar,
editable: true,
weekdayBoard,
weekendWrap,
handlers,
todayName: todayName(),
});
renderLegend(legend, calendar);
weekendWrap.classList.toggle('hidden', !calendar.showWeekend);
document.getElementById('toggleWeekend').textContent = calendar.showWeekend ? 'Hide weekend' : 'Show weekend';
buildPeriodToggles();
}
function buildPeriodToggles() {
const el = document.getElementById('periodToggles');
el.querySelectorAll('label.opt').forEach((n) => n.remove());
calendar.blocks.forEach((block) => {
const label = document.createElement('label');
label.className = 'opt';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.checked = !document.body.classList.contains('hide-' + block.key);
cb.onchange = () => document.body.classList.toggle('hide-' + block.key, !cb.checked);
const span = document.createElement('span');
span.textContent = block.label;
label.appendChild(cb);
label.appendChild(span);
el.appendChild(label);
});
}
async function load() {
if (!calendarId) {
document.body.innerHTML = '<p style="padding:40px;">No calendar selected. <a href="/dashboard.html">Back to dashboard</a></p>';
return;
}
try {
const data = await api.get(`/api/calendars/${calendarId}`);
calendar = data.calendar;
} catch (err) {
if (err.status === 401) { window.location.href = '/login.html'; return; }
document.body.innerHTML = `<p style="padding:40px;">${err.message}. <a href="/dashboard.html">Back to dashboard</a></p>`;
return;
}
draw();
}
document.getElementById('toggleWeekend').addEventListener('click', async () => {
calendar.showWeekend = !calendar.showWeekend;
weekendWrap.classList.toggle('hidden', !calendar.showWeekend);
document.getElementById('toggleWeekend').textContent = calendar.showWeekend ? 'Hide weekend' : 'Show weekend';
await api.patch(`/api/calendars/${calendarId}`, { showWeekend: calendar.showWeekend });
});
document.getElementById('resetChecks').addEventListener('click', async () => {
const data = await api.post(`/api/calendars/${calendarId}/reset-checks`);
calendar = data.calendar;
draw();
showToast('Checkboxes reset');
});
document.getElementById('printBtn').addEventListener('click', () => window.print());
const titleEl = document.getElementById('calTitle');
titleEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); titleEl.blur(); } });
const debouncedTitleSave = debounce(() => {
if (titleEl.textContent.trim()) api.patch(`/api/calendars/${calendarId}`, { title: titleEl.textContent.trim() });
}, 500);
titleEl.addEventListener('input', debouncedTitleSave);
const childNameEl = document.getElementById('childName');
childNameEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); childNameEl.blur(); } });
const debouncedChildNameSave = debounce(() => {
if (childNameEl.textContent.trim()) api.patch(`/api/children/${calendar.childId}`, { name: childNameEl.textContent.trim() });
}, 500);
childNameEl.addEventListener('input', debouncedChildNameSave);
// Polling keeps this view in sync with kiosk checkbox taps (and the other
// parent's edits) without a manual reload. Paused while the parent is mid-edit
// in any contenteditable field, so an incoming poll can't yank their cursor.
function isEditableTarget(el) {
// isContentEditable covers task/label/title/child-name text; duration is a
// plain <input type=number> instead (isContentEditable is always false for
// form fields), so it needs its own explicit check — a narrow class match
// rather than a blanket tag check, so unrelated inputs elsewhere (e.g. the
// period-toggle checkboxes, which commit instantly and don't need this)
// aren't also paused.
return !!el && (el.isContentEditable || el.classList.contains('duration-input'));
}
let isEditingFocused = false;
document.addEventListener('focusin', (e) => {
if (isEditableTarget(e.target)) isEditingFocused = true;
});
document.addEventListener('focusout', (e) => {
if (isEditableTarget(e.target)) {
setTimeout(() => {
isEditingFocused = isEditableTarget(document.activeElement);
}, 0);
}
});
async function poll() {
if (!calendar || isEditingFocused || document.hidden) return;
try {
const data = await api.get(`/api/calendars/${calendarId}/poll?since=${encodeURIComponent(calendar.updatedAt)}`);
if (data.changed) {
calendar = data.calendar;
draw();
}
} catch (err) {
if (err.status === 401) window.location.href = '/login.html';
}
}
setInterval(poll, 4000);
document.addEventListener('visibilitychange', () => { if (!document.hidden) poll(); });
load();