gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf20313aaf20313aa|||PR bound calendar context and recover state across account changes and resyncsAtlasf20313aa/components/main.hl

17.3 KB

  1. import { mergeEvents, inWindow } from '../lib/calendar-cache.hl'
  2. import { isDate, pad } from '../lib/dates.hl'
  3. import { savePush, dropPush, testPush, pushedUntil } from '../lib/push.hl'
  4. import ReminderSettings from './reminder-settings.hl'
  5. import { serverToday } from '../lib/clock.hl'
  6. import { upcoming, eventsBetween, settingsView, contextFor } from '../lib/events.hl'
  7. import { defaultsOf } from '../lib/settings.hl'
  8. import { pushConfigured } from '../lib/util.hl'
  9. import { plan, missed, shift, describe } from '../lib/reminders.hl'
  10. // components/main.hl — THE SHELL (mission 006, phone first on the WorldAPI theme): the theme's AppHeader (brand · main menu ·
  11. // user icon), the phone's Sidebar (☰ → the main menu) and the slot every page renders into; the pages render
  12. // in the theme's ContentFirst shell (a month is one big content area, no list beside it; ContentFirst without a desktop sidebar
  13. // gives it the whole 72rem column). The theme's shell files theme/shell/*.hl are never
  14. // edited here. The shell's own CSS is the Style block below; components/styles.hl keeps only the site-wide rules.
  15. // IDENT'S SELECTOR STANDS IN THE HEADER, visible signed in and signed out, on the phone and on the desktop (creator 2026-10-24: the
  16. // theme move hid it behind an icon and replaced it by the user menu — never again; the gate checks it at 390 and 1280). Signed in the
  17. // user icon beside it opens the UserMenu (Log out, Reminder settings). Nothing else stands beside the selector: no second "Log in" button (creator 2026-10-24).
  18. // THE SELECTOR: `<ident-selector key=IDENT_API_KEY>` from <ident>/selector.js, as in gitoria. Choosing an identity
  19. // fires `ident-login` (one-time code); /login.js hands it to the hidden input #identcode, whose `change` goes to the
  20. // face calendarLogin (server-side exchange, lib/users.hl userOfLoginCode; no reload). The element's class is `in` / `out`; /login.js mirrors it into
  21. // the selector's `loggedIn`.
  22. // LOGIN: a plain link to <ident>/login?key=&return=<public url>/login/callback (lib/api.hl loginCallback).
  23. // After a login or logout in this tab the page is fetched again (navigate('/')): the calendar of the session show.
  24. import { navigate, notify, subscribePush } from 'hl:web'
  25. import { siteName } from '../project.hl'
  26. import { identKey, callbackUrl, selectorScript, userIdOfSession, userOfLoginCode } from '../lib/users.hl'
  27. import { randomBytes } from 'hl:crypto'
  28. import AppHeader from '../theme/shell/app-header.hl'
  29. import MainMenu from '../theme/shell/main-menu.hl'
  30. import Sidebar from '../theme/shell/app-sidebar.hl'
  31. import ContentFirst from '../theme/shell/content-first.hl'
  32. userId = userIdOfSession(session)
  33. signedIn = userId != null
  34. today = serverToday()
  35. slot = null
  36. session = null
  37. loggedIn = userIdOfSession(session) != null
  38. loggedOut = userIdOfSession(session) == null
  39. selectorClass = loggedIn ? 'in' : 'out'
  40. selectorKey = identKey
  41. // where the selector's sign-in panel (ident#31) sends the browser: the login button's callback, with the page the user is on as `next`
  42. // (the callback takes it back there). No route known (first paint) = no `next` = the start page.
  43. route = null
  44. path = route == null ? '' : route.path
  45. selectorReturn = callbackUrl + (path == '' ? '' : '?next=' + encodeURIComponent(path))
  46. identScript = selectorScript
  47. loginError = ''
  48. hasLoginError = false
  49. // the main menu: the header from 60rem, the phone's sidebar below — one list (one page so far; the menu is the shell's place for more)
  50. menu = [ { label = 'Calendar' href = '/' } ]
  51. // The shell's own styles (calendar#16): the header's login widgets — ident's selector, the sign-in error banner and Log out.
  52. // ident's selector stands top right, signed in AND signed out, on the phone and on the desktop — never behind an icon or a popover
  53. // (creator 2026-10-24, "you removed the ident widget from all sites"). Its shadow DOM is in ident's design, restyled to the accent through its
  54. // custom properties and parts; the pill is kept compact so brand, selector and the user icon fit one row at 390 px. Its dropdown opens under it,
  55. // as wide as a phone allows. Colours are the theme's css variables (a component cannot import tokens.hl).
  56. Style {
  57. identSelector {
  58. '--ident-accent' = 'var(--color-accent)'
  59. '--ident-accent-text' = 'var(--color-accent-text)'
  60. '--ident-background' = 'var(--color-surface)'
  61. '--ident-border' = 'var(--color-surface)'
  62. '--ident-font' = '600 .9rem/1.3 system-ui, sans-serif'
  63. position = 'relative'
  64. flex = '0 1 auto'
  65. minWidth = '0'
  66. }
  67. 'ident-selector::part(button)' {
  68. minHeight = 'var(--layout-tap)'
  69. padding = '.25rem .6rem'
  70. whiteSpace = 'nowrap'
  71. }
  72. 'ident-selector::part(status)' {
  73. minHeight = 'var(--layout-tap)'
  74. padding = '.25rem .6rem'
  75. whiteSpace = 'nowrap'
  76. overflow = 'hidden'
  77. textOverflow = 'ellipsis'
  78. }
  79. 'ident-selector::part(identity)' {
  80. minHeight = 'var(--layout-tap)'
  81. }
  82. 'ident-selector::part(panel)' {
  83. position = 'absolute'
  84. top = '100%'
  85. right = '0'
  86. zIndex = '30'
  87. width = 'min(20rem, calc(100vw - 2 * var(--layout-gutter)))'
  88. maxWidth = 'none'
  89. boxShadow = '0 .75rem 2rem var(--color-background-sunken)'
  90. }
  91. #loginerror {
  92. margin = '0'
  93. padding = '.5rem var(--layout-gutter)'
  94. background = 'var(--color-background-sunken)'
  95. }
  96. #logout {
  97. flex = 'none'
  98. whiteSpace = 'nowrap'
  99. padding = '.25rem .5rem'
  100. }
  101. }
  102. View {
  103. body {
  104. AppHeader { brand = siteName
  105. MainMenu { items = menu }
  106. // ident's selector stands in the header, visible signed in AND signed out, on the phone and on the desktop (signed in it shows the
  107. // chosen identity). /login.js mirrors its state from the class (`in` / `out`). Nothing else stands beside it: no second "Log in" button (creator 2026-10-24).
  108. identSelector { id = "selector" key = selectorKey return = selectorReturn class = selectorClass }
  109. // signed in, like before the theme missions: Log out stands beside the selector (Reminder settings is on the month page)
  110. if (loggedIn) {
  111. button { id = "logout" type = "button" class = "quiet" "Log out" on click(Hybrid e) { emit doLogout(e) } }
  112. }
  113. }
  114. input { id = "identcode" type = "hidden" on change(Hybrid e) { emit gotCode(e) } }
  115. if (hasLoginError) { p { id = "loginerror" class = "message banner" loginError } }
  116. // the phone's overlay with the main menu (desktop = "false": the header shows the menu from 60rem); then the page in the
  117. // content-first shell — hybriel#130: the page slot starts its own line
  118. Sidebar { desktop = "false" MainMenu { items = menu } }
  119. main {
  120. ContentFirst { slot }
  121. }
  122. ReminderSettings { ownerId = userId askClass = askClass blockedClass = blockedClass plannedText = plannedText pushText = pushText pushOffClass = pushOffClass }
  123. script { src = identScript }
  124. script { src = "/login.js" }
  125. }
  126. }
  127. showIn = (String id) => {
  128. if (userId != id) {
  129. allEvents = []
  130. localEdits = []
  131. soon = []
  132. defRows = []
  133. defaultText = ''
  134. pushTried = false
  135. pushOn = false
  136. }
  137. userId = id
  138. signedIn = true
  139. loggedIn = true
  140. loggedOut = false
  141. selectorClass = 'in'
  142. loginError = ''
  143. hasLoginError = false
  144. }
  145. showOut = () => {
  146. allEvents = []
  147. localEdits = []
  148. soon = []
  149. defRows = []
  150. defaultText = ''
  151. pushTried = false
  152. pushOn = false
  153. userId = null
  154. signedIn = false
  155. arm()
  156. loggedIn = false
  157. loggedOut = true
  158. selectorClass = 'out'
  159. }
  160. // the selector's code (via /login.js and the hidden input) → the server exchanges it
  161. on gotCode(Hybrid e) {
  162. code = e.target.value
  163. e.target.value = ''
  164. if (code == null || code == '') { return null }
  165. r = emit server calendarLogin(code)
  166. if (r == null || r.error != null) {
  167. loginError = r != null ? r.error : 'the login failed'
  168. hasLoginError = true
  169. return null
  170. }
  171. showIn(r.userId)
  172. navigate('/')
  173. }
  174. on client calendarSignedIn(String tag, String id) {
  175. showIn(id)
  176. navigate('/')
  177. }
  178. on client calendarSignedOut(String tag) {
  179. showOut()
  180. navigate('/')
  181. }
  182. on doLogout(Hybrid e) {
  183. emit server calendarLogOut()
  184. showOut()
  185. navigate('/')
  186. }
  187. // ---- the faces (the trailing `session` is always the server's: hybriel #16) ----
  188. on server calendarLogin(code, session) {
  189. if (session == null) { return { error = 'no session — reload the page' } }
  190. x = userOfLoginCode(code)
  191. if (x.error != null) { return { error = x.error } }
  192. tag = randomBytes(16)
  193. session.user = { id = x.user.id }
  194. session.data.tag = tag
  195. emit client calendarSignedIn(tag, x.user.id)
  196. fresh = contextFor(x.user.id, serverToday())
  197. emit client calendarChanged(x.user.id, fresh.events, fresh)
  198. return { ok = true userId = x.user.id }
  199. }
  200. on server calendarLogOut(session) {
  201. if (session == null) { return { error = 'no session' } }
  202. emit client calendarSignedOut(session.data.tag)
  203. session.user = null
  204. return { ok = true }
  205. }
  206. initialContext = signedIn ? contextFor(userId, today) : null
  207. Hybrid allEvents = []
  208. Hybrid localEdits = []
  209. String contextDay = ''
  210. Hybrid soon = []
  211. String defaultText = ''
  212. Hybrid defRows = []
  213. Hybrid timers = []
  214. Number lastArm = 0
  215. Number arming = 0
  216. Number armAgain = 0
  217. String notifyState = 'unknown'
  218. String askClass = 'hidden'
  219. String blockedClass = 'hidden'
  220. String plannedText = ''
  221. String pushText = ''
  222. Boolean pushTried = false
  223. Boolean pushAvailable = pushConfigured
  224. String pushOffClass = 'hidden'
  225. Boolean pushIsOff = false
  226. Boolean pushOn = false
  227. String fZone = 'UTC'
  228. {
  229. contextDay = today
  230. if (initialContext != null) {
  231. allEvents = initialContext.events
  232. soon = initialContext.soon
  233. defaultText = initialContext.defaults
  234. defRows = initialContext.defaultRows
  235. }
  236. }
  237. deviceZone() {
  238. z = Intl.DateTimeFormat().resolvedOptions().timeZone
  239. return z != null && z != '' ? z : 'UTC'
  240. }
  241. takeSoon(Hybrid r) {
  242. soon = r.soon
  243. if (r.defaults != null) { defaultText = r.defaults }
  244. if (r.defaultRows != null) { defRows = r.defaultRows }
  245. arm()
  246. }
  247. arm() {
  248. if (arming == 1) {
  249. armAgain = 1
  250. return null
  251. }
  252. arming = 1
  253. armOnce()
  254. while (armAgain == 1) {
  255. armAgain = 0
  256. armOnce()
  257. }
  258. arming = 0
  259. return null
  260. }
  261. armOnce() {
  262. let i = 0
  263. while (i < timers.length) { clearTimeout(timers[i]) i = i + 1 }
  264. timers = []
  265. if (!signedIn) { return null }
  266. today = deviceDay()
  267. if (lastArm == 0) { contextDay = today }
  268. nowMs = Date.now()
  269. readPermission()
  270. let since = remindedUntil(nowMs)
  271. if (notifyState == 'granted') {
  272. since = pushedSince(since)
  273. late = missed(soon, since, nowMs, today, deviceZone())
  274. i = 0
  275. while (i < late.length) {
  276. q = late[i]
  277. notify(q.title, { body = q.late tag = q.key icon = '/icons/icon-192.png' })
  278. i = i + 1
  279. }
  280. }
  281. remember(nowMs)
  282. list = plan(soon, nowMs, 604800000, deviceZone())
  283. ids = []
  284. i = 0
  285. while (i < list.length) {
  286. // `p` is a new binding on every pass (hybriel #106): each timer keeps ITS reminder
  287. p = list[i]
  288. // F20 hybriel#446: replace by tag with notifyAt, cancel with cancelNotify when available.
  289. ids.push(setTimeout(() => {
  290. remember(p.at)
  291. notify(p.title, { body = p.body tag = p.key icon = '/icons/icon-192.png' })
  292. }, p.at - nowMs))
  293. i = i + 1
  294. }
  295. timers = ids
  296. lastArm = nowMs
  297. // calendar#9 part 2: a device that already allowed notifications is subscribed to Web Push once per page (its own handler:
  298. // the browser's subscribe can take long and must not hold the timers)
  299. if (!pushTried && notifyState == 'granted') {
  300. pushTried = true
  301. emit pushEnsure(1)
  302. }
  303. plannedText = list.length == 0 ? '' : (list.length == 1 ? '1 reminder' : list.length + ' reminders') + ' set for the next 7 days'
  304. }
  305. pushedSince(Number own) {
  306. if (!pushAvailable || pushOffKept()) { return own }
  307. reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : null
  308. sub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : null
  309. if (sub == null) { return own }
  310. r = emit server calPushedUntil(sub.endpoint)
  311. return r != null && r.since != null && r.since > own ? r.since : own
  312. }
  313. remindedKey() {
  314. return 'calendar-reminded-until-' + userId
  315. }
  316. remindedUntil(Number nowMs) {
  317. store = window.localStorage
  318. kept = store != null ? store.getItem(remindedKey()) : null
  319. return kept != null && kept != '' ? toNumber(kept) : nowMs - 43200000
  320. }
  321. remember(Number at) {
  322. store = window.localStorage
  323. if (store == null) { return null }
  324. kept = store.getItem(remindedKey())
  325. if (kept == null || kept == '' || toNumber(kept) < at) { store.setItem(remindedKey(), '' + at) }
  326. }
  327. readPermission() {
  328. n = window.Notification
  329. notifyState = n == null ? 'unsupported' : n.permission
  330. pushIsOff = pushOffKept()
  331. showControls()
  332. }
  333. showControls() {
  334. askClass = !pushOn && (notifyState == 'default' || (notifyState == 'granted' && pushIsOff)) ? '' : 'hidden'
  335. blockedClass = notifyState == 'denied' ? '' : 'hidden'
  336. pushOffClass = pushOn ? '' : 'hidden'
  337. if (!pushOn && notifyState == 'unsupported') { pushText = 'This browser cannot show notifications.' }
  338. if (!pushOn && pushText == '') { pushText = 'Reminders show while the calendar is open on this device.' }
  339. }
  340. askNotify(Hybrid e) {
  341. refreshDevice()
  342. notify('Notifications are on', { body = 'Your reminders show up here.' })
  343. pushTried = true
  344. pushOffKeep(false)
  345. readPermission()
  346. emit pushEnsure(1)
  347. }
  348. pushOff(Hybrid e) {
  349. refreshDevice()
  350. pushOffKeep(true)
  351. reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : null
  352. sub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : null
  353. if (sub != null) {
  354. endpoint = sub.endpoint
  355. sub.unsubscribe()
  356. emit server calPushOff(endpoint)
  357. }
  358. pushOn = false
  359. pushText = 'Reminders show while the calendar is open on this device.'
  360. readPermission()
  361. }
  362. pushTest(Hybrid e) {
  363. refreshDevice()
  364. reg = navigator.serviceWorker != null ? navigator.serviceWorker.getRegistration() : null
  365. sub = reg != null && reg.pushManager != null ? reg.pushManager.getSubscription() : null
  366. if (sub == null) {
  367. pushText = 'This device is not subscribed: tap "Turn on notifications" first.'
  368. return null
  369. }
  370. r = emit server calPushTest(sub.endpoint)
  371. 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')
  372. }
  373. pushOffKey() {
  374. return 'calendar-push-off-' + userId
  375. }
  376. pushOffKept() {
  377. store = window.localStorage
  378. return store != null && store.getItem(pushOffKey()) == '1'
  379. }
  380. pushOffKeep(Boolean off) {
  381. store = window.localStorage
  382. if (store == null) { return null }
  383. if (off) { store.setItem(pushOffKey(), '1') } else { store.removeItem(pushOffKey()) }
  384. pushIsOff = off
  385. }
  386. on pushEnsure(Number n) {
  387. if (!signedIn || !pushAvailable || notifyState != 'granted' || pushOffKept()) { return null }
  388. sub = subscribePush()
  389. if (sub == null) {
  390. pushText = 'Reminders show while the calendar is open on this device.'
  391. pushOn = false
  392. showControls()
  393. return null
  394. }
  395. r = emit server calPushSave(sub, fZone)
  396. 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.'
  397. pushOn = r != null && r.ok
  398. showControls()
  399. }
  400. // F20 hybriel#367: browser-kept reminder watermark and device choice.
  401. // F20 hybriel#443: browser notification permission.
  402. // F20 hybriel#446: notifyAt(time, title, { tag }) and cancelNotify(tag) are not in day72.
  403. // Until they are available, armOnce cancels this layout's timers before re-arming.
  404. refreshDevice() {
  405. fZone = deviceZone()
  406. readPermission()
  407. day = deviceDay()
  408. if (signedIn && day != contextDay && lastArm > 0) { refreshContext(day) }
  409. if (Date.now() - lastArm > 600000) { arm() }
  410. }
  411. on client shown(Hybrid r) { refreshDevice() arm() }
  412. on client calendarChanged(String owner, Hybrid all, Hybrid r) {
  413. if (owner == userId) {
  414. allEvents = inWindow(mergeEvents(allEvents, all), shift(deviceDay(), -42), shift(deviceDay(), 42))
  415. pending = []
  416. for (q of localEdits) {
  417. let keep = true
  418. for (c of all) { if (q.id == c.id || q.id == c.ref) { keep = false } }
  419. if (keep) { pending.push(q) }
  420. }
  421. localEdits = pending
  422. takeSoon(r)
  423. }
  424. }
  425. localSoon(Hybrid v) {
  426. localEdits = mergeEvents(localEdits, [v])
  427. allEvents = mergeEvents(allEvents, [v])
  428. pending = []
  429. for (q of soon) { if (q.id != v.id) { pending.push(q) } }
  430. pending.push({ id = v.id title = v.title allDay = v.allDay startDate = v.startDate startTime = v.startTime place = v.place zone = v.zone rows = v.custom ? v.rows : defRows })
  431. soon = pending
  432. arm()
  433. }
  434. deviceDay() {
  435. d = new Date()
  436. return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate())
  437. }
  438. refreshContext(String day) {
  439. owner = userId
  440. r = emit server calContext(day)
  441. if (owner != userId || r == null || r.error != null) { return null }
  442. contextDay = day
  443. allEvents = mergeEvents(r.events, localEdits)
  444. takeSoon(r)
  445. }
  446. on client reconnected(Hybrid r) {
  447. if (signedIn && r.how == 'resynced') { refreshContext(deviceDay()) }
  448. }
  449. on server calContext(String day, session) {
  450. u = userIdOfSession(session)
  451. if (u == null || !isDate(day)) { return { error = 'not a signed-in date' } }
  452. result = contextFor(u, day)
  453. emit client calendarInvalidated(u)
  454. return result
  455. }
  456. on server calPushSave(sub, zone, session) {
  457. u = userIdOfSession(session)
  458. if (u == null) { return { error = 'log in with ident first' } }
  459. return savePush(u, sub, zone)
  460. }
  461. on server calPushTest(endpoint, session) {
  462. u = userIdOfSession(session)
  463. if (u == null) { return { error = 'log in with ident first' } }
  464. return testPush(u, endpoint)
  465. }
  466. on server calPushedUntil(endpoint, session) {
  467. u = userIdOfSession(session)
  468. if (u == null) { return { since = 0 } }
  469. return pushedUntil(u, endpoint)
  470. }
  471. on server calPushOff(endpoint, session) {
  472. u = userIdOfSession(session)
  473. if (u == null) { return { error = 'log in with ident first' } }
  474. return dropPush(u, endpoint)
  475. }

Branches

Latest commits

  • f20313aa|||PR bound calendar context and recover state across account changes and resyncsAtlas
  • 651752c0|||PR run the browser gate once per deployAtlas
  • e24e28a1|||PR preserve calendar state across month addresses and split dialogsAtlas
  • 384d3d23|||PR give calendar months their own addressAtlas
  • 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