Skip to content

Commit

Permalink
Remove Animate.js
Browse files Browse the repository at this point in the history
Following up on the previous change to use CSS animations in Overlay.js
instead of my homegrown solution, this change replaces all uses of
Animate.js with built-in animations. The result is a markedly better
experience for all transitions (even if not everything translated 1:1).
The difference is especially noticeable on HFR monitors, as my old
hacked-together animation library limited transitions to 60 FPS.

Core change:
* Replace all Animation calls with ele.animate
* Create AnimationHelpers.js with (awaitable) helpers for common
  animation scenarios.
* Delete Animate.js

A few other tangential changes were made as well:
* Better purge table row removal animation - work around tr height
  limitations to allow a smooth slide up when a row is removed.
* Add getHex helper to ThemeColors to retrieve a full hex color string
  (with optional opacity).
* Fix a bug that prevented PurgedMarkerManager's "ignored failed"
  animation from triggering.
* Rework #clearOverlayAfterPurge to make use of Overlay's new
  replace-in-place support.
  • Loading branch information
danrahn committed Nov 5, 2023
1 parent fd12589 commit 0e9a285
Show file tree
Hide file tree
Showing 11 changed files with 232 additions and 443 deletions.
143 changes: 143 additions & 0 deletions Client/Script/AnimationHelpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { ConsoleLog, ContextualLog } from '../../Shared/ConsoleLog.js';
import { $$ } from './Common.js';

const Log = new ContextualLog('Animate');

/**
* Helper that parses animation method calls and logs to TMI output
* @param {string} method
* @param {HTMLElement} element
* @param {object} params */
const logAnimate = (method, element, params) => {
// Avoid unnecessary parsing if we're not going to show it
if (Log.getLevel() > ConsoleLog.Level.Tmi) { return; }

let msg = `method=${method}`;
for (const [key, value] of Object.entries(params)) {
let displayValue = value;
if (typeof value === 'object') {
// Assume JSON
displayValue = JSON.stringify(value);
} else if (typeof value === 'function') {
displayValue = value.name || '(anonymous)';
}

msg += `; ${key}=${displayValue}`;
}

Log.tmi(element, msg + '; element=');
};

/**
* Flashes the background of the given element
* @param {string|HTMLElement} ele The id of the element to animate, or the element itself.
* @param {string} color The color to flash.
* @param {number} [duration=500] The animation duration.
* @param {() => any} [callback]
* @returns {Promise<void>} */
export function flashBackground(ele, color, duration=1000, callback) {
logAnimate('flashBackground', ele, { color, duration, callback });
const button = typeof ele === 'string' ? $$(`#${ele}`) : ele;
if (!button) { Log.warn(`flashBackground - Didn't find button`); return Promise.resolve(); }

const initialColor = button.style.backgroundColor ?? 'transparent';
return new Promise(resolve => {
button.animate([
{ backgroundColor : initialColor },
{ backgroundColor : color, offset : 0.25 },
{ backgroundColor : color, offset : 0.75 },
{ backgroundColor : initialColor },
], {
duration
}).addEventListener('finish', async () => {
await callback?.();
resolve();
});
});
}

/**
* Returns a promise that resolve when the given element has finished animating its opacity.
* NOTE: Could probably be a Common.js method that generalizes "awaitable animate" if/when I get
* around to removing more usage of Animate.js
* @param {HTMLElement} ele The element to animate
* @param {number} start The starting opacity for the element
* @param {number} end The end opacity for the element
* @param {number|KeyframeAnimationOptions} options The length of the animation
* @param {boolean|() => any} [callback] Either a boolean value indicating whether to remove the element
* after the transition is complete, or a custom callback function.
* @returns {Promise<void>} */
export function animateOpacity(ele, start, end, options, callback) {
logAnimate('animateOpacity', ele, { start, end, options, callback });
return new Promise(resolve => {
ele.animate({ opacity : [start, end] }, options)
.addEventListener('finish', async () => {
if (callback) {
if (typeof callback === 'boolean') {
ele.parentElement.removeChild(ele);
} else if (typeof callback === 'function') {
await callback();
} else {
Log.warn(`animateOpacity options must be a boolean or a function.`);
}
}

resolve();
});
});
}

/**
* Shrink the height of ele to 0 while also fading out the content.
* @param {HTMLElement} ele
* @param {number|KeyframeAnimationOptions} options
* @param {(...any) => any} [callback]
* @returns {Promise<void>} */
export function slideUp(ele, options, callback) {
logAnimate('slideUp', ele, { options, callback });
// Initial setup:
// * Get the current height of the container so we have a known starting point
// * Set overflow to hidden so content doesn't "escape" when the element shrinks away
// * Explicitly set the height of the element BEFORE setting overflow:hidden, because
// overflow:hidden disables margin collapsing, so might increase the height of the element
// right before animating.
let startingHeight = ele.style.height;
if (!startingHeight) {
const bounds = ele.getBoundingClientRect();
startingHeight = (bounds.height) + 'px';
ele.style.height = startingHeight;
}

ele.style.overflow = 'hidden';

return new Promise(resolve => {
ele.animate(
[
{ opacity : 1, height : startingHeight, easing : 'ease-out' },
{ opacity : 0, height : '0px' }
],
options
).addEventListener('finish', async () => {
await callback?.();
resolve();
});
});
}

/**
* Thin wrapper around Element.animate that returns a promise that resolves when
* the animation is complete.
* @param {HTMLElement} ele
* @param {Keyframe[] | PropertyIndexedKeyframes} keyframes
* @param {number} duration
* @param {(...any) => any} callback
* @returns {Promise<void>} */
export function animate(ele, keyframes, duration, callback) {
logAnimate('animate', { keyframes, duration, callback });
return new Promise(resolve => {
ele.animate(keyframes, duration).addEventListener('finish', async () => {
await callback?.(); // Not necessarily async, but if it is, wait for it to complete.
resolve();
});
});
}
13 changes: 3 additions & 10 deletions Client/Script/BulkActionCommon.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { $, $$, appendChildren, buildNode } from './Common.js';
import { ContextualLog } from '../../Shared/ConsoleLog.js';

import Animation from './inc/Animate.js';

import { flashBackground } from './AnimationHelpers.js';
import { MarkerData } from '../../Shared/PlexTypes.js';
import { MarkerEnum } from '../../Shared/MarkerType.js';
import Overlay from './inc/Overlay.js';
Expand Down Expand Up @@ -512,14 +511,8 @@ class BulkActionCommon {
* @param {string|HTMLElement} buttonId
* @param {string} color
* @param {number} [duration=500] */
static async flashButton(buttonId, color, duration=500) {
const button = typeof buttonId === 'string' ? $(`#${buttonId}`) : buttonId;
if (!button) { Log.warn(`BulkActionCommon::flashButton - Didn't find button`); return Promise.resolve(); }

Animation.queue({ backgroundColor : `#${ThemeColors.get(color)}4` }, button, duration);
return new Promise((resolve, _) => {
Animation.queueDelayed({ backgroundColor : 'transparent' }, button, duration, duration, true, resolve);
});
static async flashButton(buttonId, color, duration=1000) {
return flashBackground(buttonId, ThemeColors.getHex(color, 4), duration);
}

/**
Expand Down
8 changes: 4 additions & 4 deletions Client/Script/BulkAddOverlay.js
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ class BulkAddOverlay {

await this.#postProcessBulkAdd(result);
} catch (err) {
await BulkActionCommon.flashButton('bulkAddApply', 'red', 250);
await BulkActionCommon.flashButton('bulkAddApply', 'red', 500);
errorResponseOverlay('Unable to bulk add, please try again later', err, this.show.bind(this));
}
}
Expand Down Expand Up @@ -467,7 +467,7 @@ class BulkAddOverlay {

await this.#postProcessBulkAdd(result);
} catch (err) {
await BulkActionCommon.flashButton('bulkAddApply', 'red', 250);
await BulkActionCommon.flashButton('bulkAddApply', 'red', 500);
errorResponseOverlay('Unable to bulk add, please try again later', err, this.show.bind(this));
}
}
Expand All @@ -477,7 +477,7 @@ class BulkAddOverlay {
* @param {SerializedBulkAddResult} result */
async #postProcessBulkAdd(result) {
if (!result.applied) {
BulkActionCommon.flashButton('bulkAddApply', 'red', 250);
BulkActionCommon.flashButton('bulkAddApply', 'red', 500);
return;
}

Expand Down Expand Up @@ -509,7 +509,7 @@ class BulkAddOverlay {
episodeInfo.isAdd ? ++addCount : ++editCount;
}

BulkActionCommon.flashButton('bulkAddApply', 'green', 250).then(() => {
BulkActionCommon.flashButton('bulkAddApply', 'green', 500).then(() => {
Overlay.show(`<h2>Bulk Add Succeeded</h2><hr>` +
`Markers Added: ${addCount}<br>` +
`Markers Edited: ${editCount}<br>` +
Expand Down
2 changes: 1 addition & 1 deletion Client/Script/BulkDeleteOverlay.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ class BulkDeleteOverlay {

this.#showCustomizationTable();
} catch (err) {
await BulkActionCommon.flashButton('deleteApply', 'red', 250);
await BulkActionCommon.flashButton('deleteApply', 'red', 500);
errorResponseOverlay('Unable to bulk delete, please try again later', err, this.show.bind(this));
}
}
Expand Down
7 changes: 2 additions & 5 deletions Client/Script/FilterDialog.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { $, $$, appendChildren, buildNode } from './Common.js';

import Animation from './inc/Animate.js';
import Overlay from './inc/Overlay.js';

import ButtonCreator from './ButtonCreator.js';
import { ContextualLog } from '../../Shared/ConsoleLog.js';
import { flashBackground } from './AnimationHelpers.js';
import MarkerBreakdown from '../../Shared/MarkerBreakdown.js';
import { PlexUI } from './PlexUI.js';
import { SectionType } from '../../Shared/PlexTypes.js';
Expand Down Expand Up @@ -390,10 +390,7 @@ class FilterDialog {
* Flash the background of the given element.
* @param {HTMLElement} input */
#flashInput(input) {
Animation.queue({ backgroundColor : `#${ThemeColors.get('red')}8` }, input, 500);
return new Promise((resolve, _) => {
Animation.queueDelayed({ backgroundColor : 'transparent' }, input, 500, 500, true, resolve);
});
return flashBackground(input, ThemeColors.getHex('red', 8), 1000);
}

/**
Expand Down

0 comments on commit 0e9a285

Please sign in to comment.