@cloudlet/toast 0.0.0-stage → 1.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +236 -0
- package/LICENSE +21 -0
- package/README.md +64 -2
- package/THIRD_PARTY_NOTICES.md +149 -0
- package/dist/contracts/controller.d.ts +71 -0
- package/dist/contracts/controller.d.ts.map +1 -0
- package/dist/contracts/events.d.ts +72 -0
- package/dist/contracts/events.d.ts.map +1 -0
- package/dist/contracts/identity.d.ts +32 -0
- package/dist/contracts/identity.d.ts.map +1 -0
- package/dist/contracts/internal.d.ts +188 -0
- package/dist/contracts/internal.d.ts.map +1 -0
- package/dist/contracts/notifications.d.ts +101 -0
- package/dist/contracts/notifications.d.ts.map +1 -0
- package/dist/contracts/operations.d.ts +76 -0
- package/dist/contracts/operations.d.ts.map +1 -0
- package/dist/contracts/snapshots.d.ts +48 -0
- package/dist/contracts/snapshots.d.ts.map +1 -0
- package/dist/core/controller.d.ts +7 -0
- package/dist/core/controller.d.ts.map +1 -0
- package/dist/core/controller.js +954 -0
- package/dist/core/controller.js.map +1 -0
- package/dist/core/validation.d.ts +17 -0
- package/dist/core/validation.d.ts.map +1 -0
- package/dist/core/validation.js +298 -0
- package/dist/core/validation.js.map +1 -0
- package/dist/create-cloudlet.d.ts +5 -0
- package/dist/create-cloudlet.d.ts.map +1 -0
- package/dist/create-cloudlet.js +34 -0
- package/dist/create-cloudlet.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/react/announcer.d.ts +15 -0
- package/dist/react/announcer.d.ts.map +1 -0
- package/dist/react/announcer.js +134 -0
- package/dist/react/announcer.js.map +1 -0
- package/dist/react/bindings.d.ts +8 -0
- package/dist/react/bindings.d.ts.map +1 -0
- package/dist/react/bindings.js +84 -0
- package/dist/react/bindings.js.map +1 -0
- package/dist/react/card.d.ts +58 -0
- package/dist/react/card.d.ts.map +1 -0
- package/dist/react/card.js +300 -0
- package/dist/react/card.js.map +1 -0
- package/dist/react/generators.d.ts +46 -0
- package/dist/react/generators.d.ts.map +1 -0
- package/dist/react/generators.js +115 -0
- package/dist/react/generators.js.map +1 -0
- package/dist/react/gestures.d.ts +50 -0
- package/dist/react/gestures.d.ts.map +1 -0
- package/dist/react/gestures.js +239 -0
- package/dist/react/gestures.js.map +1 -0
- package/dist/react/host.d.ts +37 -0
- package/dist/react/host.d.ts.map +1 -0
- package/dist/react/host.js +816 -0
- package/dist/react/host.js.map +1 -0
- package/dist/react/motion.d.ts +206 -0
- package/dist/react/motion.d.ts.map +1 -0
- package/dist/react/motion.js +414 -0
- package/dist/react/motion.js.map +1 -0
- package/dist/react/plan.d.ts +45 -0
- package/dist/react/plan.d.ts.map +1 -0
- package/dist/react/plan.js +58 -0
- package/dist/react/plan.js.map +1 -0
- package/dist/react/shape.d.ts +7 -0
- package/dist/react/shape.d.ts.map +1 -0
- package/dist/react/shape.js +21 -0
- package/dist/react/shape.js.map +1 -0
- package/dist/react/viewport.d.ts +15 -0
- package/dist/react/viewport.d.ts.map +1 -0
- package/dist/react/viewport.js +16 -0
- package/dist/react/viewport.js.map +1 -0
- package/dist/react.d.ts +176 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +2 -0
- package/dist/styles.css +1 -0
- package/package.json +17 -4
- package/src/contracts/controller.ts +61 -0
- package/src/contracts/events.ts +47 -0
- package/src/contracts/identity.ts +27 -0
- package/src/contracts/internal.ts +150 -0
- package/src/contracts/notifications.ts +104 -0
- package/src/contracts/operations.ts +71 -0
- package/src/contracts/snapshots.ts +59 -0
- package/src/core/controller.ts +1038 -0
- package/src/core/validation.ts +290 -0
- package/src/create-cloudlet.ts +43 -0
- package/src/index.ts +34 -0
- package/src/react/announcer.ts +189 -0
- package/src/react/bindings.tsx +100 -0
- package/src/react/card.tsx +222 -0
- package/src/react/generators.ts +274 -0
- package/src/react/gestures.ts +296 -0
- package/src/react/host.tsx +947 -0
- package/src/react/motion.ts +484 -0
- package/src/react/plan.ts +101 -0
- package/src/react/shape.ts +33 -0
- package/src/react/viewport.ts +10 -0
- package/src/react.ts +190 -0
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import type { ControllerOptions } from '../contracts/controller.js';
|
|
2
|
+
import type { InputIssue } from '../contracts/identity.js';
|
|
3
|
+
import type {
|
|
4
|
+
Description,
|
|
5
|
+
NotificationContent,
|
|
6
|
+
NotificationPatch,
|
|
7
|
+
PrimaryAction,
|
|
8
|
+
Progress,
|
|
9
|
+
} from '../contracts/notifications.js';
|
|
10
|
+
|
|
11
|
+
const contentKeys = ['title', 'description', 'icon', 'progress', 'action', 'announcementPriority', 'duration', 'attention'];
|
|
12
|
+
const patchKeys = [...contentKeys, 'kind', 'priority'];
|
|
13
|
+
const specKeys = [...patchKeys, 'id', 'dedupeKey', 'onClose'];
|
|
14
|
+
const messageKeys = [
|
|
15
|
+
'operationSuccess', 'operationError', 'operationCancelled', 'cancellationRequested', 'actionError', 'renderError',
|
|
16
|
+
] as const;
|
|
17
|
+
const noIssues: readonly InputIssue[] = Object.freeze([]);
|
|
18
|
+
const owns = Object.hasOwn;
|
|
19
|
+
const at = (path: string, key: PropertyKey): string => path ? `${path}.${String(key)}` : String(key);
|
|
20
|
+
|
|
21
|
+
function issue(issues: InputIssue[], path: string, message: string): void {
|
|
22
|
+
issues.push(Object.freeze({ path, message }));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Only Cloudlet-owned data records are inspected. Opaque slots are never passed here. */
|
|
26
|
+
function record(
|
|
27
|
+
value: unknown,
|
|
28
|
+
path: string,
|
|
29
|
+
keys: readonly string[],
|
|
30
|
+
issues: InputIssue[],
|
|
31
|
+
undefinedKeys: readonly string[] = [],
|
|
32
|
+
): Record<string, unknown> | undefined {
|
|
33
|
+
if (value === null || typeof value !== 'object' ||
|
|
34
|
+
(Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)) {
|
|
35
|
+
issue(issues, path, 'Expected a plain object');
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
let hasAccessor = false;
|
|
39
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
40
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
41
|
+
if (typeof key !== 'string' || !keys.includes(key)) {
|
|
42
|
+
issue(issues, at(path, key), 'Unknown field');
|
|
43
|
+
}
|
|
44
|
+
if (descriptor && !('value' in descriptor)) {
|
|
45
|
+
issue(issues, at(path, key), 'Expected a data property');
|
|
46
|
+
hasAccessor = true;
|
|
47
|
+
} else if (descriptor?.value === undefined &&
|
|
48
|
+
(typeof key !== 'string' || !undefinedKeys.includes(key))) {
|
|
49
|
+
issue(issues, at(path, key), 'Omit optional fields instead of passing undefined');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return hasAccessor ? undefined : value as Record<string, unknown>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
type Rule = 'string' | 'nonempty string' | 'function' | 'boolean' | readonly string[];
|
|
56
|
+
type Fields = readonly (readonly [key: string, rule: Rule, required?: boolean | 'own'])[];
|
|
57
|
+
|
|
58
|
+
/** Optional undefined is already diagnosed by record; required fields still validate. */
|
|
59
|
+
function fields(data: Record<string, unknown>, issues: InputIssue[], path: string, rules: Fields): void {
|
|
60
|
+
for (const [key, rule, required] of rules) {
|
|
61
|
+
const own = owns(data, key);
|
|
62
|
+
if (!required && (!own || data[key] === undefined)) continue;
|
|
63
|
+
const value = required === 'own' && !own ? undefined : data[key];
|
|
64
|
+
const valid = typeof rule === 'string'
|
|
65
|
+
? rule === 'nonempty string' ? typeof value === 'string' && value.trim().length > 0 : typeof value === rule
|
|
66
|
+
: typeof value === 'string' && rule.includes(value);
|
|
67
|
+
if (!valid) issue(issues, at(path, key), typeof rule === 'string' ? `Expected a ${rule}` : `Expected one of: ${rule.join(', ')}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function forbidden(data: Record<string, unknown>, issues: InputIssue[], path: string, keys: readonly string[], variant: string): void {
|
|
72
|
+
for (const key of keys) if (owns(data, key)) issue(issues, at(path, key), `Field is not allowed for ${variant}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function description(value: unknown, issues: InputIssue[]): void {
|
|
76
|
+
const data = record(value, 'description', ['kind', 'text', 'content', 'announcement'], issues, ['content']);
|
|
77
|
+
if (!data) return;
|
|
78
|
+
if (data.kind === 'text') {
|
|
79
|
+
forbidden(data, issues, 'description', ['content', 'announcement'], 'a text description');
|
|
80
|
+
fields(data, issues, 'description', [['text', 'string', 'own']]);
|
|
81
|
+
} else if (data.kind === 'rich') {
|
|
82
|
+
forbidden(data, issues, 'description', ['text'], 'a rich description');
|
|
83
|
+
if (!owns(data, 'content')) issue(issues, 'description.content', 'Required field');
|
|
84
|
+
fields(data, issues, 'description', [['announcement', 'nonempty string', 'own']]);
|
|
85
|
+
} else fields(data, issues, 'description', [['kind', ['text', 'rich'], true]]);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function progress(value: unknown, issues: InputIssue[]): void {
|
|
89
|
+
const data = record(value, 'progress', ['kind', 'value', 'label'], issues);
|
|
90
|
+
if (!data) return;
|
|
91
|
+
if (data.kind === 'determinate') {
|
|
92
|
+
if (typeof data.value !== 'number' || !Number.isFinite(data.value) || data.value < 0 || data.value > 1) {
|
|
93
|
+
issue(issues, 'progress.value', 'Expected a finite number between 0 and 1');
|
|
94
|
+
}
|
|
95
|
+
} else if (data.kind === 'indeterminate') forbidden(data, issues, 'progress', ['value'], 'indeterminate progress');
|
|
96
|
+
else fields(data, issues, 'progress', [['kind', ['indeterminate', 'determinate'], true]]);
|
|
97
|
+
fields(data, issues, 'progress', [['label', 'string']]);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function safeHref(value: string): boolean {
|
|
101
|
+
// URL parsers strip controls before interpreting schemes; rejecting them prevents scheme obfuscation.
|
|
102
|
+
if (/[\u0000-\u001f\u007f]/u.test(value)) return false;
|
|
103
|
+
const href = value.trim();
|
|
104
|
+
const colon = href.indexOf(':');
|
|
105
|
+
const boundary = href.search(/[/?#]/u);
|
|
106
|
+
if (colon === -1 || (boundary !== -1 && boundary < colon)) return true;
|
|
107
|
+
const scheme = href.slice(0, colon).toLowerCase();
|
|
108
|
+
return ['http', 'https', 'mailto', 'tel'].includes(scheme);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function action(value: unknown, issues: InputIssue[]): void {
|
|
112
|
+
const data = record(value, 'action', ['kind', 'label', 'run', 'errorMessage', 'href', 'target', 'rel'], issues);
|
|
113
|
+
if (!data) return;
|
|
114
|
+
fields(data, issues, 'action', [['label', 'nonempty string', true]]);
|
|
115
|
+
if (data.kind === 'command') {
|
|
116
|
+
forbidden(data, issues, 'action', ['href', 'target', 'rel'], 'a command action');
|
|
117
|
+
fields(data, issues, 'action', [['run', 'function', true], ['errorMessage', 'function']]);
|
|
118
|
+
} else if (data.kind === 'link') {
|
|
119
|
+
forbidden(data, issues, 'action', ['run', 'errorMessage'], 'a link action');
|
|
120
|
+
fields(data, issues, 'action', [['href', 'nonempty string', true]]);
|
|
121
|
+
if (typeof data.href === 'string' && !safeHref(data.href)) issue(issues, 'action.href', 'Unsupported or unsafe URL');
|
|
122
|
+
fields(data, issues, 'action', [['target', ['_self', '_blank', '_parent', '_top']], ['rel', 'string']]);
|
|
123
|
+
} else fields(data, issues, 'action', [['kind', ['command', 'link'], true]]);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function common(data: Record<string, unknown>, issues: InputIssue[], patch: boolean): void {
|
|
127
|
+
fields(data, issues, '', [
|
|
128
|
+
['title', 'nonempty string', !patch || owns(data, 'title')],
|
|
129
|
+
['kind', ['info', 'success', 'loading', 'warning', 'error']],
|
|
130
|
+
['priority', ['normal', 'high']], ['announcementPriority', ['polite', 'assertive', 'off']],
|
|
131
|
+
['attention', ['auto', 'open', 'stack']],
|
|
132
|
+
]);
|
|
133
|
+
for (const [key, validate] of [['description', description], ['progress', progress], ['action', action]] as const) {
|
|
134
|
+
if (owns(data, key) && data[key] !== undefined && !(patch && data[key] === null)) validate(data[key], issues);
|
|
135
|
+
}
|
|
136
|
+
if (owns(data, 'duration') && data.duration !== undefined && data.duration !== null &&
|
|
137
|
+
(typeof data.duration !== 'number' || !Number.isFinite(data.duration) || data.duration < 0)) {
|
|
138
|
+
issue(issues, 'duration', 'Expected null or a finite nonnegative duration');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function finish(issues: InputIssue[]): readonly InputIssue[] {
|
|
143
|
+
return issues.length === 0 ? noIssues : Object.freeze(issues);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function validateSpec(value: unknown): readonly InputIssue[] {
|
|
147
|
+
const issues: InputIssue[] = [];
|
|
148
|
+
const data = record(value, '', specKeys, issues);
|
|
149
|
+
if (data) {
|
|
150
|
+
common(data, issues, false);
|
|
151
|
+
fields(data, issues, '', [['id', 'nonempty string'], ['dedupeKey', 'nonempty string'], ['onClose', 'function']]);
|
|
152
|
+
}
|
|
153
|
+
return finish(issues);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function validatePatch(value: unknown): readonly InputIssue[] {
|
|
157
|
+
const issues: InputIssue[] = [];
|
|
158
|
+
const data = record(value, '', patchKeys, issues);
|
|
159
|
+
if (data) common(data, issues, true);
|
|
160
|
+
return finish(issues);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Operation content cannot set identity, scheduling priority or notification kind. */
|
|
164
|
+
export function validateContent(value: unknown, pending = false): readonly InputIssue[] {
|
|
165
|
+
const issues: InputIssue[] = [];
|
|
166
|
+
const data = record(value, '', contentKeys, issues);
|
|
167
|
+
if (data) {
|
|
168
|
+
common(data, issues, false);
|
|
169
|
+
if (pending && owns(data, 'duration')) issue(issues, 'duration', 'Pending content cannot define a duration');
|
|
170
|
+
}
|
|
171
|
+
return finish(issues);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Validate before copying or invoking user code; mapper output is validated separately. */
|
|
175
|
+
export function validateTrackOptions(value: unknown, isFactory: boolean): readonly InputIssue[] {
|
|
176
|
+
const issues: InputIssue[] = [];
|
|
177
|
+
const data = record(value, '', [
|
|
178
|
+
'id', 'priority', 'pending', 'success', 'error', 'cancelled', 'cancel', 'isCancellation', 'onClose',
|
|
179
|
+
], issues);
|
|
180
|
+
if (!data) return finish(issues);
|
|
181
|
+
fields(data, issues, '', [['id', 'nonempty string'], ['priority', ['normal', 'high']]]);
|
|
182
|
+
for (const key of ['pending', 'success', 'error', 'cancelled'] as const) {
|
|
183
|
+
if (key === 'cancelled' && !owns(data, key)) continue;
|
|
184
|
+
if (key !== 'pending' && typeof data[key] === 'function') continue;
|
|
185
|
+
for (const problem of validateContent(data[key], key === 'pending')) {
|
|
186
|
+
issue(issues, problem.path ? `${key}.${problem.path}` : key, problem.message);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
fields(data, issues, '', [['cancel', 'function'], ['isCancellation', 'function'], ['onClose', 'function']]);
|
|
190
|
+
if (isFactory && owns(data, 'cancel')) issue(issues, 'cancel', 'Factory cancellation uses its attempt signal');
|
|
191
|
+
return finish(issues);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Attention delays are finite nonnegative milliseconds. */
|
|
195
|
+
export const validDelay = (value: unknown): value is number =>
|
|
196
|
+
typeof value === 'number' && Number.isFinite(value) && value >= 0;
|
|
197
|
+
|
|
198
|
+
export function validateOptions(options: ControllerOptions | undefined): ControllerOptions {
|
|
199
|
+
if (options === undefined) return Object.freeze({ autoDismiss: true });
|
|
200
|
+
const issues: InputIssue[] = [];
|
|
201
|
+
const data = record(options, '', ['autoDismiss', 'attentionDelay', 'messages', 'onOverflow', 'onDiagnostic'], issues);
|
|
202
|
+
if (data) {
|
|
203
|
+
fields(data, issues, '', [['autoDismiss', 'boolean'], ['onOverflow', 'function'], ['onDiagnostic', 'function']]);
|
|
204
|
+
if (owns(data, 'attentionDelay') && data.attentionDelay !== undefined && typeof data.attentionDelay !== 'number') {
|
|
205
|
+
issue(issues, 'attentionDelay', 'Expected a number');
|
|
206
|
+
}
|
|
207
|
+
if (owns(data, 'messages') && data.messages !== undefined) {
|
|
208
|
+
const messages = record(data.messages, 'messages', messageKeys, issues);
|
|
209
|
+
if (messages) fields(messages, issues, 'messages', messageKeys.map((key) => [key, 'string']));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (issues.length) throw new TypeError(issues.map(({ path, message }) => `${path || 'options'}: ${message}`).join('; '));
|
|
213
|
+
if (options.attentionDelay !== undefined && !validDelay(options.attentionDelay)) {
|
|
214
|
+
throw new RangeError('attentionDelay: Expected a finite nonnegative number of milliseconds');
|
|
215
|
+
}
|
|
216
|
+
const result: { -readonly [Key in keyof ControllerOptions]: ControllerOptions[Key] } = { autoDismiss: options.autoDismiss ?? true };
|
|
217
|
+
if (options.attentionDelay !== undefined) result.attentionDelay = options.attentionDelay;
|
|
218
|
+
if (options.messages !== undefined) {
|
|
219
|
+
result.messages = copyFields(options.messages, [], messageKeys);
|
|
220
|
+
}
|
|
221
|
+
if (options.onOverflow !== undefined) result.onOverflow = options.onOverflow;
|
|
222
|
+
if (options.onDiagnostic !== undefined) result.onDiagnostic = options.onDiagnostic;
|
|
223
|
+
return Object.freeze(result);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Required fields retain undefined opaque slots; each variant has an explicit whitelist. */
|
|
227
|
+
function copyFields<Value extends object>(value: Value, required: readonly (keyof Value)[], optional: readonly (keyof Value)[] = []): Value {
|
|
228
|
+
const copy = {} as Value;
|
|
229
|
+
for (const key of [...required, ...optional]) {
|
|
230
|
+
const item = value[key];
|
|
231
|
+
if (required.includes(key) || item !== undefined) copy[key] = item;
|
|
232
|
+
}
|
|
233
|
+
return Object.freeze(copy);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function copyDescription<Slot>(value: Description<Slot>): Description<Slot> {
|
|
237
|
+
return value.kind === 'text' ? copyFields(value, ['kind', 'text']) : copyFields(value, ['kind', 'content', 'announcement']);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function copyProgress(value: Progress): Progress {
|
|
241
|
+
return value.kind === 'indeterminate' ? copyFields(value, ['kind'], ['label']) : copyFields(value, ['kind', 'value'], ['label']);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function copyAction(value: PrimaryAction): PrimaryAction {
|
|
245
|
+
return value.kind === 'command' ? copyFields(value, ['kind', 'label', 'run'], ['errorMessage'])
|
|
246
|
+
: copyFields(value, ['kind', 'label', 'href'], ['target', 'rel']);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
type MutableContent<Slot> = { -readonly [Key in keyof NotificationContent<Slot>]: NotificationContent<Slot>[Key] };
|
|
250
|
+
|
|
251
|
+
/** Call after validation. Copy only the library's structures, never the caller's opaque payloads. */
|
|
252
|
+
export function copyContent<Slot>(content: NotificationContent<Slot>): Readonly<NotificationContent<Slot>> {
|
|
253
|
+
const copy: MutableContent<Slot> = { title: content.title, announcementPriority: content.announcementPriority ?? 'polite' };
|
|
254
|
+
if (content.description !== undefined) copy.description = copyDescription(content.description);
|
|
255
|
+
if (owns(content, 'icon')) copy.icon = content.icon as Slot;
|
|
256
|
+
if (content.progress !== undefined) copy.progress = copyProgress(content.progress);
|
|
257
|
+
if (content.action !== undefined) copy.action = copyAction(content.action);
|
|
258
|
+
if (content.duration !== undefined) copy.duration = content.duration;
|
|
259
|
+
if (content.attention !== undefined) copy.attention = content.attention;
|
|
260
|
+
return Object.freeze(copy);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function equalData(left: object | undefined, right: object | undefined): boolean {
|
|
264
|
+
if (left === right) return true;
|
|
265
|
+
if (!left || !right) return false;
|
|
266
|
+
const keys = Object.keys(left);
|
|
267
|
+
return keys.length === Object.keys(right).length && keys.every((key) =>
|
|
268
|
+
owns(right, key) && Object.is((left as Record<string, unknown>)[key], (right as Record<string, unknown>)[key]));
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Kind and priority belong to the record; this helper changes only presentation content. */
|
|
272
|
+
export function patchContent<Slot>(
|
|
273
|
+
content: Readonly<NotificationContent<Slot>>,
|
|
274
|
+
patch: NotificationPatch<Slot>,
|
|
275
|
+
): Readonly<NotificationContent<Slot>> {
|
|
276
|
+
const merged: MutableContent<Slot> = { ...content };
|
|
277
|
+
for (const key of contentKeys as readonly (keyof NotificationContent<Slot>)[]) {
|
|
278
|
+
const value = patch[key];
|
|
279
|
+
if (value === null && ['description', 'icon', 'progress', 'action'].includes(key)) delete merged[key];
|
|
280
|
+
// Fields are copied between the matching keys of these validated shapes.
|
|
281
|
+
else if (value !== undefined) (merged as Record<string, unknown>)[key] = value;
|
|
282
|
+
}
|
|
283
|
+
if (merged.title === content.title && merged.announcementPriority === content.announcementPriority &&
|
|
284
|
+
merged.duration === content.duration && owns(merged, 'duration') === owns(content, 'duration') &&
|
|
285
|
+
merged.attention === content.attention &&
|
|
286
|
+
Object.is(merged.icon, content.icon) && owns(merged, 'icon') === owns(content, 'icon') &&
|
|
287
|
+
equalData(merged.description, content.description) && equalData(merged.progress, content.progress) &&
|
|
288
|
+
equalData(merged.action, content.action)) return content;
|
|
289
|
+
return copyContent(merged);
|
|
290
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { ControllerOptions } from './contracts/controller.js';
|
|
3
|
+
import type { MonotonicClock } from './contracts/internal.js';
|
|
4
|
+
import type { ReactCloudletController } from './react.js';
|
|
5
|
+
import { createCloudletCore } from './core/controller.js';
|
|
6
|
+
|
|
7
|
+
/** A lazy web adapter: constructing a controller allocates no timers or listeners. */
|
|
8
|
+
function createWebClock(): MonotonicClock {
|
|
9
|
+
return {
|
|
10
|
+
now: () => globalThis.performance.now(),
|
|
11
|
+
schedule(deadline, callback) {
|
|
12
|
+
let cancelled = false;
|
|
13
|
+
let timer: ReturnType<typeof globalThis.setTimeout>;
|
|
14
|
+
const schedule = () => {
|
|
15
|
+
const delay = Math.max(0, deadline - globalThis.performance.now());
|
|
16
|
+
// Browsers clamp longer delays to a signed 32-bit timeout. Re-arm only
|
|
17
|
+
// at that boundary so long explicit durations cannot expire early.
|
|
18
|
+
timer = globalThis.setTimeout(() => {
|
|
19
|
+
if (cancelled) return;
|
|
20
|
+
if (globalThis.performance.now() < deadline) schedule();
|
|
21
|
+
else callback();
|
|
22
|
+
}, Math.min(delay, 2_147_483_647));
|
|
23
|
+
};
|
|
24
|
+
schedule();
|
|
25
|
+
return () => {
|
|
26
|
+
if (cancelled) return;
|
|
27
|
+
cancelled = true;
|
|
28
|
+
globalThis.clearTimeout(timer);
|
|
29
|
+
};
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** DOM-free state with lazy native clock and per-attempt cancellation adapters. */
|
|
35
|
+
export function createCloudlet(options?: ControllerOptions): ReactCloudletController {
|
|
36
|
+
return createCloudletCore<ReactNode, AbortSignal>(options, {
|
|
37
|
+
clock: createWebClock(),
|
|
38
|
+
createCancellation: () => {
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
return { signal: controller.signal, abort: (reason) => controller.abort(reason) };
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export { createCloudlet } from './create-cloudlet.js';
|
|
2
|
+
export { CloudletProvider, useCloudlet, useOptionalCloudlet, Toaster } from './react.js';
|
|
3
|
+
export type * from './contracts/identity.js';
|
|
4
|
+
export type * from './contracts/notifications.js';
|
|
5
|
+
export type * from './contracts/operations.js';
|
|
6
|
+
export type * from './contracts/snapshots.js';
|
|
7
|
+
export type * from './contracts/events.js';
|
|
8
|
+
export type * from './contracts/controller.js';
|
|
9
|
+
export type {
|
|
10
|
+
ReactNotificationSpec,
|
|
11
|
+
ReactNotificationPatch,
|
|
12
|
+
ReactCloudletController,
|
|
13
|
+
ReactOperationContext,
|
|
14
|
+
ReactOperationFactory,
|
|
15
|
+
ReactTrackOptions,
|
|
16
|
+
CreateCloudlet,
|
|
17
|
+
CloudletProviderProps,
|
|
18
|
+
EdgeInsets,
|
|
19
|
+
ToasterOffsets,
|
|
20
|
+
ToasterAttention,
|
|
21
|
+
ToasterMotion,
|
|
22
|
+
CloudletSpring,
|
|
23
|
+
CloudletTimedSpring,
|
|
24
|
+
CloudletMotionConstants,
|
|
25
|
+
CloudletMotionOverrides,
|
|
26
|
+
CloudletPart,
|
|
27
|
+
CloudletLabels,
|
|
28
|
+
AnnouncementFormatters,
|
|
29
|
+
ToasterProps,
|
|
30
|
+
CloudletProviderComponent,
|
|
31
|
+
UseCloudlet,
|
|
32
|
+
UseOptionalCloudlet,
|
|
33
|
+
ToasterComponent,
|
|
34
|
+
} from './react.js';
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { AnnouncementAcknowledgement, HostLease, OperationAnnouncementPhase, RendererBridge } from '../contracts/internal.js';
|
|
3
|
+
import type { NotificationHandle } from '../contracts/identity.js';
|
|
4
|
+
import type { NotificationSnapshot } from '../contracts/snapshots.js';
|
|
5
|
+
import type { AnnouncementFormatters } from '../react.js';
|
|
6
|
+
|
|
7
|
+
type Notification = NotificationSnapshot<ReactNode>;
|
|
8
|
+
const content = ({ content: value }: Notification) => [value.title,
|
|
9
|
+
value.description?.kind === 'rich' ? value.description.announcement : value.description?.text,
|
|
10
|
+
].filter(Boolean).join('. ');
|
|
11
|
+
|
|
12
|
+
const defaults: Required<AnnouncementFormatters> = {
|
|
13
|
+
notification: content,
|
|
14
|
+
queued: count => `${count} notifications queued`,
|
|
15
|
+
occurrences: item => `${item.content.title}. ${item.occurrences} occurrences`,
|
|
16
|
+
overflow: count => `${count} missed notifications`,
|
|
17
|
+
operation: content,
|
|
18
|
+
actionError: (item, message) => `${item.content.title}. ${message}`,
|
|
19
|
+
actionPending: item => `${item.content.title}. ${item.content.action?.label}. In progress`,
|
|
20
|
+
resumed: count => `${count} current notifications`,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** One attachment, two existing live hosts, one fixed batch window. No event history. */
|
|
24
|
+
export function createAnnouncer(bridge: RendererBridge<ReactNode>, lease: HostLease, doc: Document,
|
|
25
|
+
options: () => Partial<AnnouncementFormatters> | undefined) {
|
|
26
|
+
let polite: Element | null = null;
|
|
27
|
+
let assertive: Element | null = null;
|
|
28
|
+
let timer: number | undefined;
|
|
29
|
+
let unsubscribe: (() => void) | undefined;
|
|
30
|
+
let mounted = false;
|
|
31
|
+
let resumed = false;
|
|
32
|
+
/** The record last presented, and one shown again inside the open Island (a slide back, or the next after a close). */
|
|
33
|
+
let shown: NotificationHandle | null = null;
|
|
34
|
+
let revisit: NotificationHandle | null = null;
|
|
35
|
+
let reinsert: number | undefined;
|
|
36
|
+
const view = doc.defaultView;
|
|
37
|
+
const cancel = () => { view?.clearTimeout(timer); timer = undefined; };
|
|
38
|
+
const schedule = () => {
|
|
39
|
+
if (!mounted) return;
|
|
40
|
+
const snapshot = bridge.getSnapshot();
|
|
41
|
+
if (!snapshot.notifications.length && !snapshot.overflow.pending) { cancel(); resumed = false; return; }
|
|
42
|
+
if (timer === undefined && doc.visibilityState !== 'hidden') timer = view?.setTimeout(flush, 300);
|
|
43
|
+
};
|
|
44
|
+
function format<K extends keyof AnnouncementFormatters>(key: K,
|
|
45
|
+
...args: Parameters<Required<AnnouncementFormatters>[K]>): string {
|
|
46
|
+
// The correlated tuple is preserved at all callers; the cast is local to dispatch.
|
|
47
|
+
type Formatter = (...values: typeof args) => string;
|
|
48
|
+
try {
|
|
49
|
+
const text = (options()?.[key] ?? defaults[key]) as Formatter;
|
|
50
|
+
const value = text(...args);
|
|
51
|
+
if (typeof value !== 'string' || !value.trim()) throw new TypeError('Announcement must be a nonempty string');
|
|
52
|
+
return value;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
bridge.reportDiagnostic(lease, { code: 'formatter-error', source: `Toaster.announcements.${key}`,
|
|
55
|
+
message: 'Announcement formatter failed', error });
|
|
56
|
+
return (defaults[key] as Formatter)(...args);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function flush() {
|
|
60
|
+
timer = undefined;
|
|
61
|
+
if (!mounted || doc.visibilityState === 'hidden' || !polite || !assertive) return;
|
|
62
|
+
const snapshot = bridge.getSnapshot();
|
|
63
|
+
const acks: AnnouncementAcknowledgement[] = [];
|
|
64
|
+
const messages = { polite: [] as string[], assertive: [] as string[] };
|
|
65
|
+
const queued = { polite: 0, assertive: 0 };
|
|
66
|
+
for (const item of snapshot.notifications) {
|
|
67
|
+
const ledger = snapshot.announcements.notifications.find(value => value.handle === item.handle)!;
|
|
68
|
+
const handle = item.handle;
|
|
69
|
+
const priority = item.content.announcementPriority ?? 'polite';
|
|
70
|
+
const readable = snapshot.presentation?.handle === handle && snapshot.presentation.readable;
|
|
71
|
+
const say = (text: () => string) => { if (priority !== 'off' && !resumed) messages[priority].push(text()); };
|
|
72
|
+
// Stack records behind the presented one speak only as an aggregate, like a queue.
|
|
73
|
+
if (item.location === 'stack') {
|
|
74
|
+
if (!ledger.queued) {
|
|
75
|
+
acks.push({ kind: 'queued', handle });
|
|
76
|
+
if (priority !== 'off' && !ledger.firstPresentation && !resumed) queued[priority]++;
|
|
77
|
+
}
|
|
78
|
+
// Queued payloads/progress never speak; first presentation reads the latest state.
|
|
79
|
+
if (!resumed) continue;
|
|
80
|
+
} else if (!readable && !resumed) continue;
|
|
81
|
+
|
|
82
|
+
const first = item.location === 'current' && readable && !ledger.firstPresentation;
|
|
83
|
+
if (first) acks.push({ kind: 'first-presentation', handle });
|
|
84
|
+
const operation = item.operation;
|
|
85
|
+
let operationText = false;
|
|
86
|
+
if (operation) {
|
|
87
|
+
const phase = operation.status === 'pending' ? operation.cancelRequested ? 'cancel-requested' : 'started' : operation.status;
|
|
88
|
+
const phases = ledger.operation?.token === operation.token ? ledger.operation.phases : [];
|
|
89
|
+
for (const current of new Set<OperationAnnouncementPhase>(['started', ...(operation.cancelRequested ? ['cancel-requested' as const] : []), phase])) {
|
|
90
|
+
if (!phases.includes(current)) acks.push({ kind: 'operation', handle, token: operation.token, phase: current });
|
|
91
|
+
}
|
|
92
|
+
if (!phases.includes(phase)) { say(() => format('operation', item, phase)); operationText = true; }
|
|
93
|
+
}
|
|
94
|
+
if (first && !operationText) say(() => format('notification', item));
|
|
95
|
+
// The title node is shared by every slide, so focus never moves when a slide comes back:
|
|
96
|
+
// speak the record once more so a screen reader hears where the user landed.
|
|
97
|
+
else if (revisit === handle && item.location === 'current' && !operationText && priority !== 'off' && !resumed) {
|
|
98
|
+
messages.polite.push(format('notification', item));
|
|
99
|
+
}
|
|
100
|
+
if (item.occurrences > ledger.occurrences) {
|
|
101
|
+
acks.push({ kind: 'occurrences', handle, count: item.occurrences });
|
|
102
|
+
if (!first && item.occurrences > 1) say(() => format('occurrences', item));
|
|
103
|
+
}
|
|
104
|
+
const action = item.action;
|
|
105
|
+
if (action.status !== 'idle' && (ledger.action?.token !== action.token || ledger.action.status !== action.status)) {
|
|
106
|
+
acks.push({ kind: 'action', handle, token: action.token, status: action.status });
|
|
107
|
+
say(() => action.status === 'failed' ? format('actionError', item, action.message) : format('actionPending', item));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
for (const priority of ['polite', 'assertive'] as const) {
|
|
111
|
+
if (queued[priority]) messages[priority].push(format('queued', queued[priority]));
|
|
112
|
+
}
|
|
113
|
+
if (snapshot.overflow.count > snapshot.announcements.overflowCount) {
|
|
114
|
+
acks.push({ kind: 'overflow', count: snapshot.overflow.count });
|
|
115
|
+
if (!resumed) messages.polite.push(format('overflow', snapshot.overflow.count));
|
|
116
|
+
}
|
|
117
|
+
if (resumed) {
|
|
118
|
+
for (const priority of ['polite', 'assertive'] as const) {
|
|
119
|
+
const count = snapshot.notifications.filter(item => (item.content.announcementPriority ?? 'polite') === priority).length;
|
|
120
|
+
if (count) messages[priority].push(format('resumed', count));
|
|
121
|
+
}
|
|
122
|
+
if (snapshot.overflow.pending) messages.polite.push(format('overflow', snapshot.overflow.count));
|
|
123
|
+
}
|
|
124
|
+
// A user formatter/diagnostic can reenter the controller. Never deliver its stale batch.
|
|
125
|
+
if (!mounted) return;
|
|
126
|
+
if (bridge.getSnapshot() !== snapshot) { schedule(); return; }
|
|
127
|
+
resumed = false;
|
|
128
|
+
revisit = null;
|
|
129
|
+
for (const [host, lines] of [[polite, messages.polite], [assertive, messages.assertive]] as const) {
|
|
130
|
+
if (!lines.length) continue;
|
|
131
|
+
let text = lines.join('. ');
|
|
132
|
+
// The same message again (a second failed attempt) would leave the region unchanged and silent;
|
|
133
|
+
// a trailing no-break space makes it a change without changing what is spoken.
|
|
134
|
+
if (host.textContent === text) text += '\u00a0';
|
|
135
|
+
host.replaceChildren(doc.createTextNode(text));
|
|
136
|
+
}
|
|
137
|
+
bridge.acknowledgeAnnouncements(lease, acks);
|
|
138
|
+
}
|
|
139
|
+
function visibility() {
|
|
140
|
+
cancel();
|
|
141
|
+
if (doc.visibilityState === 'hidden') {
|
|
142
|
+
polite?.replaceChildren(); assertive?.replaceChildren();
|
|
143
|
+
} else { resumed = true; schedule(); }
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
/**
|
|
147
|
+
* The announcer owns its live regions: created here, next to the host (React owns the host's
|
|
148
|
+
* children), and inserted twice. VoiceOver in Safari ignored assertive changes made while focus
|
|
149
|
+
* was in the open Island in regions inserted only once (0 of 6 runs), and spoke them after one
|
|
150
|
+
* re-insertion on the next frame (6 of 6, rc.2 gate); a zero timeout was not enough (3 of 5).
|
|
151
|
+
*/
|
|
152
|
+
mount(host: HTMLElement) {
|
|
153
|
+
mounted = true;
|
|
154
|
+
const region = (priority: 'polite' | 'assertive') => {
|
|
155
|
+
const element = doc.createElement('div');
|
|
156
|
+
element.className = 'cloudlet-announcer';
|
|
157
|
+
element.dataset.cloudletAnnouncer = priority;
|
|
158
|
+
element.setAttribute('aria-live', priority);
|
|
159
|
+
element.setAttribute('aria-atomic', 'true');
|
|
160
|
+
return element;
|
|
161
|
+
};
|
|
162
|
+
polite = region('polite');
|
|
163
|
+
assertive = region('assertive');
|
|
164
|
+
host.after(polite, assertive);
|
|
165
|
+
reinsert = view?.requestAnimationFrame?.(() => {
|
|
166
|
+
reinsert = undefined;
|
|
167
|
+
if (polite && assertive) host.after(polite, assertive);
|
|
168
|
+
});
|
|
169
|
+
unsubscribe = bridge.onEvent(event => {
|
|
170
|
+
if (event.type === 'presented') {
|
|
171
|
+
if (!event.firstPresentation && shown !== null && event.handle !== shown && bridge.getSnapshot().island.open) revisit = event.handle;
|
|
172
|
+
shown = event.handle;
|
|
173
|
+
}
|
|
174
|
+
// Updated includes progress, reflow and ordinary text edits, not a new semantic phase.
|
|
175
|
+
if (event.type !== 'updated' && event.type !== 'diagnostic') schedule();
|
|
176
|
+
});
|
|
177
|
+
doc.addEventListener('visibilitychange', visibility);
|
|
178
|
+
schedule();
|
|
179
|
+
},
|
|
180
|
+
dispose() {
|
|
181
|
+
mounted = false;
|
|
182
|
+
cancel(); unsubscribe?.();
|
|
183
|
+
doc.removeEventListener('visibilitychange', visibility);
|
|
184
|
+
if (reinsert !== undefined) view?.cancelAnimationFrame(reinsert);
|
|
185
|
+
polite?.remove(); assertive?.remove();
|
|
186
|
+
polite = assertive = null;
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createContext, useContext, useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
|
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';
|
|
6
|
+
import type { CloudletProviderProps, ReactCloudletController, ToasterProps } from '../react.js';
|
|
7
|
+
import { Host } from './host.js';
|
|
8
|
+
|
|
9
|
+
/** Undefined outside a provider; null inside one whose controller does not exist yet. */
|
|
10
|
+
const CloudletContext = createContext<ReactCloudletController | null | undefined>(undefined);
|
|
11
|
+
const subscribeMount = () => () => {};
|
|
12
|
+
const clientMounted = () => true;
|
|
13
|
+
const serverMounted = () => false;
|
|
14
|
+
|
|
15
|
+
export function CloudletProvider({ controller, children }: CloudletProviderProps): ReactElement {
|
|
16
|
+
return <CloudletContext.Provider value={controller}>{children}</CloudletContext.Provider>;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function useCloudlet(): ReactCloudletController {
|
|
20
|
+
const controller = useContext(CloudletContext);
|
|
21
|
+
if (!controller) throw new Error('useCloudlet must be used within a CloudletProvider that has a controller');
|
|
22
|
+
return controller;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The controller, or null outside a provider and while the provider's controller is null. */
|
|
26
|
+
export function useOptionalCloudlet(): ReactCloudletController | null {
|
|
27
|
+
return useContext(CloudletContext) ?? null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Attachment {
|
|
31
|
+
readonly controller: ReactCloudletController;
|
|
32
|
+
readonly lease: HostLease;
|
|
33
|
+
readonly container: Element;
|
|
34
|
+
readonly document: Document;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function Toaster(options: ToasterProps): ReactElement | null {
|
|
38
|
+
const controller = useContext(CloudletContext);
|
|
39
|
+
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);
|
|
53
|
+
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}</>;
|
|
100
|
+
}
|