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