@tristan2828/ui-foundation 4.103.0 → 4.104.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,7 +13,7 @@ to the device, where the app's service worker shows it.
13
13
  | `usePushPermission()` | the package | Whether this device gets reminders, and `enable`/`disable` |
14
14
  | `AllowReminders` | the package | The control: says what reminders are, then asks, on a click |
15
15
  | `/push/public-key`, `/push/subscriptions` | `openapi.yaml`, the foundation's part (optional) | The VAPID key to subscribe with; this device's subscription saved or dropped |
16
- | `foundation_backend.push` | `ui-foundation-backend` | `send_push(session, user_id, title, body, url)`: encrypted (RFC 8291), signed (VAPID), to every device the user allowed |
16
+ | `foundation_backend.push` | `ui-foundation-backend` | `send_push(session, user_id, title, body, url)`: encrypted (RFC 8291), signed (VAPID), to every device the user allowed; optionally a `PushAction` button and `renotify` |
17
17
  | `foundation_backend.reminders`, `reminders` | `ui-foundation-backend` | A reminder row (when, which days, the text, the path), and the `send-reminders` job that sends each one when it's due |
18
18
 
19
19
  Off until the backend turns it on (`PUSH_ENABLED`, `docs/deploy.md`
@@ -149,8 +149,9 @@ the same rules and agree on every next occurrence.
149
149
  - **Done**: the app's Done button (or a notification action that calls
150
150
  the app) runs `reminders.mark_done(row)` and commits: the occurrence is
151
151
  recorded (`done_occurrence`, `done_at`), nagging stops, and the next is
152
- pending; for `fromCompletion` it counts from the done time. After the
153
- rule itself changes, `reminders.schedule_changed(row)` forgets where it
152
+ pending; for `fromCompletion` it counts from the done time (and from
153
+ the notification itself: "A Done button on the notification" below).
154
+ After the rule itself changes, `reminders.schedule_changed(row)` forgets where it
154
155
  was.
155
156
  - **Moving a simple schedule over**: `recurrence.from_weekdays(days,
156
157
  time_of_day, time_zone, start=today)` (and the package's
@@ -164,6 +165,52 @@ the same rules and agree on every next occurrence.
164
165
  `formatOccurrence` for a Next one (cell-patterns.md "A repeat and its
165
166
  next time").
166
167
 
168
+ ## A Done button on the notification (4.104)
169
+
170
+ A repeating reminder's push can carry a **Done** button that marks the
171
+ occurrence done without opening the app. The app names its own endpoint;
172
+ the job puts it on each occurrence's push:
173
+
174
+ ```python
175
+ from foundation_backend import push, reminders
176
+
177
+ reminders.register(
178
+ model=MyReminder,
179
+ done_action=lambda row, occurrence: push.PushAction(
180
+ f"/api/reminders/{row.id}/done", {"occurrence": occurrence.isoformat()}
181
+ ),
182
+ )
183
+ ```
184
+
185
+ - **The endpoint is the app's**: an ordinary signed-in route
186
+ (`POST /reminders/{id}/done`, body `{ occurrence }`) that loads the
187
+ user's own row, checks the occurrence is still the pending one (a tap
188
+ on an old notification marks nothing), runs `reminders.mark_done(row)`
189
+ and commits. Answer 2xx when done or already done; anything else counts
190
+ as a failure. Return nothing the worker needs to read.
191
+ - **What the service worker does** (`/push-sw.js`, from `pwa()`): shows
192
+ the button where the browser has notification buttons (Chrome, Edge,
193
+ Firefox on desktop, Chrome on Android). Tapped, it POSTs the action's
194
+ body as JSON to its path on the app's own origin with the session
195
+ cookie (`credentials: 'same-origin'`), and opens no window. Done, the
196
+ notification closes. Refused (signed out, a 4xx or 5xx) or offline, it
197
+ opens the reminder's `url` instead, so the person can do it in the app.
198
+ - **iOS Safari and any browser without buttons** shows the notification
199
+ without one; a tap opens the `url` as always. Keep a Done button on the
200
+ reminder's own page.
201
+ - **Only the app's own paths.** `PushAction`'s `path` (like `url`) must
202
+ start with one `/`: `send_push` refuses `https://...`, `//host`, a
203
+ backslash or a control character, and the worker checks again and
204
+ drops a button whose path resolves to any other origin.
205
+ - **Nags sound again.** A nag is re-sent under the same tag
206
+ (`reminder-{id}`), which a browser otherwise replaces silently; the job
207
+ sends it with `renotify`, so it rings again. `send_push(..., tag=...,
208
+ renotify=True, action=PushAction(...))` does the same for an app's own
209
+ pushes.
210
+ - **A weekday-set reminder** (no `recurrence`) has no occurrence to mark,
211
+ so it gets no button. Left out, `done_action` adds none: pushes look as
212
+ before.
213
+
167
214
  ## Testing
168
215
 
169
216
  Under MSW the page is held by MSW's service worker, so `usePushPermission`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.103.0",
3
+ "version": "4.104.0",
4
4
  "description": "Shared UI foundation for contract-first, database-backed React apps: shadcn primitives, DataTable/EntityForm composites, auth, the gateway error seam, design tokens, lint rules and the AI playbook.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/vite/push-sw.js CHANGED
@@ -4,11 +4,46 @@
4
4
  // usePushPermission's enable(), not on load. ICON is set by pwa().
5
5
  /* global self, clients */
6
6
  const ICON = '__ICON__'
7
+ const ACTION = 'action'
7
8
 
8
9
  self.addEventListener('install', () => self.skipWaiting())
9
10
  self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()))
10
11
 
11
- // app/push.py sends {title, body, url, tag}. Anything else still shows.
12
+ // The app's own address for `path`, or null: a path with one leading /,
13
+ // no backslash or control character, that resolves to this origin. A
14
+ // payload naming anywhere else (https://..., //host, /\host) gets null, so
15
+ // the worker never opens or posts to another site.
16
+ function appUrl(path) {
17
+ if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//')) return null
18
+ if (/[\\\u0000-\u001f]/.test(path)) return null
19
+ let url
20
+ try {
21
+ url = new URL(path, self.location.origin)
22
+ } catch {
23
+ return null
24
+ }
25
+ return url.origin === self.location.origin ? url : null
26
+ }
27
+
28
+ // The payload's button (PushAction in foundation_backend.push), checked:
29
+ // a title, an app path and a JSON object body. Anything else is no button.
30
+ function readAction(action) {
31
+ if (!action || typeof action !== 'object') return null
32
+ const title = typeof action.title === 'string' ? action.title.trim().slice(0, 40) : ''
33
+ const url = appUrl(action.path)
34
+ if (!title || !url) return null
35
+ const body = action.body && typeof action.body === 'object' && !Array.isArray(action.body) ? action.body : {}
36
+ return { title, path: url.pathname + url.search, body }
37
+ }
38
+
39
+ // Whether this browser shows notification buttons. iOS Safari doesn't
40
+ // (no Notification.maxActions): it gets the notification without one.
41
+ function showsActions() {
42
+ return typeof Notification !== 'undefined' && Number(Notification.maxActions) > 0
43
+ }
44
+
45
+ // foundation_backend.push sends {title, body, url, tag, renotify, action}.
46
+ // Anything else still shows.
12
47
  self.addEventListener('push', (event) => {
13
48
  let data = {}
14
49
  try {
@@ -16,31 +51,69 @@ self.addEventListener('push', (event) => {
16
51
  } catch {
17
52
  data = { body: event.data ? event.data.text() : '' }
18
53
  }
19
- const options = { body: data.body || '', icon: ICON, data: { url: data.url || '/' } }
20
- if (data.tag) options.tag = data.tag
54
+ if (!data || typeof data !== 'object') data = {}
55
+ const action = readAction(data.action)
56
+ const options = { body: data.body || '', icon: ICON, data: { url: data.url || '/', action } }
57
+ if (data.tag) {
58
+ options.tag = data.tag
59
+ // A nag re-sent under the same tag sounds again instead of replacing quietly.
60
+ if (data.renotify === true) options.renotify = true
61
+ }
62
+ if (action && showsActions()) options.actions = [{ action: ACTION, title: action.title }]
21
63
  event.waitUntil(self.registration.showNotification(data.title || 'Reminder', options))
22
64
  })
23
65
 
24
- // Opens the message's path in the app: in a window already open on the
25
- // app if there is one, else a new one. Never another site.
66
+ // Opens `target` in the app: in a window already open on the app if there
67
+ // is one, else a new one.
68
+ async function openApp(target) {
69
+ const windows = await clients.matchAll({ type: 'window', includeUncontrolled: true })
70
+ const open = windows.find((client) => new URL(client.url).origin === target.origin)
71
+ if (open) {
72
+ await open.focus()
73
+ try {
74
+ await open.navigate(target.href)
75
+ return
76
+ } catch {
77
+ // An uncontrolled window can't be navigated from here.
78
+ }
79
+ }
80
+ await clients.openWindow(target.href)
81
+ }
82
+
83
+ // The button: POSTs its body to the app's path with the session cookie,
84
+ // opening nothing. Done, the notification goes; refused or offline, it
85
+ // opens the message's path so the person can do it in the app.
86
+ async function runAction(notification, action, target) {
87
+ const url = appUrl(action.path)
88
+ let ok = false
89
+ if (url) {
90
+ try {
91
+ const response = await fetch(url.href, {
92
+ method: 'POST',
93
+ credentials: 'same-origin',
94
+ headers: { 'Content-Type': 'application/json' },
95
+ body: JSON.stringify(action.body || {}),
96
+ })
97
+ ok = response.ok
98
+ } catch {
99
+ ok = false
100
+ }
101
+ }
102
+ notification.close()
103
+ if (!ok && target) await openApp(target)
104
+ }
105
+
106
+ // A tap opens the message's path; the button runs its action. Never
107
+ // another site.
26
108
  self.addEventListener('notificationclick', (event) => {
109
+ const data = event.notification.data || {}
110
+ const target = appUrl(data.url || '/')
111
+ const action = event.action === ACTION ? readAction(data.action) : null
112
+ if (action) {
113
+ event.waitUntil(runAction(event.notification, action, target))
114
+ return
115
+ }
27
116
  event.notification.close()
28
- const target = new URL((event.notification.data && event.notification.data.url) || '/', self.location.origin)
29
- if (target.origin !== self.location.origin) return
30
- event.waitUntil(
31
- (async () => {
32
- const windows = await clients.matchAll({ type: 'window', includeUncontrolled: true })
33
- const open = windows.find((client) => new URL(client.url).origin === target.origin)
34
- if (open) {
35
- await open.focus()
36
- try {
37
- await open.navigate(target.href)
38
- return
39
- } catch {
40
- // An uncontrolled window can't be navigated from here.
41
- }
42
- }
43
- await clients.openWindow(target.href)
44
- })(),
45
- )
117
+ if (!target) return
118
+ event.waitUntil(openApp(target))
46
119
  })
package/vite/pwa.js CHANGED
@@ -12,7 +12,8 @@
12
12
  // plain PNGs in the theme colour (iOS's Home Screen icon must be a PNG,
13
13
  // and drawing a letter into one needs a font rasteriser the package
14
14
  // doesn't carry). `icon` replaces them all with the app's own PNG.
15
- // - /push-sw.js: ./push-sw.js, showing pushes and opening their path.
15
+ // - /push-sw.js: ./push-sw.js, showing pushes, opening their path, and
16
+ // posting a message's action (a Done button) to the app's own path.
16
17
  // And adds the manifest, theme-color and apple-touch-icon tags to
17
18
  // index.html. Registering the worker is usePushPermission's, on a click.
18
19
  //