@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.
- package/CHANGELOG.md +84 -16
- package/README.md +7 -5
- package/dist/contracts/controller.d.ts +7 -2
- package/dist/contracts/controller.d.ts.map +1 -1
- package/dist/contracts/events.d.ts +1 -1
- package/dist/contracts/events.d.ts.map +1 -1
- package/dist/contracts/internal.d.ts +23 -0
- package/dist/contracts/internal.d.ts.map +1 -1
- package/dist/contracts/notifications.d.ts +38 -6
- package/dist/contracts/notifications.d.ts.map +1 -1
- package/dist/contracts/snapshots.d.ts +3 -1
- package/dist/contracts/snapshots.d.ts.map +1 -1
- package/dist/core/bridge.d.ts +5 -0
- package/dist/core/bridge.d.ts.map +1 -0
- package/dist/core/bridge.js +345 -0
- package/dist/core/bridge.js.map +1 -0
- package/dist/core/controller.d.ts +122 -3
- package/dist/core/controller.d.ts.map +1 -1
- package/dist/core/controller.js +400 -541
- package/dist/core/controller.js.map +1 -1
- package/dist/core/validation.d.ts.map +1 -1
- package/dist/core/validation.js +181 -89
- package/dist/core/validation.js.map +1 -1
- package/dist/react/announcer.d.ts.map +1 -1
- package/dist/react/announcer.js +29 -23
- package/dist/react/announcer.js.map +1 -1
- package/dist/react/bindings.d.ts +9 -0
- package/dist/react/bindings.d.ts.map +1 -1
- package/dist/react/bindings.js +32 -69
- package/dist/react/bindings.js.map +1 -1
- package/dist/react/card.d.ts +5 -3
- package/dist/react/card.d.ts.map +1 -1
- package/dist/react/card.js +146 -34
- package/dist/react/card.js.map +1 -1
- package/dist/react/generators.d.ts +2 -2
- package/dist/react/generators.js.map +1 -1
- package/dist/react/gestures.js.map +1 -1
- package/dist/react/host.d.ts.map +1 -1
- package/dist/react/host.js +9 -5
- package/dist/react/host.js.map +1 -1
- package/dist/react/motion.d.ts +3 -3
- package/dist/react/motion.js.map +1 -1
- package/dist/react/plan.d.ts +1 -1
- package/dist/react/plan.d.ts.map +1 -1
- package/dist/react/plan.js +1 -0
- package/dist/react/plan.js.map +1 -1
- package/dist/react/renderer.d.ts +7 -0
- package/dist/react/renderer.d.ts.map +1 -0
- package/dist/react/renderer.js +62 -0
- package/dist/react/renderer.js.map +1 -0
- package/dist/react.d.ts +7 -5
- package/dist/react.d.ts.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +4 -2
- package/src/contracts/controller.ts +7 -2
- package/src/contracts/events.ts +2 -1
- package/src/contracts/internal.ts +20 -0
- package/src/contracts/notifications.ts +45 -6
- package/src/contracts/snapshots.ts +3 -0
- package/src/core/bridge.ts +336 -0
- package/src/core/controller.ts +118 -271
- package/src/core/validation.ts +49 -4
- package/src/react/announcer.ts +9 -0
- package/src/react/bindings.tsx +28 -72
- package/src/react/card.tsx +92 -9
- package/src/react/generators.ts +2 -2
- package/src/react/gestures.ts +1 -1
- package/src/react/host.tsx +22 -7
- package/src/react/motion.ts +4 -4
- package/src/react/plan.ts +4 -3
- package/src/react/renderer.tsx +77 -0
- package/src/react.ts +7 -5
package/src/react/bindings.tsx
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
import { createContext, useContext, useEffect,
|
|
1
|
+
import { createContext, useContext, useEffect, useState } from 'react';
|
|
2
2
|
import type { ReactElement } from 'react';
|
|
3
|
-
import {
|
|
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
|
-
|
|
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
|
-
|
|
12
|
-
|
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
-
|
|
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 (
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
}
|
package/src/react/card.tsx
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Component, Suspense, useEffect, useId, useRef, useState } from 'react';
|
|
2
|
-
import type { ComponentPropsWithRef, ReactNode } from 'react';
|
|
3
|
-
import type { HostLease, RendererBridge } from '../contracts/internal.js';
|
|
2
|
+
import type { ComponentPropsWithRef, KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';
|
|
3
|
+
import type { FormDraft, HostLease, RendererBridge } from '../contracts/internal.js';
|
|
4
4
|
import type { NotificationHandle } from '../contracts/identity.js';
|
|
5
|
-
import type { NotificationKind } from '../contracts/notifications.js';
|
|
5
|
+
import type { FormAction, FormField, NotificationKind } from '../contracts/notifications.js';
|
|
6
6
|
import type { NotificationSnapshot } from '../contracts/snapshots.js';
|
|
7
7
|
import type { CloudletLabels, CloudletPart, ToasterProps } from '../react.js';
|
|
8
8
|
|
|
@@ -15,6 +15,7 @@ export const defaultLabels: CloudletLabels = {
|
|
|
15
15
|
...(missed > 0 ? [`${missed} missed`] : [])].join(', '),
|
|
16
16
|
page: (index, total) => `${index} of ${total}`,
|
|
17
17
|
overflowCount: count => `${count} missed notifications`,
|
|
18
|
+
draft: 'Draft',
|
|
18
19
|
};
|
|
19
20
|
|
|
20
21
|
interface SlotProps {
|
|
@@ -84,7 +85,7 @@ export function partClasses(classNames: ToasterProps['classNames']): PartClass {
|
|
|
84
85
|
};
|
|
85
86
|
}
|
|
86
87
|
|
|
87
|
-
/** 16 px stroke glyphs drawn in the status colour
|
|
88
|
+
/** 16 px stroke glyphs drawn in the status colour. */
|
|
88
89
|
const glyphs: Record<Exclude<NotificationKind, 'loading'>, string> = {
|
|
89
90
|
success: 'M4.5 8.5 7 11l4.5-5.5',
|
|
90
91
|
error: 'm5.5 5.5 5 5m0-5-5 5',
|
|
@@ -153,7 +154,7 @@ type Operation = NotificationSnapshot<ReactNode>['operation'];
|
|
|
153
154
|
const retryable = (operation: Operation): operation is NonNullable<Operation> => !!operation?.canRetry && operation.status !== 'fulfilled';
|
|
154
155
|
|
|
155
156
|
/**
|
|
156
|
-
* The neighbour shown only while a finger drags the Island content
|
|
157
|
+
* The neighbour shown only while a finger drags the Island content:
|
|
157
158
|
* the same layout as a live slide, but every control is a lookalike without
|
|
158
159
|
* handlers, ids, links or tab stops. The caller puts it in an `inert` container.
|
|
159
160
|
*/
|
|
@@ -162,7 +163,7 @@ export function SlidePreview({ notification, labels, part }: { notification: Not
|
|
|
162
163
|
const action = part('action', 'cloudlet-action');
|
|
163
164
|
const lookalike = (children: ReactNode, primary = false) =>
|
|
164
165
|
<button type="button" tabIndex={-1} className={primary ? `${action} cloudlet-primary` : action}>{children}</button>;
|
|
165
|
-
// Only the body slides
|
|
166
|
+
// Only the body slides: the preview shows the neighbour's body under the live heading.
|
|
166
167
|
return <div className="cloudlet-slide" data-kind={kind}>
|
|
167
168
|
<div className={part('body', 'cloudlet-body')} data-kind={kind}>
|
|
168
169
|
{content.description && <div className={part('description', 'cloudlet-description')}>
|
|
@@ -180,9 +181,9 @@ export function SlidePreview({ notification, labels, part }: { notification: Not
|
|
|
180
181
|
}
|
|
181
182
|
|
|
182
183
|
/** Island slide body: description, progress, actions and the action error. */
|
|
183
|
-
export function Body({ notification, bridge, lease, labels, navigate, slot, part }: {
|
|
184
|
-
notification: NotificationSnapshot<ReactNode>; bridge: RendererBridge<ReactNode>; lease: HostLease;
|
|
185
|
-
labels: CloudletLabels; navigate: (handle: NotificationHandle) => void; slot: (value: ReactNode) => ReactNode; part: PartClass;
|
|
184
|
+
export function Body({ notification, form, bridge, lease, labels, navigate, slot, part, titleId }: {
|
|
185
|
+
notification: NotificationSnapshot<ReactNode>; form: FormDraft | undefined; bridge: RendererBridge<ReactNode>; lease: HostLease;
|
|
186
|
+
labels: CloudletLabels; navigate: (handle: NotificationHandle) => void; slot: (value: ReactNode) => ReactNode; part: PartClass; titleId: string;
|
|
186
187
|
}) {
|
|
187
188
|
const { handle, content, operation, action, kind } = notification;
|
|
188
189
|
// The primary action is tinted with the status; retry and cancel stay neutral.
|
|
@@ -199,6 +200,8 @@ export function Body({ notification, bridge, lease, labels, navigate, slot, part
|
|
|
199
200
|
{content.description.kind === 'text' && <p>{content.description.text}</p>}
|
|
200
201
|
{content.description.kind === 'rich' && slot(content.description.content)}
|
|
201
202
|
</div>}
|
|
203
|
+
{command?.kind === 'form' && form && <Form key={formKey(command)} action={command} draft={form} notification={notification}
|
|
204
|
+
bridge={bridge} lease={lease} part={part} titleId={titleId} actionErrorId={`${id}-action-error`} />}
|
|
202
205
|
<div className={part('actions', 'cloudlet-actions')}>
|
|
203
206
|
{command?.kind === 'command' && control('action', command.label, () => {
|
|
204
207
|
if (action.status !== 'pending') bridge.invokeAction(lease, handle);
|
|
@@ -217,6 +220,86 @@ export function Body({ notification, bridge, lease, labels, navigate, slot, part
|
|
|
217
220
|
</div>;
|
|
218
221
|
}
|
|
219
222
|
|
|
223
|
+
// A new form action object starts a new draft in the controller, so its fields remount with the new defaults.
|
|
224
|
+
const formKeys = new WeakMap<FormAction, number>();
|
|
225
|
+
let nextFormKey = 0;
|
|
226
|
+
function formKey(action: FormAction): number {
|
|
227
|
+
let key = formKeys.get(action);
|
|
228
|
+
if (key === undefined) formKeys.set(action, key = ++nextFormKey);
|
|
229
|
+
return key;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const TEXTAREA_ROWS = [3, 6] as const;
|
|
233
|
+
|
|
234
|
+
/** Rows instead of a height: a strict CSP forbids style attributes, and rows grow with the text. */
|
|
235
|
+
function fitRows(element: HTMLTextAreaElement): void {
|
|
236
|
+
element.rows = TEXTAREA_ROWS[0];
|
|
237
|
+
while (element.scrollHeight > element.clientHeight && element.rows < TEXTAREA_ROWS[1]) element.rows += 1;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Look A: each field is a filled pill; the round submit button sits beside the last one. The fields
|
|
242
|
+
* are uncontrolled: their text lives in the controller's draft and seeds them on mount, so typing
|
|
243
|
+
* never waits for a snapshot round trip.
|
|
244
|
+
*/
|
|
245
|
+
function Form({ action, draft, notification, bridge, lease, part, titleId, actionErrorId }: {
|
|
246
|
+
action: FormAction; draft: FormDraft; notification: NotificationSnapshot<ReactNode>; bridge: RendererBridge<ReactNode>;
|
|
247
|
+
lease: HostLease; part: PartClass; titleId: string; actionErrorId: string;
|
|
248
|
+
}) {
|
|
249
|
+
const id = useId();
|
|
250
|
+
const fields = useRef(new Map<string, HTMLInputElement | HTMLTextAreaElement>());
|
|
251
|
+
const pending = notification.action.status === 'pending';
|
|
252
|
+
const failed = notification.action.status === 'failed';
|
|
253
|
+
const formError = draft.errors.form;
|
|
254
|
+
const submit = () => {
|
|
255
|
+
if (pending) return;
|
|
256
|
+
const result = bridge.invokeAction(lease, notification.handle);
|
|
257
|
+
if (result.status !== 'invalid') return;
|
|
258
|
+
const first = action.fields.find(field => result.errors.fields[field.name] !== undefined);
|
|
259
|
+
if (first) fields.current.get(first.name)?.focus();
|
|
260
|
+
};
|
|
261
|
+
const field = (field: FormField, index: number, last: boolean) => {
|
|
262
|
+
const fieldId = `${id}-${index}`;
|
|
263
|
+
const error = draft.errors.fields[field.name];
|
|
264
|
+
const props = {
|
|
265
|
+
id: fieldId, name: field.name, className: part('field', 'cloudlet-field'), defaultValue: draft.values[field.name] ?? '',
|
|
266
|
+
placeholder: field.placeholder ?? field.label, required: field.required, maxLength: field.maxLength,
|
|
267
|
+
autoComplete: field.autoComplete, inputMode: field.inputMode, readOnly: pending,
|
|
268
|
+
'aria-invalid': error === undefined ? undefined : true, 'aria-describedby': error === undefined ? undefined : `${fieldId}-error`,
|
|
269
|
+
};
|
|
270
|
+
const change = (element: HTMLInputElement | HTMLTextAreaElement) => bridge.setFormValue(lease, notification.handle, field.name, element.value);
|
|
271
|
+
return <div key={field.name} className="cloudlet-form-row">
|
|
272
|
+
<label htmlFor={fieldId} className="cloudlet-live">{field.label}</label>
|
|
273
|
+
{field.kind === 'text'
|
|
274
|
+
? <input type="text" {...props} ref={element => { if (element) fields.current.set(field.name, element); }}
|
|
275
|
+
onChange={event => change(event.currentTarget)} />
|
|
276
|
+
: <textarea {...props} rows={TEXTAREA_ROWS[0]} ref={element => {
|
|
277
|
+
if (!element) return;
|
|
278
|
+
fields.current.set(field.name, element);
|
|
279
|
+
fitRows(element);
|
|
280
|
+
}} onChange={event => { change(event.currentTarget); fitRows(event.currentTarget); }}
|
|
281
|
+
onKeyDown={(event: ReactKeyboardEvent<HTMLTextAreaElement>) => {
|
|
282
|
+
// Enter starts a new line in a textarea; ⌘ or Ctrl with Enter sends.
|
|
283
|
+
if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey) || event.nativeEvent.isComposing) return;
|
|
284
|
+
event.preventDefault();
|
|
285
|
+
submit();
|
|
286
|
+
}} />}
|
|
287
|
+
{last && <button type="submit" data-cloudlet-control="action" className={part('action', 'cloudlet-action cloudlet-submit')}
|
|
288
|
+
aria-label={action.label} aria-disabled={pending} aria-busy={pending}
|
|
289
|
+
aria-describedby={failed ? actionErrorId : formError ? `${id}-error` : undefined}>
|
|
290
|
+
{pending ? <svg aria-hidden="true" viewBox="0 0 16 16" className="cloudlet-spinner"><circle cx="8" cy="8" r="5.5" strokeDasharray="22 13" /></svg>
|
|
291
|
+
: glyph('M8 13V3m0 0L3.5 7.5M8 3l4.5 4.5')}
|
|
292
|
+
</button>}
|
|
293
|
+
{error !== undefined && <p id={`${fieldId}-error`} className={part('field-error', 'cloudlet-field-error')}>{error}</p>}
|
|
294
|
+
</div>;
|
|
295
|
+
};
|
|
296
|
+
return <form className={part('form', 'cloudlet-form')} noValidate aria-labelledby={titleId}
|
|
297
|
+
onSubmit={event => { event.preventDefault(); submit(); }}>
|
|
298
|
+
{action.fields.map((item, index) => field(item, index, index === action.fields.length - 1))}
|
|
299
|
+
{formError && <p id={`${id}-error`} className="cloudlet-action-error">{formError}</p>}
|
|
300
|
+
</form>;
|
|
301
|
+
}
|
|
302
|
+
|
|
220
303
|
export function closeButton(labels: CloudletLabels, part: PartClass, onClick: () => void) {
|
|
221
304
|
return control('close', glyph('m4.5 4.5 7 7m0-7-7 7'), onClick, { 'aria-label': labels.close, className: part('close', 'cloudlet-close') });
|
|
222
305
|
}
|
package/src/react/generators.ts
CHANGED
|
@@ -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
|
|
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/
|
|
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).
|
package/src/react/gestures.ts
CHANGED
|
@@ -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
|
|
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;
|
package/src/react/host.tsx
CHANGED
|
@@ -269,7 +269,13 @@ function createHostRuntime(owner: Host) {
|
|
|
269
269
|
pathRef.current?.setAttribute('d', createRoundedRectPath(width, height, radius));
|
|
270
270
|
}
|
|
271
271
|
// The shadow token is a box-shadow: the SVG box follows the path's corners.
|
|
272
|
-
if (r.bg)
|
|
272
|
+
if (r.bg) {
|
|
273
|
+
r.bg.borderRadius = px(radius);
|
|
274
|
+
// Layout keeps the box at the top and a transform carries it to the bottom edge: a growing
|
|
275
|
+
// silhouette then moves no layout start point, so the morph is not counted as layout shift (CLS).
|
|
276
|
+
r.bg.top = '0px'; r.bg.bottom = 'auto';
|
|
277
|
+
r.bg.transform = `translateX(-50%) translateY(${px(top)})`;
|
|
278
|
+
}
|
|
273
279
|
if (r.clip) r.clip.clipPath = `path("${createRoundedRectPath(width, height, radius, (layout.width - width) / 2, top)}")`;
|
|
274
280
|
if (r.badge) {
|
|
275
281
|
const scale = still ? 1 : constants.badge.scale + (1 - constants.badge.scale) * frame.badge;
|
|
@@ -441,7 +447,7 @@ function createHostRuntime(owner: Host) {
|
|
|
441
447
|
if (plan.header && head) clones.header = inertClone(head);
|
|
442
448
|
const body = bodyElement();
|
|
443
449
|
// Rapid updates (progress text every 150 ms) must not restart the crossfade: within
|
|
444
|
-
// `bodyQuiet` of the previous update the new text lands in place
|
|
450
|
+
// `bodyQuiet` of the previous update the new text lands in place.
|
|
445
451
|
const now = motion?.now() ?? 0;
|
|
446
452
|
const rapid = plan.body && now - lastBodyUpdate < (motion?.constants.bodyQuiet ?? 0);
|
|
447
453
|
if (plan.body) lastBodyUpdate = now;
|
|
@@ -493,7 +499,7 @@ function createHostRuntime(owner: Host) {
|
|
|
493
499
|
else if (flung) motion.release('dragX', 0);
|
|
494
500
|
if (plan.presence === 'exit') motion.hide();
|
|
495
501
|
}
|
|
496
|
-
// An arrival keeps the shell
|
|
502
|
+
// An arrival keeps the shell: the title blur-swaps and the width springs to the new text.
|
|
497
503
|
if (plan.presence === 'enter' || plan.presence === 'replace') {
|
|
498
504
|
motion.enter(edge, reveal('presence'));
|
|
499
505
|
if (plan.presence === 'enter') {
|
|
@@ -692,7 +698,10 @@ function createHostRuntime(owner: Host) {
|
|
|
692
698
|
const visibility = () => pause('document-hidden', doc.visibilityState === 'hidden');
|
|
693
699
|
// A pointer press outside the open Island collapses it to the stack.
|
|
694
700
|
const outside = (event: Event) => {
|
|
695
|
-
|
|
701
|
+
const snapshot = bridge.getSnapshot();
|
|
702
|
+
// Unsent text holds the Island open; Escape and the pill's own controls still collapse it.
|
|
703
|
+
const draft = snapshot.notifications.some(item => item.handle === snapshot.island.current && item.draft);
|
|
704
|
+
if (snapshot.island.open && !draft && event.target instanceof view.Node && !root.contains(event.target)) bridge.collapseIsland(lease);
|
|
696
705
|
};
|
|
697
706
|
// No mouseout reaches the host when the hovered card is removed or hidden under a still pointer
|
|
698
707
|
// (React then never sees the leave): the next pointer over anything outside releases the pause.
|
|
@@ -803,11 +812,15 @@ function createHostRuntime(owner: Host) {
|
|
|
803
812
|
function onIslandKey(event: ReactKeyboardEvent, stack: readonly NotificationHandle[], index: number, rtl: boolean) {
|
|
804
813
|
if (event.defaultPrevented) return;
|
|
805
814
|
let next: number | null = null;
|
|
815
|
+
// An IME composition owns Escape and the arrows until it ends.
|
|
816
|
+
if (event.nativeEvent.isComposing) return;
|
|
806
817
|
if (event.key === 'Escape') {
|
|
807
818
|
event.preventDefault();
|
|
808
819
|
bridge.collapseIsland(lease);
|
|
809
820
|
return;
|
|
810
821
|
}
|
|
822
|
+
// The arrows, Home and End move the caret inside a form field.
|
|
823
|
+
if ((event.target as Element).closest('input, textarea')) return;
|
|
811
824
|
// A focused scrolling body keeps Home/End for its own scroll.
|
|
812
825
|
if ((event.key === 'Home' || event.key === 'End') && event.target === bodyElement() && bodyElement()?.tabIndex === 0) return;
|
|
813
826
|
if (event.key === 'Home') next = 0;
|
|
@@ -857,7 +870,7 @@ function createHostRuntime(owner: Host) {
|
|
|
857
870
|
onClickCapture={event => {
|
|
858
871
|
const target = (event.target as Element).closest('button');
|
|
859
872
|
// A double click must not fire a one-shot action twice; close, the pill and the dots are
|
|
860
|
-
// repeatable on purpose (each click dismisses or shows another record
|
|
873
|
+
// repeatable on purpose (each click dismisses or shows another record).
|
|
861
874
|
const oneShot = !!target?.matches('[data-cloudlet-control="action"], [data-cloudlet-control="retry"], [data-cloudlet-control="cancel"]');
|
|
862
875
|
if (target && (repeating || (oneShot && event.detail > 1) || (activation && activation !== target))) { event.preventDefault(); event.stopPropagation(); }
|
|
863
876
|
activation = null;
|
|
@@ -887,7 +900,8 @@ function createHostRuntime(owner: Host) {
|
|
|
887
900
|
<Heading notification={presented} slot={slot} part={part} titleId={`${islandId}-title`} />
|
|
888
901
|
<div className="cloudlet-heading-out" aria-hidden="true" />
|
|
889
902
|
</div>
|
|
890
|
-
{open && <Body notification={presented}
|
|
903
|
+
{open && <Body notification={presented} form={snapshot.forms.find(form => form.handle === presented.handle)} bridge={bridge}
|
|
904
|
+
lease={lease} labels={labels} navigate={navigate} slot={slot} part={part} titleId={`${islandId}-title`} />}
|
|
891
905
|
<div className="cloudlet-body-out" aria-hidden="true" />
|
|
892
906
|
</div>}
|
|
893
907
|
{preview && <div ref={inertRef} className="cloudlet-peek" aria-hidden="true"><SlidePreview notification={preview} labels={labels} part={part} /></div>}
|
|
@@ -908,7 +922,8 @@ function createHostRuntime(owner: Host) {
|
|
|
908
922
|
</div>
|
|
909
923
|
{presented && !open && <button type="button" className={part('pill', 'cloudlet-pill')} data-cloudlet-pill=""
|
|
910
924
|
aria-expanded="false" aria-controls={islandId} onClick={() => bridge.openIsland(lease, 'user')}
|
|
911
|
-
aria-label={format(labels.stackSummary, defaultLabels.stackSummary, presented.content.title, total, missed)
|
|
925
|
+
aria-label={[format(labels.stackSummary, defaultLabels.stackSummary, presented.content.title, total, missed),
|
|
926
|
+
...(presented.draft ? [labels.draft] : [])].join(', ')} />}
|
|
912
927
|
<span className={part('badge', 'cloudlet-badge')} aria-hidden="true"><span className="cloudlet-badge-value">{badgeCount}</span><span className="cloudlet-badge-out" /></span>
|
|
913
928
|
</div>
|
|
914
929
|
<div ref={exitRef} className="cloudlet-exit" aria-hidden="true" />
|
package/src/react/motion.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { spring, tween as tweenGenerator } from './generators.js';
|
|
|
3
3
|
import type { Generator } from './generators.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* Values
|
|
6
|
+
* Values tuned on the laboratory, the one place
|
|
7
7
|
* to tune them. Durations are milliseconds at `timeScale: 1`; offsets are CSS px.
|
|
8
8
|
*/
|
|
9
9
|
export const MOTION = {
|
|
@@ -33,7 +33,7 @@ export const MOTION = {
|
|
|
33
33
|
/** Reduced motion: every transition becomes an opacity change of this length; swipes are off. */
|
|
34
34
|
reduced: 80,
|
|
35
35
|
/**
|
|
36
|
-
* Swipes
|
|
36
|
+
* Swipes: the axis is decided after `intent` px; a release commits past
|
|
37
37
|
* `distance` of the swiped dimension, or after `minDistance` px with `velocity` px/ms
|
|
38
38
|
* towards the commit (a flick back cancels). Edges resist with the rubber-band
|
|
39
39
|
* coefficient; a trackpad swipe ends after `wheelIdle` ms without wheel events and commits
|
|
@@ -50,7 +50,7 @@ const tunable: CloudletMotionConstants = MOTION;
|
|
|
50
50
|
const positive = new Set(['stiffness', 'mass']);
|
|
51
51
|
|
|
52
52
|
/**
|
|
53
|
-
* Resolves `ToasterMotion.overrides` (a debugging channel
|
|
53
|
+
* Resolves `ToasterMotion.overrides` (a debugging channel) onto the starting
|
|
54
54
|
* values. A field that is not a finite number in range (springs: stiffness and mass > 0,
|
|
55
55
|
* everything else ≥ 0) keeps its default; unknown keys are ignored.
|
|
56
56
|
*/
|
|
@@ -309,7 +309,7 @@ export function createShellMotion(options: ShellMotionOptions) {
|
|
|
309
309
|
enter(edge: -1 | 1, done?: () => void) {
|
|
310
310
|
request(time => {
|
|
311
311
|
jump('opacity', 0); jump('scale', m.enter.scale); jump('y', edge * m.enter.offset);
|
|
312
|
-
// The shell becomes opaque within `fade`; only scale and y follow the spring
|
|
312
|
+
// The shell becomes opaque within `fade`; only scale and y follow the spring.
|
|
313
313
|
to('opacity', 1, tween(m.enter.fade), time);
|
|
314
314
|
for (const key of ['scale', 'y'] as const) to(key, key === 'y' ? 0 : 1, enterSpring(), time);
|
|
315
315
|
after('presence', ['opacity', 'scale', 'y'], done);
|
package/src/react/plan.ts
CHANGED
|
@@ -14,7 +14,7 @@ export interface ShellView {
|
|
|
14
14
|
readonly total: number;
|
|
15
15
|
/** Tails behind the collapsed pill (0–2); none in the Island. */
|
|
16
16
|
readonly depth: number;
|
|
17
|
-
/** Missed notifications (overflow), part of the badge and the pill name
|
|
17
|
+
/** Missed notifications (overflow), part of the badge and the pill name. */
|
|
18
18
|
readonly missed: number;
|
|
19
19
|
/** Badge number: records in the stack plus missed ones; shown on the pill at ≥ 2 or with missed ones. */
|
|
20
20
|
readonly count: number;
|
|
@@ -59,7 +59,8 @@ function bodyKey(item: Presented) {
|
|
|
59
59
|
const { content, operation, action } = item;
|
|
60
60
|
const description = content.description;
|
|
61
61
|
return [description?.kind, description?.kind === 'text' ? description.text : '', content.progress?.kind,
|
|
62
|
-
content.action?.kind, content.action?.label, action
|
|
62
|
+
content.action?.kind, content.action?.label, content.action?.kind === 'form' ? content.action.fields.map(field => field.name).join('\u0001') : '',
|
|
63
|
+
action.status === 'failed' ? action.message : '',
|
|
63
64
|
operation?.status, operation?.canRetry, operation?.canCancel].join('\u0000');
|
|
64
65
|
}
|
|
65
66
|
|
|
@@ -79,7 +80,7 @@ export function planShell(previous: ShellView, next: ShellView): ShellPlan {
|
|
|
79
80
|
if (previous.open !== next.open) plan.morph = next.open ? 'open' : 'close';
|
|
80
81
|
if (before.handle !== after.handle) {
|
|
81
82
|
if (previous.open && next.open) {
|
|
82
|
-
// Only the body slides
|
|
83
|
+
// Only the body slides: the title and icon blur-swap in place.
|
|
83
84
|
plan.slide = next.index >= previous.index ? 1 : -1;
|
|
84
85
|
plan.header = headerKey(before) !== headerKey(after) || before.content.icon !== after.content.icon;
|
|
85
86
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { useEffect, useRef, useState, useSyncExternalStore } from 'react';
|
|
2
|
+
import type { ReactElement } from 'react';
|
|
3
|
+
import { createPortal } from 'react-dom';
|
|
4
|
+
import { getRendererBridge } from '../core/bridge.js';
|
|
5
|
+
import type { HostLease } from '../contracts/internal.js';
|
|
6
|
+
import type { ReactCloudletController, ToasterProps } from '../react.js';
|
|
7
|
+
import { Host } from './host.js';
|
|
8
|
+
|
|
9
|
+
// The renderer chunk: Toaster in bindings.tsx loads this module on the client once, after mount.
|
|
10
|
+
const subscribeMount = () => () => {};
|
|
11
|
+
const clientMounted = () => true;
|
|
12
|
+
const serverMounted = () => false;
|
|
13
|
+
|
|
14
|
+
interface Attachment {
|
|
15
|
+
readonly controller: ReactCloudletController;
|
|
16
|
+
readonly lease: HostLease;
|
|
17
|
+
readonly container: Element;
|
|
18
|
+
readonly document: Document;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function AttachedToaster({ controller, options }: { controller: ReactCloudletController; options: ToasterProps }): ReactElement | null {
|
|
22
|
+
// React supplies the server value during hydration, then the client value.
|
|
23
|
+
// The inert marker can therefore identify the owner document without a store
|
|
24
|
+
// or effect whose only purpose is an extra mounting render.
|
|
25
|
+
const mounted = useSyncExternalStore(subscribeMount, clientMounted, serverMounted);
|
|
26
|
+
const bridge = getRendererBridge(controller);
|
|
27
|
+
const snapshot = useSyncExternalStore(bridge.subscribe, bridge.getSnapshot, bridge.getServerSnapshot);
|
|
28
|
+
const marker = useRef<HTMLTemplateElement>(null);
|
|
29
|
+
const [attachment, setAttachment] = useState<Attachment | null>(null);
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!mounted || !marker.current) return;
|
|
32
|
+
const ownerDocument = marker.current.ownerDocument;
|
|
33
|
+
let container: Element;
|
|
34
|
+
try {
|
|
35
|
+
const requested = typeof options.container === 'function' ? options.container() : options.container;
|
|
36
|
+
const candidate = requested ?? ownerDocument.body;
|
|
37
|
+
// nodeType/ownerDocument also work when the mounting React root is in another realm.
|
|
38
|
+
if (!candidate || candidate.nodeType !== 1 || candidate.ownerDocument !== ownerDocument
|
|
39
|
+
|| candidate.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !candidate.isConnected
|
|
40
|
+
|| candidate.getRootNode().nodeType === 11) {
|
|
41
|
+
bridge.reportInvalidContainer('Toaster container must be a connected HTML Element in the mounting document, outside Shadow DOM');
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
container = candidate;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
bridge.reportInvalidContainer('Toaster container resolver failed', error);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const delay = options.attention?.delay;
|
|
50
|
+
let attached = bridge.attach(delay === undefined ? undefined : { attentionDelay: delay });
|
|
51
|
+
// An invalid delay must not suppress the host: fall back to the controller default and report it.
|
|
52
|
+
const invalidDelay = attached.status === 'rejected' && attached.reason === 'invalid-input';
|
|
53
|
+
if (invalidDelay) attached = bridge.attach();
|
|
54
|
+
if (attached.status !== 'attached') return;
|
|
55
|
+
if (invalidDelay) bridge.reportDiagnostic(attached.lease, { code: 'invalid-input', source: 'Toaster.attention',
|
|
56
|
+
message: 'attention.delay must be a finite nonnegative number of milliseconds' });
|
|
57
|
+
const current = { controller, lease: attached.lease, container, document: ownerDocument };
|
|
58
|
+
applyAutoDismiss(current.lease, false);
|
|
59
|
+
setAttachment(current);
|
|
60
|
+
return () => { bridge.detach(current.lease); };
|
|
61
|
+
// Container and attention delay are fixed for this attachment; changing them requires remount.
|
|
62
|
+
}, [controller, mounted]);
|
|
63
|
+
// Applied before the first presentation, then whenever the prop changes (which reports an invalid value once).
|
|
64
|
+
function applyAutoDismiss(lease: HostLease, report: boolean) {
|
|
65
|
+
const value = options.autoDismiss;
|
|
66
|
+
const valid = value === undefined || typeof value === 'boolean';
|
|
67
|
+
bridge.setAutoDismiss(lease, valid ? value : undefined);
|
|
68
|
+
if (!valid && report) bridge.reportDiagnostic(lease, { code: 'invalid-input', source: 'Toaster.autoDismiss',
|
|
69
|
+
message: 'autoDismiss must be a boolean' });
|
|
70
|
+
}
|
|
71
|
+
useEffect(() => { if (attachment) applyAutoDismiss(attachment.lease, true); }, [attachment, options.autoDismiss]);
|
|
72
|
+
|
|
73
|
+
if (!mounted) return null;
|
|
74
|
+
return <><template ref={marker} />{attachment?.controller === controller && !snapshot.disposed
|
|
75
|
+
? createPortal(<Host key={attachment.lease} bridge={bridge} lease={attachment.lease} snapshot={snapshot}
|
|
76
|
+
options={options} document={attachment.document} />, attachment.container) : null}</>;
|
|
77
|
+
}
|
package/src/react.ts
CHANGED
|
@@ -57,6 +57,8 @@ export interface CloudletLabels {
|
|
|
57
57
|
/** 1-based slide position. */
|
|
58
58
|
readonly page: (index: number, total: number) => string;
|
|
59
59
|
readonly overflowCount: (count: number) => string;
|
|
60
|
+
/** Added to the collapsed stack button's name while the presented form holds unsent text. */
|
|
61
|
+
readonly draft: string;
|
|
60
62
|
}
|
|
61
63
|
|
|
62
64
|
export interface AnnouncementFormatters {
|
|
@@ -77,7 +79,7 @@ export interface ToasterAttention {
|
|
|
77
79
|
readonly delay?: number;
|
|
78
80
|
}
|
|
79
81
|
|
|
80
|
-
/** A physical spring of
|
|
82
|
+
/** A physical spring of the motion system. */
|
|
81
83
|
export interface CloudletSpring {
|
|
82
84
|
readonly stiffness: number;
|
|
83
85
|
readonly damping: number;
|
|
@@ -91,7 +93,7 @@ export interface CloudletTimedSpring {
|
|
|
91
93
|
}
|
|
92
94
|
|
|
93
95
|
/**
|
|
94
|
-
* The motion constants
|
|
96
|
+
* The motion constants: durations in ms at `timeScale: 1`, offsets and blur in CSS px.
|
|
95
97
|
* Reported by the laboratory's tuning panel; see `ToasterMotion.overrides`.
|
|
96
98
|
*/
|
|
97
99
|
export interface CloudletMotionConstants {
|
|
@@ -148,7 +150,7 @@ export interface ToasterMotion {
|
|
|
148
150
|
*/
|
|
149
151
|
readonly timeScale?: number;
|
|
150
152
|
/**
|
|
151
|
-
* Debugging and laboratory channel
|
|
153
|
+
* Debugging and laboratory channel: replaces the motion constants live, for
|
|
152
154
|
* transitions started after the change. A field that is not a finite number in range
|
|
153
155
|
* (stiffness and mass > 0, the rest ≥ 0) keeps its default. Not a styling API: the
|
|
154
156
|
* values may change between releases; do not ship overrides to production.
|
|
@@ -156,9 +158,9 @@ export interface ToasterMotion {
|
|
|
156
158
|
readonly overrides?: CloudletMotionOverrides;
|
|
157
159
|
}
|
|
158
160
|
|
|
159
|
-
/** Styling hooks of the renderer
|
|
161
|
+
/** Styling hooks of the renderer; see `ToasterProps.classNames`. */
|
|
160
162
|
export type CloudletPart = 'host' | 'stack' | 'pill' | 'tail' | 'badge' | 'island' | 'header' | 'icon' | 'title'
|
|
161
|
-
| 'close' | 'body' | 'description' | 'actions' | 'action' | 'indicator' | 'overflow';
|
|
163
|
+
| 'close' | 'body' | 'description' | 'actions' | 'action' | 'indicator' | 'overflow' | 'form' | 'field' | 'field-error';
|
|
162
164
|
|
|
163
165
|
export interface ToasterProps {
|
|
164
166
|
readonly position?: 'auto' | 'top-center' | 'bottom-center';
|