calendar
All repositories: gitoria
40.4 KB
// month-view.hl — THE MONTH VIEW: prev / next buttons on top, the month's name and the year between them, the// days below (weeks start on Monday; the days of the neighbouring months are dimmed; today is marked).// THE CALENDAR'S COPY of the pure-Hybriel month view of components.hybriel.worldapi.org (no .js), plus the user's// events on the days and the editor for them (add: click a day; edit / delete: click an event). Events come from// events.hl, one server round trip per change (faces calLoad / calSave / calDelete in calendar.hl). The date// arithmetic is written here (plain integers), so it runs the same on the server (first render) and in the browser.// What only the browser knows — today in the user's time zone, the month and weekday names in the user's language,// the time zone's name (`Date` and `Intl` are browser globals of View handlers) — is read the moment the pointer, a// finger or the keyboard reaches the month view; until then the server's UTC date and language-neutral names (month number, dots) show — the server never knows// the language, so it never guesses one: names appear once, in the browser's language, and stay.// The page reads `year` and `month` (1–12) as its own members. USE ONE PER PAGE: a composed component's// members are the page's state (COMPONENTS.md §12).import { serverToday } from './clock.hl'import { pad, daysIn, before } from './dates.hl'import { namesFor } from './names.hl'import { userIdOfSession } from '../../lib/users.hl'import { eventsBetween, upcoming } from '../../lib/events.hl'import { defaultsOf } from '../../lib/settings.hl'import { pushConfigured } from '../../lib/util.hl'import { notify, subscribePush } from 'hl:web'import { plan, missed, shift, describe, withIndex, defaultRows } from './reminders.hl'// the request's Accept-Language, handed in by the page (calendar.hl reads it from `headers`, hybriel #105): the first// render already writes the namesacceptLanguage = nullHybrid known = namesFor(acceptLanguage)Boolean namesKnown = known != nullString today = serverToday()Number year = toNumber(today.slice(0, 4))Number month = toNumber(today.slice(5, 7))Hybrid monthNames = namesKnown ? known.months : ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']Hybrid weekdayNames = namesKnown ? known.days : ['·', '·', '·', '·', '·', '·', '·']String title = monthNames[month - 1] + ' ' + yearHybrid base = build(year, month, today)Hybrid weekdays = weekdayNamessession = nulluserId = userIdOfSession(session)Boolean signedIn = userId != nullString winFirst = base[0].dateString winLast = base[41].dateHybrid events = signedIn ? eventsBetween(userId, winFirst, winLast) : []Hybrid days = fill(base, events)// the reminders (ticket calendar#4): the events of the next days with the reminders that apply (`soon`, kept with the page// state, so an offline page still knows them), the calendar's defaults in words, the timers the browser holdsHybrid soon = signedIn ? upcoming(userId, shift(today, -2), shift(today, 9)) : []String defaultText = signedIn ? describe(defaultsOf(userId)) : ''Hybrid defRows = signedIn ? defaultsOf(userId) : []Boolean fCustom = falseHybrid remRows = []Hybrid setRows = []Hybrid timers = []Number lastArm = 0// P1: arm() is called from several places at once (page load, pageshow, visibilitychange, the server's answer); its notify calls wait// for the browser, so a second run started in between showed the same missed reminder again and left timers behind. One at a time.Number arming = 0Number armAgain = 0String notifyState = 'unknown'String setError = ''String askClass = 'hidden'String blockedClass = 'hidden'String plannedText = ''String pushText = ''Boolean pushTried = falseBoolean pushAvailable = pushConfiguredString pushOffClass = 'hidden'Boolean pushIsOff = falseBoolean pushOn = falseString fId = ''String fTitle = ''Boolean fAllDay = falseString fStartDate = ''String fStartTime = '09:00'String fEndDate = ''String fEndTime = '10:00'String fPlace = ''String fNotes = ''String fZone = 'UTC'String formClass = 'closed'String formError = ''String formHeading = 'New event'Boolean isNew = trueString formKind = 'timed'String ownClass = 'quiet'String calClass = ''String defaultClass = ''String rowsClass = 'hidden'String addClass = 'quiet hidden'String timedButton = ''String alldayButton = 'quiet'String deleteClass = 'danger hidden'String prevLabel = namesKnown ? known.prev : '‹'String nextLabel = namesKnown ? known.next : '›'Number seen = 0Number paged = 0// 0 = Monday … 6 = Sunday (Sakamoto's method gives 0 = Sunday)weekdayOf(Number y, Number m, Number d) {t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]yy = m < 3 ? y - 1 : ysun = (yy + (yy - yy % 4) / 4 - (yy - yy % 100) / 100 + (yy - yy % 400) / 400 + t[m - 1] + d) % 7return (sun + 6) % 7}// 42 days (six weeks of seven), so the view keeps its height from month to monthbuild(Number y, Number m, String todayText) {py = m == 1 ? y - 1 : ypm = m == 1 ? 12 : m - 1ny = m == 12 ? y + 1 : ynm = m == 12 ? 1 : m + 1lead = weekdayOf(y, m, 1)n = daysIn(y, m)pn = daysIn(py, pm)out = []let day = 1 - leadlet w = 0while (w < 6) {let i = 0while (i < 7) {let cy = ylet cm = mlet cd = daylet cls = ''if (day < 1) { cy = py cm = pm cd = pn + day cls = 'outside' }if (day > n) { cy = ny cm = nm cd = day - n cls = 'outside' }date = cy + '-' + pad(cm) + '-' + pad(cd)if (date == todayText) { cls = 'today' }out.push({ n = cd date = date cls = cls })day = day + 1i = i + 1}w = w + 1}return out}// the events that touch a day, as four chips on the day cell (a nested `for` does not repaint when the outer list is// reassigned: hybriel #86 — so the chips are fixed members of the day: t = text, c = class, v = event id).// Timed events start with their time on the first day. More than four: the fourth chip says "+N more".fill(Hybrid list, Hybrid evs) {out = []let i = 0while (i < list.length) {d = list[i]hit = []let j = 0while (j < evs.length) {e = evs[j]if (!before(d.date, e.first) && !before(e.last, d.date)) { hit.push(e) }j = j + 1}row = { n = d.n date = d.date cls = d.cls }let k = 0while (k < 4) {let text = ''let cls = 'unused'let id = ''if (k < hit.length && (hit.length <= 4 || k < 3)) {e = hit[k]text = (e.allDay || d.date != e.first ? '' : e.startTime + ' ') + e.titlecls = 'event'id = e.id}if (k == 3 && hit.length > 4) { text = '+' + (hit.length - 3) + ' more' cls = 'more' }row['t' + k] = textrow['c' + k] = clsrow['v' + k] = idk = k + 1}out.push(row)i = i + 1}return out}// the form's fields for a new event on `date` (all text; allDay a Boolean); zone = the browser's time zone nameblank(String date, String zone) {return { id = '' title = '' allDay = false startDate = date startTime = '09:00' endDate = date endTime = '10:00' place = '' notes = '' zone = zone custom = false rows = [] }}show(Number y, Number m, Hybrid evs) {year = ymonth = mtitle = monthNames[m - 1] + ' ' + ybase = build(y, m, today)winFirst = base[0].datewinLast = base[41].dateevents = evsdays = fill(base, evs)}// Layout only (mission 006): the theme (theme/theme.hl, `html month-view …`) tiles the day cells and takes the frames and radii away, buttons// and fields come from the theme (44 px taps, 16 px fields). Colours: the semantic WorldAPI tokens as css variables, each with its palette// value as fallback (a component's browser module cannot import tokens.hl itself); the app sets --color-accent in its styles.hl.// PHONE FIRST: a day cell has no side padding (its event chips are 44 px tall and as wide as the cell); the wide layout is from 60rem.Style {monthView { display = 'grid' gap = '.5rem'header { display = 'flex' flexWrap = 'wrap' alignItems = 'center' justifyContent = 'space-between' gap = '.5rem'// sync of components.hybriel 4922f9c (MC): the prev / next buttons are 44 px targets on any width (the theme gave 36 px high at 1280)button { minWidth = '2.75rem' minHeight = '2.75rem' }}// calendar#14: on a phone the month name and the Reminder settings button did not fit in one row, so the name broke into two lines// ("Oktobe / r 2026"). The name never breaks; the button drops to its own row on the right when the row is too narrow.'#settings-open' { marginLeft = 'auto' }h2 { margin = '0' fontSize = '1.1rem' color = 'var(--color-text-strong, rgb(245, 250, 255))' textAlign = 'center' flex = '1 1 auto' whiteSpace = 'nowrap' textTransform = 'capitalize' }'.hidden' { display = 'none' }}// the 7-column grid is the weekday row's and the days' only: it used to be `month-view ol`, so it also caught the reminder// lists (the settings dialog's rows stood in 7 narrow columns, calendar#11)'#month-weekdays, #month-days' { display = 'grid' gridTemplateColumns = 'repeat(7, minmax(0, 1fr))' margin = '0' padding = '0' listStyle = 'none' }'#month-weekdays' {li { margin = '0' padding = '.3rem 0' fontSize = '.8rem' fontWeight = '600' color = 'var(--color-text-muted, rgb(145, 150, 155))' textAlign = 'center' }}'#month-days' {li { minHeight = '3.5rem' margin = '0' padding = '.2rem 0' textAlign = 'right' background = 'var(--color-surface, rgb(35, 40, 45))' cursor = 'pointer' overflow = 'hidden' }time { display = 'block' paddingRight = '.25rem' color = 'var(--color-text, rgb(195, 200, 205))' fontSize = '.95rem' }'li.outside' { background = 'var(--color-background, rgb(25, 30, 35))'time { color = 'var(--color-text-muted, rgb(145, 150, 155))' }}'li.today' { outline = '2px solid var(--color-accent, #569bd4)' outlineOffset = '-2px'time { color = 'var(--color-accent, #569bd4)' fontWeight = '800' }}}// the notifications section of the reminder settings: the state in words, then one full-width button per action (44 px taps)notifyBox { display = 'grid' gap = '.5rem'h3 { margin = '0' fontSize = '.85rem' fontWeight = '600' color = 'var(--color-text-muted, rgb(145, 150, 155))' }p { margin = '0' fontSize = '.85rem' color = 'var(--color-text-muted, rgb(145, 150, 155))'empty { display = 'none' }}button { width = '100%' }}reminderBox { display = 'grid' gap = '.4rem'h3 { margin = '0' fontSize = '.85rem' fontWeight = '600' color = 'var(--color-text-muted, rgb(145, 150, 155))' }p { margin = '0' fontSize = '.85rem' color = 'var(--color-text-muted, rgb(145, 150, 155))' }}// the reminder lists (the event's own, the calendar's defaults): one row per reminder, the full width'#rem-rows, #set-rows' { display = 'grid' gridTemplateColumns = 'minmax(0, 1fr)' gap = '.5rem' margin = '0' padding = '0' listStyle = 'none' }// PHONE: a reminder is `[number] [unit, the rest of the width] [×]` and, for "days before, at", the time under them; every// field is at least a tap (2.75rem) high (the theme); the unit's select takes the width the number and × leavereminderRow { display = 'grid' gridTemplateColumns = '5rem minmax(0, 1fr) 2.75rem' alignItems = 'center' gap = '.4rem'input { minWidth = '0' width = '100%' }select { minWidth = '0' width = '100%' gridColumn = '2' }'input[type=time]' { gridColumn = '1 / 3' }button { gridColumn = '3' gridRow = '1' minWidth = '2.75rem' minHeight = '2.75rem' padding = '0' }}'reminder-row.other' { 'input[type=time]' { display = 'none' } }// ---- the events on the days and the editors (moved here from styles.hl, calendar#16; the markup is this file's) ----// PHONE: a cell is 48 px wide, so a chip is the cell's width and at least the tap (44 px, the theme's button size) high; its// text is cut with an ellipsis. The cell has no side padding so the chip may be that wide.dayEvents { display = 'grid' gap = '.15rem' marginTop = '.2rem' textAlign = 'left' }'button.unused' { display = 'none' }'button.hidden' { display = 'none' }'button.event, button.more' { display = 'block' minWidth = '0' width = '100%' padding = '.15rem .2rem' overflow = 'hidden' fontSize = '.75rem' fontWeight = '500' lineHeight = '1.3' textAlign = 'left' textOverflow = 'ellipsis' whiteSpace = 'nowrap' color = 'var(--color-accent)' background = 'var(--color-background-sunken)' }'button.more' { color = 'var(--color-text-muted)' background = 'transparent' }'#notify-ask' { color = 'var(--color-accent-text)' background = 'var(--color-accent)' }// the switches (time/all day, the event's own reminders or the calendar's): the chosen one is the accent, the other `quiet`kindSwitch { display = 'flex' flexWrap = 'wrap' gap = '.5rem''button:not(.quiet)' { color = 'var(--color-accent-text)' background = 'var(--color-accent)' }}formButtons { display = 'flex' flexWrap = 'wrap' gap = '.5rem''button.danger' { marginLeft = 'auto' }}// the editors (event, reminder settings): a full-page scrim with one paneleventEditor { position = 'fixed' inset = '0' zIndex = '40' display = 'grid' placeItems = 'center' padding = '1rem' background = 'color-mix(in srgb, var(--color-background-sunken) 82%, transparent)'form { display = 'grid' gap = '.7rem' width = '100%' maxWidth = '28rem' maxHeight = '100%' overflowY = 'auto' padding = '1rem' background = 'var(--color-surface)' borderRadius = 'var(--radius-large)' }h2 { margin = '0' }label { display = 'grid' gap = '.2rem' margin = '0' fontSize = '.85rem' fontWeight = '400' color = 'var(--color-text-muted)' }input { width = '100%' color = 'var(--color-text-strong)' }textarea { width = '100%' color = 'var(--color-text-strong)' }}'event-editor.closed' { display = 'none' }// the settings dialog is a popover (top layer): the browser's popover defaults (fit-content box, border, margin) give way to the full-page scrim'event-editor[popover]' { width = '100%' height = '100%' maxWidth = 'none' maxHeight = 'none' margin = '0' border = '0' overflow = 'hidden' color = 'var(--color-text)' }'event-editor[popover]:not(:popover-open)' { display = 'none' }fieldRow { display = 'grid' gridTemplateColumns = 'minmax(0, 1fr) minmax(0, 1fr)' gap = '.5rem' }'form.allday' { 'label.timed' { display = 'none' }fieldRow { gridTemplateColumns = 'minmax(0, 1fr)' }}'@media (min-width: 60rem)' {// the desktop's chips are small on purpose (a pointer; four of them stand in one cell): under 44 px, deliberately'button.event, button.more' { minHeight = '0' padding = '.05rem .3rem' borderRadius = 'var(--radius-small)' }'#month-days' { li { minHeight = '5rem' padding = '.3rem' } }// the editor's panel is 28rem wide there: the time stands in the row's line againreminderRow { gridTemplateColumns = '5rem minmax(0, 1fr) 7.5rem 2.75rem''input[type=time]' { gridColumn = '3' }button { gridColumn = '4' }}'reminder-row.other' { select { gridColumn = '2 / 4' } }}}View {monthView { on pointerover(e) { emit monthEnv(e) } on focusin(e) { emit monthEnv(e) } on touchstart(e) { emit monthEnv(e) }header {button { id = "month-prev" type = "button" class = "quiet" title = prevLabel "‹" on click(e) { emit monthPrev(e) } }h2 { id = "month-title" title }button { id = "month-next" type = "button" class = "quiet" title = nextLabel "›" on click(e) { emit monthNext(e) } } if (signedIn) { button { id = "settings-open" type = "button" class = "quiet" popovertarget = "settingseditor" popovertargetaction = "show" "Reminder settings" } }}ol { id = "month-weekdays" for (name of weekdays) { li { name } } }ol { id = "month-days" on click(e) { emit dayClick(e) }for (d of days) {li { class = d.clstime { datetime = d.date d.n }dayEvents {button { class = d.c0 type = "button" value = d.v0 d.t0 }button { class = d.c1 type = "button" value = d.v1 d.t1 }button { class = d.c2 type = "button" value = d.v2 d.t2 }button { class = d.c3 type = "button" value = d.v3 d.t3 }}}}}eventEditor { id = "eventeditor" class = formClassform { id = "eventform" class = formKindon submit(e) {e.preventDefault()emit saveEvent(e)}h2 { id = "formheading" formHeading }kindSwitch {button { id = "kind-timed" type = "button" class = timedButton "At a time" on click(e) { emit setKind(false) } }button { id = "kind-allday" type = "button" class = alldayButton "All day" on click(e) { emit setKind(true) } }}label { "Title"input { id = "f-title" name = "title" maxlength = "200" autocomplete = "off" required = "required" value = fTitle on input(e) { emit setF('title', e.target.value) } }}fieldRow {label { "From"input { id = "f-startdate" name = "startDate" type = "date" required = "required" value = fStartDate on input(e) { emit setF('startDate', e.target.value) } }}label { class = "timed" "at"input { id = "f-starttime" name = "startTime" type = "time" value = fStartTime on input(e) { emit setF('startTime', e.target.value) } }}}fieldRow {label { "To"input { id = "f-enddate" name = "endDate" type = "date" value = fEndDate on input(e) { emit setF('endDate', e.target.value) } }}label { class = "timed" "at"input { id = "f-endtime" name = "endTime" type = "time" value = fEndTime on input(e) { emit setF('endTime', e.target.value) } }}}label { "Place"input { id = "f-place" name = "place" maxlength = "200" autocomplete = "off" value = fPlace on input(e) { emit setF('place', e.target.value) } }}label { "Notes"textarea { id = "f-notes" name = "notes" rows = "4" maxlength = "5000" value = fNotes on input(e) { emit setF('notes', e.target.value) } }}reminderBox {h3 { "Reminders" }kindSwitch {button { id = "rem-calendar" type = "button" class = calClass "Calendar's" on click(e) { emit setCustom(false) } }button { id = "rem-own" type = "button" class = ownClass "Own" on click(e) { emit setCustom(true) } }}p { id = "rem-default-text" class = defaultClass defaultText }ol { id = "rem-rows" class = rowsClassfor (r of remRows) {reminderRow { class = r.clsinput { type = "number" min = "0" value = r.n on change(e) { emit setRem('rem', r.i, 'n', e.target.value) } }select { value = r.unit on change(e) { emit setRem('rem', r.i, 'unit', e.target.value) }option { value = "minutes" "minutes before" }option { value = "hours" "hours before" }option { value = "days" "days before, at" }}input { type = "time" value = r.time on change(e) { emit setRem('rem', r.i, 'time', e.target.value) } }button { type = "button" class = "quiet" "×" on click(e) { emit delRem('rem', r.i) } }}}}button { id = "rem-add" type = "button" class = addClass "Add reminder" on click(e) { emit addRem('rem') } }}p { id = "formerror" class = "message" formError }formButtons {button { id = "event-save" type = "submit" "Save" }button { id = "event-cancel" type = "button" class = "quiet" "Cancel" on click(e) { emit closeForm(e) } }button { id = "event-delete" type = "button" class = deleteClass "Delete" on click(e) { emit deleteEvent(e) } }}}}eventEditor { id = "settingseditor" popover = "manual" on toggle(e) { emit settingsToggled(e) } on keydown(e) { emit settingsKey(e) }form { id = "settingsform" class = "timed"on submit(e) {e.preventDefault()emit saveSettings(e)}h2 { "Reminder settings" }notifyBox {h3 { "Notifications on this device" }p { id = "notify-blocked" class = blockedClass "Notifications are blocked for this site in the browser settings." }p { id = "notify-planned" plannedText }p { id = "push-state" pushText }button { id = "notify-ask" type = "button" class = askClass "Turn on notifications" on click(e) { emit askNotify(e) } }button { id = "push-test" type = "button" class = pushOffClass "Send a test notification" on click(e) { emit pushTest(e) } }button { id = "push-off" type = "button" class = pushOffClass "Turn off on this device" on click(e) { emit pushOff(e) } }}reminderBox {h3 { "Default reminders" }p { class = "muted" "Every event without reminders of its own is reminded like this:" }ol { id = "set-rows"for (r of setRows) {reminderRow { class = r.clsinput { type = "number" min = "0" value = r.n on change(e) { emit setRem('set', r.i, 'n', e.target.value) } }select { value = r.unit on change(e) { emit setRem('set', r.i, 'unit', e.target.value) }option { value = "minutes" "minutes before" }option { value = "hours" "hours before" }option { value = "days" "days before, at" }}input { type = "time" value = r.time on change(e) { emit setRem('set', r.i, 'time', e.target.value) } }button { type = "button" class = "quiet" "×" on click(e) { emit delRem('set', r.i) } }}}}button { id = "set-add" type = "button" class = "quiet" "Add reminder" on click(e) { emit addRem('set') } }}p { id = "settingserror" class = "message" setError }formButtons {button { id = "set-save" type = "submit" "Save" }button { id = "set-cancel" type = "button" class = "quiet" popovertarget = "settingseditor" popovertargetaction = "hide" autofocus = "autofocus" "Cancel" }}}}input { id = "month-view-goto" type = "hidden" on change(e) { emit monthGoto(e.target.value) } }}}// the events of the six weeks shown, from the server (none while signed out)loadEvents(Number y, Number m) {if (!signedIn) { return [] }b = build(y, m, today)r = emit server calLoad(b[0].date, b[41].date)if (r != null && r.soon != null) { takeSoon(r) }return r == null || r.events == null ? [] : r.events}on monthPrev(Hybrid e) {browserEnv()paged = 1y = month == 1 ? year - 1 : yearm = month == 1 ? 12 : month - 1show(y, m, loadEvents(y, m))}on monthNext(Hybrid e) {browserEnv()paged = 1y = month == 12 ? year + 1 : yearm = month == 12 ? 1 : month + 1show(y, m, loadEvents(y, m))}// the browser's today, language and time zone, once: today follows the user's time zone, the names their languageon monthEnv(Hybrid e) {browserEnv()// every ten minutes of use the timers are set again (a long-open page keeps the next week planned)if (signedIn && Date.now() - lastArm > 600000) { arm() }}// the device's IANA time zone, read from the browser each time (arm can run before the first pointer set fZone)deviceZone() {z = Intl.DateTimeFormat().resolvedOptions().timeZonereturn z != null && z != '' ? z : 'UTC'}browserEnv() {if (seen == 1) { return null }seen = 1serverDay = todaynow = new Date()lang = navigator.language != null ? navigator.language : 'en'zone = Intl.DateTimeFormat().resolvedOptions().timeZonebrowserDay = ('' + (10000 + now.getFullYear())).slice(1) + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate())if (browserDay != serverDay) { today = browserDay }// the server already wrote the names of a language it knows: they stay, so paging never switches themif (!namesKnown) {mf = Intl.DateTimeFormat(lang, { month = 'long' timeZone = 'UTC' })df = Intl.DateTimeFormat(lang, { weekday = 'short' timeZone = 'UTC' })ms = []ds = []let i = 0while (i < 12) { ms.push(mf.format(new Date(Date.UTC(2024, i, 15, 12)))) i = i + 1 }i = 0while (i < 7) { ds.push(df.format(new Date(Date.UTC(2024, 0, 1 + i, 12)))) i = i + 1 }// (only what differs is assigned: a same-valued assignment still repaints the title and the days)if (ms.join('|') != monthNames.join('|')) { monthNames = ms }if (ds.join('|') != weekdayNames.join('|')) { weekdayNames = ds weekdays = ds }de = lang.slice(0, 2) == 'de'pl = de ? 'Voriger Monat' : 'Previous month'nl = de ? 'Nächster Monat' : 'Next month'if (pl != prevLabel) { prevLabel = pl }if (nl != nextLabel) { nextLabel = nl }}fZone = zone != null && zone != '' ? zone : 'UTC'readPermission()// calendar#9: a phone freezes or drops an app it switched away from, and its timers with it. Whenever the app is// shown again the timers are set again, and what came due meanwhile is shown at once (arm → missed)document.addEventListener('visibilitychange', () => { if (document.visibilityState == 'visible') { arm() } })window.addEventListener('pageshow', () => { arm() })// Nothing is repainted unless the browser's day is not the server's: the server already drew this month with its events,// and a round trip here, answered while the user pages or taps a day, used to put the month back or swallow the tap.if (browserDay == serverDay) {if (!namesKnown) {named = monthNames[month - 1] + ' ' + yearif (named != title) { title = named }}} else if (paged == 0) {// the month shown follows the corrected today only while the user has not paged yet (also when they page meanwhile)y = toNumber(today.slice(0, 4))m = toNumber(today.slice(5, 7))evs = loadEvents(y, m)if (paged == 0) { show(y, m, evs) } else { show(year, month, events) }} else { show(year, month, events) }// (offline the server did not answer: the timers are set from the reminders the page already holds)arm()}// ---- the reminders: notifications the browser holds a timer for (they fire while the app or its worker is open, also offline) ----// the server's newest answer about the reminders to come; the timers are set again from ittakeSoon(Hybrid r) {soon = r.soonif (r.defaults != null) { defaultText = r.defaults }if (r.defaultRows != null) { defRows = r.defaultRows }arm()}// one timer per reminder that is still to come within a week; the old timers are dropped first. Before that, calendar#9:// the reminders that came due since this device last planned or showed one, while no timer could fire (the app switched// away and frozen, dropped, or closed), are shown now — late, for events that have not started yetarm() {if (arming == 1) {armAgain = 1return null}arming = 1armOnce()while (armAgain == 1) {armAgain = 0armOnce()}arming = 0return null}armOnce() {if (!signedIn) { return null }let i = 0while (i < timers.length) { clearTimeout(timers[i]) i = i + 1 }nowMs = Date.now()readPermission()let since = remindedUntil(nowMs)if (notifyState == 'granted') {since = pushedSince(since)late = missed(soon, since, nowMs, today, deviceZone())i = 0while (i < late.length) {q = late[i]notify(q.title, { body = q.late tag = q.key icon = '/icons/icon-192.png' })i = i + 1}}remember(nowMs)list = plan(soon, nowMs, 604800000, deviceZone())ids = []i = 0while (i < list.length) {// `p` is a new binding on every pass (hybriel #106): each timer keeps ITS reminderp = list[i]ids.push(setTimeout(() => {remember(p.at)notify(p.title, { body = p.body tag = p.key icon = '/icons/icon-192.png' })}, p.at - nowMs))i = i + 1}timers = idslastArm = nowMs// calendar#9 part 2: a device that already allowed notifications is subscribed to Web Push once per page (its own handler:// the browser's subscribe can take long and must not hold the timers)if (!pushTried && notifyState == 'granted') {pushTried = trueemit pushEnsure(1)}plannedText = list.length == 0 ? '' : (list.length == 1 ? '1 reminder' : list.length + ' reminders') + ' set for the next 7 days'}// P1: a device with push gets its reminders from the server, even when the page is closed. A reminder the server pushed// (shown, tapped, swiped away) must not be shown again by this page as "missed": the later of the page's own instant and the// server's. Without a subscription, or if the server does not answer, the page's own instant stays.pushedSince(Number own) {if (!pushAvailable || pushOffKept()) { return own }reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : nullsub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : nullif (sub == null) { return own }r = emit server calPushedUntil(sub.endpoint)return r != null && r.since != null && r.since > own ? r.since : own}// the instant up to which this device has planned or shown the user's reminders (the browser's localStorage); none// kept yet → the last 12 hours count as missedremindedKey() {return 'calendar-reminded-until-' + userId}remindedUntil(Number nowMs) {store = window.localStoragekept = store != null ? store.getItem(remindedKey()) : nullreturn kept != null && kept != '' ? toNumber(kept) : nowMs - 43200000}remember(Number at) {store = window.localStorageif (store == null) { return null }kept = store.getItem(remindedKey())if (kept == null || kept == '' || toNumber(kept) < at) { store.setItem(remindedKey(), '' + at) }}// ONE state for the notification section (C13): `pushOn` (this device is subscribed to push) and `notifyState` / `pushIsOff` decide// every control at once — "Turn on" only while not on, test + off only while on, the blocked hint only when blockedreadPermission() {n = window.NotificationnotifyState = n == null ? 'unsupported' : n.permissionpushIsOff = pushOffKept()showControls()}showControls() {askClass = !pushOn && (notifyState == 'default' || (notifyState == 'granted' && pushIsOff)) ? '' : 'hidden'blockedClass = notifyState == 'denied' ? '' : 'hidden'pushOffClass = pushOn ? '' : 'hidden'if (!pushOn && notifyState == 'unsupported') { pushText = 'This browser cannot show notifications.' }if (!pushOn && pushText == '') { pushText = 'Reminders show while the calendar is open on this device.' }}// the button is the click the browser wants before it allows notificationson askNotify(Hybrid e) {browserEnv()notify('Notifications are on', { body = 'Your reminders show up here.' })pushTried = truepushOffKeep(false)readPermission()emit pushEnsure(1)}// "Turn off on this device": the browser drops its push subscription and the server forgets the device. The choice is kept// (localStorage) so that this device is not subscribed again at the next page; "Turn on notifications" undoes it.on pushOff(Hybrid e) {browserEnv()pushOffKeep(true)reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : nullsub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : nullif (sub != null) {endpoint = sub.endpointsub.unsubscribe()emit server calPushOff(endpoint)}pushOn = falsepushText = 'Reminders show while the calendar is open on this device.'readPermission()}// "Send a test notification": the server sends ONE push to this device in ~10 seconds; leave the app and it arrives like a reminderon pushTest(Hybrid e) {browserEnv()reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : nullsub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : nullif (sub == null) {pushText = 'This device is not subscribed: tap "Turn on notifications" first.'return null}r = emit server calPushTest(sub.endpoint)pushText = r != null && r.ok ? 'A test notification is on its way (about 10 seconds). Close the calendar or lock the phone now: "Calendar test - Push works on this device" should appear.' : 'The test could not be started: ' + (r != null && r.error != null ? r.error : 'no answer')}pushOffKey() {return 'calendar-push-off-' + userId}pushOffKept() {store = window.localStoragereturn store != null && store.getItem(pushOffKey()) == '1'}pushOffKeep(Boolean off) {store = window.localStorageif (store == null) { return null }if (off) { store.setItem(pushOffKey(), '1') } else { store.removeItem(pushOffKey()) }pushIsOff = off}// calendar#9 part 2: this device's Web Push subscription goes to the server, which sends the reminders to it when the page// is closed. No push (no key on the server, no browser support, refused) leaves the page's own timers as they were.on pushEnsure(Number n) {if (!signedIn || !pushAvailable || notifyState != 'granted' || pushOffKept()) { return null }sub = subscribePush()if (sub == null) {pushText = 'Reminders show while the calendar is open on this device.'pushOn = falseshowControls()return null}r = emit server calPushSave(sub, fZone)pushText = r != null && r.ok ? 'Reminders also reach this device when the calendar is closed.' : 'Reminders show while the calendar is open on this device.'pushOn = r != null && r.okshowControls()}// the page is shown (first show included): a device that already allowed notifications is subscribed / its subscription// refreshed now, not at the user's first touchon client shown(r) {browserEnv()}// from a host script (the date picker): "YYYY-MM-DD" → show that date's monthon monthGoto(String text) {paged = 1y = toNumber(text.slice(0, 4))m = toNumber(text.slice(5, 7))show(y, m, loadEvents(y, m))}// ---- the editor ----// the reminders switch: the calendar's or the event's ownsyncCustom() {calClass = fCustom ? 'quiet' : ''ownClass = fCustom ? '' : 'quiet'defaultClass = fCustom ? 'hidden' : ''rowsClass = fCustom ? '' : 'hidden'addClass = fCustom ? 'quiet' : 'quiet hidden'}// the classes that follow the form's kind and whether it edits an existing eventsyncForm() {formKind = fAllDay ? 'allday' : 'timed'timedButton = fAllDay ? 'quiet' : ''alldayButton = fAllDay ? '' : 'quiet'deleteClass = isNew ? 'danger hidden' : 'danger'}openForm(Hybrid fields, String heading, Boolean fresh) {fId = fields.idfTitle = fields.titlefAllDay = fields.allDayfStartDate = fields.startDatefStartTime = fields.startTimefEndDate = fields.endDatefEndTime = fields.endTimefPlace = fields.placefNotes = fields.notesisNew = freshfCustom = fields.customremRows = withIndex(fields.rows)syncCustom()formHeading = headingformError = ''formClass = 'open'syncForm()}// one click on the day list: an event button edits that event, anywhere else on a day adds one to that dayon dayClick(Hybrid e) {if (!signedIn) { return null }li = e.target.closest('li')if (li == null) { return null }date = li.querySelector('time').getAttribute('datetime')b = e.target.closest('button.event')if (b == null) {fresh = blank(date, fZone)openForm(fresh, 'New event', true)return null}let j = 0while (j < events.length) {ev = events[j]if (ev.id == b.value) {fields = { id = ev.id title = ev.title allDay = ev.allDay startDate = ev.startDate startTime = ev.startTime endDate = ev.endDate endTime = ev.endTime place = ev.place notes = ev.notes zone = fZone custom = ev.custom rows = ev.rows }openForm(fields, 'Edit event', false)return null}j = j + 1}}on setF(String name, String value) {if (name == 'title') { fTitle = value }if (name == 'startDate') { fStartDate = value }if (name == 'startTime') { fStartTime = value }if (name == 'endDate') { fEndDate = value }if (name == 'endTime') { fEndTime = value }if (name == 'place') { fPlace = value }if (name == 'notes') { fNotes = value }}on setCustom(Boolean own) {fCustom = own// switching to own reminders starts from the calendar's, so nothing has to be typed for the usual caseif (own && remRows.length == 0) { remRows = withIndex(defaultRows) }syncCustom()}// one reminder row of the event editor (which = 'rem') or of the settings (which = 'set')on setRem(String which, Number i, String field, String value) {rows = which == 'rem' ? remRows : setRowsif (i < 0 || i >= rows.length) { return null }out = []let k = 0while (k < rows.length) {r = rows[k]let n = r.nlet unit = r.unitlet time = r.timeif (k == i && field == 'n') { n = value }if (k == i && field == 'unit') { unit = value }if (k == i && field == 'time') { time = value }out.push({ unit = unit n = n time = time })k = k + 1}if (which == 'rem') { remRows = withIndex(out) } else { setRows = withIndex(out) }}on addRem(String which) {rows = which == 'rem' ? remRows : setRowsout = []let k = 0while (k < rows.length) { out.push({ unit = rows[k].unit n = rows[k].n time = rows[k].time }) k = k + 1 }out.push({ unit = 'minutes' n = '10' time = '09:00' })if (which == 'rem') { remRows = withIndex(out) } else { setRows = withIndex(out) }}on delRem(String which, Number i) {rows = which == 'rem' ? remRows : setRowsout = []let k = 0while (k < rows.length) {if (k != i) { out.push({ unit = rows[k].unit n = rows[k].n time = rows[k].time }) }k = k + 1}if (which == 'rem') { remRows = withIndex(out) } else { setRows = withIndex(out) }}// ---- the calendar settings: the default reminders ----// the dialog is a MANUAL popover (a nested auto one would be closed with the menu that opened it; the menu's "Reminder settings" opens it declaratively, popovertarget — the menu lives in the shell, outside this// component): opening it is the event that reads the device's state and the calendar's defaultson settingsToggled(Hybrid e) {if (e.newState != 'open') { return null }// no pointer event of the month view may have come yet, so the page's browser state is read now —// the notification section is right on the first look (and a device that allowed notifications is subscribed)browserEnv()readPermission()r = emit server calSettingsLoad()if (r == null || r.error != null) {setError = r == null ? 'the settings need the server: you are offline' : r.errorreturn null}setRows = withIndex(r.rows)setError = ''}// Escape closes it (a manual popover has no light dismiss: it must stay open when the menu, which opened it, closes)on settingsKey(Hybrid e) {if (e.key == 'Escape') { document.getElementById('settingseditor').hidePopover() }}on saveSettings(Hybrid e) {r = emit server calSettingsSave(setRows)if (r == null || r.error != null) {setError = r == null ? 'the settings could not be saved (offline?)' : r.errorreturn null}document.getElementById('settingseditor').hidePopover()takeSoon(r)}on setKind(Boolean allDay) {fAllDay = allDayif (!allDay && fStartTime == '') { fStartTime = '09:00' }if (!allDay && fEndTime == '' && fEndDate != '') { fEndTime = '10:00' }syncForm()}on closeForm(Hybrid e) {formClass = 'closed'}// what the form holds, as the face takes itformFields() {return { id = fId title = fTitle allDay = fAllDay startDate = fStartDate startTime = fStartTime endDate = fEndDate endTime = fEndTime place = fPlace notes = fNotes zone = fZone custom = fCustom reminders = remRows }}// the event as the page shows it, for an event saved while offline (the server sends the real one when it is back)localView(Hybrid f) {allDay = f.allDaylast = f.endDate != '' ? f.endDate : f.startDatemine = []let k = 0while (k < f.reminders.length) { mine.push({ unit = f.reminders[k].unit n = f.reminders[k].n time = f.reminders[k].time }) k = k + 1 }return { id = f.id title = f.title allDay = allDay first = f.startDate last = laststartDate = f.startDate startTime = allDay ? '' : f.startTime endDate = f.endDate endTime = allDay ? '' : f.endTimeplace = f.place notes = f.notes start = f.startDate zone = f.zone custom = f.custom rows = f.custom ? mine : defRows }}on saveEvent(Hybrid e) {f = formFields()if (fTitle.trim() == '' || fStartDate == '') {formError = 'the event needs a title and a start date'return null}r = emit server calSave(f, winFirst, winLast)if (r == null) {// OFFLINE: the save waits in the app's queue (it is sent when the connection is back); here the event and its// reminders are set at once, so the notification still comesif (f.id == '') { f.id = 'local-' + Date.now() }emit server calSaveQueued(f, winFirst, winLast)v = localView(f)evs = []let k = 0while (k < events.length) { if (events[k].id != v.id) { evs.push(events[k]) } k = k + 1 }evs.push(v)mine = []k = 0while (k < soon.length) { if (soon[k].id != v.id) { mine.push(soon[k]) } k = k + 1 }mine.push({ id = v.id title = v.title allDay = v.allDay startDate = v.startDate startTime = v.startTime place = v.place zone = v.zone rows = v.rows })soon = mineformClass = 'closed'show(year, month, evs)arm()return null}if (r.error != null) {formError = r.errorreturn null}formClass = 'closed'takeSoon(r)show(year, month, r.events)}on deleteEvent(Hybrid e) {r = emit server calDelete(fId, winFirst, winLast)if (r == null || r.error != null) {formError = r == null ? 'the event could not be deleted (offline?)' : r.errorreturn null}formClass = 'closed'takeSoon(r)show(year, month, r.events)}
Branches
Latest commits
- e9fec7bb|||PR HL-STANDARD clean-up: typed parameters, plain locals, by-reference cacheAtlas
- eff166a4Re-vendor complete Hybriel plugins and runtime to day44mre
- cef81394Wait for the DST fixture page instead of an unused socketmre
- 42434f47Check lazy-session cookies after login with a stored anonymous fixturemre
- 728e84e3Re-vendor complete Hybriel day41 plugin directoriesmre
- cbd7ff43Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
- 59d1da0acalendar: plain declarations instead of needless let in 9 files (calendar#17): 49 declarations that are never reassigned; reassigned ones and the timer closure's p stay letmre
- f5415cf9calendar: the Style blocks in the language's nested form (calendar#16): rules named after the View's own elements with their children nested, pseudo-classes and @media nested, merged duplicate select rule; same CSS, shots identical in Chrome at 4 sizesmre
- edb7c947calendar: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 56+4 failing → 60 passedmre
- bf8cc0fcStyles move into their components: the shell's styles into main.hl, the events and the editors into the month view's Style block; styles.hl keeps only the theme inherit, the accent and the message line; .gitignore ignores a bin symlink too; tests/styles-shots.mjs for the before/after pixel comparemre
- 5d8579d7README: login.js stays by caramboleyo's explicit rulemre
- cc759328Merge sb3-standby: calendar deploys through its standbymre
- f2fcdc6dcalendar: a standby container (port 45015, profile standby, reminder clock off) and a /health page; deploy hands over through standby-swap.sh without a gapmre
- 229643f7Merge branch 'cal-14'mre
- 1110b26fcalendar#14: the month name no longer breaks into two lines on a phone (Reminder settings drops to its own row when the header is too narrow), gate checks for one-line title and all header controls on screenmre
- 490c658aident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- 18095868calendar: Reminder settings button opens its dialog again (the dialog's open handler still closed the removed user menu and stopped); old e2e and gate scripts use the new headermre
- 6eee4b5acalendar header: the selector alone top right plus Log out as before the theme missions; Reminder settings back on the month page (WIP: the settings test still fails)mre
- 0b909decident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
- 0c8f9364Merge branch 'sy-sync'mre