@barqjs/aria 0.0.0-stage → 0.2.0-next.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/LICENSE +21 -0
- package/README.md +293 -2
- package/package.json +347 -4
- package/src/breadcrumbs.tsx +296 -0
- package/src/button.tsx +342 -0
- package/src/calendar.tsx +1389 -0
- package/src/checkbox.tsx +570 -0
- package/src/collections.ts +976 -0
- package/src/color.ts +562 -0
- package/src/colorpicker.tsx +1478 -0
- package/src/combobox.tsx +2481 -0
- package/src/command.tsx +1184 -0
- package/src/date.ts +652 -0
- package/src/datefield.tsx +951 -0
- package/src/datepicker.tsx +556 -0
- package/src/dialog.tsx +890 -0
- package/src/disclosure.tsx +659 -0
- package/src/dom.ts +706 -0
- package/src/drawer.ts +674 -0
- package/src/focus.ts +1370 -0
- package/src/form.tsx +94 -0
- package/src/gridlist.tsx +563 -0
- package/src/i18n.ts +823 -0
- package/src/index.ts +1270 -0
- package/src/interactions/description.ts +73 -0
- package/src/interactions/flags.ts +35 -0
- package/src/interactions/focus-events.ts +218 -0
- package/src/interactions/focusable.ts +86 -0
- package/src/interactions/hover.ts +213 -0
- package/src/interactions/interact-outside.ts +123 -0
- package/src/interactions/keyboard.ts +105 -0
- package/src/interactions/listeners.ts +78 -0
- package/src/interactions/long-press.ts +160 -0
- package/src/interactions/modality.ts +416 -0
- package/src/interactions/move.ts +257 -0
- package/src/interactions/open-link.ts +193 -0
- package/src/interactions/press.ts +898 -0
- package/src/interactions/prevent-focus.ts +102 -0
- package/src/interactions/scroll-wheel.ts +43 -0
- package/src/interactions/text-selection.ts +77 -0
- package/src/interactions.ts +81 -0
- package/src/label.ts +128 -0
- package/src/link.tsx +381 -0
- package/src/listbox.tsx +721 -0
- package/src/live.ts +204 -0
- package/src/menu.tsx +2290 -0
- package/src/menubar.tsx +575 -0
- package/src/navigation.ts +735 -0
- package/src/numberfield.tsx +838 -0
- package/src/otp.ts +430 -0
- package/src/overlays.ts +1247 -0
- package/src/platform.ts +74 -0
- package/src/presence.ts +164 -0
- package/src/questionnaire.tsx +1712 -0
- package/src/radio.tsx +567 -0
- package/src/register-dom.ts +12 -0
- package/src/scroller.ts +1165 -0
- package/src/select.tsx +1665 -0
- package/src/selection.ts +1415 -0
- package/src/slider.tsx +1042 -0
- package/src/splitter.ts +1152 -0
- package/src/static-collection.ts +211 -0
- package/src/switch.tsx +186 -0
- package/src/table.tsx +0 -0
- package/src/tabs.tsx +1018 -0
- package/src/tag.tsx +452 -0
- package/src/textfield.tsx +417 -0
- package/src/toast.ts +658 -0
- package/src/toggle-input.tsx +48 -0
- package/src/toggle.ts +321 -0
- package/src/togglegroup.ts +365 -0
- package/src/toolbar.tsx +179 -0
- package/src/tooltip.tsx +657 -0
- package/src/utils.ts +758 -0
- package/src/validation.ts +447 -0
- package/src/virtualizer.tsx +674 -0
package/src/toast.ts
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A queue of toasts, and the timers that take them away.
|
|
3
|
+
*
|
|
4
|
+
* This is the piece `@barqjs/ui`'s `<Toaster>` needed. shadcn's is the `sonner`
|
|
5
|
+
* package, which is React to its foundations, so the engine is written here and
|
|
6
|
+
* only the shape of it is upstream's.
|
|
7
|
+
*
|
|
8
|
+
* Four things are decisions rather than details.
|
|
9
|
+
*
|
|
10
|
+
* **A toast is announced, not focused.** Moving focus to something that appeared
|
|
11
|
+
* on its own takes the keyboard away from whatever the person was doing, so the
|
|
12
|
+
* region is a live one and the toast waits to be reached. That is why `dismiss`
|
|
13
|
+
* is on the toast and not only on a timer: something has to be able to remove
|
|
14
|
+
* it deliberately.
|
|
15
|
+
*
|
|
16
|
+
* **The timer pauses.** A toast that expires while the pointer is over it, or
|
|
17
|
+
* while the tab is in the background, was never read. Hovering the region stops
|
|
18
|
+
* every timer in it, and leaving starts them again from where they stopped.
|
|
19
|
+
*
|
|
20
|
+
* **A queue has a limit and it is visible.** Beyond it the oldest goes, because
|
|
21
|
+
* the alternative is a column that grows past the viewport and hides the newest
|
|
22
|
+
* behind the ones it replaced.
|
|
23
|
+
*
|
|
24
|
+
* **An id is returned so the caller can update.** A promise that resolves wants
|
|
25
|
+
* to become "Saved" rather than stack a second toast under "Saving"; without an
|
|
26
|
+
* id there is no way to say which one.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { createSignal, type Accessor, type Child } from "@barqjs/core";
|
|
30
|
+
import { isServer } from "@barqjs/web";
|
|
31
|
+
|
|
32
|
+
import { access, type MaybeAccessor } from "./utils.ts";
|
|
33
|
+
|
|
34
|
+
export type ToastKind = "default" | "success" | "info" | "warning" | "error" | "loading";
|
|
35
|
+
|
|
36
|
+
export type ToastId = number | string;
|
|
37
|
+
|
|
38
|
+
/** Text, or something that builds what to draw in its place. */
|
|
39
|
+
export type ToastContent = string | (() => Child);
|
|
40
|
+
|
|
41
|
+
export interface ToastButton {
|
|
42
|
+
readonly label: ToastContent;
|
|
43
|
+
/** Handed the event that pressed it, when there was one. */
|
|
44
|
+
readonly onAction: (event?: Event) => void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ToastOptions<D = unknown> {
|
|
48
|
+
/**
|
|
49
|
+
* Which toast this is. One already up under the same id is replaced in
|
|
50
|
+
* place, so a caller that names its toasts cannot stack two of one thing.
|
|
51
|
+
*/
|
|
52
|
+
readonly id?: ToastId;
|
|
53
|
+
readonly title?: ToastContent;
|
|
54
|
+
readonly description?: ToastContent;
|
|
55
|
+
/** @default "default" */
|
|
56
|
+
readonly kind?: ToastKind;
|
|
57
|
+
/**
|
|
58
|
+
* How long before it goes, in ms. `Infinity` keeps it, and a `loading` toast
|
|
59
|
+
* has no clock whatever this says. @default 4000
|
|
60
|
+
*/
|
|
61
|
+
readonly duration?: number;
|
|
62
|
+
/** A button on the toast, and what it does. */
|
|
63
|
+
readonly action?: ToastButton;
|
|
64
|
+
/** A second button, for declining what the first one offers. */
|
|
65
|
+
readonly cancel?: ToastButton;
|
|
66
|
+
/** Whether a person can take it away themselves. @default true */
|
|
67
|
+
readonly dismissible?: boolean;
|
|
68
|
+
/** `high` interrupts a screen reader; `low` waits its turn. @default "low" */
|
|
69
|
+
readonly priority?: "low" | "high";
|
|
70
|
+
/** Told when it goes, however it went. */
|
|
71
|
+
readonly onDismiss?: () => void;
|
|
72
|
+
/** Told only when its own clock took it. */
|
|
73
|
+
readonly onAutoClose?: () => void;
|
|
74
|
+
/** Whatever the design system drawing it needs to carry along. */
|
|
75
|
+
readonly data?: D;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface Toast<D = unknown> extends ToastOptions<D> {
|
|
79
|
+
readonly id: ToastId;
|
|
80
|
+
/** When the remaining time was last measured, so pausing can be resumed. */
|
|
81
|
+
readonly kind: ToastKind;
|
|
82
|
+
readonly duration: number;
|
|
83
|
+
/** Decided to go, and still being drawn on its way out. */
|
|
84
|
+
readonly isLeaving?: boolean;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** A message for one outcome: the title alone, or the whole toast. */
|
|
88
|
+
export type ToastMessage<D = unknown> = ToastContent | ToastOptions<D>;
|
|
89
|
+
|
|
90
|
+
export interface ToastPromiseMessages<T, D = unknown> {
|
|
91
|
+
readonly loading: ToastMessage<D>;
|
|
92
|
+
readonly success: ToastMessage<D> | ((value: T) => ToastMessage<D>);
|
|
93
|
+
readonly error: ToastMessage<D> | ((reason: unknown) => ToastMessage<D>);
|
|
94
|
+
readonly finally?: () => void;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The work's own promise, with the id of the toast that is following it. */
|
|
98
|
+
export interface ToastPromise<T> extends Promise<T> {
|
|
99
|
+
readonly id: ToastId;
|
|
100
|
+
unwrap(): Promise<T>;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ToastQueueOptions {
|
|
104
|
+
/** How many are on screen at once. @default 3 */
|
|
105
|
+
limit?: MaybeAccessor<number | undefined>;
|
|
106
|
+
/** The default lifetime. @default 4000 */
|
|
107
|
+
duration?: MaybeAccessor<number | undefined>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface ToastQueue<D = unknown> {
|
|
111
|
+
readonly toasts: Accessor<readonly Toast<D>[]>;
|
|
112
|
+
/** Adds one and returns its id, which is what an update needs. */
|
|
113
|
+
add<I extends ToastId = number>(options: ToastOptions<D> & { readonly id?: I }): I;
|
|
114
|
+
/** Replaces one in place, keeping its position. Unknown ids are ignored. */
|
|
115
|
+
update(id: ToastId, options: ToastOptions<D>): void;
|
|
116
|
+
/** Takes one away, or every one when no id is given. */
|
|
117
|
+
dismiss(id?: ToastId): void;
|
|
118
|
+
get(id: ToastId): Toast<D> | undefined;
|
|
119
|
+
clear(): void;
|
|
120
|
+
/**
|
|
121
|
+
* Stop every timer, which is what entering the region does.
|
|
122
|
+
*
|
|
123
|
+
* A reason is held until the same reason is given back, so the pointer
|
|
124
|
+
* leaving does not restart clocks a hidden tab stopped.
|
|
125
|
+
*/
|
|
126
|
+
pause(reason?: string): void;
|
|
127
|
+
/** Start them again from the time each had left. */
|
|
128
|
+
resume(reason?: string): void;
|
|
129
|
+
readonly isPaused: Accessor<boolean>;
|
|
130
|
+
/** Pauses while the document is hidden. Returns what stops watching. */
|
|
131
|
+
watchDocument(target?: Document): () => void;
|
|
132
|
+
/**
|
|
133
|
+
* Asks how long a toast needs to be drawn leaving, in ms.
|
|
134
|
+
*
|
|
135
|
+
* Asked at the moment it is dismissed. Above zero the toast stays in the
|
|
136
|
+
* list marked `isLeaving` for that long; at zero, or with nobody to ask, it
|
|
137
|
+
* goes at once. Returns what withdraws the question.
|
|
138
|
+
*/
|
|
139
|
+
onLeave(measure: (id: ToastId) => number): () => void;
|
|
140
|
+
/**
|
|
141
|
+
* `loading` while the work runs, then `success` or `error` on the same toast.
|
|
142
|
+
*
|
|
143
|
+
* Given a function, the work starts after the toast is up.
|
|
144
|
+
*/
|
|
145
|
+
promise<T>(
|
|
146
|
+
work: Promise<T> | (() => Promise<T>),
|
|
147
|
+
messages: ToastPromiseMessages<T, D>,
|
|
148
|
+
): ToastPromise<T>;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const DEFAULT_LIMIT = 3;
|
|
152
|
+
const DEFAULT_DURATION = 4000;
|
|
153
|
+
|
|
154
|
+
interface Timer {
|
|
155
|
+
handle: ReturnType<typeof setTimeout> | null;
|
|
156
|
+
/** What is left of the duration, in ms. */
|
|
157
|
+
remaining: number;
|
|
158
|
+
/** When the current run started, for working out what is left on a pause. */
|
|
159
|
+
startedAt: number;
|
|
160
|
+
/** False for a toast that waits on work rather than on a clock. */
|
|
161
|
+
runs: boolean;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const POINTER = "pointer";
|
|
165
|
+
const HIDDEN = "hidden";
|
|
166
|
+
|
|
167
|
+
function isOptions<D>(message: ToastMessage<D>): message is ToastOptions<D> {
|
|
168
|
+
return typeof message === "object";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function messageOptions<D>(message: ToastMessage<D>): ToastOptions<D> {
|
|
172
|
+
return isOptions(message) ? message : { title: message };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Whether a function is content to draw rather than a message to work out.
|
|
177
|
+
*
|
|
178
|
+
* Both are functions. One that takes the outcome declares a parameter for it;
|
|
179
|
+
* one that builds what to draw declares none, and has to be left alone until
|
|
180
|
+
* something is drawing, because building outside a render has no scope to
|
|
181
|
+
* build in.
|
|
182
|
+
*/
|
|
183
|
+
function isBuilder(message: (...given: never[]) => unknown): message is () => Child {
|
|
184
|
+
return message.length === 0;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export function toastQueue<D = unknown>(options: ToastQueueOptions = {}): ToastQueue<D> {
|
|
188
|
+
const [toasts, setToasts] = createSignal<readonly Toast<D>[]>([]);
|
|
189
|
+
const [paused, setPaused] = createSignal(false);
|
|
190
|
+
// The timers' own copy. `paused()` is a published value and the pause is not
|
|
191
|
+
// published until the flush, so `resume()` starting the clocks it just
|
|
192
|
+
// un-paused would read itself as still paused and start nothing.
|
|
193
|
+
let isPaused = false;
|
|
194
|
+
const reasons = new Set<string>();
|
|
195
|
+
const timers = new Map<ToastId, Timer>();
|
|
196
|
+
const leaving = new Map<ToastId, ReturnType<typeof setTimeout>>();
|
|
197
|
+
// The list as of the last write. A dismissal in the same tick as the add has
|
|
198
|
+
// to find the toast, and the published list does not hold it yet.
|
|
199
|
+
let current: readonly Toast<D>[] = [];
|
|
200
|
+
let measureLeave: ((id: ToastId) => number) | null = null;
|
|
201
|
+
let nextId = 1;
|
|
202
|
+
|
|
203
|
+
const write = (next: (prev: readonly Toast<D>[]) => readonly Toast<D>[]): void => {
|
|
204
|
+
current = next(current);
|
|
205
|
+
const settled = current;
|
|
206
|
+
setToasts(() => settled);
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const stop = (id: ToastId): void => {
|
|
210
|
+
const timer = timers.get(id);
|
|
211
|
+
if (timer !== undefined && timer.handle !== null) {
|
|
212
|
+
clearTimeout(timer.handle);
|
|
213
|
+
timer.handle = null;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const drop = (id: ToastId): void => {
|
|
218
|
+
const pending = leaving.get(id);
|
|
219
|
+
if (pending !== undefined) clearTimeout(pending);
|
|
220
|
+
leaving.delete(id);
|
|
221
|
+
write((prev) => prev.filter((each) => each.id !== id));
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const remove = (id: ToastId, byTimer = false): void => {
|
|
225
|
+
stop(id);
|
|
226
|
+
timers.delete(id);
|
|
227
|
+
const going = current.find((each) => each.id === id);
|
|
228
|
+
if (going === undefined || going.isLeaving === true) return;
|
|
229
|
+
|
|
230
|
+
const lasts = measureLeave?.(id) ?? 0;
|
|
231
|
+
if (lasts > 0) {
|
|
232
|
+
write((prev) => prev.map((each) => (each.id === id ? { ...each, isLeaving: true } : each)));
|
|
233
|
+
leaving.set(
|
|
234
|
+
id,
|
|
235
|
+
setTimeout(() => drop(id), lasts),
|
|
236
|
+
);
|
|
237
|
+
} else {
|
|
238
|
+
drop(id);
|
|
239
|
+
}
|
|
240
|
+
if (byTimer) going.onAutoClose?.();
|
|
241
|
+
going.onDismiss?.();
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
const start = (id: ToastId): void => {
|
|
245
|
+
const timer = timers.get(id);
|
|
246
|
+
// A toast raised while a server renders is drawn once and sent. A clock
|
|
247
|
+
// there takes nothing away, and holds the process open until it runs out.
|
|
248
|
+
if (isServer) return;
|
|
249
|
+
if (timer === undefined || isPaused || !timer.runs) return;
|
|
250
|
+
// `Infinity` is the documented way to keep one, and `setTimeout` would
|
|
251
|
+
// treat it as zero and take it away at once.
|
|
252
|
+
if (!Number.isFinite(timer.remaining)) return;
|
|
253
|
+
timer.startedAt = Date.now();
|
|
254
|
+
timer.handle = setTimeout(() => remove(id, true), timer.remaining);
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const clock = (toast: Toast<D>): void => {
|
|
258
|
+
stop(toast.id);
|
|
259
|
+
timers.set(toast.id, {
|
|
260
|
+
handle: null,
|
|
261
|
+
remaining: toast.duration,
|
|
262
|
+
startedAt: Date.now(),
|
|
263
|
+
// Work in flight decides when its toast goes; a timer would take it
|
|
264
|
+
// away before the answer.
|
|
265
|
+
runs: toast.kind !== "loading",
|
|
266
|
+
});
|
|
267
|
+
start(toast.id);
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
const fallbackDuration = (): number => access(options.duration) ?? DEFAULT_DURATION;
|
|
271
|
+
|
|
272
|
+
const update = (id: ToastId, given: ToastOptions<D>): void => {
|
|
273
|
+
const before = current.find((each) => each.id === id);
|
|
274
|
+
if (before === undefined) return;
|
|
275
|
+
const pending = leaving.get(id);
|
|
276
|
+
if (pending !== undefined) clearTimeout(pending);
|
|
277
|
+
leaving.delete(id);
|
|
278
|
+
const next: Toast<D> = {
|
|
279
|
+
...before,
|
|
280
|
+
...given,
|
|
281
|
+
id,
|
|
282
|
+
kind: given.kind ?? before.kind,
|
|
283
|
+
duration: given.duration ?? before.duration,
|
|
284
|
+
isLeaving: false,
|
|
285
|
+
};
|
|
286
|
+
// In PLACE, so a "Saving" that becomes "Saved" does not jump to the
|
|
287
|
+
// bottom of the column and read as a second thing happening.
|
|
288
|
+
write((prev) => prev.map((each) => (each.id === id ? next : each)));
|
|
289
|
+
clock(next);
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const add = <I extends ToastId = number>(given: ToastOptions<D> & { readonly id?: I }): I => {
|
|
293
|
+
if (given.id !== undefined && current.some((each) => each.id === given.id)) {
|
|
294
|
+
update(given.id, given);
|
|
295
|
+
return given.id;
|
|
296
|
+
}
|
|
297
|
+
const id: ToastId = given.id ?? nextId++;
|
|
298
|
+
const toast: Toast<D> = {
|
|
299
|
+
...given,
|
|
300
|
+
id,
|
|
301
|
+
kind: given.kind ?? "default",
|
|
302
|
+
duration: given.duration ?? fallbackDuration(),
|
|
303
|
+
};
|
|
304
|
+
const limit = access(options.limit) ?? DEFAULT_LIMIT;
|
|
305
|
+
write((prev) => {
|
|
306
|
+
// The OLDEST goes. Dropping the newest would mean the thing that just
|
|
307
|
+
// happened is the one nobody is told about.
|
|
308
|
+
const kept = [...prev, toast].slice(-Math.max(1, limit));
|
|
309
|
+
for (const each of prev) {
|
|
310
|
+
if (!kept.some((one) => one.id === each.id)) {
|
|
311
|
+
stop(each.id);
|
|
312
|
+
timers.delete(each.id);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return kept;
|
|
316
|
+
});
|
|
317
|
+
clock(toast);
|
|
318
|
+
return id as I;
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
const hold = (reason: string): void => {
|
|
322
|
+
reasons.add(reason);
|
|
323
|
+
if (isPaused) return;
|
|
324
|
+
isPaused = true;
|
|
325
|
+
setPaused(true);
|
|
326
|
+
const now = Date.now();
|
|
327
|
+
for (const [id, timer] of timers) {
|
|
328
|
+
if (timer.handle === null) continue;
|
|
329
|
+
// What is LEFT, not the whole duration: pausing twice would otherwise
|
|
330
|
+
// give a toast its full life back each time the pointer crossed it.
|
|
331
|
+
timer.remaining = Math.max(0, timer.remaining - (now - timer.startedAt));
|
|
332
|
+
stop(id);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const release = (reason: string): void => {
|
|
337
|
+
reasons.delete(reason);
|
|
338
|
+
if (!isPaused || reasons.size > 0) return;
|
|
339
|
+
isPaused = false;
|
|
340
|
+
setPaused(false);
|
|
341
|
+
for (const id of timers.keys()) start(id);
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
return {
|
|
345
|
+
toasts,
|
|
346
|
+
isPaused: paused,
|
|
347
|
+
add,
|
|
348
|
+
update,
|
|
349
|
+
get: (id) => current.find((each) => each.id === id),
|
|
350
|
+
dismiss(id) {
|
|
351
|
+
if (id !== undefined) {
|
|
352
|
+
remove(id);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
for (const each of current) remove(each.id);
|
|
356
|
+
},
|
|
357
|
+
clear() {
|
|
358
|
+
for (const each of current) stop(each.id);
|
|
359
|
+
for (const pending of leaving.values()) clearTimeout(pending);
|
|
360
|
+
leaving.clear();
|
|
361
|
+
timers.clear();
|
|
362
|
+
write(() => []);
|
|
363
|
+
},
|
|
364
|
+
pause: (reason = POINTER) => hold(reason),
|
|
365
|
+
resume: (reason = POINTER) => release(reason),
|
|
366
|
+
watchDocument(target) {
|
|
367
|
+
const watched = target ?? (typeof document === "undefined" ? undefined : document);
|
|
368
|
+
if (watched === undefined) return () => {};
|
|
369
|
+
// A toast that ran out in a background tab was never seen at all.
|
|
370
|
+
const sync = (): void => {
|
|
371
|
+
if (watched.hidden) hold(HIDDEN);
|
|
372
|
+
else release(HIDDEN);
|
|
373
|
+
};
|
|
374
|
+
watched.addEventListener("visibilitychange", sync);
|
|
375
|
+
sync();
|
|
376
|
+
return () => {
|
|
377
|
+
watched.removeEventListener("visibilitychange", sync);
|
|
378
|
+
release(HIDDEN);
|
|
379
|
+
};
|
|
380
|
+
},
|
|
381
|
+
onLeave(measure) {
|
|
382
|
+
measureLeave = measure;
|
|
383
|
+
return () => {
|
|
384
|
+
if (measureLeave === measure) measureLeave = null;
|
|
385
|
+
};
|
|
386
|
+
},
|
|
387
|
+
promise<T>(
|
|
388
|
+
work: Promise<T> | (() => Promise<T>),
|
|
389
|
+
messages: ToastPromiseMessages<T, D>,
|
|
390
|
+
): ToastPromise<T> {
|
|
391
|
+
const id = add({ ...messageOptions(messages.loading), kind: "loading" });
|
|
392
|
+
const { finally: afterwards } = messages;
|
|
393
|
+
const settle = (kind: ToastKind, message: ToastMessage<D>): void => {
|
|
394
|
+
const given = messageOptions(message);
|
|
395
|
+
// The loading toast's lifetime was never used, so the outcome gets a
|
|
396
|
+
// whole one rather than whatever "no clock" left behind. A message
|
|
397
|
+
// that names its own kind keeps it: work can resolve with a failure.
|
|
398
|
+
update(id, {
|
|
399
|
+
...given,
|
|
400
|
+
kind: given.kind ?? kind,
|
|
401
|
+
duration: given.duration ?? fallbackDuration(),
|
|
402
|
+
});
|
|
403
|
+
};
|
|
404
|
+
const run = async (): Promise<T> => {
|
|
405
|
+
try {
|
|
406
|
+
const value = await (typeof work === "function" ? work() : work);
|
|
407
|
+
settle(
|
|
408
|
+
"success",
|
|
409
|
+
typeof messages.success === "function" && !isBuilder(messages.success)
|
|
410
|
+
? messages.success(value)
|
|
411
|
+
: messages.success,
|
|
412
|
+
);
|
|
413
|
+
return value;
|
|
414
|
+
} catch (reason) {
|
|
415
|
+
settle(
|
|
416
|
+
"error",
|
|
417
|
+
typeof messages.error === "function" && !isBuilder(messages.error)
|
|
418
|
+
? messages.error(reason)
|
|
419
|
+
: messages.error,
|
|
420
|
+
);
|
|
421
|
+
throw reason;
|
|
422
|
+
} finally {
|
|
423
|
+
afterwards?.();
|
|
424
|
+
}
|
|
425
|
+
};
|
|
426
|
+
const result = run();
|
|
427
|
+
// A caller that only wants the toast never awaits this, and a failure
|
|
428
|
+
// it was already shown must not also surface as an unhandled rejection.
|
|
429
|
+
result.catch(() => {});
|
|
430
|
+
return Object.assign(result, { id, unwrap: () => result });
|
|
431
|
+
},
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
export type ToastSwipeDirection = "up" | "down" | "left" | "right";
|
|
436
|
+
|
|
437
|
+
/** How far it has to be dragged before letting go throws it away, in px. */
|
|
438
|
+
const SWIPE_THRESHOLD = 45;
|
|
439
|
+
/** px per ms past which a flick throws it away however short it was. */
|
|
440
|
+
const SWIPE_VELOCITY = 0.11;
|
|
441
|
+
/** How far a pointer moves before the swipe has an axis. */
|
|
442
|
+
const SWIPE_SLOP = 1;
|
|
443
|
+
/** How far back from the furthest point a pull has to come to be called off, in px. */
|
|
444
|
+
const REVERSE_CANCEL = 10;
|
|
445
|
+
|
|
446
|
+
export interface ToastSwipeOptions {
|
|
447
|
+
/** The ways it can be thrown. Any other way is resisted. */
|
|
448
|
+
directions: MaybeAccessor<readonly ToastSwipeDirection[]>;
|
|
449
|
+
/**
|
|
450
|
+
* A pull brought back toward where it started is called off, as Base UI's
|
|
451
|
+
* is. Sonner's is not. @default false
|
|
452
|
+
*/
|
|
453
|
+
reverseCancels?: MaybeAccessor<boolean | undefined>;
|
|
454
|
+
/** @default 45 */
|
|
455
|
+
threshold?: MaybeAccessor<number | undefined>;
|
|
456
|
+
/** @default 0.11 */
|
|
457
|
+
velocity?: MaybeAccessor<number | undefined>;
|
|
458
|
+
onDismiss?: (direction: ToastSwipeDirection) => void;
|
|
459
|
+
/** Told when a tracked pointer takes hold of the toast, and when it lets go. */
|
|
460
|
+
onHold?: (isHeld: boolean) => void;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
export interface ToastSwipe {
|
|
464
|
+
/** Where the pointer has taken it, in px from where it rests. */
|
|
465
|
+
readonly offset: Accessor<{ readonly x: number; readonly y: number }>;
|
|
466
|
+
readonly isSwiping: Accessor<boolean>;
|
|
467
|
+
/** The way it was thrown, once it has been. */
|
|
468
|
+
readonly direction: Accessor<ToastSwipeDirection | null>;
|
|
469
|
+
start(point: { readonly x: number; readonly y: number }): void;
|
|
470
|
+
move(point: { readonly x: number; readonly y: number }): void;
|
|
471
|
+
/** Ends the swipe, and answers whether it threw the toast away. */
|
|
472
|
+
end(): boolean;
|
|
473
|
+
/** Ends it where it started: a cancelled pointer took no decision. */
|
|
474
|
+
cancel(): void;
|
|
475
|
+
/**
|
|
476
|
+
* Starts a swipe from a `pointerdown` on the toast and follows the pointer
|
|
477
|
+
* to its end. Answers whether it took the gesture: a press on a control
|
|
478
|
+
* inside the toast, or with any but the main button, is left alone.
|
|
479
|
+
*/
|
|
480
|
+
track(event: PointerEvent, toast: Element): boolean;
|
|
481
|
+
/** Lets go of a tracked pointer, for a toast that leaves mid-gesture. */
|
|
482
|
+
release(): void;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** A control the pointer belongs to, whatever the toast would rather do. */
|
|
486
|
+
function ownsPointer(target: EventTarget | null, toast: Element): boolean {
|
|
487
|
+
if (!(target instanceof Element)) return false;
|
|
488
|
+
const control = target.closest("button, a, input, select, textarea, [role='button']");
|
|
489
|
+
return control !== null && toast.contains(control);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** The pull kept when dragging a way the toast does not go. */
|
|
493
|
+
function resisted(delta: number): number {
|
|
494
|
+
return delta / (1.5 + Math.abs(delta) / 20);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* A toast that follows the pointer and can be thrown away.
|
|
499
|
+
*
|
|
500
|
+
* Three decisions.
|
|
501
|
+
*
|
|
502
|
+
* **One axis a swipe.** The first direction the pointer moves in is the one it
|
|
503
|
+
* keeps, because a toast that drifts diagonally under a thumb reads as broken
|
|
504
|
+
* and a diagonal has no single way to leave by.
|
|
505
|
+
*
|
|
506
|
+
* **Distance or speed.** A slow drag past the threshold and a short flick both
|
|
507
|
+
* mean "away", and requiring both makes a flick on a phone do nothing.
|
|
508
|
+
*
|
|
509
|
+
* **The wrong way gives, and never dismisses.** It moves a little so the
|
|
510
|
+
* gesture is answered, and springs back however hard it was pulled: a toast
|
|
511
|
+
* anchored to the bottom that leaves upward crosses the page it was beside.
|
|
512
|
+
*/
|
|
513
|
+
export function toastSwipe(options: ToastSwipeOptions): ToastSwipe {
|
|
514
|
+
const rest = { x: 0, y: 0 } as const;
|
|
515
|
+
const [trackOffset, setOffset] = createSignal<{ readonly x: number; readonly y: number }>(rest);
|
|
516
|
+
const [swiping, setSwiping] = createSignal(false);
|
|
517
|
+
const [direction, setDirection] = createSignal<ToastSwipeDirection | null>(null);
|
|
518
|
+
// The gesture's own copies. A pointer stream is read in the tick it is
|
|
519
|
+
// written, and a signal write is not published until the flush.
|
|
520
|
+
let isSwiping = false;
|
|
521
|
+
let from = { x: 0, y: 0 };
|
|
522
|
+
let at: { readonly x: number; readonly y: number } = rest;
|
|
523
|
+
let axis: "x" | "y" | null = null;
|
|
524
|
+
let startedAt = 0;
|
|
525
|
+
// The furthest the pull went the way it is going, for telling a change of
|
|
526
|
+
// mind from a wobble.
|
|
527
|
+
let furthest = 0;
|
|
528
|
+
|
|
529
|
+
const offset = (): { readonly x: number; readonly y: number } => {
|
|
530
|
+
trackOffset();
|
|
531
|
+
return at;
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
const place = (next: { readonly x: number; readonly y: number }): void => {
|
|
535
|
+
at = next;
|
|
536
|
+
setOffset(next);
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
const allows = (way: ToastSwipeDirection): boolean => access(options.directions).includes(way);
|
|
540
|
+
|
|
541
|
+
const wayOf = (along: "x" | "y", amount: number): ToastSwipeDirection =>
|
|
542
|
+
along === "x" ? (amount > 0 ? "right" : "left") : amount > 0 ? "down" : "up";
|
|
543
|
+
|
|
544
|
+
const reset = (): void => {
|
|
545
|
+
isSwiping = false;
|
|
546
|
+
axis = null;
|
|
547
|
+
setSwiping(false);
|
|
548
|
+
place(rest);
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
const start = (point: { readonly x: number; readonly y: number }): void => {
|
|
552
|
+
from = { x: point.x, y: point.y };
|
|
553
|
+
axis = null;
|
|
554
|
+
furthest = 0;
|
|
555
|
+
startedAt = Date.now();
|
|
556
|
+
isSwiping = true;
|
|
557
|
+
setDirection(null);
|
|
558
|
+
setSwiping(true);
|
|
559
|
+
place(rest);
|
|
560
|
+
};
|
|
561
|
+
|
|
562
|
+
const move = (point: { readonly x: number; readonly y: number }): void => {
|
|
563
|
+
if (!isSwiping) return;
|
|
564
|
+
const dx = point.x - from.x;
|
|
565
|
+
const dy = point.y - from.y;
|
|
566
|
+
if (axis === null) {
|
|
567
|
+
if (Math.abs(dx) <= SWIPE_SLOP && Math.abs(dy) <= SWIPE_SLOP) return;
|
|
568
|
+
axis = Math.abs(dx) > Math.abs(dy) ? "x" : "y";
|
|
569
|
+
}
|
|
570
|
+
const delta = axis === "x" ? dx : dy;
|
|
571
|
+
// Resistance answers a pull the wrong way along an axis the toast does
|
|
572
|
+
// leave by. Along one it never leaves by there is nothing to answer.
|
|
573
|
+
const leavesAlong =
|
|
574
|
+
axis === "x" ? allows("left") || allows("right") : allows("up") || allows("down");
|
|
575
|
+
const amount = !leavesAlong ? 0 : allows(wayOf(axis, delta)) ? delta : resisted(delta);
|
|
576
|
+
furthest = Math.max(furthest, Math.abs(amount));
|
|
577
|
+
place(axis === "x" ? { x: amount, y: 0 } : { x: 0, y: amount });
|
|
578
|
+
};
|
|
579
|
+
|
|
580
|
+
const end = (): boolean => {
|
|
581
|
+
if (!isSwiping) return false;
|
|
582
|
+
const along = axis;
|
|
583
|
+
const amount = along === "x" ? at.x : at.y;
|
|
584
|
+
const way = along === null || amount === 0 ? null : wayOf(along, amount);
|
|
585
|
+
// At least a millisecond, so a move and a release in the same one is a
|
|
586
|
+
// fast flick rather than a division by zero.
|
|
587
|
+
const elapsed = Math.max(1, Date.now() - startedAt);
|
|
588
|
+
const far = Math.abs(amount) >= (access(options.threshold) ?? SWIPE_THRESHOLD);
|
|
589
|
+
const fast = Math.abs(amount) / elapsed > (access(options.velocity) ?? SWIPE_VELOCITY);
|
|
590
|
+
// Brought back toward where it started, it was not meant: Base UI's
|
|
591
|
+
// reverse-to-cancel. Along an axis it leaves by both ways, coming back is
|
|
592
|
+
// a throw the other way instead, so there is nothing to call off.
|
|
593
|
+
const bothWays =
|
|
594
|
+
along === "x" ? allows("left") && allows("right") : allows("up") && allows("down");
|
|
595
|
+
const changedMind =
|
|
596
|
+
access(options.reverseCancels) === true &&
|
|
597
|
+
!bothWays &&
|
|
598
|
+
furthest - Math.abs(amount) >= REVERSE_CANCEL;
|
|
599
|
+
if (way !== null && allows(way) && (far || fast) && !changedMind) {
|
|
600
|
+
// The offset stays where the pointer left it: the exit starts from
|
|
601
|
+
// there, and snapping back first would throw it from the wrong place.
|
|
602
|
+
isSwiping = false;
|
|
603
|
+
axis = null;
|
|
604
|
+
setSwiping(false);
|
|
605
|
+
setDirection(way);
|
|
606
|
+
options.onDismiss?.(way);
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
reset();
|
|
610
|
+
return false;
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
let tracking = false;
|
|
614
|
+
const onMove = (event: PointerEvent): void => {
|
|
615
|
+
move({ x: event.clientX, y: event.clientY });
|
|
616
|
+
};
|
|
617
|
+
const release = (): void => {
|
|
618
|
+
if (!tracking) return;
|
|
619
|
+
tracking = false;
|
|
620
|
+
window.removeEventListener("pointermove", onMove);
|
|
621
|
+
window.removeEventListener("pointerup", onUp);
|
|
622
|
+
window.removeEventListener("pointercancel", onCancel);
|
|
623
|
+
options.onHold?.(false);
|
|
624
|
+
};
|
|
625
|
+
function onUp(): void {
|
|
626
|
+
release();
|
|
627
|
+
end();
|
|
628
|
+
}
|
|
629
|
+
function onCancel(): void {
|
|
630
|
+
release();
|
|
631
|
+
reset();
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
return {
|
|
635
|
+
offset,
|
|
636
|
+
isSwiping: swiping,
|
|
637
|
+
direction,
|
|
638
|
+
start,
|
|
639
|
+
move,
|
|
640
|
+
end,
|
|
641
|
+
cancel: reset,
|
|
642
|
+
release,
|
|
643
|
+
track(event, toast) {
|
|
644
|
+
if (event.button !== 0 || tracking) return false;
|
|
645
|
+
if (ownsPointer(event.target, toast)) return false;
|
|
646
|
+
start({ x: event.clientX, y: event.clientY });
|
|
647
|
+
tracking = true;
|
|
648
|
+
options.onHold?.(true);
|
|
649
|
+
// On the window rather than through `setPointerCapture`: a toast dragged
|
|
650
|
+
// out from under the pointer stops receiving its moves, and a captured
|
|
651
|
+
// pointer would retarget the click that follows to the toast.
|
|
652
|
+
window.addEventListener("pointermove", onMove);
|
|
653
|
+
window.addEventListener("pointerup", onUp);
|
|
654
|
+
window.addEventListener("pointercancel", onCancel);
|
|
655
|
+
return true;
|
|
656
|
+
},
|
|
657
|
+
};
|
|
658
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Accessor, Child, Incoming } from "@barqjs/core";
|
|
2
|
+
import { mergeRefs, type Ref, type RefTarget } from "@barqjs/primitives/refs";
|
|
3
|
+
|
|
4
|
+
import { HIDDEN_INPUT_STYLE, pressesInput, type ToggleElementType } from "./toggle.ts";
|
|
5
|
+
import { access, type DOMProps, mergeProps } from "./utils.ts";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A toggle's own element with its hidden input inside, the children after it.
|
|
9
|
+
* A `<span>` forwards a press on itself to the input, which a `<label>` does
|
|
10
|
+
* without being asked.
|
|
11
|
+
*/
|
|
12
|
+
export function toggleInput(parts: {
|
|
13
|
+
elementType: ToggleElementType;
|
|
14
|
+
outerProps: DOMProps;
|
|
15
|
+
inputProps: DOMProps;
|
|
16
|
+
focusProps: DOMProps;
|
|
17
|
+
inputRef: Ref<HTMLInputElement>;
|
|
18
|
+
ref: RefTarget<HTMLInputElement> | undefined;
|
|
19
|
+
children: Incoming<{ children?: Child }>["children"];
|
|
20
|
+
isDisabled: Accessor<boolean>;
|
|
21
|
+
}) {
|
|
22
|
+
const { inputProps, focusProps, inputRef, ref, children } = parts;
|
|
23
|
+
if (parts.elementType === "span") {
|
|
24
|
+
const onClick = pressesInput(() => access(inputRef), parts.isDisabled);
|
|
25
|
+
|
|
26
|
+
return (
|
|
27
|
+
<span {...mergeProps(parts.outerProps, { onClick })}>
|
|
28
|
+
<input
|
|
29
|
+
{...mergeProps(inputProps, focusProps)}
|
|
30
|
+
ref={mergeRefs(inputRef.set, ref)}
|
|
31
|
+
style={HIDDEN_INPUT_STYLE}
|
|
32
|
+
/>
|
|
33
|
+
{children}
|
|
34
|
+
</span>
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return (
|
|
39
|
+
<label {...parts.outerProps}>
|
|
40
|
+
<input
|
|
41
|
+
{...mergeProps(inputProps, focusProps)}
|
|
42
|
+
ref={mergeRefs(inputRef.set, ref)}
|
|
43
|
+
style={HIDDEN_INPUT_STYLE}
|
|
44
|
+
/>
|
|
45
|
+
{children}
|
|
46
|
+
</label>
|
|
47
|
+
);
|
|
48
|
+
}
|