diff --git a/packages/animate/README.md b/packages/animate/README.md index c25608f..2a3bee4 100644 --- a/packages/animate/README.md +++ b/packages/animate/README.md @@ -1,54 +1,55 @@ # @okikio/animate -An animation library for the modern web which utilizes the Web Animation API. Inspired by animate plus, and animejs, `@okikio/animate` is a Javascript animation library focusing on performance and ease of use. It aims to deliver butter smooth animations at a small size, it weighs ~2.7 KB (minified and compressed). +An animation library for the modern web, which. Inspired by animate plus, and animejs, [@okikio/animate](https://www.skypack.dev/view/@okikio/animate) is a Javascript animation library focused on performance and ease of use. It utilizes the Web Animation API to deliver butter smooth animations at a small size, it weighs ~4.7 KB (minified and gzipped). -*Before even getting started, you will most likely need the Web Animation API polyfill. If you install `@okikio/animate` via `npm` you are most likely going to need [rollup](https://rollupjs.org/) or [esbuild](https://esbuild.github.io/). You can use [web-animations-js](https://github.com/web-animations/web-animations-js), or [polyfill.io](https://polyfill.io/) to create a polyfill. The minimum feature requirement for a polyfill are Maps and a WebAnimations polyfill, e.g. [https://polyfill.io/v3/polyfill.min.js?features=Map%2CWebAnimations](https://polyfill.io/v3/polyfill.min.js?features=Map%2CWebAnimations).* +*Before even getting started, you will most likely need the Web Animation API, Promise, Set, and Map polyfills. If you install [@okikio/animate](https://www.skypack.dev/view/@okikio/animate) via [npm](https://www.npmjs.com/package/@okikio/animate) you are most likely going to need [rollup](https://rollupjs.org/) or [esbuild](https://esbuild.github.io/). You can use [web-animations-js](https://github.com/web-animations/web-animations-js), or [polyfill.io](https://polyfill.io/) to create a polyfill. The minimum feature requirement for a polyfill are Maps, Set, Promises, and a WebAnimation polyfill, e.g. [https://cdn.polyfill.io/v3/polyfill.min.js?features=default,es2015,es2018,Array.prototype.includes,Map,Set,Promise,WebAnimations](https://cdn.polyfill.io/v3/polyfill.min.js?features=default,es2015,es2018,Array.prototype.includes,Map,Set,Promise,WebAnimations).* ***Warning**: polyfilling may not fix animation format bugs, e.g. [composite animations](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/composite) don't work on older browsers, so, if you use `polyfill.io` and set it to check if the browser supports the feature before applying the polyfill, your project might encounter errors, as the browser may only have partial support of the Web Animation API.* ***Note**: to properly understand `@okikio/animate`, please read up on the [Web Animation API](https://developer.mozilla.org/en-US/docs/Web/API/Element/animate) on MDN.* +You can try out `@okikio/animate` using Gitpod: +[![Open In Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/okikio/native/blob/master/packages/animate/README.md) - - -You can play with `@okikio/animate` using Gitpod: - - -[![Edit with Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/okikio/native) - -_Start the dev script by typing into the terminal_ +By default Gitpod will start the dev script for you, but if you need to restart the dev script you can do so by typing into the terminal. ```bash pnpm demo ``` -Once Gitpod has booted up, go to the `./build folder` and start tweaking and testing to your hearts content. - +Once Gitpod has booted up, click on the `@okikio/animate (no-pjax)` button in the preview, then go to [../../build/pug/animate.pug](../../build/pug/animate.pug) and [../../build/ts/animate.ts](../../build/ts/animate.ts) and start tweaking and testing to your hearts content. ## Table of Contents + - [@okikio/animate](#okikioanimate) - [Table of Contents](#table-of-contents) - [Installation](#installation) - [Demo](#demo) - [Getting started](#getting-started) - [Options](#options) - - [target](#target) + - [target(s)](#targets) - [easing](#easing) - [duration](#duration) - [delay](#delay) + - [timelineOffset](#timelineoffset) - [endDelay](#enddelay) + - [padEndDelay](#padenddelay) - [loop](#loop) - [onfinish](#onfinish) + - [oncancel](#oncancel) - [autoplay](#autoplay) - [direction](#direction) - [speed](#speed) - [fillMode](#fillmode) - [options](#options-1) + - [offset](#offset) + - [timeline](#timeline) + - [keyframes](#keyframes) - [extend](#extend) - [Animations](#animations) - - [CSS & SVG Animations](#css--svg-animations) - - [Options & Properties as Methods](#options--properties-as-methods) + - [Animation Options & CSS Properties as Methods](#animation-options--css-properties-as-methods) + - [Transformable CSS Properties](#transformable-css-properties) - [Promises and Promise-Like](#promises-and-promise-like) - [Events](#events) - [Additional methods & properties](#additional-methods--properties) @@ -56,18 +57,22 @@ Once Gitpod has booted up, go to the `./build folder` and start tweaking and tes - [animations: Manager](#animations-managerhtmlelement-animation) - [computedOptions: Manager](#computedoptions-manageranimation-animationoptions) - [minDelay: number](#mindelay-number) + - [maxSpeed: number](#maxspeed-number) - [on(...), off(...), and emit(...)](#on-off-and-emit) - - [play(), pause(), and reset()](#play-pause-and-reset) + - [is(playstate: TypePlayStates)](#isplaystate-typeplaystates) + - [play(), pause(), reverse(), and reset()](#play-pause-reverse-and-reset) - [The long list of Get Methods](#the-long-list-of-get-methods) - [The almost as long list of Set Methods; these methods are chainable](#the-almost-as-long-list-of-set-methods-these-methods-are-chainable) - [then(...), catch(...), and finally(...)](#then-catch-and-finally) - [toJSON()](#tojson) - - [all(method: (animation: Animation) => void)](#allmethod-animation-animation--void) + - [all(method: (animation: Animation, target?: HTMLElement) => void)](#allmethod-animation-animation-target-htmlelement--void) - [finish()](#finish) - [cancel()](#cancel) - [stop()](#stop) - - [Example](#example) + - [API Documentation](#api-documentation) + - [Examples](#examples) - [Browser support](#browser-support) + - [CSS & SVG Animations Support](#css--svg-animations-support) - [Content delivery networks](#content-delivery-networks) - [Memory Management](#memory-management) - [Best practices (these are from Animate Plus, but they are true for all Animation libraries)](#best-practices-these-are-from-animate-plus-but-they-are-true-for-all-animation-libraries) @@ -75,21 +80,26 @@ Once Gitpod has booted up, go to the `./build folder` and start tweaking and tes - [Licence](#licence) ## Installation -You can install `@okikio/animate` from `npm` via `npm i @okikio/animate` or `yarn add @okikio/animate`. You can use `@okikio/animate` on the web via -* [https://unpkg.com/@okikio/animate@latest/lib/api.es.js](https://unpkg.com/@okikio/animate@latest/lib/api.es.js), -* [https://cdn.skypack.dev/@okikio/animate](https://cdn.skypack.dev/@okikio/animate) or -* [https://cdn.jsdelivr.net/npm/@okikio/animate@latest/lib/api.es.js](https://cdn.jsdelivr.net/npm/@okikio/animate@latest/lib/api.es.js). + +You can install [@okikio/animate](https://www.skypack.dev/view/@okikio/animate) from [npm](https://www.npmjs.com/package/@okikio/animate) via `npm i @okikio/animate`, `pnpm i @okikio/animate` or `yarn add @okikio/animate`. + +You can use `@okikio/animate` on the web via + +- [https://unpkg.com/@okikio/animate/lib/api.es.js](https://unpkg.com/@okikio/animate/lib/api.es.js), +- [https://cdn.skypack.dev/@okikio/animate](https://cdn.skypack.dev/@okikio/animate) or +- [https://cdn.jsdelivr.net/npm/@okikio/animate/lib/api.es.js](https://cdn.jsdelivr.net/npm/@okikio/animate/lib/api.es.js). Once installed it can be used like this: -```javascript + +```ts import { animate } from "@okikio/animate"; -import { animate } from "https://unpkg.com/@okikio/animate@latest/lib/api.es.js"; -import { animate } from "https://cdn.jsdelivr.net/npm/@okikio/animate@latest/lib/api.es.js"; +import { animate } from "https://unpkg.com/@okikio/animate/lib/api.es.js"; +import { animate } from "https://cdn.jsdelivr.net/npm/@okikio/animate/lib/api.es.js"; // Or import { animate } from "https://cdn.skypack.dev/@okikio/animate"; // Via script tag - + // Do note, on the web you need to do this, if you installed it via the script tag: const animate = window.animate.default; // or @@ -99,10 +109,10 @@ const { default: anime } = window.animate; // LOL ``` ## Demo -I built a small demo showing off the abilities of the `@okikio/animate` library. You can find the files for the demo in the [./build](https://github.com/okikio/native/tree/master/build) folder. +I built a small demo showing off the abilities of the `@okikio/animate` library. You can find the files for the demo in [./build](https://github.com/okikio/native/tree/master/build) folder. -> [Click to view demo →](https://okikio.github.io/native/demo) +> [Click to view demo →](https://okikio.github.io/native/demo/animate) ## Getting started @@ -112,7 +122,7 @@ The `Animate` class recieves a set of targets to animate, it then creates a list The main animation is there to ensure accuracy in different browser vendor implementation of the Web Animation API. The main animation is stored in `Animate.prototype.mainAnimation: Animation`, the other `Animation` instances are stored in a `Manager` (from [@okikio/manager](https://www.npmjs.com/package/@okikio/manager)) `Animate.prototype.animations: Manager`. -```javascript +```ts import animate from "@okikio/animate"; // Do note, on the web you need to do this, if you installed it via the script tag: @@ -185,11 +195,13 @@ animate({ [Preview this example →](https://codepen.io/okikio/pen/mdPwNbJ?editors=0010) ## Options + Animation options control how an animation is produced, it shouldn't be too different for those who have used `animejs`, or `jquery`'s animate method. An animation option is an object with keys and values that are computed and passed to the `Animate` class to create animations that match the specified options. The default options are: + ```ts export const DefaultAnimationOptions: AnimationOptions = { keyframes: [], @@ -203,34 +215,36 @@ export const DefaultAnimationOptions: AnimationOptions = { duration: 1000, fillMode: "auto", direction: "normal", + padEndDelay: true, extend: {} }; ``` -### target +### target(s) -| Default | Type | -| :------ | :--------------------------------------------------------------------------------------------------- | -| `null` | AnimationTarget = string \| Node \| NodeList \| HTMLCollection \| HTMLElement[] \| AnimationTarget[] | +| Default | Type | +| :---------- | :--------------------------------------------------------------------------------------------------- | +| `undefined` | AnimationTarget = string \| Node \| NodeList \| HTMLCollection \| HTMLElement[] \| AnimationTarget[] | Determines the DOM elements to animate. You can pass it a CSS selector, DOM elements, or an Array of DOM Elements and/or CSS Selectors. -```javascript +```ts animate({ - target: document.body.children, + target: document.body.children, // You can use either `target` or `targets` for your animations // or // target: ".div", // target: document.querySelectorAll(".el"), // target: [document.querySelectorAll(".el"), ".div"]", + // targets: [document.querySelectorAll(".el"), ".div"]", transform: ["rotate(0turn)", "rotate(1turn)"], }); ``` ### easing -| Default | Type | -| :------ | :----------------- | -| `ease` | String \| Function | +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------- | +| `ease` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | Determines the acceleration curve of your animation. Based on the easings of [easings.net](https://easings.net) @@ -246,9 +260,9 @@ Based on the easings of [easings.net](https://easings.net) You can create your own custom cubic-bezier easing curves. Similar to css you type `cubic-bezier(...)` with 4 numbers representing the shape of the bezier curve, for example, `cubic-bezier(0.47, 0, 0.745, 0.715)` this is the bezier curve for `in-sine`. -*Note: the `easing` property supports the original values and functions for easing as well, for example, `steps(1)`, and etc... are supported.* +_**Note**: the `easing` property supports the original values and functions for easing as well, for example, `steps(1)`, and etc... are supported._ -```javascript +```ts // cubic-bezier easing animate({ target: ".div", @@ -259,20 +273,29 @@ animate({ }); ``` +As of right now these are the limits of easing, but a couple standards are in discussions right now, so cross your fingers and hope they are standardized soon. + +Here are some standards in discussion: + +- [Easing Worklet](https://github.com/jakearchibald/easing-worklet) +- [Animation Worklet](https://drafts.css-houdini.org/css-animation-worklet-1/#example-1) +- [CSS Defined Easing](https://github.com/w3c/csswg-drafts/issues/229) ### duration -| Default | Type | -| :------ | :----------------- | -| `1000` | Number \| Function | +| Default | Type | +| :------ | :--------------------------------------------------------------------------------------------------------- | +| `1000` | Number \| String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | Determines the duration of your animation in milliseconds. By passing it a callback, you can define a different duration for each element. The callback takes the index of each element, the target dom element, and the total number of target elements as its argument and returns a number. -```javascript +```ts // First element fades out in 1s, second element in 2s, etc. animate({ target: ".div", easing: "linear", + duration: 1000, + // or duration: (index) => (index + 1) * 1000, opacity: [1, 0], }); @@ -280,58 +303,84 @@ animate({ ### delay -| Default | Type | -| :------ | :----------------- | -| `0` | Number \| Function | +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------- | +| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | Determines the delay of your animation in milliseconds. By passing it a callback, you can define a different delay for each element. The callback takes the index of each element, the target dom element, and the total number of target elements as its argument and returns a number. -```javascript +```ts // First element starts fading out after 1s, second element after 2s, etc. animate({ target: ".div", easing: "linear", + delay: 5, + // or delay: (index) => (index + 1) * 1000, opacity: [1, 0], }); ``` +### timelineOffset + +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------- | +| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | + +Adds an offset amount to the `delay` option, for creating a timeline similar to `animejs`. + +I don't intend to create a `timeline` function for this library but if you wish to please try your hands at creating one, if it's small, light-weight, and there is a need I might incorperate it. + ### endDelay -| Default | Type | -| :------ | :----------------- | -| `0` | Number \| Function | +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------- | +| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | Similar to delay but it indicates the number of milliseconds to delay **after** the full animation has played **not before**. -*Note: `endDelay` will delay the `onfinish` method and event, but will not reserve the current state of the CSS animation, if you need to use endDelay you may need to use the `fillMode` property to reserve the changes to the animation target. +_**Note**: `endDelay` will delay the `onfinish` method and event, but will not reserve the finished state of the CSS animation, if you need to use `endDelay` you may need to use the `fillMode` property to reserve the changes to the animation target._ -```javascript +```ts // First element fades out but then after 1s finishes, the second element after 2s, etc. animate({ target: ".div", easing: "linear", + endDelay: 1000, + // or endDelay: (index) => (index + 1) * 1000, opacity: [1, 0], }); ``` +### padEndDelay + +| Default | Type | +| :------ | :------ | +| `false` | Boolean | + +This ensures all `animations` match up to the total duration, and don't finish too early, if animations finish too early when the `.play()` method is called specific animations that are finished will restart while the rest of the animations will continue playing. + +_**Note**: you cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will replace the padded endDelay, `padEndDelay` is also ignored if `loop` is `true` or is set to `infinity`._ + +When creating progress/seek bars this needs to be enabled for the animation to function properly. + ### loop -| Default | Type | -| :------ | :---------------------------- | -| `1` | Boolean \| Number \| Function | +| Default | Type | +| :------ | :---------------------------------------------------------------------------------------------------------- | +| `1` | Boolean \| Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | Determines if the animation should repeat, and how many times it should repeat. -```javascript +```ts // Loop forever animate({ target: ".div", easing: "linear", - loop: true, + loop: true, // Using `loop: Infinity,` would also have worked // or - // loop: 5, // If you want the animation to loop 5 times + loop: 5, // If you want the animation to loop 5 times opacity: [1, 0], }); ``` @@ -342,19 +391,26 @@ animate({ | :--------------------------------------------------------------------------------- | :------- | | `(element: HTMLElement, index: number, total: number, animation: Animation) => {}` | Function | -Occurs when the animation for one of the elements completes, meaning when animating many elements that finish at different times this will run multiple times. The method it takes is slightly different. +Occurs when the animation for one of the targets completes, meaning when animating many targets that finish at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. -The animation argument represents the animation for the current element. +The animation argument represents the animation for the current target. **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. -```javascript +```ts // Avoid using fillMode, use this instead to commit style changes // Do note endDelay delays the onfinish method animate({ target: ".div", opacity: [0, 1], + /** + * @param {HTMLElement} element - the current target element + * @param {number} index - the index of the current target element in `Animate.prototype.targets` + * @param {number} total - the total number of target elements + * @param {Animation} animation - the animation of the current target element + */ + // Note the order of the arguments -- it's different from other properties onfinish(element, index, total, animation) { element.style.opacity = 0; @@ -367,46 +423,98 @@ animate({ }); ``` +### oncancel + +| Default | Type | +| :--------------------------------------------------------------------------------- | :------- | +| `(element: HTMLElement, index: number, total: number, animation: Animation) => {}` | Function | + +Occurs when the animation for one of the targets is cancelled, meaning when animating many elements that are cancelled at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. + +The animation argument represents the animation for the current element. + +**Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. + +```ts +// Avoid using fillMode, use this instead to commit style changes +// Do note endDelay delays the onfinish method +animate({ + target: ".div", + opacity: [0, 1], + + /** + * @param element - the current target element + * @param index - the index of the current target element in `Animate.prototype.targets` + * @param total - the total number of target elements + * @param animation - the animation of the current target element + */ + + // Note the order of the arguments -- it's different from other properties + oncacel(element, index, total, animation) { + console.log( + `${ + index + 1 + } out of ${total}, elements have been cancelled. Animation playback speed is ${animation.playbackRate}, the target elements id attribute is ${element.id}` + ); + }, +}); +``` + ### autoplay -| Default | Type | -| :------ | :------------------ | -| `true` | Boolean \| Function | +| Default | Type | +| :------ | :------ | +| `true` | Boolean | Determines if the animation should automatically play, immediately after being instantiated. ### direction -| Default | Type | -| :------- | :----------------- | -| `normal` | String \| Function | +| Default | Type | +| :------- | :----------------------------------------------------------------------------------------------- | +| `normal` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | + +Determines the direction of the animation, the directions available are: -Determines the direction of the animation; `reverse` runs the animation backwards, `alternate` switches direction after each iteration if the animation loops. `alternate-reverse` starts the animation at what would be the end of the animation if the direction were `normal` but then when the animation reaches the beginning of the animation it alternates going back to the position it started at. +- `reverse` runs the animation backwards, +- `alternate` switches direction after each iteration if the animation loops. +- `alternate-reverse` starts the animation at what would be the end of the animation if the direction were +- `normal` but then when the animation reaches the beginning of the animation it alternates going back to the position it started at. ### speed -| Default | Type | -| :------ | :----------------- | -| `1` | Number \| Function | +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------- | +| `1` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | Determines the animation playback rate. Useful in the authoring process to speed up some parts of a -long sequence (value above 1) or slow down a specific animation to observe it (value between 0 to 1), don't put negative numbers for speed. +long sequence (value above 1) or slow down a specific animation to observe it (value between 0 to 1), + +_**Note**: negative numbers reverse the animation._ ### fillMode -| Default | Type | -| :------ | :----------------- | -| `auto` | String \| Function | +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------- | +| `auto` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | _Be careful when using fillMode, it has some problems when it comes to concurrency of animations read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill), if browser support were better I would remove fillMode and use Animation.commitStyles, I'll have to change the way `fillMode` functions later. Use the onfinish method to commit styles [onfinish](#onfinish)._ -Defines how an element should look after the animation. `none` the animation's effects are only visible while the animation is playing. `forwards` the affected element will continue to be rendered in the state of the final animation frame. `backwards` the animation's effects should be reflected by the element(s) state prior to playing. `both` combining the effects of both forwards and backwards: The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing. `auto` if the animation effect fill mode is being applied to is a keyframe effect. "auto" is equivalent to "none". Otherwise, the result is "both". You can learn more here on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). +Defines how an element should look after the animation. The fillModes availble are: + +- `none` means the animation's effects are only visible while the animation is playing. +- `forwards` the affected element will continue to be rendered in the state of the final animation frame. +- `backwards` the animation's effects should be reflected by the element(s) state prior to playing. +- `both` combining the effects of both forwards and backwards; The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing. +- `auto` if the animation effect fill mode is being applied to is a keyframe effect. "auto" is equivalent to "none". Otherwise, the result is "both". + +You can learn more here on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). ### options -| Default | Type | -| :------ | :----------------------------- | -| `{}` | Object \| Animate \| Animate[] | +| Default | Type | +| :------ | :----------------------------------------------------------------------------------------------------------------------------------- | +| `{}` | [IAnimationOptions](https://okikio.github.io/native/docs/interfaces/animate.ianimationoptions.html) = Object \| Animate \| Animate[] | Another way to input options for an animation, it's also used to chain animations. @@ -414,7 +522,7 @@ The `options` animation option is another way to declare options, it can take an `options` extends the animation properties of an animation, but more importance is given to the actual animation options object, so, the properties from `options` will be ignored if there is already an animation option with the same name declared. -*Note: you can't use this property as a method.* +_**Note**: you can't use this property as a method._ ```ts (async () => { @@ -455,6 +563,25 @@ The `options` animation option is another way to declare options, it can take an console.log(options); //= [Animate] })(); +// or +(async () => { + let options = animate({ + target: ".div", + opacity: [0, 1], + }); + + await options; + + animate({ + options, + + // opacity overrides the opacity property from `options` + opacity: [1, 0], + }); + + console.log(options); //= Animate +})(); + // or (async () => { let options = { @@ -472,19 +599,93 @@ The `options` animation option is another way to declare options, it can take an })(); ``` +### offset + +| Default | Type | +| :---------- | :------------------------------------------------------------------------------------------------------------- | +| `undefined` | (Number \| String)[] \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | + +Controls the starting point of certain parts of an animation. + +The offset of the keyframe specified as a number between `0.0` and `1.0` inclusive or null. This is equivalent to specifying start and end states in percentages in CSS stylesheets using @keyframes. If this value is null or missing, the keyframe will be evenly spaced between adjacent keyframes. + +Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats) + +```ts +animate({ + duration: 2000, + opacity: [ 0, 0.9, 1 ], + easing: [ 'ease-in', 'ease-out' ], + + offset: [ "from", 0.8 ], // Shorthand for [ 0, 0.8, 1 ] + // or + offset: [ 0, "80%", "to" ], // Shorthand for [ 0, 0.8, 1 ] + // or + offset: [ "0", "0.8", "to" ], // Shorthand for [ 0, 0.8, 1 ] +}); +``` + +### timeline + +| Default | Type | +| :------------------------------------------------------------------------------------ | :---------------- | +| [DocumentTimeline](https://developer.mozilla.org/en-US/docs/Web/API/DocumentTimeline) | AnimationTimeline | + +Represents the timeline of animation. It exists to pass timeline features to Animations. + +As of right now it doesn't contain any features but in the future when other timelines like the [ScrollTimeline](https://drafts.csswg.org/scroll-animations-1/#scrolltimeline), read the Google Developer article for [examples and demos of ScrollTimeLine](https://developers.google.com/web/updates/2018/10/animation-worklet#hooking_into_the_space-time_continuum_scrolltimeline) + +### keyframes + +| Default | Type | +| :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `[]` | TypeCSSLikeKeyframe \| ICSSComputedTransformableProperties[] & Keyframe[] \| object[] \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | + +I highly suggest going through the API documentation to better understand [keyframes](https://okikio.github.io/native/docs/interfaces/animate.ianimationoptions.html#keyframes). + +Allows you to manually set keyframes using a `keyframe` array + +Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes). + +An `array` of objects (keyframes) consisting of properties and values to iterate over. This is the canonical format returned by the [getKeyframes()](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/getKeyframes) method. + +`@okikio/animate` also offers another format called `CSSLikeKeyframe`, read more about [KeyframeParse](https://okikio.github.io/native/docs/modules/native.html#keyframeparse) + +It basically functions the same way CSS's `@keyframe` works + +```ts +animate({ + keyframes: { + "from, 50%, to": { + opacity: 1 + }, + "25%, 0.7": { + opacity: 0 + } + } +}) + +// Results in a keyframe array like this +//= [ +//= { opacity: 1, offset: 0 }, +//= { opacity: 0, offset: 0.25 }, +//= { opacity: 1, offset: 0.5 }, +//= { opacity: 0, offset: 0.7 }, +//= { opacity: 1, offset: 1 } +//= ] +``` + ### extend -| Default | Type | -| :------ | :----- | -| `{}` | Object | +| Default | Type | +| :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `{}` | [KeyframeEffectOptions](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffectOptions) \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) | The properties of the `extend` animation option are not interperted or computed, they are given directly to the Web Animation API, as way to access features that haven't been implemented in `@okikio/animate`, for example, `iterationStart`. `extend` is supposed to future proof the library if new features are added to the Web Animation API that you want to use, but that has not been implemented yet. -*Note: you can't use this property as a method, neither can it's properties be used as methods.* - -*Note: it doesn't allow for declaring animation keyframes, it's just for animation options, and it overrides all other animation options that accomplish the same goal, e.g. `loop` & `iterations`, if iterations is a property of `extend` then `iterations` will override `loop`.* +_**Note**: it doesn't allow for declaring actual animation keyframes; it's just for animation timing options, and it overrides all other animation timing options that accomplish the same goal, e.g. `loop` & `iterations`, if `iterations` is a property of `extend` then `iterations` will override `loop`._ ```ts animate({ @@ -495,7 +696,8 @@ animate({ iterationStart: 0.5, // etc... fill: "both", // This overrides fillMode - iteration: 2 // This overrides loop + iteration: 2, // This overrides loop + composite: "add" } }); ``` @@ -505,7 +707,7 @@ animate({ `@okikio/animate` lets you animate HTML and SVG elements with any property that takes numeric values, including hexadecimal colors. The `@okikio/animate` module contains a class that controls animatations called `Animate`. To create new instances of the `Animate` class I created the `animate()` function. -```javascript +```ts // Animate the fill color of an SVG circle animate({ target: "circle", @@ -515,7 +717,7 @@ animate({ Each property you animate needs an array defining the start and end values, or an Array of keyframes. -```javascript +```ts animate({ target: ".div", transform: ["translate(0px)", "translate(1000px)"], @@ -531,11 +733,12 @@ animate({ ], }); ``` + *Note: you can only use one of these formats for an animation, and if `Animate` sees the `keyframes` property, it ignores all other css properties, in situations where `Animate` sees the keyframes property it will still accept animation properties like `easing`, `duration`, etc...* These arrays can optionally be returned by a callback that takes the index of each element, the total number of elements, and each specific element, just like with other properties. -```javascript +```ts // First element translates by 100px, second element by 200px, etc. animate({ target: ".div", @@ -557,133 +760,13 @@ animate({ }); ``` -### CSS & SVG Animations -`Animate` can animate `~197` CSS properties; [MDN Animatable CSS Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties) and `~63` SVG properties; [MDN SVG Presentation Attributes](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation). - -The animatable CSS properties are: -* backdrop-filter -* background -* background-color -* background-position -* background-size -* block-size -* border -* border-block-end -* border-block-end-color -* border-block-end-width -* border-block-start -* border-block-start-color -* border-block-start-width -* border-bottom -* border-bottom-color -* border-bottom-left-radius -* border-bottom-right-radius -* border-bottom-width -* border-color -* border-end-end-radius -* border-end-start-radius -* border-image-outset -* border-image-slice -* border-image-width -* border-inline-end -* border-inline-end-color -* border-inline-end-width -* border-inline-start -* border-inline-start-color -* border-inline-start-width -* border-left -* border-left-color -* border-left-width -* border-radius -* border-right -* border-right-color -* border-right-width -* border-start-end-radius -* border-start-start-radius -* border-top -* border-top-color -* border-top-left-radius -* border-top-right-radius -* border-top-width -* border-width -* bottom -* box-shadow -* caret-color -* clip -* clip-path -* color -* [etc...](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties) - - -The animatable SVG properties are: -* alignment-baseline -* baseline-shift -* clip -* clip-path -* clip-rule -* color -* color-interpolation -* color-interpolation-filters -* color-profile -* color-rendering -* cursor -* direction -* display -* dominant-baseline -* enable-background -* fill -* fill-opacity -* fill-rule -* filter -* flood-color -* flood-opacity -* font-family -* font-size -* font-size-adjust -* font-stretch -* font-style -* font-variant -* font-weight -* letter-spacing -* lighting-color -* marker-end -* marker-mid -* marker-start -* mask -* opacity -* overflow -* pointer-events -* shape-rendering -* solid-color -* solid-opacity -* stop-color -* stop-opacity -* stroke -* stroke-dasharray -* stroke-dashoffset -* stroke-linecap -* stroke-linejoin -* stroke-miterlimit -* stroke-opacity -* stroke-width -* text-anchor -* text-decoration -* text-rendering -* transform -* vector-effect -* visibility -* word-spacing -* writing-mode -* [etc...](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation) - -Unfortunately, morphing SVG paths via the `d` property isn't supported yet as browsers don't yet support it, and there are other limitations to what the Web Animation API will allow 😭 :sob:, these limitation are covered in detail by an article published by Adobe about [the current state of SVG animation on the web](https://blog.adobe.com/en/publish/2015/06/05/the-state-of-svg-animation.html#gs.pihpjw). -## Options & Properties as Methods +## Animation Options & CSS Properties as Methods All options & properties except `target`, `speed`, `autoplay`, `extend`, `onfinish`, and `options` can be represented by a method with the arguments `(index: number, total: number, element: HTMLElement)`. *Note: the `keyframes` option **can** be a method*. -```javascript +```ts /** * @param {number} [index] - index of each element * @param {number} [total] - total number of elements @@ -704,6 +787,92 @@ animate({ }); ``` +### Transformable CSS Properties + +I added the ability to use single value unitless numbers, strings, and arrays, as well as added the transform functions as CSS properties. + +Single value means, + +```ts +animate({ + opacity: 0.5, // This will turn into `["5"]`, notice no units, this could also be a string + translateX: 250, // This will turn into `["250px"]`, notice how it adds units, this could also be a string + rotate: 360, // This will turn into `["360deg"]`, notice how it adds units, this could also be a string + skew: "1.25turn", // This will turn into `["1.25turn"]`, notice how it doesn't add "deg" as the units + left: 50, // This is actually an error, this will turn into `["50"]`, notice no units, this could also be a string. Only transform properties support automatic units +}) +``` + +This is in preperation for [Implicit to/from keyframes](https://developer.mozilla.org/en-US/docs/Web/API/Element/animate#implicit_tofrom_keyframes) + +Removes the need for the full transform statement in order to use translate, rotate, scale, skew, or perspective including their X, Y, Z, and 3d varients. Plus adds automatic units to the transform CSS properties. + +Also, adds the ability to use single string or number values for transform functions. + +_**Note**: the `transform` animation option will override all transform CSS properties_ + +_**Note**: all other features will work with Transformable CSS Properties, this includes the `keyframes` animation options and `animation options` as callbacks_ + +_**Warning**: only the transform CSS properties will get automatic units, but all other CSS properties can be used a a single value option_ + +Read more about the [ParseTransformableCSSProperties](https://okikio.github.io/native/docs/modules/animate.html#parsetransformablecssproperties) method. + +Also, read about the [ParseTransformableCSSKeyframes](https://okikio.github.io/native/docs/modules/animate.html#parsetransformablecsskeyframes) method. + +Check out an example on [Codepen](https://codepen.io/okikio/pen/qBrNXoY?editors=0110) + +```ts +animate({ + // ... + /* + keyframes(index) { + return [ + { translateX: 0 }, + { translateX: (index + 1) * 250 } + ]; + }, + + // or + translateX(index) { + return `0, ${(index + 1) * 250}`; + }, + */ + + // It will automatically add the "px" units for you, or you can write a string with the units you want + translate3d: [ + "25, 35, 60%", + [50, "60px", 70], + ["70", 50] + ], + translate: "25, 35, 60%", + translateX: [50, "60px", "70"], + translateY: ["50, 60", "60"], // Note: this will actually result in an error, make sure to pay attention to where you are putting strings and commas + translateZ: 0, + perspective: 0, + opacity: "0, 5", + scale: [ + [1, "2"], + ["2", 1] + ], + rotate3d: [ + [1, 2, 5, "3deg"], // The last value in the array must be a string with units for rotate3d + [2, "4", 6, "45turn"], + ["2", "4", "6", "-1rad"] + ], + opacity: [0, 1] +}) + +//= { +//= transform: [ +//= // `translateY(50, 60)` will actually result in an error +//= 'translate(25px) translate3d(25px, 35px, 60%) translateX(50px) translateY(50, 60) translateZ(0px) rotate3d(1, 2, 5, 3deg) scale(1, 2) perspective(0px)', +//= 'translate(35px) translate3d(50px, 60px, 70px) ranslateX(60px) translateY(60px) rotate3d(2, 4, 6, 45turn) scale(2, 1)', +//= 'translate(60%) translate3d(70px, 50px) translateX(70px) rotate3d(2, 4, 6, -1rad)' +//= ], +//= opacity: [ '0', '5' ] +//= } +``` + ## Promises and Promise-Like `animate()` is promise-like meaning it has `then`, `catch`, and `finally` methods, but `Animate` itself isn't a Promise (this is important to keep in mind when dealing with async/await asynchronous animations). `Animate`'s `then` resolves once all animations are complete. The promise resolves to an Array with the `Animate` instance being the only element, but the `options` animation option can use the options of another `Animate` instance allowing animation chaining to be straightforward and convenient. The [Getting started](#getting-started) section gives a basic example. @@ -711,13 +880,12 @@ animate({ Since `Animate` relies on native promises, you can benefit from all the usual features promises provide, such as `Promise.all`, `Promise.race`, and especially `async/await` which makes animation timelines easy to set up. - > *An interesting quirk of Promises is that even though `Animate` is not a Promise, async/await still work with it because it has a `then`, and `catch`.* -*Warning: `then`, `catch`, and `finally` are not resetable, however, the `Animate.prototype.on("complete", ...)` event is, meaning if you reset an animation while the using `then`, `catch`, and `finally`, they will **not** fire again after the reset.* - +*Warning: `then`, `catch`, and `finally` are not resetable, however, the `Animate.prototype.on("finish", ...)` event is, meaning if you reset an animation while then using `then`, `catch`, and `finally`, they will **not** fire again after the reset.* For example, + ```ts animate({ target: ".div", @@ -758,17 +926,20 @@ animate({ }); })(); ``` + ## Events + There are `8` events in total, they are: -* "update" -* "play" -* "pause" -* "begin" -* "complete" -* "finish" -* "error" -* "stop" +- "update" +- "play" +- "pause" +- "begin" +- "finish" +- "cancel" +- "error" +- "stop" +- "playstate-change" ```ts // The update event is triggered continously while an animation is playing. @@ -780,28 +951,25 @@ There are `8` events in total, they are: }); // The play & pause events are triggered when the Animate.prototype.play() or .pause() methods are called. -....on("play" | "pause", (playstate, instance) => { +// The "playstate-change" event occurs when the playstate changes, so, when the animation is played, paused, cancelled, or finished +....on("play" | "pause" | "playstate-change", (playstate, instance) => { /** * @param {"idle" | "running" | "paused" | "finished"} playstate - it is the animations play state * @param {Animate} instance - it is the instance of Animate the event is triggered from */ }); -// The begin & complete events are triggered when all animations in an instance of Animate begin or complete. -// The begining of all animations is when the smallest delay in the Animate instance has passed, while the complete event is when all animations (taking into account the endDelay and loops as well) have ended. -....on("begin" | "complete", (instance) => { - /** - * @param {Animate} instance - it is the instance of Animate the event is triggered from - */ -}); +// The begin, finish, and cancel events are triggered when all animations in an instance of Animate begin, finish or are cancelled. + +// The begin event occurs at the begining of all animations and its when the the Animate instance has started, while the finish event is when all animations (taking into account the endDelay and loops as well) have ended. +// Note: By the time events are registered the animation would have started and there wouldn't have be a `begin` event listener to actually emit, so, +// the `begin` event emitter is wrapped in a setTimeout of 0ms so that the event can be defered; by the end of the timeout the rest of the js to run, +// the `begin` event to be registered thus the `begin` event can be emitter -// The finish event is triggered for all animation as they finish their individual animations -....on("finish", (target, i, len, animation) => { +// The cancel event occurs when the mainElement animation is cancelled or the `.cancel()` method is called +....on("begin" | "finish" | "cancel", (instance) => { /** - * @param {HTMLElement} target - it is the current element being animated - * @param {number} i - the index of the target element in a list of target elements - * @param {number} len - the total number of target elements - * @param {Animation} animation - it is the instance of the `Animation` (this is a Web Animation API class) that has just finished + * @param {Animate} instance - it is the instance of Animate the event is triggered from */ }); @@ -812,19 +980,22 @@ There are `8` events in total, they are: */ }); -// The stop event is triggered when an `Animate` instance has been permanently stopped. +// The stop event is triggered when an `Animate` instance has been permanently stopped via the `.stop()` method. ....on("stop", () => { }); ``` ## Additional methods & properties ### mainAnimation: Animation + Stores an animation that runs on the total duration of all the `Animation` instances, and as such it's the main Animation. ### animations: Manager + A Manager of `Animations`; it stores all the `Animation` instances. ### computedOptions: Manager + A Manager that stores all the fully calculated options for individual `Animation` instances. *Note: the `computedOptions` are changed to their proper `Animation` instance options, so, some of the names are different, and options that can't be computed are not present. E.g. `fillMode` in the animation options is now just `fill` in the `computedOptions`.* @@ -832,13 +1003,18 @@ A Manager that stores all the fully calculated options for individual `Animation *Note: `keyframes` are not included, both the array form and the object form, the `options`, `speed`, and `autoplay` animation options are not allowed.* ### minDelay: number + The smallest delay out of all `Animation`'s, it is zero by default. +### maxSpeed: number + +The largest speed out of all `Animation`'s, it is zero by default. + ### on(...), off(...), and emit(...) These methods are inherited from [@okikio/emitter](https://www.npmjs.com/package/@okikio/emitter). They control events and their listeners. The only difference is that by default their scopes are set to the instance of `Animate`. -```javascript +```ts import { animate } from "@okikio/animate"; let anim = animate({ @@ -875,27 +1051,31 @@ anim.on("complete", () => { }); ``` -### play(), pause(), and reset() +### is(playstate: TypePlayStates) -They are self explanatory, the `play/pause` methods play/pause animation, while the `reset` method resets the progress of an animation. +Returns a boolean determining if the `animate` instances playstate is equal to the `playstate` parameter + +### play(), pause(), reverse(), and reset() + +They are self explanatory, the `play/pause` methods play/pause animation, the `reverse` method causes all animation to reverse directions, while the `reset` method resets the progress of an animation. ### The long list of Get Methods -- `getTargets(): HTMLElement[]` - Returns an Array of HTMLElement's -- `getAnimation(element: HTMLElement): Animation` - Allows you to select a specific animation from an element -- `getTiming(value: HTMLElement | Animation): EffectTiming | AnimationOptions` - Returns the timings of an Animation, given a target E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... } -- `getTotalDuration(): number` - Returns the total duration of the animation of all elements added together -- `getCurrentTime(): number` - Returns the current time of the animation of all elements -- `getProgress(): number` - Returns the progress of the animation of all elements as a percentage between 0 to 100. -- `getPlayState(): string` - Returns the current playing state, it can be `"idle" | "running" | "paused" | "finished"` -- `getSpeed(): number` - Return the playback speed of the animation -- `getOptions(): object` - Returns the options that were used to create the animation +- `getTargets(): HTMLElement[]` - Returns an Array of HTMLElement's +- `getAnimation(element: HTMLElement): Animation` - Allows you to select a specific animation from an element +- `getTiming(value: HTMLElement | Animation): EffectTiming | AnimationOptions` - Returns the timings of an Animation, given a target E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... } +- `getTotalDuration(): number` - Returns the total duration of the animation of all elements added together +- `getCurrentTime(): number` - Returns the current time of the animation of all elements +- `getProgress(): number` - Returns the progress of the animation of all elements as a percentage between 0 to 100. +- `getPlayState(): string` - Returns the current playing state, it can be `"idle" | "running" | "paused" | "finished"` +- `getSpeed(): number` - Return the playback speed of the animation +- `getOptions(): object` - Returns the options that were used to create the animation ### The almost as long list of Set Methods; these methods are chainable -- `setCurrentTime(time: number)` - Sets the current time of the animation -- `setProgress(percent: number)` - Similar to `setCurrentTime` except it use a number between 0 and 100 to set the current progress of the animation -- `setSpeed(speed: number = 1)` - Sets the playback speed of an animation +- `setCurrentTime(time: number)` - Sets the current time of the animation +- `setProgress(percent: number)` - Similar to `setCurrentTime` except it use a number between 0 and 100 to set the current progress of the animation +- `setSpeed(speed: number = 1)` - Sets the playback speed of an animation ### then(...), catch(...), and finally(...) @@ -905,11 +1085,12 @@ They represent the then, catch, and finally methods of a Promise that is resolve An alias for `getOptions` -### all(method: (animation: Animation) => void) +### all(method: (animation: Animation, target?: HTMLElement) => void) Calls a method that affects all animations including the mainAnimation; the method only allows the animation parameter For example, + ```ts // This is a small snippet from the setCurrentTime() method this.all((animation: Animation) => { @@ -919,11 +1100,11 @@ this.all((animation: Animation) => { ### finish() -Forces all Animations to finish, it triggers the `finish` and `complete` events. +Forces all Animations to finish, and triggers the `finish` event. ### cancel() -Cancels all Animations, it just runs the cancel method from each individual animation. +Cancels all Animations, it just runs the cancel method from each individual animation including the mainAnimation; it triggers the `cancel` event. ### stop() @@ -931,34 +1112,163 @@ Cancels all Animations and de-references them allowing them to be garbage collec The `stop` method is not chainable. -*Warning: if you try to reference properties from the `Animate` class after stop has been called many things will break. The `Animate` class cannont and will not recover from stop, it is meant as a final trash run of animations, don't use it if you think you may restart the animation.* +*Warning: if you try to reference properties from the `Animate` class after stop has been called many things will break. The `Animate` class cannot and will not recover from stop, it is meant as a final trash run of animations, don't use it if you think you may restart the animation.* + +## API Documentation + +Not all available methods and properties are listed here (otherwise this README would be too long), so go to [okikio.github.io/native/docs](https://okikio.github.io/native/docs) for a fully documented API. + +## Examples -## Example -[![Web Animation API Library Playground](https://raw.githubusercontent.com/okikio/native/master/packages/animate/assets/Web%20Animation%20API%20Library%20Playground.png)](https://codepen.io/okikio/pen/qBbdGaW?editors=0010) +[![@okikio/animate - playground](https://raw.githubusercontent.com/okikio/native/master/packages/animate/assets/Web%20Animation%20API%20Library%20Playground.png)](https://codepen.io/collection/rxOEBO) -[Check out the example on Codepen →](https://codepen.io/okikio/pen/qBbdGaW?editors=0010) +[Go through this collection of examples for more detailed demos →](https://codepen.io/collection/rxOEBO) ## Browser support `@okikio/animate` is provided as a native ES6 module, which means you may need to transpile it depending on your browser support policy. The library works using `