@jskit-ai/push-web 0.1.1 → 0.1.3

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/CHANGELOG.md CHANGED
@@ -2,4 +2,6 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The notifications section (`PushSettingsSection`, its state in `usePushSettings`) keeps its form on screen and the person's unsaved edits when the device switch is turned or a device is removed; only the first load shows the skeleton. A failed save reads "Your notification settings weren't saved. Try again." and a failed removal "{label} wasn't removed. Try again." (they read "didn't load"), in the shell's snackbar rather than an alert pushing the form down. Each device row and the empty list carry the notifications icon. A quiet hours end the server refuses shows beside that field. Remove sends one request however often it is pressed, and Remove, Save ("Saving…") and the device switch stay focusable while they run (`v-pending`).
6
+ - The manifest marks `push.core` install-time only (`jskit.capabilities.installRequires`): the client calls push-core's routes and no server feature of push-web requires it, so start-up no longer logs it as a requirement no feature has.
5
7
  - New package: the `client.push` capability (`PushClientProvider`). Registers this browser through JSKIT's own service worker (`/jskit-sw.js`, served by `PushWebFeature`) or this phone through `@capacitor/push-notifications` ^9 (an optional peer) with `@jskit-ai/push-core`, asks permission only from the person's own action, opens a tapped notification's own page and tells the app's `onTap` handlers, forgets this device before every sign-out, and provides the account settings section `push.web.settings.section`.
package/locales/en.json CHANGED
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "settings": {
10
10
  "save": "Save notifications",
11
+ "saving": "Saving…",
11
12
  "thisDevice": "Notifications on this device",
12
13
  "thisDeviceUnavailable": "This browser can't receive notifications.",
13
14
  "kinds": "What to notify you about",
@@ -20,6 +21,8 @@
20
21
  "noDevices": "No device gets notifications yet.",
21
22
  "remove": "Remove {label}",
22
23
  "loadFailed": "Your notification settings didn't load.",
24
+ "saveFailed": "Your notification settings weren't saved. Try again.",
25
+ "removeFailed": "{label} wasn't removed. Try again.",
23
26
  "tryAgain": "Try again",
24
27
  "kind": {
25
28
  "webpush": "Browser",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/push-web",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -21,6 +21,9 @@
21
21
  ],
22
22
  "requires": [
23
23
  "push.core"
24
+ ],
25
+ "installRequires": [
26
+ "push.core"
24
27
  ]
25
28
  },
26
29
  "runtime": {
@@ -68,14 +71,14 @@
68
71
  }
69
72
  },
70
73
  "dependencies": {
71
- "@jskit-ai/push-core": "0.1.1"
74
+ "@jskit-ai/push-core": "0.1.3"
72
75
  },
73
76
  "peerDependencies": {
74
77
  "@capacitor/push-notifications": "^9.0.2",
75
- "@jskit-ai/auth-web": "0.2.81",
76
- "@jskit-ai/http-web": "0.2.84",
77
- "@jskit-ai/kernel": "0.2.41",
78
- "@jskit-ai/shell-web": "0.2.73",
78
+ "@jskit-ai/auth-web": "0.2.83",
79
+ "@jskit-ai/http-web": "0.2.86",
80
+ "@jskit-ai/kernel": "0.2.43",
81
+ "@jskit-ai/shell-web": "0.2.75",
79
82
  "vue": "^3.5.44",
80
83
  "vuetify": "^4.3.0"
81
84
  },
@@ -1,109 +1,35 @@
1
1
  <script setup>
2
- import { computed, onMounted, reactive, ref } from "vue";
2
+ import { onMounted } from "vue";
3
3
  import { getHttpWebClient } from "@jskit-ai/http-web/client";
4
4
  import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageAction";
5
5
  import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
6
+ import { vPending } from "@jskit-ai/shell-web/client/directives/vPending";
7
+ import { useShellWebErrorRuntime } from "@jskit-ai/shell-web/client/error";
6
8
  import { usePushClient } from "../PushClientProvider.js";
9
+ import { usePushSettings } from "../composables/usePushSettings.js";
7
10
  import { useJskitText } from "../i18n.js";
8
11
 
9
12
  // The account settings' notifications on phones and browsers: this device on or off, the kinds a person wants, text
10
13
  // shown or not, quiet hours, and the devices that get them. Place it at `account-settings:sections` as
11
14
  // `push.web.settings.section`.
12
15
  const push = usePushClient();
13
- const { t, text, serverMessage } = useJskitText();
14
- const request = (path, options) => getHttpWebClient().request(path, options);
15
-
16
- const status = ref("loading");
17
- const loadError = ref("");
18
- const actionError = ref("");
19
- const saving = ref(false);
20
- const deviceBusy = ref(false);
21
- const deviceOn = ref(false);
22
- const devices = ref([]);
23
- const saved = ref(null);
24
- const form = reactive({ kindsOff: [], showText: true, quietFrom: "", quietTo: "" });
16
+ const { t, text } = useJskitText();
25
17
  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
26
- const KIND_LABELS = Object.freeze({
27
- webpush: "jskit.push.settings.kind.webpush",
28
- apns: "jskit.push.settings.kind.apns",
29
- fcm: "jskit.push.settings.kind.fcm"
18
+ const errorRuntime = useShellWebErrorRuntime();
19
+ // A command's failure goes to the shell's snackbar, which never pushes the form down.
20
+ const report = (message) => errorRuntime.report({
21
+ source: "push-web.settings",
22
+ message,
23
+ intent: "action-feedback",
24
+ severity: "error",
25
+ channel: "snackbar",
26
+ dedupeKey: `push-web.settings:${message}`,
27
+ dedupeWindowMs: 3000
30
28
  });
31
- const deviceLabel = (device) => device.label || t(KIND_LABELS[device.kind] || KIND_LABELS.webpush);
32
-
33
- const hasUnsavedEdits = computed(() => saved.value !== null && JSON.stringify(formBody()) !== JSON.stringify(saved.value));
34
-
35
- function formBody() {
36
- return {
37
- kindsOff: [...form.kindsOff].sort(),
38
- showText: form.showText,
39
- quietFrom: form.quietFrom || null,
40
- quietTo: form.quietTo || null,
41
- timeZone: form.quietFrom || form.quietTo ? timeZone : null
42
- };
43
- }
44
-
45
- function showSettings(settings) {
46
- form.kindsOff = [...settings.kindsOff];
47
- form.showText = settings.showText;
48
- form.quietFrom = settings.quietFrom || "";
49
- form.quietTo = settings.quietTo || "";
50
- saved.value = formBody();
51
- }
52
-
53
- async function load() {
54
- status.value = "loading";
55
- try {
56
- const overview = await request("/api/push", { method: "GET" });
57
- const current = await push.current();
58
- devices.value = overview.devices;
59
- deviceOn.value = Boolean(current) && (await push.permission()) === "granted";
60
- showSettings(overview.settings);
61
- status.value = "ready";
62
- } catch (error) {
63
- loadError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
64
- status.value = "error";
65
- }
66
- }
67
-
68
- async function toggleDevice(on) {
69
- deviceBusy.value = true;
70
- actionError.value = "";
71
- try {
72
- if (on) await push.enable();
73
- else await push.disable();
74
- await load();
75
- } catch (error) {
76
- actionError.value = serverMessage(error, t("jskit.push.device.registrationFailed"));
77
- } finally {
78
- deviceBusy.value = false;
79
- }
80
- }
81
-
82
- function setKind(id, on) {
83
- form.kindsOff = on ? form.kindsOff.filter((kind) => kind !== id) : [...new Set([...form.kindsOff, id])];
84
- }
85
-
86
- async function save() {
87
- saving.value = true;
88
- actionError.value = "";
89
- try {
90
- showSettings(await request("/api/push/settings", { method: "PUT", body: formBody() }));
91
- } catch (error) {
92
- actionError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
93
- } finally {
94
- saving.value = false;
95
- }
96
- }
97
-
98
- async function removeDevice(id) {
99
- actionError.value = "";
100
- try {
101
- await request(`/api/push/devices/${encodeURIComponent(id)}`, { method: "DELETE" });
102
- await load();
103
- } catch (error) {
104
- actionError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
105
- }
106
- }
29
+ const {
30
+ status, loadError, fieldErrors, saving, deviceBusy, deviceOn, devices, removing, deviceLabel, form, hasUnsavedEdits,
31
+ load, toggleDevice, setKind, save, removeDevice
32
+ } = usePushSettings({ push, request: (path, options) => getHttpWebClient().request(path, options), timeZone, report });
107
33
 
108
34
  onMounted(load);
109
35
  </script>
@@ -123,26 +49,24 @@ onMounted(load);
123
49
  <ShellPageActions>
124
50
  <ShellPageAction
125
51
  primary
126
- :label="t('jskit.push.settings.save')"
52
+ :label="saving ? t('jskit.push.settings.saving') : t('jskit.push.settings.save')"
127
53
  type="submit"
128
54
  form="push-settings-form"
129
- :loading="saving"
130
55
  :pending="saving"
131
56
  :disabled="!hasUnsavedEdits"
132
57
  />
133
58
  </ShellPageActions>
134
- <v-alert v-if="actionError" type="error" variant="tonal" class="mb-4" role="alert">{{ actionError }}</v-alert>
135
59
  <v-switch
136
60
  v-if="push.available"
61
+ v-pending="deviceBusy"
137
62
  :model-value="deviceOn"
138
63
  :label="t('jskit.push.settings.thisDevice')"
139
64
  :loading="deviceBusy"
140
- :disabled="deviceBusy"
141
65
  color="primary"
142
66
  hide-details
143
67
  @update:model-value="toggleDevice"
144
68
  />
145
- <p v-else class="text-body-2 text-medium-emphasis">{{ t("jskit.push.settings.thisDeviceUnavailable") }}</p>
69
+ <p v-else class="text-body-medium text-on-surface-variant">{{ t("jskit.push.settings.thisDeviceUnavailable") }}</p>
146
70
 
147
71
  <v-form id="push-settings-form" novalidate @submit.prevent="save">
148
72
  <h2 v-if="push.kinds.length" class="text-title-medium mt-6 mb-2">{{ t("jskit.push.settings.kinds") }}</h2>
@@ -159,18 +83,34 @@ onMounted(load);
159
83
  <v-switch v-model="form.showText" :label="t('jskit.push.settings.showText')" color="primary" hide-details :disabled="saving" />
160
84
  <h2 class="text-title-medium mt-6 mb-2">{{ t("jskit.push.settings.quietHours") }}</h2>
161
85
  <div class="push-settings__quiet">
162
- <v-text-field v-model="form.quietFrom" type="time" :label="t('jskit.push.settings.quietFrom')" :disabled="saving" />
163
- <v-text-field v-model="form.quietTo" type="time" :label="t('jskit.push.settings.quietTo')" :disabled="saving" />
86
+ <v-text-field
87
+ v-model="form.quietFrom"
88
+ type="time"
89
+ :label="t('jskit.push.settings.quietFrom')"
90
+ :error-messages="fieldErrors.quietFrom"
91
+ :disabled="saving"
92
+ />
93
+ <v-text-field
94
+ v-model="form.quietTo"
95
+ type="time"
96
+ :label="t('jskit.push.settings.quietTo')"
97
+ :error-messages="fieldErrors.quietTo"
98
+ :disabled="saving"
99
+ />
164
100
  </div>
165
- <p class="text-body-2 text-medium-emphasis">{{ t("jskit.push.settings.quietHint", { timeZone }) }}</p>
101
+ <p class="text-body-medium text-on-surface-variant">{{ t("jskit.push.settings.quietHint", { timeZone }) }}</p>
166
102
  </v-form>
167
103
 
168
104
  <h2 class="text-title-medium mt-6 mb-2">{{ t("jskit.push.settings.devices") }}</h2>
169
- <p v-if="!devices.length" class="text-body-2 text-medium-emphasis">{{ t("jskit.push.settings.noDevices") }}</p>
105
+ <p v-if="!devices.length" class="push-settings__empty text-body-medium text-on-surface-variant">
106
+ <v-icon icon="$notifications" color="on-surface-variant" />
107
+ {{ t("jskit.push.settings.noDevices") }}
108
+ </p>
170
109
  <v-list v-else lines="one">
171
- <v-list-item v-for="device in devices" :key="device.id" :title="deviceLabel(device)">
110
+ <v-list-item v-for="device in devices" :key="device.id" prepend-icon="$notifications" :title="deviceLabel(device)">
172
111
  <template #append>
173
112
  <v-btn
113
+ v-pending="removing.has(device.id)"
174
114
  icon="$delete"
175
115
  variant="text"
176
116
  :aria-label="t('jskit.push.settings.remove', { label: deviceLabel(device) })"
@@ -188,6 +128,12 @@ onMounted(load);
188
128
  padding: 1rem 0;
189
129
  }
190
130
 
131
+ .push-settings__empty {
132
+ align-items: center;
133
+ display: flex;
134
+ gap: 0.75rem;
135
+ }
136
+
191
137
  .push-settings__quiet {
192
138
  display: grid;
193
139
  grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -0,0 +1,148 @@
1
+ import { computed, reactive, ref, watch } from "vue";
2
+ import { useJskitText } from "../i18n.js";
3
+
4
+ const KIND_LABELS = Object.freeze({
5
+ webpush: "jskit.push.settings.kind.webpush",
6
+ apns: "jskit.push.settings.kind.apns",
7
+ fcm: "jskit.push.settings.kind.fcm"
8
+ });
9
+
10
+ /**
11
+ * The state and actions of the account settings' notifications section (PushSettingsSection): this device on or off,
12
+ * the kinds a person wants, text shown or not, quiet hours, and the devices that get them. Only the first load shows the
13
+ * skeleton: turning this device on or off and removing a device refresh the device list and leave the form as the
14
+ * person left it.
15
+ * @param {object} options
16
+ * @param {{ available: boolean, current: () => Promise<unknown>, permission: () => Promise<string>, enable: () => Promise<unknown>, disable: () => Promise<unknown> }} options.push
17
+ * @param {(path: string, options?: object) => Promise<any>} options.request The page's HTTP client's request.
18
+ * @param {string} options.timeZone The person's time zone, which quiet hours are kept in.
19
+ * @param {(message: string) => void} options.report Shows a command's failure (the shell's snackbar); a refusal about
20
+ * a field shows beside it instead.
21
+ */
22
+ function usePushSettings({ push, request, timeZone, report }) {
23
+ const { t, serverMessage, fieldErrorMessages } = useJskitText();
24
+ const status = ref("loading");
25
+ const loadError = ref("");
26
+ // A refusal about one field (quiet hours with one end), shown beside it until the person changes it.
27
+ const fieldErrors = ref({});
28
+ const saving = ref(false);
29
+ const deviceBusy = ref(false);
30
+ const deviceOn = ref(false);
31
+ const devices = ref([]);
32
+ const removing = ref(new Set());
33
+ const saved = ref(null);
34
+ const form = reactive({ kindsOff: [], showText: true, quietFrom: "", quietTo: "" });
35
+ const deviceLabel = (device) => device.label || t(KIND_LABELS[device.kind] || KIND_LABELS.webpush);
36
+
37
+ const hasUnsavedEdits = computed(() => saved.value !== null && JSON.stringify(formBody()) !== JSON.stringify(saved.value));
38
+
39
+ function formBody() {
40
+ return {
41
+ kindsOff: [...form.kindsOff].sort(),
42
+ showText: form.showText,
43
+ quietFrom: form.quietFrom || null,
44
+ quietTo: form.quietTo || null,
45
+ timeZone: form.quietFrom || form.quietTo ? timeZone : null
46
+ };
47
+ }
48
+
49
+ function showSettings(settings) {
50
+ form.kindsOff = [...settings.kindsOff];
51
+ form.showText = settings.showText;
52
+ form.quietFrom = settings.quietFrom || "";
53
+ form.quietTo = settings.quietTo || "";
54
+ saved.value = formBody();
55
+ }
56
+
57
+ watch(() => [form.quietFrom, form.quietTo], () => {
58
+ fieldErrors.value = {};
59
+ }, { flush: "sync" });
60
+
61
+ /** The device list and whether this device is on, as the server and the device have them now. */
62
+ async function readDevices() {
63
+ const overview = await request("/api/push", { method: "GET" });
64
+ const current = await push.current();
65
+ devices.value = overview.devices;
66
+ deviceOn.value = Boolean(current) && (await push.permission()) === "granted";
67
+ return overview;
68
+ }
69
+
70
+ async function load() {
71
+ status.value = "loading";
72
+ try {
73
+ showSettings((await readDevices()).settings);
74
+ status.value = "ready";
75
+ } catch (error) {
76
+ loadError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
77
+ status.value = "error";
78
+ }
79
+ }
80
+
81
+ async function toggleDevice(on) {
82
+ deviceBusy.value = true;
83
+ try {
84
+ if (on) await push.enable();
85
+ else await push.disable();
86
+ await readDevices();
87
+ } catch (error) {
88
+ report(serverMessage(error, t("jskit.push.device.registrationFailed")));
89
+ } finally {
90
+ deviceBusy.value = false;
91
+ }
92
+ }
93
+
94
+ function setKind(id, on) {
95
+ form.kindsOff = on ? form.kindsOff.filter((kind) => kind !== id) : [...new Set([...form.kindsOff, id])];
96
+ }
97
+
98
+ async function save() {
99
+ saving.value = true;
100
+ fieldErrors.value = {};
101
+ try {
102
+ showSettings(await request("/api/push/settings", { method: "PUT", body: formBody() }));
103
+ } catch (error) {
104
+ fieldErrors.value = fieldErrorMessages(error);
105
+ if (Object.keys(fieldErrors.value).length === 0) {
106
+ report(serverMessage(error, t("jskit.push.settings.saveFailed")));
107
+ }
108
+ } finally {
109
+ saving.value = false;
110
+ }
111
+ }
112
+
113
+ /** Removes one of the person's devices; pressing Remove again while it goes sends nothing more. */
114
+ async function removeDevice(id) {
115
+ if (removing.value.has(id)) return;
116
+ removing.value = new Set([...removing.value, id]);
117
+ const device = devices.value.find((entry) => entry.id === id);
118
+ try {
119
+ await request(`/api/push/devices/${encodeURIComponent(id)}`, { method: "DELETE" });
120
+ await readDevices();
121
+ } catch (error) {
122
+ report(serverMessage(error, t("jskit.push.settings.removeFailed", { label: deviceLabel(device) })));
123
+ } finally {
124
+ removing.value = new Set([...removing.value].filter((entry) => entry !== id));
125
+ }
126
+ }
127
+
128
+ return {
129
+ status,
130
+ loadError,
131
+ fieldErrors,
132
+ saving,
133
+ deviceBusy,
134
+ deviceOn,
135
+ devices,
136
+ removing,
137
+ deviceLabel,
138
+ form,
139
+ hasUnsavedEdits,
140
+ load,
141
+ toggleDevice,
142
+ setKind,
143
+ save,
144
+ removeDevice
145
+ };
146
+ }
147
+
148
+ export { usePushSettings };
@@ -21,4 +21,4 @@ function registerServiceWorkerRoutes(router) {
21
21
  });
22
22
  }
23
23
 
24
- export { SERVICE_WORKER_PATH, registerServiceWorkerRoutes };
24
+ export { registerServiceWorkerRoutes };
@@ -0,0 +1,85 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { watch } from "vue";
4
+ import { usePushSettings } from "../src/client/composables/usePushSettings.js";
5
+
6
+ // The notifications section's states, driven as the person drives them: what stays on screen while the device switch
7
+ // and the device list change, the words of each failure, and a refusal shown beside the field it is about.
8
+
9
+ const SETTINGS = Object.freeze({ kindsOff: [], showText: true, quietFrom: null, quietTo: null });
10
+ const PHONE = Object.freeze({ id: "7", kind: "apns", label: "Ada's iPhone" });
11
+
12
+ /** The section over a server answering `routes` ("GET /api/push" and so on), with the calls it got. */
13
+ function section(routes = {}, { current = null } = {}) {
14
+ const calls = [];
15
+ const reported = [];
16
+ const answers = {
17
+ "GET /api/push": () => ({ devices: [PHONE], settings: SETTINGS, publicKey: "key" }),
18
+ ...routes
19
+ };
20
+ const request = async (path, options = {}) => {
21
+ calls.push(`${options.method || "GET"} ${path}`);
22
+ const answer = answers[`${options.method || "GET"} ${path}`];
23
+ if (!answer) throw new Error(`No answer for ${options.method} ${path}`);
24
+ return answer(options);
25
+ };
26
+ const push = {
27
+ available: true,
28
+ kinds: [],
29
+ current: async () => current,
30
+ permission: async () => "granted",
31
+ enable: async () => {},
32
+ disable: async () => {}
33
+ };
34
+ return { calls, reported, settings: usePushSettings({ push, request, timeZone: "Europe/Rome", report: (message) => reported.push(message) }) };
35
+ }
36
+
37
+ const refusal = (fields = {}) => Object.assign(new Error(""), fields);
38
+
39
+ test("turning this device on keeps the form on screen and the quiet hours the person was typing", async () => {
40
+ const { settings } = section();
41
+ await settings.load();
42
+ settings.form.quietFrom = "22:00";
43
+ settings.form.quietTo = "07:00";
44
+ const statuses = [];
45
+ const stop = watch(settings.status, (status) => statuses.push(status));
46
+ await settings.toggleDevice(true);
47
+ stop();
48
+ assert.deepEqual(statuses, [], "the section never went back to its skeleton");
49
+ assert.deepEqual([settings.form.quietFrom, settings.form.quietTo, settings.hasUnsavedEdits.value], ["22:00", "07:00", true]);
50
+ });
51
+
52
+ test("removing a device keeps the form's edits, and a device is removed once however often Remove is pressed", async () => {
53
+ const { calls, settings } = section({ "DELETE /api/push/devices/7": () => ({ ok: true }) });
54
+ await settings.load();
55
+ settings.form.showText = false;
56
+ await Promise.all([settings.removeDevice("7"), settings.removeDevice("7")]);
57
+ assert.equal(calls.filter((call) => call === "DELETE /api/push/devices/7").length, 1);
58
+ assert.deepEqual([settings.status.value, settings.form.showText], ["ready", false]);
59
+ });
60
+
61
+ test("a failed save says the settings weren't saved, and a failed removal that the device wasn't", async () => {
62
+ const { settings, reported } = section({
63
+ "PUT /api/push/settings": () => { throw refusal(); },
64
+ "DELETE /api/push/devices/7": () => { throw refusal(); }
65
+ });
66
+ await settings.load();
67
+ await settings.save();
68
+ await settings.removeDevice("7");
69
+ assert.deepEqual(reported, ["Your notification settings weren't saved. Try again.", "Ada's iPhone wasn't removed. Try again."]);
70
+ });
71
+
72
+ test("quiet hours with one end refused show beside the empty field, not above the form", async () => {
73
+ const quietRefusal = refusal({
74
+ message: "Quiet hours need both a start and an end.",
75
+ code: "push.settings.quietHoursIncomplete",
76
+ details: { fieldErrors: { quietTo: "Choose when quiet hours end." } }
77
+ });
78
+ const { settings, reported } = section({ "PUT /api/push/settings": () => { throw quietRefusal; } });
79
+ await settings.load();
80
+ settings.form.quietFrom = "22:00";
81
+ await settings.save();
82
+ assert.deepEqual([settings.fieldErrors.value, reported], [{ quietTo: "Choose when quiet hours end." }, []]);
83
+ settings.form.quietTo = "07:00";
84
+ assert.deepEqual(settings.fieldErrors.value, {}, "the field's error goes once the person fills it");
85
+ });
@@ -0,0 +1,96 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { createSSRApp, defineComponent, h, ref } from "vue";
4
+ import { renderToString } from "vue/server-renderer";
5
+ import { importComponent } from "../../../tooling/test-support/vueComponent.mjs";
6
+
7
+ // The notifications section as the app renders it over usePushSettings' state, without a browser: a refusal about a
8
+ // quiet hours end beside that field, Save reading "Saving…" while it runs, and Remove and the device switch staying
9
+ // focusable while they run. Vuetify's components and the shell's page actions are stand-ins that show the props the
10
+ // section gives them, as attributes.
11
+ const VIEW = new URL("../src/client/components/PushSettingsSection.vue", import.meta.url);
12
+ const STUBS = Object.freeze({
13
+ "@jskit-ai/http-web/client": "export const getHttpWebClient = () => ({});",
14
+ "@jskit-ai/shell-web/client/components/ShellPageAction": "export default globalThis.__pushSettingsTest.ShellPageAction;",
15
+ "@jskit-ai/shell-web/client/components/ShellPageActions": "export default globalThis.__pushSettingsTest.ShellPageActions;",
16
+ "@jskit-ai/shell-web/client/directives/vPending": "export const vPending = { getSSRProps: ({ value }) => ({ 'data-pending': String(value) }) };",
17
+ "../PushClientProvider.js": "export const usePushClient = () => ({ available: true, kinds: [] });",
18
+ "../composables/usePushSettings.js": "export const usePushSettings = () => globalThis.__pushSettingsTest.state;"
19
+ });
20
+
21
+ const importView = () => importComponent(VIEW, STUBS);
22
+
23
+ /** A Vuetify component as an element of `tag` carrying the props it was given, its slot inside. */
24
+ const stand = (tag, props = []) => defineComponent({
25
+ inheritAttrs: false,
26
+ props: Object.fromEntries(props.map((name) => [name, null])),
27
+ setup: (given, { slots, attrs }) => () => h(tag, {
28
+ ...Object.fromEntries(props.filter((name) => given[name] !== undefined && given[name] !== false).map((name) => [`data-${name}`, String(given[name])])),
29
+ ...(attrs["data-pending"] ? { "data-pending": attrs["data-pending"] } : {})
30
+ }, slots.default?.())
31
+ });
32
+
33
+ globalThis.__pushSettingsTest = {
34
+ state: null,
35
+ ShellPageActions: defineComponent({ setup: (_props, { slots }) => () => h("nav", slots.default?.()) }),
36
+ ShellPageAction: defineComponent({
37
+ props: { label: { type: String, default: "" }, pending: Boolean, loading: Boolean },
38
+ setup: (props) => () => h("button", { "data-action": props.label, "data-pending": String(props.pending), "data-loading": String(props.loading) })
39
+ })
40
+ };
41
+
42
+ async function render(state) {
43
+ globalThis.__pushSettingsTest.state = state;
44
+ const PushSettingsSection = await importView();
45
+ const root = createSSRApp({ render: () => h(PushSettingsSection) });
46
+ for (const [name, component] of Object.entries(VUETIFY)) root.component(name, component);
47
+ return renderToString(root);
48
+ }
49
+
50
+ const VUETIFY = {
51
+ VBtn: stand("button", ["ariaLabel"]),
52
+ VAlert: stand("div"),
53
+ VForm: stand("form"),
54
+ VList: stand("ul"),
55
+ VListItem: defineComponent({ props: { title: { type: String, default: "" } }, setup: (props, { slots }) => () => h("li", { "data-title": props.title }, slots.append?.()) }),
56
+ VSwitch: stand("label", ["label"]),
57
+ VTextField: stand("input", ["label", "errorMessages"])
58
+ };
59
+
60
+ function settings({ saving = false, fieldErrors = {}, removing = [], deviceBusy = false } = {}) {
61
+ return {
62
+ status: ref("ready"),
63
+ loadError: ref(""),
64
+ actionError: ref(""),
65
+ fieldErrors: ref(fieldErrors),
66
+ saving: ref(saving),
67
+ deviceBusy: ref(deviceBusy),
68
+ deviceOn: ref(false),
69
+ devices: ref([{ id: "7", kind: "apns", label: "Ada's iPhone" }]),
70
+ removing: ref(new Set(removing)),
71
+ deviceLabel: (device) => device.label,
72
+ form: { kindsOff: [], showText: true, quietFrom: "22:00", quietTo: "" },
73
+ hasUnsavedEdits: ref(true),
74
+ load() {},
75
+ toggleDevice() {},
76
+ setKind() {},
77
+ save() {},
78
+ removeDevice() {}
79
+ };
80
+ }
81
+
82
+ test("a refusal about a quiet hours end shows beside that field", async () => {
83
+ const html = await render(settings({ fieldErrors: { quietTo: "Choose when quiet hours end." } }));
84
+ assert.match(html, /<input[^>]*data-errormessages="Choose when quiet hours end\."[^>]*data-label="To"|<input[^>]*data-label="To"[^>]*data-errormessages="Choose when quiet hours end\."/u);
85
+ });
86
+
87
+ test("while it saves, Save reads Saving… and stays a pending action rather than a spinner", async () => {
88
+ const html = await render(settings({ saving: true }));
89
+ assert.match(html, /data-action="Saving…" data-pending="true" data-loading="false"/u);
90
+ });
91
+
92
+ test("Remove and the device switch stay focusable while they run", async () => {
93
+ const html = await render(settings({ removing: ["7"], deviceBusy: true }));
94
+ assert.match(html, /<button data-arialabel="Remove Ada&#39;s iPhone" data-pending="true">/u);
95
+ assert.match(html, /<label[^>]*data-pending="true"/u);
96
+ });