gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2dd53dcc2dd53dccP1: one reminder shows once: arm() one at a time, the page skips reminders the server already pushed; push-twice gatemre2dd53dcc/components/month-view/month-view.hl

36.8 KB

  1. // month-view.hl — THE MONTH VIEW: prev / next buttons on top, the month's name and the year between them, the
  2. // days below (weeks start on Monday; the days of the neighbouring months are dimmed; today is marked).
  3. // THE CALENDAR'S COPY of the pure-Hybriel month view of components.hybriel.worldapi.org (no .js), plus the user's
  4. // events on the days and the editor for them (add: click a day; edit / delete: click an event). Events come from
  5. // events.hl, one server round trip per change (faces calLoad / calSave / calDelete in calendar.hl). The date
  6. // arithmetic is written here (plain integers), so it runs the same on the server (first render) and in the browser.
  7. // What only the browser knows — today in the user's time zone, the month and weekday names in the user's language,
  8. // the time zone's name (`Date` and `Intl` are browser globals of View handlers) — is read the moment the pointer, a
  9. // 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
  10. // the language, so it never guesses one: names appear once, in the browser's language, and stay.
  11. // The page reads `year` and `month` (1–12) as its own members. USE ONE PER PAGE: a composed component's
  12. // members are the page's state (COMPONENTS.md §12).
  13. import { serverToday } from './clock.hl'
  14. import { pad, daysIn, before } from './dates.hl'
  15. import { namesFor } from './names.hl'
  16. import { userIdOfSession } from '../../lib/users.hl'
  17. import { eventsBetween, upcoming } from '../../lib/events.hl'
  18. import { defaultsOf } from '../../lib/settings.hl'
  19. import { pushConfigured } from '../../lib/util.hl'
  20. import { notify, subscribePush } from 'hl:web'
  21. import { plan, missed, shift, describe, withIndex, defaultRows } from './reminders.hl'
  22. // the request's Accept-Language, handed in by the page (calendar.hl reads it from `headers`, hybriel #105): the first
  23. // render already writes the names
  24. acceptLanguage = null
  25. Hybrid known = namesFor(acceptLanguage)
  26. Boolean namesKnown = known != null
  27. String today = serverToday()
  28. Number year = toNumber(today.slice(0, 4))
  29. Number month = toNumber(today.slice(5, 7))
  30. Hybrid monthNames = namesKnown ? known.months : ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
  31. Hybrid weekdayNames = namesKnown ? known.days : ['·', '·', '·', '·', '·', '·', '·']
  32. String title = monthNames[month - 1] + ' ' + year
  33. Hybrid base = build(year, month, today)
  34. Hybrid weekdays = weekdayNames
  35. session = null
  36. userId = userIdOfSession(session)
  37. Boolean signedIn = userId != null
  38. String winFirst = base[0].date
  39. String winLast = base[41].date
  40. Hybrid events = signedIn ? eventsBetween(userId, winFirst, winLast) : []
  41. Hybrid days = fill(base, events)
  42. // the reminders (ticket calendar#4): the events of the next days with the reminders that apply (`soon`, kept with the page
  43. // state, so an offline page still knows them), the calendar's defaults in words, the timers the browser holds
  44. Hybrid soon = signedIn ? upcoming(userId, shift(today, -2), shift(today, 9)) : []
  45. String defaultText = signedIn ? describe(defaultsOf(userId)) : ''
  46. Hybrid defRows = signedIn ? defaultsOf(userId) : []
  47. Boolean fCustom = false
  48. Hybrid remRows = []
  49. Hybrid setRows = []
  50. Hybrid timers = []
  51. Number lastArm = 0
  52. // P1: arm() is called from several places at once (page load, pageshow, visibilitychange, the server's answer); its notify calls wait
  53. // for the browser, so a second run started in between showed the same missed reminder again and left timers behind. One at a time.
  54. Number arming = 0
  55. Number armAgain = 0
  56. String notifyState = 'unknown'
  57. String setError = ''
  58. String askClass = 'hidden'
  59. String blockedClass = 'hidden'
  60. String plannedText = ''
  61. String pushText = ''
  62. Boolean pushTried = false
  63. Boolean pushAvailable = pushConfigured
  64. String pushOffClass = 'hidden'
  65. Boolean pushIsOff = false
  66. Boolean pushOn = false
  67. String fId = ''
  68. String fTitle = ''
  69. Boolean fAllDay = false
  70. String fStartDate = ''
  71. String fStartTime = '09:00'
  72. String fEndDate = ''
  73. String fEndTime = '10:00'
  74. String fPlace = ''
  75. String fNotes = ''
  76. String fZone = 'UTC'
  77. String formClass = 'closed'
  78. String formError = ''
  79. String formHeading = 'New event'
  80. Boolean isNew = true
  81. String formKind = 'timed'
  82. String ownClass = 'quiet'
  83. String calClass = ''
  84. String defaultClass = ''
  85. String rowsClass = 'hidden'
  86. String addClass = 'quiet hidden'
  87. String timedButton = ''
  88. String alldayButton = 'quiet'
  89. String deleteClass = 'danger hidden'
  90. String prevLabel = namesKnown ? known.prev : '‹'
  91. String nextLabel = namesKnown ? known.next : '›'
  92. Number seen = 0
  93. Number paged = 0
  94. // 0 = Monday … 6 = Sunday (Sakamoto's method gives 0 = Sunday)
  95. weekdayOf(y, m, d) {
  96. t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
  97. yy = m < 3 ? y - 1 : y
  98. sun = (yy + (yy - yy % 4) / 4 - (yy - yy % 100) / 100 + (yy - yy % 400) / 400 + t[m - 1] + d) % 7
  99. return (sun + 6) % 7
  100. }
  101. // 42 days (six weeks of seven), so the view keeps its height from month to month
  102. build(y, m, todayText) {
  103. py = m == 1 ? y - 1 : y
  104. pm = m == 1 ? 12 : m - 1
  105. ny = m == 12 ? y + 1 : y
  106. nm = m == 12 ? 1 : m + 1
  107. lead = weekdayOf(y, m, 1)
  108. let n = daysIn(y, m)
  109. pn = daysIn(py, pm)
  110. out = []
  111. let day = 1 - lead
  112. let w = 0
  113. while (w < 6) {
  114. let i = 0
  115. while (i < 7) {
  116. let cy = y
  117. let cm = m
  118. let cd = day
  119. let cls = ''
  120. if (day < 1) { cy = py cm = pm cd = pn + day cls = 'outside' }
  121. if (day > n) { cy = ny cm = nm cd = day - n cls = 'outside' }
  122. let date = cy + '-' + pad(cm) + '-' + pad(cd)
  123. if (date == todayText) { cls = 'today' }
  124. out.push({ n = cd date = date cls = cls })
  125. day = day + 1
  126. i = i + 1
  127. }
  128. w = w + 1
  129. }
  130. return out
  131. }
  132. // the events that touch a day, as four chips on the day cell (a nested `for` does not repaint when the outer list is
  133. // reassigned: hybriel #86 — so the chips are fixed members of the day: t = text, c = class, v = event id).
  134. // Timed events start with their time on the first day. More than four: the fourth chip says "+N more".
  135. fill(list, evs) {
  136. out = []
  137. let i = 0
  138. while (i < list.length) {
  139. let d = list[i]
  140. let hit = []
  141. let j = 0
  142. while (j < evs.length) {
  143. let e = evs[j]
  144. if (!before(d.date, e.first) && !before(e.last, d.date)) { hit.push(e) }
  145. j = j + 1
  146. }
  147. let row = { n = d.n date = d.date cls = d.cls }
  148. let k = 0
  149. while (k < 4) {
  150. let text = ''
  151. let cls = 'unused'
  152. let id = ''
  153. if (k < hit.length && (hit.length <= 4 || k < 3)) {
  154. let e = hit[k]
  155. text = (e.allDay || d.date != e.first ? '' : e.startTime + ' ') + e.title
  156. cls = 'event'
  157. id = e.id
  158. }
  159. if (k == 3 && hit.length > 4) { text = '+' + (hit.length - 3) + ' more' cls = 'more' }
  160. row['t' + k] = text
  161. row['c' + k] = cls
  162. row['v' + k] = id
  163. k = k + 1
  164. }
  165. out.push(row)
  166. i = i + 1
  167. }
  168. return out
  169. }
  170. // the form's fields for a new event on `date` (all text; allDay a Boolean); zone = the browser's time zone name
  171. blank(date, zone) {
  172. return { id = '' title = '' allDay = false startDate = date startTime = '09:00' endDate = date endTime = '10:00' place = '' notes = '' zone = zone custom = false rows = [] }
  173. }
  174. show(y, m, evs) {
  175. year = y
  176. month = m
  177. title = monthNames[m - 1] + ' ' + y
  178. base = build(y, m, today)
  179. winFirst = base[0].date
  180. winLast = base[41].date
  181. events = evs
  182. days = fill(base, evs)
  183. }
  184. // Layout only (mission 006): the theme (theme/theme.hl, `html month-view …`) tiles the day cells and takes the frames and radii away, buttons
  185. // and fields come from the theme (44 px taps, 16 px fields). Colours: the semantic WorldAPI tokens as css variables, each with its palette
  186. // value as fallback (a component's browser module cannot import tokens.hl itself); the app sets --color-accent in its styles.hl.
  187. // 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.
  188. Style {
  189. 'month-view' { display = 'grid' gap = '.5rem' }
  190. 'month-view header' { display = 'flex' alignItems = 'center' justifyContent = 'space-between' gap = '.5rem' }
  191. 'month-view h2' { margin = '0' fontSize = '1.1rem' color = 'var(--color-text-strong, rgb(245, 250, 255))' textAlign = 'center' flex = '1' textTransform = 'capitalize' }
  192. // 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
  193. // lists (the settings dialog's rows stood in 7 narrow columns, calendar#11)
  194. '#month-weekdays,
  195. #month-days' { display = 'grid' gridTemplateColumns = 'repeat(7, minmax(0, 1fr))' margin = '0' padding = '0' listStyle = 'none' }
  196. '#month-weekdays li' { margin = '0' padding = '.3rem 0' fontSize = '.8rem' fontWeight = '600' color = 'var(--color-text-muted, rgb(145, 150, 155))' textAlign = 'center' }
  197. '#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' }
  198. '#month-days time' { display = 'block' paddingRight = '.25rem' color = 'var(--color-text, rgb(195, 200, 205))' fontSize = '.95rem' }
  199. '#month-days li.outside' { background = 'var(--color-background, rgb(25, 30, 35))' }
  200. '#month-days li.outside time' { color = 'var(--color-text-muted, rgb(145, 150, 155))' }
  201. '#month-days li.today' { outline = '2px solid var(--color-accent, #569bd4)' outlineOffset = '-2px' }
  202. '#month-days li.today time' { color = 'var(--color-accent, #569bd4)' fontWeight = '800' }
  203. // the notifications section of the reminder settings: the state in words, then one full-width button per action (44 px taps)
  204. 'notify-box' { display = 'grid' gap = '.5rem' }
  205. 'notify-box h3' { margin = '0' fontSize = '.85rem' fontWeight = '600' color = 'var(--color-text-muted, rgb(145, 150, 155))' }
  206. 'notify-box p' { margin = '0' fontSize = '.85rem' color = 'var(--color-text-muted, rgb(145, 150, 155))' }
  207. 'notify-box p:empty' { display = 'none' }
  208. 'notify-box button' { width = '100%' }
  209. 'month-view .hidden' { display = 'none' }
  210. 'reminder-box' { display = 'grid' gap = '.4rem' }
  211. 'reminder-box h3' { margin = '0' fontSize = '.85rem' fontWeight = '600' color = 'var(--color-text-muted, rgb(145, 150, 155))' }
  212. 'reminder-box p' { margin = '0' fontSize = '.85rem' color = 'var(--color-text-muted, rgb(145, 150, 155))' }
  213. // the reminder lists (the event's own, the calendar's defaults): one row per reminder, the full width
  214. '#rem-rows,
  215. #set-rows' { display = 'grid' gridTemplateColumns = 'minmax(0, 1fr)' gap = '.5rem' margin = '0' padding = '0' listStyle = 'none' }
  216. // PHONE: a reminder is `[number] [unit, the rest of the width] [×]` and, for "days before, at", the time under them; every
  217. // field is at least a tap (2.75rem) high (the theme); the unit's select takes the width the number and × leave
  218. 'reminder-row' { display = 'grid' gridTemplateColumns = '5rem minmax(0, 1fr) 2.75rem' alignItems = 'center' gap = '.4rem' }
  219. 'reminder-row input,
  220. reminder-row select' { minWidth = '0' width = '100%' }
  221. 'reminder-row select' { gridColumn = '2' }
  222. 'reminder-row input[type=time]' { gridColumn = '1 / 3' }
  223. 'reminder-row button' { gridColumn = '3' gridRow = '1' minWidth = '2.75rem' minHeight = '2.75rem' padding = '0' }
  224. 'reminder-row.other input[type=time]' { display = 'none' }
  225. '@media (min-width: 60rem)' {
  226. '#month-days li' { minHeight = '5rem' padding = '.3rem' }
  227. // the editor's panel is 28rem wide there: the time stands in the row's line again
  228. 'reminder-row' { gridTemplateColumns = '5rem minmax(0, 1fr) 7.5rem 2.75rem' }
  229. 'reminder-row input[type=time]' { gridColumn = '3' }
  230. 'reminder-row.other select' { gridColumn = '2 / 4' }
  231. 'reminder-row button' { gridColumn = '4' }
  232. }
  233. }
  234. View {
  235. monthView { on pointerover(e) { emit monthEnv(e) } on focusin(e) { emit monthEnv(e) } on touchstart(e) { emit monthEnv(e) }
  236. header {
  237. button { id = "month-prev" type = "button" class = "quiet" title = prevLabel "‹" on click(e) { emit monthPrev(e) } }
  238. h2 { id = "month-title" title }
  239. button { id = "month-next" type = "button" class = "quiet" title = nextLabel "›" on click(e) { emit monthNext(e) } }
  240. }
  241. ol { id = "month-weekdays" for (name of weekdays) { li { name } } }
  242. ol { id = "month-days" on click(e) { emit dayClick(e) }
  243. for (d of days) {
  244. li { class = d.cls
  245. time { datetime = d.date d.n }
  246. dayEvents {
  247. button { class = d.c0 type = "button" value = d.v0 d.t0 }
  248. button { class = d.c1 type = "button" value = d.v1 d.t1 }
  249. button { class = d.c2 type = "button" value = d.v2 d.t2 }
  250. button { class = d.c3 type = "button" value = d.v3 d.t3 }
  251. }
  252. }
  253. }
  254. }
  255. eventEditor { id = "eventeditor" class = formClass
  256. form { id = "eventform" class = formKind
  257. on submit(e) {
  258. e.preventDefault()
  259. emit saveEvent(e)
  260. }
  261. h2 { id = "formheading" formHeading }
  262. kindSwitch {
  263. button { id = "kind-timed" type = "button" class = timedButton "At a time" on click(e) { emit setKind(false) } }
  264. button { id = "kind-allday" type = "button" class = alldayButton "All day" on click(e) { emit setKind(true) } }
  265. }
  266. label { "Title"
  267. input { id = "f-title" name = "title" maxlength = "200" autocomplete = "off" required = "required" value = fTitle on input(e) { emit setF('title', e.target.value) } }
  268. }
  269. fieldRow {
  270. label { "From"
  271. input { id = "f-startdate" name = "startDate" type = "date" required = "required" value = fStartDate on input(e) { emit setF('startDate', e.target.value) } }
  272. }
  273. label { class = "timed" "at"
  274. input { id = "f-starttime" name = "startTime" type = "time" value = fStartTime on input(e) { emit setF('startTime', e.target.value) } }
  275. }
  276. }
  277. fieldRow {
  278. label { "To"
  279. input { id = "f-enddate" name = "endDate" type = "date" value = fEndDate on input(e) { emit setF('endDate', e.target.value) } }
  280. }
  281. label { class = "timed" "at"
  282. input { id = "f-endtime" name = "endTime" type = "time" value = fEndTime on input(e) { emit setF('endTime', e.target.value) } }
  283. }
  284. }
  285. label { "Place"
  286. input { id = "f-place" name = "place" maxlength = "200" autocomplete = "off" value = fPlace on input(e) { emit setF('place', e.target.value) } }
  287. }
  288. label { "Notes"
  289. textarea { id = "f-notes" name = "notes" rows = "4" maxlength = "5000" value = fNotes on input(e) { emit setF('notes', e.target.value) } }
  290. }
  291. reminderBox {
  292. h3 { "Reminders" }
  293. kindSwitch {
  294. button { id = "rem-calendar" type = "button" class = calClass "Calendar's" on click(e) { emit setCustom(false) } }
  295. button { id = "rem-own" type = "button" class = ownClass "Own" on click(e) { emit setCustom(true) } }
  296. }
  297. p { id = "rem-default-text" class = defaultClass defaultText }
  298. ol { id = "rem-rows" class = rowsClass
  299. for (r of remRows) {
  300. reminderRow { class = r.cls
  301. input { type = "number" min = "0" value = r.n on change(e) { emit setRem('rem', r.i, 'n', e.target.value) } }
  302. select { value = r.unit on change(e) { emit setRem('rem', r.i, 'unit', e.target.value) }
  303. option { value = "minutes" "minutes before" }
  304. option { value = "hours" "hours before" }
  305. option { value = "days" "days before, at" }
  306. }
  307. input { type = "time" value = r.time on change(e) { emit setRem('rem', r.i, 'time', e.target.value) } }
  308. button { type = "button" class = "quiet" "×" on click(e) { emit delRem('rem', r.i) } }
  309. }
  310. }
  311. }
  312. button { id = "rem-add" type = "button" class = addClass "Add reminder" on click(e) { emit addRem('rem') } }
  313. }
  314. p { id = "formerror" class = "message" formError }
  315. formButtons {
  316. button { id = "event-save" type = "submit" "Save" }
  317. button { id = "event-cancel" type = "button" class = "quiet" "Cancel" on click(e) { emit closeForm(e) } }
  318. button { id = "event-delete" type = "button" class = deleteClass "Delete" on click(e) { emit deleteEvent(e) } }
  319. }
  320. }
  321. }
  322. eventEditor { id = "settingseditor" popover = "manual" on toggle(e) { emit settingsToggled(e) } on keydown(e) { emit settingsKey(e) }
  323. form { id = "settingsform" class = "timed"
  324. on submit(e) {
  325. e.preventDefault()
  326. emit saveSettings(e)
  327. }
  328. h2 { "Reminder settings" }
  329. notifyBox {
  330. h3 { "Notifications on this device" }
  331. p { id = "notify-blocked" class = blockedClass "Notifications are blocked for this site in the browser settings." }
  332. p { id = "notify-planned" plannedText }
  333. p { id = "push-state" pushText }
  334. button { id = "notify-ask" type = "button" class = askClass "Turn on notifications" on click(e) { emit askNotify(e) } }
  335. button { id = "push-test" type = "button" class = pushOffClass "Send a test notification" on click(e) { emit pushTest(e) } }
  336. button { id = "push-off" type = "button" class = pushOffClass "Turn off on this device" on click(e) { emit pushOff(e) } }
  337. }
  338. reminderBox {
  339. h3 { "Default reminders" }
  340. p { class = "muted" "Every event without reminders of its own is reminded like this:" }
  341. ol { id = "set-rows"
  342. for (r of setRows) {
  343. reminderRow { class = r.cls
  344. input { type = "number" min = "0" value = r.n on change(e) { emit setRem('set', r.i, 'n', e.target.value) } }
  345. select { value = r.unit on change(e) { emit setRem('set', r.i, 'unit', e.target.value) }
  346. option { value = "minutes" "minutes before" }
  347. option { value = "hours" "hours before" }
  348. option { value = "days" "days before, at" }
  349. }
  350. input { type = "time" value = r.time on change(e) { emit setRem('set', r.i, 'time', e.target.value) } }
  351. button { type = "button" class = "quiet" "×" on click(e) { emit delRem('set', r.i) } }
  352. }
  353. }
  354. }
  355. button { id = "set-add" type = "button" class = "quiet" "Add reminder" on click(e) { emit addRem('set') } }
  356. }
  357. p { id = "settingserror" class = "message" setError }
  358. formButtons {
  359. button { id = "set-save" type = "submit" "Save" }
  360. button { id = "set-cancel" type = "button" class = "quiet" popovertarget = "settingseditor" popovertargetaction = "hide" autofocus = "autofocus" "Cancel" }
  361. }
  362. }
  363. }
  364. input { id = "month-view-goto" type = "hidden" on change(e) { emit monthGoto(e.target.value) } }
  365. }
  366. }
  367. // the events of the six weeks shown, from the server (none while signed out)
  368. loadEvents(y, m) {
  369. if (!signedIn) { return [] }
  370. b = build(y, m, today)
  371. r = emit server calLoad(b[0].date, b[41].date)
  372. if (r != null && r.soon != null) { takeSoon(r) }
  373. return r == null || r.events == null ? [] : r.events
  374. }
  375. on monthPrev(e) {
  376. browserEnv()
  377. paged = 1
  378. y = month == 1 ? year - 1 : year
  379. m = month == 1 ? 12 : month - 1
  380. show(y, m, loadEvents(y, m))
  381. }
  382. on monthNext(e) {
  383. browserEnv()
  384. paged = 1
  385. y = month == 12 ? year + 1 : year
  386. m = month == 12 ? 1 : month + 1
  387. show(y, m, loadEvents(y, m))
  388. }
  389. // the browser's today, language and time zone, once: today follows the user's time zone, the names their language
  390. on monthEnv(e) {
  391. browserEnv()
  392. // every ten minutes of use the timers are set again (a long-open page keeps the next week planned)
  393. if (signedIn && Date.now() - lastArm > 600000) { arm() }
  394. }
  395. // the device's IANA time zone, read from the browser each time (arm can run before the first pointer set fZone)
  396. deviceZone() {
  397. z = Intl.DateTimeFormat().resolvedOptions().timeZone
  398. return z != null && z != '' ? z : 'UTC'
  399. }
  400. browserEnv() {
  401. if (seen == 1) { return null }
  402. seen = 1
  403. serverDay = today
  404. now = new Date()
  405. lang = navigator.language != null ? navigator.language : 'en'
  406. zone = Intl.DateTimeFormat().resolvedOptions().timeZone
  407. browserDay = ('' + (10000 + now.getFullYear())).slice(1) + '-' + pad(now.getMonth() + 1) + '-' + pad(now.getDate())
  408. if (browserDay != serverDay) { today = browserDay }
  409. // the server already wrote the names of a language it knows: they stay, so paging never switches them
  410. if (!namesKnown) {
  411. mf = Intl.DateTimeFormat(lang, { month = 'long' })
  412. df = Intl.DateTimeFormat(lang, { weekday = 'short' })
  413. ms = []
  414. ds = []
  415. let i = 0
  416. while (i < 12) { ms.push(mf.format(new Date(Date.UTC(2024, i, 15, 12)))) i = i + 1 }
  417. i = 0
  418. while (i < 7) { ds.push(df.format(new Date(Date.UTC(2024, 0, 1 + i, 12)))) i = i + 1 }
  419. // (only what differs is assigned: a same-valued assignment still repaints the title and the days)
  420. if (ms.join('|') != monthNames.join('|')) { monthNames = ms }
  421. if (ds.join('|') != weekdayNames.join('|')) { weekdayNames = ds weekdays = ds }
  422. de = lang.slice(0, 2) == 'de'
  423. pl = de ? 'Voriger Monat' : 'Previous month'
  424. nl = de ? 'Nächster Monat' : 'Next month'
  425. if (pl != prevLabel) { prevLabel = pl }
  426. if (nl != nextLabel) { nextLabel = nl }
  427. }
  428. fZone = zone != null && zone != '' ? zone : 'UTC'
  429. readPermission()
  430. // calendar#9: a phone freezes or drops an app it switched away from, and its timers with it. Whenever the app is
  431. // shown again the timers are set again, and what came due meanwhile is shown at once (arm → missed)
  432. document.addEventListener('visibilitychange', () => { if (document.visibilityState == 'visible') { arm() } })
  433. window.addEventListener('pageshow', () => { arm() })
  434. // Nothing is repainted unless the browser's day is not the server's: the server already drew this month with its events,
  435. // and a round trip here, answered while the user pages or taps a day, used to put the month back or swallow the tap.
  436. if (browserDay == serverDay) {
  437. if (!namesKnown) {
  438. named = monthNames[month - 1] + ' ' + year
  439. if (named != title) { title = named }
  440. }
  441. } else if (paged == 0) {
  442. // the month shown follows the corrected today only while the user has not paged yet (also when they page meanwhile)
  443. y = toNumber(today.slice(0, 4))
  444. m = toNumber(today.slice(5, 7))
  445. evs = loadEvents(y, m)
  446. if (paged == 0) { show(y, m, evs) } else { show(year, month, events) }
  447. } else { show(year, month, events) }
  448. // (offline the server did not answer: the timers are set from the reminders the page already holds)
  449. arm()
  450. }
  451. // ---- the reminders: notifications the browser holds a timer for (they fire while the app or its worker is open, also offline) ----
  452. // the server's newest answer about the reminders to come; the timers are set again from it
  453. takeSoon(r) {
  454. soon = r.soon
  455. if (r.defaults != null) { defaultText = r.defaults }
  456. if (r.defaultRows != null) { defRows = r.defaultRows }
  457. arm()
  458. }
  459. // one timer per reminder that is still to come within a week; the old timers are dropped first. Before that, calendar#9:
  460. // the reminders that came due since this device last planned or showed one, while no timer could fire (the app switched
  461. // away and frozen, dropped, or closed), are shown now — late, for events that have not started yet
  462. arm() {
  463. if (arming == 1) {
  464. armAgain = 1
  465. return null
  466. }
  467. arming = 1
  468. armOnce()
  469. while (armAgain == 1) {
  470. armAgain = 0
  471. armOnce()
  472. }
  473. arming = 0
  474. return null
  475. }
  476. armOnce() {
  477. if (!signedIn) { return null }
  478. let i = 0
  479. while (i < timers.length) { clearTimeout(timers[i]) i = i + 1 }
  480. nowMs = Date.now()
  481. readPermission()
  482. let since = remindedUntil(nowMs)
  483. if (notifyState == 'granted') {
  484. since = pushedSince(since)
  485. late = missed(soon, since, nowMs, today, deviceZone())
  486. i = 0
  487. while (i < late.length) {
  488. let q = late[i]
  489. notify(q.title, { body = q.late tag = q.key icon = '/icons/icon-192.png' })
  490. i = i + 1
  491. }
  492. }
  493. remember(nowMs)
  494. list = plan(soon, nowMs, 604800000, deviceZone())
  495. ids = []
  496. i = 0
  497. while (i < list.length) {
  498. // `p` is a new binding on every pass (hybriel #106): each timer keeps ITS reminder
  499. let p = list[i]
  500. ids.push(setTimeout(() => {
  501. remember(p.at)
  502. notify(p.title, { body = p.body tag = p.key icon = '/icons/icon-192.png' })
  503. }, p.at - nowMs))
  504. i = i + 1
  505. }
  506. timers = ids
  507. lastArm = nowMs
  508. // calendar#9 part 2: a device that already allowed notifications is subscribed to Web Push once per page (its own handler:
  509. // the browser's subscribe can take long and must not hold the timers)
  510. if (!pushTried && notifyState == 'granted') {
  511. pushTried = true
  512. emit pushEnsure(1)
  513. }
  514. plannedText = list.length == 0 ? '' : (list.length == 1 ? '1 reminder' : list.length + ' reminders') + ' set for the next 7 days'
  515. }
  516. // P1: a device with push gets its reminders from the server, even when the page is closed. A reminder the server pushed
  517. // (shown, tapped, swiped away) must not be shown again by this page as "missed": the later of the page's own instant and the
  518. // server's. Without a subscription, or if the server does not answer, the page's own instant stays.
  519. pushedSince(own) {
  520. if (!pushAvailable || pushOffKept()) { return own }
  521. reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : null
  522. sub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : null
  523. if (sub == null) { return own }
  524. r = emit server calPushedUntil(sub.endpoint)
  525. return r != null && r.since != null && r.since > own ? r.since : own
  526. }
  527. // the instant up to which this device has planned or shown the user's reminders (the browser's localStorage); none
  528. // kept yet → the last 12 hours count as missed
  529. remindedKey() {
  530. return 'calendar-reminded-until-' + userId
  531. }
  532. remindedUntil(nowMs) {
  533. store = window.localStorage
  534. kept = store != null ? store.getItem(remindedKey()) : null
  535. return kept != null && kept != '' ? toNumber(kept) : nowMs - 43200000
  536. }
  537. remember(at) {
  538. store = window.localStorage
  539. if (store == null) { return null }
  540. kept = store.getItem(remindedKey())
  541. if (kept == null || kept == '' || toNumber(kept) < at) { store.setItem(remindedKey(), '' + at) }
  542. }
  543. // ONE state for the notification section (C13): `pushOn` (this device is subscribed to push) and `notifyState` / `pushIsOff` decide
  544. // every control at once — "Turn on" only while not on, test + off only while on, the blocked hint only when blocked
  545. readPermission() {
  546. n = window.Notification
  547. notifyState = n == null ? 'unsupported' : n.permission
  548. pushIsOff = pushOffKept()
  549. showControls()
  550. }
  551. showControls() {
  552. askClass = !pushOn && (notifyState == 'default' || (notifyState == 'granted' && pushIsOff)) ? '' : 'hidden'
  553. blockedClass = notifyState == 'denied' ? '' : 'hidden'
  554. pushOffClass = pushOn ? '' : 'hidden'
  555. if (!pushOn && notifyState == 'unsupported') { pushText = 'This browser cannot show notifications.' }
  556. if (!pushOn && pushText == '') { pushText = 'Reminders show while the calendar is open on this device.' }
  557. }
  558. // the button is the click the browser wants before it allows notifications
  559. on askNotify(e) {
  560. browserEnv()
  561. notify('Notifications are on', { body = 'Your reminders show up here.' })
  562. pushTried = true
  563. pushOffKeep(false)
  564. readPermission()
  565. emit pushEnsure(1)
  566. }
  567. // "Turn off on this device": the browser drops its push subscription and the server forgets the device. The choice is kept
  568. // (localStorage) so that this device is not subscribed again at the next page; "Turn on notifications" undoes it.
  569. on pushOff(e) {
  570. browserEnv()
  571. pushOffKeep(true)
  572. reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : null
  573. sub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : null
  574. if (sub != null) {
  575. endpoint = sub.endpoint
  576. sub.unsubscribe()
  577. emit server calPushOff(endpoint)
  578. }
  579. pushOn = false
  580. pushText = 'Reminders show while the calendar is open on this device.'
  581. readPermission()
  582. }
  583. // "Send a test notification": the server sends ONE push to this device in ~10 seconds; leave the app and it arrives like a reminder
  584. on pushTest(e) {
  585. browserEnv()
  586. reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : null
  587. sub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : null
  588. if (sub == null) {
  589. pushText = 'This device is not subscribed: tap "Turn on notifications" first.'
  590. return null
  591. }
  592. r = emit server calPushTest(sub.endpoint)
  593. 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')
  594. }
  595. pushOffKey() {
  596. return 'calendar-push-off-' + userId
  597. }
  598. pushOffKept() {
  599. store = window.localStorage
  600. return store != null && store.getItem(pushOffKey()) == '1'
  601. }
  602. pushOffKeep(off) {
  603. store = window.localStorage
  604. if (store == null) { return null }
  605. if (off) { store.setItem(pushOffKey(), '1') } else { store.removeItem(pushOffKey()) }
  606. pushIsOff = off
  607. }
  608. // calendar#9 part 2: this device's Web Push subscription goes to the server, which sends the reminders to it when the page
  609. // is closed. No push (no key on the server, no browser support, refused) leaves the page's own timers as they were.
  610. on pushEnsure(n) {
  611. if (!signedIn || !pushAvailable || notifyState != 'granted' || pushOffKept()) { return null }
  612. sub = subscribePush()
  613. if (sub == null) {
  614. pushText = 'Reminders show while the calendar is open on this device.'
  615. pushOn = false
  616. showControls()
  617. return null
  618. }
  619. r = emit server calPushSave(sub, fZone)
  620. 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.'
  621. pushOn = r != null && r.ok
  622. showControls()
  623. }
  624. // the page is shown (first show included): a device that already allowed notifications is subscribed / its subscription
  625. // refreshed now, not at the user's first touch
  626. on client shown(r) {
  627. browserEnv()
  628. }
  629. // from a host script (the date picker): "YYYY-MM-DD" → show that date's month
  630. on monthGoto(text) {
  631. paged = 1
  632. y = toNumber(text.slice(0, 4))
  633. m = toNumber(text.slice(5, 7))
  634. show(y, m, loadEvents(y, m))
  635. }
  636. // ---- the editor ----
  637. // the reminders switch: the calendar's or the event's own
  638. syncCustom() {
  639. calClass = fCustom ? 'quiet' : ''
  640. ownClass = fCustom ? '' : 'quiet'
  641. defaultClass = fCustom ? 'hidden' : ''
  642. rowsClass = fCustom ? '' : 'hidden'
  643. addClass = fCustom ? 'quiet' : 'quiet hidden'
  644. }
  645. // the classes that follow the form's kind and whether it edits an existing event
  646. syncForm() {
  647. formKind = fAllDay ? 'allday' : 'timed'
  648. timedButton = fAllDay ? 'quiet' : ''
  649. alldayButton = fAllDay ? '' : 'quiet'
  650. deleteClass = isNew ? 'danger hidden' : 'danger'
  651. }
  652. openForm(fields, heading, fresh) {
  653. fId = fields.id
  654. fTitle = fields.title
  655. fAllDay = fields.allDay
  656. fStartDate = fields.startDate
  657. fStartTime = fields.startTime
  658. fEndDate = fields.endDate
  659. fEndTime = fields.endTime
  660. fPlace = fields.place
  661. fNotes = fields.notes
  662. isNew = fresh
  663. fCustom = fields.custom
  664. remRows = withIndex(fields.rows)
  665. syncCustom()
  666. formHeading = heading
  667. formError = ''
  668. formClass = 'open'
  669. syncForm()
  670. }
  671. // one click on the day list: an event button edits that event, anywhere else on a day adds one to that day
  672. on dayClick(e) {
  673. if (!signedIn) { return null }
  674. li = e.target.closest('li')
  675. if (li == null) { return null }
  676. date = li.querySelector('time').getAttribute('datetime')
  677. b = e.target.closest('button.event')
  678. if (b == null) {
  679. fresh = blank(date, fZone)
  680. openForm(fresh, 'New event', true)
  681. return null
  682. }
  683. let j = 0
  684. while (j < events.length) {
  685. let ev = events[j]
  686. if (ev.id == b.value) {
  687. let 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 }
  688. openForm(fields, 'Edit event', false)
  689. return null
  690. }
  691. j = j + 1
  692. }
  693. }
  694. on setF(name, value) {
  695. if (name == 'title') { fTitle = value }
  696. if (name == 'startDate') { fStartDate = value }
  697. if (name == 'startTime') { fStartTime = value }
  698. if (name == 'endDate') { fEndDate = value }
  699. if (name == 'endTime') { fEndTime = value }
  700. if (name == 'place') { fPlace = value }
  701. if (name == 'notes') { fNotes = value }
  702. }
  703. on setCustom(own) {
  704. fCustom = own
  705. // switching to own reminders starts from the calendar's, so nothing has to be typed for the usual case
  706. if (own && remRows.length == 0) { remRows = withIndex(defaultRows) }
  707. syncCustom()
  708. }
  709. // one reminder row of the event editor (which = 'rem') or of the settings (which = 'set')
  710. on setRem(which, i, field, value) {
  711. rows = which == 'rem' ? remRows : setRows
  712. if (i < 0 || i >= rows.length) { return null }
  713. out = []
  714. let k = 0
  715. while (k < rows.length) {
  716. let r = rows[k]
  717. let n = r.n
  718. let unit = r.unit
  719. let time = r.time
  720. if (k == i && field == 'n') { n = value }
  721. if (k == i && field == 'unit') { unit = value }
  722. if (k == i && field == 'time') { time = value }
  723. out.push({ unit = unit n = n time = time })
  724. k = k + 1
  725. }
  726. if (which == 'rem') { remRows = withIndex(out) } else { setRows = withIndex(out) }
  727. }
  728. on addRem(which) {
  729. rows = which == 'rem' ? remRows : setRows
  730. out = []
  731. let k = 0
  732. while (k < rows.length) { out.push({ unit = rows[k].unit n = rows[k].n time = rows[k].time }) k = k + 1 }
  733. out.push({ unit = 'minutes' n = '10' time = '09:00' })
  734. if (which == 'rem') { remRows = withIndex(out) } else { setRows = withIndex(out) }
  735. }
  736. on delRem(which, i) {
  737. rows = which == 'rem' ? remRows : setRows
  738. out = []
  739. let k = 0
  740. while (k < rows.length) {
  741. if (k != i) { out.push({ unit = rows[k].unit n = rows[k].n time = rows[k].time }) }
  742. k = k + 1
  743. }
  744. if (which == 'rem') { remRows = withIndex(out) } else { setRows = withIndex(out) }
  745. }
  746. // ---- the calendar settings: the default reminders ----
  747. // 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
  748. // component): opening it is the event that reads the device's state and the calendar's defaults
  749. on settingsToggled(e) {
  750. if (e.newState != 'open') { return null }
  751. // the menu button that opened this stands inside the menu's popover, so the browser keeps the menu open behind the dialog: close it
  752. document.getElementById('user-menu').hidePopover()
  753. // the menu is outside the month view: no pointer event of the month view came yet, so the page's browser state is read now —
  754. // the notification section is right on the first look (and a device that allowed notifications is subscribed)
  755. browserEnv()
  756. readPermission()
  757. r = emit server calSettingsLoad()
  758. if (r == null || r.error != null) {
  759. setError = r == null ? 'the settings need the server: you are offline' : r.error
  760. return null
  761. }
  762. setRows = withIndex(r.rows)
  763. setError = ''
  764. }
  765. // Escape closes it (a manual popover has no light dismiss: it must stay open when the menu, which opened it, closes)
  766. on settingsKey(e) {
  767. if (e.key == 'Escape') { document.getElementById('settingseditor').hidePopover() }
  768. }
  769. on saveSettings(e) {
  770. r = emit server calSettingsSave(setRows)
  771. if (r == null || r.error != null) {
  772. setError = r == null ? 'the settings could not be saved (offline?)' : r.error
  773. return null
  774. }
  775. document.getElementById('settingseditor').hidePopover()
  776. takeSoon(r)
  777. }
  778. on setKind(allDay) {
  779. fAllDay = allDay
  780. if (!allDay && fStartTime == '') { fStartTime = '09:00' }
  781. if (!allDay && fEndTime == '' && fEndDate != '') { fEndTime = '10:00' }
  782. syncForm()
  783. }
  784. on closeForm(e) {
  785. formClass = 'closed'
  786. }
  787. // what the form holds, as the face takes it
  788. formFields() {
  789. 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 }
  790. }
  791. // the event as the page shows it, for an event saved while offline (the server sends the real one when it is back)
  792. localView(f) {
  793. let allDay = f.allDay
  794. let last = f.endDate != '' ? f.endDate : f.startDate
  795. mine = []
  796. let k = 0
  797. while (k < f.reminders.length) { mine.push({ unit = f.reminders[k].unit n = f.reminders[k].n time = f.reminders[k].time }) k = k + 1 }
  798. return { id = f.id title = f.title allDay = allDay first = f.startDate last = last
  799. startDate = f.startDate startTime = allDay ? '' : f.startTime endDate = f.endDate endTime = allDay ? '' : f.endTime
  800. place = f.place notes = f.notes start = f.startDate zone = f.zone custom = f.custom rows = f.custom ? mine : defRows }
  801. }
  802. on saveEvent(e) {
  803. f = formFields()
  804. if (fTitle.trim() == '' || fStartDate == '') {
  805. formError = 'the event needs a title and a start date'
  806. return null
  807. }
  808. r = emit server calSave(f, winFirst, winLast)
  809. if (r == null) {
  810. // OFFLINE: the save waits in the app's queue (it is sent when the connection is back); here the event and its
  811. // reminders are set at once, so the notification still comes
  812. if (f.id == '') { f.id = 'local-' + Date.now() }
  813. emit server calSaveQueued(f, winFirst, winLast)
  814. v = localView(f)
  815. evs = []
  816. let k = 0
  817. while (k < events.length) { if (events[k].id != v.id) { evs.push(events[k]) } k = k + 1 }
  818. evs.push(v)
  819. mine = []
  820. k = 0
  821. while (k < soon.length) { if (soon[k].id != v.id) { mine.push(soon[k]) } k = k + 1 }
  822. 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 })
  823. soon = mine
  824. formClass = 'closed'
  825. show(year, month, evs)
  826. arm()
  827. return null
  828. }
  829. if (r.error != null) {
  830. formError = r.error
  831. return null
  832. }
  833. formClass = 'closed'
  834. takeSoon(r)
  835. show(year, month, r.events)
  836. }
  837. on deleteEvent(e) {
  838. r = emit server calDelete(fId, winFirst, winLast)
  839. if (r == null || r.error != null) {
  840. formError = r == null ? 'the event could not be deleted (offline?)' : r.error
  841. return null
  842. }
  843. formClass = 'closed'
  844. takeSoon(r)
  845. show(year, month, r.events)
  846. }

Branches

Latest commits

  • 2dd53dccP1: one reminder shows once: arm() one at a time, the page skips reminders the server already pushed; push-twice gatemre
  • 3a29760aC13 report (handoff)mre
  • 33ab66ffCalendar: notification controls move from the month view into Reminder settings (user menu), one consistent state, state read when the dialog opensmre
  • 682a5b43reports: calendar gate countsmre
  • 876d22b2reports/H1-hydrate.mdmre
  • ef0cae45tests/dst.mjs: wait for hydration instead of a fixed 2.5 s sleep before clicking #gomre
  • d9cadecatests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • efa61227re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • 7808adbecalendar#12: report 011, LOG, STATUS, push-shots-testmre
  • df2e4fa0calendar#12: test push rate limit (1 per 30 s per device), owner-only gate checksmre
  • acb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mre
  • 0b222eb8tests: e2e-theme CDP port default from E2E_THEME_CDP_PORT (8756 unchanged)mre
  • 8b8a5abare-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • a69b27f9docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 1a97edfdcalendar mission 010: reminder rows at 390 px (the 7-column month grid no longer catches the reminder lists), gate checks, settings-shots, reportmre
  • 61b21404calendar mission 009: reminder times on hl:time in the browser (lib/push-plan.hl and the Intl code removed), DST gate tests/dst.mjs, E2E script, reportmre
  • 875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre
  • ce16a4efdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • f490bc8cdeploy: Web Push gate tests/push.mjs (PUSH_GATE_PORT)mre
  • 3af29fc8calendar mission 008 (A8): report, README, LOG, push-shots.mjsmre