gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7808adbe7808adbecalendar#12: report 011, LOG, STATUS, push-shots-testmre7808adbe/components/month-view/month-view.hl

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

Branches

Latest commits

  • 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
  • f91f3663calendar mission 008 (A8): push only asked of the browser when the app has the VAPID settings (pushAvailable); real-FCM E2E scripts (push-real-app.mjs, push-real.mjs)mre
  • bf571badcalendar mission 008 (A8): Turn off on this device (unsubscribes the browser, server drops the device, choice kept), subscribe/refresh when the app is shown again; push gate part 3mre
  • 50985708calendar mission 008 (A7): Web Push report, README, mission, LOGmre
  • ee318774calendar mission 008 (A7): push-real.mjs, push sent log linemre
  • ebda0fd1calendar mission 008 (A7): server-side reminder plan on hl:time (push-plan.hl; hl:time fromLocal in a browser static is refused: repro .scratch/hltime-client), push gate 9/9mre
  • d063dad3calendar mission 008 (A7): Web Push (WIP): lib/push.hl subscriptions + sender clock, faces calPushSave/calPushOff, button subscribes, VAPID tool, tests/push.mjs; instantOf on hl:timemre
  • cf175c80calendar mission 008 (A7): re-vendor Hybriel master 0e3c9830 (bin 9d957fed, plugins whole: hl:crypto Web Push primitives, hl:web sendPush)mre
  • 9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre