forked from formkit/auto-animate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
509 lines (508 loc) · 15.9 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/**
* A set of all the parents currently being observe. This is the only non weak
* registry.
*/
const parents = new Set();
/**
* Element coordinates that is constantly kept up to date.
*/
const coords = new WeakMap();
/**
* Siblings of elements that have been removed from the dom.
*/
const siblings = new WeakMap();
/**
* Animations that are currently running.
*/
const animations = new WeakMap();
/**
* A map of existing intersection observers used to track element movements.
*/
const intersections = new WeakMap();
/**
* Intervals for automatically checking the position of elements occasionally.
*/
const intervals = new WeakMap();
/**
* The configuration options for each group of elements.
*/
const options = new WeakMap();
/**
* Debounce counters by id, used to debounce calls to update positions.
*/
const debounces = new WeakMap();
/**
* The document used to calculate transitions.
*/
let root;
/**
* Used to sign an element as the target.
*/
const TGT = "__aa_tgt";
/**
* Used to sign an element as being part of a removal.
*/
const DEL = "__aa_del";
/**
* Callback for handling all mutations.
* @param mutations - A mutation list
*/
const handleMutations = (mutations) => {
const elements = getElements(mutations);
// If elements is "false" that means this mutation that should be ignored.
if (elements) {
elements.forEach((el) => animate(el));
}
};
/**
*
* @param entries - Elements that have been resized.
*/
const handleResizes = (entries) => {
entries.forEach((entry) => {
if (entry.target === root)
updateAllPos();
if (coords.has(entry.target))
updatePos(entry.target);
});
};
/**
* Observe this elements position.
* @param el - The element to observe the position of.
*/
function observePosition(el) {
const oldObserver = intersections.get(el);
oldObserver === null || oldObserver === void 0 ? void 0 : oldObserver.disconnect();
let rect = coords.get(el);
let invocations = 0;
const buffer = 5;
if (!rect) {
rect = getCoords(el);
coords.set(el, rect);
}
const { offsetWidth, offsetHeight } = root;
const rootMargins = [
rect.top - buffer,
offsetWidth - (rect.left + buffer + rect.width),
offsetHeight - (rect.top + buffer + rect.height),
rect.left - buffer,
];
const rootMargin = rootMargins
.map((px) => `${-1 * Math.floor(px)}px`)
.join(" ");
const observer = new IntersectionObserver(() => {
++invocations > 1 && updatePos(el);
}, {
root,
threshold: 1,
rootMargin,
});
observer.observe(el);
intersections.set(el, observer);
}
/**
* Update the exact position of a given element.
* @param el - An element to update the position of.
*/
function updatePos(el) {
clearTimeout(debounces.get(el));
const optionsOrPlugin = getOptions(el);
const delay = typeof optionsOrPlugin === "function" ? 500 : optionsOrPlugin.duration;
debounces.set(el, setTimeout(() => {
const currentAnimation = animations.get(el);
if (!currentAnimation || currentAnimation.finished) {
coords.set(el, getCoords(el));
observePosition(el);
}
}, delay));
}
/**
* Updates all positions that are currently being tracked.
*/
function updateAllPos() {
clearTimeout(debounces.get(root));
debounces.set(root, setTimeout(() => {
parents.forEach((parent) => forEach(parent, (el) => lowPriority(() => updatePos(el))));
}, 100));
}
/**
* Its possible for a quick scroll or other fast events to get past the
* intersection observer, so occasionally we need want "cold-poll" for the
* latests and greatest position. We try to do this in the most non-disruptive
* fashion possible. First we only do this ever couple seconds, staggard by a
* random offset.
* @param el - Element
*/
function poll(el) {
setTimeout(() => {
intervals.set(el, setInterval(() => lowPriority(updatePos.bind(null, el)), 2000));
}, Math.round(2000 * Math.random()));
}
/**
* Perform some operation that is non critical at some point.
* @param callback
*/
function lowPriority(callback) {
if (typeof requestIdleCallback === "function") {
requestIdleCallback(() => callback());
}
else {
requestAnimationFrame(() => callback());
}
}
/**
* The mutation observer responsible for watching each root element.
*/
let mutations;
/**
* A resize observer, responsible for recalculating elements on resize.
*/
let resize;
/**
* If this is in a browser, initialize our Web APIs
*/
if (typeof window !== "undefined") {
root = document.documentElement;
mutations = new MutationObserver(handleMutations);
resize = new ResizeObserver(handleResizes);
resize.observe(root);
}
/**
* Retrieves all the elements that may have been affected by the last mutation
* including ones that have been removed and are no longer in the DOM.
* @param mutations - A mutation list.
* @returns
*/
function getElements(mutations) {
return mutations.reduce((elements, mutation) => {
// Short circuit if we find a purposefully deleted node.
if (elements === false)
return false;
if (mutation.target instanceof Element) {
target(mutation.target);
if (!elements.has(mutation.target)) {
elements.add(mutation.target);
for (let i = 0; i < mutation.target.children.length; i++) {
const child = mutation.target.children.item(i);
if (!child)
continue;
if (DEL in child)
return false;
target(mutation.target, child);
elements.add(child);
}
}
if (mutation.removedNodes.length) {
for (let i = 0; i < mutation.removedNodes.length; i++) {
const child = mutation.removedNodes[i];
if (DEL in child)
return false;
if (child instanceof Element) {
elements.add(child);
target(mutation.target, child);
siblings.set(child, [
mutation.previousSibling,
mutation.nextSibling,
]);
}
}
}
}
return elements;
}, new Set());
}
/**
*
* @param el - The root element
* @param child
*/
function target(el, child) {
if (!child && !(TGT in el))
Object.defineProperty(el, TGT, { value: el });
else if (child && !(TGT in child))
Object.defineProperty(child, TGT, { value: el });
}
/**
* Determines what kind of change took place on the given element and then
* performs the proper animation based on that.
* @param el - The specific element to animate.
*/
function animate(el) {
var _a;
const isMounted = root.contains(el);
const preExisting = coords.has(el);
if (isMounted && siblings.has(el))
siblings.delete(el);
if (animations.has(el)) {
(_a = animations.get(el)) === null || _a === void 0 ? void 0 : _a.cancel();
}
if (preExisting && isMounted) {
remain(el);
}
else if (preExisting && !isMounted) {
remove(el);
}
else {
add(el);
}
}
/**
* Removes all non-digits from a string and casts to a number.
* @param str - A string containing a pixel value.
* @returns
*/
function raw(str) {
return Number(str.replace(/[^0-9.\-]/g, ""));
}
/**
* Get the coordinates of elements adjusted for scroll position.
* @param el - Element
* @returns
*/
function getCoords(el) {
const rect = el.getBoundingClientRect();
const optionsOrPlugin = getOptions(el);
const offsetY = typeof optionsOrPlugin !== "function" && optionsOrPlugin.scrollContainer
? optionsOrPlugin.scrollContainer.scrollTop
: window.scrollY;
const offsetX = typeof optionsOrPlugin !== "function" && optionsOrPlugin.scrollContainer
? optionsOrPlugin.scrollContainer.scrollLeft
: window.scrollX;
return {
top: rect.top + offsetY,
left: rect.left + offsetX,
width: rect.width,
height: rect.height,
};
}
/**
* Returns the width/height that the element should be transitioned between.
* This takes into account box-sizing.
* @param el - Element being animated
* @param oldCoords - Old set of Coordinates coordinates
* @param newCoords - New set of Coordinates coordinates
* @returns
*/
function getTransitionSizes(el, oldCoords, newCoords) {
let widthFrom = oldCoords.width;
let heightFrom = oldCoords.height;
let widthTo = newCoords.width;
let heightTo = newCoords.height;
const styles = getComputedStyle(el);
const sizing = styles.getPropertyValue("box-sizing");
if (sizing === "content-box") {
const paddingY = raw(styles.paddingTop) +
raw(styles.paddingBottom) +
raw(styles.borderTopWidth) +
raw(styles.borderBottomWidth);
const paddingX = raw(styles.paddingLeft) +
raw(styles.paddingRight) +
raw(styles.borderRightWidth) +
raw(styles.borderLeftWidth);
widthFrom -= paddingX;
widthTo -= paddingX;
heightFrom -= paddingY;
heightTo -= paddingY;
}
return [widthFrom, widthTo, heightFrom, heightTo].map(Math.round);
}
/**
* Retrieves animation options for the current element.
* @param el - Element to retrieve options for.
* @returns
*/
function getOptions(el) {
return TGT in el && options.has(el[TGT])
? options.get(el[TGT])
: { duration: 250, easing: "ease-in-out" };
}
/**
* Iterate over the children of a given parent.
* @param parent - A parent element
* @param callback - A callback
*/
function forEach(parent, ...callbacks) {
callbacks.forEach((callback) => callback(parent, options.has(parent)));
for (let i = 0; i < parent.children.length; i++) {
const child = parent.children.item(i);
if (child) {
callbacks.forEach((callback) => callback(child, options.has(child)));
}
}
}
/**
* The element in question is remaining in the DOM.
* @param el - Element to flip
* @returns
*/
function remain(el) {
const oldCoords = coords.get(el);
const newCoords = getCoords(el);
let animation;
if (!oldCoords)
return;
const pluginOrOptions = getOptions(el);
if (typeof pluginOrOptions !== "function") {
const deltaX = oldCoords.left - newCoords.left;
const deltaY = oldCoords.top - newCoords.top;
const [widthFrom, widthTo, heightFrom, heightTo] = getTransitionSizes(el, oldCoords, newCoords);
const start = {
transform: `translate(${deltaX}px, ${deltaY}px)`,
};
const end = {
transform: `translate(0, 0)`,
};
if (widthFrom !== widthTo) {
start.width = `${widthFrom}px`;
end.width = `${widthTo}px`;
}
if (heightFrom !== heightTo) {
start.height = `${heightFrom}px`;
end.height = `${heightTo}px`;
}
animation = el.animate([start, end], pluginOrOptions);
}
else {
animation = new Animation(pluginOrOptions(el, "remain", oldCoords, newCoords));
animation.play();
}
animations.set(el, animation);
coords.set(el, newCoords);
animation.addEventListener("finish", updatePos.bind(null, el));
}
/**
* Adds the element with a transition.
* @param el - Animates the element being added.
*/
function add(el) {
const newCoords = getCoords(el);
coords.set(el, newCoords);
const pluginOrOptions = getOptions(el);
let animation;
if (typeof pluginOrOptions !== "function") {
animation = el.animate([
{ transform: "scale(.98)", opacity: 0 },
{ transform: "scale(0.98)", opacity: 0, offset: 0.5 },
{ transform: "scale(1)", opacity: 1 },
], {
duration: pluginOrOptions.duration * 1.5,
easing: "ease-in",
});
}
else {
animation = new Animation(pluginOrOptions(el, "add", newCoords));
animation.play();
}
animations.set(el, animation);
animation.addEventListener("finish", updatePos.bind(null, el));
}
/**
* Animates the removal of an element.
* @param el - Element to remove
*/
function remove(el) {
if (!siblings.has(el) || !coords.has(el))
return;
const [prev, next] = siblings.get(el);
Object.defineProperty(el, DEL, { value: true });
if (next && next.parentNode && next.parentNode instanceof Element) {
next.parentNode.insertBefore(el, next);
}
else if (prev && prev.parentNode) {
prev.parentNode.appendChild(el);
}
const [top, left, width, height] = deletePosition(el);
const optionsOrPlugin = getOptions(el);
const oldCoords = coords.get(el);
let animation;
Object.assign(el.style, {
position: "absolute",
top: `${top}px`,
left: `${left}px`,
width: `${width}px`,
height: `${height}px`,
margin: 0,
pointerEvents: "none",
transformOrigin: "center",
zIndex: 100,
});
if (typeof optionsOrPlugin !== "function") {
animation = el.animate([
{
transform: "scale(1)",
opacity: 1,
},
{
transform: "scale(.98)",
opacity: 0,
},
], { duration: optionsOrPlugin.duration, easing: "ease-out" });
}
else {
animation = new Animation(optionsOrPlugin(el, "remove", oldCoords));
animation.play();
}
animations.set(el, animation);
animation.addEventListener("finish", () => {
var _a;
el.remove();
coords.delete(el);
siblings.delete(el);
animations.delete(el);
(_a = intersections.get(el)) === null || _a === void 0 ? void 0 : _a.disconnect();
});
}
function deletePosition(el) {
const oldCoords = coords.get(el);
const [width, , height] = getTransitionSizes(el, oldCoords, getCoords(el));
let offsetParent = el.parentElement;
while (offsetParent &&
(getComputedStyle(offsetParent).position === "static" ||
offsetParent instanceof HTMLBodyElement)) {
offsetParent = offsetParent.parentElement;
}
if (!offsetParent)
offsetParent = document.body;
const parentStyles = getComputedStyle(offsetParent);
const parentCoords = coords.get(offsetParent) || getCoords(offsetParent);
const top = Math.round(oldCoords.top - parentCoords.top) -
raw(parentStyles.borderTopWidth);
const left = Math.round(oldCoords.left - parentCoords.left) -
raw(parentStyles.borderLeftWidth);
return [top, left, width, height];
}
/**
* A function that automatically adds animation effects to itself and its
* immediate children. Specifically it adds effects for adding, moving, and
* removing DOM elements.
* @param el - A parent element to add animations to.
* @param options - An optional object of options.
*/
function autoAnimate(el, config = {}) {
if (mutations && resize) {
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
if (mediaQuery.matches)
return;
if (getComputedStyle(el).position === "static") {
Object.assign(el.style, { position: "relative" });
}
forEach(el, updatePos, poll, (element) => resize === null || resize === void 0 ? void 0 : resize.observe(element));
if (typeof config === "function") {
options.set(el, config);
}
else {
options.set(el, { duration: 250, easing: "ease-in-out", ...config });
}
mutations.observe(el, { childList: true });
parents.add(el);
}
}
/**
* The vue directive.
*/
const vAutoAnimate = {
mounted: (el, binding) => {
autoAnimate(el, binding.value || {});
},
};
export { autoAnimate as default, getTransitionSizes, vAutoAnimate };