@tristan2828/ui-foundation 4.102.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.
@@ -4,46 +4,46 @@
4
4
  ## Index
5
5
 
6
6
  - [The rules that apply to every cell](#the-rules-that-apply-to-every-cell) · lines 75–98
7
- - [1. Plain text](#1-plain-text) · lines 100–153
8
- - [2. Icon + label](#2-icon--label) · lines 155–178
9
- - [3. Icon in a badge](#3-icon-in-a-badge) · lines 180–193
10
- - [4. Icon only, label in a tooltip](#4-icon-only-label-in-a-tooltip) · lines 195–272
11
- - [Several values: the icons side by side, every name in one tooltip](#several-values-the-icons-side-by-side-every-name-in-one-tooltip) · lines 220–272
12
- - [5. Enum → tone-mapped badge](#5-enum--tone-mapped-badge) · lines 274–294
13
- - [6. Multi-value enum, clustered](#6-multi-value-enum-clustered) · lines 296–308
14
- - [7. Link as an outline button](#7-link-as-an-outline-button) · lines 310–331
15
- - [8. Date, relative](#8-date-relative) · lines 333–370
16
- - [9. Ordinal scale (bounded integer)](#9-ordinal-scale-bounded-integer) · lines 372–420
17
- - [Two variants the package draws: a step bar and a star](#two-variants-the-package-draws-a-step-bar-and-a-star) · lines 390–420
18
- - [10. Summary in the cell, detail in a popover](#10-summary-in-the-cell-detail-in-a-popover) · lines 422–472
19
- - [A second example: what a row depends on](#a-second-example-what-a-row-depends-on) · lines 440–472
20
- - [11. Number or currency — Unproven](#11-number-or-currency--unproven) · lines 474–514
21
- - [12. Boolean](#12-boolean) · lines 516–546
22
- - [13. Progress bar — Unproven](#13-progress-bar--unproven) · lines 548–584
23
- - [The compact form: `ProgressRing`](#the-compact-form-progressring) · lines 568–584
24
- - [14. Avatar and name — Unproven](#14-avatar-and-name--unproven) · lines 586–603
25
- - [15. Yes/no you flip in the row](#15-yesno-you-flip-in-the-row) · lines 605–714
26
- - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 631–714
27
- - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 716–751
28
- - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 753–826
29
- - [18. Editable value](#18-editable-value) · lines 828–1531
30
- - [Presets: one line per field](#presets-one-line-per-field) · lines 1163–1231
31
- - [Several fields edited as one](#several-fields-edited-as-one) · lines 1233–1269
32
- - [A link and its label](#a-link-and-its-label) · lines 1271–1295
33
- - [A list of sub-items](#a-list-of-sub-items) · lines 1297–1430
34
- - [In a table's rows](#in-a-tables-rows) · lines 1432–1517
35
- - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1519–1531
36
- - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1533–1599
37
- - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1601–1665
38
- - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1667–1765
39
- - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1767–1796
40
- - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1798–1836
41
- - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1838–1914
42
- - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1916–1939
43
- - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1941–2067
44
- - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2029–2067
45
- - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2069–2105
46
- - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2107–2152
7
+ - [1. Plain text](#1-plain-text) · lines 100–155
8
+ - [2. Icon + label](#2-icon--label) · lines 157–180
9
+ - [3. Icon in a badge](#3-icon-in-a-badge) · lines 182–195
10
+ - [4. Icon only, label in a tooltip](#4-icon-only-label-in-a-tooltip) · lines 197–274
11
+ - [Several values: the icons side by side, every name in one tooltip](#several-values-the-icons-side-by-side-every-name-in-one-tooltip) · lines 222–274
12
+ - [5. Enum → tone-mapped badge](#5-enum--tone-mapped-badge) · lines 276–296
13
+ - [6. Multi-value enum, clustered](#6-multi-value-enum-clustered) · lines 298–310
14
+ - [7. Link as an outline button](#7-link-as-an-outline-button) · lines 312–333
15
+ - [8. Date, relative](#8-date-relative) · lines 335–372
16
+ - [9. Ordinal scale (bounded integer)](#9-ordinal-scale-bounded-integer) · lines 374–422
17
+ - [Two variants the package draws: a step bar and a star](#two-variants-the-package-draws-a-step-bar-and-a-star) · lines 392–422
18
+ - [10. Summary in the cell, detail in a popover](#10-summary-in-the-cell-detail-in-a-popover) · lines 424–474
19
+ - [A second example: what a row depends on](#a-second-example-what-a-row-depends-on) · lines 442–474
20
+ - [11. Number or currency — Unproven](#11-number-or-currency--unproven) · lines 476–516
21
+ - [12. Boolean](#12-boolean) · lines 518–548
22
+ - [13. Progress bar — Unproven](#13-progress-bar--unproven) · lines 550–586
23
+ - [The compact form: `ProgressRing`](#the-compact-form-progressring) · lines 570–586
24
+ - [14. Avatar and name — Unproven](#14-avatar-and-name--unproven) · lines 588–605
25
+ - [15. Yes/no you flip in the row](#15-yesno-you-flip-in-the-row) · lines 607–716
26
+ - [A variant: a pressed icon inside another value's cell](#a-variant-a-pressed-icon-inside-another-values-cell) · lines 633–716
27
+ - [16. Title linking to the record's view](#16-title-linking-to-the-records-view) · lines 718–764
28
+ - [17. Quick action on the view](#17-quick-action-on-the-view) · lines 766–839
29
+ - [18. Editable value](#18-editable-value) · lines 841–1544
30
+ - [Presets: one line per field](#presets-one-line-per-field) · lines 1176–1244
31
+ - [Several fields edited as one](#several-fields-edited-as-one) · lines 1246–1282
32
+ - [A link and its label](#a-link-and-its-label) · lines 1284–1308
33
+ - [A list of sub-items](#a-list-of-sub-items) · lines 1310–1443
34
+ - [In a table's rows](#in-a-tables-rows) · lines 1445–1530
35
+ - [A table of a few short columns: `width="content"`](#a-table-of-a-few-short-columns-widthcontent) · lines 1532–1544
36
+ - [19. Stage circle for an ordered status](#19-stage-circle-for-an-ordered-status) · lines 1546–1612
37
+ - [20. Count linking to the related records](#20-count-linking-to-the-related-records) · lines 1614–1678
38
+ - [21. Rows grouped under headings, and a pill filter](#21-rows-grouped-under-headings-and-a-pill-filter) · lines 1680–1778
39
+ - [22. A highlighted row, and rows that are done](#22-a-highlighted-row-and-rows-that-are-done) · lines 1780–1809
40
+ - [24. A list's rows: hover, lines, rows per page](#24-a-lists-rows-hover-lines-rows-per-page) · lines 1811–1849
41
+ - [23. A Group menu, and a record read beside the list](#23-a-group-menu-and-a-record-read-beside-the-list) · lines 1851–1927
42
+ - [24. A stored colour beside its name](#24-a-stored-colour-beside-its-name) · lines 1929–1952
43
+ - [25. A list's tools: views, filters, columns, row actions, a phone's rows](#25-a-lists-tools-views-filters-columns-row-actions-a-phones-rows) · lines 1954–2080
44
+ - [The framed look, and sibling lists beside the title](#the-framed-look-and-sibling-lists-beside-the-title) · lines 2042–2080
45
+ - [26. A record's related list, capped](#26-a-records-related-list-capped) · lines 2082–2118
46
+ - [27. A repeat and its next time](#27-a-repeat-and-its-next-time) · lines 2120–2165
47
47
 
48
48
  <!-- /index -->
49
49
 
@@ -151,6 +151,8 @@ can't make the whole table thousands of pixels wide:
151
151
  reads the whole text either way, and the record shows it too.
152
152
  - `meta.maxWidth` alone caps the column and lets its text wrap, for a
153
153
  value worth reading whole in the row.
154
+ - The title column (the first) is cut this way already, with no `meta`
155
+ (pattern 16, 4.103).
154
156
 
155
157
  ## 2. Icon + label
156
158
 
@@ -749,6 +751,17 @@ cell: ({ row }) => (
749
751
  - **Cost:** none to speak of. Specs that match the title as a cell still
750
752
  work (`getByRole('cell', { name })` reads the link's text); ones that
751
753
  opened the form from a row button go through the view's Edit instead.
754
+ - **DataTable caps the title column (4.103).** The first column is the
755
+ title column: at every width it's cut to one line at 24rem (never over
756
+ 60% of the table's area) with an ellipsis, so a long title (a
757
+ discussion's topic) can't push the other columns off. A cut title shows
758
+ whole in a tooltip on hover and when its link takes focus; the link
759
+ stays the row's only tab stop, and a screen reader reads it whole. Put
760
+ the title column first and write no clip of your own (`truncate`,
761
+ `max-w-*`) around it. `meta: { wrap: true }` wraps it at the cap
762
+ instead, for a title worth reading whole in the row;
763
+ `meta: { maxWidth: 'none' }` lifts the cap. Its own `meta.clip` or
764
+ `meta.maxWidth` works as on any column (cut, or wrapped, at that width).
752
765
 
753
766
  ## 17. Quick action on the view
754
767
 
@@ -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`
@@ -22,9 +22,19 @@ declare module '@tanstack/table-core' {
22
22
  /**
23
23
  * The widest the column's content gets, as a CSS length: `'24rem'`
24
24
  * unless set, with `clip` (and never over 60% of the table's area, for
25
- * a phone). Without `clip`, the content wraps at it.
25
+ * a phone). Without `clip`, the content wraps at it. The title column
26
+ * (the first) is cut at 24rem when neither is set.
26
27
  */
27
28
  maxWidth?: string;
29
+ /**
30
+ * The title column (the table's first, the row's name): wrap at
31
+ * `maxWidth` (`'24rem'` unless set) instead of the default, one line cut
32
+ * at 24rem with an ellipsis. For a title worth reading whole in the row.
33
+ * A title column with `maxWidth: 'none'` has no cap at all (the look
34
+ * before 4.103); one with its own `clip` or `maxWidth` is cut or wrapped
35
+ * at it, as any column is.
36
+ */
37
+ wrap?: boolean;
28
38
  /**
29
39
  * The column's name in DataTable's Columns menu (`columnsMenu`), for a
30
40
  * column whose `header` isn't a string.
@@ -138,15 +138,20 @@ function PageSizeMenu({ pageSizes, value, onValueChange, }) {
138
138
  // A cell's text cut to one line (`meta.clip`). Only when it is cut does it
139
139
  // take a tab stop and a tooltip with the whole text, on hover and on focus;
140
140
  // re-measured on every render (the text may change) and on every resize.
141
- function ClippedText({ maxWidth, children }) {
141
+ // A cut cell whose content has a control of its own (the title's link)
142
+ // takes no tab stop: the control already has one, and focusing it opens
143
+ // the tooltip, since focus reaches the trigger from inside it.
144
+ function ClippedText({ maxWidth, slot = 'data-table-clip', children, }) {
142
145
  const ref = useRef(null);
143
146
  const [fullText, setFullText] = useState(null);
147
+ const [hasControl, setHasControl] = useState(false);
144
148
  const measure = () => {
145
149
  const element = ref.current;
146
150
  if (!element)
147
151
  return;
148
152
  const isCut = element.scrollWidth > element.clientWidth + 0.5;
149
153
  setFullText(isCut ? element.textContent?.trim() || null : null);
154
+ setHasControl(element.querySelector(ROW_CONTROL_SELECTOR) !== null);
150
155
  };
151
156
  useLayoutEffect(measure);
152
157
  useEffect(() => {
@@ -157,10 +162,10 @@ function ClippedText({ maxWidth, children }) {
157
162
  observer.observe(element);
158
163
  return () => observer.disconnect();
159
164
  }, []);
160
- return (_jsxs(Tooltip, { disabled: fullText === null, children: [_jsx(TooltipTrigger, { render: _jsx("span", { ref: ref, "data-slot": "data-table-clip", className: CLIP_CLASS,
165
+ return (_jsxs(Tooltip, { disabled: fullText === null, children: [_jsx(TooltipTrigger, { render: _jsx("span", { ref: ref, "data-slot": slot, className: slot === 'data-table-title' ? TITLE_CLIP_CLASS : CLIP_CLASS,
161
166
  // Never more than 60% of the table's area, so on a phone the
162
167
  // cut column leaves the name and the rest room.
163
- style: { maxWidth: `min(${maxWidth}, 60cqw)` }, tabIndex: fullText === null ? undefined : 0 }), children: children }), _jsx(TooltipContent, { className: "max-w-sm break-words whitespace-normal", children: fullText })] }));
168
+ style: { maxWidth: `min(${maxWidth}, 60cqw)` }, tabIndex: fullText === null || hasControl ? undefined : 0 }), children: children }), _jsx(TooltipContent, { className: "max-w-sm break-words whitespace-normal", children: fullText })] }));
164
169
  }
165
170
  // Whether the detail panel (`detailPanel`) fits beside the table, or opens
166
171
  // as a bottom sheet. Wide on the server and wherever matchMedia is missing
@@ -221,11 +226,15 @@ const HOVER_FOCUSED_ROW_CLASS = 'focus-visible:hover:[&>td:first-child]:shadow-[
221
226
  // A column's `meta.clip`: one line, cut at `meta.maxWidth` with an ellipsis.
222
227
  const DEFAULT_CLIP_WIDTH = '24rem';
223
228
  const CLIP_CLASS = 'block truncate rounded-sm outline-none focus-visible:ring-3 focus-visible:ring-ring/50';
229
+ // The title's: padding, taken back by the margin, keeps its link's focus
230
+ // ring clear of the cut.
231
+ const TITLE_CLIP_CLASS = cn(CLIP_CLASS, '-m-1 p-1');
224
232
  // A pinned first column's content, capped below md at 45% of the table's
225
233
  // scroll area (`cqw`: the container is an inline-size query container)
226
234
  // and wrapping, so a long title can't widen the column past the screen
227
235
  // and leave every other column scrolling underneath it (issue #91).
228
- // Wider screens are unchanged: the column sizes to its content.
236
+ // The title inside is capped at every width too (cut at 24rem, or
237
+ // wrapped with `meta.wrap`), so wider screens don't overrun either.
229
238
  const PINNED_FIRST_CONTENT_CLASS = 'max-md:max-w-[45cqw] max-md:whitespace-normal max-md:break-words';
230
239
  // `highlightRow`: the wash on every cell, so it covers the zebra stripe
231
240
  // (on the row) and the pinned cells' opaque backgrounds (on the cell, and
@@ -700,7 +709,14 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
700
709
  : {}), className: cn('hover:bg-transparent', hovers && HOVER_ROW_CLASS, isHighlighted && HIGHLIGHTED_ROW_CLASS, rowsOpen && SELECTABLE_ROW_CLASS, rowsOpen && hovers && HOVER_FOCUSED_ROW_CLASS, isSelected && SELECTED_ROW_CLASS), children: row.getVisibleCells().map((cell, index) => {
701
710
  const meta = cell.column.columnDef.meta;
702
711
  const value = flexRender(cell.column.columnDef.cell, cell.getContext());
703
- const shown = meta?.clip ? (_jsx(ClippedText, { maxWidth: meta.maxWidth ?? DEFAULT_CLIP_WIDTH, children: value })) : meta?.maxWidth ? (_jsx("div", { className: "whitespace-normal break-words", style: { maxWidth: meta.maxWidth }, children: value })) : (value);
712
+ // The title column (the first) is capped at every width (a long
713
+ // discussion topic overran above md): cut to one line by default,
714
+ // or wrapped with `meta.wrap`; `maxWidth: 'none'` lifts the cap. A
715
+ // first column with its own `clip` or `maxWidth` keeps their meaning.
716
+ const isTitle = index === 0 &&
717
+ cell.column.id !== ROW_ACTIONS_COLUMN_ID &&
718
+ (meta?.wrap || (!meta?.clip && meta?.maxWidth === undefined));
719
+ const shown = isTitle && meta?.wrap ? (_jsx("div", { "data-slot": "data-table-title", className: "whitespace-normal break-words", style: { maxWidth: `min(${meta.maxWidth ?? DEFAULT_CLIP_WIDTH}, 60cqw)` }, children: value })) : isTitle ? (_jsx(ClippedText, { maxWidth: meta?.maxWidth ?? DEFAULT_CLIP_WIDTH, slot: "data-table-title", children: value })) : meta?.clip ? (_jsx(ClippedText, { maxWidth: meta.maxWidth ?? DEFAULT_CLIP_WIDTH, children: value })) : meta?.maxWidth && meta.maxWidth !== 'none' ? (_jsx("div", { className: "whitespace-normal break-words", style: { maxWidth: meta.maxWidth }, children: value })) : (value);
704
720
  const isPinnedFirst = pinFirstColumn && index === 0;
705
721
  const isPinnedLast = pinLast && index === row.getVisibleCells().length - 1;
706
722
  return (_jsx(TableCell, { className: cn(isPinnedFirst && PINNED_COLUMN_CLASS, isPinnedLast && PINNED_LAST_COLUMN_CLASS, (isPinnedFirst || isPinnedLast) && striped && PINNED_STRIPED_CELL_CLASS, alignClass(meta?.align), cell.column.id === ROW_ACTIONS_COLUMN_ID && ROW_ACTIONS_CELL_CLASS), children: isPinnedFirst ? _jsx("div", { className: PINNED_FIRST_CONTENT_CLASS, children: shown }) : shown }, cell.id));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tristan2828/ui-foundation",
3
- "version": "4.102.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
  //