All files / lib toasts.svelte.js

28.57% Statements 30/105
100% Branches 3/3
12.5% Functions 2/16
28.57% Lines 30/105

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272                                                                      1x 1x 1x 1x   1x 1x 1x                                             1x     1x       1x             1x 1x   1x 1x   1x               1x                     1x                 1x                       1x                                                                                         1x                     1x                     1x                           1x                   1x                             1x                       1x                   1x                   1x         1x   1x  
import { minutesToMilliseconds } from 'date-fns';
import { nanoid } from 'nanoid';
import { entries, mapValues } from './utils.js';
 
/**
 * @template T
 * @typedef {T | Promise<T>} MaybePromise<T>
 */
 
/**
 * @template T
 * @typedef {Object} Toast
 * @property {Date} addedAt
 * @property {string} id
 * @property {string} message
 * @property {'info' | 'success' | 'error' | 'warning' | 'debug'} type
 * @property {Object} labels
 * @property {string} [labels.action]
 * @property {string} [labels.close]
 * @property {Object} callbacks
 * @property {(toast: Toast<T>) => MaybePromise<void>} [callbacks.action]
 * @property {(toast: Toast<T>) => MaybePromise<void>} [callbacks.closed]
 * @property {boolean} [showLifetime]
 * @property {number} [lifetime]
 * @property {number|NodeJS.Timeout} [timeoutHandle]
 * @property {?T} data
 */
 
/**
 * @typedef {object} ToastPool
 * @property {Toast<any>[]} items
 * @property {number} capacity maximum number of toasts to show in this pool
 * @property {number} lifetime default lifetime for toasts in this pool (in ms).
 */
 
const TOAST_POOLS = /** @type {const} @satisfies {Record<string, Omit<ToastPool, 'items'>>} */ ({
	default: {
		lifetime: 3_000,
		capacity: 3
	},
	exporter: {
		lifetime: Infinity,
		capacity: Infinity
	}
});
 
/**
 * @typedef {keyof typeof TOAST_POOLS} ToastPoolNames
 */
 
/**
 * @template T
 * @typedef {Object} ToastOptions
 * @property {T} [data]
 * @property {Toast<T>['labels']} [labels]
 * @property {boolean} [showLifetime]
 * @property {number | 'inferred'} [lifetime]
 * @property {Toast<T>['callbacks']['action']} [action]
 * @property {Toast<T>['callbacks']['closed']} [closed]
 */
 
/**
 * @template {string} PoolNames
 * @template {{[Name in PoolNames]: ToastPool}} Pools
 */
class Toasts {
	/** @type {Pools} */
	// @ts-expect-error
	pools = $state();
 
	/** @type {keyof Pools & string} */
	// @ts-expect-error
	currentPoolName = $state();
 
	/**
	 *
	 * @param { {[Key in PoolNames]: Omit<Pools[Key], 'items'> } } poolsConfig
	 * @param {NoInfer<PoolNames>} initialPool
	 */
	constructor(poolsConfig, initialPool) {
		this.currentPoolName = initialPool;
		// @ts-expect-error
		this.pools = mapValues(poolsConfig, (pool) => ({ items: [], ...pool }));
	}
 
	get pool() {
		return this.pools[this.currentPoolName];
	}
 
	/**
	 * Sets the current toast pool. Freezes toasts of the previously active pool, and unfreezes toasts of the newly active pool.
	 * @param {PoolNames} name
	 */
	setCurrentPool(name) {
		this.#ensurePoolName(name);
		this.freeze(this.currentPoolName);
		this.currentPoolName = name;
		this.unfreeze(this.currentPoolName);
	}
 
	/**
	 * Return the toasts of the given pool, or of the current pool if none is specified.
	 * @param {undefined | (keyof Pools & string)} pool
	 */
	items(pool = undefined) {
		if (pool) this.#ensurePoolName(pool);
		return this.pools[pool ?? this.currentPoolName].items;
	}
 
	/**
	 *
	 * @param {keyof Pools & string} name
	 */
	#ensurePoolName(name) {
		if (!this.pools[name]) throw new Error(`Toast pool ${name} does not exist`);
	}
 
	/**
	 * Adds a toast notification.
	 * @template T
	 * @param {Toast<T>['type']} type
	 * @param {string} message
	 * @param {ToastOptions<T>} [options]
	 * @returns {string | undefined}
	 */
	add(type, message, options) {
		if (!message) return;
		const { labels, data, closed, action, lifetime = 'inferred', ...rest } = options ?? {};
		const callbacks = { closed, action };
		if (Object.values(callbacks).some(Boolean) && !data)
			throw new Error("You must provide data if you're using callbacks");
 
		const id = nanoid();
		const wordsCount = message.split(' ').length + message.split(' ').length;
 
		/** @type {Toast<typeof data>} */
		const newToast = {
			addedAt: new Date(),
			id,
			message: message.replaceAll('\n', '; '),
			type,
			labels: labels ?? {},
			// @ts-ignore
			callbacks,
			data: data ?? null,
			lifetime:
				lifetime === 'inferred'
					? this.pool.lifetime + minutesToMilliseconds(wordsCount / 300)
					: lifetime,
			...rest
		};
 
		if (Number.isFinite(newToast.lifetime)) {
			this.#armTimeout(newToast);
		}
 
		this.pools[this.currentPoolName].items = [
			...this.items().slice(0, this.pool.capacity - 1),
			newToast
		];
		return id;
	}
 
	/**
	 * Displays an info toast.
	 * @template T
	 * @param {string} message
	 * @param {ToastOptions<T>} [options]
	 * @returns {string | undefined}
	 */
	info(message, options) {
		return this.add('info', message, options);
	}
 
	/**
	 * Displays a warning toast.
	 * @template T
	 * @param {string} message
	 * @param {ToastOptions<T>} [options]
	 * @returns {string | undefined}
	 */
	warn(message, options) {
		return this.add('warning', message, options);
	}
 
	/**
	 * Displays an error toast.
	 * @template T
	 * @param {any} message
	 * @param {ToastOptions<T>} [options]
	 * @returns {string | undefined}
	 */
	error(message, options) {
		return this.add('error', message?.toString() ?? 'Erreur inattendue', {
			...options,
			lifetime: options?.lifetime ?? 'inferred'
		});
	}
 
	/**
	 * Displays a success toast.
	 * @template T
	 * @param {string} message
	 * @param {ToastOptions<T>} [options]
	 * @returns {string | undefined}
	 */
	success(message, options) {
		return this.add('success', message, options);
	}
 
	/**
	 * Removes a toast by ID.
	 * @param {string} id
	 * @param {keyof Pools} [pool] only search in this pool, defaults to all pools
	 * @returns {Promise<void>}
	 */
	async remove(id, pool) {
		for (const [poolName, { items }] of entries(this.pools)) {
			if (pool && pool !== poolName) continue;
 
			const toast = items.find((t) => t.id === id);
			if (!toast) return;
			if (toast.callbacks?.closed) await toast.callbacks.closed(toast);
 
			this.pools[poolName].items = this.items(poolName).filter((t) => t.id !== id);
		}
	}
 
	/**
	 * @param {keyof Pools & string} pool
	 */
	async clear(pool = this.currentPoolName) {
		const items = this.items(pool);
		await Promise.all(
			items.map((t) => (t.callbacks?.closed ? t.callbacks.closed(t) : Promise.resolve()))
		);
		this.pools[pool].items = [];
	}
 
	/**
	 * Freeze timeouts for all toasts of pool
	 * @param {keyof Pools & string} pool
	 */
	freeze(pool = this.currentPoolName) {
		for (const toast of this.items(pool).filter((t) => t.timeoutHandle)) {
			clearTimeout(toast.timeoutHandle);
		}
	}
 
	/**
	 * Restores timeouts for all toasts of pool
	 * @param {keyof Pools & string} pool
	 */
	unfreeze(pool = this.currentPoolName) {
		for (const toast of this.items(pool).filter((t) => t.timeoutHandle)) {
			this.#armTimeout(toast);
		}
	}
 
	/**
	 *
	 * @param {Toast<any>} toast
	 */
	#armTimeout(toast) {
		toast.timeoutHandle = setTimeout(() => {
			this.remove(toast.id);
		}, toast.lifetime);
	}
}
 
export const toasts = new Toasts(TOAST_POOLS, 'default');