@samline/notify 0.1.1 → 0.1.7

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