@tristan2828/ui-foundation 4.16.0 → 4.18.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.
- package/README.md +2 -2
- package/conventions/AGENTS.md +7 -0
- package/conventions/docs/add-an-entity.md +18 -0
- package/conventions/docs/reminders.md +85 -0
- package/dist/api/gateway/push.d.ts +8 -0
- package/dist/api/gateway/push.js +25 -0
- package/dist/api/schema.d.ts +148 -0
- package/dist/components/app/allow-reminders.d.ts +9 -0
- package/dist/components/app/allow-reminders.js +11 -0
- package/dist/components/app/milkdown-editor.js +4 -2
- package/dist/components/app/row-edit-cells.js +7 -4
- package/dist/hooks/use-push-permission.d.ts +72 -0
- package/dist/hooks/use-push-permission.js +154 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/lib/link-href.d.ts +2 -0
- package/dist/lib/link-href.js +9 -1
- package/dist/mocks/index.d.ts +1 -0
- package/dist/mocks/index.js +1 -0
- package/dist/mocks/push.d.ts +9 -0
- package/dist/mocks/push.js +40 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.js +25 -4
- package/openapi/foundation.yaml +99 -3
- package/package.json +1 -1
- package/vite/index.d.ts +27 -0
- package/vite/index.js +2 -0
- package/vite/push-sw.js +46 -0
- package/vite/pwa.d.ts +18 -0
- package/vite/pwa.js +230 -0
package/README.md
CHANGED
|
@@ -18,11 +18,11 @@ than installing this by hand:
|
|
|
18
18
|
|
|
19
19
|
| Import | What |
|
|
20
20
|
|---|---|
|
|
21
|
-
| `@tristan2828/ui-foundation` | `AppShell`, `DataTable`, `EntityView` (with `EditableValue`, `editInPlace`), `EntityForm`, `Markdown`, `RichTextEditor`, `ErrorState`, `MultiChoice`, `MultiReference`, `ListEditor`, `PasswordInput`, `RouteErrorBoundary`, `FoundationProviders`, `DataEnvironmentBanner`, `LoginRoute`, `RegisterRoute`, `useAuth`, `useTableUrlState`, `useRecordUpdate`, `useDebouncedValue`, `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. For timed screens (`docs/foundation/timed-screens.md`): `SessionView`, `useSessionClock`, `useWakeLock`, `useMuted`, `usePrefersReducedMotion`, and the audio cues `unlockAudio`, `chime`, `sequence`, `say`, `hush`, `vibrate` |
|
|
21
|
+
| `@tristan2828/ui-foundation` | `AppShell`, `DataTable`, `EntityView` (with `EditableValue`, `editInPlace`), `EntityForm`, `Markdown`, `RichTextEditor`, `ErrorState`, `MultiChoice`, `MultiReference`, `ListEditor`, `PasswordInput`, `RouteErrorBoundary`, `FoundationProviders`, `DataEnvironmentBanner`, `LoginRoute`, `RegisterRoute`, `useAuth`, `useTableUrlState`, `useRecordUpdate`, `useDebouncedValue`, `createQueryClient`, `cn`; types `Page`, `AppError`, `QuerySpec`. For timed screens (`docs/foundation/timed-screens.md`): `SessionView`, `useSessionClock`, `useWakeLock`, `useMuted`, `usePrefersReducedMotion`, and the audio cues `unlockAudio`, `chime`, `sequence`, `say`, `hush`, `vibrate`. For reminders (`docs/foundation/reminders.md`): `AllowReminders`, `usePushPermission` |
|
|
22
22
|
| `@tristan2828/ui-foundation/ui/<name>` | shadcn primitives: badge, button, calendar, card, checkbox, combobox, dialog, empty, field, input, input-group, label, popover, select, separator, sheet, sidebar, skeleton, sonner, spinner, switch, table, textarea, tooltip |
|
|
23
23
|
| `@tristan2828/ui-foundation/gateway` | `safeFetch`, `toAppError`, `networkError` — for an app's `src/api/gateway/` only |
|
|
24
24
|
| `@tristan2828/ui-foundation/mocks` | MSW: `authHandlers`, `environmentHandlers`, `resetMockAuth`, `getMockCurrentUser`, `MOCK_USER`, `exposeMswForE2E` |
|
|
25
|
-
| `@tristan2828/ui-foundation/testing` | Playwright: `defineA11ySuite`, `defineMockModeBannerSuite`, `defineDataEnvironmentBannerSuite`, `forceMswOverride`, `forceLoggedOut`, `waitForMswReady` |
|
|
25
|
+
| `@tristan2828/ui-foundation/testing` | Playwright: `defineA11ySuite`, `defineMockModeBannerSuite`, `defineDataEnvironmentBannerSuite`, `forceMswOverride`, `forceLoggedOut`, `waitForMswReady`, `expectDataViewsLoaded` |
|
|
26
26
|
| `@tristan2828/ui-foundation/eslint` | the lint rules, as a flat config: `export default [...uiFoundation()]` |
|
|
27
27
|
| `@tristan2828/ui-foundation/styles.css` | tokens and base styles, after `@import "tailwindcss";` |
|
|
28
28
|
| `@tristan2828/ui-foundation/openapi.yaml` | the part of an app's API contract the package calls: `/auth/*`, `/environment` (optional) and the error bodies |
|
package/conventions/AGENTS.md
CHANGED
|
@@ -96,6 +96,13 @@ routine) is built from the package's parts: `SessionView`,
|
|
|
96
96
|
`docs/foundation/timed-screens.md`, including its Playwright recipe
|
|
97
97
|
(`clock.install()` before `goto`, then `fastForward`, never `runFor`).
|
|
98
98
|
|
|
99
|
+
## Reminders
|
|
100
|
+
A notification at a time the user chose, with the app closed, is Web
|
|
101
|
+
Push: `pwa()` in `vite.config.ts`, `AllowReminders` with
|
|
102
|
+
`usePushPermission()`, and the backend's `send_push` and reminders job.
|
|
103
|
+
Follow `docs/foundation/reminders.md`. Never ask for notification
|
|
104
|
+
permission on page load: only from the click on "Allow reminders".
|
|
105
|
+
|
|
99
106
|
## Scope and Stopping
|
|
100
107
|
- Do the task you were given and nothing beyond it. A task is done when
|
|
101
108
|
`npm run verify` passes — not when it feels complete.
|
|
@@ -554,6 +554,24 @@ is a filled-in example while the Widgets demo is still here).
|
|
|
554
554
|
one into `src/` to change it: raise it for the foundation (AGENTS.md
|
|
555
555
|
"Changing the Foundation") and build the screen once the release ships.
|
|
556
556
|
|
|
557
|
+
## After a commit, in the backend
|
|
558
|
+
|
|
559
|
+
A router reads who's signed in from the `User` that `get_current_user`
|
|
560
|
+
loaded in the request's own database session. `session.commit()` expires
|
|
561
|
+
every object in that session (`expire_on_commit`, on by default), the user
|
|
562
|
+
included, and reading an expired attribute is a lazy load, which under
|
|
563
|
+
asyncio is a `MissingGreenlet` and a 500.
|
|
564
|
+
|
|
565
|
+
- **After a commit, read by a `user_id` saved before it, never by the
|
|
566
|
+
`User`.** Take `user_id = user.id` at the top of the handler and use that
|
|
567
|
+
from then on; or `await session.refresh(user)` first, as `_start_session`
|
|
568
|
+
in `routers/auth.py` does to return it.
|
|
569
|
+
- **Test signed in for real.** The backend's `client` fixture
|
|
570
|
+
(`tests/conftest.py`) holds a `sessions` row and sends its cookie,
|
|
571
|
+
so the real `get_current_user` runs (`tests/signed_in.py`). Never stand
|
|
572
|
+
a `User(...)` in for `get_current_user` in an override: a detached user
|
|
573
|
+
never expires, so the test passes and the route fails live.
|
|
574
|
+
|
|
557
575
|
## Deleting
|
|
558
576
|
|
|
559
577
|
The plan's "Deleting" line says which of three. The Widget reference is the
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Reminders
|
|
2
|
+
|
|
3
|
+
A notification at a time the user chose ("time for your morning routine",
|
|
4
|
+
"a short break at 3 pm", a habit, a medication) that reaches them with the
|
|
5
|
+
app closed. It's Web Push: the browser subscribes with its push service
|
|
6
|
+
(Google's, Mozilla's, Apple's, Microsoft's), the backend encrypts a message
|
|
7
|
+
to that subscription and posts it there, and the push service delivers it
|
|
8
|
+
to the device, where the app's service worker shows it.
|
|
9
|
+
|
|
10
|
+
| Part | Where | What it does |
|
|
11
|
+
|---|---|---|
|
|
12
|
+
| `pwa({ name })` | `vite.config.ts`, from `@tristan2828/ui-foundation/vite` | The app installable: a manifest, icons in the theme's colours, and `/push-sw.js`, the service worker that shows pushes and opens their path |
|
|
13
|
+
| `usePushPermission()` | the package | Whether this device gets reminders, and `enable`/`disable` |
|
|
14
|
+
| `AllowReminders` | the package | The control: says what reminders are, then asks, on a click |
|
|
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
|
+
| `app/push.py` | the reference backend | `send_push(session, user_id, title, body, url)`: encrypted (RFC 8291), signed (VAPID), to every device the user allowed |
|
|
17
|
+
| `app/reminders.py`, `reminders` | the reference 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
|
+
|
|
19
|
+
Off until the backend turns it on (`PUSH_ENABLED`, `docs/deploy.md`
|
|
20
|
+
"Reminders (Web Push)"). An app without reminders leaves `/push/*` out of
|
|
21
|
+
`openapi.yaml` and `pwa()` out of its config.
|
|
22
|
+
|
|
23
|
+
## Allowing reminders
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
import { AllowReminders, usePushPermission } from '@tristan2828/ui-foundation'
|
|
27
|
+
|
|
28
|
+
const push = usePushPermission()
|
|
29
|
+
<AllowReminders push={push} description="We'll remind you when it's time for your routine." />
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- **Never ask on page load.** A prompt nobody expected gets refused, and a
|
|
33
|
+
refusal is final: only the browser's site settings undo it. The button
|
|
34
|
+
says what reminders are first; `enable()` asks then, from the click.
|
|
35
|
+
- **Put it where reminders are set**: the top of the reminders list, or a
|
|
36
|
+
settings page. One per device: each phone or browser allows its own.
|
|
37
|
+
- **Every state says what to do next.** `AllowReminders` shows them all
|
|
38
|
+
(the package's Storybook, `app/AllowReminders`):
|
|
39
|
+
|
|
40
|
+
| `status` | Means | Shows |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| `off` | Can be turned on | The description and "Allow reminders" |
|
|
43
|
+
| `on` | This device gets them | "Reminders are on for this device", and "Turn off" |
|
|
44
|
+
| `needs-install` | iPhone or iPad in a browser tab | How to add the app to the Home Screen |
|
|
45
|
+
| `blocked` | The person said no | Where to allow it again |
|
|
46
|
+
| `unsupported` | No push in this browser | That it can't |
|
|
47
|
+
| `mock` | The app runs on MSW | That reminders need the real backend |
|
|
48
|
+
|
|
49
|
+
## On iPhone and iPad
|
|
50
|
+
|
|
51
|
+
Push works only in the app added to the Home Screen (Share, then Add to
|
|
52
|
+
Home Screen) and opened from there, on iOS 16.4 or later. In a Safari tab
|
|
53
|
+
there is no push at all, so `usePushPermission` says `needs-install` and
|
|
54
|
+
`AllowReminders` shows the steps. `pwa()`'s manifest (`display:
|
|
55
|
+
standalone`) is what makes the Home Screen app an app.
|
|
56
|
+
|
|
57
|
+
## A reminder is the app's own row
|
|
58
|
+
|
|
59
|
+
The reference backend has a `reminders` table and the job that sends it;
|
|
60
|
+
what a reminder means is the app's. Give it an API and screens like any
|
|
61
|
+
entity (`add-an-entity.md`): its fields are `title`, `body`, `url` (a
|
|
62
|
+
path in the app, opened when it's tapped), `timeOfDay` ("07:30"), `days`
|
|
63
|
+
(some of mon,tue,wed,thu,fri,sat,sun), `timeZone` (the person's IANA
|
|
64
|
+
zone: `Intl.DateTimeFormat().resolvedOptions().timeZone`) and `enabled`.
|
|
65
|
+
Scope it to the signed-in user, as Widgets are.
|
|
66
|
+
|
|
67
|
+
- **The job** (`send-reminders`, every minute, with `JOBS_ENABLED`)
|
|
68
|
+
sends a reminder when today is one of its days in its time zone and the
|
|
69
|
+
time has come, once a day at most. More than 15 minutes late (the
|
|
70
|
+
backend was down) and it's skipped for the day rather than sent late.
|
|
71
|
+
- **Something else to send?** Call `send_push` from the app's own code or
|
|
72
|
+
job: a message when a long task finishes, a daily summary. The `url` is
|
|
73
|
+
always the app's own path.
|
|
74
|
+
- **Time zones** come from the system's time zone database. On Windows
|
|
75
|
+
that's the `tzdata` package, which the backend doesn't install: a
|
|
76
|
+
Windows dev machine reads only `UTC` until it's added.
|
|
77
|
+
|
|
78
|
+
## Testing
|
|
79
|
+
|
|
80
|
+
Under MSW the page is held by MSW's service worker, so `usePushPermission`
|
|
81
|
+
reads `mock` and never subscribes: screens show the `mock` state, and a
|
|
82
|
+
Playwright spec checks it the same way. The rest is the backend's: its
|
|
83
|
+
tests decrypt every message as a browser would. To try it end to end, run
|
|
84
|
+
the real backend with push on, allow reminders in the browser, then
|
|
85
|
+
`backend/scripts/send_test_push.py <email>`.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { components } from "../schema.js";
|
|
2
|
+
export type PushSubscriptionRequest = components["schemas"]["PushSubscriptionRequest"];
|
|
3
|
+
/** The key to subscribe with. A 404 is a backend with push turned off. */
|
|
4
|
+
export declare function getPushPublicKey(): Promise<string>;
|
|
5
|
+
/** Saves the subscription; the same device again answers the same id. */
|
|
6
|
+
export declare function savePushSubscription(subscription: PushSubscriptionRequest): Promise<number>;
|
|
7
|
+
/** Already gone (404) counts as done. */
|
|
8
|
+
export declare function deletePushSubscription(id: number): Promise<void>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { safeFetch, toAppError } from "./errors.js";
|
|
2
|
+
/** The key to subscribe with. A 404 is a backend with push turned off. */
|
|
3
|
+
export async function getPushPublicKey() {
|
|
4
|
+
const res = await safeFetch("/push/public-key");
|
|
5
|
+
if (res.status !== 200)
|
|
6
|
+
throw toAppError(res.status, res.body, res.headers);
|
|
7
|
+
return res.body.publicKey;
|
|
8
|
+
}
|
|
9
|
+
/** Saves the subscription; the same device again answers the same id. */
|
|
10
|
+
export async function savePushSubscription(subscription) {
|
|
11
|
+
const res = await safeFetch("/push/subscriptions", {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: { "content-type": "application/json" },
|
|
14
|
+
body: JSON.stringify(subscription),
|
|
15
|
+
});
|
|
16
|
+
if (res.status !== 201)
|
|
17
|
+
throw toAppError(res.status, res.body, res.headers);
|
|
18
|
+
return res.body.id;
|
|
19
|
+
}
|
|
20
|
+
/** Already gone (404) counts as done. */
|
|
21
|
+
export async function deletePushSubscription(id) {
|
|
22
|
+
const res = await safeFetch(`/push/subscriptions/${id}`, { method: "DELETE" });
|
|
23
|
+
if (res.status !== 204 && res.status !== 404)
|
|
24
|
+
throw toAppError(res.status, res.body, res.headers);
|
|
25
|
+
}
|
package/dist/api/schema.d.ts
CHANGED
|
@@ -131,6 +131,63 @@ export interface paths {
|
|
|
131
131
|
patch?: never;
|
|
132
132
|
trace?: never;
|
|
133
133
|
};
|
|
134
|
+
"/push/public-key": {
|
|
135
|
+
parameters: {
|
|
136
|
+
query?: never;
|
|
137
|
+
header?: never;
|
|
138
|
+
path?: never;
|
|
139
|
+
cookie?: never;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* The app's VAPID public key, which a browser subscribes to push with
|
|
143
|
+
* @description For usePushPermission. 404 when the backend has push turned off.
|
|
144
|
+
*/
|
|
145
|
+
get: operations["getPushPublicKey"];
|
|
146
|
+
put?: never;
|
|
147
|
+
post?: never;
|
|
148
|
+
delete?: never;
|
|
149
|
+
options?: never;
|
|
150
|
+
head?: never;
|
|
151
|
+
patch?: never;
|
|
152
|
+
trace?: never;
|
|
153
|
+
};
|
|
154
|
+
"/push/subscriptions": {
|
|
155
|
+
parameters: {
|
|
156
|
+
query?: never;
|
|
157
|
+
header?: never;
|
|
158
|
+
path?: never;
|
|
159
|
+
cookie?: never;
|
|
160
|
+
};
|
|
161
|
+
get?: never;
|
|
162
|
+
put?: never;
|
|
163
|
+
/**
|
|
164
|
+
* Save this device's push subscription for the signed-in user
|
|
165
|
+
* @description The browser's PushSubscription.toJSON(). The same endpoint again replaces its keys and owner and answers the same id. The endpoint must be a push service's (422 otherwise): the backend POSTs to it.
|
|
166
|
+
*/
|
|
167
|
+
post: operations["savePushSubscription"];
|
|
168
|
+
delete?: never;
|
|
169
|
+
options?: never;
|
|
170
|
+
head?: never;
|
|
171
|
+
patch?: never;
|
|
172
|
+
trace?: never;
|
|
173
|
+
};
|
|
174
|
+
"/push/subscriptions/{id}": {
|
|
175
|
+
parameters: {
|
|
176
|
+
query?: never;
|
|
177
|
+
header?: never;
|
|
178
|
+
path?: never;
|
|
179
|
+
cookie?: never;
|
|
180
|
+
};
|
|
181
|
+
get?: never;
|
|
182
|
+
put?: never;
|
|
183
|
+
post?: never;
|
|
184
|
+
/** Stop sending to one of the signed-in user's devices */
|
|
185
|
+
delete: operations["deletePushSubscription"];
|
|
186
|
+
options?: never;
|
|
187
|
+
head?: never;
|
|
188
|
+
patch?: never;
|
|
189
|
+
trace?: never;
|
|
190
|
+
};
|
|
134
191
|
}
|
|
135
192
|
export type webhooks = Record<string, never>;
|
|
136
193
|
export interface components {
|
|
@@ -185,6 +242,23 @@ export interface components {
|
|
|
185
242
|
/** @description The frontend build (its commit). */
|
|
186
243
|
release?: string;
|
|
187
244
|
};
|
|
245
|
+
PushPublicKey: {
|
|
246
|
+
/** @description The P-256 public key, base64url (applicationServerKey). */
|
|
247
|
+
publicKey: string;
|
|
248
|
+
};
|
|
249
|
+
PushSubscriptionRequest: {
|
|
250
|
+
/** @description The push service's URL for this device. */
|
|
251
|
+
endpoint: string;
|
|
252
|
+
/** @description Milliseconds since the epoch, sent by some browsers, ignored. */
|
|
253
|
+
expirationTime?: number | null;
|
|
254
|
+
keys: {
|
|
255
|
+
p256dh: string;
|
|
256
|
+
auth: string;
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
PushSubscriptionCreated: {
|
|
260
|
+
id: number;
|
|
261
|
+
};
|
|
188
262
|
/** @description FastAPI's default 422 shape (RequestValidationError). */
|
|
189
263
|
ValidationErrorBody: {
|
|
190
264
|
detail: {
|
|
@@ -442,4 +516,78 @@ export interface operations {
|
|
|
442
516
|
500: components["responses"]["ServerError"];
|
|
443
517
|
};
|
|
444
518
|
};
|
|
519
|
+
getPushPublicKey: {
|
|
520
|
+
parameters: {
|
|
521
|
+
query?: never;
|
|
522
|
+
header?: never;
|
|
523
|
+
path?: never;
|
|
524
|
+
cookie?: never;
|
|
525
|
+
};
|
|
526
|
+
requestBody?: never;
|
|
527
|
+
responses: {
|
|
528
|
+
/** @description OK. */
|
|
529
|
+
200: {
|
|
530
|
+
headers: {
|
|
531
|
+
[name: string]: unknown;
|
|
532
|
+
};
|
|
533
|
+
content: {
|
|
534
|
+
"application/json": components["schemas"]["PushPublicKey"];
|
|
535
|
+
};
|
|
536
|
+
};
|
|
537
|
+
401: components["responses"]["UnauthorizedError"];
|
|
538
|
+
404: components["responses"]["NotFoundError"];
|
|
539
|
+
500: components["responses"]["ServerError"];
|
|
540
|
+
};
|
|
541
|
+
};
|
|
542
|
+
savePushSubscription: {
|
|
543
|
+
parameters: {
|
|
544
|
+
query?: never;
|
|
545
|
+
header?: never;
|
|
546
|
+
path?: never;
|
|
547
|
+
cookie?: never;
|
|
548
|
+
};
|
|
549
|
+
requestBody: {
|
|
550
|
+
content: {
|
|
551
|
+
"application/json": components["schemas"]["PushSubscriptionRequest"];
|
|
552
|
+
};
|
|
553
|
+
};
|
|
554
|
+
responses: {
|
|
555
|
+
/** @description Saved. */
|
|
556
|
+
201: {
|
|
557
|
+
headers: {
|
|
558
|
+
[name: string]: unknown;
|
|
559
|
+
};
|
|
560
|
+
content: {
|
|
561
|
+
"application/json": components["schemas"]["PushSubscriptionCreated"];
|
|
562
|
+
};
|
|
563
|
+
};
|
|
564
|
+
401: components["responses"]["UnauthorizedError"];
|
|
565
|
+
404: components["responses"]["NotFoundError"];
|
|
566
|
+
422: components["responses"]["ValidationError"];
|
|
567
|
+
500: components["responses"]["ServerError"];
|
|
568
|
+
};
|
|
569
|
+
};
|
|
570
|
+
deletePushSubscription: {
|
|
571
|
+
parameters: {
|
|
572
|
+
query?: never;
|
|
573
|
+
header?: never;
|
|
574
|
+
path: {
|
|
575
|
+
id: number;
|
|
576
|
+
};
|
|
577
|
+
cookie?: never;
|
|
578
|
+
};
|
|
579
|
+
requestBody?: never;
|
|
580
|
+
responses: {
|
|
581
|
+
/** @description Deleted. */
|
|
582
|
+
204: {
|
|
583
|
+
headers: {
|
|
584
|
+
[name: string]: unknown;
|
|
585
|
+
};
|
|
586
|
+
content?: never;
|
|
587
|
+
};
|
|
588
|
+
401: components["responses"]["UnauthorizedError"];
|
|
589
|
+
404: components["responses"]["NotFoundError"];
|
|
590
|
+
500: components["responses"]["ServerError"];
|
|
591
|
+
};
|
|
592
|
+
};
|
|
445
593
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { PushPermission } from '../../hooks/use-push-permission.js';
|
|
3
|
+
export type AllowRemindersProps = {
|
|
4
|
+
push: PushPermission;
|
|
5
|
+
/** What reminders are for, in the app's words, shown before asking. */
|
|
6
|
+
description?: ReactNode;
|
|
7
|
+
className?: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function AllowReminders({ push, description, className }: AllowRemindersProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { BellIcon, BellOffIcon } from 'lucide-react';
|
|
3
|
+
import { cn } from 'cn';
|
|
4
|
+
import { Button } from '../ui/button.js';
|
|
5
|
+
import { Skeleton } from '../ui/skeleton.js';
|
|
6
|
+
import { Notice } from './notice.js';
|
|
7
|
+
const DEFAULT_DESCRIPTION = 'Get a notification on this device at the times you set, even when the app is closed. Your browser will ask first.';
|
|
8
|
+
export function AllowReminders({ push, description = DEFAULT_DESCRIPTION, className }) {
|
|
9
|
+
const { status, pending, error } = push;
|
|
10
|
+
return (_jsxs("div", { "data-slot": "allow-reminders", className: cn('flex flex-col gap-3', className), "aria-busy": status === undefined || pending, children: [status === undefined && _jsx(Skeleton, { className: "h-9 w-full max-w-md" }), status === 'off' && (_jsxs(_Fragment, { children: [_jsx("p", { className: "text-sm text-foreground", children: description }), _jsx("div", { children: _jsxs(Button, { onClick: push.enable, disabled: pending, children: [_jsx(BellIcon, { "aria-hidden": "true" }), pending ? 'Turning on…' : 'Allow reminders'] }) })] })), status === 'on' && (_jsx(Notice, { tone: "success", icon: BellIcon, action: _jsxs(Button, { size: "sm", variant: "outline", onClick: push.disable, disabled: pending, children: [_jsx(BellOffIcon, { "aria-hidden": "true" }), pending ? 'Turning off…' : 'Turn off'] }), children: "Reminders are on for this device." })), status === 'needs-install' && (_jsx(Notice, { title: "Add the app to your Home Screen first", children: "On iPhone and iPad, reminders work in the app from the Home Screen. Tap Share, then Add to Home Screen, open the app from there and allow reminders." })), status === 'blocked' && (_jsx(Notice, { tone: "warning", title: "Notifications are blocked", icon: BellOffIcon, children: "This browser was told not to show this app\u2019s notifications. Allow them in the site\u2019s settings (the icon beside the address), then reload." })), status === 'unsupported' && (_jsx("p", { className: "text-sm text-muted-foreground", children: "This browser can\u2019t show reminders." })), status === 'mock' && (_jsx("p", { className: "text-sm text-muted-foreground", children: "Reminders need the real backend: with mock data nothing can send them." })), error && (_jsx("p", { role: "alert", className: "text-sm text-destructive-text", children: error }))] }));
|
|
11
|
+
}
|
|
@@ -54,7 +54,7 @@ import { Button } from '../ui/button.js';
|
|
|
54
54
|
import { Field, FieldError, FieldLabel } from '../ui/field.js';
|
|
55
55
|
import { Input } from '../ui/input.js';
|
|
56
56
|
import { Popover, PopoverContent } from '../ui/popover.js';
|
|
57
|
-
import { linkHref } from '../../lib/link-href.js';
|
|
57
|
+
import { linkHref, linkRefusal } from '../../lib/link-href.js';
|
|
58
58
|
import { passEscapeThrough } from './escape-passthrough.js';
|
|
59
59
|
import { calloutHandler, remarkCalloutNodes } from '../../lib/markdown-callout.js';
|
|
60
60
|
import { MarkdownMergeError, markdownStyle, mergeMarkdown } from '../../lib/markdown-merge.js';
|
|
@@ -751,7 +751,9 @@ function LinkForm({ box, onApply }) {
|
|
|
751
751
|
const apply = () => {
|
|
752
752
|
const href = linkHref(typed);
|
|
753
753
|
if (href === null) {
|
|
754
|
-
setError(
|
|
754
|
+
setError(linkRefusal(typed) === 'whitespace'
|
|
755
|
+
? 'An address has no spaces. Remove them, or write each as %20.'
|
|
756
|
+
: 'Enter a web or email address, like https://example.com.');
|
|
755
757
|
return;
|
|
756
758
|
}
|
|
757
759
|
onApply(href);
|
|
@@ -2,7 +2,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
2
2
|
import { ExternalLinkIcon } from 'lucide-react';
|
|
3
3
|
import { Input } from '../ui/input.js';
|
|
4
4
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
|
|
5
|
-
import { linkHref } from '../../lib/link-href.js';
|
|
5
|
+
import { linkHref, linkRefusal } from '../../lib/link-href.js';
|
|
6
6
|
import { editInPlace } from './edit-in-place.js';
|
|
7
7
|
import { EditableValue } from './editable-value.js';
|
|
8
8
|
/** A name in one line: Enter saves, the form's rule runs first, a taken name's 422 shows in the cell. */
|
|
@@ -31,14 +31,17 @@ export function ChoiceCell({ label, value, options, render, save, triggerClassNa
|
|
|
31
31
|
}), children: render(value) }));
|
|
32
32
|
}
|
|
33
33
|
// A web or email address (`example.com` gains https://), blank for none.
|
|
34
|
-
// Another scheme (`javascript:`)
|
|
34
|
+
// Another scheme (`javascript:`) or a space inside the address is refused
|
|
35
|
+
// before anything is sent.
|
|
35
36
|
const LINK_RULE = {
|
|
36
37
|
safeParse: (value) => {
|
|
37
|
-
const
|
|
38
|
+
const typed = String(value ?? '');
|
|
39
|
+
const href = linkHref(typed);
|
|
38
40
|
if (href === '')
|
|
39
41
|
return { success: true, data: null };
|
|
40
42
|
if (href === null) {
|
|
41
|
-
|
|
43
|
+
const message = linkRefusal(typed) === 'whitespace' ? 'An address has no spaces' : 'Use a web or email address';
|
|
44
|
+
return { success: false, error: { issues: [{ message }] } };
|
|
42
45
|
}
|
|
43
46
|
return { success: true, data: href };
|
|
44
47
|
},
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type PushSubscriptionRequest } from '../api/gateway/push.js';
|
|
2
|
+
/**
|
|
3
|
+
* - `unsupported`: this browser has no push.
|
|
4
|
+
* - `needs-install`: iPhone or iPad in a browser tab; push works once the
|
|
5
|
+
* app is added to the Home Screen and opened from there.
|
|
6
|
+
* - `mock`: the page runs on MSW; reminders need the real backend.
|
|
7
|
+
* - `blocked`: the person said no; only the browser's site settings undo it.
|
|
8
|
+
* - `off`: can be turned on. `on`: this device gets reminders.
|
|
9
|
+
*/
|
|
10
|
+
export type PushStatus = 'unsupported' | 'needs-install' | 'mock' | 'blocked' | 'off' | 'on';
|
|
11
|
+
type PushRegistration = {
|
|
12
|
+
active: {
|
|
13
|
+
scriptURL: string;
|
|
14
|
+
} | null;
|
|
15
|
+
pushManager: Pick<PushManager, 'getSubscription' | 'subscribe'>;
|
|
16
|
+
};
|
|
17
|
+
/** What createPushController needs from the browser and the backend. */
|
|
18
|
+
export type PushEnvironment = {
|
|
19
|
+
notification: {
|
|
20
|
+
permission: NotificationPermission;
|
|
21
|
+
requestPermission: () => Promise<NotificationPermission>;
|
|
22
|
+
} | undefined;
|
|
23
|
+
serviceWorker: {
|
|
24
|
+
register: (url: string, options: RegistrationOptions) => Promise<unknown>;
|
|
25
|
+
getRegistration: () => Promise<PushRegistration | undefined>;
|
|
26
|
+
ready: () => Promise<PushRegistration>;
|
|
27
|
+
/** The script of the worker controlling this page, if any. */
|
|
28
|
+
controllerScript: () => string | undefined;
|
|
29
|
+
} | undefined;
|
|
30
|
+
/** `'PushManager' in window`. */
|
|
31
|
+
pushSupported: boolean;
|
|
32
|
+
/** Opened from the Home Screen (display-mode: standalone). */
|
|
33
|
+
standalone: boolean;
|
|
34
|
+
/** An iPhone or iPad, whatever the browser says it is. */
|
|
35
|
+
appleMobile: boolean;
|
|
36
|
+
api: {
|
|
37
|
+
getPublicKey: () => Promise<string>;
|
|
38
|
+
save: (subscription: PushSubscriptionRequest) => Promise<number>;
|
|
39
|
+
remove: (id: number) => Promise<void>;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
export type PushController = {
|
|
43
|
+
status: () => Promise<PushStatus>;
|
|
44
|
+
/** Asks the browser, subscribes, and saves it. Call it straight from a click. */
|
|
45
|
+
enable: () => Promise<PushStatus>;
|
|
46
|
+
/** Stops sending to this device, and unsubscribes it. */
|
|
47
|
+
disable: () => Promise<PushStatus>;
|
|
48
|
+
};
|
|
49
|
+
export type PushControllerOptions = {
|
|
50
|
+
/** Where pwa() serves the worker. Default `/push-sw.js`. */
|
|
51
|
+
serviceWorkerUrl?: string;
|
|
52
|
+
};
|
|
53
|
+
export declare function createPushController(env: PushEnvironment, options?: PushControllerOptions): PushController;
|
|
54
|
+
export declare const PUSH_STATUS_QUERY_KEY: readonly ["ui-foundation", "push-status"];
|
|
55
|
+
/** What usePushPermission returns, and what AllowReminders shows. */
|
|
56
|
+
export type PushPermission = {
|
|
57
|
+
/** Undefined while it's being worked out. */
|
|
58
|
+
status: PushStatus | undefined;
|
|
59
|
+
enable: () => void;
|
|
60
|
+
disable: () => void;
|
|
61
|
+
/** Turning on or off is under way. */
|
|
62
|
+
pending: boolean;
|
|
63
|
+
/** Why the last enable or disable failed, in words to show. */
|
|
64
|
+
error: string | null;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Whether this device gets reminders, and `enable`/`disable` for one
|
|
68
|
+
* button (AllowReminders is that button, with the words around it).
|
|
69
|
+
* `enable` asks the browser for permission: only ever call it from a click.
|
|
70
|
+
*/
|
|
71
|
+
export declare function usePushPermission(options?: PushControllerOptions): PushPermission;
|
|
72
|
+
export {};
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
2
|
+
import { deletePushSubscription, getPushPublicKey, savePushSubscription, } from '../api/gateway/push.js';
|
|
3
|
+
const isMockWorker = (script) => !!script && script.includes('mockServiceWorker');
|
|
4
|
+
function base64UrlToBytes(value) {
|
|
5
|
+
const base64 = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (value.length % 4)) % 4);
|
|
6
|
+
const binary = atob(base64);
|
|
7
|
+
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
8
|
+
for (let i = 0; i < binary.length; i++)
|
|
9
|
+
bytes[i] = binary.charCodeAt(i);
|
|
10
|
+
return bytes;
|
|
11
|
+
}
|
|
12
|
+
function sameKey(current, wanted) {
|
|
13
|
+
if (!current)
|
|
14
|
+
return false;
|
|
15
|
+
const bytes = new Uint8Array(current);
|
|
16
|
+
return bytes.length === wanted.length && bytes.every((byte, i) => byte === wanted[i]);
|
|
17
|
+
}
|
|
18
|
+
function toRequest(subscription) {
|
|
19
|
+
const json = subscription.toJSON();
|
|
20
|
+
const p256dh = json.keys?.p256dh;
|
|
21
|
+
const auth = json.keys?.auth;
|
|
22
|
+
if (!json.endpoint || !p256dh || !auth)
|
|
23
|
+
throw new Error('The browser gave a subscription without its keys.');
|
|
24
|
+
return { endpoint: json.endpoint, expirationTime: json.expirationTime ?? null, keys: { p256dh, auth } };
|
|
25
|
+
}
|
|
26
|
+
export function createPushController(env, options = {}) {
|
|
27
|
+
const workerUrl = options.serviceWorkerUrl ?? '/push-sw.js';
|
|
28
|
+
// What can be told without waiting on anything, so enable() can ask
|
|
29
|
+
// the browser in the same task as the click.
|
|
30
|
+
const knownNow = () => {
|
|
31
|
+
if (env.appleMobile && !env.standalone)
|
|
32
|
+
return 'needs-install';
|
|
33
|
+
if (!env.notification || !env.serviceWorker || !env.pushSupported)
|
|
34
|
+
return 'unsupported';
|
|
35
|
+
if (isMockWorker(env.serviceWorker.controllerScript()))
|
|
36
|
+
return 'mock';
|
|
37
|
+
if (env.notification.permission === 'denied')
|
|
38
|
+
return 'blocked';
|
|
39
|
+
return null;
|
|
40
|
+
};
|
|
41
|
+
const ours = (registration) => registration?.active && !isMockWorker(registration.active.scriptURL) ? registration : undefined;
|
|
42
|
+
return {
|
|
43
|
+
async status() {
|
|
44
|
+
const known = knownNow();
|
|
45
|
+
if (known)
|
|
46
|
+
return known;
|
|
47
|
+
const registration = await env.serviceWorker.getRegistration();
|
|
48
|
+
if (isMockWorker(registration?.active?.scriptURL))
|
|
49
|
+
return 'mock';
|
|
50
|
+
if (env.notification.permission !== 'granted')
|
|
51
|
+
return 'off';
|
|
52
|
+
const subscription = await ours(registration)?.pushManager.getSubscription();
|
|
53
|
+
return subscription ? 'on' : 'off';
|
|
54
|
+
},
|
|
55
|
+
async enable() {
|
|
56
|
+
const known = knownNow();
|
|
57
|
+
if (known)
|
|
58
|
+
return known;
|
|
59
|
+
const permission = await env.notification.requestPermission();
|
|
60
|
+
if (permission !== 'granted')
|
|
61
|
+
return permission === 'denied' ? 'blocked' : 'off';
|
|
62
|
+
await env.serviceWorker.register(workerUrl, { scope: '/' });
|
|
63
|
+
const registration = await env.serviceWorker.ready();
|
|
64
|
+
const key = base64UrlToBytes(await env.api.getPublicKey());
|
|
65
|
+
let subscription = await registration.pushManager.getSubscription();
|
|
66
|
+
// Made with another key (the backend's was replaced): it can't be
|
|
67
|
+
// sent to any more, so start again.
|
|
68
|
+
if (subscription && !sameKey(subscription.options.applicationServerKey, key)) {
|
|
69
|
+
await subscription.unsubscribe();
|
|
70
|
+
subscription = null;
|
|
71
|
+
}
|
|
72
|
+
subscription ??= await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
|
|
73
|
+
await env.api.save(toRequest(subscription));
|
|
74
|
+
return 'on';
|
|
75
|
+
},
|
|
76
|
+
async disable() {
|
|
77
|
+
const subscription = await ours(await env.serviceWorker?.getRegistration())?.pushManager.getSubscription();
|
|
78
|
+
if (subscription) {
|
|
79
|
+
// Saving again is how the device learns its id (the same endpoint
|
|
80
|
+
// answers the same one), so nothing is kept on the device.
|
|
81
|
+
const id = await env.api.save(toRequest(subscription));
|
|
82
|
+
await env.api.remove(id);
|
|
83
|
+
await subscription.unsubscribe();
|
|
84
|
+
}
|
|
85
|
+
return 'off';
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function browserEnvironment() {
|
|
90
|
+
const hasWindow = typeof window !== 'undefined';
|
|
91
|
+
const container = hasWindow && 'serviceWorker' in navigator ? navigator.serviceWorker : undefined;
|
|
92
|
+
const ua = hasWindow ? navigator.userAgent : '';
|
|
93
|
+
return {
|
|
94
|
+
notification: hasWindow && 'Notification' in window ? Notification : undefined,
|
|
95
|
+
serviceWorker: container && {
|
|
96
|
+
register: (url, options) => container.register(url, options),
|
|
97
|
+
getRegistration: () => container.getRegistration(),
|
|
98
|
+
ready: () => container.ready,
|
|
99
|
+
controllerScript: () => container.controller?.scriptURL,
|
|
100
|
+
},
|
|
101
|
+
pushSupported: hasWindow && 'PushManager' in window,
|
|
102
|
+
standalone: hasWindow &&
|
|
103
|
+
(window.matchMedia?.('(display-mode: standalone)').matches ||
|
|
104
|
+
navigator.standalone === true),
|
|
105
|
+
// iPadOS says it's a Mac; a Mac has no touch screen.
|
|
106
|
+
appleMobile: /iPhone|iPad|iPod/.test(ua) || (/Macintosh/.test(ua) && hasWindow && navigator.maxTouchPoints > 1),
|
|
107
|
+
api: { getPublicKey: getPushPublicKey, save: savePushSubscription, remove: deletePushSubscription },
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function messageOf(error) {
|
|
111
|
+
const appError = error;
|
|
112
|
+
if (appError && typeof appError.kind === 'string') {
|
|
113
|
+
if (appError.kind === 'notfound')
|
|
114
|
+
return "This app's backend doesn't send reminders yet.";
|
|
115
|
+
if (appError.kind === 'network')
|
|
116
|
+
return "Couldn't reach the app. Check the connection and try again.";
|
|
117
|
+
return appError.message ?? 'Something went wrong. Try again.';
|
|
118
|
+
}
|
|
119
|
+
return "The browser couldn't turn on reminders. Try again, or check its notification settings.";
|
|
120
|
+
}
|
|
121
|
+
export const PUSH_STATUS_QUERY_KEY = ['ui-foundation', 'push-status'];
|
|
122
|
+
/**
|
|
123
|
+
* Whether this device gets reminders, and `enable`/`disable` for one
|
|
124
|
+
* button (AllowReminders is that button, with the words around it).
|
|
125
|
+
* `enable` asks the browser for permission: only ever call it from a click.
|
|
126
|
+
*/
|
|
127
|
+
export function usePushPermission(options = {}) {
|
|
128
|
+
const queryClient = useQueryClient();
|
|
129
|
+
const controller = createPushController(browserEnvironment(), options);
|
|
130
|
+
const { data: status } = useQuery({
|
|
131
|
+
queryKey: PUSH_STATUS_QUERY_KEY,
|
|
132
|
+
queryFn: () => controller.status(),
|
|
133
|
+
staleTime: Infinity,
|
|
134
|
+
});
|
|
135
|
+
const settle = (next) => queryClient.setQueryData(PUSH_STATUS_QUERY_KEY, next);
|
|
136
|
+
// Each takes the run already started: enable() must ask the browser in
|
|
137
|
+
// the click itself, and mutate() may call its function a tick later.
|
|
138
|
+
const enable = useMutation({ mutationFn: (run) => run, onSuccess: settle });
|
|
139
|
+
const disable = useMutation({ mutationFn: (run) => run, onSuccess: settle });
|
|
140
|
+
const failed = enable.error ?? disable.error;
|
|
141
|
+
return {
|
|
142
|
+
status,
|
|
143
|
+
enable: () => {
|
|
144
|
+
disable.reset();
|
|
145
|
+
enable.mutate(controller.enable());
|
|
146
|
+
},
|
|
147
|
+
disable: () => {
|
|
148
|
+
enable.reset();
|
|
149
|
+
disable.mutate(controller.disable());
|
|
150
|
+
},
|
|
151
|
+
pending: enable.isPending || disable.isPending,
|
|
152
|
+
error: failed ? messageOf(failed) : null,
|
|
153
|
+
};
|
|
154
|
+
}
|