@cloudlet/toast 1.2.0 → 1.4.0-rc.1
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 +139 -0
- package/README.md +7 -3
- package/dist/agent.d.ts +334 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +494 -0
- package/dist/agent.js.map +1 -0
- package/dist/contracts/events.d.ts +14 -0
- package/dist/contracts/events.d.ts.map +1 -1
- package/dist/contracts/internal.d.ts +16 -2
- package/dist/contracts/internal.d.ts.map +1 -1
- package/dist/contracts/notifications.d.ts +16 -0
- package/dist/contracts/notifications.d.ts.map +1 -1
- package/dist/contracts/snapshots.d.ts +8 -0
- package/dist/contracts/snapshots.d.ts.map +1 -1
- package/dist/core/actions.d.ts +69 -0
- package/dist/core/actions.d.ts.map +1 -0
- package/dist/core/actions.js +160 -0
- package/dist/core/actions.js.map +1 -0
- package/dist/core/agent-port.d.ts +116 -0
- package/dist/core/agent-port.d.ts.map +1 -0
- package/dist/core/agent-port.js +138 -0
- package/dist/core/agent-port.js.map +1 -0
- package/dist/core/bridge.d.ts.map +1 -1
- package/dist/core/bridge.js +120 -231
- package/dist/core/bridge.js.map +1 -1
- package/dist/core/controller.d.ts +44 -9
- package/dist/core/controller.d.ts.map +1 -1
- package/dist/core/controller.js +367 -292
- package/dist/core/controller.js.map +1 -1
- package/dist/core/validation.d.ts.map +1 -1
- package/dist/core/validation.js +103 -94
- package/dist/core/validation.js.map +1 -1
- package/dist/react/card.d.ts.map +1 -1
- package/dist/react/card.js +3 -3
- package/dist/react/card.js.map +1 -1
- package/dist/react/gestures.d.ts +6 -0
- package/dist/react/gestures.d.ts.map +1 -1
- package/dist/react/gestures.js +28 -15
- package/dist/react/gestures.js.map +1 -1
- package/dist/react/host.d.ts.map +1 -1
- package/dist/react/host.js +290 -270
- package/dist/react/host.js.map +1 -1
- package/dist/react.d.ts +9 -1
- package/dist/react.d.ts.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +3 -2
- package/src/agent.ts +879 -0
- package/src/contracts/events.ts +15 -0
- package/src/contracts/internal.ts +14 -1
- package/src/contracts/notifications.ts +16 -0
- package/src/contracts/snapshots.ts +8 -0
- package/src/core/actions.ts +149 -0
- package/src/core/agent-port.ts +237 -0
- package/src/core/bridge.ts +19 -105
- package/src/core/controller.ts +183 -56
- package/src/core/validation.ts +6 -3
- package/src/react/card.tsx +4 -3
- package/src/react/gestures.ts +45 -8
- package/src/react/host.tsx +48 -12
- package/src/react.ts +9 -1
package/src/contracts/events.ts
CHANGED
|
@@ -23,8 +23,23 @@ export interface Diagnostic {
|
|
|
23
23
|
readonly error?: unknown;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Who caused a change.
|
|
28
|
+
*
|
|
29
|
+
* - `user`: a person, through the `Toaster` on screen: a click, a swipe, a key.
|
|
30
|
+
* - `agent`: a step an agent took through `@cloudlet/toast/agent`.
|
|
31
|
+
* - `app`: the application's own code, through the controller or an operation handle.
|
|
32
|
+
* - `system`: Cloudlet itself: a timer, the outcome of an operation, `dispose()`.
|
|
33
|
+
*/
|
|
34
|
+
export type ChangeSource = 'user' | 'agent' | 'app' | 'system';
|
|
35
|
+
|
|
26
36
|
export interface EventBase {
|
|
27
37
|
readonly controller: ControllerIdentity;
|
|
38
|
+
/**
|
|
39
|
+
* Who caused the event. Both outcomes of an action attempt carry the source of whoever pressed
|
|
40
|
+
* it, however long the action ran; the outcome of an operation is always `system`.
|
|
41
|
+
*/
|
|
42
|
+
readonly source: ChangeSource;
|
|
28
43
|
readonly sequence: number;
|
|
29
44
|
/** Monotonic milliseconds, not wall-clock time. */
|
|
30
45
|
readonly at: number;
|
|
@@ -84,6 +84,16 @@ export type AnnouncementAcknowledgement =
|
|
|
84
84
|
export interface FormErrors {
|
|
85
85
|
readonly form: string | null;
|
|
86
86
|
readonly fields: Readonly<Record<string, string>>;
|
|
87
|
+
/**
|
|
88
|
+
* The messages are what the app's `validate` returned, so they may quote what the person typed;
|
|
89
|
+
* absent for the built-in messages, which never hold a value.
|
|
90
|
+
*/
|
|
91
|
+
readonly authored?: true;
|
|
92
|
+
/**
|
|
93
|
+
* `validate` threw or answered nonsense: `form` is the app's configured failure message, which
|
|
94
|
+
* stays with the person.
|
|
95
|
+
*/
|
|
96
|
+
readonly broken?: true;
|
|
87
97
|
}
|
|
88
98
|
|
|
89
99
|
/** The values a form action holds for one record; only the renderer sees them. */
|
|
@@ -91,6 +101,8 @@ export interface FormDraft {
|
|
|
91
101
|
readonly handle: NotificationHandle;
|
|
92
102
|
readonly values: Readonly<Record<string, string>>;
|
|
93
103
|
readonly errors: FormErrors;
|
|
104
|
+
/** Who wrote each field last (own keys only); a field nobody wrote and without a default has none. */
|
|
105
|
+
readonly authors: Readonly<Record<string, 'app' | 'user' | 'agent'>>;
|
|
94
106
|
}
|
|
95
107
|
|
|
96
108
|
export interface RendererSnapshot<Slot = never> extends ControllerSnapshot<Slot> {
|
|
@@ -122,7 +134,8 @@ export type ActionResult =
|
|
|
122
134
|
| { readonly status: 'started' }
|
|
123
135
|
/** A form failed `required`, `maxLength` or `validate`; the messages are in the record's draft. */
|
|
124
136
|
| { readonly status: 'invalid'; readonly errors: FormErrors }
|
|
125
|
-
|
|
137
|
+
/** `action-replaced`: the form's own `validate` put another action on the record; neither runs. */
|
|
138
|
+
| { readonly status: 'rejected'; readonly reason: BridgeRejection | 'no-command' | 'already-pending' | 'action-replaced' };
|
|
126
139
|
|
|
127
140
|
export type RetryOperationResult =
|
|
128
141
|
| { readonly status: 'started'; readonly token: OperationAttemptToken }
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ChangeSource } from './events.js';
|
|
1
2
|
import type { ActionAttemptToken, InputIssue, NotificationHandle } from './identity.js';
|
|
2
3
|
|
|
3
4
|
export type NotificationKind = 'info' | 'success' | 'loading' | 'warning' | 'error';
|
|
@@ -26,6 +27,12 @@ export interface CommandAction {
|
|
|
26
27
|
readonly label: string;
|
|
27
28
|
readonly run: (context: ActionContext) => unknown;
|
|
28
29
|
readonly errorMessage?: (error: unknown) => string;
|
|
30
|
+
/**
|
|
31
|
+
* What an agent may do with this command through `@cloudlet/toast/agent`: `allow` lets it press;
|
|
32
|
+
* `confirm` needs a person to approve each press; `deny` never lets an agent press, whatever the
|
|
33
|
+
* app approves. A person can always press it. Omitted = `confirm`.
|
|
34
|
+
*/
|
|
35
|
+
readonly agent?: 'allow' | 'confirm' | 'deny';
|
|
29
36
|
}
|
|
30
37
|
|
|
31
38
|
export interface NavigationAction {
|
|
@@ -73,6 +80,13 @@ export interface FormAction<Name extends string = string> {
|
|
|
73
80
|
errorMessage?(error: unknown): string;
|
|
74
81
|
/** Runs on submit after `required` and `maxLength`. */
|
|
75
82
|
validate?(values: FormValues<Name>): FormValidation<Name>;
|
|
83
|
+
/**
|
|
84
|
+
* What an agent may do with this form through `@cloudlet/toast/agent`: `allow` lets it submit;
|
|
85
|
+
* `confirm` needs a person to approve each submit; `deny` never lets an agent submit, whatever the
|
|
86
|
+
* app approves. None of them stops an agent from filling the fields, and a person can always
|
|
87
|
+
* submit. Omitted = `confirm`.
|
|
88
|
+
*/
|
|
89
|
+
readonly agent?: 'allow' | 'confirm' | 'deny';
|
|
76
90
|
}
|
|
77
91
|
|
|
78
92
|
export type PrimaryAction<Name extends string = string> = CommandAction | NavigationAction | FormAction<Name>;
|
|
@@ -104,6 +118,8 @@ export type CloseReason =
|
|
|
104
118
|
export interface CloseNotice {
|
|
105
119
|
readonly handle: NotificationHandle;
|
|
106
120
|
readonly reason: CloseReason;
|
|
121
|
+
/** Who closed the notification; the same value the `closed` event carries. */
|
|
122
|
+
readonly source: ChangeSource;
|
|
107
123
|
}
|
|
108
124
|
|
|
109
125
|
export interface NotificationSpec<Slot = never, Name extends string = string> extends NotificationContent<Slot, Name> {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ChangeSource } from './events.js';
|
|
1
2
|
import type { ActionAttemptToken, ControllerIdentity, NotificationHandle } from './identity.js';
|
|
2
3
|
import type { NotificationContent, NotificationKind, OverflowSnapshot, Priority } from './notifications.js';
|
|
3
4
|
import type { OperationSnapshot } from './operations.js';
|
|
@@ -47,6 +48,13 @@ export interface IslandSnapshot {
|
|
|
47
48
|
readonly reason: IslandReason | null;
|
|
48
49
|
/** Null exactly when the Island is closed. */
|
|
49
50
|
readonly current: NotificationHandle | null;
|
|
51
|
+
/**
|
|
52
|
+
* Who opened the Island or moved it to its current notification last: `user` by hand, `system`
|
|
53
|
+
* when it opened for attention on its own, `agent` for an agent's step or its request for a
|
|
54
|
+
* person. When the current notification closed and the Island moved on, whoever closed it.
|
|
55
|
+
* Null exactly when the Island is closed.
|
|
56
|
+
*/
|
|
57
|
+
readonly source: ChangeSource | null;
|
|
50
58
|
}
|
|
51
59
|
|
|
52
60
|
export interface ControllerSnapshot<Slot = never> {
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import type { ChangeSource } from '../contracts/events.js';
|
|
2
|
+
import type { ActionAttemptToken, NotificationHandle } from '../contracts/identity.js';
|
|
3
|
+
import type { FormErrors } from '../contracts/internal.js';
|
|
4
|
+
import { NO_FORM_ERRORS, UNCHANGED, reject, type ControllerKernel, type FieldAuthor, type FormState, type RecordState } from './controller.js';
|
|
5
|
+
|
|
6
|
+
// Running a notification's action and editing its form, shared by every caller that may act on a
|
|
7
|
+
// record. Callers check their own capability (a host lease, say) and resolve the record first;
|
|
8
|
+
// these functions own the order of the remaining checks, the rejections, events and diagnostics.
|
|
9
|
+
// The controller never imports this module, so it stays out of the start bundle.
|
|
10
|
+
const freeze = Object.freeze;
|
|
11
|
+
|
|
12
|
+
/** `required` and `maxLength` first, then the form's own `validate`; null lets the submit run. */
|
|
13
|
+
export function checkForm<Slot>(k: ControllerKernel<Slot>, form: FormState, handle: NotificationHandle): FormErrors | null {
|
|
14
|
+
const messages = k.options.messages;
|
|
15
|
+
// Own keys only, read and written: a field named `constructor` must not meet `Object.prototype`,
|
|
16
|
+
// and one named `__proto__` must keep its message (an assignment would set the prototype).
|
|
17
|
+
const entries: [string, string][] = [];
|
|
18
|
+
for (const field of form.action.fields) {
|
|
19
|
+
const value = Object.hasOwn(form.values, field.name) ? form.values[field.name]! : '';
|
|
20
|
+
if (field.required && !value.trim()) entries.push([field.name, messages?.fieldRequired ?? 'This field is required']);
|
|
21
|
+
else if (field.maxLength !== undefined && value.length > field.maxLength) entries.push([field.name, messages?.fieldTooLong ?? 'This text is too long']);
|
|
22
|
+
}
|
|
23
|
+
if (entries.length) return freeze({ form: null, fields: freeze(Object.fromEntries(entries)) });
|
|
24
|
+
if (!form.action.validate) return null;
|
|
25
|
+
let result: unknown;
|
|
26
|
+
try {
|
|
27
|
+
result = form.action.validate(form.values);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
k.failure('callback-error', 'action.validate', error, handle);
|
|
30
|
+
return freeze({ form: messages?.actionError ?? 'Action failed', fields: freeze({}), broken: true as const });
|
|
31
|
+
}
|
|
32
|
+
if (result === true) return null;
|
|
33
|
+
if (typeof result === 'string' && result.trim()) return freeze({ form: result, fields: freeze({}), authored: true as const });
|
|
34
|
+
const names = form.action.fields.map((field) => field.name);
|
|
35
|
+
if (result !== null && typeof result === 'object' && Object.getPrototypeOf(result) === Object.prototype &&
|
|
36
|
+
Object.entries(result).every(([name, message]) => names.includes(name) && typeof message === 'string' && message.trim())) {
|
|
37
|
+
return Object.keys(result).length ? freeze({ form: null, fields: freeze({ ...result as Record<string, string> }), authored: true as const }) : null;
|
|
38
|
+
}
|
|
39
|
+
k.diagnostic({ code: 'callback-error', source: 'action.validate', handle,
|
|
40
|
+
message: 'validate must return true, a message, or messages keyed by field name' });
|
|
41
|
+
return freeze({ form: messages?.actionError ?? 'Action failed', fields: freeze({}), broken: true as const });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Starts a command action or submits a form; an invalid form records its errors and does not run.
|
|
46
|
+
* The attempt remembers `source`, who pressed: its start and both its outcomes carry it, however
|
|
47
|
+
* long the action runs and whoever acts in between.
|
|
48
|
+
*/
|
|
49
|
+
export function invokeAction<Slot>(k: ControllerKernel<Slot>, record: RecordState<Slot>, source: ChangeSource) {
|
|
50
|
+
const handle = record.handle;
|
|
51
|
+
const action = record.content.action;
|
|
52
|
+
if (!action || action.kind === 'link') return reject('no-command');
|
|
53
|
+
if (record.action.status === 'pending') return reject('already-pending');
|
|
54
|
+
const form = k.formOf(record);
|
|
55
|
+
if (form) {
|
|
56
|
+
const errors = checkForm(k, form, handle);
|
|
57
|
+
if (errors) {
|
|
58
|
+
k.mutate(() => { form.errors = errors; });
|
|
59
|
+
return { status: 'invalid' as const, errors };
|
|
60
|
+
}
|
|
61
|
+
// `validate` is the app's code and may have replaced the action it was checking: the press was
|
|
62
|
+
// for the one that is gone, so neither runs.
|
|
63
|
+
if (k.records.get(handle.id) !== record || record.content.action !== action) return reject('action-replaced');
|
|
64
|
+
}
|
|
65
|
+
const actionToken = k.token() as ActionAttemptToken;
|
|
66
|
+
const live = () => !k.disposed && k.records.get(handle.id) === record &&
|
|
67
|
+
record.action.status === 'pending' && record.action.token === actionToken;
|
|
68
|
+
const now = k.settle();
|
|
69
|
+
record.action = freeze({ status: 'pending', token: actionToken });
|
|
70
|
+
if (form) form.errors = NO_FORM_ERRORS;
|
|
71
|
+
k.commit([{ type: 'action-started', source, handle, token: actionToken }], now);
|
|
72
|
+
// A listener of `action-started` may have dismissed or replaced the record: the attempt is over
|
|
73
|
+
// before it began, and running the action now would act for a notification that is gone.
|
|
74
|
+
if (!live()) return { status: 'started' as const, token: actionToken };
|
|
75
|
+
function failed(reason: unknown): void {
|
|
76
|
+
if (!live()) return;
|
|
77
|
+
let message = k.options.messages?.actionError ?? 'Action failed';
|
|
78
|
+
if (action && action.kind !== 'link' && action.errorMessage) {
|
|
79
|
+
try {
|
|
80
|
+
const mapped = action.errorMessage(reason);
|
|
81
|
+
if (typeof mapped !== 'string' || !mapped.trim()) throw new TypeError('Invalid action error message');
|
|
82
|
+
message = mapped;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (!k.disposed) k.failure('mapper-error', 'action.errorMessage', error, handle);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (!live()) return;
|
|
88
|
+
const now = k.settle();
|
|
89
|
+
record.action = freeze({ status: 'failed', token: actionToken, message });
|
|
90
|
+
k.commit([{ type: 'action-failed', source, handle, token: actionToken, message }], now);
|
|
91
|
+
}
|
|
92
|
+
let result: Promise<unknown>;
|
|
93
|
+
try {
|
|
94
|
+
result = Promise.resolve(form ? form.action.run(freeze({ handle, token: actionToken, values: form.values }))
|
|
95
|
+
: action.kind === 'command' ? action.run(freeze({ handle, token: actionToken })) : undefined);
|
|
96
|
+
}
|
|
97
|
+
catch (error) { result = Promise.reject(error); }
|
|
98
|
+
void result.then(() => {
|
|
99
|
+
if (live()) k.dismiss(handle, 'action-success', source);
|
|
100
|
+
}, failed).catch((error: unknown) => {
|
|
101
|
+
if (!k.disposed) k.failure('callback-error', 'action-settlement', error, handle);
|
|
102
|
+
});
|
|
103
|
+
return { status: 'started' as const, token: actionToken };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Writes one field of the record's form as the person; editing a field clears its own message. */
|
|
107
|
+
export function setFormValue<Slot>(k: ControllerKernel<Slot>, record: RecordState<Slot>, name: string, value: string) {
|
|
108
|
+
const target = fieldOf(k, record, name, value);
|
|
109
|
+
return 'status' in target ? target : write(k, target.form, name, value, 'user');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Writes one field as an agent. Its value must fit `maxLength`, and it never replaces what the
|
|
114
|
+
* person typed, not even text they have since deleted.
|
|
115
|
+
*/
|
|
116
|
+
export function fillFormValue<Slot>(k: ControllerKernel<Slot>, record: RecordState<Slot>, name: string, value: string) {
|
|
117
|
+
const target = fieldOf(k, record, name, value);
|
|
118
|
+
if ('status' in target) return target;
|
|
119
|
+
const { form, field } = target;
|
|
120
|
+
if (field.maxLength !== undefined && value.length > field.maxLength) return reject('too-long');
|
|
121
|
+
// Own keys only: a field named `constructor` must not read `Object.prototype`.
|
|
122
|
+
if (Object.hasOwn(form.authors, name) && form.authors[name] === 'user') return reject('person-typed');
|
|
123
|
+
return write(k, form, name, value, 'agent');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function fieldOf<Slot>(k: ControllerKernel<Slot>, record: RecordState<Slot>, name: string, value: string) {
|
|
127
|
+
const form = k.formOf(record);
|
|
128
|
+
if (!form) return reject('no-form');
|
|
129
|
+
const field = form.action.fields.find((item) => item.name === name);
|
|
130
|
+
if (typeof value !== 'string' || !field) return reject('invalid-input');
|
|
131
|
+
if (record.action.status === 'pending') return reject('already-pending');
|
|
132
|
+
return { form, field };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function write<Slot>(k: ControllerKernel<Slot>, form: FormState, name: string, value: string, author: FieldAuthor) {
|
|
136
|
+
// The same text again changes nothing, its author included.
|
|
137
|
+
if (Object.hasOwn(form.values, name) && form.values[name] === value) return UNCHANGED;
|
|
138
|
+
return k.mutate(() => {
|
|
139
|
+
// Spreads and computed keys define own properties, so `__proto__` stays a field here too.
|
|
140
|
+
form.authors = freeze({ ...form.authors, [name]: author });
|
|
141
|
+
form.values = freeze({ ...form.values, [name]: value });
|
|
142
|
+
// Editing a field clears its own message; the rest wait for the next submit.
|
|
143
|
+
if (Object.hasOwn(form.errors.fields, name)) {
|
|
144
|
+
const { [name]: _, ...fields } = form.errors.fields;
|
|
145
|
+
// The marks stay: the messages left are still the app's own.
|
|
146
|
+
form.errors = freeze({ ...form.errors, fields: freeze(fields) });
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import type { ChangeSource } from '../contracts/events.js';
|
|
2
|
+
import type { NotificationHandle } from '../contracts/identity.js';
|
|
3
|
+
import type { FormErrors, RendererSnapshot } from '../contracts/internal.js';
|
|
4
|
+
import type { CancellationSignal, CancelResult } from '../contracts/operations.js';
|
|
5
|
+
import type { ControllerSnapshot } from '../contracts/snapshots.js';
|
|
6
|
+
import { fillFormValue, invokeAction } from './actions.js';
|
|
7
|
+
import { UNCHANGED, getControllerKernel, reject, type ControllerKernel, type EventPayload, type FieldAuthor, type RecordState } from './controller.js';
|
|
8
|
+
|
|
9
|
+
// The agent adapter's way into a controller. Only the `agent` entry imports it, so the root entry
|
|
10
|
+
// and the renderer chunk never carry it. It hands out no lease: a step that needs a screen only
|
|
11
|
+
// checks that a `Toaster` holds one, and no step asks for focus. Form values reach the adapter only
|
|
12
|
+
// as "holds text" and who wrote them: `forms` is reduced here, and `controller` is typed as the
|
|
13
|
+
// public snapshot, although at runtime it is the renderer's object with its form drafts.
|
|
14
|
+
|
|
15
|
+
const freeze = Object.freeze;
|
|
16
|
+
|
|
17
|
+
/** What a reader may know about a form: which fields hold text, who wrote them, the last submit's messages. */
|
|
18
|
+
export interface FormReading {
|
|
19
|
+
/** Names of the fields whose value has non-blank text, the same test `required` uses. */
|
|
20
|
+
readonly filled: ReadonlySet<string>;
|
|
21
|
+
/** Who wrote each field last; a field nobody wrote and without a default is missing. */
|
|
22
|
+
readonly authors: ReadonlyMap<string, FieldAuthor>;
|
|
23
|
+
readonly errors: FormErrors;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface ToasterReading<Slot> {
|
|
27
|
+
readonly controller: ControllerSnapshot<Slot>;
|
|
28
|
+
/** A `Toaster` holds the controller's host lease. */
|
|
29
|
+
readonly mounted: boolean;
|
|
30
|
+
/** A person is on the Toaster: hover, focus, a gesture, or a draft in the open Island. */
|
|
31
|
+
readonly busy: boolean;
|
|
32
|
+
/** One entry per record with a form action. */
|
|
33
|
+
readonly forms: ReadonlyMap<NotificationHandle, FormReading>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** An event as the commit queued it: its type, source and fields, before it is stamped and delivered. */
|
|
37
|
+
export type PortEvent = EventPayload;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* One committed change: its events and the state it left. A listener of an earlier commit may have
|
|
41
|
+
* committed again, so `read()` can be ahead of this state.
|
|
42
|
+
*/
|
|
43
|
+
export interface PortCommit<Slot> {
|
|
44
|
+
readonly events: readonly PortEvent[];
|
|
45
|
+
readonly controller: ControllerSnapshot<Slot>;
|
|
46
|
+
/** Who wrote each field of each form last; never a value. */
|
|
47
|
+
readonly authors: ReadonlyMap<NotificationHandle, ReadonlyMap<string, FieldAuthor>>;
|
|
48
|
+
/** Who closed the Island last; null before the first close. */
|
|
49
|
+
readonly closedBy: ChangeSource | null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The grant a step was approved under; a marker stricter than it stops the step. */
|
|
53
|
+
export type StepGrant = 'allow' | 'confirm';
|
|
54
|
+
|
|
55
|
+
type Rejection<Reason extends string> = { readonly status: 'rejected'; readonly reason: Reason };
|
|
56
|
+
type HandleReason = 'disposed' | 'invalid-handle' | 'foreign-controller' | 'stale-handle';
|
|
57
|
+
type Changed = { readonly status: 'applied' | 'unchanged' };
|
|
58
|
+
|
|
59
|
+
/** How a pressed command or a submitted form ended, as far as the step waited for it. */
|
|
60
|
+
export type PressOutcome =
|
|
61
|
+
/** The action succeeded and closed its notification. */
|
|
62
|
+
| { readonly status: 'done' }
|
|
63
|
+
/** The action failed; `message` is what the person sees. */
|
|
64
|
+
| { readonly status: 'failed'; readonly message: string }
|
|
65
|
+
/** The form did not pass its checks and was not sent; the person sees the same messages. */
|
|
66
|
+
| { readonly status: 'invalid'; readonly errors: FormErrors }
|
|
67
|
+
/** The form's `validate` replaced the action it was checking; neither ran. */
|
|
68
|
+
| { readonly status: 'replaced' }
|
|
69
|
+
/** The step stopped waiting: the notification closed otherwise, the action was replaced, or the signal ended the wait. */
|
|
70
|
+
| { readonly status: 'pending'; readonly gone: boolean };
|
|
71
|
+
|
|
72
|
+
export interface ToasterPort<Slot> {
|
|
73
|
+
/** The same object until the controller publishes again. */
|
|
74
|
+
readonly read: () => ToasterReading<Slot>;
|
|
75
|
+
/**
|
|
76
|
+
* Calls `listener` after every committed change with that commit's events and state, so a reader
|
|
77
|
+
* learns what happened and who did it together with the new state. The controller delivers the
|
|
78
|
+
* events themselves only after its state listeners.
|
|
79
|
+
*/
|
|
80
|
+
readonly subscribe: (listener: (commit: PortCommit<Slot>) => void) => () => void;
|
|
81
|
+
/** Opens the Island on the top notification, unless a person is busy with the Toaster. */
|
|
82
|
+
readonly open: () => Changed | Rejection<'disposed' | 'no-host' | 'empty' | 'busy'>;
|
|
83
|
+
/** Collapses the Island, unless it holds a draft. */
|
|
84
|
+
readonly close: () => Changed | Rejection<'disposed' | 'busy'>;
|
|
85
|
+
/** Opens the Island on the notification or moves the open one to it, unless a person is busy. */
|
|
86
|
+
readonly show: (handle: NotificationHandle) => Changed | Rejection<HandleReason | 'no-host' | 'busy'>;
|
|
87
|
+
/**
|
|
88
|
+
* Brings the notification in front of the person for a step only they may take: opens the Island
|
|
89
|
+
* on it now, or once they stop interacting (`waiting`). Never moves focus.
|
|
90
|
+
*/
|
|
91
|
+
readonly summon: (handle: NotificationHandle) => { readonly status: 'shown' | 'waiting' | 'unchanged' } | Rejection<HandleReason | 'no-host'>;
|
|
92
|
+
readonly dismiss: (handle: NotificationHandle) => Changed | Rejection<HandleReason>;
|
|
93
|
+
readonly clear: () => { readonly status: 'cleared'; readonly count: number } | Rejection<'disposed'>;
|
|
94
|
+
readonly acknowledge: () => Changed | Rejection<'disposed'>;
|
|
95
|
+
readonly cancel: (handle: NotificationHandle) => CancelResult | Rejection<HandleReason | 'no-operation'>;
|
|
96
|
+
readonly retry: (handle: NotificationHandle) => { readonly status: 'started' } | Rejection<HandleReason | 'no-operation' | 'not-retryable' | 'already-pending'>;
|
|
97
|
+
/** Writes a form field as an agent, never over what the person typed. */
|
|
98
|
+
readonly fill: (handle: NotificationHandle, name: string, value: string)
|
|
99
|
+
=> Changed | Rejection<HandleReason | 'no-form' | 'invalid-input' | 'already-pending' | 'too-long' | 'person-typed'>;
|
|
100
|
+
/**
|
|
101
|
+
* Starts the command or submits the form, and waits until it settles, its notification closes or
|
|
102
|
+
* `signal` aborts.
|
|
103
|
+
*/
|
|
104
|
+
readonly press: (handle: NotificationHandle, grant: StepGrant, signal: CancellationSignal)
|
|
105
|
+
=> Promise<PressOutcome> | Rejection<HandleReason | 'no-command' | 'already-pending' | 'stale'>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const STRICTNESS = { allow: 0, confirm: 1, deny: 2 } as const;
|
|
109
|
+
|
|
110
|
+
/** Throws a TypeError for a controller this package instance did not create. */
|
|
111
|
+
export function createToasterPort<Slot>(controller: object): ToasterPort<Slot> {
|
|
112
|
+
const k = getControllerKernel<Slot>(controller);
|
|
113
|
+
let source: RendererSnapshot<Slot> | undefined;
|
|
114
|
+
let mounted = false;
|
|
115
|
+
let reading: ToasterReading<Slot> | undefined;
|
|
116
|
+
|
|
117
|
+
const read = (): ToasterReading<Slot> => {
|
|
118
|
+
// Every change of the lease or of what `interacting` reads publishes a new renderer snapshot.
|
|
119
|
+
const next = k.rendererSnapshot;
|
|
120
|
+
const lease = k.lease !== null;
|
|
121
|
+
if (reading && next === source && lease === mounted) return reading;
|
|
122
|
+
source = next;
|
|
123
|
+
mounted = lease;
|
|
124
|
+
const forms = new Map<NotificationHandle, FormReading>();
|
|
125
|
+
for (const form of next.forms) {
|
|
126
|
+
const filled = new Set(Object.keys(form.values).filter((name) => form.values[name]!.trim() !== ''));
|
|
127
|
+
forms.set(form.handle, freeze({ filled, authors: new Map(Object.entries(form.authors)), errors: form.errors }));
|
|
128
|
+
}
|
|
129
|
+
reading = freeze({ controller: next, mounted, busy: k.interacting(), forms });
|
|
130
|
+
return reading;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const withRecord = k.withRecord;
|
|
134
|
+
|
|
135
|
+
return freeze<ToasterPort<Slot>>({
|
|
136
|
+
read,
|
|
137
|
+
subscribe: (listener) => k.subscribe(() => {
|
|
138
|
+
const commit = k.announced;
|
|
139
|
+
if (!commit) return;
|
|
140
|
+
listener({
|
|
141
|
+
events: commit.deliveries.filter((delivery): delivery is PortEvent => !('callback' in delivery)),
|
|
142
|
+
controller: commit.snapshot,
|
|
143
|
+
authors: new Map(commit.snapshot.forms.map((form) => [form.handle, new Map(Object.entries(form.authors))])),
|
|
144
|
+
closedBy: commit.closedBy,
|
|
145
|
+
});
|
|
146
|
+
}),
|
|
147
|
+
open() {
|
|
148
|
+
if (k.disposed) return reject('disposed');
|
|
149
|
+
if (k.lease === null) return reject('no-host');
|
|
150
|
+
const record = k.newest();
|
|
151
|
+
if (!record) return reject('empty');
|
|
152
|
+
if (k.island) return UNCHANGED;
|
|
153
|
+
if (k.interacting()) return reject('busy');
|
|
154
|
+
return k.mutate(() => { k.island = { reason: 'attention', current: record, source: 'agent' }; });
|
|
155
|
+
},
|
|
156
|
+
close() {
|
|
157
|
+
if (k.disposed) return reject('disposed');
|
|
158
|
+
if (!k.island) return UNCHANGED;
|
|
159
|
+
// A person's Escape collapses an Island with a draft; an agent is not that person.
|
|
160
|
+
if (k.dirty(k.island.current)) return reject('busy');
|
|
161
|
+
return k.mutate(() => { k.collapse('agent'); });
|
|
162
|
+
},
|
|
163
|
+
show: withRecord((record) => {
|
|
164
|
+
if (k.lease === null) return reject('no-host');
|
|
165
|
+
if (k.island?.current === record) return UNCHANGED;
|
|
166
|
+
if (k.interacting()) return reject('busy');
|
|
167
|
+
// Showing is navigation, as in the renderer: reaching the pending auto-open's record fulfils
|
|
168
|
+
// it, and any other pending auto-open restarts its delay.
|
|
169
|
+
return k.mutate(() => k.reach(record, 'agent'));
|
|
170
|
+
}),
|
|
171
|
+
summon: withRecord((record) => k.lease === null ? reject('no-host') : freeze({ status: k.summon(record) })),
|
|
172
|
+
dismiss: (handle) => k.dismiss(handle, 'programmatic', 'agent'),
|
|
173
|
+
clear: () => k.clear('clear', 'agent'),
|
|
174
|
+
acknowledge: () => k.acknowledgeOverflow('agent'),
|
|
175
|
+
// The current attempt's own capability: no token leaves the port.
|
|
176
|
+
cancel: withRecord((record) => record.operation ? record.operation.cancel(undefined, 'agent') : reject('no-operation')),
|
|
177
|
+
retry: withRecord((record) => {
|
|
178
|
+
if (!record.operation) return reject('no-operation');
|
|
179
|
+
const result = record.operation.retry('agent');
|
|
180
|
+
return result.status === 'started' ? freeze({ status: 'started' as const }) : reject(result.reason);
|
|
181
|
+
}),
|
|
182
|
+
fill: withRecord((record, name: string, value: string) => fillFormValue(k, record, name, value)),
|
|
183
|
+
press: withRecord((record, grant: StepGrant, signal: CancellationSignal) => press(k, record, grant, signal)),
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function press<Slot>(k: ControllerKernel<Slot>, record: RecordState<Slot>, grant: StepGrant, signal: CancellationSignal) {
|
|
188
|
+
const action = record.content.action;
|
|
189
|
+
if (!action || action.kind === 'link') return reject('no-command');
|
|
190
|
+
// The marker is read from the record's content right before the action runs: one the app made
|
|
191
|
+
// stricter after the step was approved stops it.
|
|
192
|
+
if (STRICTNESS[action.agent ?? 'confirm'] > STRICTNESS[grant]) return reject('stale');
|
|
193
|
+
if (record.action.status === 'pending') return reject('already-pending');
|
|
194
|
+
// A wait that has already ended starts nothing.
|
|
195
|
+
if (signal.aborted) return Promise.resolve<PressOutcome>(freeze({ status: 'pending', gone: false }));
|
|
196
|
+
const handle = record.handle;
|
|
197
|
+
return new Promise<PressOutcome>((resolve) => {
|
|
198
|
+
let settled = false;
|
|
199
|
+
let token: string | undefined;
|
|
200
|
+
const finish = (outcome: PressOutcome): void => {
|
|
201
|
+
if (settled) return;
|
|
202
|
+
settled = true;
|
|
203
|
+
stopState();
|
|
204
|
+
stopEvents();
|
|
205
|
+
signal.removeEventListener('abort', abort);
|
|
206
|
+
resolve(freeze(outcome));
|
|
207
|
+
};
|
|
208
|
+
const abort = (): void => { finish({ status: 'pending', gone: k.records.get(handle.id) !== record }); };
|
|
209
|
+
// Only the closing event says why the notification closed; state listeners run before it.
|
|
210
|
+
const stopEvents = k.onEvent((event) => {
|
|
211
|
+
if (event.type === 'closed' && event.handle === handle) {
|
|
212
|
+
finish(event.reason === 'action-success' ? { status: 'done' } : { status: 'pending', gone: true });
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
const stopState = k.subscribe(() => {
|
|
216
|
+
if (token === undefined || k.records.get(handle.id) !== record) return;
|
|
217
|
+
const state = record.action;
|
|
218
|
+
if (state.status === 'failed' && state.token === token) finish({ status: 'failed', message: state.message });
|
|
219
|
+
else if (state.status === 'idle' || state.token !== token) finish({ status: 'pending', gone: false });
|
|
220
|
+
});
|
|
221
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
222
|
+
// Listeners first: the command may close or replace its notification synchronously.
|
|
223
|
+
const started = invokeAction(k, record, 'agent');
|
|
224
|
+
if (started.status === 'invalid') { finish({ status: 'invalid', errors: started.errors }); return; }
|
|
225
|
+
if (started.status !== 'started') {
|
|
226
|
+
finish(started.reason === 'action-replaced' ? { status: 'replaced' } : { status: 'pending', gone: k.records.get(handle.id) !== record });
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (settled) return;
|
|
230
|
+
// This press's own attempt: a listener of `action-started` may already have begun another one.
|
|
231
|
+
token = started.token;
|
|
232
|
+
const state = record.action;
|
|
233
|
+
if (state.status === 'failed' && state.token === token) finish({ status: 'failed', message: state.message });
|
|
234
|
+
else if (state.status === 'idle' || state.token !== token) finish({ status: 'pending', gone: false });
|
|
235
|
+
else if (signal.aborted) abort();
|
|
236
|
+
});
|
|
237
|
+
}
|