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