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