calendar
All repositories: gitoria
43.7 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 '../../lib/clock.hl'import { pad, daysIn, before } from '../../lib/dates.hl'import { namesFor } from '../../lib/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 '../../lib/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 = ''Boolean settingsOpen = falseString plannedText = ''String pushText = ''Boolean pushTried = falseBoolean pushAvailable = pushConfiguredBoolean 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'Boolean formOpen = falseBoolean timedPressed = !fAllDayBoolean calendarPressed = !fCustomBoolean askNotifyVisible = !pushOn && (notifyState == 'default' || (notifyState == 'granted' && pushIsOff))String formError = ''String formHeading = 'New event'Boolean isNew = trueString 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 outside = falseif (day < 1) { cy = py cm = pm cd = pn + day outside = true }if (day > n) { cy = ny cm = nm cd = day - n outside = true }date = cy + '-' + pad(cm) + '-' + pad(cd)isToday = date == todayTextout.push({ n = cd date = date isOutside = outside && !isToday isToday = isToday })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, has = visible, more = overflow, 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 isOutside = d.isOutside isToday = d.isToday addLabel = 'Add event on ' + d.date }let k = 0while (k < 4) {let text = ''let visible = falselet more = falselet id = ''if (k < hit.length && (hit.length <= 4 || k < 3)) {e = hit[k]text = (e.allDay || d.date != e.first ? '' : e.startTime + ' ') + e.titlevisible = trueid = e.id}if (k == 3 && hit.length > 4) { text = '+' + (hit.length - 3) + ' more' visible = true more = true }row['t' + k] = textrow['has' + k] = visiblerow['more' + k] = morerow['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' {today {outline = '2px solid var(--color-accent, #569bd4)'outlineOffset = '-2px'time {color = 'var(--color-accent, #569bd4)'fontWeight = '800'}}outside {background = 'var(--color-background, rgb(25, 30, 35))'time { color = 'var(--color-text-muted, rgb(145, 150, 155))' }}li {position = 'relative'minHeight = '3.5rem'margin = '0'padding = '.2rem 0'textAlign = 'right'cursor = 'pointer'overflow = 'hidden'}'li:not(.outside)' { background = 'var(--color-surface, rgb(35, 40, 45))' }// The add action covers the cell; the date stays visible above it.'button.day-add' {position = 'absolute'inset = '0'width = '100%'height = '100%'minWidth = '0'minHeight = '0'padding = '0'border = '0'borderRadius = '0'background = 'transparent'focusVisible {outline = '2px solid var(--color-accent)'outlineOffset = '-2px'}}time {pointerEvents = 'none'position = 'relative'display = 'block'paddingRight = '.25rem'color = 'var(--color-text, rgb(195, 200, 205))'fontSize = '.95rem'}}// 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' }}// ---- 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 {position = 'relative'pointerEvents = 'none'display = 'grid'gap = '.15rem'marginTop = '.2rem'textAlign = 'left'}buttonEvent {pointerEvents = 'auto'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)'}buttonMore = buttonEvent + {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 {// Attribute selector keeps each toggle and its keyboard focus in place.'button[aria-pressed="true"]' {color = 'var(--color-accent-text)'background = 'var(--color-accent)'}display = 'flex' flexWrap = 'wrap' gap = '.5rem'}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)' }}// 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' }'field-row:has(label:only-child)' { 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:not(:has(input[type=time]))' { 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"for (d of days) {if (d.isToday) { li { Style.todayif (signedIn) { button { type = "button" class = "day-add" 'aria-label' = d.addLabel on click() { addDay(d.date) } } }time { datetime = d.date d.n }dayEvents {if (d.has0) { if (d.more0) { button { Style.buttonMore type = "button" value = d.v0 d.t0 on click() { pickEvent(d.v0, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v0 d.t0 on click() { pickEvent(d.v0, d.date) } } } }if (d.has1) { if (d.more1) { button { Style.buttonMore type = "button" value = d.v1 d.t1 on click() { pickEvent(d.v1, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v1 d.t1 on click() { pickEvent(d.v1, d.date) } } } }if (d.has2) { if (d.more2) { button { Style.buttonMore type = "button" value = d.v2 d.t2 on click() { pickEvent(d.v2, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v2 d.t2 on click() { pickEvent(d.v2, d.date) } } } }if (d.has3) { if (d.more3) { button { Style.buttonMore type = "button" value = d.v3 d.t3 on click() { pickEvent(d.v3, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v3 d.t3 on click() { pickEvent(d.v3, d.date) } } } }}} } else { if (d.isOutside) { li { Style.outsideif (signedIn) { button { type = "button" class = "day-add" 'aria-label' = d.addLabel on click() { addDay(d.date) } } }time { datetime = d.date d.n }dayEvents {if (d.has0) { if (d.more0) { button { Style.buttonMore type = "button" value = d.v0 d.t0 on click() { pickEvent(d.v0, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v0 d.t0 on click() { pickEvent(d.v0, d.date) } } } }if (d.has1) { if (d.more1) { button { Style.buttonMore type = "button" value = d.v1 d.t1 on click() { pickEvent(d.v1, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v1 d.t1 on click() { pickEvent(d.v1, d.date) } } } }if (d.has2) { if (d.more2) { button { Style.buttonMore type = "button" value = d.v2 d.t2 on click() { pickEvent(d.v2, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v2 d.t2 on click() { pickEvent(d.v2, d.date) } } } }if (d.has3) { if (d.more3) { button { Style.buttonMore type = "button" value = d.v3 d.t3 on click() { pickEvent(d.v3, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v3 d.t3 on click() { pickEvent(d.v3, d.date) } } } }}} } else { li {if (signedIn) { button { type = "button" class = "day-add" 'aria-label' = d.addLabel on click() { addDay(d.date) } } }time { datetime = d.date d.n }dayEvents {if (d.has0) { if (d.more0) { button { Style.buttonMore type = "button" value = d.v0 d.t0 on click() { pickEvent(d.v0, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v0 d.t0 on click() { pickEvent(d.v0, d.date) } } } }if (d.has1) { if (d.more1) { button { Style.buttonMore type = "button" value = d.v1 d.t1 on click() { pickEvent(d.v1, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v1 d.t1 on click() { pickEvent(d.v1, d.date) } } } }if (d.has2) { if (d.more2) { button { Style.buttonMore type = "button" value = d.v2 d.t2 on click() { pickEvent(d.v2, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v2 d.t2 on click() { pickEvent(d.v2, d.date) } } } }if (d.has3) { if (d.more3) { button { Style.buttonMore type = "button" value = d.v3 d.t3 on click() { pickEvent(d.v3, d.date) } } } else { button { Style.buttonEvent type = "button" value = d.v3 d.t3 on click() { pickEvent(d.v3, d.date) } } } }}} } }}}if (formOpen) { eventEditor { id = "eventeditor"form { id = "eventform"on submit(e) {e.preventDefault()emit saveEvent(e)}h2 { id = "formheading" formHeading }kindSwitch {button { id = "kind-timed" type = "button" 'aria-pressed' = timedPressed "At a time" on click(Hybrid e) { emit setKind(false) } }button { id = "kind-allday" type = "button" 'aria-pressed' = fAllDay "All day" on click(Hybrid 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) } }}if (!fAllDay) { label { "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) } }}if (!fAllDay) { label { "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" 'aria-pressed' = calendarPressed "Calendar's" on click(Hybrid e) { emit setCustom(false) } }button { id = "rem-own" type = "button" 'aria-pressed' = fCustom "Own" on click(Hybrid e) { emit setCustom(true) } }}if (!fCustom) { p { id = "rem-default-text" defaultText } }if (fCustom) { ol { id = "rem-rows"for (r of remRows) {reminderRow {input { 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" }}if (r.unit == 'days') { input { type = "time" value = r.time on change(e) { emit setRem('rem', r.i, 'time', e.target.value) } } } else { input { type = "hidden" 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) } }}}} }if (fCustom) { button { id = "rem-add" type = "button" class = "quiet" "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) } }if (!isNew) { button { id = "event-delete" type = "button" class = "danger" "Delete" on click(e) { emit deleteEvent(e) } } }}}} }eventEditor { id = "settingseditor" popover = "manual" popoverOpen = settingsOpen on toggle(Hybrid e) { emit settingsToggled(e) } on keydown(Hybrid 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" }if (notifyState == 'denied') { p { id = "notify-blocked" "Notifications are blocked for this site in the browser settings." } }p { id = "notify-planned" plannedText }p { id = "push-state" pushText }if (askNotifyVisible) { button { id = "notify-ask" type = "button" "Turn on notifications" on click(e) { emit askNotify(e) } } }if (pushOn) { button { id = "push-test" type = "button" "Send a test notification" on click(e) { emit pushTest(e) } } }if (pushOn) { button { id = "push-off" type = "button" "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 {input { 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" }}if (r.unit == 'days') { input { type = "time" value = r.time on change(e) { emit setRem('set', r.i, 'time', e.target.value) } } } else { input { type = "hidden" 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)// 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()updateNotificationText()}updateNotificationText() {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 = falseupdateNotificationText()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.okupdateNotificationText()}// 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(Hybrid r) {if (seen == 0) { browserEnv() } else { arm() }}// 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 ----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)formHeading = headingformError = ''formOpen = true}// Each day and chip carries its action's date or event id from the loop record.addDay(String date) {if (!signedIn) { return null }openForm(blank(date, fZone), 'New event', true)}pickEvent(String id, String date) {if (!signedIn) { return null }// The overflow chip has always opened a new event for its day.if (id == '') { addDay(date) return null }let j = 0while (j < events.length) {ev = events[j]if (ev.id == id) {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) }}// 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) {settingsOpen = e.newState == 'open'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') { settingsOpen = false }}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}settingsOpen = falsetakeSoon(r)}on setKind(Boolean allDay) {fAllDay = allDayif (!allDay && fStartTime == '') { fStartTime = '09:00' }if (!allDay && fEndTime == '' && fEndDate != '') { fEndTime = '10:00' }}on closeForm(Hybrid e) {formOpen = false}// 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 = mineformOpen = falseshow(year, month, evs)arm()return null}if (r.error != null) {formError = r.errorreturn null}formOpen = falsetakeSoon(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}formOpen = falsetakeSoon(r)show(year, month, r.events)}
Branches
Latest commits
- bc2d7776|||PR WIP calendar28: preserve toggle focus and chip specificityAtlas
- 189c4c8c|||PR WIP calendar28: replace visual class state with View conditionsAtlas
- fff2f537Merge branch 'calendar31-lib' into mainAtlas
- 07cde3dc|||PR keep worker records out of the repo; README vendor is day72Atlas
- a753b0ab|||PR move shared calendar logic to libAtlas
- b32a921dMerge branch 'vendor-day72' into mainAtlas
- 60a0dd19|||PR Hybriel day72 (00c9dbb8) instead of the withdrawn day73Atlas
- 53f5464dMerge branch 'calendar26-day73' into mainAtlas
- 338499ec|||PR Keep reminder settings open during editing and rejected savesAtlas
- ad9e8d59|||PR Use framework page and popover state, Hybriel day73Atlas
- cab224a1Re-vendor calendar to verified Hybriel day73Atlas
- f9b8f918Merge branch 'calendar-vendor-day61' into mainAtlas
- 66341793|||PR Vendor Hybriel day61Atlas
- 36fc596bMerge branch 'vendor-day59' into mainAtlas
- b37cc1da|||PR Vendor Hybriel day59Atlas
- 05665102Merge branch 'vendor-day56' into mainAtlas
- 687296fb|||PR Vendor Hybriel day56Atlas
- a6166d4eMerge branch 'hl-standard-3' into mainAtlas
- 6d0eb3b0|||PR Calendar day add buttons only when signed in (Kunibert minor)Atlas
- add4b499|||PR Make calendar day actions keyboard accessibleAtlas