@cloudlet/toast 1.0.0-rc.3 → 1.1.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.
Files changed (72) hide show
  1. package/CHANGELOG.md +84 -16
  2. package/README.md +7 -5
  3. package/dist/contracts/controller.d.ts +7 -2
  4. package/dist/contracts/controller.d.ts.map +1 -1
  5. package/dist/contracts/events.d.ts +1 -1
  6. package/dist/contracts/events.d.ts.map +1 -1
  7. package/dist/contracts/internal.d.ts +23 -0
  8. package/dist/contracts/internal.d.ts.map +1 -1
  9. package/dist/contracts/notifications.d.ts +38 -6
  10. package/dist/contracts/notifications.d.ts.map +1 -1
  11. package/dist/contracts/snapshots.d.ts +3 -1
  12. package/dist/contracts/snapshots.d.ts.map +1 -1
  13. package/dist/core/bridge.d.ts +5 -0
  14. package/dist/core/bridge.d.ts.map +1 -0
  15. package/dist/core/bridge.js +345 -0
  16. package/dist/core/bridge.js.map +1 -0
  17. package/dist/core/controller.d.ts +122 -3
  18. package/dist/core/controller.d.ts.map +1 -1
  19. package/dist/core/controller.js +400 -541
  20. package/dist/core/controller.js.map +1 -1
  21. package/dist/core/validation.d.ts.map +1 -1
  22. package/dist/core/validation.js +181 -89
  23. package/dist/core/validation.js.map +1 -1
  24. package/dist/react/announcer.d.ts.map +1 -1
  25. package/dist/react/announcer.js +29 -23
  26. package/dist/react/announcer.js.map +1 -1
  27. package/dist/react/bindings.d.ts +9 -0
  28. package/dist/react/bindings.d.ts.map +1 -1
  29. package/dist/react/bindings.js +32 -69
  30. package/dist/react/bindings.js.map +1 -1
  31. package/dist/react/card.d.ts +5 -3
  32. package/dist/react/card.d.ts.map +1 -1
  33. package/dist/react/card.js +146 -34
  34. package/dist/react/card.js.map +1 -1
  35. package/dist/react/generators.d.ts +2 -2
  36. package/dist/react/generators.js.map +1 -1
  37. package/dist/react/gestures.js.map +1 -1
  38. package/dist/react/host.d.ts.map +1 -1
  39. package/dist/react/host.js +9 -5
  40. package/dist/react/host.js.map +1 -1
  41. package/dist/react/motion.d.ts +3 -3
  42. package/dist/react/motion.js.map +1 -1
  43. package/dist/react/plan.d.ts +1 -1
  44. package/dist/react/plan.d.ts.map +1 -1
  45. package/dist/react/plan.js +1 -0
  46. package/dist/react/plan.js.map +1 -1
  47. package/dist/react/renderer.d.ts +7 -0
  48. package/dist/react/renderer.d.ts.map +1 -0
  49. package/dist/react/renderer.js +62 -0
  50. package/dist/react/renderer.js.map +1 -0
  51. package/dist/react.d.ts +7 -5
  52. package/dist/react.d.ts.map +1 -1
  53. package/dist/styles.css +1 -1
  54. package/package.json +4 -2
  55. package/src/contracts/controller.ts +7 -2
  56. package/src/contracts/events.ts +2 -1
  57. package/src/contracts/internal.ts +20 -0
  58. package/src/contracts/notifications.ts +45 -6
  59. package/src/contracts/snapshots.ts +3 -0
  60. package/src/core/bridge.ts +336 -0
  61. package/src/core/controller.ts +118 -271
  62. package/src/core/validation.ts +49 -4
  63. package/src/react/announcer.ts +9 -0
  64. package/src/react/bindings.tsx +28 -72
  65. package/src/react/card.tsx +92 -9
  66. package/src/react/generators.ts +2 -2
  67. package/src/react/gestures.ts +1 -1
  68. package/src/react/host.tsx +22 -7
  69. package/src/react/motion.ts +4 -4
  70. package/src/react/plan.ts +4 -3
  71. package/src/react/renderer.tsx +77 -0
  72. package/src/react.ts +7 -5
@@ -2,16 +2,15 @@ import type { CloudletController, ControllerOptions, FocusTarget } from '../cont
2
2
  import type { Diagnostic, EventBase, SemanticEvent } from '../contracts/events.js';
3
3
  import type { ActionAttemptToken, ControllerIdentity, Generation, HandleRejection, NotificationHandle, OperationAttemptToken, Unsubscribe } from '../contracts/identity.js';
4
4
  import type {
5
- AnnouncementAcknowledgement, BridgeRejection, BridgeResult, FocusRequest, FocusRequestToken,
6
- ControllerDependencies, HostLease, HostOptions, OperationAnnouncementPhase, PauseChange, PresentationToken, RendererBridge,
5
+ FocusRequest, FocusRequestToken, ControllerDependencies, FormErrors, HostLease, OperationAnnouncementPhase, PresentationToken,
7
6
  RendererSnapshot,
8
7
  } from '../contracts/internal.js';
9
- import type { AdmissionResult, CloseReason, NotificationContent, NotificationKind, NotificationPatch, NotificationSpec, OperationAdmissionResult, Priority } from '../contracts/notifications.js';
8
+ import type { AdmissionResult, CloseReason, FormAction, NotificationContent, NotificationKind, NotificationPatch, NotificationSpec, OperationAdmissionResult, Priority } from '../contracts/notifications.js';
10
9
  import type { AttemptStartResult, CancellationSignal, CancelResult, OperationAttempt, OperationContext, OperationHandle, OperationSnapshot, OperationSource, OperationStatus, TrackOptions } from '../contracts/operations.js';
11
10
  import type { ActionSnapshot, ControllerSnapshot, IslandReason, IslandSnapshot, PauseReason } from '../contracts/snapshots.js';
12
- import { copyContent, patchContent, validDelay, validateContent, validateOptions, validatePatch, validateSpec, validateTrackOptions } from './validation.js';
11
+ import { copyContent, patchContent, validateContent, validateOptions, validatePatch, validateSpec, validateTrackOptions } from './validation.js';
13
12
 
14
- interface OperationBinding {
13
+ export interface OperationBinding {
15
14
  readonly getSnapshot: () => OperationSnapshot;
16
15
  readonly retry: () => AttemptStartResult<unknown>;
17
16
  readonly cancel: (reason?: unknown) => CancelResult;
@@ -19,9 +18,9 @@ interface OperationBinding {
19
18
  }
20
19
 
21
20
  type EventPayload = SemanticEvent extends infer E ? E extends SemanticEvent ? Omit<E, keyof EventBase> : never : never;
22
- type Delivery = EventPayload | { readonly callback: () => void; readonly source: string; readonly handle?: NotificationHandle };
21
+ export type Delivery = EventPayload | { readonly callback: () => void; readonly source: string; readonly handle?: NotificationHandle };
23
22
 
24
- interface RecordState<Slot> {
23
+ export interface RecordState<Slot> {
25
24
  readonly handle: NotificationHandle;
26
25
  readonly dedupeKey: string | undefined;
27
26
  readonly onClose: NotificationSpec<Slot>['onClose'];
@@ -42,28 +41,36 @@ interface RecordState<Slot> {
42
41
  readonly operationAnnounced: Set<OperationAnnouncementPhase>;
43
42
  action: ActionSnapshot;
44
43
  actionAnnounced?: { readonly token: ActionAttemptToken; readonly status: 'pending' | 'failed' };
44
+ /** Values of the form action the record holds; a new action object starts from its defaults. */
45
+ form: FormState | null;
46
+ }
47
+
48
+ export interface FormState {
49
+ readonly action: FormAction;
50
+ values: Readonly<Record<string, string>>;
51
+ errors: FormErrors;
45
52
  }
46
53
 
47
54
  /** Open Island state; `null` is the collapsed stack. */
48
- interface IslandState<Slot> {
55
+ export interface IslandState<Slot> {
49
56
  readonly reason: IslandReason;
50
57
  current: RecordState<Slot>;
51
58
  }
52
59
 
53
- interface AttentionCandidate<Slot> {
60
+ export interface AttentionCandidate<Slot> {
54
61
  readonly record: RecordState<Slot>;
55
62
  due: number;
56
63
  /** Expired during user interaction or without a host; restarts the delay afterwards. */
57
64
  waiting: boolean;
58
65
  }
59
66
 
60
- const ATTENTION_DELAY = 600;
67
+ export const ATTENTION_DELAY = 600;
61
68
 
62
69
  const freeze = Object.freeze;
63
70
 
64
71
  // Weak registries authenticate capabilities without retaining disposed controllers.
65
72
  const handles = new WeakSet<object>();
66
- const bridges = new WeakMap<object, RendererBridge<unknown>>();
73
+ const kernels = new WeakMap<object, ControllerKernel<unknown>>();
67
74
  let nextController = 0;
68
75
  const EMPTY: readonly never[] = freeze([]);
69
76
  const COLLAPSED: IslandSnapshot = freeze({ open: false, reason: null, current: null });
@@ -71,20 +78,66 @@ const SERVER: ControllerSnapshot<never> = freeze({
71
78
  controller: null, revision: 0, disposed: false, notifications: EMPTY, stack: EMPTY,
72
79
  island: COLLAPSED, overflow: freeze({ count: 0, pending: false }),
73
80
  });
74
- const RENDERER_SERVER: RendererSnapshot<never> = freeze({
75
- ...SERVER, presentation: null, focusRequest: null,
81
+ export const RENDERER_SERVER: RendererSnapshot<never> = freeze({
82
+ ...SERVER, presentation: null, focusRequest: null, forms: EMPTY,
76
83
  announcements: freeze({ notifications: EMPTY, overflowCount: 0 }),
77
84
  });
78
85
  const IDLE = freeze({ status: 'idle' as const });
79
- const APPLIED = freeze({ status: 'applied' as const });
80
- const UNCHANGED = freeze({ status: 'unchanged' as const });
81
- const reject = <Reason extends string>(reason: Reason) => ({ status: 'rejected' as const, reason });
86
+ export const NO_FORM_ERRORS: FormErrors = freeze({ form: null, fields: freeze({}) });
87
+ export const APPLIED = freeze({ status: 'applied' as const });
88
+ export const UNCHANGED = freeze({ status: 'unchanged' as const });
89
+ export const reject = <Reason extends string>(reason: Reason) => ({ status: 'rejected' as const, reason });
90
+
91
+ type Rejected<Reason extends string> = { status: 'rejected'; reason: Reason };
92
+
93
+ /**
94
+ * Controller state and transactions the renderer bridge needs (core/bridge.ts). The bridge travels
95
+ * in the lazily loaded renderer chunk, so the start bundle carries only this accessor object.
96
+ */
97
+ export interface ControllerKernel<Slot> {
98
+ readonly options: ReturnType<typeof validateOptions>;
99
+ readonly clock: ControllerDependencies<CancellationSignal>['clock'];
100
+ readonly records: Map<string, RecordState<Slot>>;
101
+ readonly globalPauses: Set<PauseReason>;
102
+ readonly subscribe: CloudletController<Slot, CancellationSignal>['subscribe'];
103
+ readonly onEvent: CloudletController<Slot, CancellationSignal>['onEvent'];
104
+ readonly disposed: boolean;
105
+ readonly presented: RecordState<Slot> | null;
106
+ readonly rendererSnapshot: RendererSnapshot<Slot>;
107
+ readonly overflow: number;
108
+ lease: HostLease | null;
109
+ lastLease: HostLease | null;
110
+ hostDelay: number | undefined;
111
+ hostAutoDismiss: boolean | undefined;
112
+ island: IslandState<Slot> | null;
113
+ attention: AttentionCandidate<Slot> | null;
114
+ focusRequest: FocusRequest | null;
115
+ focused: NotificationHandle | null;
116
+ overflowAnnounced: number;
117
+ readonly token: () => string;
118
+ readonly diagnostic: (diagnostic: Diagnostic) => void;
119
+ readonly failure: (code: Diagnostic['code'], source: string, error: unknown, handle?: NotificationHandle) => void;
120
+ readonly mutate: (apply: (deliveries: Delivery[]) => void, final?: boolean) => typeof APPLIED;
121
+ readonly commit: (deliveries?: readonly Delivery[], now?: number, final?: boolean) => void;
122
+ readonly settle: () => number;
123
+ readonly assign: (record: RecordState<Slot>) => void;
124
+ readonly newest: () => RecordState<Slot> | null;
125
+ readonly formOf: (record: RecordState<Slot>) => FormState | null;
126
+ readonly handleError: (handle: NotificationHandle) => HandleRejection | 'disposed' | undefined;
127
+ readonly withRecord: <Args extends unknown[], Result>(action: (record: RecordState<Slot>, ...args: Args) => Result)
128
+ => (handle: NotificationHandle, ...args: Args) => Result | Rejected<HandleRejection | 'disposed'>;
129
+ readonly autoDismissing: (host: boolean | undefined) => boolean;
130
+ readonly setHostAutoDismiss: (value: boolean | undefined) => void;
131
+ readonly dismiss: (handle: NotificationHandle, reason: CloseReason) => typeof APPLIED | Rejected<HandleRejection | 'disposed'>;
132
+ readonly acknowledgeOverflow: () => typeof APPLIED | typeof UNCHANGED | Rejected<'disposed'>;
133
+ readonly reportRendererLoadError: (error: unknown) => void;
134
+ }
82
135
 
83
- export function getRendererBridge<Slot, Signal extends CancellationSignal>(controller: CloudletController<Slot, Signal>): RendererBridge<Slot> {
84
- const bridge = bridges.get(controller);
85
- if (!bridge) throw new TypeError('Controller was not created by this Cloudlet package instance');
86
- // The registry stores the bridge together with its controller's opaque Slot type.
87
- return bridge as RendererBridge<Slot>;
136
+ export function getControllerKernel<Slot>(controller: object): ControllerKernel<Slot> {
137
+ const kernel = kernels.get(controller);
138
+ if (!kernel) throw new TypeError('Controller was not created by this Cloudlet package instance');
139
+ // The registry stores the kernel together with its controller's opaque Slot type.
140
+ return kernel as ControllerKernel<Slot>;
88
141
  }
89
142
 
90
143
  /** The sole owner of notification state, the stack/Island, budgets, attention and host leases. */
@@ -146,8 +199,23 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
146
199
  const rule = record.content.attention ?? 'auto';
147
200
  return rule === 'open' || (rule === 'auto' && (requiresAction(record) || !!record.content.description));
148
201
  };
202
+ /** The record's form state, started from the field defaults whenever its form action object changes. */
203
+ const formOf = (record: RecordState<Slot>): FormState | null => {
204
+ const action = record.content.action;
205
+ if (action?.kind !== 'form') return record.form = null;
206
+ if (record.form?.action !== action) {
207
+ record.form = { action, errors: NO_FORM_ERRORS,
208
+ values: freeze(Object.fromEntries(action.fields.map((field) => [field.name, field.defaultValue ?? '']))) };
209
+ }
210
+ return record.form;
211
+ };
212
+ const dirty = (record: RecordState<Slot>) => {
213
+ const form = formOf(record);
214
+ return !!form && form.action.fields.some((field) => form.values[field.name] !== (field.defaultValue ?? ''));
215
+ };
216
+ // A draft in the open Island holds it like a hand on it: attention never switches it away.
149
217
  const interacting = () => globalPauses.has('hover') || globalPauses.has('focus')
150
- || [...records.values()].some((record) => record.pauses.has('gesture'));
218
+ || [...records.values()].some((record) => record.pauses.has('gesture')) || (!!island && dirty(island.current));
151
219
  const pauses = (record: RecordState<Slot>): PauseReason[] => {
152
220
  const current = record === presented;
153
221
  return [
@@ -157,6 +225,7 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
157
225
  // An Island opened by the user, or a slide that asks for action, keeps its time.
158
226
  ...(current && island && (island.reason === 'user' || requiresAction(record)) ? ['island' as const] : []),
159
227
  ...(record.action.status === 'pending' ? ['action-pending' as const] : []),
228
+ ...(dirty(record) ? ['draft' as const] : []),
160
229
  ...globalPauses, ...record.pauses,
161
230
  ];
162
231
  };
@@ -167,10 +236,6 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
167
236
  if (records.get(handle.id)?.handle !== handle) return 'stale-handle';
168
237
  return undefined;
169
238
  };
170
- const leaseError = (value: HostLease): 'disposed' | 'stale-lease' | undefined =>
171
- disposed ? 'disposed' : lease === null || value !== lease ? 'stale-lease' : undefined;
172
- const currentError = (handle: NotificationHandle): BridgeRejection | undefined =>
173
- handleError(handle) ?? (records.get(handle.id) !== presented ? 'not-current' : undefined);
174
239
 
175
240
  // Capability validation always precedes method-specific validation/mutation.
176
241
  function withRecord<Args extends unknown[], Result>(action: (record: RecordState<Slot>, ...args: Args) => Result) {
@@ -179,16 +244,6 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
179
244
  return error ? reject(error) : action(records.get(handle.id)!, ...args);
180
245
  };
181
246
  }
182
- function withCurrent<Args extends unknown[], Result>(action: (record: RecordState<Slot>, ...args: Args) => Result) {
183
- return withRecord((record, ...args: Args) => record !== presented ? reject('not-current') : action(record, ...args));
184
- }
185
- function withOperation<Args extends unknown[], Result>(action: (operation: OperationBinding, ...args: Args) => Result) {
186
- return withRecord((record, expected: OperationAttemptToken, ...args: Args) => {
187
- const operation = record.operation;
188
- return !operation ? reject('no-operation') : operation.getSnapshot().token !== expected
189
- ? reject('stale-operation-token') : action(operation, ...args);
190
- });
191
- }
192
247
 
193
248
  function diagnostic(diagnosticValue: Diagnostic): void {
194
249
  const value = freeze({ ...diagnosticValue });
@@ -284,6 +339,7 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
284
339
  handle: record.handle, kind: record.kind, content: record.content, priority: record.priority,
285
340
  occurrences: record.occurrences, location: record === presented ? 'current' as const : 'stack' as const,
286
341
  remainingMs: record.remaining, pauseReasons: freeze(pauses(record)), operation: record.operation?.getSnapshot() ?? null, action: record.action,
342
+ draft: dirty(record),
287
343
  })));
288
344
  snapshot = freeze({ controller: identity, revision, disposed, notifications,
289
345
  stack: freeze(stackOrder().map((record) => record.handle)),
@@ -293,6 +349,10 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
293
349
  rendererSnapshot = freeze({ ...snapshot,
294
350
  presentation: presented ? freeze({ handle: presented.handle, token: presented.presentation, readable: presented.readable }) : null,
295
351
  focusRequest,
352
+ forms: freeze(current.flatMap((record) => {
353
+ const form = formOf(record);
354
+ return form ? [freeze({ handle: record.handle, values: form.values, errors: form.errors })] : [];
355
+ })),
296
356
  announcements: freeze({ overflowCount: overflowAnnounced,
297
357
  notifications: freeze(current.map((record) => freeze({
298
358
  handle: record.handle, queued: record.queuedAnnounced, firstPresentation: record.firstAnnounced,
@@ -478,6 +538,7 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
478
538
  operation: null,
479
539
  operationAnnounced: new Set(),
480
540
  action: IDLE,
541
+ form: null,
481
542
  };
482
543
  record.remaining = budget(record);
483
544
  records.set(id, record);
@@ -798,241 +859,27 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
798
859
  },
799
860
  });
800
861
 
801
- function validHostOptions(value: HostOptions | undefined): boolean {
802
- if (value === undefined) return true;
803
- return value !== null && typeof value === 'object' && Object.keys(value).every((key) => key === 'attentionDelay')
804
- && (value.attentionDelay === undefined || validDelay(value.attentionDelay));
805
- }
806
- // Preserve the bridge's lease-first validation order in one entry guard.
807
- function withLease<Args extends unknown[], Result>(action: (...args: Args) => Result) {
808
- return (value: HostLease, ...args: Args) => {
809
- const error = leaseError(value);
810
- return error ? reject(error) : action(...args);
811
- };
812
- }
813
- const bridge = freeze<RendererBridge<Slot>>({
814
- renderError: options.messages?.renderError ?? 'Content unavailable',
815
- reportInvalidContainer(message, error) {
816
- if (!disposed) diagnostic({ code: 'invalid-container', source: 'Toaster.container', message, ...(error === undefined ? {} : { error }) });
817
- },
818
- attach(hostOptions) {
819
- if (disposed) return reject('disposed');
820
- if (lease !== null) {
821
- diagnostic({ code: 'second-host', source: 'attach', message: 'A renderer is already attached' });
822
- return reject('host-exists');
823
- }
824
- if (!validHostOptions(hostOptions)) return reject('invalid-input');
825
- const nextLease = token() as HostLease;
826
- mutate(() => {
827
- lease = lastLease = nextLease;
828
- hostDelay = hostOptions?.attentionDelay;
829
- if (presented) assign(presented);
830
- });
831
- return { status: 'attached', lease: nextLease };
832
- },
833
- detach(value) {
834
- if (disposed) return reject('disposed');
835
- if (lease === null && lastLease !== null && value === lastLease) return UNCHANGED;
836
- const error = leaseError(value);
837
- if (error) return reject(error);
838
- return mutate(() => {
839
- lease = null;
840
- hostDelay = undefined;
841
- setHostAutoDismiss(undefined);
842
- focusRequest = null;
843
- focused = null;
844
- globalPauses.clear();
845
- for (const record of records.values()) { record.pauses.clear(); record.readable = false; record.presentation = null; }
846
- });
847
- },
848
- getSnapshot: () => rendererSnapshot,
849
- getServerSnapshot: () => RENDERER_SERVER,
850
- subscribe: controller.subscribe,
851
- onEvent: controller.onEvent,
852
- openIsland: withLease((reason: IslandReason, handle?: NotificationHandle) => {
853
- if (reason !== 'user' && reason !== 'attention') return reject('invalid-input');
854
- let record: RecordState<Slot> | null;
855
- if (handle === undefined) record = newest();
856
- else {
857
- const error = handleError(handle);
858
- if (error) return reject(error);
859
- record = records.get(handle.id)!;
860
- }
861
- if (!record) return reject('empty');
862
- const target = record;
863
- if (island?.current === target) return UNCHANGED;
864
- // An open Island only moves its slider; the opening reason is kept.
865
- return mutate(() => {
866
- if (island) island.current = target;
867
- else island = { reason, current: target };
868
- });
869
- }),
870
- collapseIsland: withLease(() => island ? mutate(() => { island = null; }) : UNCHANGED),
871
- setAutoDismiss: withLease((value?: boolean) => {
872
- if (value !== undefined && typeof value !== 'boolean') return reject('invalid-input');
873
- if (autoDismissing(value) === autoDismissing(hostAutoDismiss)) { hostAutoDismiss = value; return UNCHANGED; }
874
- return mutate(() => setHostAutoDismiss(value));
875
- }),
876
- navigate: withLease(withRecord((record) => {
877
- if (!island) return reject('island-closed');
878
- if (island.current === record) return UNCHANGED;
879
- return mutate(() => {
880
- island!.current = record;
881
- // Navigation is interaction (DESIGN §5): a pending auto-open restarts its delay,
882
- // and reaching the initiator by hand fulfils it.
883
- if (attention?.record === record) attention = null;
884
- else if (attention) { attention.waiting = false; attention.due = clock.now() + (hostDelay ?? options.attentionDelay ?? ATTENTION_DELAY); }
885
- });
886
- })),
887
- setPause: withLease((change: PauseChange) => {
888
- if (!change || typeof change.active !== 'boolean') return reject('invalid-input');
889
- let set: Set<PauseReason>;
890
- if (change.scope === 'host') {
891
- if (!['hover', 'focus', 'document-hidden', 'window-blur'].includes(change.reason)) return reject('invalid-input');
892
- set = globalPauses;
893
- } else if (change.scope === 'notification') {
894
- const error = currentError(change.handle);
895
- if (error) return reject(error);
896
- if (!['gesture', 'content-transition'].includes(change.reason)) return reject('invalid-input');
897
- set = records.get(change.handle.id)!.pauses;
898
- } else return reject('invalid-input');
899
- if (set.has(change.reason) === change.active) return UNCHANGED;
900
- return mutate(() => {
901
- if (change.active) set.add(change.reason); else set.delete(change.reason);
902
- });
903
- }),
904
- // Informational since the stack has no slots to protect; it has no observable effect.
905
- setFocused: withLease((handle: NotificationHandle | null) => {
906
- const error = (handle === null ? undefined : currentError(handle));
907
- if (error) return reject(error);
908
- if (focused === handle) return UNCHANGED;
909
- focused = handle;
910
- return APPLIED;
911
- }),
912
- beginPresentation: withLease(withCurrent((record, previous: PresentationToken) => {
913
- if (record.presentation !== previous) return reject('stale-presentation');
914
- const presentation = token() as PresentationToken;
915
- mutate(() => { record.presentation = presentation; record.readable = false; });
916
- return { status: 'started' as const, token: presentation };
917
- })),
918
- acknowledgePresentation: withLease(withCurrent((record, presentation: PresentationToken) => {
919
- if (record.presentation !== presentation) return reject('stale-presentation');
920
- if (record.readable) return UNCHANGED;
921
- return mutate((deliveries) => {
922
- deliveries.push({ type: 'presented', handle: record.handle, firstPresentation: !record.everPresented });
923
- record.readable = record.everPresented = true;
924
- });
925
- })),
926
- acknowledgeFocus: withLease((focusToken: FocusRequestToken, outcome: 'focused' | 'unavailable') => {
927
- if (focusRequest?.token !== focusToken) return reject('stale-focus-request');
928
- if (outcome !== 'focused' && outcome !== 'unavailable') return reject('invalid-input');
929
- return mutate(() => { focusRequest = null; });
930
- }),
931
- acknowledgeOverflow: withLease(() => {
932
- return acknowledgeOverflow();
933
- }),
934
- acknowledgeAnnouncements: withLease((acknowledgements: readonly AnnouncementAcknowledgement[]) => {
935
- return acknowledgeAnnouncements(acknowledgements);
936
- }),
937
- dismiss: withLease((handle: NotificationHandle, reason: 'close-button' | 'swipe' | 'navigation') => {
938
- const error = handleError(handle);
939
- if (error) return reject(error);
940
- // Renderer close reasons are a closed protocol, never an exit callback.
941
- if (!['close-button', 'swipe', 'navigation'].includes(reason)) return reject('invalid-input');
942
- return dismiss(handle, reason);
943
- }),
944
- invokeAction: withLease(withRecord((record) => {
945
- const handle = record.handle;
946
- const action = record.content.action;
947
- if (!action || action.kind !== 'command') return reject('no-command');
948
- if (record.action.status === 'pending') return reject('already-pending');
949
- const actionToken = token() as ActionAttemptToken;
950
- const live = () => !disposed && records.get(handle.id) === record &&
951
- record.action.status === 'pending' && record.action.token === actionToken;
952
- const now = settle();
953
- record.action = freeze({ status: 'pending', token: actionToken });
954
- commit([{ type: 'action-started', handle, token: actionToken }], now);
955
- function failed(reason: unknown): void {
956
- if (!live()) return;
957
- let message = options.messages?.actionError ?? 'Action failed';
958
- if (action?.kind === 'command' && action.errorMessage) {
959
- try {
960
- const mapped = action.errorMessage(reason);
961
- if (typeof mapped !== 'string' || !mapped.trim()) throw new TypeError('Invalid action error message');
962
- message = mapped;
963
- } catch (error) {
964
- if (!disposed) failure('mapper-error', 'action.errorMessage', error, handle);
965
- }
966
- }
967
- if (!live()) return;
968
- const now = settle();
969
- record.action = freeze({ status: 'failed', token: actionToken, message });
970
- commit([{ type: 'action-failed', handle, token: actionToken, message }], now);
971
- }
972
- let result: Promise<unknown>;
973
- try { result = Promise.resolve(action.run(freeze({ handle, token: actionToken }))); }
974
- catch (error) { result = Promise.reject(error); }
975
- void result.then(() => {
976
- if (live()) dismiss(handle, 'action-success');
977
- }, failed).catch((error: unknown) => {
978
- if (!disposed) failure('callback-error', 'action-settlement', error, handle);
979
- });
980
- return { status: 'started' as const };
981
- })),
982
- retryOperation: withLease(withOperation((operation) => {
983
- const result = operation.retry();
984
- return result.status === 'started' ? { status: 'started' as const, token: result.attempt.token } : result;
985
- })),
986
- cancelOperation: withLease(withOperation((operation, reason?: unknown) => operation.cancel(reason))),
987
- reportDiagnostic: withLease((report: Diagnostic) => {
988
- if (!report || typeof report.source !== 'string' || typeof report.message !== 'string'
989
- || !['invalid-input', 'second-host', 'stale-host', 'mapper-error', 'callback-error', 'listener-error', 'cancellation-error', 'slot-error', 'formatter-error', 'invalid-container'].includes(report.code)) return reject('invalid-input');
990
- diagnostic(report);
991
- return APPLIED;
992
- }),
993
- });
994
-
995
- function acknowledgeAnnouncements(acks: readonly AnnouncementAcknowledgement[]): BridgeResult {
996
- if (!Array.isArray(acks)) return reject('invalid-input');
997
- // Stage only effective changes; no ledger mutation occurs until every
998
- // acknowledgement has passed validation. Repeated counts remain monotonic.
999
- const changes: (() => void)[] = [];
1000
- const validCount = (count: number, maximum: number) => Number.isSafeInteger(count) && count >= 0 && count <= maximum;
1001
- for (const ack of acks) {
1002
- if (!ack || typeof ack !== 'object') return reject('invalid-input');
1003
- if (ack.kind === 'overflow') {
1004
- if (!validCount(ack.count, overflow)) return reject('invalid-input');
1005
- if (ack.count > overflowAnnounced) changes.push(() => { overflowAnnounced = Math.max(overflowAnnounced, ack.count); });
1006
- continue;
1007
- }
1008
- const error = handleError(ack.handle);
1009
- if (error) return reject(error);
1010
- const record = records.get(ack.handle.id)!;
1011
- if (ack.kind === 'operation') {
1012
- const operation = record.operation?.getSnapshot();
1013
- if (!operation || operation.token !== ack.token) return reject('stale-operation-token');
1014
- if (!['started', 'fulfilled', 'rejected', 'cancelled', 'cancel-requested'].includes(ack.phase)) return reject('invalid-input');
1015
- if (ack.phase === 'cancel-requested' ? !operation.cancelRequested
1016
- : ack.phase !== 'started' && ack.phase !== operation.status) return reject('invalid-input');
1017
- if (!record.operationAnnounced.has(ack.phase)) changes.push(() => { record.operationAnnounced.add(ack.phase); });
1018
- } else if (ack.kind === 'action') {
1019
- if (record.action.status === 'idle' || record.action.token !== ack.token || record.action.status !== ack.status) return reject('invalid-input');
1020
- if (record.actionAnnounced?.token !== ack.token || record.actionAnnounced?.status !== ack.status) {
1021
- changes.push(() => { record.actionAnnounced = freeze({ token: ack.token, status: ack.status }); });
1022
- }
1023
- } else if (ack.kind === 'occurrences') {
1024
- if (!validCount(ack.count, record.occurrences)) return reject('invalid-input');
1025
- if (ack.count > record.occurrencesAnnounced) changes.push(() => { record.occurrencesAnnounced = Math.max(record.occurrencesAnnounced, ack.count); });
1026
- } else if (ack.kind === 'queued' || ack.kind === 'first-presentation') {
1027
- const key = ack.kind === 'queued' ? 'queuedAnnounced' : 'firstAnnounced';
1028
- if (!record[key]) changes.push(() => { record[key] = true; });
1029
- } else return reject('invalid-input');
1030
- }
1031
- if (!changes.length) return UNCHANGED;
1032
- return mutate(() => { for (const apply of changes) apply(); });
1033
- }
1034
-
1035
862
  publish();
1036
- bridges.set(controller, bridge as RendererBridge<unknown>);
863
+ kernels.set(controller, freeze<ControllerKernel<Slot>>({
864
+ options, clock, records, globalPauses, subscribe: controller.subscribe, onEvent: controller.onEvent,
865
+ get disposed() { return disposed; },
866
+ get presented() { return presented; },
867
+ get rendererSnapshot() { return rendererSnapshot; },
868
+ get overflow() { return overflow; },
869
+ get lease() { return lease; }, set lease(value) { lease = value; },
870
+ get lastLease() { return lastLease; }, set lastLease(value) { lastLease = value; },
871
+ get hostDelay() { return hostDelay; }, set hostDelay(value) { hostDelay = value; },
872
+ get hostAutoDismiss() { return hostAutoDismiss; }, set hostAutoDismiss(value) { hostAutoDismiss = value; },
873
+ get island() { return island; }, set island(value) { island = value; },
874
+ get attention() { return attention; }, set attention(value) { attention = value; },
875
+ get focusRequest() { return focusRequest; }, set focusRequest(value) { focusRequest = value; },
876
+ get focused() { return focused; }, set focused(value) { focused = value; },
877
+ get overflowAnnounced() { return overflowAnnounced; }, set overflowAnnounced(value) { overflowAnnounced = value; },
878
+ token, diagnostic, failure, mutate, commit, settle, assign, newest, formOf, handleError, withRecord,
879
+ autoDismissing, setHostAutoDismiss, dismiss, acknowledgeOverflow,
880
+ reportRendererLoadError(error) {
881
+ if (!disposed) diagnostic({ code: 'renderer-load-error', source: 'Toaster', message: 'Toaster renderer failed to load', error });
882
+ },
883
+ }) as ControllerKernel<unknown>);
1037
884
  return controller;
1038
885
  }
@@ -13,7 +13,10 @@ const patchKeys = [...contentKeys, 'kind', 'priority'];
13
13
  const specKeys = [...patchKeys, 'id', 'dedupeKey', 'onClose'];
14
14
  const messageKeys = [
15
15
  'operationSuccess', 'operationError', 'operationCancelled', 'cancellationRequested', 'actionError', 'renderError',
16
+ 'fieldRequired', 'fieldTooLong',
16
17
  ] as const;
18
+ const fieldKeys = ['name', 'kind', 'label', 'placeholder', 'defaultValue', 'required', 'maxLength', 'autoComplete', 'inputMode'];
19
+ const inputModes = ['text', 'email', 'numeric', 'decimal', 'tel', 'url', 'search'];
17
20
  const noIssues: readonly InputIssue[] = Object.freeze([]);
18
21
  const owns = Object.hasOwn;
19
22
  const at = (path: string, key: PropertyKey): string => path ? `${path}.${String(key)}` : String(key);
@@ -108,10 +111,43 @@ function safeHref(value: string): boolean {
108
111
  return ['http', 'https', 'mailto', 'tel'].includes(scheme);
109
112
  }
110
113
 
114
+ function formFields(value: unknown, issues: InputIssue[]): void {
115
+ if (!Array.isArray(value) || value.length < 1 || value.length > 3) {
116
+ issue(issues, 'action.fields', 'Expected an array of one to three fields');
117
+ return;
118
+ }
119
+ const names = new Set<unknown>();
120
+ value.forEach((item: unknown, index) => {
121
+ const path = `action.fields.${index}`;
122
+ const data = record(item, path, fieldKeys, issues);
123
+ if (!data) return;
124
+ fields(data, issues, path, [
125
+ ['name', 'nonempty string', true], ['kind', ['text', 'textarea'], true], ['label', 'nonempty string', true],
126
+ ['placeholder', 'string'], ['defaultValue', 'string'], ['required', 'boolean'], ['autoComplete', 'string'],
127
+ ['inputMode', inputModes],
128
+ ]);
129
+ if (names.has(data.name)) issue(issues, `${path}.name`, 'Field names must be unique');
130
+ names.add(data.name);
131
+ if (owns(data, 'maxLength') && data.maxLength !== undefined &&
132
+ (typeof data.maxLength !== 'number' || !Number.isInteger(data.maxLength) || data.maxLength < 1)) {
133
+ issue(issues, `${path}.maxLength`, 'Expected a positive integer');
134
+ } else if (typeof data.maxLength === 'number' && typeof data.defaultValue === 'string' && data.defaultValue.length > data.maxLength) {
135
+ issue(issues, `${path}.defaultValue`, 'Longer than maxLength');
136
+ }
137
+ });
138
+ }
139
+
111
140
  function action(value: unknown, issues: InputIssue[]): void {
112
- const data = record(value, 'action', ['kind', 'label', 'run', 'errorMessage', 'href', 'target', 'rel'], issues);
141
+ const data = record(value, 'action', ['kind', 'label', 'run', 'errorMessage', 'href', 'target', 'rel', 'fields', 'validate'], issues);
113
142
  if (!data) return;
114
143
  fields(data, issues, 'action', [['label', 'nonempty string', true]]);
144
+ if (data.kind === 'form') {
145
+ forbidden(data, issues, 'action', ['href', 'target', 'rel'], 'a form action');
146
+ fields(data, issues, 'action', [['run', 'function', true], ['errorMessage', 'function'], ['validate', 'function']]);
147
+ formFields(data.fields, issues);
148
+ return;
149
+ }
150
+ forbidden(data, issues, 'action', ['fields', 'validate'], `a ${data.kind === 'link' ? 'link' : 'command'} action`);
115
151
  if (data.kind === 'command') {
116
152
  forbidden(data, issues, 'action', ['href', 'target', 'rel'], 'a command action');
117
153
  fields(data, issues, 'action', [['run', 'function', true], ['errorMessage', 'function']]);
@@ -120,7 +156,7 @@ function action(value: unknown, issues: InputIssue[]): void {
120
156
  fields(data, issues, 'action', [['href', 'nonempty string', true]]);
121
157
  if (typeof data.href === 'string' && !safeHref(data.href)) issue(issues, 'action.href', 'Unsupported or unsafe URL');
122
158
  fields(data, issues, 'action', [['target', ['_self', '_blank', '_parent', '_top']], ['rel', 'string']]);
123
- } else fields(data, issues, 'action', [['kind', ['command', 'link'], true]]);
159
+ } else fields(data, issues, 'action', [['kind', ['command', 'link', 'form'], true]]);
124
160
  }
125
161
 
126
162
  function common(data: Record<string, unknown>, issues: InputIssue[], patch: boolean): void {
@@ -241,9 +277,18 @@ function copyProgress(value: Progress): Progress {
241
277
  return value.kind === 'indeterminate' ? copyFields(value, ['kind'], ['label']) : copyFields(value, ['kind', 'value'], ['label']);
242
278
  }
243
279
 
280
+ // A patch that keeps the action passes its existing copy back; keeping that identity keeps a form's draft.
281
+ const copiedActions = new WeakSet<PrimaryAction>();
282
+
244
283
  function copyAction(value: PrimaryAction): PrimaryAction {
245
- return value.kind === 'command' ? copyFields(value, ['kind', 'label', 'run'], ['errorMessage'])
246
- : copyFields(value, ['kind', 'label', 'href'], ['target', 'rel']);
284
+ if (copiedActions.has(value)) return value;
285
+ const copy = value.kind === 'command' ? copyFields(value, ['kind', 'label', 'run'], ['errorMessage'])
286
+ : value.kind === 'link' ? copyFields(value, ['kind', 'label', 'href'], ['target', 'rel'])
287
+ : copyFields({ ...value, fields: Object.freeze(value.fields.map((field) => copyFields(field, ['name', 'kind', 'label'],
288
+ ['placeholder', 'defaultValue', 'required', 'maxLength', 'autoComplete', 'inputMode']))) },
289
+ ['kind', 'fields', 'label', 'run'], ['errorMessage', 'validate']);
290
+ copiedActions.add(copy);
291
+ return copy;
247
292
  }
248
293
 
249
294
  type MutableContent<Slot> = { -readonly [Key in keyof NotificationContent<Slot>]: NotificationContent<Slot>[Key] };
@@ -32,6 +32,8 @@ export function createAnnouncer(bridge: RendererBridge<ReactNode>, lease: HostLe
32
32
  /** The record last presented, and one shown again inside the open Island (a slide back, or the next after a close). */
33
33
  let shown: NotificationHandle | null = null;
34
34
  let revisit: NotificationHandle | null = null;
35
+ /** A flush held back until the presented record is readable (see `flush`). */
36
+ let waiting = false;
35
37
  let reinsert: number | undefined;
36
38
  const view = doc.defaultView;
37
39
  const cancel = () => { view?.clearTimeout(timer); timer = undefined; };
@@ -60,6 +62,11 @@ export function createAnnouncer(bridge: RendererBridge<ReactNode>, lease: HostLe
60
62
  timer = undefined;
61
63
  if (!mounted || doc.visibilityState === 'hidden' || !polite || !assertive) return;
62
64
  const snapshot = bridge.getSnapshot();
65
+ // The presented record speaks first and the queue after it. While its pill or slide is still
66
+ // arriving (a slow first frame), sending now would say the queue alone; its `presented` event
67
+ // flushes instead.
68
+ if (snapshot.presentation && !snapshot.presentation.readable && !resumed) { waiting = true; return; }
69
+ waiting = false;
63
70
  const acks: AnnouncementAcknowledgement[] = [];
64
71
  const messages = { polite: [] as string[], assertive: [] as string[] };
65
72
  const queued = { polite: 0, assertive: 0 };
@@ -170,6 +177,8 @@ export function createAnnouncer(bridge: RendererBridge<ReactNode>, lease: HostLe
170
177
  if (event.type === 'presented') {
171
178
  if (!event.firstPresentation && shown !== null && event.handle !== shown && bridge.getSnapshot().island.open) revisit = event.handle;
172
179
  shown = event.handle;
180
+ // The window already passed while the presentation was pending: deliver right away.
181
+ if (waiting) { waiting = false; cancel(); timer = view?.setTimeout(flush, 0); return; }
173
182
  }
174
183
  // Updated includes progress, reflow and ordinary text edits, not a new semantic phase.
175
184
  if (event.type !== 'updated' && event.type !== 'diagnostic') schedule();