@cloudlet/toast 0.0.0-stage → 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.
- package/CHANGELOG.md +271 -0
- package/LICENSE +21 -0
- package/README.md +65 -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/bridge.d.ts +5 -0
- package/dist/core/bridge.d.ts.map +1 -0
- package/dist/core/bridge.js +277 -0
- package/dist/core/bridge.js.map +1 -0
- package/dist/core/controller.d.ts +117 -0
- package/dist/core/controller.d.ts.map +1 -0
- package/dist/core/controller.js +787 -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 +140 -0
- package/dist/react/announcer.js.map +1 -0
- package/dist/react/bindings.d.ts +17 -0
- package/dist/react/bindings.d.ts.map +1 -0
- package/dist/react/bindings.js +47 -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/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/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 +19 -4
- package/src/contracts/controller.ts +61 -0
- package/src/contracts/events.ts +48 -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/bridge.ts +280 -0
- package/src/core/controller.ts +853 -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 +198 -0
- package/src/react/bindings.tsx +56 -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 +953 -0
- package/src/react/motion.ts +484 -0
- package/src/react/plan.ts +101 -0
- package/src/react/renderer.tsx +77 -0
- package/src/react/shape.ts +33 -0
- package/src/react/viewport.ts +10 -0
- package/src/react.ts +190 -0
|
@@ -0,0 +1,222 @@
|
|
|
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';
|
|
4
|
+
import type { NotificationHandle } from '../contracts/identity.js';
|
|
5
|
+
import type { NotificationKind } from '../contracts/notifications.js';
|
|
6
|
+
import type { NotificationSnapshot } from '../contracts/snapshots.js';
|
|
7
|
+
import type { CloudletLabels, CloudletPart, ToasterProps } from '../react.js';
|
|
8
|
+
|
|
9
|
+
export const defaultLabels: CloudletLabels = {
|
|
10
|
+
region: 'Notifications', island: 'Current notifications', carousel: 'carousel', slide: 'slide',
|
|
11
|
+
close: 'Close notification', retry: 'Retry',
|
|
12
|
+
cancel: 'Request cancellation', cancellationRequested: 'Cancellation requested',
|
|
13
|
+
acknowledgeOverflow: 'Acknowledge missed notifications', collapse: 'Press Escape to collapse',
|
|
14
|
+
stackSummary: (title, count, missed) => [title, ...(count > 1 ? [`${count} notifications`] : []),
|
|
15
|
+
...(missed > 0 ? [`${missed} missed`] : [])].join(', '),
|
|
16
|
+
page: (index, total) => `${index} of ${total}`,
|
|
17
|
+
overflowCount: count => `${count} missed notifications`,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
interface SlotProps {
|
|
21
|
+
readonly content: ReactNode;
|
|
22
|
+
readonly bridge: RendererBridge<ReactNode>;
|
|
23
|
+
readonly lease: HostLease;
|
|
24
|
+
readonly handle: NotificationHandle;
|
|
25
|
+
readonly rejectFocus: (previous: EventTarget | null) => void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
class SlotBoundary extends Component<SlotProps, { failed: boolean; content: ReactNode }> {
|
|
29
|
+
override state = { failed: false, content: this.props.content };
|
|
30
|
+
static getDerivedStateFromError() { return { failed: true }; }
|
|
31
|
+
static getDerivedStateFromProps(props: SlotProps, state: { content: ReactNode }) {
|
|
32
|
+
return props.content === state.content ? null : { failed: false, content: props.content };
|
|
33
|
+
}
|
|
34
|
+
override componentDidCatch(error: unknown) {
|
|
35
|
+
this.props.bridge.reportDiagnostic(this.props.lease, { code: 'slot-error', source: 'Toaster.slot',
|
|
36
|
+
message: 'A rich slot could not be rendered', handle: this.props.handle, error });
|
|
37
|
+
}
|
|
38
|
+
override render() {
|
|
39
|
+
return this.state.failed ? this.props.bridge.renderError
|
|
40
|
+
: <Suspense fallback={this.props.bridge.renderError}><CheckedSlot {...this.props} /></Suspense>;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function CheckedSlot({ content, bridge, lease, handle, rejectFocus }: SlotProps) {
|
|
45
|
+
const ref = useRef<HTMLDivElement>(null);
|
|
46
|
+
const [invalidContent, setInvalidContent] = useState<{ content: ReactNode } | null>(null);
|
|
47
|
+
const invalid = invalidContent?.content === content;
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
const element = ref.current;
|
|
50
|
+
if (!element) return;
|
|
51
|
+
let reported = false;
|
|
52
|
+
const check = () => {
|
|
53
|
+
if (reported || !element.querySelector('a[href],button,input,select,textarea,summary,iframe,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]')) return;
|
|
54
|
+
reported = true;
|
|
55
|
+
setInvalidContent({ content });
|
|
56
|
+
bridge.reportDiagnostic(lease, { code: 'slot-error', source: 'Toaster.slot',
|
|
57
|
+
message: 'Rich slots must be non-interactive; use the notification action', handle });
|
|
58
|
+
};
|
|
59
|
+
check();
|
|
60
|
+
const Observer = element.ownerDocument.defaultView?.MutationObserver;
|
|
61
|
+
const observer = Observer ? new Observer(check) : null;
|
|
62
|
+
observer?.observe(element, { childList: true, subtree: true, attributes: true });
|
|
63
|
+
return () => observer?.disconnect();
|
|
64
|
+
}, [content, bridge, lease, handle]);
|
|
65
|
+
return <div ref={ref} className="cloudlet-slot" onFocusCapture={event => rejectFocus(event.relatedTarget)}>
|
|
66
|
+
{invalid ? bridge.renderError : content}
|
|
67
|
+
</div>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function control(name: string, children: ReactNode, onClick: () => void, props?: ComponentPropsWithRef<'button'>) {
|
|
71
|
+
return <button type="button" data-cloudlet-control={name} {...props} onClick={onClick}>{children}</button>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function glyph(path: string) {
|
|
75
|
+
return <svg aria-hidden="true" viewBox="0 0 16 16"><path d={path} /></svg>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Adds the application's `classNames` part to an own `cloudlet-*` class, never replacing it. */
|
|
79
|
+
export type PartClass = (part: CloudletPart, own: string) => string;
|
|
80
|
+
export function partClasses(classNames: ToasterProps['classNames']): PartClass {
|
|
81
|
+
return (part, own) => {
|
|
82
|
+
const extra = classNames?.[part];
|
|
83
|
+
return typeof extra === 'string' && extra.trim() ? `${own} ${extra.trim()}` : own;
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 16 px stroke glyphs drawn in the status colour. */
|
|
88
|
+
const glyphs: Record<Exclude<NotificationKind, 'loading'>, string> = {
|
|
89
|
+
success: 'M4.5 8.5 7 11l4.5-5.5',
|
|
90
|
+
error: 'm5.5 5.5 5 5m0-5-5 5',
|
|
91
|
+
info: 'M8 7.5V11M8 5h.01',
|
|
92
|
+
warning: 'M8 4.75V8.5M8 11.25h.01',
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The status icon: a 24 px tinted circle with a glyph, the loading spinner or the
|
|
97
|
+
* notification's own icon, and the 2 px progress ring around it (pill and Island
|
|
98
|
+
* share these nodes). With progress the icon is the accessible progressbar. The
|
|
99
|
+
* determinate arc is owned by the host sampler (one RAF per host, 240 ms tween);
|
|
100
|
+
* `preview` draws the value statically for the inert swipe neighbour.
|
|
101
|
+
*/
|
|
102
|
+
export function StatusIcon({ notification, slot, part, preview = false }: {
|
|
103
|
+
notification: NotificationSnapshot<ReactNode>; slot: (value: ReactNode) => ReactNode; part: PartClass; preview?: boolean;
|
|
104
|
+
}) {
|
|
105
|
+
const { content, kind } = notification;
|
|
106
|
+
const { progress } = content;
|
|
107
|
+
const determinate = progress?.kind === 'determinate';
|
|
108
|
+
return <div className={part('icon', 'cloudlet-icon')} data-kind={kind}
|
|
109
|
+
{...(progress && !preview ? { role: 'progressbar', 'aria-valuemin': 0, 'aria-valuemax': 100,
|
|
110
|
+
'aria-valuenow': determinate ? Math.round(progress.value * 100) : undefined, 'aria-label': progress.label ?? content.title }
|
|
111
|
+
: { 'aria-hidden': 'true' })}>
|
|
112
|
+
{content.icon !== undefined
|
|
113
|
+
? <span className="cloudlet-glyph" aria-hidden="true">{slot(content.icon)}</span>
|
|
114
|
+
// With progress the ring is the activity indicator of a loading record.
|
|
115
|
+
: kind === 'loading' ? !progress && <svg aria-hidden="true" viewBox="0 0 16 16" className="cloudlet-glyph cloudlet-spinner">
|
|
116
|
+
<circle cx="8" cy="8" r="5.5" strokeDasharray="22 13" /></svg>
|
|
117
|
+
: <svg aria-hidden="true" viewBox="0 0 16 16" className="cloudlet-glyph"><path d={glyphs[kind]} /></svg>}
|
|
118
|
+
{progress && <svg aria-hidden="true" viewBox="0 0 32 32" className="cloudlet-ring" data-progress={progress.kind}>
|
|
119
|
+
<circle className="cloudlet-ring-track" cx="16" cy="16" r="15" />
|
|
120
|
+
<circle className="cloudlet-progress-fill" cx="16" cy="16" r="15" pathLength="100" transform="rotate(-90 16 16)"
|
|
121
|
+
strokeDasharray={!determinate ? '25 75' : preview ? `${Math.round(progress.value * 10000) / 100} 100` : '0 100'} />
|
|
122
|
+
</svg>}
|
|
123
|
+
</div>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function slotRenderer(bridge: RendererBridge<ReactNode>, lease: HostLease, handle: NotificationHandle,
|
|
127
|
+
rejectSlotFocus: (previous: EventTarget | null) => void) {
|
|
128
|
+
return (value: ReactNode) => <SlotBoundary content={value} bridge={bridge} lease={lease} handle={handle} rejectFocus={rejectSlotFocus} />;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Status icon and title: the same DOM nodes in the pill and in the Island header,
|
|
133
|
+
* so opening never re-creates them and the title can receive focus in place.
|
|
134
|
+
*/
|
|
135
|
+
export function Heading({ notification, slot, part, titleId }: {
|
|
136
|
+
notification: NotificationSnapshot<ReactNode>; slot: (value: ReactNode) => ReactNode; part: PartClass;
|
|
137
|
+
/** Omitted for the inert neighbour preview: no id, focus target, data hook or live progress. */
|
|
138
|
+
titleId?: string;
|
|
139
|
+
}) {
|
|
140
|
+
const title = part('title', 'cloudlet-title');
|
|
141
|
+
return <div className="cloudlet-heading">
|
|
142
|
+
<StatusIcon notification={notification} slot={slot} part={part} preview={titleId === undefined} />
|
|
143
|
+
{titleId === undefined ? <h2 className={title}>{notification.content.title}</h2>
|
|
144
|
+
: <h2 id={titleId} tabIndex={-1} data-cloudlet-title="" className={title}>{notification.content.title}</h2>}
|
|
145
|
+
</div>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Rich content of the inert neighbour preview: rendered as is, never checked or reported twice. */
|
|
149
|
+
export const previewSlot = (value: ReactNode) => <div className="cloudlet-slot">{value}</div>;
|
|
150
|
+
|
|
151
|
+
/** A settled factory can always retry through the API; only an unsuccessful attempt offers the button. */
|
|
152
|
+
type Operation = NotificationSnapshot<ReactNode>['operation'];
|
|
153
|
+
const retryable = (operation: Operation): operation is NonNullable<Operation> => !!operation?.canRetry && operation.status !== 'fulfilled';
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The neighbour shown only while a finger drags the Island content:
|
|
157
|
+
* the same layout as a live slide, but every control is a lookalike without
|
|
158
|
+
* handlers, ids, links or tab stops. The caller puts it in an `inert` container.
|
|
159
|
+
*/
|
|
160
|
+
export function SlidePreview({ notification, labels, part }: { notification: NotificationSnapshot<ReactNode>; labels: CloudletLabels; part: PartClass }) {
|
|
161
|
+
const { content, operation, kind } = notification;
|
|
162
|
+
const action = part('action', 'cloudlet-action');
|
|
163
|
+
const lookalike = (children: ReactNode, primary = false) =>
|
|
164
|
+
<button type="button" tabIndex={-1} className={primary ? `${action} cloudlet-primary` : action}>{children}</button>;
|
|
165
|
+
// Only the body slides: the preview shows the neighbour's body under the live heading.
|
|
166
|
+
return <div className="cloudlet-slide" data-kind={kind}>
|
|
167
|
+
<div className={part('body', 'cloudlet-body')} data-kind={kind}>
|
|
168
|
+
{content.description && <div className={part('description', 'cloudlet-description')}>
|
|
169
|
+
{content.description.kind === 'text' ? <p>{content.description.text}</p> : previewSlot(content.description.content)}
|
|
170
|
+
</div>}
|
|
171
|
+
<div className={part('actions', 'cloudlet-actions')}>
|
|
172
|
+
{content.action?.kind === 'command' && lookalike(content.action.label, true)}
|
|
173
|
+
{content.action?.kind === 'link' && <a className={`${action} cloudlet-primary`}>{content.action.label}</a>}
|
|
174
|
+
{retryable(operation) && lookalike(labels.retry)}
|
|
175
|
+
{operation?.canCancel && lookalike(operation.cancelRequested ? labels.cancellationRequested : labels.cancel)}
|
|
176
|
+
</div>
|
|
177
|
+
{notification.action.status === 'failed' && <p className="cloudlet-action-error">{notification.action.message}</p>}
|
|
178
|
+
</div>
|
|
179
|
+
</div>;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 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;
|
|
186
|
+
}) {
|
|
187
|
+
const { handle, content, operation, action, kind } = notification;
|
|
188
|
+
// The primary action is tinted with the status; retry and cancel stay neutral.
|
|
189
|
+
const neutral = part('action', 'cloudlet-action');
|
|
190
|
+
const primary = `${neutral} cloudlet-primary`;
|
|
191
|
+
const id = useId();
|
|
192
|
+
const command = content.action;
|
|
193
|
+
const activateLink = (event: MouseEvent) => {
|
|
194
|
+
// Observe cancellation after portal/application ancestors have handled activation.
|
|
195
|
+
queueMicrotask(() => { if (!event.defaultPrevented) navigate(handle); });
|
|
196
|
+
};
|
|
197
|
+
return <div className={part('body', 'cloudlet-body')} data-kind={kind}>
|
|
198
|
+
{content.description && <div className={part('description', 'cloudlet-description')}>
|
|
199
|
+
{content.description.kind === 'text' && <p>{content.description.text}</p>}
|
|
200
|
+
{content.description.kind === 'rich' && slot(content.description.content)}
|
|
201
|
+
</div>}
|
|
202
|
+
<div className={part('actions', 'cloudlet-actions')}>
|
|
203
|
+
{command?.kind === 'command' && control('action', command.label, () => {
|
|
204
|
+
if (action.status !== 'pending') bridge.invokeAction(lease, handle);
|
|
205
|
+
}, { className: primary, 'aria-disabled': action.status === 'pending', 'aria-busy': action.status === 'pending',
|
|
206
|
+
'aria-describedby': action.status === 'failed' ? `${id}-action-error` : undefined })}
|
|
207
|
+
{command?.kind === 'link' && <a data-cloudlet-control="action" className={primary} href={command.href} target={command.target}
|
|
208
|
+
rel={command.target === '_blank' ? [...new Set(`${command.rel ?? ''} noopener`.trim().split(/\s+/u))].join(' ') : command.rel}
|
|
209
|
+
onClick={event => activateLink(event.nativeEvent)}
|
|
210
|
+
onAuxClick={event => { if (event.button === 1) activateLink(event.nativeEvent); }}>{command.label}</a>}
|
|
211
|
+
{retryable(operation) && control('retry', labels.retry, () => bridge.retryOperation(lease, handle, operation.token), { className: neutral })}
|
|
212
|
+
{operation?.canCancel && control('cancel', operation.cancelRequested ? labels.cancellationRequested : labels.cancel, () => {
|
|
213
|
+
if (!operation.cancelRequested) bridge.cancelOperation(lease, handle, operation.token);
|
|
214
|
+
}, { className: neutral, 'aria-disabled': operation.cancelRequested })}
|
|
215
|
+
</div>
|
|
216
|
+
{action.status === 'failed' && <p id={`${id}-action-error`} className="cloudlet-action-error">{action.message}</p>}
|
|
217
|
+
</div>;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function closeButton(labels: CloudletLabels, part: PartClass, onClick: () => void) {
|
|
221
|
+
return control('close', glyph('m4.5 4.5 7 7m0-7-7 7'), onClick, { 'aria-label': labels.close, className: part('close', 'cloudlet-close') });
|
|
222
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Numeric animation generators for the shell sampler (motion.ts), ported from Motion 14.3.0
|
|
3
|
+
* so that every frame matches what was tuned on the laboratory:
|
|
4
|
+
*
|
|
5
|
+
* - `spring` is the numeric part of motion-dom/dist/es/animation/generators/spring.mjs
|
|
6
|
+
* (physics-defined and duration/bounce-defined springs, `findSpring`, analytical velocity,
|
|
7
|
+
* granular rest thresholds, the overdamped settle limit);
|
|
8
|
+
* - `tween` is the two-keyframe fast path of motion-dom's `keyframes` generator for numbers,
|
|
9
|
+
* with `easeOut` = `cubicBezier(0, 0, 0.58, 1)` from motion-utils 14.1.1.
|
|
10
|
+
*
|
|
11
|
+
* Motion is Copyright (c) 2024 Motion B.V., MIT (packages/toast/THIRD_PARTY_NOTICES.md).
|
|
12
|
+
* Colour/string mixing, keyframe arrays and the rest of Motion are not needed here: Cloudlet
|
|
13
|
+
* animates numbers only. tests/unit/generators-reference.test.ts samples both implementations
|
|
14
|
+
* every millisecond against the installed Motion 14.3.0 (|Δ| < 1e-9, same `done` frame).
|
|
15
|
+
* Expressions keep Motion's operation order on purpose: a re-association changes the last bits.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export interface GeneratorState { value: number; done: boolean }
|
|
19
|
+
export interface Generator {
|
|
20
|
+
/** `t` in generator milliseconds. Returns a mutable state object, like Motion's iterator. */
|
|
21
|
+
readonly next: (t: number) => GeneratorState;
|
|
22
|
+
/** Analytical derivative in units per second; tweens have none (a following spring starts at rest). */
|
|
23
|
+
readonly velocity?: (t: number) => number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SpringOptions {
|
|
27
|
+
readonly from: number;
|
|
28
|
+
readonly to: number;
|
|
29
|
+
/** Units per second; ignored by duration/bounce springs, as in Motion. */
|
|
30
|
+
readonly velocity?: number | undefined;
|
|
31
|
+
readonly stiffness?: number | undefined;
|
|
32
|
+
readonly damping?: number | undefined;
|
|
33
|
+
readonly mass?: number | undefined;
|
|
34
|
+
readonly duration?: number | undefined;
|
|
35
|
+
readonly bounce?: number | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const clamp = (min: number, max: number, v: number) => (v > max ? max : v < min ? min : v);
|
|
39
|
+
const millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000;
|
|
40
|
+
const secondsToMilliseconds = (seconds: number) => seconds * 1000;
|
|
41
|
+
|
|
42
|
+
/* ------------------------------------------------------------------------------------------ */
|
|
43
|
+
/* motion-utils/dist/es/easing/cubic-bezier.mjs (modified from Gaëtan Renaudeau's BezierEasing) */
|
|
44
|
+
|
|
45
|
+
const calcBezier = (t: number, a1: number, a2: number) => t * (3 * (1 - t) * ((1 - t) * a1 + t * a2) + t * t);
|
|
46
|
+
function cubicBezier(mX1: number, mY1: number, mX2: number, mY2: number): (x: number) => number {
|
|
47
|
+
if (mX1 === mY1 && mX2 === mY2) return (x) => x;
|
|
48
|
+
return (x) => {
|
|
49
|
+
let lowerBound = 0;
|
|
50
|
+
let upperBound = 1;
|
|
51
|
+
let t = x;
|
|
52
|
+
for (let i = 0; ; i++) {
|
|
53
|
+
// Outside the bracket (x out of range or a Newton overshoot on a flat part): bisect.
|
|
54
|
+
if (!(t >= lowerBound && t <= upperBound)) t = (lowerBound + upperBound) / 2;
|
|
55
|
+
const currentX = calcBezier(t, mX1, mX2) - x;
|
|
56
|
+
if (currentX * currentX < 1e-28 || i === 40) break;
|
|
57
|
+
currentX > 0 ? (upperBound = t) : (lowerBound = t);
|
|
58
|
+
// Newton-Raphson step, dx/dt from a forward difference.
|
|
59
|
+
t -= (currentX * 1e-7) / (calcBezier(t + 1e-7, mX1, mX2) - x - currentX);
|
|
60
|
+
}
|
|
61
|
+
return calcBezier(t, mY1, mY2);
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const easeOut = cubicBezier(0, 0, 0.58, 1);
|
|
65
|
+
|
|
66
|
+
/* ------------------------------------------------------------------------------------------ */
|
|
67
|
+
/* motion-dom/dist/es/animation/generators/keyframes.mjs: two numeric keyframes, one easing */
|
|
68
|
+
|
|
69
|
+
/** `keyframes({ keyframes: [from, to], duration, ease: 'easeOut' })` for numbers. */
|
|
70
|
+
export function tween(from: number, to: number, duration: number): Generator {
|
|
71
|
+
const state: GeneratorState = { done: false, value: from };
|
|
72
|
+
const mixes = from !== to;
|
|
73
|
+
return {
|
|
74
|
+
next: (t) => {
|
|
75
|
+
state.value = mixes ? from + (to - from) * easeOut(duration > 0 ? clamp(0, 1, t / duration) : 1) : to;
|
|
76
|
+
state.done = t >= duration;
|
|
77
|
+
return state;
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/* ------------------------------------------------------------------------------------------ */
|
|
83
|
+
/* motion-dom/dist/es/animation/generators/spring.mjs */
|
|
84
|
+
|
|
85
|
+
const springDefaults = {
|
|
86
|
+
stiffness: 100,
|
|
87
|
+
damping: 10,
|
|
88
|
+
mass: 1.0,
|
|
89
|
+
duration: 800,
|
|
90
|
+
bounce: 0.3,
|
|
91
|
+
restSpeed: { granular: 0.01, default: 2 },
|
|
92
|
+
restDelta: { granular: 0.005, default: 0.5 },
|
|
93
|
+
minDuration: 0.01,
|
|
94
|
+
maxDuration: 10.0,
|
|
95
|
+
minDamping: 0.05,
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** Bounce → damping ratio as SwiftUI does: 0 critically damped, towards 1 undamped, towards −1 overdamped. */
|
|
99
|
+
const bounceToDampingRatio = (bounce: number) => bounce < 0
|
|
100
|
+
? 1 / Math.max(1 + bounce, springDefaults.minDamping)
|
|
101
|
+
: Math.max(1 - bounce, springDefaults.minDamping);
|
|
102
|
+
|
|
103
|
+
const rootIterations = 12;
|
|
104
|
+
function approximateRoot(envelope: (v: number) => number, derivative: (v: number) => number, initialGuess: number) {
|
|
105
|
+
let result = initialGuess;
|
|
106
|
+
for (let i = 1; i < rootIterations; i++) result = result - envelope(result) / derivative(result);
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Scales an overdamped spring's undamped frequency so a negative bounce changes the shape, not the arrival. */
|
|
111
|
+
function overdampedFreqScale(dampingRatio: number, criticalFreqTime: number) {
|
|
112
|
+
if (!(dampingRatio > 1)) return 1;
|
|
113
|
+
const root = Math.sqrt(dampingRatio * dampingRatio - 1);
|
|
114
|
+
const slow = dampingRatio - root;
|
|
115
|
+
const fast = dampingRatio + root;
|
|
116
|
+
const target = 2 * root * Math.exp(-criticalFreqTime) * (1 + criticalFreqTime);
|
|
117
|
+
return approximateRoot(
|
|
118
|
+
(freqTime) => fast * Math.exp(-slow * freqTime) - slow * Math.exp(-fast * freqTime) - target,
|
|
119
|
+
(freqTime) => Math.exp(-fast * freqTime) - Math.exp(-slow * freqTime),
|
|
120
|
+
criticalFreqTime,
|
|
121
|
+
) / criticalFreqTime;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function calcAngularFreq(undampedFreq: number, dampingRatio: number) {
|
|
125
|
+
return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const safeMin = 0.001;
|
|
129
|
+
/** Duration/bounce → stiffness/damping (zero initial velocity, default mass), by Newton's method. */
|
|
130
|
+
function findSpring(duration: number, bounce: number) {
|
|
131
|
+
let envelope: (undampedFreq: number) => number;
|
|
132
|
+
let derivative: (undampedFreq: number) => number;
|
|
133
|
+
const dampingRatio = bounceToDampingRatio(bounce);
|
|
134
|
+
duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, millisecondsToSeconds(duration));
|
|
135
|
+
if (dampingRatio < 1) {
|
|
136
|
+
envelope = (undampedFreq) => {
|
|
137
|
+
const exponentialDecay = undampedFreq * dampingRatio;
|
|
138
|
+
const delta = exponentialDecay * duration;
|
|
139
|
+
const b = calcAngularFreq(undampedFreq, dampingRatio);
|
|
140
|
+
const c = Math.exp(-delta);
|
|
141
|
+
return safeMin - (exponentialDecay / b) * c;
|
|
142
|
+
};
|
|
143
|
+
derivative = (undampedFreq) => {
|
|
144
|
+
const exponentialDecay = undampedFreq * dampingRatio;
|
|
145
|
+
const delta = exponentialDecay * duration;
|
|
146
|
+
const e = dampingRatio * dampingRatio * undampedFreq * undampedFreq * duration;
|
|
147
|
+
const f = Math.exp(-delta);
|
|
148
|
+
const g = calcAngularFreq(undampedFreq * undampedFreq, dampingRatio);
|
|
149
|
+
const factor = -envelope(undampedFreq) + safeMin > 0 ? -1 : 1;
|
|
150
|
+
return (factor * -e * f) / g;
|
|
151
|
+
};
|
|
152
|
+
} else {
|
|
153
|
+
// Critically damped; overdamped springs reuse this root, scaled below.
|
|
154
|
+
envelope = (undampedFreq) => {
|
|
155
|
+
const a = Math.exp(-undampedFreq * duration);
|
|
156
|
+
const b = undampedFreq * duration + 1;
|
|
157
|
+
return -safeMin + a * b;
|
|
158
|
+
};
|
|
159
|
+
derivative = (undampedFreq) => {
|
|
160
|
+
const a = Math.exp(-undampedFreq * duration);
|
|
161
|
+
const b = -undampedFreq * (duration * duration);
|
|
162
|
+
return a * b;
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
const initialGuess = 5 / duration;
|
|
166
|
+
const criticalFreq = approximateRoot(envelope, derivative, initialGuess);
|
|
167
|
+
const undampedFreq = criticalFreq * overdampedFreqScale(dampingRatio, criticalFreq * duration);
|
|
168
|
+
const stiffness = undampedFreq * undampedFreq;
|
|
169
|
+
return { stiffness, damping: dampingRatio * 2 * Math.sqrt(stiffness), duration: secondsToMilliseconds(duration) };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Stiffness and mass are divisors (positive); damping 0 is a valid perpetual oscillation. */
|
|
173
|
+
const isValidPhysics = (value: number | undefined, canBeZero = false): value is number =>
|
|
174
|
+
(canBeZero ? (value as number) >= 0 : (value as number) > 0) && (value as number) < Infinity;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* `spring({ keyframes: [from, to], velocity, stiffness, damping, mass })` or
|
|
178
|
+
* `spring({ keyframes: [from, to], duration, bounce })`. Physics, when valid, wins over
|
|
179
|
+
* duration/bounce; a duration/bounce spring that fails to resolve falls back to Motion's defaults.
|
|
180
|
+
*/
|
|
181
|
+
export function spring(options: SpringOptions): Generator {
|
|
182
|
+
const origin = options.from;
|
|
183
|
+
const target = options.to;
|
|
184
|
+
const state: GeneratorState = { done: false, value: origin };
|
|
185
|
+
|
|
186
|
+
const validStiffness = isValidPhysics(options.stiffness) ? options.stiffness : undefined;
|
|
187
|
+
const validDamping = isValidPhysics(options.damping, true) ? options.damping : undefined;
|
|
188
|
+
const validMass = isValidPhysics(options.mass) ? options.mass : undefined;
|
|
189
|
+
let stiffness = validStiffness ?? springDefaults.stiffness;
|
|
190
|
+
let damping = validDamping ?? springDefaults.damping;
|
|
191
|
+
const mass = validMass ?? springDefaults.mass;
|
|
192
|
+
let duration = 0;
|
|
193
|
+
let isResolvedFromDuration = false;
|
|
194
|
+
const isTimeDefined = (validStiffness ?? validDamping ?? validMass) === undefined
|
|
195
|
+
&& (options.duration !== undefined || options.bounce !== undefined);
|
|
196
|
+
if (isTimeDefined) {
|
|
197
|
+
const resolved = findSpring(options.duration ?? springDefaults.duration, options.bounce ?? springDefaults.bounce);
|
|
198
|
+
stiffness = resolved.stiffness;
|
|
199
|
+
damping = resolved.damping;
|
|
200
|
+
duration = resolved.duration;
|
|
201
|
+
isResolvedFromDuration = true;
|
|
202
|
+
// Degenerate time options (NaN bounce, no convergence): replace the pair together.
|
|
203
|
+
if (!isValidPhysics(stiffness) || !isValidPhysics(damping, true)) {
|
|
204
|
+
stiffness = springDefaults.stiffness;
|
|
205
|
+
damping = springDefaults.damping;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Time-defined springs ignore inherited velocity (it would oscillate small ranges heavily).
|
|
210
|
+
const inheritVelocity = (velocity: number) => (isTimeDefined ? 0 : -millisecondsToSeconds(velocity));
|
|
211
|
+
const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
|
|
212
|
+
const undampedAngularFreq = millisecondsToSeconds(Math.sqrt(stiffness / mass));
|
|
213
|
+
const decay = dampingRatio * undampedAngularFreq;
|
|
214
|
+
const delta = target - origin;
|
|
215
|
+
const velocity = inheritVelocity(options.velocity || 0) || 0;
|
|
216
|
+
const isGranularScale = Math.abs(delta) < 5;
|
|
217
|
+
const restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default;
|
|
218
|
+
const restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default;
|
|
219
|
+
|
|
220
|
+
let resolveSpring: (t: number) => number;
|
|
221
|
+
let resolveVelocity: (t: number) => number;
|
|
222
|
+
if (dampingRatio < 1) {
|
|
223
|
+
// Underdamped. exp/sin/cos depend only on t: memoised per t, as in Motion.
|
|
224
|
+
const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
|
|
225
|
+
const A = (velocity + decay * delta) / angularFreq;
|
|
226
|
+
const sinC = decay * A + delta * angularFreq;
|
|
227
|
+
const cosC = decay * delta - A * angularFreq;
|
|
228
|
+
const c = { t: -1, env: 0, sin: 0, cos: 0 };
|
|
229
|
+
const sample = (t: number) => {
|
|
230
|
+
if (t !== c.t) {
|
|
231
|
+
c.t = t;
|
|
232
|
+
c.env = Math.exp(-decay * t);
|
|
233
|
+
c.sin = Math.sin(angularFreq * t);
|
|
234
|
+
c.cos = Math.cos(angularFreq * t);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
resolveSpring = (t) => { sample(t); return target - c.env * (A * c.sin + delta * c.cos); };
|
|
238
|
+
resolveVelocity = (t) => { sample(t); return c.env * (sinC * c.sin + cosC * c.cos); };
|
|
239
|
+
} else if (dampingRatio === 1) {
|
|
240
|
+
// Critically damped.
|
|
241
|
+
const C = velocity + undampedAngularFreq * delta;
|
|
242
|
+
resolveSpring = (t) => target - Math.exp(-undampedAngularFreq * t) * (delta + (velocity + undampedAngularFreq * delta) * t);
|
|
243
|
+
resolveVelocity = (t) => Math.exp(-undampedAngularFreq * t) * (undampedAngularFreq * C * t - velocity);
|
|
244
|
+
} else {
|
|
245
|
+
// Overdamped: a slow and a fast decaying exponential, so no term overflows.
|
|
246
|
+
const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
|
|
247
|
+
const slow = decay - dampedAngularFreq;
|
|
248
|
+
const fast = decay + dampedAngularFreq;
|
|
249
|
+
// Physics-defined springs settle at the damping rate once dampedAngularFreq·t passes 300;
|
|
250
|
+
// time-defined (negative bounce) springs keep the exact curve.
|
|
251
|
+
const limit = isTimeDefined ? Infinity : 300 / dampedAngularFreq;
|
|
252
|
+
const decayAt = (rate: number, t: number) => Math.exp(t > limit ? -rate * limit - decay * (t - limit) : -rate * t);
|
|
253
|
+
const P = (velocity + decay * delta) / dampedAngularFreq;
|
|
254
|
+
const S = (delta + P) / 2;
|
|
255
|
+
const F = (delta - P) / 2;
|
|
256
|
+
resolveSpring = (t) => target - S * decayAt(slow, t) - F * decayAt(fast, t);
|
|
257
|
+
resolveVelocity = (t) => slow * S * decayAt(slow, t) + fast * F * decayAt(fast, t);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
velocity: (t) => secondsToMilliseconds(resolveVelocity(t)),
|
|
262
|
+
next: (t) => {
|
|
263
|
+
const current = resolveSpring(t);
|
|
264
|
+
if (!isResolvedFromDuration) {
|
|
265
|
+
const currentVelocity = secondsToMilliseconds(resolveVelocity(t));
|
|
266
|
+
state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current) <= restDelta;
|
|
267
|
+
} else {
|
|
268
|
+
state.done = t >= duration;
|
|
269
|
+
}
|
|
270
|
+
state.value = state.done ? target : current;
|
|
271
|
+
return state;
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|