@human-kit/ui 1.0.0-beta.8 → 1.0.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/internal/localized-strings.d.ts +24 -0
  4. package/dist/internal/localized-strings.js +24 -0
  5. package/dist/primitives/aria-hide-outside.d.ts +13 -0
  6. package/dist/primitives/aria-hide-outside.js +7 -1
  7. package/dist/primitives/focus-trap.d.ts +2 -0
  8. package/dist/primitives/focus-trap.js +7 -1
  9. package/dist/primitives/presence.svelte.js +6 -1
  10. package/dist/toast/README.md +75 -0
  11. package/dist/toast/action/toast-action.svelte +42 -0
  12. package/dist/toast/action/toast-action.svelte.d.ts +4 -0
  13. package/dist/toast/close/toast-close.svelte +41 -0
  14. package/dist/toast/close/toast-close.svelte.d.ts +4 -0
  15. package/dist/toast/content/toast-content.svelte +24 -0
  16. package/dist/toast/content/toast-content.svelte.d.ts +4 -0
  17. package/dist/toast/description/toast-description.svelte +41 -0
  18. package/dist/toast/description/toast-description.svelte.d.ts +4 -0
  19. package/dist/toast/index.d.ts +34 -0
  20. package/dist/toast/index.js +15 -0
  21. package/dist/toast/index.parts.d.ts +9 -0
  22. package/dist/toast/index.parts.js +9 -0
  23. package/dist/toast/positioner/toast-positioner.svelte +75 -0
  24. package/dist/toast/positioner/toast-positioner.svelte.d.ts +4 -0
  25. package/dist/toast/provider/context.d.ts +36 -0
  26. package/dist/toast/provider/context.js +22 -0
  27. package/dist/toast/provider/toast-manager.svelte.d.ts +113 -0
  28. package/dist/toast/provider/toast-manager.svelte.js +210 -0
  29. package/dist/toast/provider/toast-provider.svelte +98 -0
  30. package/dist/toast/provider/toast-provider.svelte.d.ts +4 -0
  31. package/dist/toast/root/context.d.ts +18 -0
  32. package/dist/toast/root/context.js +15 -0
  33. package/dist/toast/root/toast-root.svelte +296 -0
  34. package/dist/toast/root/toast-root.svelte.d.ts +4 -0
  35. package/dist/toast/title/toast-title.svelte +38 -0
  36. package/dist/toast/title/toast-title.svelte.d.ts +4 -0
  37. package/dist/toast/types.d.ts +100 -0
  38. package/dist/toast/types.js +1 -0
  39. package/dist/toast/viewport/toast-viewport.svelte +389 -0
  40. package/dist/toast/viewport/toast-viewport.svelte.d.ts +4 -0
  41. package/package.json +6 -1
@@ -0,0 +1,22 @@
1
+ import { getContext, setContext } from 'svelte';
2
+ const PROVIDER_KEY = Symbol('toast-provider');
3
+ export function setToastProviderContext(context) {
4
+ setContext(PROVIDER_KEY, context);
5
+ }
6
+ export function getToastProviderContext() {
7
+ return getContext(PROVIDER_KEY);
8
+ }
9
+ export function useToastProviderContext(part = 'Toast') {
10
+ const context = getToastProviderContext();
11
+ if (!context) {
12
+ throw new Error(`${part} must be used within Toast.Provider.`);
13
+ }
14
+ return context;
15
+ }
16
+ /**
17
+ * The manager of the nearest `Toast.Provider`: `add`, `update`, `close` and `promise`. Call it
18
+ * in a component under the provider, at the start of its script.
19
+ */
20
+ export function useToastManager() {
21
+ return useToastProviderContext('useToastManager').manager;
22
+ }
@@ -0,0 +1,113 @@
1
+ import type { ExtendedPlacement } from '../../primitives/floating';
2
+ export type ToastPriority = 'low' | 'high';
3
+ export type ToastStatus = 'open' | 'ending';
4
+ /** The default time a toast stays, in milliseconds. `0` keeps a toast until a close. */
5
+ export declare const DEFAULT_TOAST_TIMEOUT = 5000;
6
+ /** The default count of toasts on the screen. The older ones wait behind. */
7
+ export declare const DEFAULT_TOAST_LIMIT = 3;
8
+ export type ToastOptions<Data = unknown> = {
9
+ /** The id of the toast. With the id of a toast that is on the screen, `add` updates it. */
10
+ id?: string;
11
+ /** The title. It names the toast, and it is the first part of the announcement. */
12
+ title?: string;
13
+ /** The description. It is the message when there is no title. */
14
+ description?: string;
15
+ /**
16
+ * A kind of your own, such as `success` or `error`, for `data-type` on the toast. A `loading`
17
+ * toast stays until an update, because a task that runs has no end that a timer knows.
18
+ */
19
+ type?: string;
20
+ /** The time the toast stays, in milliseconds. `0` keeps it until a close. */
21
+ timeout?: number;
22
+ /**
23
+ * How the screen reader hears it. `low` is announced when the user is idle, and `high`
24
+ * interrupts, thus the toast is `alertdialog`. Use `high` only for a message that cannot wait.
25
+ */
26
+ priority?: ToastPriority;
27
+ /** Data of your own, for the content you render. */
28
+ data?: Data;
29
+ /**
30
+ * An element the toast sits against, in place of the viewport. `Toast.Positioner` puts the
31
+ * toast there. The toast is out of the stack: it has no place in the corner to take.
32
+ */
33
+ anchor?: HTMLElement | null;
34
+ /** The side of the anchor for the toast. `top` by default. */
35
+ placement?: ExtendedPlacement;
36
+ /** The gap between the anchor and the toast, in pixels. 8 by default. */
37
+ offset?: number;
38
+ /** Runs when the toast starts to close. */
39
+ onClose?: () => void;
40
+ /** Runs when the toast leaves the DOM, after its exit animation. */
41
+ onRemove?: () => void;
42
+ };
43
+ export type ToastItem<Data = unknown> = {
44
+ readonly id: string;
45
+ readonly title: string | undefined;
46
+ readonly description: string | undefined;
47
+ readonly type: string | undefined;
48
+ readonly timeout: number;
49
+ readonly priority: ToastPriority;
50
+ readonly data: Data | undefined;
51
+ readonly anchor: HTMLElement | null | undefined;
52
+ readonly placement: ExtendedPlacement | undefined;
53
+ readonly offset: number | undefined;
54
+ /** `open` on the screen, `ending` through the exit animation. */
55
+ readonly status: ToastStatus;
56
+ /** The toast is past the limit of the viewport. It waits, hidden and inert. */
57
+ readonly limited: boolean;
58
+ /** Goes up on each update. Replay an attention animation from it. */
59
+ readonly updateKey: number;
60
+ readonly onClose: (() => void) | undefined;
61
+ readonly onRemove: (() => void) | undefined;
62
+ };
63
+ export type ToastUpdate<Data = unknown> = Omit<ToastOptions<Data>, 'id'> | ((toast: ToastItem<Data>) => Omit<ToastOptions<Data>, 'id'>);
64
+ export type ToastPromiseOptions<Value, Data = unknown> = {
65
+ loading: string | Omit<ToastOptions<Data>, 'id'>;
66
+ success: string | Omit<ToastOptions<Data>, 'id'> | ((value: Value) => string | Omit<ToastOptions<Data>, 'id'>);
67
+ error: string | Omit<ToastOptions<Data>, 'id'> | ((error: unknown) => string | Omit<ToastOptions<Data>, 'id'>);
68
+ };
69
+ export type ToastManager<Data = unknown> = {
70
+ /** The toasts, the newest first. Render them in `Toast.Viewport`. */
71
+ readonly toasts: readonly ToastItem<Data>[];
72
+ /** The toasts on the screen: the newest ones, up to the limit. */
73
+ readonly visibleToasts: readonly ToastItem<Data>[];
74
+ /**
75
+ * The toasts that take a place in the stack of the viewport: the ones on the screen, without
76
+ * an anchor, and not on their way out. A toast through its exit keeps the place it had, and
77
+ * the ones behind it move up at once.
78
+ */
79
+ readonly stackedToasts: readonly ToastItem<Data>[];
80
+ /** Adds a toast, and answers its id. */
81
+ add: (options: ToastOptions<Data>) => string;
82
+ /** Updates a toast. The options replace the fields they name. */
83
+ update: (id: string, update: ToastUpdate<Data>) => void;
84
+ /** Starts the close of one toast, or of all of them. */
85
+ close: (id?: string) => void;
86
+ /** Takes a toast out of the list. `Toast.Root` calls it after the exit animation. */
87
+ remove: (id: string) => void;
88
+ /** Adds a `loading` toast that turns into `success` or `error` with the promise. */
89
+ promise: <Value>(promise: Promise<Value>, options: ToastPromiseOptions<Value, Data>) => Promise<Value>;
90
+ /** Stops every timer, for example while the pointer rests on the viewport. */
91
+ pauseTimers: () => void;
92
+ /** Starts the timers again, with the time each toast had left. */
93
+ resumeTimers: () => void;
94
+ /** Whether the timers are stopped. */
95
+ readonly paused: boolean;
96
+ };
97
+ export type CreateToastManagerOptions = {
98
+ /** The default time a toast stays, in milliseconds. */
99
+ timeout?: () => number;
100
+ /** The count of toasts on the screen. */
101
+ limit?: () => number;
102
+ };
103
+ /**
104
+ * The list of toasts and their timers. `Toast.Provider` makes one, and gives it to the parts
105
+ * and to the page through `useToastManager`. The timers live here and not in the toasts,
106
+ * thus one pause stops all of them, and a resume gives each one the time it had left.
107
+ */
108
+ export declare function createToastManager<Data = unknown>(options?: CreateToastManagerOptions): InternalToastManager<Data>;
109
+ /** The manager with the calls that only the parts make. */
110
+ export type InternalToastManager<Data = unknown> = ToastManager<Data> & {
111
+ /** `Toast.Provider` applies a new limit. */
112
+ syncLimit: () => void;
113
+ };
@@ -0,0 +1,210 @@
1
+ import { untrack } from 'svelte';
2
+ /** The default time a toast stays, in milliseconds. `0` keeps a toast until a close. */
3
+ export const DEFAULT_TOAST_TIMEOUT = 5000;
4
+ /** The default count of toasts on the screen. The older ones wait behind. */
5
+ export const DEFAULT_TOAST_LIMIT = 3;
6
+ let toastCounter = 0;
7
+ function nextToastId() {
8
+ toastCounter += 1;
9
+ return `toast-${toastCounter}`;
10
+ }
11
+ function resolveText(source, value) {
12
+ const resolved = typeof source === 'function' ? source(value) : source;
13
+ return typeof resolved === 'string' ? { description: resolved } : resolved;
14
+ }
15
+ /**
16
+ * The list of toasts and their timers. `Toast.Provider` makes one, and gives it to the parts
17
+ * and to the page through `useToastManager`. The timers live here and not in the toasts,
18
+ * thus one pause stops all of them, and a resume gives each one the time it had left.
19
+ */
20
+ export function createToastManager(options = {}) {
21
+ let toasts = $state([]);
22
+ let paused = $state(false);
23
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity -- the timers are bookkeeping, not state: nothing renders from them.
24
+ const timers = new Map();
25
+ const getTimeout = options.timeout ?? (() => DEFAULT_TOAST_TIMEOUT);
26
+ const getLimit = options.limit ?? (() => DEFAULT_TOAST_LIMIT);
27
+ const visibleToasts = $derived(toasts.filter((toast) => !toast.limited));
28
+ const stackedToasts = $derived(visibleToasts.filter((toast) => !toast.anchor && toast.status !== 'ending'));
29
+ function setToasts(next) {
30
+ toasts = applyLimit(next);
31
+ }
32
+ // The newest toasts stay on the screen; the older ones past the limit wait, inert. A toast on
33
+ // its way out no longer takes a place.
34
+ function applyLimit(list) {
35
+ const limit = Math.max(0, untrack(getLimit));
36
+ let active = 0;
37
+ return list.map((toast) => {
38
+ if (toast.status === 'ending')
39
+ return toast.limited ? { ...toast, limited: false } : toast;
40
+ const limited = active >= limit;
41
+ active += 1;
42
+ return toast.limited === limited ? toast : { ...toast, limited };
43
+ });
44
+ }
45
+ function hasTimer(toast) {
46
+ return toast.timeout > 0 && toast.type !== 'loading' && toast.status !== 'ending';
47
+ }
48
+ function clearTimer(id) {
49
+ const timer = timers.get(id);
50
+ if (!timer)
51
+ return;
52
+ if (timer.timeoutId !== null)
53
+ clearTimeout(timer.timeoutId);
54
+ timers.delete(id);
55
+ }
56
+ function startTimer(id, duration) {
57
+ clearTimer(id);
58
+ const timer = { timeoutId: null, remaining: duration, startedAt: Date.now() };
59
+ timers.set(id, timer);
60
+ if (!paused)
61
+ run(id, timer);
62
+ }
63
+ function run(id, timer) {
64
+ timer.startedAt = Date.now();
65
+ timer.timeoutId = setTimeout(() => {
66
+ timers.delete(id);
67
+ close(id);
68
+ }, timer.remaining);
69
+ }
70
+ // A timer runs only for a toast the user can see. A hidden one that closes on its own is a
71
+ // message nobody read.
72
+ function syncTimers() {
73
+ for (const toast of untrack(() => toasts)) {
74
+ const wants = hasTimer(toast) && !toast.limited;
75
+ const has = timers.has(toast.id);
76
+ if (wants && !has)
77
+ startTimer(toast.id, toast.timeout);
78
+ if (!wants && has)
79
+ clearTimer(toast.id);
80
+ }
81
+ }
82
+ function pauseTimers() {
83
+ if (paused)
84
+ return;
85
+ paused = true;
86
+ for (const timer of timers.values()) {
87
+ if (timer.timeoutId === null)
88
+ continue;
89
+ clearTimeout(timer.timeoutId);
90
+ timer.timeoutId = null;
91
+ timer.remaining = Math.max(0, timer.remaining - (Date.now() - timer.startedAt));
92
+ }
93
+ }
94
+ function resumeTimers() {
95
+ if (!paused)
96
+ return;
97
+ paused = false;
98
+ for (const [id, timer] of timers) {
99
+ if (timer.timeoutId === null)
100
+ run(id, timer);
101
+ }
102
+ }
103
+ function add(options) {
104
+ const id = options.id ?? nextToastId();
105
+ const existing = untrack(() => toasts.find((toast) => toast.id === id));
106
+ if (existing && existing.status !== 'ending') {
107
+ update(id, options);
108
+ return id;
109
+ }
110
+ const toast = {
111
+ id,
112
+ title: options.title,
113
+ description: options.description,
114
+ type: options.type,
115
+ timeout: options.timeout ?? untrack(getTimeout),
116
+ priority: options.priority ?? 'low',
117
+ data: options.data,
118
+ anchor: options.anchor,
119
+ placement: options.placement,
120
+ offset: options.offset,
121
+ status: 'open',
122
+ limited: false,
123
+ updateKey: 0,
124
+ onClose: options.onClose,
125
+ onRemove: options.onRemove
126
+ };
127
+ setToasts([toast, ...untrack(() => toasts).filter((candidate) => candidate.id !== id)]);
128
+ syncTimers();
129
+ return id;
130
+ }
131
+ function update(id, incoming) {
132
+ const current = untrack(() => toasts.find((toast) => toast.id === id));
133
+ if (!current || current.status === 'ending')
134
+ return;
135
+ const changes = typeof incoming === 'function' ? incoming(current) : incoming;
136
+ const next = {
137
+ ...current,
138
+ ...changes,
139
+ timeout: changes.timeout ??
140
+ (Object.hasOwn(changes, 'timeout') ? untrack(getTimeout) : current.timeout),
141
+ priority: changes.priority ?? current.priority,
142
+ updateKey: current.updateKey + 1
143
+ };
144
+ setToasts(untrack(() => toasts).map((toast) => (toast.id === id ? next : toast)));
145
+ // An update is a new message: the toast gets its full time again.
146
+ clearTimer(id);
147
+ syncTimers();
148
+ }
149
+ function close(id) {
150
+ const targets = untrack(() => toasts.filter((toast) => (id === undefined || toast.id === id) && toast.status !== 'ending'));
151
+ if (targets.length === 0)
152
+ return;
153
+ for (const toast of targets)
154
+ clearTimer(toast.id);
155
+ setToasts(untrack(() => toasts).map((toast) => targets.includes(toast) ? { ...toast, status: 'ending' } : toast));
156
+ syncTimers();
157
+ for (const toast of targets)
158
+ toast.onClose?.();
159
+ }
160
+ function remove(id) {
161
+ const target = untrack(() => toasts.find((toast) => toast.id === id));
162
+ if (!target)
163
+ return;
164
+ clearTimer(id);
165
+ setToasts(untrack(() => toasts).filter((toast) => toast.id !== id));
166
+ syncTimers();
167
+ target.onRemove?.();
168
+ }
169
+ async function promise(task, promiseOptions) {
170
+ const loading = resolveText(promiseOptions.loading, undefined);
171
+ const id = add({ type: 'loading', ...loading, timeout: 0 });
172
+ try {
173
+ const value = await task;
174
+ const success = resolveText(promiseOptions.success, value);
175
+ update(id, { type: 'success', timeout: undefined, ...success });
176
+ return value;
177
+ }
178
+ catch (error) {
179
+ const failure = resolveText(promiseOptions.error, error);
180
+ update(id, { type: 'error', timeout: undefined, ...failure });
181
+ throw error;
182
+ }
183
+ }
184
+ function syncLimit() {
185
+ toasts = applyLimit(untrack(() => toasts));
186
+ syncTimers();
187
+ }
188
+ return {
189
+ get toasts() {
190
+ return toasts;
191
+ },
192
+ get visibleToasts() {
193
+ return visibleToasts;
194
+ },
195
+ get stackedToasts() {
196
+ return stackedToasts;
197
+ },
198
+ get paused() {
199
+ return paused;
200
+ },
201
+ add,
202
+ update,
203
+ close,
204
+ remove,
205
+ promise,
206
+ pauseTimers,
207
+ resumeTimers,
208
+ syncLimit
209
+ };
210
+ }
@@ -0,0 +1,98 @@
1
+ <script lang="ts">
2
+ import { untrack } from 'svelte';
3
+ import { SvelteMap } from 'svelte/reactivity';
4
+ import type { ToastProviderProps } from '../types.js';
5
+ import { setToastProviderContext, type ToastProviderContext } from './context';
6
+ import {
7
+ createToastManager,
8
+ DEFAULT_TOAST_LIMIT,
9
+ DEFAULT_TOAST_TIMEOUT,
10
+ type InternalToastManager
11
+ } from './toast-manager.svelte';
12
+
13
+ /**
14
+ * Toast.Provider — the list of toasts, and the manager that adds to it.
15
+ *
16
+ * Put one around the app, thus every toast lands in the same viewport. The manager is on
17
+ * `bind:manager` for the page, and on `useToastManager()` for a component under the provider.
18
+ * Give `manager` to share one list between two providers, such as an app and a dialog in it.
19
+ */
20
+ let {
21
+ timeout = DEFAULT_TOAST_TIMEOUT,
22
+ limit = DEFAULT_TOAST_LIMIT,
23
+ manager: managerProp = $bindable(),
24
+ children
25
+ }: ToastProviderProps = $props();
26
+
27
+ const manager: InternalToastManager = untrack(
28
+ () =>
29
+ (managerProp as InternalToastManager | undefined) ??
30
+ createToastManager({ timeout: () => timeout, limit: () => limit })
31
+ );
32
+ managerProp = manager;
33
+
34
+ // A new limit takes effect on the toasts that are already there.
35
+ $effect(() => {
36
+ void limit;
37
+ untrack(() => manager.syncLimit());
38
+ });
39
+
40
+ let hovering = $state(false);
41
+ let focused = $state(false);
42
+ let tapped = $state(false);
43
+ let viewportElement = $state<HTMLElement | null>(null);
44
+ const heights = new SvelteMap<string, number>();
45
+ let focusAfterCloseHandler: ((id: string) => void) | null = null;
46
+
47
+ const context: ToastProviderContext = {
48
+ manager,
49
+ get hovering() {
50
+ return hovering;
51
+ },
52
+ get focused() {
53
+ return focused;
54
+ },
55
+ get tapped() {
56
+ return tapped;
57
+ },
58
+ get expanded() {
59
+ return hovering || focused || tapped;
60
+ },
61
+ get viewportElement() {
62
+ return viewportElement;
63
+ },
64
+ get heights() {
65
+ return heights;
66
+ },
67
+ setHovering(value) {
68
+ hovering = value;
69
+ },
70
+ setFocused(value) {
71
+ focused = value;
72
+ },
73
+ setTapped(value) {
74
+ tapped = value;
75
+ },
76
+ setViewportElement(element) {
77
+ viewportElement = element;
78
+ },
79
+ // `untrack` because the root measures from an effect: reading the map here would make
80
+ // that effect depend on what it writes.
81
+ setHeight(id, height) {
82
+ untrack(() => {
83
+ if (height === null) heights.delete(id);
84
+ else if (heights.get(id) !== height) heights.set(id, height);
85
+ });
86
+ },
87
+ focusAfterClose(id) {
88
+ focusAfterCloseHandler?.(id);
89
+ },
90
+ setFocusAfterClose(handler) {
91
+ focusAfterCloseHandler = handler;
92
+ }
93
+ };
94
+
95
+ setToastProviderContext(context);
96
+ </script>
97
+
98
+ {@render children?.()}
@@ -0,0 +1,4 @@
1
+ import type { ToastProviderProps } from '../types.js';
2
+ declare const ToastProvider: import("svelte").Component<ToastProviderProps, {}, "manager">;
3
+ type ToastProvider = ReturnType<typeof ToastProvider>;
4
+ export default ToastProvider;
@@ -0,0 +1,18 @@
1
+ import type { ToastItem } from '../provider/toast-manager.svelte';
2
+ export type ToastContext = {
3
+ /** The item of this toast. */
4
+ readonly toast: ToastItem;
5
+ /** The ids of the registered titles, for `aria-labelledby`. */
6
+ readonly labelledBy: string | undefined;
7
+ /** The ids of the registered descriptions, for `aria-describedby`. */
8
+ readonly describedBy: string | undefined;
9
+ /** Registers a title id; the returned function unregisters it. */
10
+ registerTitle: (id: string) => () => void;
11
+ /** Registers a description id; the returned function unregisters it. */
12
+ registerDescription: (id: string) => () => void;
13
+ /** Closes this toast, and moves the focus on when it was in it. */
14
+ close: () => void;
15
+ };
16
+ export declare function setToastContext(context: ToastContext): void;
17
+ export declare function getToastContext(): ToastContext | undefined;
18
+ export declare function useToastContext(part?: string): ToastContext;
@@ -0,0 +1,15 @@
1
+ import { getContext, setContext } from 'svelte';
2
+ const KEY = Symbol('toast');
3
+ export function setToastContext(context) {
4
+ setContext(KEY, context);
5
+ }
6
+ export function getToastContext() {
7
+ return getContext(KEY);
8
+ }
9
+ export function useToastContext(part = 'Toast') {
10
+ const context = getToastContext();
11
+ if (!context) {
12
+ throw new Error(`${part} must be used within Toast.Root.`);
13
+ }
14
+ return context;
15
+ }