@samline/notify 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1137 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.notify = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ class NotifyController {
8
+ constructor() {
9
+ this.toasts = [];
10
+ this.listeners = new Set();
11
+ this.idCounter = 1;
12
+ }
13
+ nextId() {
14
+ return `notify_${Date.now()}_${this.idCounter++}`;
15
+ }
16
+ subscribe(fn) {
17
+ this.listeners.add(fn);
18
+ fn(this.toasts.slice());
19
+ return () => this.listeners.delete(fn);
20
+ }
21
+ notify() {
22
+ const snapshot = this.toasts.slice();
23
+ this.listeners.forEach((l) => l(snapshot));
24
+ }
25
+ getToasts() {
26
+ return this.toasts.slice();
27
+ }
28
+ show(opts) {
29
+ const id = this.nextId();
30
+ const item = { id, options: { ...opts }, createdAt: Date.now() };
31
+ this.toasts.push(item);
32
+ this.notify();
33
+ return id;
34
+ }
35
+ success(opts) {
36
+ return this.show({ ...opts, type: 'success' });
37
+ }
38
+ error(opts) {
39
+ return this.show({ ...opts, type: 'error' });
40
+ }
41
+ info(opts) {
42
+ return this.show({ ...opts, type: 'info' });
43
+ }
44
+ warning(opts) {
45
+ return this.show({ ...opts, type: 'warning' });
46
+ }
47
+ action(opts) {
48
+ return this.show({ ...opts, type: 'action' });
49
+ }
50
+ dismiss(id) {
51
+ const idx = this.toasts.findIndex((t) => t.id === id);
52
+ if (idx >= 0) {
53
+ this.toasts.splice(idx, 1);
54
+ this.notify();
55
+ }
56
+ }
57
+ clear(position) {
58
+ if (position) {
59
+ this.toasts = this.toasts.filter((t) => t.options.position !== position);
60
+ }
61
+ else {
62
+ this.toasts = [];
63
+ }
64
+ this.notify();
65
+ }
66
+ promise(p, opts) {
67
+ const loadingId = this.show({ ...(opts.loading || {}), type: 'loading', position: opts.position });
68
+ p.then((res) => {
69
+ this.dismiss(loadingId);
70
+ const successOpt = typeof opts.success === 'function' ? opts.success(res) : opts.success;
71
+ if (successOpt)
72
+ this.show({ ...(successOpt || {}), type: 'success', position: opts.position });
73
+ }).catch((err) => {
74
+ this.dismiss(loadingId);
75
+ const errorOpt = typeof opts.error === 'function' ? opts.error(err) : opts.error;
76
+ if (errorOpt)
77
+ this.show({ ...(errorOpt || {}), type: 'error', position: opts.position });
78
+ });
79
+ return p;
80
+ }
81
+ }
82
+ const notify$1 = new NotifyController();
83
+ // backward compatibility alias
84
+ const sileo = notify$1;
85
+
86
+ function addUniqueItem(array, item) {
87
+ array.indexOf(item) === -1 && array.push(item);
88
+ }
89
+
90
+ const clamp = (min, max, v) => Math.min(Math.max(v, min), max);
91
+
92
+ const defaults = {
93
+ duration: 0.3,
94
+ delay: 0,
95
+ endDelay: 0,
96
+ repeat: 0,
97
+ easing: "ease",
98
+ };
99
+
100
+ const isNumber = (value) => typeof value === "number";
101
+
102
+ const isEasingList = (easing) => Array.isArray(easing) && !isNumber(easing[0]);
103
+
104
+ const wrap = (min, max, v) => {
105
+ const rangeSize = max - min;
106
+ return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
107
+ };
108
+
109
+ function getEasingForSegment(easing, i) {
110
+ return isEasingList(easing) ? easing[wrap(0, easing.length, i)] : easing;
111
+ }
112
+
113
+ const mix = (min, max, progress) => -progress * min + progress * max + min;
114
+
115
+ const noop = () => { };
116
+ const noopReturn = (v) => v;
117
+
118
+ const progress = (min, max, value) => max - min === 0 ? 1 : (value - min) / (max - min);
119
+
120
+ function fillOffset(offset, remaining) {
121
+ const min = offset[offset.length - 1];
122
+ for (let i = 1; i <= remaining; i++) {
123
+ const offsetProgress = progress(0, remaining, i);
124
+ offset.push(mix(min, 1, offsetProgress));
125
+ }
126
+ }
127
+ function defaultOffset(length) {
128
+ const offset = [0];
129
+ fillOffset(offset, length - 1);
130
+ return offset;
131
+ }
132
+
133
+ function interpolate(output, input = defaultOffset(output.length), easing = noopReturn) {
134
+ const length = output.length;
135
+ /**
136
+ * If the input length is lower than the output we
137
+ * fill the input to match. This currently assumes the input
138
+ * is an animation progress value so is a good candidate for
139
+ * moving outside the function.
140
+ */
141
+ const remainder = length - input.length;
142
+ remainder > 0 && fillOffset(input, remainder);
143
+ return (t) => {
144
+ let i = 0;
145
+ for (; i < length - 2; i++) {
146
+ if (t < input[i + 1])
147
+ break;
148
+ }
149
+ let progressInRange = clamp(0, 1, progress(input[i], input[i + 1], t));
150
+ const segmentEasing = getEasingForSegment(easing, i);
151
+ progressInRange = segmentEasing(progressInRange);
152
+ return mix(output[i], output[i + 1], progressInRange);
153
+ };
154
+ }
155
+
156
+ const isCubicBezier = (easing) => Array.isArray(easing) && isNumber(easing[0]);
157
+
158
+ const isEasingGenerator = (easing) => typeof easing === "object" &&
159
+ Boolean(easing.createAnimation);
160
+
161
+ const isFunction = (value) => typeof value === "function";
162
+
163
+ const isString = (value) => typeof value === "string";
164
+
165
+ const time = {
166
+ ms: (seconds) => seconds * 1000,
167
+ s: (milliseconds) => milliseconds / 1000,
168
+ };
169
+
170
+ /*
171
+ Bezier function generator
172
+
173
+ This has been modified from Gaëtan Renaudeau's BezierEasing
174
+ https://github.com/gre/bezier-easing/blob/master/src/index.js
175
+ https://github.com/gre/bezier-easing/blob/master/LICENSE
176
+
177
+ I've removed the newtonRaphsonIterate algo because in benchmarking it
178
+ wasn't noticiably faster than binarySubdivision, indeed removing it
179
+ usually improved times, depending on the curve.
180
+
181
+ I also removed the lookup table, as for the added bundle size and loop we're
182
+ only cutting ~4 or so subdivision iterations. I bumped the max iterations up
183
+ to 12 to compensate and this still tended to be faster for no perceivable
184
+ loss in accuracy.
185
+
186
+ Usage
187
+ const easeOut = cubicBezier(.17,.67,.83,.67);
188
+ const x = easeOut(0.5); // returns 0.627...
189
+ */
190
+ // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
191
+ const calcBezier = (t, a1, a2) => (((1.0 - 3.0 * a2 + 3.0 * a1) * t + (3.0 * a2 - 6.0 * a1)) * t + 3.0 * a1) * t;
192
+ const subdivisionPrecision = 0.0000001;
193
+ const subdivisionMaxIterations = 12;
194
+ function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
195
+ let currentX;
196
+ let currentT;
197
+ let i = 0;
198
+ do {
199
+ currentT = lowerBound + (upperBound - lowerBound) / 2.0;
200
+ currentX = calcBezier(currentT, mX1, mX2) - x;
201
+ if (currentX > 0.0) {
202
+ upperBound = currentT;
203
+ }
204
+ else {
205
+ lowerBound = currentT;
206
+ }
207
+ } while (Math.abs(currentX) > subdivisionPrecision &&
208
+ ++i < subdivisionMaxIterations);
209
+ return currentT;
210
+ }
211
+ function cubicBezier(mX1, mY1, mX2, mY2) {
212
+ // If this is a linear gradient, return linear easing
213
+ if (mX1 === mY1 && mX2 === mY2)
214
+ return noopReturn;
215
+ const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
216
+ // If animation is at start/end, return t without easing
217
+ return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
218
+ }
219
+
220
+ const steps = (steps, direction = "end") => (progress) => {
221
+ progress =
222
+ direction === "end"
223
+ ? Math.min(progress, 0.999)
224
+ : Math.max(progress, 0.001);
225
+ const expanded = progress * steps;
226
+ const rounded = direction === "end" ? Math.floor(expanded) : Math.ceil(expanded);
227
+ return clamp(0, 1, rounded / steps);
228
+ };
229
+
230
+ const namedEasings = {
231
+ ease: cubicBezier(0.25, 0.1, 0.25, 1.0),
232
+ "ease-in": cubicBezier(0.42, 0.0, 1.0, 1.0),
233
+ "ease-in-out": cubicBezier(0.42, 0.0, 0.58, 1.0),
234
+ "ease-out": cubicBezier(0.0, 0.0, 0.58, 1.0),
235
+ };
236
+ const functionArgsRegex = /\((.*?)\)/;
237
+ function getEasingFunction(definition) {
238
+ // If already an easing function, return
239
+ if (isFunction(definition))
240
+ return definition;
241
+ // If an easing curve definition, return bezier function
242
+ if (isCubicBezier(definition))
243
+ return cubicBezier(...definition);
244
+ // If we have a predefined easing function, return
245
+ const namedEasing = namedEasings[definition];
246
+ if (namedEasing)
247
+ return namedEasing;
248
+ // If this is a steps function, attempt to create easing curve
249
+ if (definition.startsWith("steps")) {
250
+ const args = functionArgsRegex.exec(definition);
251
+ if (args) {
252
+ const argsArray = args[1].split(",");
253
+ return steps(parseFloat(argsArray[0]), argsArray[1].trim());
254
+ }
255
+ }
256
+ return noopReturn;
257
+ }
258
+
259
+ class Animation {
260
+ constructor(output, keyframes = [0, 1], { easing, duration: initialDuration = defaults.duration, delay = defaults.delay, endDelay = defaults.endDelay, repeat = defaults.repeat, offset, direction = "normal", autoplay = true, } = {}) {
261
+ this.startTime = null;
262
+ this.rate = 1;
263
+ this.t = 0;
264
+ this.cancelTimestamp = null;
265
+ this.easing = noopReturn;
266
+ this.duration = 0;
267
+ this.totalDuration = 0;
268
+ this.repeat = 0;
269
+ this.playState = "idle";
270
+ this.finished = new Promise((resolve, reject) => {
271
+ this.resolve = resolve;
272
+ this.reject = reject;
273
+ });
274
+ easing = easing || defaults.easing;
275
+ if (isEasingGenerator(easing)) {
276
+ const custom = easing.createAnimation(keyframes);
277
+ easing = custom.easing;
278
+ keyframes = custom.keyframes || keyframes;
279
+ initialDuration = custom.duration || initialDuration;
280
+ }
281
+ this.repeat = repeat;
282
+ this.easing = isEasingList(easing) ? noopReturn : getEasingFunction(easing);
283
+ this.updateDuration(initialDuration);
284
+ const interpolate$1 = interpolate(keyframes, offset, isEasingList(easing) ? easing.map(getEasingFunction) : noopReturn);
285
+ this.tick = (timestamp) => {
286
+ var _a;
287
+ // TODO: Temporary fix for OptionsResolver typing
288
+ delay = delay;
289
+ let t = 0;
290
+ if (this.pauseTime !== undefined) {
291
+ t = this.pauseTime;
292
+ }
293
+ else {
294
+ t = (timestamp - this.startTime) * this.rate;
295
+ }
296
+ this.t = t;
297
+ // Convert to seconds
298
+ t /= 1000;
299
+ // Rebase on delay
300
+ t = Math.max(t - delay, 0);
301
+ /**
302
+ * If this animation has finished, set the current time
303
+ * to the total duration.
304
+ */
305
+ if (this.playState === "finished" && this.pauseTime === undefined) {
306
+ t = this.totalDuration;
307
+ }
308
+ /**
309
+ * Get the current progress (0-1) of the animation. If t is >
310
+ * than duration we'll get values like 2.5 (midway through the
311
+ * third iteration)
312
+ */
313
+ const progress = t / this.duration;
314
+ // TODO progress += iterationStart
315
+ /**
316
+ * Get the current iteration (0 indexed). For instance the floor of
317
+ * 2.5 is 2.
318
+ */
319
+ let currentIteration = Math.floor(progress);
320
+ /**
321
+ * Get the current progress of the iteration by taking the remainder
322
+ * so 2.5 is 0.5 through iteration 2
323
+ */
324
+ let iterationProgress = progress % 1.0;
325
+ if (!iterationProgress && progress >= 1) {
326
+ iterationProgress = 1;
327
+ }
328
+ /**
329
+ * If iteration progress is 1 we count that as the end
330
+ * of the previous iteration.
331
+ */
332
+ iterationProgress === 1 && currentIteration--;
333
+ /**
334
+ * Reverse progress if we're not running in "normal" direction
335
+ */
336
+ const iterationIsOdd = currentIteration % 2;
337
+ if (direction === "reverse" ||
338
+ (direction === "alternate" && iterationIsOdd) ||
339
+ (direction === "alternate-reverse" && !iterationIsOdd)) {
340
+ iterationProgress = 1 - iterationProgress;
341
+ }
342
+ const p = t >= this.totalDuration ? 1 : Math.min(iterationProgress, 1);
343
+ const latest = interpolate$1(this.easing(p));
344
+ output(latest);
345
+ const isAnimationFinished = this.pauseTime === undefined &&
346
+ (this.playState === "finished" || t >= this.totalDuration + endDelay);
347
+ if (isAnimationFinished) {
348
+ this.playState = "finished";
349
+ (_a = this.resolve) === null || _a === void 0 ? void 0 : _a.call(this, latest);
350
+ }
351
+ else if (this.playState !== "idle") {
352
+ this.frameRequestId = requestAnimationFrame(this.tick);
353
+ }
354
+ };
355
+ if (autoplay)
356
+ this.play();
357
+ }
358
+ play() {
359
+ const now = performance.now();
360
+ this.playState = "running";
361
+ if (this.pauseTime !== undefined) {
362
+ this.startTime = now - this.pauseTime;
363
+ }
364
+ else if (!this.startTime) {
365
+ this.startTime = now;
366
+ }
367
+ this.cancelTimestamp = this.startTime;
368
+ this.pauseTime = undefined;
369
+ this.frameRequestId = requestAnimationFrame(this.tick);
370
+ }
371
+ pause() {
372
+ this.playState = "paused";
373
+ this.pauseTime = this.t;
374
+ }
375
+ finish() {
376
+ this.playState = "finished";
377
+ this.tick(0);
378
+ }
379
+ stop() {
380
+ var _a;
381
+ this.playState = "idle";
382
+ if (this.frameRequestId !== undefined) {
383
+ cancelAnimationFrame(this.frameRequestId);
384
+ }
385
+ (_a = this.reject) === null || _a === void 0 ? void 0 : _a.call(this, false);
386
+ }
387
+ cancel() {
388
+ this.stop();
389
+ this.tick(this.cancelTimestamp);
390
+ }
391
+ reverse() {
392
+ this.rate *= -1;
393
+ }
394
+ commitStyles() { }
395
+ updateDuration(duration) {
396
+ this.duration = duration;
397
+ this.totalDuration = duration * (this.repeat + 1);
398
+ }
399
+ get currentTime() {
400
+ return this.t;
401
+ }
402
+ set currentTime(t) {
403
+ if (this.pauseTime !== undefined || this.rate === 0) {
404
+ this.pauseTime = t;
405
+ }
406
+ else {
407
+ this.startTime = performance.now() - t / this.rate;
408
+ }
409
+ }
410
+ get playbackRate() {
411
+ return this.rate;
412
+ }
413
+ set playbackRate(rate) {
414
+ this.rate = rate;
415
+ }
416
+ }
417
+
418
+ var invariant = function () { };
419
+ if (process.env.NODE_ENV !== 'production') {
420
+ invariant = function (check, message) {
421
+ if (!check) {
422
+ throw new Error(message);
423
+ }
424
+ };
425
+ }
426
+
427
+ /**
428
+ * The MotionValue tracks the state of a single animatable
429
+ * value. Currently, updatedAt and current are unused. The
430
+ * long term idea is to use this to minimise the number
431
+ * of DOM reads, and to abstract the DOM interactions here.
432
+ */
433
+ class MotionValue {
434
+ setAnimation(animation) {
435
+ this.animation = animation;
436
+ animation === null || animation === void 0 ? void 0 : animation.finished.then(() => this.clearAnimation()).catch(() => { });
437
+ }
438
+ clearAnimation() {
439
+ this.animation = this.generator = undefined;
440
+ }
441
+ }
442
+
443
+ const data = new WeakMap();
444
+ function getAnimationData(element) {
445
+ if (!data.has(element)) {
446
+ data.set(element, {
447
+ transforms: [],
448
+ values: new Map(),
449
+ });
450
+ }
451
+ return data.get(element);
452
+ }
453
+ function getMotionValue(motionValues, name) {
454
+ if (!motionValues.has(name)) {
455
+ motionValues.set(name, new MotionValue());
456
+ }
457
+ return motionValues.get(name);
458
+ }
459
+
460
+ /**
461
+ * A list of all transformable axes. We'll use this list to generated a version
462
+ * of each axes for each transform.
463
+ */
464
+ const axes = ["", "X", "Y", "Z"];
465
+ /**
466
+ * An ordered array of each transformable value. By default, transform values
467
+ * will be sorted to this order.
468
+ */
469
+ const order = ["translate", "scale", "rotate", "skew"];
470
+ const transformAlias = {
471
+ x: "translateX",
472
+ y: "translateY",
473
+ z: "translateZ",
474
+ };
475
+ const rotation = {
476
+ syntax: "<angle>",
477
+ initialValue: "0deg",
478
+ toDefaultUnit: (v) => v + "deg",
479
+ };
480
+ const baseTransformProperties = {
481
+ translate: {
482
+ syntax: "<length-percentage>",
483
+ initialValue: "0px",
484
+ toDefaultUnit: (v) => v + "px",
485
+ },
486
+ rotate: rotation,
487
+ scale: {
488
+ syntax: "<number>",
489
+ initialValue: 1,
490
+ toDefaultUnit: noopReturn,
491
+ },
492
+ skew: rotation,
493
+ };
494
+ const transformDefinitions = new Map();
495
+ const asTransformCssVar = (name) => `--motion-${name}`;
496
+ /**
497
+ * Generate a list of every possible transform key
498
+ */
499
+ const transforms = ["x", "y", "z"];
500
+ order.forEach((name) => {
501
+ axes.forEach((axis) => {
502
+ transforms.push(name + axis);
503
+ transformDefinitions.set(asTransformCssVar(name + axis), baseTransformProperties[name]);
504
+ });
505
+ });
506
+ /**
507
+ * A function to use with Array.sort to sort transform keys by their default order.
508
+ */
509
+ const compareTransformOrder = (a, b) => transforms.indexOf(a) - transforms.indexOf(b);
510
+ /**
511
+ * Provide a quick way to check if a string is the name of a transform
512
+ */
513
+ const transformLookup = new Set(transforms);
514
+ const isTransform = (name) => transformLookup.has(name);
515
+ const addTransformToElement = (element, name) => {
516
+ // Map x to translateX etc
517
+ if (transformAlias[name])
518
+ name = transformAlias[name];
519
+ const { transforms } = getAnimationData(element);
520
+ addUniqueItem(transforms, name);
521
+ /**
522
+ * TODO: An optimisation here could be to cache the transform in element data
523
+ * and only update if this has changed.
524
+ */
525
+ element.style.transform = buildTransformTemplate(transforms);
526
+ };
527
+ const buildTransformTemplate = (transforms) => transforms
528
+ .sort(compareTransformOrder)
529
+ .reduce(transformListToString, "")
530
+ .trim();
531
+ const transformListToString = (template, name) => `${template} ${name}(var(${asTransformCssVar(name)}))`;
532
+
533
+ const isCssVar = (name) => name.startsWith("--");
534
+ const registeredProperties = new Set();
535
+ function registerCssVariable(name) {
536
+ if (registeredProperties.has(name))
537
+ return;
538
+ registeredProperties.add(name);
539
+ try {
540
+ const { syntax, initialValue } = transformDefinitions.has(name)
541
+ ? transformDefinitions.get(name)
542
+ : {};
543
+ CSS.registerProperty({
544
+ name,
545
+ inherits: false,
546
+ syntax,
547
+ initialValue,
548
+ });
549
+ }
550
+ catch (e) { }
551
+ }
552
+
553
+ const testAnimation = (keyframes, options) => document.createElement("div").animate(keyframes, options);
554
+ const featureTests = {
555
+ cssRegisterProperty: () => typeof CSS !== "undefined" &&
556
+ Object.hasOwnProperty.call(CSS, "registerProperty"),
557
+ waapi: () => Object.hasOwnProperty.call(Element.prototype, "animate"),
558
+ partialKeyframes: () => {
559
+ try {
560
+ testAnimation({ opacity: [1] });
561
+ }
562
+ catch (e) {
563
+ return false;
564
+ }
565
+ return true;
566
+ },
567
+ finished: () => Boolean(testAnimation({ opacity: [0, 1] }, { duration: 0.001 }).finished),
568
+ linearEasing: () => {
569
+ try {
570
+ testAnimation({ opacity: 0 }, { easing: "linear(0, 1)" });
571
+ }
572
+ catch (e) {
573
+ return false;
574
+ }
575
+ return true;
576
+ },
577
+ };
578
+ const results = {};
579
+ const supports = {};
580
+ for (const key in featureTests) {
581
+ supports[key] = () => {
582
+ if (results[key] === undefined)
583
+ results[key] =
584
+ featureTests[key]();
585
+ return results[key];
586
+ };
587
+ }
588
+
589
+ // Create a linear easing point for every x second
590
+ const resolution = 0.015;
591
+ const generateLinearEasingPoints = (easing, duration) => {
592
+ let points = "";
593
+ const numPoints = Math.round(duration / resolution);
594
+ for (let i = 0; i < numPoints; i++) {
595
+ points += easing(progress(0, numPoints - 1, i)) + ", ";
596
+ }
597
+ return points.substring(0, points.length - 2);
598
+ };
599
+ const convertEasing = (easing, duration) => {
600
+ if (isFunction(easing)) {
601
+ return supports.linearEasing()
602
+ ? `linear(${generateLinearEasingPoints(easing, duration)})`
603
+ : defaults.easing;
604
+ }
605
+ else {
606
+ return isCubicBezier(easing) ? cubicBezierAsString(easing) : easing;
607
+ }
608
+ };
609
+ const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
610
+
611
+ function hydrateKeyframes(keyframes, readInitialValue) {
612
+ for (let i = 0; i < keyframes.length; i++) {
613
+ if (keyframes[i] === null) {
614
+ keyframes[i] = i ? keyframes[i - 1] : readInitialValue();
615
+ }
616
+ }
617
+ return keyframes;
618
+ }
619
+ const keyframesList = (keyframes) => Array.isArray(keyframes) ? keyframes : [keyframes];
620
+
621
+ function getStyleName(key) {
622
+ if (transformAlias[key])
623
+ key = transformAlias[key];
624
+ return isTransform(key) ? asTransformCssVar(key) : key;
625
+ }
626
+
627
+ const style = {
628
+ get: (element, name) => {
629
+ name = getStyleName(name);
630
+ let value = isCssVar(name)
631
+ ? element.style.getPropertyValue(name)
632
+ : getComputedStyle(element)[name];
633
+ // TODO Decide if value can be 0
634
+ if (!value && value !== 0) {
635
+ const definition = transformDefinitions.get(name);
636
+ if (definition)
637
+ value = definition.initialValue;
638
+ }
639
+ return value;
640
+ },
641
+ set: (element, name, value) => {
642
+ name = getStyleName(name);
643
+ if (isCssVar(name)) {
644
+ element.style.setProperty(name, value);
645
+ }
646
+ else {
647
+ element.style[name] = value;
648
+ }
649
+ },
650
+ };
651
+
652
+ function stopAnimation(animation, needsCommit = true) {
653
+ if (!animation || animation.playState === "finished")
654
+ return;
655
+ // Suppress error thrown by WAAPI
656
+ try {
657
+ if (animation.stop) {
658
+ animation.stop();
659
+ }
660
+ else {
661
+ needsCommit && animation.commitStyles();
662
+ animation.cancel();
663
+ }
664
+ }
665
+ catch (e) { }
666
+ }
667
+
668
+ function getUnitConverter(keyframes, definition) {
669
+ var _a;
670
+ let toUnit = (definition === null || definition === void 0 ? void 0 : definition.toDefaultUnit) || noopReturn;
671
+ const finalKeyframe = keyframes[keyframes.length - 1];
672
+ if (isString(finalKeyframe)) {
673
+ const unit = ((_a = finalKeyframe.match(/(-?[\d.]+)([a-z%]*)/)) === null || _a === void 0 ? void 0 : _a[2]) || "";
674
+ if (unit)
675
+ toUnit = (value) => value + unit;
676
+ }
677
+ return toUnit;
678
+ }
679
+
680
+ function getDevToolsRecord() {
681
+ return window.__MOTION_DEV_TOOLS_RECORD;
682
+ }
683
+ function animateStyle(element, key, keyframesDefinition, options = {}, AnimationPolyfill) {
684
+ const record = getDevToolsRecord();
685
+ const isRecording = options.record !== false && record;
686
+ let animation;
687
+ let { duration = defaults.duration, delay = defaults.delay, endDelay = defaults.endDelay, repeat = defaults.repeat, easing = defaults.easing, persist = false, direction, offset, allowWebkitAcceleration = false, autoplay = true, } = options;
688
+ const data = getAnimationData(element);
689
+ const valueIsTransform = isTransform(key);
690
+ let canAnimateNatively = supports.waapi();
691
+ /**
692
+ * If this is an individual transform, we need to map its
693
+ * key to a CSS variable and update the element's transform style
694
+ */
695
+ valueIsTransform && addTransformToElement(element, key);
696
+ const name = getStyleName(key);
697
+ const motionValue = getMotionValue(data.values, name);
698
+ /**
699
+ * Get definition of value, this will be used to convert numerical
700
+ * keyframes into the default value type.
701
+ */
702
+ const definition = transformDefinitions.get(name);
703
+ /**
704
+ * Stop the current animation, if any. Because this will trigger
705
+ * commitStyles (DOM writes) and we might later trigger DOM reads,
706
+ * this is fired now and we return a factory function to create
707
+ * the actual animation that can get called in batch,
708
+ */
709
+ stopAnimation(motionValue.animation, !(isEasingGenerator(easing) && motionValue.generator) &&
710
+ options.record !== false);
711
+ /**
712
+ * Batchable factory function containing all DOM reads.
713
+ */
714
+ return () => {
715
+ const readInitialValue = () => { var _a, _b; return (_b = (_a = style.get(element, name)) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition.initialValue) !== null && _b !== void 0 ? _b : 0; };
716
+ /**
717
+ * Replace null values with the previous keyframe value, or read
718
+ * it from the DOM if it's the first keyframe.
719
+ */
720
+ let keyframes = hydrateKeyframes(keyframesList(keyframesDefinition), readInitialValue);
721
+ /**
722
+ * Detect unit type of keyframes.
723
+ */
724
+ const toUnit = getUnitConverter(keyframes, definition);
725
+ if (isEasingGenerator(easing)) {
726
+ const custom = easing.createAnimation(keyframes, key !== "opacity", readInitialValue, name, motionValue);
727
+ easing = custom.easing;
728
+ keyframes = custom.keyframes || keyframes;
729
+ duration = custom.duration || duration;
730
+ }
731
+ /**
732
+ * If this is a CSS variable we need to register it with the browser
733
+ * before it can be animated natively. We also set it with setProperty
734
+ * rather than directly onto the element.style object.
735
+ */
736
+ if (isCssVar(name)) {
737
+ if (supports.cssRegisterProperty()) {
738
+ registerCssVariable(name);
739
+ }
740
+ else {
741
+ canAnimateNatively = false;
742
+ }
743
+ }
744
+ /**
745
+ * If we've been passed a custom easing function, and this browser
746
+ * does **not** support linear() easing, and the value is a transform
747
+ * (and thus a pure number) we can still support the custom easing
748
+ * by falling back to the animation polyfill.
749
+ */
750
+ if (valueIsTransform &&
751
+ !supports.linearEasing() &&
752
+ (isFunction(easing) || (isEasingList(easing) && easing.some(isFunction)))) {
753
+ canAnimateNatively = false;
754
+ }
755
+ /**
756
+ * If we can animate this value with WAAPI, do so.
757
+ */
758
+ if (canAnimateNatively) {
759
+ /**
760
+ * Convert numbers to default value types. Currently this only supports
761
+ * transforms but it could also support other value types.
762
+ */
763
+ if (definition) {
764
+ keyframes = keyframes.map((value) => isNumber(value) ? definition.toDefaultUnit(value) : value);
765
+ }
766
+ /**
767
+ * If this browser doesn't support partial/implicit keyframes we need to
768
+ * explicitly provide one.
769
+ */
770
+ if (keyframes.length === 1 &&
771
+ (!supports.partialKeyframes() || isRecording)) {
772
+ keyframes.unshift(readInitialValue());
773
+ }
774
+ const animationOptions = {
775
+ delay: time.ms(delay),
776
+ duration: time.ms(duration),
777
+ endDelay: time.ms(endDelay),
778
+ easing: !isEasingList(easing)
779
+ ? convertEasing(easing, duration)
780
+ : undefined,
781
+ direction,
782
+ iterations: repeat + 1,
783
+ fill: "both",
784
+ };
785
+ animation = element.animate({
786
+ [name]: keyframes,
787
+ offset,
788
+ easing: isEasingList(easing)
789
+ ? easing.map((thisEasing) => convertEasing(thisEasing, duration))
790
+ : undefined,
791
+ }, animationOptions);
792
+ /**
793
+ * Polyfill finished Promise in browsers that don't support it
794
+ */
795
+ if (!animation.finished) {
796
+ animation.finished = new Promise((resolve, reject) => {
797
+ animation.onfinish = resolve;
798
+ animation.oncancel = reject;
799
+ });
800
+ }
801
+ const target = keyframes[keyframes.length - 1];
802
+ animation.finished
803
+ .then(() => {
804
+ if (persist)
805
+ return;
806
+ // Apply styles to target
807
+ style.set(element, name, target);
808
+ // Ensure fill modes don't persist
809
+ animation.cancel();
810
+ })
811
+ .catch(noop);
812
+ /**
813
+ * This forces Webkit to run animations on the main thread by exploiting
814
+ * this condition:
815
+ * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/platform/graphics/ca/GraphicsLayerCA.cpp?rev=281238#L1099
816
+ *
817
+ * This fixes Webkit's timing bugs, like accelerated animations falling
818
+ * out of sync with main thread animations and massive delays in starting
819
+ * accelerated animations in WKWebView.
820
+ */
821
+ if (!allowWebkitAcceleration)
822
+ animation.playbackRate = 1.000001;
823
+ /**
824
+ * If we can't animate the value natively then we can fallback to the numbers-only
825
+ * polyfill for transforms.
826
+ */
827
+ }
828
+ else if (AnimationPolyfill && valueIsTransform) {
829
+ /**
830
+ * If any keyframe is a string (because we measured it from the DOM), we need to convert
831
+ * it into a number before passing to the Animation polyfill.
832
+ */
833
+ keyframes = keyframes.map((value) => typeof value === "string" ? parseFloat(value) : value);
834
+ /**
835
+ * If we only have a single keyframe, we need to create an initial keyframe by reading
836
+ * the current value from the DOM.
837
+ */
838
+ if (keyframes.length === 1) {
839
+ keyframes.unshift(parseFloat(readInitialValue()));
840
+ }
841
+ animation = new AnimationPolyfill((latest) => {
842
+ style.set(element, name, toUnit ? toUnit(latest) : latest);
843
+ }, keyframes, Object.assign(Object.assign({}, options), { duration,
844
+ easing }));
845
+ }
846
+ else {
847
+ const target = keyframes[keyframes.length - 1];
848
+ style.set(element, name, definition && isNumber(target)
849
+ ? definition.toDefaultUnit(target)
850
+ : target);
851
+ }
852
+ if (isRecording) {
853
+ record(element, key, keyframes, {
854
+ duration,
855
+ delay: delay,
856
+ easing,
857
+ repeat,
858
+ offset,
859
+ }, "motion-one");
860
+ }
861
+ motionValue.setAnimation(animation);
862
+ if (animation && !autoplay)
863
+ animation.pause();
864
+ return animation;
865
+ };
866
+ }
867
+
868
+ const getOptions = (options, key) =>
869
+ /**
870
+ * TODO: Make test for this
871
+ * Always return a new object otherwise delay is overwritten by results of stagger
872
+ * and this results in no stagger
873
+ */
874
+ options[key] ? Object.assign(Object.assign({}, options), options[key]) : Object.assign({}, options);
875
+
876
+ function resolveElements(elements, selectorCache) {
877
+ var _a;
878
+ if (typeof elements === "string") {
879
+ if (selectorCache) {
880
+ (_a = selectorCache[elements]) !== null && _a !== void 0 ? _a : (selectorCache[elements] = document.querySelectorAll(elements));
881
+ elements = selectorCache[elements];
882
+ }
883
+ else {
884
+ elements = document.querySelectorAll(elements);
885
+ }
886
+ }
887
+ else if (elements instanceof Element) {
888
+ elements = [elements];
889
+ }
890
+ /**
891
+ * Return an empty array
892
+ */
893
+ return Array.from(elements || []);
894
+ }
895
+
896
+ const createAnimation = (factory) => factory();
897
+ const withControls = (animationFactory, options, duration = defaults.duration) => {
898
+ return new Proxy({
899
+ animations: animationFactory.map(createAnimation).filter(Boolean),
900
+ duration,
901
+ options,
902
+ }, controls);
903
+ };
904
+ /**
905
+ * TODO:
906
+ * Currently this returns the first animation, ideally it would return
907
+ * the first active animation.
908
+ */
909
+ const getActiveAnimation = (state) => state.animations[0];
910
+ const controls = {
911
+ get: (target, key) => {
912
+ const activeAnimation = getActiveAnimation(target);
913
+ switch (key) {
914
+ case "duration":
915
+ return target.duration;
916
+ case "currentTime":
917
+ return time.s((activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) || 0);
918
+ case "playbackRate":
919
+ case "playState":
920
+ return activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key];
921
+ case "finished":
922
+ if (!target.finished) {
923
+ target.finished = Promise.all(target.animations.map(selectFinished)).catch(noop);
924
+ }
925
+ return target.finished;
926
+ case "stop":
927
+ return () => {
928
+ target.animations.forEach((animation) => stopAnimation(animation));
929
+ };
930
+ case "forEachNative":
931
+ /**
932
+ * This is for internal use only, fire a callback for each
933
+ * underlying animation.
934
+ */
935
+ return (callback) => {
936
+ target.animations.forEach((animation) => callback(animation, target));
937
+ };
938
+ default:
939
+ return typeof (activeAnimation === null || activeAnimation === void 0 ? void 0 : activeAnimation[key]) ===
940
+ "undefined"
941
+ ? undefined
942
+ : () => target.animations.forEach((animation) => animation[key]());
943
+ }
944
+ },
945
+ set: (target, key, value) => {
946
+ switch (key) {
947
+ case "currentTime":
948
+ value = time.ms(value);
949
+ // Fall-through
950
+ case "playbackRate":
951
+ for (let i = 0; i < target.animations.length; i++) {
952
+ target.animations[i][key] = value;
953
+ }
954
+ return true;
955
+ }
956
+ return false;
957
+ },
958
+ };
959
+ const selectFinished = (animation) => animation.finished;
960
+
961
+ function resolveOption(option, i, total) {
962
+ return isFunction(option) ? option(i, total) : option;
963
+ }
964
+
965
+ function createAnimate(AnimatePolyfill) {
966
+ return function animate(elements, keyframes, options = {}) {
967
+ elements = resolveElements(elements);
968
+ const numElements = elements.length;
969
+ invariant(Boolean(numElements), "No valid element provided.");
970
+ invariant(Boolean(keyframes), "No keyframes defined.");
971
+ /**
972
+ * Create and start new animations
973
+ */
974
+ const animationFactories = [];
975
+ for (let i = 0; i < numElements; i++) {
976
+ const element = elements[i];
977
+ for (const key in keyframes) {
978
+ const valueOptions = getOptions(options, key);
979
+ valueOptions.delay = resolveOption(valueOptions.delay, i, numElements);
980
+ const animation = animateStyle(element, key, keyframes[key], valueOptions, AnimatePolyfill);
981
+ animationFactories.push(animation);
982
+ }
983
+ }
984
+ return withControls(animationFactories, options,
985
+ /**
986
+ * TODO:
987
+ * If easing is set to spring or glide, duration will be dynamically
988
+ * generated. Ideally we would dynamically generate this from
989
+ * animation.effect.getComputedTiming().duration but this isn't
990
+ * supported in iOS13 or our number polyfill. Perhaps it's possible
991
+ * to Proxy animations returned from animateStyle that has duration
992
+ * as a getter.
993
+ */
994
+ options.duration);
995
+ };
996
+ }
997
+
998
+ const animate$1 = createAnimate(Animation);
999
+
1000
+ function animateProgress(target, options = {}) {
1001
+ return withControls([
1002
+ () => {
1003
+ const animation = new Animation(target, [0, 1], options);
1004
+ animation.finished.catch(() => { });
1005
+ return animation;
1006
+ },
1007
+ ], options, options.duration);
1008
+ }
1009
+ function animate(target, keyframesOrOptions, options) {
1010
+ const factory = isFunction(target) ? animateProgress : animate$1;
1011
+ return factory(target, keyframesOrOptions, options);
1012
+ }
1013
+
1014
+ const POSITIONS = [
1015
+ 'top-left',
1016
+ 'top-center',
1017
+ 'top-right',
1018
+ 'bottom-left',
1019
+ 'bottom-center',
1020
+ 'bottom-right'
1021
+ ];
1022
+ function createContainer(position, root) {
1023
+ const c = document.createElement('div');
1024
+ c.className = 'sileo-toaster';
1025
+ c.setAttribute('data-position', position);
1026
+ c.setAttribute('role', 'status');
1027
+ c.setAttribute('aria-live', 'polite');
1028
+ return c;
1029
+ }
1030
+ function renderToast(item) {
1031
+ const el = document.createElement('div');
1032
+ el.className = 'sileo-toast';
1033
+ el.dataset.id = item.id;
1034
+ el.setAttribute('data-type', item.options.type || 'info');
1035
+ el.style.opacity = '0';
1036
+ el.style.transform = 'translateY(-6px)';
1037
+ const body = document.createElement('div');
1038
+ body.style.display = 'flex';
1039
+ body.style.flexDirection = 'column';
1040
+ body.style.flex = '1';
1041
+ const header = document.createElement('div');
1042
+ header.className = 'sileo-toast-header';
1043
+ header.textContent = item.options.title || '';
1044
+ body.appendChild(header);
1045
+ if (item.options.description) {
1046
+ const desc = document.createElement('div');
1047
+ desc.className = 'sileo-toast-desc';
1048
+ desc.textContent = item.options.description;
1049
+ body.appendChild(desc);
1050
+ }
1051
+ el.appendChild(body);
1052
+ if (item.options.button) {
1053
+ const btn = document.createElement('button');
1054
+ btn.className = 'sileo-toast-btn';
1055
+ btn.textContent = item.options.button.title;
1056
+ btn.addEventListener('click', (e) => {
1057
+ e.stopPropagation();
1058
+ try {
1059
+ if (item.options.button && typeof item.options.button.onClick === 'function') {
1060
+ item.options.button.onClick();
1061
+ }
1062
+ }
1063
+ catch (err) {
1064
+ console.error(err);
1065
+ }
1066
+ });
1067
+ el.appendChild(btn);
1068
+ }
1069
+ const close = document.createElement('button');
1070
+ close.className = 'sileo-toast-close';
1071
+ close.innerHTML = '×';
1072
+ close.addEventListener('click', () => sileo.dismiss(item.id));
1073
+ el.appendChild(close);
1074
+ if (typeof item.options.duration === 'number') {
1075
+ if (item.options.duration > 0) {
1076
+ setTimeout(() => sileo.dismiss(item.id), item.options.duration);
1077
+ }
1078
+ }
1079
+ return el;
1080
+ }
1081
+ function initToasters(root = document.body, positions = ['top-right']) {
1082
+ const containers = {};
1083
+ positions.forEach((pos) => {
1084
+ const c = createContainer(pos);
1085
+ root.appendChild(c);
1086
+ containers[pos] = c;
1087
+ });
1088
+ function rerender(items) {
1089
+ positions.forEach((pos) => {
1090
+ const container = containers[pos];
1091
+ const visible = items.filter((t) => (t.options.position || 'top-right') === pos);
1092
+ // Diff existing children and animate out removed toasts
1093
+ const visibleIds = new Set(visible.map((v) => v.id));
1094
+ const existing = Array.from(container.children);
1095
+ existing.forEach((child) => {
1096
+ const id = child.dataset.id;
1097
+ if (!id || !visibleIds.has(id)) {
1098
+ // animate out then remove
1099
+ animate(child, { opacity: 0, y: -8 }, { duration: 0.18 }).finished.then(() => child.remove());
1100
+ }
1101
+ });
1102
+ // Add new items
1103
+ visible.forEach((t) => {
1104
+ if (!container.querySelector(`[data-id="${t.id}"]`)) {
1105
+ const node = renderToast(t);
1106
+ container.appendChild(node);
1107
+ // animate in
1108
+ requestAnimationFrame(() => {
1109
+ animate(node, { opacity: [0, 1], y: [-6, 0] }, { duration: 0.24 });
1110
+ });
1111
+ }
1112
+ });
1113
+ });
1114
+ }
1115
+ const unsub = sileo.subscribe(rerender);
1116
+ return {
1117
+ destroy() {
1118
+ unsub();
1119
+ Object.values(containers).forEach((c) => c.remove());
1120
+ }
1121
+ };
1122
+ }
1123
+
1124
+ // convenience: keep the previous shape where `notify` was the quick-show function
1125
+ const notify = notify$1.show.bind(notify$1);
1126
+ const defaultExport = { sileo: sileo, initToasters, notify, controller: notify$1 };
1127
+ // backward compatibility: expose `notifications` key pointing to the same API object
1128
+ defaultExport.notifications = defaultExport;
1129
+
1130
+ exports.POSITIONS = POSITIONS;
1131
+ exports.default = defaultExport;
1132
+ exports.initToasters = initToasters;
1133
+ exports.notify = notify;
1134
+
1135
+ Object.defineProperty(exports, '__esModule', { value: true });
1136
+
1137
+ }));