@cloudlet/toast 1.0.0-rc.3 → 1.0.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 (52) hide show
  1. package/CHANGELOG.md +42 -7
  2. package/README.md +5 -4
  3. package/dist/contracts/events.d.ts +1 -1
  4. package/dist/contracts/events.d.ts.map +1 -1
  5. package/dist/core/bridge.d.ts +5 -0
  6. package/dist/core/bridge.d.ts.map +1 -0
  7. package/dist/core/bridge.js +277 -0
  8. package/dist/core/bridge.js.map +1 -0
  9. package/dist/core/controller.d.ts +113 -3
  10. package/dist/core/controller.d.ts.map +1 -1
  11. package/dist/core/controller.js +416 -583
  12. package/dist/core/controller.js.map +1 -1
  13. package/dist/react/announcer.d.ts.map +1 -1
  14. package/dist/react/announcer.js +29 -23
  15. package/dist/react/announcer.js.map +1 -1
  16. package/dist/react/bindings.d.ts +9 -0
  17. package/dist/react/bindings.d.ts.map +1 -1
  18. package/dist/react/bindings.js +32 -69
  19. package/dist/react/bindings.js.map +1 -1
  20. package/dist/react/card.d.ts +1 -1
  21. package/dist/react/card.js.map +1 -1
  22. package/dist/react/generators.d.ts +2 -2
  23. package/dist/react/generators.js.map +1 -1
  24. package/dist/react/gestures.js.map +1 -1
  25. package/dist/react/host.d.ts.map +1 -1
  26. package/dist/react/host.js +1 -1
  27. package/dist/react/host.js.map +1 -1
  28. package/dist/react/motion.d.ts +3 -3
  29. package/dist/react/motion.js.map +1 -1
  30. package/dist/react/plan.d.ts +1 -1
  31. package/dist/react/plan.d.ts.map +1 -1
  32. package/dist/react/plan.js.map +1 -1
  33. package/dist/react/renderer.d.ts +7 -0
  34. package/dist/react/renderer.d.ts.map +1 -0
  35. package/dist/react/renderer.js +62 -0
  36. package/dist/react/renderer.js.map +1 -0
  37. package/dist/react.d.ts +4 -4
  38. package/dist/react.d.ts.map +1 -1
  39. package/package.json +4 -2
  40. package/src/contracts/events.ts +2 -1
  41. package/src/core/bridge.ts +280 -0
  42. package/src/core/controller.ts +83 -268
  43. package/src/react/announcer.ts +9 -0
  44. package/src/react/bindings.tsx +28 -72
  45. package/src/react/card.tsx +3 -3
  46. package/src/react/generators.ts +2 -2
  47. package/src/react/gestures.ts +1 -1
  48. package/src/react/host.tsx +10 -4
  49. package/src/react/motion.ts +4 -4
  50. package/src/react/plan.ts +2 -2
  51. package/src/react/renderer.tsx +77 -0
  52. package/src/react.ts +4 -4
@@ -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, HostLease, OperationAnnouncementPhase, PresentationToken,
7
6
  RendererSnapshot,
8
7
  } from '../contracts/internal.js';
9
8
  import type { AdmissionResult, CloseReason, 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'];
@@ -45,25 +44,25 @@ interface RecordState<Slot> {
45
44
  }
46
45
 
47
46
  /** Open Island state; `null` is the collapsed stack. */
48
- interface IslandState<Slot> {
47
+ export interface IslandState<Slot> {
49
48
  readonly reason: IslandReason;
50
49
  current: RecordState<Slot>;
51
50
  }
52
51
 
53
- interface AttentionCandidate<Slot> {
52
+ export interface AttentionCandidate<Slot> {
54
53
  readonly record: RecordState<Slot>;
55
54
  due: number;
56
55
  /** Expired during user interaction or without a host; restarts the delay afterwards. */
57
56
  waiting: boolean;
58
57
  }
59
58
 
60
- const ATTENTION_DELAY = 600;
59
+ export const ATTENTION_DELAY = 600;
61
60
 
62
61
  const freeze = Object.freeze;
63
62
 
64
63
  // Weak registries authenticate capabilities without retaining disposed controllers.
65
64
  const handles = new WeakSet<object>();
66
- const bridges = new WeakMap<object, RendererBridge<unknown>>();
65
+ const kernels = new WeakMap<object, ControllerKernel<unknown>>();
67
66
  let nextController = 0;
68
67
  const EMPTY: readonly never[] = freeze([]);
69
68
  const COLLAPSED: IslandSnapshot = freeze({ open: false, reason: null, current: null });
@@ -71,20 +70,64 @@ const SERVER: ControllerSnapshot<never> = freeze({
71
70
  controller: null, revision: 0, disposed: false, notifications: EMPTY, stack: EMPTY,
72
71
  island: COLLAPSED, overflow: freeze({ count: 0, pending: false }),
73
72
  });
74
- const RENDERER_SERVER: RendererSnapshot<never> = freeze({
73
+ export const RENDERER_SERVER: RendererSnapshot<never> = freeze({
75
74
  ...SERVER, presentation: null, focusRequest: null,
76
75
  announcements: freeze({ notifications: EMPTY, overflowCount: 0 }),
77
76
  });
78
77
  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 });
78
+ export const APPLIED = freeze({ status: 'applied' as const });
79
+ export const UNCHANGED = freeze({ status: 'unchanged' as const });
80
+ export const reject = <Reason extends string>(reason: Reason) => ({ status: 'rejected' as const, reason });
82
81
 
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>;
82
+ type Rejected<Reason extends string> = { status: 'rejected'; reason: Reason };
83
+
84
+ /**
85
+ * Controller state and transactions the renderer bridge needs (core/bridge.ts). The bridge travels
86
+ * in the lazily loaded renderer chunk, so the start bundle carries only this accessor object.
87
+ */
88
+ export interface ControllerKernel<Slot> {
89
+ readonly options: ReturnType<typeof validateOptions>;
90
+ readonly clock: ControllerDependencies<CancellationSignal>['clock'];
91
+ readonly records: Map<string, RecordState<Slot>>;
92
+ readonly globalPauses: Set<PauseReason>;
93
+ readonly subscribe: CloudletController<Slot, CancellationSignal>['subscribe'];
94
+ readonly onEvent: CloudletController<Slot, CancellationSignal>['onEvent'];
95
+ readonly disposed: boolean;
96
+ readonly presented: RecordState<Slot> | null;
97
+ readonly rendererSnapshot: RendererSnapshot<Slot>;
98
+ readonly overflow: number;
99
+ lease: HostLease | null;
100
+ lastLease: HostLease | null;
101
+ hostDelay: number | undefined;
102
+ hostAutoDismiss: boolean | undefined;
103
+ island: IslandState<Slot> | null;
104
+ attention: AttentionCandidate<Slot> | null;
105
+ focusRequest: FocusRequest | null;
106
+ focused: NotificationHandle | null;
107
+ overflowAnnounced: number;
108
+ readonly token: () => string;
109
+ readonly diagnostic: (diagnostic: Diagnostic) => void;
110
+ readonly failure: (code: Diagnostic['code'], source: string, error: unknown, handle?: NotificationHandle) => void;
111
+ readonly mutate: (apply: (deliveries: Delivery[]) => void, final?: boolean) => typeof APPLIED;
112
+ readonly commit: (deliveries?: readonly Delivery[], now?: number, final?: boolean) => void;
113
+ readonly settle: () => number;
114
+ readonly assign: (record: RecordState<Slot>) => void;
115
+ readonly newest: () => RecordState<Slot> | null;
116
+ readonly handleError: (handle: NotificationHandle) => HandleRejection | 'disposed' | undefined;
117
+ readonly withRecord: <Args extends unknown[], Result>(action: (record: RecordState<Slot>, ...args: Args) => Result)
118
+ => (handle: NotificationHandle, ...args: Args) => Result | Rejected<HandleRejection | 'disposed'>;
119
+ readonly autoDismissing: (host: boolean | undefined) => boolean;
120
+ readonly setHostAutoDismiss: (value: boolean | undefined) => void;
121
+ readonly dismiss: (handle: NotificationHandle, reason: CloseReason) => typeof APPLIED | Rejected<HandleRejection | 'disposed'>;
122
+ readonly acknowledgeOverflow: () => typeof APPLIED | typeof UNCHANGED | Rejected<'disposed'>;
123
+ readonly reportRendererLoadError: (error: unknown) => void;
124
+ }
125
+
126
+ export function getControllerKernel<Slot>(controller: object): ControllerKernel<Slot> {
127
+ const kernel = kernels.get(controller);
128
+ if (!kernel) throw new TypeError('Controller was not created by this Cloudlet package instance');
129
+ // The registry stores the kernel together with its controller's opaque Slot type.
130
+ return kernel as ControllerKernel<Slot>;
88
131
  }
89
132
 
90
133
  /** The sole owner of notification state, the stack/Island, budgets, attention and host leases. */
@@ -167,10 +210,6 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
167
210
  if (records.get(handle.id)?.handle !== handle) return 'stale-handle';
168
211
  return undefined;
169
212
  };
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
213
 
175
214
  // Capability validation always precedes method-specific validation/mutation.
176
215
  function withRecord<Args extends unknown[], Result>(action: (record: RecordState<Slot>, ...args: Args) => Result) {
@@ -179,16 +218,6 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
179
218
  return error ? reject(error) : action(records.get(handle.id)!, ...args);
180
219
  };
181
220
  }
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
221
 
193
222
  function diagnostic(diagnosticValue: Diagnostic): void {
194
223
  const value = freeze({ ...diagnosticValue });
@@ -798,241 +827,27 @@ export function createCloudletCore<Slot = never, Signal extends CancellationSign
798
827
  },
799
828
  });
800
829
 
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
830
  publish();
1036
- bridges.set(controller, bridge as RendererBridge<unknown>);
831
+ kernels.set(controller, freeze<ControllerKernel<Slot>>({
832
+ options, clock, records, globalPauses, subscribe: controller.subscribe, onEvent: controller.onEvent,
833
+ get disposed() { return disposed; },
834
+ get presented() { return presented; },
835
+ get rendererSnapshot() { return rendererSnapshot; },
836
+ get overflow() { return overflow; },
837
+ get lease() { return lease; }, set lease(value) { lease = value; },
838
+ get lastLease() { return lastLease; }, set lastLease(value) { lastLease = value; },
839
+ get hostDelay() { return hostDelay; }, set hostDelay(value) { hostDelay = value; },
840
+ get hostAutoDismiss() { return hostAutoDismiss; }, set hostAutoDismiss(value) { hostAutoDismiss = value; },
841
+ get island() { return island; }, set island(value) { island = value; },
842
+ get attention() { return attention; }, set attention(value) { attention = value; },
843
+ get focusRequest() { return focusRequest; }, set focusRequest(value) { focusRequest = value; },
844
+ get focused() { return focused; }, set focused(value) { focused = value; },
845
+ get overflowAnnounced() { return overflowAnnounced; }, set overflowAnnounced(value) { overflowAnnounced = value; },
846
+ token, diagnostic, failure, mutate, commit, settle, assign, newest, handleError, withRecord,
847
+ autoDismissing, setHostAutoDismiss, dismiss, acknowledgeOverflow,
848
+ reportRendererLoadError(error) {
849
+ if (!disposed) diagnostic({ code: 'renderer-load-error', source: 'Toaster', message: 'Toaster renderer failed to load', error });
850
+ },
851
+ }) as ControllerKernel<unknown>);
1037
852
  return controller;
1038
853
  }
@@ -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();
@@ -1,16 +1,14 @@
1
- import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react';
1
+ import { createContext, useContext, useEffect, useState } from 'react';
2
2
  import type { ReactElement } from 'react';
3
- import { createPortal } from 'react-dom';
4
- import { getRendererBridge } from '../core/controller.js';
5
- import type { HostLease } from '../contracts/internal.js';
3
+ import { getControllerKernel } from '../core/controller.js';
6
4
  import type { CloudletProviderProps, ReactCloudletController, ToasterProps } from '../react.js';
7
- import { Host } from './host.js';
5
+
6
+ type Renderer = typeof import('./renderer.js');
8
7
 
9
8
  /** Undefined outside a provider; null inside one whose controller does not exist yet. */
10
9
  const CloudletContext = createContext<ReactCloudletController | null | undefined>(undefined);
11
- const subscribeMount = () => () => {};
12
- const clientMounted = () => true;
13
- const serverMounted = () => false;
10
+ let renderer: Renderer | undefined;
11
+ let loading: Promise<Renderer> | undefined;
14
12
 
15
13
  export function CloudletProvider({ controller, children }: CloudletProviderProps): ReactElement {
16
14
  return <CloudletContext.Provider value={controller}>{children}</CloudletContext.Provider>;
@@ -27,74 +25,32 @@ export function useOptionalCloudlet(): ReactCloudletController | null {
27
25
  return useContext(CloudletContext) ?? null;
28
26
  }
29
27
 
30
- interface Attachment {
31
- readonly controller: ReactCloudletController;
32
- readonly lease: HostLease;
33
- readonly container: Element;
34
- readonly document: Document;
28
+ /** Fetches the renderer chunk once for every Toaster; after a failure the next attempt fetches again. */
29
+ export function loadRenderer(): Promise<Renderer> {
30
+ loading ??= import('./renderer.js').then((module) => (renderer = module), (error: unknown) => {
31
+ loading = undefined;
32
+ throw error;
33
+ });
34
+ return loading;
35
35
  }
36
36
 
37
+ /**
38
+ * The renderer stays out of the start bundle: the chunk loads after mount, and
39
+ * notifications shown meanwhile wait in the controller. On the server and during
40
+ * hydration this renders nothing, exactly like the attached renderer does.
41
+ */
37
42
  export function Toaster(options: ToasterProps): ReactElement | null {
38
43
  const controller = useContext(CloudletContext);
39
44
  if (controller === undefined) throw new Error('Toaster must be used within a CloudletProvider');
40
- // A provider without a controller yet (server, first client render) renders nothing.
41
- return controller ? <AttachedToaster controller={controller} options={options} /> : null;
42
- }
43
-
44
- function AttachedToaster({ controller, options }: { controller: ReactCloudletController; options: ToasterProps }): ReactElement | null {
45
- // React supplies the server value during hydration, then the client value.
46
- // The inert marker can therefore identify the owner document without a store
47
- // or effect whose only purpose is an extra mounting render.
48
- const mounted = useSyncExternalStore(subscribeMount, clientMounted, serverMounted);
49
- const bridge = getRendererBridge(controller);
50
- const snapshot = useSyncExternalStore(bridge.subscribe, bridge.getSnapshot, bridge.getServerSnapshot);
51
- const marker = useRef<HTMLTemplateElement>(null);
52
- const [attachment, setAttachment] = useState<Attachment | null>(null);
45
+ const [loaded, setLoaded] = useState(renderer);
53
46
  useEffect(() => {
54
- if (!mounted || !marker.current) return;
55
- const ownerDocument = marker.current.ownerDocument;
56
- let container: Element;
57
- try {
58
- const requested = typeof options.container === 'function' ? options.container() : options.container;
59
- const candidate = requested ?? ownerDocument.body;
60
- // nodeType/ownerDocument also work when the mounting React root is in another realm.
61
- if (!candidate || candidate.nodeType !== 1 || candidate.ownerDocument !== ownerDocument
62
- || candidate.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !candidate.isConnected
63
- || candidate.getRootNode().nodeType === 11) {
64
- bridge.reportInvalidContainer('Toaster container must be a connected HTML Element in the mounting document, outside Shadow DOM');
65
- return;
66
- }
67
- container = candidate;
68
- } catch (error) {
69
- bridge.reportInvalidContainer('Toaster container resolver failed', error);
70
- return;
71
- }
72
- const delay = options.attention?.delay;
73
- let attached = bridge.attach(delay === undefined ? undefined : { attentionDelay: delay });
74
- // An invalid delay must not suppress the host: fall back to the controller default and report it.
75
- const invalidDelay = attached.status === 'rejected' && attached.reason === 'invalid-input';
76
- if (invalidDelay) attached = bridge.attach();
77
- if (attached.status !== 'attached') return;
78
- if (invalidDelay) bridge.reportDiagnostic(attached.lease, { code: 'invalid-input', source: 'Toaster.attention',
79
- message: 'attention.delay must be a finite nonnegative number of milliseconds' });
80
- const current = { controller, lease: attached.lease, container, document: ownerDocument };
81
- applyAutoDismiss(current.lease, false);
82
- setAttachment(current);
83
- return () => { bridge.detach(current.lease); };
84
- // Container and attention delay are fixed for this attachment; changing them requires remount.
85
- }, [controller, mounted]);
86
- // Applied before the first presentation, then whenever the prop changes (which reports an invalid value once).
87
- function applyAutoDismiss(lease: HostLease, report: boolean) {
88
- const value = options.autoDismiss;
89
- const valid = value === undefined || typeof value === 'boolean';
90
- bridge.setAutoDismiss(lease, valid ? value : undefined);
91
- if (!valid && report) bridge.reportDiagnostic(lease, { code: 'invalid-input', source: 'Toaster.autoDismiss',
92
- message: 'autoDismiss must be a boolean' });
93
- }
94
- useEffect(() => { if (attachment) applyAutoDismiss(attachment.lease, true); }, [attachment, options.autoDismiss]);
95
-
96
- if (!mounted) return null;
97
- return <><template ref={marker} />{attachment?.controller === controller && !snapshot.disposed
98
- ? createPortal(<Host key={attachment.lease} bridge={bridge} lease={attachment.lease} snapshot={snapshot}
99
- options={options} document={attachment.document} />, attachment.container) : null}</>;
47
+ if (loaded) return;
48
+ let live = true;
49
+ loadRenderer().then((module) => { if (live) setLoaded(module); }, (error: unknown) => {
50
+ if (live && controller) getControllerKernel(controller).reportRendererLoadError(error);
51
+ });
52
+ return () => { live = false; };
53
+ }, [loaded, controller]);
54
+ // A provider without a controller yet (server, first client render) renders nothing.
55
+ return controller && loaded ? <loaded.AttachedToaster controller={controller} options={options} /> : null;
100
56
  }
@@ -84,7 +84,7 @@ export function partClasses(classNames: ToasterProps['classNames']): PartClass {
84
84
  };
85
85
  }
86
86
 
87
- /** 16 px stroke glyphs drawn in the status colour (DESIGN §8). */
87
+ /** 16 px stroke glyphs drawn in the status colour. */
88
88
  const glyphs: Record<Exclude<NotificationKind, 'loading'>, string> = {
89
89
  success: 'M4.5 8.5 7 11l4.5-5.5',
90
90
  error: 'm5.5 5.5 5 5m0-5-5 5',
@@ -153,7 +153,7 @@ type Operation = NotificationSnapshot<ReactNode>['operation'];
153
153
  const retryable = (operation: Operation): operation is NonNullable<Operation> => !!operation?.canRetry && operation.status !== 'fulfilled';
154
154
 
155
155
  /**
156
- * The neighbour shown only while a finger drags the Island content (DESIGN §3, §9):
156
+ * The neighbour shown only while a finger drags the Island content:
157
157
  * the same layout as a live slide, but every control is a lookalike without
158
158
  * handlers, ids, links or tab stops. The caller puts it in an `inert` container.
159
159
  */
@@ -162,7 +162,7 @@ export function SlidePreview({ notification, labels, part }: { notification: Not
162
162
  const action = part('action', 'cloudlet-action');
163
163
  const lookalike = (children: ReactNode, primary = false) =>
164
164
  <button type="button" tabIndex={-1} className={primary ? `${action} cloudlet-primary` : action}>{children}</button>;
165
- // Only the body slides (DESIGN §7, task 17): the preview shows the neighbour's body under the live heading.
165
+ // Only the body slides: the preview shows the neighbour's body under the live heading.
166
166
  return <div className="cloudlet-slide" data-kind={kind}>
167
167
  <div className={part('body', 'cloudlet-body')} data-kind={kind}>
168
168
  {content.description && <div className={part('description', 'cloudlet-description')}>
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Numeric animation generators for the shell sampler (motion.ts), ported from Motion 14.3.0
3
- * so that every frame matches what the owner accepted on the laboratory (D47):
3
+ * so that every frame matches what was tuned on the laboratory:
4
4
  *
5
5
  * - `spring` is the numeric part of motion-dom/dist/es/animation/generators/spring.mjs
6
6
  * (physics-defined and duration/bounce-defined springs, `findSpring`, analytical velocity,
@@ -8,7 +8,7 @@
8
8
  * - `tween` is the two-keyframe fast path of motion-dom's `keyframes` generator for numbers,
9
9
  * with `easeOut` = `cubicBezier(0, 0, 0.58, 1)` from motion-utils 14.1.1.
10
10
  *
11
- * Motion is Copyright (c) 2024 Motion B.V., MIT (packages/cloudlet/THIRD_PARTY_NOTICES.md).
11
+ * Motion is Copyright (c) 2024 Motion B.V., MIT (packages/toast/THIRD_PARTY_NOTICES.md).
12
12
  * Colour/string mixing, keyframe arrays and the rest of Motion are not needed here: Cloudlet
13
13
  * animates numbers only. tests/unit/generators-reference.test.ts samples both implementations
14
14
  * every millisecond against the installed Motion 14.3.0 (|Δ| < 1e-9, same `done` frame).
@@ -255,7 +255,7 @@ export function createSwipe(root: HTMLElement, options: SwipeOptions) {
255
255
  stream.time = time;
256
256
  root.dataset.dragging = 'x';
257
257
  stream.session.move(stream.offset);
258
- // A trackpad swipe commits as soon as its release would (task 17): macOS momentum keeps
258
+ // A trackpad swipe commits as soon as its release would: macOS momentum keeps
259
259
  // sending wheel events for a second or more, which otherwise holds the preview in place.
260
260
  if (decideRelease(stream.offset, stream.velocity, root.clientWidth || 0, { negative: true, positive: true })) {
261
261
  const session = stream.session;