diff --git a/packages/animate/README.md b/packages/animate/README.md
index 378e509..a5f5b70 100644
--- a/packages/animate/README.md
+++ b/packages/animate/README.md
@@ -1,12 +1,18 @@
# @okikio/animate
-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 **~5.79 KB** (minified and gzipped).
+[](https://www.npmjs.com/package/@okikio/animate) [](https://bundlephobia.com/package/@okikio/animate)  
-*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). and [https://cdn.jsdelivr.net/npm/web-animations-js/web-animations-next.min.js](https://cdn.jsdelivr.net/npm/web-animations-js/web-animations-next.min.js)*
+An animation library for the modern web. 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 **~11.6 KB** (minified and gzipped), since, `@okiko/animate` is treeshakeable the minimum usable file size you can reach is **~5.6 KB** (minified and gzipped).
+
+I suggest reading the in depth article I made on CSS-Tricks about `@okikio/animate`, , it will help you determine if `@okikio/animate` is right for your project.
+
+_**Note**: [Custom Easing](#custom-easing), as well as a proper [Timeline](#timeline-class) are now supported._
+
+*Before even getting started, you will most likely need the Web Animation API, Promise, WeakMap, 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, WeakMap, Promise, and a WebAnimation polyfill (that supports KeyframeEffect), e.g. [https://cdn.polyfill.io/v3/polyfill.min.js?features=default,es2015,es2018,Array.prototype.includes,Map,WeakMap,Set,Promise,WebAnimations](https://cdn.polyfill.io/v3/polyfill.min.js?features=default,es2015,es2018,Array.prototype.includes,Map,WeakMap,Set,Promise), and [https://cdn.jsdelivr.net/npm/web-animations-js/web-animations-next.min.js](https://cdn.jsdelivr.net/npm/web-animations-js/web-animations-next.min.js). I suggest checking out the [demo](../../build/ts/webanimation-polyfill.ts) to see how I setup the Web Animation Polyfill*
***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.*
+***Also 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:
@@ -20,6 +26,24 @@ pnpm demo
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.
+You can run `@okikio/animate` locally by first installing some packages via these commands into your terminal,
+
+```bash
+npm install -g pnpm && pnpm install -g gulp ultra-runner commitizen && pnpm install && pnpm build
+```
+
+and then you can test/demo it using this command,
+
+```bash
+pnpm demo
+```
+
+You can build your changes/contributions using,
+
+```bash
+pnpm build
+```
+
## Table of Contents
- [@okikio/animate](#okikioanimate)
@@ -47,12 +71,21 @@ Once Gitpod has booted up, click on the `@okikio/animate (no-pjax)` button in th
- [offset](#offset)
- [timeline](#timeline)
- [keyframes](#keyframes)
+ - [composite](#composite)
- [extend](#extend)
- [Animations](#animations)
- [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)
+ - [Custom Easing](#custom-easing)
+ - [SpringEasing](#springeasing)
+ - [ApplyCustomEasing](#applycustomeasing)
+ - [DestroyableAnimate](#destroyableanimate)
+ - [Tweens](#tweens)
+ - [tween](#tween)
+ - [tweenAttr](#tweenattr)
+ - [Effects](#effects)
- [Additional methods & properties](#additional-methods--properties)
- [mainAnimation: Animation](#mainanimation-animation)
- [targetIndexes: WeakMap](#targetindexes-weakmapnode-number)
@@ -211,7 +244,7 @@ animate({
## API Documentation
-Not all available methods and properties are listed here (otherwise this README would be too long), so go through the [API documentation](https://okikio.github.io/native/docs/modules/animate.html) for the full documented API.
+Not all available methods and properties are listed here (otherwise this README would be too long), so go through the [API documentation](https://okikio.github.io/native/docs/modules/_okikio_animate.html) for the full documented API.
## Options
@@ -261,26 +294,33 @@ animate({
### easing
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------- |
-| `ease` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------- |
+| `ease` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback) |
Determines the acceleration curve of your animation.
Based on the easings of [easings.net](https://easings.net)
-| constant | accelerate | decelerate | accelerate-decelerate |
-| :------- | :--------- | :--------- | :-------------------- |
-| linear | in-cubic | out-cubic | in-out-cubic |
-| ease | in-quart | out-quart | in-out-quart |
-| | in-quint | out-quint | in-out-quint |
-| | in-expo | out-expo | in-out-expo |
-| | in-circ | out-circ | in-out-circ |
-| | in-back | out-back | in-out-back |
+| constant | accelerate | decelerate | accelerate-decelerate |
+| :--------- | :----------- | :------------- | :-------------------- |
+| linear | ease-in / in | ease-out / out | ease-in-out / in-out |
+| ease | in-sine | out-sine | in-out-sine |
+| steps | in-quad | out-quad | in-out-quad |
+| step-start | in-cubic | out-cubic | in-out-cubic |
+| step-end | in-quart | out-quart | in-out-quart |
+| | in-quint | out-quint | in-out-quint |
+| | in-expo | out-expo | in-out-expo |
+| | in-circ | out-circ | in-out-circ |
+| | in-back | out-back | in-out-back |
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**: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`_
+
+Yay, [Custom Easing](#custom-easing) are now supported, they have limitations, but those shouldn't affect too much.
+
```ts
// cubic-bezier easing
animate({
@@ -288,6 +328,8 @@ animate({
easing: "cubic-bezier(0.47, 0, 0.745, 0.715)",
/* or */
// easing: "in-sine",
+ /* or */
+ // easing: "inSine",
transform: ["translate(0px)", "translate(500px)"],
});
```
@@ -302,9 +344,9 @@ Here are some standards in discussion:
### duration
-| Default | Type |
-| :------ | :--------------------------------------------------------------------------------------------------------- |
-| `1000` | Number \| String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :----------------------------------------------------------------------------------------------------------------- |
+| `1000` | Number \| String \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_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.
@@ -322,9 +364,9 @@ animate({
### delay
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------- |
-| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------- |
+| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_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.
@@ -342,9 +384,9 @@ animate({
### timelineOffset
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------- |
-| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------- |
+| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback) |
Adds an offset amount to the `delay` option, for creating a timeline similar to `animejs`.
@@ -352,9 +394,9 @@ I don't intend to create a `timeline` function for this library but if you wish
### endDelay
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------- |
-| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------- |
+| `0` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback) |
Similar to delay but it indicates the number of milliseconds to delay **after** the full animation has played **not before**.
@@ -386,9 +428,9 @@ When creating progress/seek bars this needs to be enabled for the animation to f
### loop
-| Default | Type |
-| :------ | :---------------------------------------------------------------------------------------------------------- |
-| `1` | Boolean \| Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------------------ |
+| `1` | Boolean \| Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback) |
Determines if the animation should repeat, and how many times it should repeat.
@@ -489,9 +531,9 @@ Determines if the animation should automatically play, immediately after being i
### direction
-| Default | Type |
-| :------- | :----------------------------------------------------------------------------------------------- |
-| `normal` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------- | :------------------------------------------------------------------------------------------------------- |
+| `normal` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback) |
Determines the direction of the animation, the directions available are:
@@ -502,9 +544,9 @@ Determines the direction of the animation, the directions available are:
### speed
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------- |
-| `1` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------- |
+| `1` | Number \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_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),
@@ -513,9 +555,9 @@ _**Note**: negative numbers reverse the animation._
### fillMode
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------- |
-| `auto` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------- |
+| `auto` | String \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_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)._
@@ -531,9 +573,9 @@ You can learn more here on [MDN](https://developer.mozilla.org/en-US/docs/Web/AP
### options
-| Default | Type |
-| :------ | :----------------------------------------------------------------------------------------------------------------------------------- |
-| `{}` | [IAnimationOptions](https://okikio.github.io/native/docs/interfaces/animate.ianimationoptions.html) = Object \| Animate \| Animate[] |
+| Default | Type |
+| :------ | :------------------------------------------------------------------------------------------------------------------------------------------- |
+| `{}` | [IAnimationOptions](https://okikio.github.io/native/docs/interfaces/_okikio_animate.ianimationoptions.html) = Object \| Animate \| Animate[] |
Another way to input options for an animation, it's also used to chain animations.
@@ -620,9 +662,9 @@ _**Note**: you can't use this property as a method._
### offset
-| Default | Type |
-| :---------- | :------------------------------------------------------------------------------------------------------------- |
-| `undefined` | (Number \| String)[] \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :---------- | :--------------------------------------------------------------------------------------------------------------------- |
+| `undefined` | (Number \| String)[] \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback) |
Controls the starting point of certain parts of an animation.
@@ -658,11 +700,11 @@ _**Note**: timeline cannot be a callback/function_
### keyframes
-| Default | Type |
-| :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `[]` | TypeCSSLikeKeyframe \| ICSSComputedTransformableProperties[] & Keyframe[] \| object[] \| [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback) |
+| Default | Type |
+| :------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `[]` | TypeCSSLikeKeyframe \| ICSSComputedTransformableProperties[] & Keyframe[] \| object[] \| [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_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).
+I highly suggest going through the API documentation to better understand [keyframes](https://okikio.github.io/native/docs/interfaces/_okikio_animate.ianimationoptions.html#keyframes).
Allows you to manually set keyframes using a `keyframe` array
@@ -670,9 +712,11 @@ Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffe
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)
+`@okikio/animate` also offers another format called `CSSLikeKeyframe`, read more about [KeyframeParse](https://okikio.github.io/native/docs/modules/_okikio_native.html#keyframeparse)
+
+It basically functions the same way CSS's `@keyframe` works.
-It basically functions the same way CSS's `@keyframe` works
+_**Note**: the order of `transform` functions in CSS Property form...matter, meanwhile in keyframes the transform order doesn't, keep this in mind when you are try to create complex rotation based animations or other complex animations in general._
```ts
animate({
@@ -696,13 +740,27 @@ animate({
//= ]
```
+### composite
+
+The `composite` property of a `KeyframeEffect` resolves how an element's animation impacts its underlying property values.
+
+To understand these values, take the example of a `keyframeEffect` value of `blur(2)` working on an underlying property value of `blur(3)`.
+
+- `replace` - The keyframeEffect overrides the underlying value it is combined with: `blur(2)` replaces `blur(3)`.
+- `add` - The keyframeEffect is added to the underlying value with which it is combined (aka additive): `blur(2) blur(3)`.
+- `accumulate` - The keyframeEffect is accumulated on to the underlying value: `blur(5)`.
+
+Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/composite)
+
+I recommend reading [web.dev](https://web.dev)'s article on [web-animations](https://web.dev/web-animations/#smoother-animations-with-composite-modes).
+
### extend
| Default | Type |
| :------ | :---------------------------------------------------------------------------------------------- |
| `{}` | [KeyframeEffectOptions](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffectOptions) |
-The properties of the `extend` animation option are computed and can use [TypeCallback](https://okikio.github.io/native/docs/modules/animate.html#typecallback), they are a way to access features that haven't been implemented in `@okikio/animate`, for example, `iterationStart`.
+The properties of the `extend` animation option are computed and can use [TypeCallback](https://okikio.github.io/native/docs/modules/_okikio_animate.html#typecallback), they are a 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.
@@ -838,11 +896,13 @@ _**Note**: dash & camel case are supported as CSS property names, this also incl
_**Note**: all other features will work with Transformable CSS Properties, this includes the `keyframes` animation options and `animation options` as callbacks_
+_**Note**: the order of `transform` functions in CSS Property form...matter, meanwhile in keyframes the transform order doesn't, keep this in mind when you are try to create complex rotation based animations or other complex animations in general._
+
_**Warning**: only the transform function properties and CSS properties with the keys ["margin", "padding", "size", "width", "height", "left", "right", "top", "bottom", "radius", ,"gap", "basis", "inset", "outline-offset", "perspective", "thickness", "position", "distance", "spacing", "rotate"] will get automatic units. It will also work with multiple unit CSS properties like "margin", "padding", and "inset", etc..., however, no automatic units will be applied to any CSS properties that can accept color, this is to avoid unforseen bugs_
-Read more about the [ParseTransformableCSSProperties](https://okikio.github.io/native/docs/modules/animate.html#parsetransformablecssproperties) method.
+Read more about the [ParseTransformableCSSProperties](https://okikio.github.io/native/docs/modules/_okikio_animate.html#parsetransformablecssproperties) method.
-Also, read about the [ParseTransformableCSSKeyframes](https://okikio.github.io/native/docs/modules/animate.html#parsetransformablecsskeyframes) method.
+Also, read about the [ParseTransformableCSSKeyframes](https://okikio.github.io/native/docs/modules/_okikio_animate.html#parsetransformablecsskeyframes) method.
Check out an example on [Codepen](https://codepen.io/okikio/pen/qBrNXoY?editors=0110)
@@ -969,7 +1029,17 @@ There are `8` events in total, they are:
- "playstate-change"
```ts
-// The update event is triggered continously while an animation is playing.
+/*
+ The update event is triggered continously while an animation is playing, it does this by calling requestAnimationFrame.
+ By default, whenever an animation is played, the current Animate instance is added to `Animate.RUNNING` WeakSet and
+ a requests for an animation frame is called, where it checks if there are any listeners for the "update" event.
+ If there are none, the Animate instance is removed from the `Animate.RUNNING` WeakSet.
+ If there are listeners the Animate instances loop method is called, and the "update" event is emitted every frame until,
+ the Animation is done, where it stops
+
+ If there are no Animate instances in the `Animate.RUNNING` WeakSet, the requestAnimationFrame loop, is stopped,
+ until there are other Animate instances that are played
+*/
....on("update", (progress, instance) => {
/**
* @param {number} progress - it is the animation progress from 0 to 100
@@ -1011,6 +1081,244 @@ There are `8` events in total, they are:
....on("stop", () => { });
```
+## Custom Easing
+
+Custom Easing isn't currently a thing in the Web Animation API (WAAPI), so, the next best thing is to emulate the effect of Custom Easing. I added the `CustomEasing` function for this reason, you can use it like this,
+
+```ts
+import { animate, CustomEasing, EaseOut, Quad } from "@okikio/animate";
+
+animate({
+ // Notice how only, the first value in the Array uses the "px" unit
+ border: CustomEasing(["1px solid red", "3 dashed green", "2 solid black"], {
+ // This is a custom easing function
+ easing: EaseOut(Quad)
+ }),
+
+ translateX: CustomEasing([0, 250], {
+ easing: "linear",
+
+ // You can change the size of Array for the CustomEasing function to generate
+ numPoints: 200,
+
+ // The number of decimal places to round, final values in the generated Array
+ decimal: 5,
+ }),
+
+ // You can set the easing without an object
+ // Also, if units are detected in the values Array,
+ // the unit of the first value in the values Array are
+ // applied to other values in the values Array, even if they
+ // have prior units
+ rotate: CustomEasing(["0turn", 1, 0, 0.5], "out"),
+ "background-color": CustomEasing(["#616aff", "white"]),
+ easing: "linear"
+})
+```
+
+You can view a demo of Custom Easing on [Codepen](https://codepen.io/okikio/pen/abJMWNy). I based the Custom Easing implementation on a comment by [@jakearchibald](https://github.com/jakearchibald) on [Github](https://github.com/w3c/csswg-drafts/issues/229#issuecomment-860778689) and an article by [kirillvasiltsov](https://www.kirillvasiltsov.com/writing/how-to-create-a-spring-animation-with-web-animation-api/).
+
+Custom Easing uses the fact that WAAPI allows for linear easing, and for users to set multiple different values in Array format, thus, I created a small function that generates a set of arrays that create custom easing effects like bounce, elastic, and spring. As of right now it builds on top of `@okikio/animate` but `@okikio/animate` isn't absolutely necessary, it just may not be as comfortable to using it without `@okikio/animate`.
+
+Custom Easing has 3 properties they are `easing` (all the easings from [#easing](#easing) are supported on top of custom easing functions, like spring, bounce, etc...), `numPoints` (the size of the Array the Custom Easing function should create), and `decimal` (the number of decimal places of the values within said Array).
+
+| Properties | Default Value |
+| ----------- | ----------------------- |
+| `easing` | `spring(1, 100, 10, 0)` |
+| `numPoints` | `50` |
+| `decimal` | `3` |
+
+By default, Custom Easing support easing functions, in the form,
+
+| constant | accelerate | decelerate | accelerate-decelerate | decelerate-accelerate |
+| :--------- | :----------------- | :------------- | :-------------------- | :-------------------- |
+| linear | ease-in / in | ease-out / out | ease-in-out / in-out | ease-out-in / out-in |
+| ease | in-sine | out-sine | in-out-sine | out-in-sine |
+| steps | in-quad | out-quad | in-out-quad | out-in-quad |
+| step-start | in-cubic | out-cubic | in-out-cubic | out-in-cubic |
+| step-end | in-quart | out-quart | in-out-quart | out-in-quart |
+| | in-quint | out-quint | in-out-quint | out-in-quint |
+| | in-expo | out-expo | in-out-expo | out-in-expo |
+| | in-circ | out-circ | in-out-circ | out-in-circ |
+| | in-back | out-back | in-out-back | out-in-back |
+| | in-bounce | out-bounce | in-out-bounce | out-in-bounce |
+| | in-elastic | out-elastic | in-out-elastic | out-in-elastic |
+| | spring / spring-in | spring-out | spring-in-out | spring-out-in |
+
+All **Elastic** easing's can be configured using theses parameters,
+
+`*-elastic(amplitude, period)`
+
+Each parameter comes with these defaults
+
+| Parameter | Default Value |
+| --------- | ------------- |
+| amplitude | `1` |
+| period | `0.5` |
+
+***
+
+All **Spring** easing's can be configured using theses parameters,
+
+`spring-*(mass, stiffness, damping, velocity)`
+
+Each parameter comes with these defaults
+
+| Parameter | Default Value |
+| --------- | ------------- |
+| mass | `1` |
+| stiffness | `100` |
+| damping | `10` |
+| velocity | `0` |
+
+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**: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`_
+
+### SpringEasing
+
+Returns an array containing `[easing points, duration]`, it's meant to be a self enclosed way to create spring easing.
+Springs have an optimal duration; using [`getEasingDuration()`](https://okikio.github.io/native/docs/modules/_okikio_animate.html#geteasingduration) we are able to have the determine the optimal duration for a spring with given parameters.
+
+By default it will only give the optimal duration for `spring` or `spring-in` easing, this is to avoid infinite loops caused by the `getEasingDuration()` function.
+
+Internally the `SpringEasing` uses [CustomEasing](https://okikio.github.io/native/docs/modules/_okikio_animate.html#applycustomeasing), read more on it, to understand how the `SpringEasing` function works.
+
+e.g.
+
+```ts
+import { animate, SpringEasing } from "@okikio/animate";
+
+// `duration` is the optimal duration for the spring with the set parameters
+let [translateX, duration] = SpringEasing([0, 250], "spring(5, 100, 10, 1)");
+// or
+// `duration` is 5000 here
+let [translateX, duration] = SpringEasing([0, 250], {
+ easing: "spring(5, 100, 10, 1)",
+ numPoints: 50,
+ duration: 5000,
+ decimal: 3
+});
+
+animate({
+ target: "div",
+ translateX,
+ duration
+});
+```
+
+### ApplyCustomEasing
+
+You can also use `ApplyCustomEasing`. It applies the same custom easings to all properties of an object it also returns an object with each property having an array of custom eased values
+
+If you use the `spring` or `spring-in` easings it will also return the optimal duration as a key in the object it returns.
+If you set `duration` to a number, it will prioritize that `duration` over optimal duration given by the spring easings.
+
+Read more about [CustomEasing](https://okikio.github.io/native/docs/modules/_okikio_animate.html#applycustomeasing).
+
+e.g.
+
+```ts
+import { animate, ApplyCustomEasing } from "@okikio/animate";
+animate({
+ target: "div",
+
+ ...ApplyCustomEasing({
+ border: ["1px solid red", "3 dashed green", "2 solid black"],
+ translateX: [0, 250],
+ rotate: ["0turn", 1, 0, 0.5],
+ "background-color": ["#616aff", "white"],
+
+ // You don't need to enter any parameters, you can just use the default values
+ easing: "spring",
+ // You can change the size of Array for the CustomEasing function to generate
+ numPoints: 200,
+ // The number of decimal places to round, final values in the generated Array
+ decimal: 5,
+
+ // You can also set the duration from here.
+ // When using spring animations, the duration you set here is not nesscary,
+ // since by default springs will try to determine the most appropriate duration for the spring animation.
+ // But the duration value here will override `spring` easings optimal duration value
+ duration: 3000
+ })
+})
+```
+
+## DestroyableAnimate
+
+[`DestroyableAnimate`](https://okikio.github.io/native/docs/modules/_okikio_animate.html#destroyableanimate) is an extended varient of [`Animate`](https://okikio.github.io/native/docs/classes/_okikio_animate.animate.html) that automatically removes the target elements from the DOM, when the [`stop()`](https://okikio.github.io/native/docs/classes/_okikio_animate.animate.html#stop) method is called.
+
+## Tweens
+
+### tween
+
+[`tween()`](https://okikio.github.io/native/docs/modules/_okikio_animate.html#tween) creates an empty new element with an id of `empty-animate-el-${number...}` with a display style of `none`, and then attaches it to the DOM. `tween()` returns a new instance of the `DestroyableAnimate` class and then animates the opacity of the empty element.
+
+You can then use the "update" event to watch for changes in opacity and use the opacity as a progress bar of values between 0 to 1. This enables you to animate properties and attributes the Web Animation API (WAAPI) doesn't yet support.
+
+### tweenAttr
+
+[`tweenAttr()`](https://okikio.github.io/native/docs/modules/_okikio_animate.html#tweenattr) uses the change in opacity (from the [tween](https://okikio.github.io/native/docs/modules/_okikio_animate.html#tween) function) to interpolate the value of other elements.
+
+e.g.
+
+```ts
+import { tweenAttr } from "@okikio/animate";
+import { interpolate } from "polymorph-js";
+
+let startPath = usingPolymorphPathEl.getAttribute("d");
+let endPath = "M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z";
+
+// This is an svg path interpolate function
+// If used in tandem with `tweenAttr`, you can create morphing animations
+let morph = interpolate([startPath, endPath], {
+ addPoints: 0,
+ origin: { x: 0, y: 0 },
+ optimize: "fill",
+ precision: 3
+});
+
+// `tweenAttr` supports all Animation Options.
+// The first argument in Animation Options callbacks are set to the progress of the animation beteen 0 and 1, while the other arguments are moved 1 right
+
+// So, animation options can look like this
+// `(progress: number, i: number, len: number, el: HTMLElement) => {
+// return progress;
+// }`
+
+tweenAttr({
+ target: "svg path",
+ d: progress => morph(progress)
+});
+
+// `tweenAttr` can automatically choose between custom easing functions and or normal easings
+tweenAttr({
+ target: ".div",
+ targets: ".el",
+ width: 250,
+ height: ["500px", 600],
+ easing: "spring"
+
+// If you want to update styles instead of attributes,
+// you can change this to "style"
+}, "style");
+```
+
+Read more about [tween](https://okikio.github.io/native/docs/modules/_okikio_animate.html#tween).
+
+## Effects
+
+You may want to use premade effects like the onces [animate.css](https://www.npmjs.com/package/animate.css) provide, I initially planned on bundling this functionality in, but because of the plentiful number of libraries that do the same thing, I suggest using those instead, and if you want to create your own effects from CSS, you can use CSS Keyframe style JSON object, make sure to read the documentation for [KeyframeParse](https://okikio.github.io/native/docs/modules/_okikio_animate.html#keyframeparse)
+
+I suggest [@shoelace-style/animations](https://www.npmjs.com/package/@shoelace-style/animations) for all your animate.css needs.
+
+or
+
+if you just need some quick effects go to [github.com/wellyshen/use-web-animations/](https://github.com/wellyshen/use-web-animations/tree/master/src/animations) and copy the `keyframes` array for the effect you want, remember to say thank you to [@wellyshen](https://github.com/wellyshen) for all his hardwork, 😂.
+
## Additional methods & properties
### mainAnimation: Animation
diff --git a/packages/animate/src/animate.ts b/packages/animate/src/animate.ts
new file mode 100644
index 0000000..ad40b8b
--- /dev/null
+++ b/packages/animate/src/animate.ts
@@ -0,0 +1,1186 @@
+import { EventEmitter } from "@okikio/emitter";
+import { Manager } from "@okikio/manager";
+import { KeyframeParse, parseOffset } from "./builtin-effects";
+import { ParseTransformableCSSProperties, ParseTransformableCSSKeyframes } from "./css-properties";
+import { flatten, mapObject, convertToDash, isValid, omit } from "./utils";
+
+import type { TypeEventInput, TypeListenerCallback } from "@okikio/emitter";
+import type { TypeAnimationTarget, TypeAnimationOptionTypes, TypeCallbackArgs, TypeComputedAnimationOptions, IAnimationOptions, TypeComputedOptions, TypeKeyFrameOptionsType, TypeCSSLikeKeyframe, ICSSComputedTransformableProperties, TypeAnimationEvents, TypePlayStates } from "./types";
+
+/* DOM */
+export const getElements = (selector: string | Node): Node[] => {
+ return typeof selector === "string" ? Array.from(document.querySelectorAll(selector as string)) : [selector];
+};
+
+export const getTargets = (targets: TypeAnimationTarget): Node[] => {
+ if (Array.isArray(targets)) {
+ return flatten((targets as TypeAnimationTarget[]).map(getTargets));
+ }
+ if (typeof targets == "string" || targets instanceof Node)
+ return getElements(targets);
+ if (targets instanceof NodeList || targets instanceof HTMLCollection)
+ return Array.from(targets);
+ return [];
+};
+
+/* VALUES */
+export const computeOption = (value: TypeAnimationOptionTypes, args: TypeCallbackArgs, context: Animate): TypeComputedAnimationOptions => {
+ if (typeof value === "function") {
+ return value.apply(context, args);
+ } else return value;
+};
+
+export const mapAnimationOptions = (options: IAnimationOptions, args: TypeCallbackArgs, animate: Animate): TypeComputedOptions => {
+ return mapObject(options, (value) => computeOption(value, args, animate));
+};
+
+/**
+ * From: [https://easings.net]
+ *
+ * Read More about easings on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing)
+ *
+ * ```ts
+ * {
+ * "in": "ease-in",
+ * "out": "ease-out",
+ * "in-out": "ease-in-out",
+ *
+ * // Sine
+ * "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)",
+ * "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)",
+ * "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)",
+ *
+ * // Quad
+ * "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)",
+ * "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
+ * "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)",
+ *
+ * // Cubic
+ * "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)",
+ * "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)",
+ * "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)",
+ *
+ * // Quart
+ * "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)",
+ * "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)",
+ * "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)",
+ *
+ * // Quint
+ * "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)",
+ * "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)",
+ * "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)",
+ *
+ * // Expo
+ * "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)",
+ * "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)",
+ * "in-out-expo": "cubic-bezier(1, 0, 0, 1)",
+ *
+ * // Circ
+ * "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)",
+ * "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)",
+ * "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)",
+ *
+ * // Back
+ * "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)",
+ * "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)",
+ * "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)"
+ * }
+ * ```
+ */
+export const EASINGS = {
+ "in": "ease-in",
+ "out": "ease-out",
+ "in-out": "ease-in-out",
+
+ // Sine
+ "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)",
+ "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)",
+ "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)",
+
+ // Quad
+ "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)",
+ "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
+ "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)",
+
+ // Cubic
+ "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)",
+ "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)",
+ "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)",
+
+ // Quart
+ "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)",
+ "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)",
+ "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)",
+
+ // Quint
+ "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)",
+ "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)",
+ "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)",
+
+ // Expo
+ "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)",
+ "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)",
+ "in-out-expo": "cubic-bezier(1, 0, 0, 1)",
+
+ // Circ
+ "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)",
+ "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)",
+ "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)",
+
+ // Back
+ "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)",
+ "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)",
+ "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)"
+};
+
+/**
+ * The keys of {@link EASINGS}
+ *
+ * @remark
+ * "in", "out", "in-out", "in-sine", "out-sine", "in-out-sine", "in-quad", "out-quad", "in-out-quad", "in-cubic", "out-cubic", "in-out-cubic", "in-quart", "out-quart", "in-out-quart", "in-quint", "out-quint", "in-out-quint", "in-expo", "out-expo", "in-out-expo", "in-circ", "out-circ", "in-out-circ", "in-back", "out-back", "in-out-back"
+ */
+export const EasingKeys = Object.keys(EASINGS);
+
+/**
+ * Converts users input into a usable easing function string
+ *
+ * @param ease - easing functions; {@link EasingKeys}, cubic-bezier, steps, linear, etc...
+ * @returns an easing function that `KeyframeEffect` can accept
+ */
+export const GetEase = (ease: keyof typeof EASINGS | string = "ease"): string => {
+ // Convert camelCase strings into dashed strings, then Remove the "ease-" keyword
+ let search = convertToDash(ease).replace(/^ease-/, "");
+ return EasingKeys.includes(search) ? EASINGS[search] : ease;
+};
+
+/**
+ * The default options for every Animate instance
+ *
+ * ```ts
+ * {
+ * keyframes: [],
+ *
+ * loop: 1,
+ * delay: 0,
+ * speed: 1,
+ * endDelay: 0,
+ * easing: "ease",
+ * autoplay: true,
+ * duration: 1000,
+ * fillMode: "none",
+ * direction: "normal",
+ * padEndDelay: false,
+ * timeline: document.timeline,
+ * extend: {}
+ * }
+ * ```
+ */
+export const DefaultAnimationOptions: IAnimationOptions = {
+ keyframes: [],
+ offset: [],
+
+ loop: 1,
+ delay: 0,
+ speed: 1,
+ endDelay: 0,
+ easing: "ease",
+ timelineOffset: 0,
+ autoplay: true,
+ duration: 1000,
+ fillMode: "none",
+ direction: "normal",
+ padEndDelay: false,
+ timeline: document.timeline,
+ extend: {}
+};
+
+/** Parses the different ways to define options, and returns a merged options object */
+export const parseOptions = (options: IAnimationOptions): IAnimationOptions => {
+ let { options: animation, ...rest } = options;
+ let oldOptions = animation instanceof Animate ? animation.options : (Array.isArray(animation) ? animation?.[0]?.options : animation);
+ return Object.assign({}, oldOptions, rest);
+}
+
+export const FUNCTION_SUPPORTED_TIMING_KEYS = ["easing", "loop", "endDelay", "duration", "speed", "delay", "timelineOffset", "direction", "extend", "fillMode", "offset"];
+export const NOT_FUNCTION_SUPPORTED_TIMING_KEYS = ["keyframes", "padEndDelay", "onfinish", "oncancel", "autoplay", "target", "targets", "timeline"];
+export const ALL_TIMING_KEYS = [...FUNCTION_SUPPORTED_TIMING_KEYS, ...NOT_FUNCTION_SUPPORTED_TIMING_KEYS];
+
+/**
+ * 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.
+ *
+ * You can check it out here:
+ */
+export class Animate {
+ /**
+ * Stores the options for the current animation
+ *
+ * Read more about the {@link DefaultAnimationOptions}
+ */
+ public options: IAnimationOptions = {};
+
+ /**
+ * The properties to animate
+ */
+ public properties: object = {};
+
+ /**
+ * The total duration of all Animation's
+ */
+ public totalDuration: number = -Infinity;
+
+ /**
+ * The smallest delay out of all Animation's
+ */
+ public minDelay: number = Infinity;
+
+ /**
+ * The smallest speed out of all Animation's
+ */
+ public maxSpeed: number = Infinity;
+
+ /**
+ * The Element the mainAnimation runs on
+ */
+ public mainElement: HTMLElement;
+
+ /**
+ * Stores an animation that runs on the total duration of all the `Animation` instances, and as such it's the main Animation.
+ */
+ public mainAnimation: Animation;
+
+ /**
+ * The Keyframe Effect for the mainAnimation
+ */
+ public mainkeyframeEffect: KeyframeEffect;
+
+ /**
+ * An event emitter
+ */
+ public emitter: EventEmitter = new EventEmitter();
+
+ /**
+ * Returns a promise that is fulfilled when the mainAnimation is finished
+ */
+ public promise: Promise;
+
+ /**
+ * The list of Elements to Animate
+ */
+ public targets: Manager = new Manager();
+
+ /**
+ * The indexs of target Elements in Animate
+ */
+ public targetIndexes: WeakMap = new WeakMap();
+
+ /**
+ * A WeakMap of KeyFrameEffects
+ */
+ public keyframeEffects: WeakMap = new WeakMap();
+
+ /**
+ * The options for individual animations
+ *
+ * A WeakMap 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.*_
+ *
+ * _**Note**: keyframes are not included, both the array form and the object form; the options, speed, extend, padEndDelay, and autoplay animation options are not included_
+ */
+ public computedOptions: WeakMap = new WeakMap();
+
+ /**
+ * A WeakMap of Animations
+ */
+ public animations: WeakMap = new WeakMap();
+
+ /**
+ * The keyframes for individual animations
+ *
+ * A WeakMap that stores all the fully calculated keyframes for individual Animation instances.
+ *
+ * _**Note**: the computedKeyframes 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. translateX, skew, etc..., they've all been turned into the transform property.*_
+ */
+ public computedKeyframes: WeakMap = new WeakMap();
+ constructor(options: IAnimationOptions) {
+ this.loop = this.loop.bind(this);
+ this.onVisibilityChange = this.onVisibilityChange.bind(this);
+
+ this.on("error", console.error);
+ this.updateOptions(options);
+
+ if (this.mainAnimation) {
+ this.visibilityPlayState = this.getPlayState();
+ if (Animate.pauseOnPageHidden) {
+ document.addEventListener('visibilitychange', this.onVisibilityChange, false);
+ }
+ }
+
+ this.newPromise();
+ }
+
+ /**
+ * Tells all animate instances to pause when the page is hidden
+ */
+ static pauseOnPageHidden: Boolean = true;
+
+ /**
+ * Stores all currently running instances of the Animate Class that are actively using requestAnimationFrame to check progress,
+ * it's meant to ensure you don't have multiple instances of the Animate Class creating multiple requestAnimationFrames at the same time
+ * this can cause performance hiccups
+ */
+ static RUNNING: Set = new Set();
+
+ /**
+ * Stores request frame calls
+ */
+ static animationFrame: number;
+
+ /**
+ * Calls requestAnimationFrame for each running instance of Animate
+ */
+ static requestFrame() {
+ // Cancel any lingering requestAnimationFrames from preious run of the requestFrame method
+ Animate.cancelFrame();
+ Animate.RUNNING.forEach((inst) => {
+ if (inst.emitter.getEvent("update").length <= 0) {
+ inst.stopLoop();
+ } else { inst.loop(); }
+ });
+
+ // If there are no more Animate instances in the RUNNING WeakSet,
+ // cancel the requestAnimationFrame
+ if (Animate.RUNNING.size > 0) {
+ Animate.animationFrame = window.requestAnimationFrame(Animate.requestFrame);
+ } else Animate.cancelFrame();
+ }
+
+ /**
+ * Cancels animationFrame
+ */
+ static cancelFrame() {
+ window.cancelAnimationFrame(Animate.animationFrame);
+ Animate.animationFrame = null;
+ }
+
+ /**
+ * Represents an Animation Frame Loop
+ */
+ public loop(): void {
+ this.emit("update", this.getProgress(), this);
+ }
+
+ /**
+ * Cancels animation frame
+ */
+ public stopLoop() {
+ Animate.RUNNING.delete(this);
+ }
+
+ /**
+ * Store the last remebered playstate before page was hidden
+ */
+ protected visibilityPlayState: TypePlayStates;
+
+ /**
+ * document `visibilitychange` event handler
+ */
+ protected onVisibilityChange() {
+ if (document.hidden) {
+ this.visibilityPlayState = this.getPlayState();
+ if (this.is("running")) {
+ this.loop();
+ this.pause();
+ }
+ } else {
+ if (this.visibilityPlayState == "running" && this.is("paused"))
+ this.play();
+ }
+ }
+
+ /**
+ * Returns a new Promise that is resolved when the animation finishes
+ */
+ public newPromise(): Promise {
+ this.promise = new Promise((resolve, reject) => {
+ /*
+ Note that the `this` keyword is in an Array when it is resolved,
+ this is due to Promises not wanting to resolve references,
+ so, you can't resolve `this` directly, so, I chose to resolve `this` in an
+ Array
+
+ Note: the `resolve` method by default will only run once so to avoid
+ */
+ this.emitter?.once?.("finish", () => resolve([this]));
+ this.emitter?.once?.("error", err => reject(err));
+ });
+
+ return this.promise;
+ }
+
+ /**
+ * Fulfills the `this.promise` Promise
+ */
+ public then(
+ onFulfilled?: (value?: any) => any,
+ onRejected?: (reason?: any) => any
+ ): Animate {
+ onFulfilled = onFulfilled?.bind(this);
+ onRejected = onRejected?.bind(this);
+ this.promise?.then?.(onFulfilled, onRejected);
+ return this;
+ }
+
+ /**
+ * Catches error that occur in the `this.promise` Promise
+ */
+ public catch(onRejected: (reason?: any) => any): Animate {
+ onRejected = onRejected?.bind(this);
+ this.promise?.catch?.(onRejected);
+ return this;
+ }
+
+ /**
+ * If you don't care if the `this.promise` Promise has either been rejected or resolved
+ */
+ public finally(onFinally: () => any): Animate {
+ onFinally = onFinally?.bind(this);
+ this.promise?.finally?.(onFinally);
+ return this;
+ }
+
+ /**
+ * Calls a method that affects all animations **excluding** the mainAnimation; the method only allows the animation parameter
+ */
+ public allAnimations(method: (animation?: Animation, target?: HTMLElement) => void) {
+ this.targets.forEach((target: HTMLElement) => {
+ let keyframeEffect = this.keyframeEffects.get(target);
+ let animation = this.animations.get(keyframeEffect);
+ return method(animation, target);
+ });
+ return this;
+ }
+
+ /**
+ * Calls a method that affects all animations **including** the mainAnimation; the method only allows the animation parameter
+ */
+ public all(method: (animation?: Animation, target?: HTMLElement) => void) {
+ this.mainAnimation && method(this.mainAnimation, this.mainElement);
+ this.allAnimations(method);
+ return this;
+ }
+
+ /**
+ * Register the begin event
+ */
+ protected beginEvent() {
+ if (this.getProgress() == 0)
+ this.emit("begin", this);
+ }
+
+ /**
+ * Play Animation
+ */
+ public play(): Animate {
+ let playstate = this.getPlayState();
+ this.beginEvent();
+ this.all(anim => anim.play());
+ this.emit("play", playstate, this);
+ if (!this.is(playstate))
+ this.emit("playstate-change", playstate, this);
+
+ this.loop();
+
+ // Because the Web Animation API doesn't require requestAnimationFrame for animations,
+ // we only run the requestAnimationFrame when there is a "update" event listener
+ Animate.RUNNING.add(this);
+ Animate.requestFrame();
+ return this;
+ }
+
+ /**
+ * Pause Animation
+ */
+ public pause(): Animate {
+ let playstate = this.getPlayState();
+ this.all(anim => anim.pause());
+ this.emit("pause", playstate, this);
+ if (!this.is(playstate))
+ this.emit("playstate-change", playstate, this);
+ this.stopLoop();
+ return this;
+ }
+
+ /**
+ * Reverse Animation
+ */
+ public reverse() {
+ this.all(anim => anim.reverse());
+ return this;
+ }
+
+ /**
+ * Reset all Animations
+ */
+ public reset() {
+ this.setProgress(0);
+
+ if (this.options.autoplay) this.play();
+ else this.pause();
+ return this;
+ }
+
+ /**
+ * Cancels all Animations
+ */
+ public cancel() {
+ this.all(anim => anim.cancel());
+ return this;
+ }
+
+ /**
+ * Force complete all Animations
+ */
+ public finish() {
+ this.all(anim => anim.finish());
+ return this;
+ }
+
+ /**
+ * Cancels & Clears all Animations
+ */
+ public stop() {
+ this.cancel();
+ this.stopLoop();
+ document.removeEventListener('visibilitychange', this.onVisibilityChange, false);
+
+ this.targets.forEach((target: HTMLElement) => this.removeTarget(target));
+
+ this.emit("stop");
+ this.emitter.clear();
+
+ this.mainkeyframeEffect = null;
+ this.mainAnimation = null;
+
+ this.mainElement?.remove?.();
+ this.mainElement = null;
+
+ this.promise = null;
+ this.computedOptions = null;
+ this.animations = null;
+ this.keyframeEffects = null;
+ this.emitter = null;
+ this.targets = null;
+ this.options = null;
+ this.properties = null;
+ }
+
+ /**
+ * Get a specific Animation from an Animate instance
+ */
+ public getAnimation(target: HTMLElement) {
+ let keyframeEffect = this.keyframeEffects.get(target);
+ return this.animations.get(keyframeEffect);
+ }
+
+ /**
+ * Returns the timings of an Animation, given a target
+ * E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... }
+ */
+ public getTiming(target: HTMLElement): TypeComputedAnimationOptions {
+ let keyframeOptions = this.computedOptions.get(target) ?? {};
+ let timings = this.keyframeEffects.get(target).getTiming?.() ?? {};
+
+ return { ...keyframeOptions, ...timings };
+ }
+
+ /**
+ * Returns the current time of the Main Animation
+ */
+ public getCurrentTime(): number {
+ return this.mainAnimation.currentTime;
+ }
+
+ /**
+ * Returns the Animation progress as a fraction of the current time / duration * 100
+ */
+ public getProgress() {
+ return (this.getCurrentTime() / this.totalDuration) * 100;
+ }
+
+ /**
+ * Return the playback speed of the animation
+ */
+ public getSpeed(): number {
+ return this.mainAnimation.playbackRate;
+ }
+
+ /**
+ * Returns the current playing state
+ */
+ public getPlayState(): TypePlayStates {
+ return this.mainAnimation.playState;
+ }
+
+ /**
+ * Returns a boolean determining if the `animate` instances playstate is equal to the `playstate` parameter.
+ */
+ public is(playstate: TypePlayStates) {
+ return this.getPlayState() == playstate;
+ }
+
+ /**
+ * Set the current time of the Main Animation
+ */
+ public setCurrentTime(time: number): Animate {
+ this.all(anim => (anim.currentTime = time));
+ this.emit("update", this.getProgress());
+ return this;
+ }
+
+ /**
+ * Set the Animation progress as a value from 0 to 100
+ */
+ public setProgress(percent: number): Animate {
+ let time = (percent / 100) * this.totalDuration;
+ this.setCurrentTime(time);
+ return this;
+ }
+
+ /**
+ * Set the playback speed of an Animation
+ */
+ public setSpeed(speed: number = 1): Animate {
+ this.maxSpeed = speed;
+ this.all(anim => {
+ if (anim.updatePlaybackRate)
+ anim.updatePlaybackRate(speed);
+ else anim.playbackRate = speed;
+ });
+ return this;
+ }
+
+ /**
+ * Returns an array of computed options
+ */
+ protected createArrayOfComputedOptions(optionsFromParam: IAnimationOptions, len: number) {
+ let result: TypeComputedAnimationOptions = [];
+ this.targets.forEach((target: HTMLElement, i) => {
+ // Basically if there is already a computedOption for the target element use it, but don't ovveride any new options
+ let oldComputedOptions: IAnimationOptions = this.computedOptions.get(target) ?? {};
+ let getOption = (key: string) => {
+ let computedKey = key;
+ if (key == "loop") computedKey = "iterations";
+ if (key == "fillMode") computedKey = "fill";
+ return optionsFromParam[key] ?? oldComputedOptions[computedKey] ?? this.options[key] ?? DefaultAnimationOptions[key];
+ };
+
+ let animationOptions = Object.assign({
+ easing: getOption("easing"),
+ iterations: getOption("loop"),
+ direction: getOption("direction"),
+ endDelay: getOption("endDelay"),
+ duration: getOption("duration"),
+ speed: getOption("speed"),
+ delay: getOption("delay"),
+ timelineOffset: getOption("timelineOffset"),
+ keyframes: getOption("keyframes"),
+ }, getOption("extend") ?? {});
+
+ // let oldComputedOptions = this.computedOptions.get(target)
+ // Allows the use of functions as the values, for both the keyframes and the animation object
+ // It adds the capability of advanced stagger animation, similar to the animejs stagger functions
+ let computedOptions = mapAnimationOptions(animationOptions as IAnimationOptions, [i, len, target], this);
+
+ if (typeof computedOptions.easing == "string")
+ computedOptions.easing = GetEase(computedOptions.easing);
+
+ if (computedOptions.iterations === true)
+ computedOptions.iterations = Infinity;
+
+ computedOptions.fill = getOption("fillMode");
+
+ // Add timelineOffset to delay, this is future proofing;
+ // if you want to create a custom timeline similar to animejs this will help you
+ // I don't intend to make a timeline function for this project
+ let {
+ timelineOffset,
+ speed,
+ endDelay,
+ delay,
+ duration,
+ iterations,
+ ...remainingComputedOptions
+ } = computedOptions;
+
+ iterations = Number(iterations);
+ duration = Number(duration);
+ endDelay = Number(endDelay);
+ speed = Number(speed);
+ delay = Number(delay) + Number(timelineOffset);
+
+ let tempDurations = delay + (duration * iterations) + endDelay;
+
+ // Set the totalDuration to be the Animation with the largest totalDuration
+ if (this.totalDuration < tempDurations)
+ this.totalDuration = tempDurations;
+
+ result[i] = {
+ ...remainingComputedOptions,
+ speed,
+ tempDurations,
+ endDelay,
+ delay,
+ duration,
+ iterations,
+ };
+
+ if (this.minDelay > delay) this.minDelay = delay;
+ if (this.maxSpeed > speed) this.maxSpeed = speed;
+ });
+ return result;
+ }
+
+ /**
+ * Creates animations out of an array of computed options
+ */
+ protected createAnimations(param: { arrOfComputedOptions: any; padEndDelay: any; oldCSSProperties: any; onfinish: any; oncancel: any; timeline?: any; }, len: number) {
+ let {
+ arrOfComputedOptions,
+ padEndDelay,
+ oldCSSProperties,
+ onfinish,
+ oncancel,
+ timeline
+ } = param;
+
+ this.targets.forEach((target: HTMLElement, i) => {
+ let { speed, keyframes, tempDurations, ...computedOptions } = arrOfComputedOptions[i];
+
+ // You cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will
+ // replace the padded endDelay
+
+ // 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, some animations
+ // that are finished will restart, while the rest will continue playing.
+ // This is mostly for progress control, but depending on your usage may truly benefit you
+ if (padEndDelay && computedOptions.endDelay == 0 &&
+ Math.abs(computedOptions.iterations) != Math.abs(Infinity)) {
+ computedOptions.endDelay = this.totalDuration - tempDurations;
+ }
+
+ let computedKeyframes: Keyframe[] | PropertyIndexedKeyframes;
+ let animationKeyframe: TypeKeyFrameOptionsType;
+
+ // Accept keyframes as a keyframes Object, or a method,
+ // if there are no animations in the keyframes array,
+ // uses css properties from the options object
+ let arrKeyframes = keyframes as (Keyframe[] | TypeCSSLikeKeyframe);
+ if (typeof arrKeyframes == "object") arrKeyframes = KeyframeParse(arrKeyframes);
+
+ // If `computedKeyframes` have been previously computed for this target element replace
+ // the old uncomputed CSS properties with it, otherwise, use the uncomputed property
+ let oldComputedKeyframe = this.computedKeyframes.get(target) ?? {};
+ let fullProperties = Object.assign({}, oldCSSProperties, oldComputedKeyframe);
+
+ // Replace old CSS properties with new CSS properties if there is a new value for the CSS property
+ // As in the new CSS property is not null or null
+ let properties = mapObject(fullProperties, (value, key) => (this.properties[key] ?? value));
+
+ // Prefer arrays of keyframes over pure CSS Properties
+ animationKeyframe = isValid(arrKeyframes) ? arrKeyframes : properties as PropertyIndexedKeyframes;
+
+ if (!Array.isArray(animationKeyframe)) {
+ // Remove `keyframes` animation option, it's not a valid CSS property
+ let remaining: IAnimationOptions = omit(["keyframes"], animationKeyframe);
+ let { offset, ...CSSProperties } = mapAnimationOptions(remaining, [i, len, target], this);
+
+ // transform, is often used so, to make them easier to use we parse them for strings, number, and/or arrays of both;
+ // for transform we parse the translate, skew, scale, and perspective functions (including all their varients) as CSS properties;
+ // it then turns these properties into valid `PropertyIndexedKeyframes`
+ // Read the documentation for `ParseTransformableCSSProperties`
+ CSSProperties = ParseTransformableCSSProperties(CSSProperties as ICSSComputedTransformableProperties);
+
+ let _offset = offset as (string | number)[];
+ computedKeyframes = Object.assign({},
+ CSSProperties,
+ isValid(_offset) ? { offset: _offset.map(parseOffset) } : null
+ ) as PropertyIndexedKeyframes;
+ } else {
+ computedKeyframes = animationKeyframe.map((keyframe: Keyframe) => {
+ // Remove `speed` & `loop`, they are not valid CSS properties
+ let { easing, offset, ...remaining } = omit(["speed", "loop"], keyframe);
+
+ return Object.assign({},
+ remaining,
+ typeof easing == "string" ? { easing: GetEase(easing) } : null,
+ typeof offset == "string" || typeof offset == "number"
+ ? { offset: parseOffset(offset) } : null
+ );
+ });
+
+ // Transform transformable CSS properties in each keyframe of the keyframe array
+ computedKeyframes = ParseTransformableCSSKeyframes(computedKeyframes) as Keyframe[];
+ }
+
+ let animation: Animation, keyFrameEffect: KeyframeEffect;
+ if (this.keyframeEffects.has(target)) {
+ // Update the animation, if the target already is already being animated
+ keyFrameEffect = this.keyframeEffects.get(target);
+ animation = this.animations.get(keyFrameEffect);
+
+ keyFrameEffect?.setKeyframes?.(computedKeyframes);
+ keyFrameEffect?.updateTiming?.(computedOptions as KeyframeAnimationOptions);
+ } else {
+ // Create animation and add it to the Animations Set
+ keyFrameEffect = new KeyframeEffect(target, computedKeyframes, computedOptions as KeyframeAnimationOptions);
+ animation = new Animation(keyFrameEffect, timeline);
+
+ this.keyframeEffects.set(target, keyFrameEffect);
+ this.animations.set(keyFrameEffect, animation);
+ }
+
+ animation.playbackRate = speed;
+
+ // Support for on finish
+ animation.onfinish = () => {
+ typeof onfinish == "function" && onfinish.call(this, target, i, len, animation);
+ };
+
+ // // Support for on cancel
+ animation.oncancel = () => {
+ typeof oncancel == "function" && oncancel.call(this, target, i, len, animation);
+ };
+
+ // Set the calculated options & keyframes for each individual animation
+ this.computedOptions.set(target, computedOptions);
+ this.computedKeyframes.set(target, computedKeyframes);
+ });
+ }
+
+ /**
+ * Update the options for all targets
+ *
+ * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `updateOptions` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_
+ *
+ * @beta
+ */
+ public updateOptions(options: IAnimationOptions = {}) {
+ try {
+ let optionsFromParam = parseOptions(options);
+ this.options = Object.assign({}, DefaultAnimationOptions, this.options, optionsFromParam);
+
+ // This removes all none CSS properties from `properties`
+ let {
+ // These values cannot be functions
+ padEndDelay,
+ autoplay,
+ target,
+ targets,
+ timeline,
+
+ onfinish,
+ oncancel,
+
+ /**
+ * Theses are the CSS properties to be animated as Keyframes
+ */
+ ...oldCSSProperties
+ } = omit(FUNCTION_SUPPORTED_TIMING_KEYS, this.options);
+
+ // This removes all none CSS properties from `optionsFromParam`
+ this.properties = omit(ALL_TIMING_KEYS, optionsFromParam);
+
+ // Avoid duplicate elements
+ let oldTargets = this.targets.values();
+ let targetSet = [...new Set([...oldTargets, ...getTargets(targets), ...getTargets(target)])];
+ this.targets.clear();
+ targetSet.forEach((value, i) => {
+ this.targets.set(i, value);
+ this.targetIndexes.set(value, i);
+ });
+
+ let len = this.targets.size;
+ let arrOfComputedOptions = this.createArrayOfComputedOptions(optionsFromParam, len);
+ this.createAnimations({
+ arrOfComputedOptions,
+ padEndDelay,
+ oldCSSProperties,
+ onfinish,
+ oncancel,
+ timeline
+ }, len);
+
+ // If the total number of targets is zero or less, it means there not values in `arrOfComputedOptions`
+ // So, set the values for `totalDuration`, `minDelay`, and `maxSpeed` to the options directly
+ // This is for anyone who wants to build a `timeline` in the future
+ if (len <= 0) {
+ if (this.maxSpeed == Infinity) this.maxSpeed = Number(this.options.speed);
+ if (this.minDelay == Infinity)
+ this.minDelay = Number(this.options.delay) + Number(this.options.timelineOffset);
+ if (this.totalDuration == -Infinity) this.totalDuration = Number(this.options.duration);
+ }
+
+ if (!this.mainAnimation) {
+ this.mainkeyframeEffect = new KeyframeEffect(this.mainElement, null, {
+ duration: this.totalDuration
+ });
+
+ this.mainAnimation = new Animation(this.mainkeyframeEffect, timeline);
+ } else {
+ this.mainkeyframeEffect?.updateTiming?.({
+ duration: this.totalDuration
+ });
+
+ if (!this.mainkeyframeEffect.setKeyframes || !this.mainkeyframeEffect.updateTiming)
+ console.warn("@okikio/animate - `KeyframeEffect.setKeyframes` and/or `KeyframeEffect.updateTiming` are not supported in this browser.");
+ }
+
+ this.mainAnimation.playbackRate = this.maxSpeed;
+ this.mainAnimation.onfinish = () => {
+ if (this.mainAnimation) {
+ let playstate = this.getPlayState();
+ if (!this.is(playstate))
+ this.emit("playstate-change", playstate, this);
+
+ // Ensure the progress reaches 100%
+ this.loop();
+ this.stopLoop();
+ }
+
+ this.emit("finish", this);
+ };
+
+ this.mainAnimation.oncancel = () => {
+ if (this.mainAnimation) {
+ let playstate = this.getPlayState();
+ if (!this.is(playstate))
+ this.emit("playstate-change", playstate, this);
+
+ // Ensure the progress is accurate
+ this.loop();
+ this.stopLoop();
+ }
+
+ this.emit("cancel", this);
+ };
+
+ if (autoplay) {
+ // 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, this defers the emitting for a 0ms time allowing the rest of the js to run, the `begin` event to be registered thus
+ // the `begin` event can be emitter
+ let timer: number | void = window.setTimeout(() => {
+ this.emit("begin", this);
+ timer = window.clearTimeout(timer as number);
+ }, 0);
+
+ this.play();
+ } else this.pause();
+ } catch (err) {
+ this.emit("error", err);
+ }
+ }
+
+ /**
+ * Adds a target to the Animate instance, and update the animation options with the change
+ *
+ * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `add` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_
+ *
+ * @beta
+ */
+ public add(target: HTMLElement) {
+ let progress = this.getProgress();
+ let running = this.is("running");
+ let paused = this.is("paused");
+
+ this.updateOptions({ target });
+ this.setProgress(progress);
+
+ if (running) this.play();
+ else if (paused) this.pause();
+ }
+
+ /**
+ * Removes a target from an Animate instance
+ *
+ * _**Note**: it doesn't update the current running options, you need to use the `Animate.prototype.remove(...)` method if you want to also update the running options_
+ */
+ public removeTarget(target: HTMLElement) {
+ let keyframeEffect = this.keyframeEffects.get(target);
+ this.animations.delete(keyframeEffect);
+ keyframeEffect = null;
+
+ this.computedKeyframes.delete(target);
+ this.computedOptions.delete(target);
+ this.keyframeEffects.delete(target);
+
+ let index = this.targetIndexes.get(target);
+ this.targets.delete(index);
+ this.targetIndexes.delete(target);
+ }
+
+ /**
+ * Removes a target from an Animate instance, and update the animation options with the change
+ *
+ * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `remove` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_
+ *
+ * @beta
+ */
+ public remove(target: HTMLElement) {
+ this.removeTarget(target);
+
+ let targetSet = new Set([].concat(this.targets.values()));
+
+ this.options.target = [...targetSet];
+ this.options.targets = [];
+ targetSet.clear();
+ targetSet = null;
+
+ let progress = this.getProgress();
+ let running = this.is("running");
+ let paused = this.is("paused");
+
+ this.updateOptions();
+
+ if (running) this.play();
+ else if (paused) this.pause();
+
+ this.setProgress(progress);
+ }
+
+ /**
+ * Adds a listener for a given event
+ */
+ public on(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate {
+ this.emitter?.on?.(events, callback, scope ?? this);
+
+ // Because the Web Animation API doesn't require requestAnimationFrame for animations,
+ // we only run the requestAnimationFrame when there is a "update" event listener
+ if (this.emitter.getEvent("update").length > 0) {
+ Animate.RUNNING.add(this);
+ if (Animate.animationFrame == null) Animate.requestFrame();
+ }
+ return this;
+ }
+
+ /**
+ * Removes a listener from an event
+ */
+ public off(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate {
+ this.emitter?.off?.(events, callback, scope ?? this);
+ return this;
+ }
+
+ /**
+ * Call all listeners within an event
+ */
+ public emit(events: TypeAnimationEvents[] | TypeAnimationEvents | string | any[], ...args: any): Animate {
+ this.emitter?.emit?.(events, ...args);
+ return this;
+ }
+
+ /** Returns the Animate options, as JSON */
+ public toJSON(): IAnimationOptions {
+ return this.options;
+ }
+
+ /**
+ * The Symbol.toStringTag well-known symbol is a string valued property that is used
+ * in the creation of the default string description of an object.
+ * It is accessed internally by the Object.prototype.toString() method.
+ */
+ get [Symbol.toStringTag]() {
+ return `Animate`;
+ }
+}
+
+/**
+ * Creates a new Animate instance
+ *
+ * @remark
+ * `@okikio/animate` create animations by creating instances of `Animate`, a class that acts as a wrapper around the Web Animation API. To create new instances of the `Animate` class, you can either import the `Animate` class and do this, `new Animate({ ... })` or import the `animate` (lowercase) method and do this, `animate({ ... })`. The `animate` method creates new instances of the `Animate` class and passes the options it recieves as arguments to the `Animate` class.
+ *
+ * The `Animate` class recieves a set of targets to animate, it then creates a list of Web Animation API `Animation` instances, along side a main animation, which is small `Animation` instance that is set to animate the opacity of a non visible element, the `Animate` class then plays each `Animation` instances keyframes including the main animation.
+
+ * 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`.
+
+ * @example
+ * ```ts
+ * import animate from "@okikio/animate";
+ *
+ * // Do note, on the web you need to do this, if you installed it via the script tag:
+ * // const { animate } = window.animate;
+ *
+ * (async () => {
+ * let [options] = await animate({
+ * target: ".div",
+ * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation
+ * // keyframes: [
+ * // { transform: "translateX(0px)" },
+ * // { transform: "translateX(300px)" }
+ * // ],
+ * transform: ["translateX(0px)", "translateX(300px)"],
+ * easing: "out",
+ * duration(i) {
+ * return (i + 1) * 500;
+ * },
+ * loop: 1,
+ * speed: 2,
+ * fillMode: "both",
+ * direction: "normal",
+ * autoplay: true,
+ * delay(i) {
+ * return (i + 1) * 100;
+ * },
+ * endDelay(i) {
+ * return (i + 1) * 100;
+ * },
+ * });
+ *
+ * animate({
+ * options,
+ * transform: ["translateX(300px)", "translateX(0px)"],
+ * });
+ * })();
+ *
+ * // or you can use the .then() method
+ * animate({
+ * target: ".div",
+ * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation
+ * // keyframes: [
+ * // { transform: "translateX(0px)" },
+ * // { transform: "translateX(300px)" }
+ * // ],
+ * transform: ["translateX(0px)", "translateX(300px)"],
+ * easing: "out",
+ * duration(i) {
+ * return (i + 1) * 500;
+ * },
+ * loop: 1,
+ * speed: 2,
+ * fillMode: "both",
+ * direction: "normal",
+ * delay(i) {
+ * return (i + 1) * 100;
+ * },
+ * autoplay: true,
+ * endDelay(i) {
+ * return (i + 1) * 100;
+ * }
+ * }).then((options) => {
+ * animate({
+ * options,
+ * transform: ["translateX(300px)", "translateX(0px)"]
+ * });
+ * });
+ * ```
+ *
+ * [Preview this example →](https://codepen.io/okikio/pen/mdPwNbJ?editors=0010)
+ *
+ * @packageDocumentation
+ */
+export const animate = (options: IAnimationOptions = {}): Animate => {
+ return new Animate(options);
+};
+
+export default animate;
\ No newline at end of file
diff --git a/packages/animate/src/api.ts b/packages/animate/src/api.ts
index b4a7145..4ebe5ad 100644
--- a/packages/animate/src/api.ts
+++ b/packages/animate/src/api.ts
@@ -1,1176 +1,6 @@
-import { EventEmitter, TypeEventInput, TypeListenerCallback } from "@okikio/emitter";
-import { Manager } from "@okikio/manager";
-
-import { TypeAnimationTarget, TypeAnimationOptionTypes, TypeCallbackArgs, TypeComputedAnimationOptions, IAnimationOptions, TypeComputedOptions, TypeKeyFrameOptionsType, TypeCSSLikeKeyframe, ICSSComputedTransformableProperties, TypeAnimationEvents, TypePlayStates } from "./types";
-import { KeyframeParse, parseOffset } from "./builtin-effects";
-import { isValid, ParseTransformableCSSProperties, ParseTransformableCSSKeyframes } from "./css-properties";
-
export * from "./types";
export * from "./builtin-effects";
export * from "./css-properties";
-
-/* DOM */
-export const getElements = (selector: string | Node): Node[] => {
- return typeof selector === "string" ? Array.from(document.querySelectorAll(selector as string)) : [selector];
-};
-
-export const flatten = (arr: TypeAnimationTarget[]) => [].concat(...arr);
-export const getTargets = (targets: TypeAnimationTarget): Node[] => {
- if (Array.isArray(targets)) {
- return flatten((targets as TypeAnimationTarget[]).map(getTargets));
- }
- if (typeof targets == "string" || targets instanceof Node)
- return getElements(targets);
- if (targets instanceof NodeList || targets instanceof HTMLCollection)
- return Array.from(targets);
- return [];
-};
-
-/* VALUES */
-export const computeOption = (value: TypeAnimationOptionTypes, args: TypeCallbackArgs, context: Animate): TypeComputedAnimationOptions => {
- if (typeof value === "function") {
- return value.apply(context, args);
- } else return value;
-};
-
-/**
- * Acts like array.map(...) but for functions
- */
-export const mapObject = (obj: object, fn: (value, key, obj) => any) => {
- let keys = Object.keys(obj);
- let key, value, result = {};
- for (let i = 0, len = keys.length; i < len; i++) {
- key = keys[i];
- value = obj[key];
- result[key] = fn(value, key, obj);
- }
-
- return result;
-};
-
-export const mapAnimationOptions = (options: IAnimationOptions, args: TypeCallbackArgs, animate: Animate): TypeComputedOptions => {
- return mapObject(options, (value) => computeOption(value, args, animate));
-};
-
-/**
- * From: [https://easings.net]
- *
- * Read More about easings on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing)
- *
- * ```ts
- * {
- * "in": "ease-in",
- * "out": "ease-out",
- * "in-out": "ease-in-out",
- *
- * // Sine
- * "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)",
- * "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)",
- * "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)",
- *
- * // Quad
- * "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)",
- * "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
- * "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)",
- *
- * // Cubic
- * "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)",
- * "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)",
- * "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)",
- *
- * // Quart
- * "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)",
- * "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)",
- * "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)",
- *
- * // Quint
- * "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)",
- * "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)",
- * "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)",
- *
- * // Expo
- * "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)",
- * "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)",
- * "in-out-expo": "cubic-bezier(1, 0, 0, 1)",
- *
- * // Circ
- * "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)",
- * "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)",
- * "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)",
- *
- * // Back
- * "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)",
- * "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)",
- * "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)"
- * }
- * ```
- */
-export const EASINGS = {
- "in": "ease-in",
- "out": "ease-out",
- "in-out": "ease-in-out",
-
- // Sine
- "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)",
- "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)",
- "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)",
-
- // Quad
- "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)",
- "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
- "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)",
-
- // Cubic
- "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)",
- "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)",
- "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)",
-
- // Quart
- "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)",
- "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)",
- "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)",
-
- // Quint
- "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)",
- "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)",
- "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)",
-
- // Expo
- "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)",
- "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)",
- "in-out-expo": "cubic-bezier(1, 0, 0, 1)",
-
- // Circ
- "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)",
- "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)",
- "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)",
-
- // Back
- "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)",
- "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)",
- "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)"
-};
-
-/**
- * The keys of {@link EASINGS}
- *
- * @remark
- * "in", "out", "in-out", "in-sine", "out-sine", "in-out-sine", "in-quad", "out-quad", "in-out-quad", "in-cubic", "out-cubic", "in-out-cubic", "in-quart", "out-quart", "in-out-quart", "in-quint", "out-quint", "in-out-quint", "in-expo", "out-expo", "in-out-expo", "in-circ", "out-circ", "in-out-circ", "in-back", "out-back", "in-out-back"
- */
-export const EasingKeys = Object.keys(EASINGS);
-
-/**
- * Converts users input into a usable easing function
- *
- * @param ease - easing functions; {@link EasingKeys}, cubic-bezier, steps, linear, etc...
- * @returns an easing function that `KeyframeEffect` can accept
- */
-export const GetEase = (ease: keyof typeof EASINGS | string): string => {
- let search = ease.replace(/^ease-/, ""); // Remove the "ease-" keyword
- return EasingKeys.includes(search) ? EASINGS[search] : ease;
-};
-/**
- * The default options for every Animate instance
- *
- * ```ts
- * {
- * keyframes: [],
- *
- * loop: 1,
- * delay: 0,
- * speed: 1,
- * endDelay: 0,
- * easing: "ease",
- * autoplay: true,
- * duration: 1000,
- * fillMode: "none",
- * direction: "normal",
- * padEndDelay: false,
- * timeline: document.timeline,
- * extend: {}
- * }
- * ```
- */
-export const DefaultAnimationOptions: IAnimationOptions = {
- keyframes: [],
- offset: [],
-
- loop: 1,
- delay: 0,
- speed: 1,
- endDelay: 0,
- easing: "ease",
- timelineOffset: 0,
- autoplay: true,
- duration: 1000,
- fillMode: "none",
- direction: "normal",
- padEndDelay: false,
- timeline: document.timeline,
- extend: {}
-};
-
-
-export const parseOptions = (options: IAnimationOptions): IAnimationOptions => {
- let { options: animation, ...rest } = options;
- let oldOptions = animation instanceof Animate ? animation.options : (Array.isArray(animation) ? animation?.[0]?.options : animation);
- return Object.assign({}, oldOptions, rest);
-}
-
-/**
- * Return a copy of the object without the keys specified in the keys argument
- *
- * @param keys - arrays of keys to remove from the object
- * @param obj - the object in question
- * @returns
- * a copy of the object without certain key
- */
-export const omit = (keys: string[], obj: { [key: string]: any }) => {
- let rest = { ...obj };
- while (keys.length) {
- let { [keys.pop()]: omitted, ...remaining } = rest;
- rest = remaining;
- }
- return rest;
-}
-
-/**
- * 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.
- *
- * You can check it out here:
- */
-export class Animate {
- /**
- * Stores the options for the current animation
- *
- * @inheritDoc DefaultAnimationOptions
- */
- public options: IAnimationOptions = {};
-
- /**
- * The properties to animate
- */
- public properties: object = {};
-
- /**
- * The total duration of all Animation's
- */
- public totalDuration: number = -Infinity;
-
- /**
- * The smallest delay out of all Animation's
- */
- public minDelay: number = Infinity;
-
- /**
- * The smallest speed out of all Animation's
- */
- public maxSpeed: number = Infinity;
-
- /**
- * The Element the mainAnimation runs on
- */
- public mainElement: HTMLElement;
-
- /**
- * Stores an animation that runs on the total duration of all the `Animation` instances, and as such it's the main Animation.
- */
- public mainAnimation: Animation;
-
- /**
- * The Keyframe Effect for the mainAnimation
- */
- public mainkeyframeEffect: KeyframeEffect;
-
- /**
- * Stores request frame calls
- */
- public animationFrame: number;
-
- /**
- * An event emitter
- */
- public emitter: EventEmitter = new EventEmitter();
-
- /**
- * Returns a promise that is fulfilled when the mainAnimation is finished
- */
- public promise: Promise;
-
- /**
- * The list of Elements to Animate
- */
- public targets: Manager = new Manager();
-
- /**
- * The indexs of target Elements in Animate
- */
- public targetIndexes: WeakMap = new WeakMap();
-
- /**
- * A WeakMap of KeyFrameEffects
- */
- public keyframeEffects: WeakMap = new WeakMap();
-
- /**
- * The options for individual animations
- *
- * A WeakMap 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.*_
- *
- * _**Note**: keyframes are not included, both the array form and the object form; the options, speed, extend, padEndDelay, and autoplay animation options are not included_
- */
- public computedOptions: WeakMap = new WeakMap();
-
- /**
- * A WeakMap of Animations
- */
- public animations: WeakMap = new WeakMap();
-
- /**
- * The keyframes for individual animations
- *
- * A WeakMap that stores all the fully calculated keyframes for individual Animation instances.
- *
- * _**Note**: the computedKeyframes 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. translateX, skew, etc..., they've all been turned into the transform property.*_
- */
- public computedKeyframes: WeakMap = new WeakMap();
- constructor(options: IAnimationOptions) {
- this.loop = this.loop.bind(this);
- this.onVisibilityChange = this.onVisibilityChange.bind(this);
- this.on("error", console.error);
- this.updateOptions(options);
-
- if (this.mainAnimation) {
- this.visibilityPlayState = this.getPlayState();
- if (Animate.pauseOnPageHidden) {
- document.addEventListener('visibilitychange', this.onVisibilityChange, false);
- }
- }
-
- this.newPromise();
- }
-
- /**
- * Tells all animate instances to pause when the page is hidden
- *
- * @static
- * @type {Boolean}
- * @memberof Animate
- */
- static pauseOnPageHidden: Boolean = true;
-
- /**
- * Store the last remebered playstate before page was hidden
- *
- * @protected
- * @type {TypePlayStates}
- * @memberof Animate
- */
- protected visibilityPlayState: TypePlayStates;
-
- /**
- * document `visibilitychange` event handler
- */
- protected onVisibilityChange() {
- if (document.hidden) {
- this.visibilityPlayState = this.getPlayState();
- if (this.is("running")) {
- this.loop();
- this.pause();
- }
- } else {
- if (this.visibilityPlayState == "running" && this.is("paused"))
- this.play();
- }
- }
-
- /**
- * Returns a new Promise that is resolved when the animation finishes
- */
- public newPromise(): Promise {
- this.promise = new Promise((resolve, reject) => {
- /*
- Note that the `this` keyword is in an Array when it is resolved,
- this is due to Promises not wanting to resolve references,
- so, you can't resolve `this` directly, so, I chose to resolve `this` in an
- Array
-
- Note: the `resolve` method by default will only run once so to avoid
- */
- this?.emitter?.once?.("finish", () => resolve([this]));
- this?.emitter?.once?.("error", err => reject(err));
- });
-
- return this.promise;
- }
-
- /**
- * Fulfills the `this.promise` Promise
- */
- public then(
- onFulfilled?: (value?: any) => any,
- onRejected?: (reason?: any) => any
- ): Animate {
- onFulfilled = onFulfilled?.bind(this);
- onRejected = onRejected?.bind(this);
- this?.promise?.then?.(onFulfilled, onRejected);
- return this;
- }
-
- /**
- * Catches error that occur in the `this.promise` Promise
- */
- public catch(onRejected: (reason?: any) => any): Animate {
- onRejected = onRejected?.bind(this);
- this.promise?.catch?.(onRejected);
- return this;
- }
-
- /**
- * If you don't care if the `this.promise` Promise has either been rejected or resolved
- */
- public finally(onFinally: () => any): Animate {
- onFinally = onFinally?.bind(this);
- this.promise?.finally?.(onFinally);
- return this;
- }
-
- /**
- * Represents an Animation Frame Loop
- */
- public loop(): void {
- this.stopLoop();
- this.animationFrame = window.requestAnimationFrame(this.loop);
- this.emit("update", this.getProgress(), this);
- }
-
- /**
- * Cancels animation frame
- */
- public stopLoop() {
- window.cancelAnimationFrame(this.animationFrame);
- }
-
- /**
- * Calls a method that affects all animations **excluding** the mainAnimation; the method only allows the animation parameter
- */
- public allAnimations(method: (animation?: Animation, target?: HTMLElement) => void) {
- this.targets.forEach((target: HTMLElement) => {
- let keyframeEffect = this.keyframeEffects.get(target);
- let animation = this.animations.get(keyframeEffect);
- return method(animation, target);
- });
- return this;
- }
-
- /**
- * Calls a method that affects all animations **including** the mainAnimation; the method only allows the animation parameter
- */
- public all(method: (animation?: Animation, target?: HTMLElement) => void) {
- this.mainAnimation && method(this.mainAnimation, this.mainElement);
- this.allAnimations(method);
- return this;
- }
-
- /**
- * Register the begin event
- */
- protected beginEvent() {
- if (this.getProgress() == 0)
- this.emit("begin", this);
- }
-
- /**
- * Play Animation
- */
- public play(): Animate {
- let playstate = this.getPlayState();
- this.beginEvent();
- this.all(anim => anim.play());
- this.emit("play", playstate, this);
- if (!this.is(playstate))
- this.emit("playstate-change", playstate, this);
- this.loop();
- return this;
- }
-
- /**
- * Pause Animation
- */
- public pause(): Animate {
- let playstate = this.getPlayState();
- this.all(anim => anim.pause());
- this.emit("pause", playstate, this);
- if (!this.is(playstate))
- this.emit("playstate-change", playstate, this);
- this.stopLoop();
- return this;
- }
-
- /**
- * Reverse Animation
- */
- public reverse() {
- this.all(anim => anim.reverse());
- return this;
- }
-
- /**
- * Reset all Animations
- */
- public reset() {
- this.setProgress(0);
-
- if (this.options.autoplay) this.play();
- else this.pause();
- return this;
- }
-
- /**
- * Cancels all Animations
- */
- public cancel() {
- this.all(anim => anim.cancel());
- return this;
- }
-
- /**
- * Force complete all Animations
- */
- public finish() {
- this.all(anim => anim.finish());
- return this;
- }
-
- /**
- * Cancels & Clears all Animations
- */
- public stop() {
- this.cancel();
- this.stopLoop();
- document.removeEventListener('visibilitychange', this.onVisibilityChange, false);
-
- this.targets.forEach((target: HTMLElement) => this.removeTarget(target));
-
- this.emit("stop");
- this.emitter.clear();
-
- this.mainkeyframeEffect = null;
- this.mainAnimation = null;
- this.mainElement = null;
-
- this.promise = null;
- this.computedOptions = null;
- this.animations = null;
- this.keyframeEffects = null;
- this.emitter = null;
- this.targets = null;
- this.options = null;
- this.properties = null;
- }
-
- /**
- * Get a specific Animation from an Animate instance
- */
- public getAnimation(target: HTMLElement) {
- let keyframeEffect = this.keyframeEffects.get(target);
- return this.animations.get(keyframeEffect);
- }
-
- /**
- * Returns the timings of an Animation, given a target
- * E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... }
- */
- public getTiming(target: HTMLElement): TypeComputedAnimationOptions {
- let keyframeOptions = this.computedOptions.get(target) ?? {};
- let timings = this.keyframeEffects.get(target).getTiming?.() ?? {};
-
- return { ...keyframeOptions, ...timings };
- }
-
- /**
- * Returns the current time of the Main Animation
- */
- public getCurrentTime(): number {
- return this.mainAnimation.currentTime;
- }
-
- /**
- * Returns the Animation progress as a fraction of the current time / duration * 100
- */
- public getProgress() {
- return (this.getCurrentTime() / this.totalDuration) * 100;
- }
-
- /**
- * Return the playback speed of the animation
- */
- public getSpeed(): number {
- return this.mainAnimation.playbackRate;
- }
-
- /**
- * Returns the current playing state
- */
- public getPlayState(): TypePlayStates {
- return this.mainAnimation.playState;
- }
-
- /**
- * Returns a boolean determining if the `animate` instances playstate is equal to the `playstate` parameter.
- */
- public is(playstate: TypePlayStates) {
- return this.getPlayState() == playstate;
- }
-
- /**
- * Set the current time of the Main Animation
- */
- public setCurrentTime(time: number): Animate {
- this.all(anim => (anim.currentTime = time));
- this.emit("update", this.getProgress());
- return this;
- }
-
- /**
- * Set the Animation progress as a value from 0 to 100
- */
- public setProgress(percent: number): Animate {
- let time = (percent / 100) * this.totalDuration;
- this.setCurrentTime(time);
- return this;
- }
-
- /**
- * Set the playback speed of an Animation
- */
- public setSpeed(speed: number = 1): Animate {
- this.maxSpeed = speed;
- this.all(anim => {
- if (anim.updatePlaybackRate)
- anim.updatePlaybackRate(speed);
- else anim.playbackRate = speed;
- });
- return this;
- }
-
- /**
- * Returns an array of computed options
- */
- protected createArrayOfComputedOptions(optionsFromParam: IAnimationOptions, len: number) {
- let result: TypeComputedAnimationOptions = [];
- this.targets.forEach((target: HTMLElement, i) => {
- // Basically if there is already a computedOption for the target element use it, but don't ovveride any new options
- let oldComputedOptions: IAnimationOptions = this.computedOptions.get(target) ?? {};
- let getOption = (key: string) => {
- let computedKey = key;
- if (key == "loop") computedKey = "iterations";
- if (key == "fillMode") computedKey = "fill";
- return optionsFromParam[key] ?? oldComputedOptions[computedKey] ?? this.options[key];
- };
-
- let animationOptions = Object.assign({
- easing: getOption("easing"),
- iterations: getOption("loop"),
- direction: getOption("direction"),
- endDelay: getOption("endDelay"),
- duration: getOption("duration"),
- speed: getOption("speed"),
- delay: getOption("delay"),
- timelineOffset: getOption("timelineOffset"),
- keyframes: getOption("keyframes"),
- }, getOption("extend") ?? {});
-
- // let oldComputedOptions = this.computedOptions.get(target)
- // Allows the use of functions as the values, for both the keyframes and the animation object
- // It adds the capability of advanced stagger animation, similar to the animejs stagger functions
- let computedOptions = mapAnimationOptions(animationOptions as IAnimationOptions, [i, len, target], this);
-
- if (typeof computedOptions.easing == "string")
- computedOptions.easing = GetEase(computedOptions.easing);
-
- if (computedOptions.iterations === true)
- computedOptions.iterations = Infinity;
-
- computedOptions.fill = getOption("fillMode");
-
- // Add timelineOffset to delay, this is future proofing;
- // if you want to create a custom timeline similar to animejs this will help you
- // I don't intend to make a timeline function for this project
- let {
- timelineOffset,
- speed,
- endDelay,
- delay,
- duration,
- iterations,
- ...remainingComputedOptions
- } = computedOptions;
-
- iterations = Number(iterations);
- duration = Number(duration);
- endDelay = Number(endDelay);
- speed = Number(speed);
- delay = Number(delay) + Number(timelineOffset);
-
- let tempDurations = delay + (duration * iterations) + endDelay;
-
- // Set the totalDuration to be the Animation with the largest totalDuration
- if (this.totalDuration < tempDurations)
- this.totalDuration = tempDurations;
-
- result[i] = {
- ...remainingComputedOptions,
- speed,
- tempDurations,
- endDelay,
- delay,
- duration,
- iterations,
- };
-
- if (this.minDelay > delay) this.minDelay = delay;
- if (this.maxSpeed > speed) this.maxSpeed = speed;
- });
- return result;
- }
-
- /**
- * Creates animations out of an array of computed options
- */
- protected createAnimations(param: { arrOfComputedOptions: any; padEndDelay: any; oldCSSProperties: any; onfinish: any; oncancel: any; timeline?: any; }, len: number) {
- let {
- arrOfComputedOptions,
- padEndDelay,
- oldCSSProperties,
- onfinish,
- oncancel,
- timeline
- } = param;
-
- this.targets.forEach((target: HTMLElement, i) => {
- let { speed, keyframes, tempDurations, ...computedOptions } = arrOfComputedOptions[i];
-
- // You cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will
- // replace the padded endDelay
-
- // 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, some animations
- // that are finished will restart, while the rest will continue playing.
- // This is mostly for progress control, but depending on your usage may truly benefit you
- if (padEndDelay && computedOptions.endDelay == 0 &&
- Math.abs(computedOptions.iterations) != Math.abs(Infinity)) {
- computedOptions.endDelay = this.totalDuration - tempDurations;
- }
-
- let computedKeyframes: Keyframe[] | PropertyIndexedKeyframes;
- let animationKeyframe: TypeKeyFrameOptionsType;
-
- // Accept keyframes as a keyframes Object, or a method,
- // if there are no animations in the keyframes array,
- // uses css properties from the options object
- let arrKeyframes = keyframes as (Keyframe[] | TypeCSSLikeKeyframe);
- if (typeof arrKeyframes == "object") arrKeyframes = KeyframeParse(arrKeyframes);
-
- // If `computedKeyframes` have been previously computed for this target element replace
- // the old uncomputed CSS properties with it, otherwise, use the uncomputed property
- let oldComputedKeyframe = this.computedKeyframes.get(target) ?? {};
- let fullProperties = Object.assign({}, oldCSSProperties, oldComputedKeyframe);
-
- // Replace old CSS properties with new CSS properties if there is a new value for the CSS property
- // As in the new CSS property is not null or null
- let properties = mapObject(fullProperties, (value, key) => (this.properties[key] ?? value));
-
- // Prefer arrays of keyframes over pure CSS Properties
- animationKeyframe = isValid(arrKeyframes) ? arrKeyframes : properties as PropertyIndexedKeyframes;
-
- if (!Array.isArray(animationKeyframe)) {
- // Remove `keyframes` animation option, it's not a valid CSS property
- let remaining: IAnimationOptions = omit(["keyframes"], animationKeyframe);
- let { offset, ...CSSProperties } = mapAnimationOptions(remaining, [i, len, target], this);
-
- // transform, is often used so, to make them easier to use we parse them for strings, number, and/or arrays of both;
- // for transform we parse the translate, skew, scale, and perspective functions (including all their varients) as CSS properties;
- // it then turns these properties into valid `PropertyIndexedKeyframes`
- // Read the documentation for `ParseTransformableCSSProperties`
- CSSProperties = ParseTransformableCSSProperties(CSSProperties as ICSSComputedTransformableProperties);
-
- let _offset = offset as (string | number)[];
- computedKeyframes = Object.assign({},
- CSSProperties,
- isValid(_offset) ? { offset: _offset.map(parseOffset) } : null
- ) as PropertyIndexedKeyframes;
- } else {
- computedKeyframes = animationKeyframe.map((keyframe: Keyframe) => {
- // Remove `speed` & `loop`, they are not valid CSS properties
- let { easing, offset, ...remaining } = omit(["speed", "loop"], keyframe);
-
- return Object.assign({},
- remaining,
- typeof easing == "string" ? { easing: GetEase(easing) } : null,
- typeof offset == "string" || typeof offset == "number"
- ? { offset: parseOffset(offset) } : null
- );
- });
-
- // Transform transformable CSS properties in each keyframe of the keyframe array
- computedKeyframes = ParseTransformableCSSKeyframes(computedKeyframes) as Keyframe[];
- }
-
- let animation: Animation, keyFrameEffect: KeyframeEffect;
- if (this.keyframeEffects.has(target)) {
- // Update the animation, if the target already is already being animated
- keyFrameEffect = this.keyframeEffects.get(target);
- animation = this.animations.get(keyFrameEffect);
-
- keyFrameEffect?.setKeyframes?.(computedKeyframes);
- keyFrameEffect?.updateTiming?.(computedOptions as KeyframeAnimationOptions);
- } else {
- // Create animation and add it to the Animations Set
- keyFrameEffect = new KeyframeEffect(target, computedKeyframes, computedOptions as KeyframeAnimationOptions);
- animation = new Animation(keyFrameEffect, timeline);
-
- this.keyframeEffects.set(target, keyFrameEffect);
- this.animations.set(keyFrameEffect, animation);
- }
-
- animation.playbackRate = speed;
-
- // Support for on finish
- animation.onfinish = () => {
- typeof onfinish == "function" && onfinish.call(this, target, i, len, animation);
- };
-
- // // Support for on cancel
- animation.oncancel = () => {
- typeof oncancel == "function" && oncancel.call(this, target, i, len, animation);
- };
-
- // Set the calculated options & keyframes for each individual animation
- this.computedOptions.set(target, computedOptions);
- this.computedKeyframes.set(target, computedKeyframes);
- });
- }
-
- /**
- * Update the options for all targets
- *
- * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `updateOptions` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_
- *
- * @beta
- */
- public updateOptions(options: IAnimationOptions = {}) {
- try {
- let optionsFromParam = parseOptions(options);
- this.options = Object.assign({}, DefaultAnimationOptions, this.options, optionsFromParam);
-
- // This removes all none CSS properties from `properties`
- let sharedTimingKeys = ["easing", "loop", "endDelay", "duration", "speed", "delay", "timelineOffset", "direction", "extend", "fillMode", "offset"];
- let {
- // These values cannot be functions
- padEndDelay,
- autoplay,
- target,
- targets,
- timeline,
-
- onfinish,
- oncancel,
-
- /**
- * Theses are the CSS properties to be animated as Keyframes
- */
- ...oldCSSProperties
- } = omit(sharedTimingKeys, this.options);
-
- // This removes all none CSS properties from `optionsFromParam`
- this.properties = omit([...sharedTimingKeys, "keyframes", "padEndDelay", "onfinish", "oncancel", "autoplay", "target", "targets", "timeline"], optionsFromParam);
-
- // Avoid duplicate elements
- let oldTargets = this.targets.values();
- let targetSet = [...new Set([...oldTargets, ...getTargets(targets), ...getTargets(target)])];
- this.targets.clear();
- targetSet.forEach((value, i) => {
- this.targets.set(i, value);
- this.targetIndexes.set(value, i);
- });
-
- let len = this.targets.size;
- let arrOfComputedOptions = this.createArrayOfComputedOptions(optionsFromParam, len);
- this.createAnimations({
- arrOfComputedOptions,
- padEndDelay,
- oldCSSProperties,
- onfinish,
- oncancel,
- timeline
- }, len);
-
- // If the total number of targets is zero or less, it means there not values in `arrOfComputedOptions`
- // So, set the values for `totalDuration`, `minDelay`, and `maxSpeed` to the options directly
- // This is for anyone who wants to build a `timeline` in the future
- if (len <= 0) {
- if (this.maxSpeed == Infinity) this.maxSpeed = Number(this.options.speed);
- if (this.minDelay == Infinity)
- this.minDelay = Number(this.options.delay) + Number(this.options.timelineOffset);
- if (this.totalDuration == -Infinity) this.totalDuration = Number(this.options.duration);
- }
-
- if (!this.mainAnimation) {
- this.mainkeyframeEffect = new KeyframeEffect(this.mainElement, null, {
- duration: this.totalDuration
- });
-
- this.mainAnimation = new Animation(this.mainkeyframeEffect, timeline);
- } else {
- this.mainkeyframeEffect?.updateTiming?.({
- duration: this.totalDuration
- });
-
- if (!this.mainkeyframeEffect.setKeyframes || !this.mainkeyframeEffect.updateTiming)
- console.warn("@okikio/animate - `KeyframeEffect.setKeyframes` and/or `KeyframeEffect.updateTiming` are not supported in this browser.");
- }
-
- this.mainAnimation.playbackRate = this.maxSpeed;
- this.mainAnimation.onfinish = () => {
- if (this.mainAnimation) {
- let playstate = this.getPlayState();
- if (!this.is(playstate))
- this.emit("playstate-change", playstate, this);
-
- // Ensure the progress reaches 100%
- this.loop();
- this.stopLoop();
- }
-
- this.emit("finish", this);
- };
-
- this.mainAnimation.oncancel = () => {
- if (this.mainAnimation) {
- let playstate = this.getPlayState();
- if (!this.is(playstate))
- this.emit("playstate-change", playstate, this);
-
- // Ensure the progress is accurate
- this.loop();
- this.stopLoop();
- }
-
- this.emit("cancel", this);
- };
-
- if (autoplay) {
- // 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, this defers the emitting for a 0ms time allowing the rest of the js to run, the `begin` event to be registered thus
- // the `begin` event can be emitter
- let timer: number | void = window.setTimeout(() => {
- this.emit("begin", this);
- timer = window.clearTimeout(timer as number);
- }, 0);
-
- this.play();
- } else this.pause();
- } catch (err) {
- this.emit("error", err);
- }
- }
-
- /**
- * Adds a target to the Animate instance, and update the animation options with the change
- *
- * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `add` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_
- *
- * @beta
- */
- public add(target: HTMLElement) {
- let progress = this.getProgress();
- let running = this.is("running");
- let paused = this.is("paused");
-
- this.updateOptions({ target });
- this.setProgress(progress);
-
- if (running) this.play();
- else if (paused) this.pause();
- }
-
- /**
- * Removes a target from an Animate instance
- *
- * _**Note**: it doesn't update the current running options, you need to use the `Animate.prototype.remove(...)` method if you want to also update the running options_
- */
- public removeTarget(target: HTMLElement) {
- let keyframeEffect = this.keyframeEffects.get(target);
- this.animations.delete(keyframeEffect);
- keyframeEffect = null;
-
- this.computedKeyframes.delete(target);
- this.computedOptions.delete(target);
- this.keyframeEffects.delete(target);
-
- let index = this.targetIndexes.get(target);
- this.targets.delete(index);
- this.targetIndexes.delete(target);
- }
-
- /**
- * Removes a target from an Animate instance, and update the animation options with the change
- *
- * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `remove` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_
- *
- * @beta
- */
- public remove(target: HTMLElement) {
- this.removeTarget(target);
-
- let targetSet = new Set([].concat(this.targets.values()));
-
- this.options.target = [...targetSet];
- this.options.targets = [];
- targetSet.clear();
- targetSet = null;
-
- let progress = this.getProgress();
- let running = this.is("running");
- let paused = this.is("paused");
-
- this.updateOptions();
-
- if (running) this.play();
- else if (paused) this.pause();
-
- this.setProgress(progress);
- }
-
- /**
- * Adds a listener for a given event
- */
- public on(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate {
- this?.emitter?.on(events, callback, scope ?? this);
- return this;
- }
-
- /**
- * Removes a listener from an event
- */
- public off(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate {
- this?.emitter?.off(events, callback, scope ?? this);
- return this;
- }
-
- /**
- * Call all listeners within an event
- */
- public emit(events: TypeAnimationEvents[] | TypeAnimationEvents | string | any[], ...args: any): Animate {
- this?.emitter?.emit(events, ...args);
- return this;
- }
-
- /** Returns the Animate options, as JSON */
- public toJSON(): IAnimationOptions {
- return this.options;
- }
-
- /**
- * The Symbol.toStringTag well-known symbol is a string valued property that is used
- * in the creation of the default string description of an object.
- * It is accessed internally by the Object.prototype.toString() method.
- */
- get [Symbol.toStringTag]() {
- return `Animate`;
- }
-}
-
-/**
- * Creates a new Animate instance
- *
- * @remark
- * `@okikio/animate` create animations by creating instances of `Animate`, a class that acts as a wrapper around the Web Animation API. To create new instances of the `Animate` class, you can either import the `Animate` class and do this, `new Animate({ ... })` or import the `animate` (lowercase) method and do this, `animate({ ... })`. The `animate` method creates new instances of the `Animate` class and passes the options it recieves as arguments to the `Animate` class.
- *
- * The `Animate` class recieves a set of targets to animate, it then creates a list of Web Animation API `Animation` instances, along side a main animation, which is small `Animation` instance that is set to animate the opacity of a non visible element, the `Animate` class then plays each `Animation` instances keyframes including the main animation.
-
- * 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`.
-
- * @example
- * ```ts
- * import animate from "@okikio/animate";
- *
- * // Do note, on the web you need to do this, if you installed it via the script tag:
- * // const { animate } = window.animate;
- *
- * (async () => {
- * let [options] = await animate({
- * target: ".div",
- * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation
- * // keyframes: [
- * // { transform: "translateX(0px)" },
- * // { transform: "translateX(300px)" }
- * // ],
- * transform: ["translateX(0px)", "translateX(300px)"],
- * easing: "out",
- * duration(i) {
- * return (i + 1) * 500;
- * },
- * loop: 1,
- * speed: 2,
- * fillMode: "both",
- * direction: "normal",
- * autoplay: true,
- * delay(i) {
- * return (i + 1) * 100;
- * },
- * endDelay(i) {
- * return (i + 1) * 100;
- * },
- * });
- *
- * animate({
- * options,
- * transform: ["translateX(300px)", "translateX(0px)"],
- * });
- * })();
- *
- * // or you can use the .then() method
- * animate({
- * target: ".div",
- * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation
- * // keyframes: [
- * // { transform: "translateX(0px)" },
- * // { transform: "translateX(300px)" }
- * // ],
- * transform: ["translateX(0px)", "translateX(300px)"],
- * easing: "out",
- * duration(i) {
- * return (i + 1) * 500;
- * },
- * loop: 1,
- * speed: 2,
- * fillMode: "both",
- * direction: "normal",
- * delay(i) {
- * return (i + 1) * 100;
- * },
- * autoplay: true,
- * endDelay(i) {
- * return (i + 1) * 100;
- * }
- * }).then((options) => {
- * animate({
- * options,
- * transform: ["translateX(300px)", "translateX(0px)"]
- * });
- * });
- * ```
- *
- * [Preview this example →](https://codepen.io/okikio/pen/mdPwNbJ?editors=0010)
- *
- * @packageDocumentation
- */
-export const animate = (options: IAnimationOptions = {}): Animate => {
- return new Animate(options);
-};
-
-export default animate;
+export * from "./custom-easing";
+export * from "./animate";
+export * from "./empty-tween";
\ No newline at end of file
diff --git a/packages/animate/src/bezier-easing.ts b/packages/animate/src/bezier-easing.ts
new file mode 100644
index 0000000..c5124e2
--- /dev/null
+++ b/packages/animate/src/bezier-easing.ts
@@ -0,0 +1,93 @@
+/**
+ * https://github.com/gre/bezier-easing
+ * BezierEasing - use bezier curve for transition easing function
+ * by Gaëtan Renaudeau 2014 - 2015 – MIT License
+ */
+
+// These values are established by empiricism with tests (tradeoff: performance VS precision)
+export const NEWTON_ITERATIONS = 4;
+export const NEWTON_MIN_SLOPE = 0.001;
+export const SUBDIVISION_PRECISION = 0.0000001;
+export const SUBDIVISION_MAX_ITERATIONS = 10;
+
+export const kSplineTableSize = 11;
+export const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
+
+export const float32ArraySupported = typeof Float32Array === 'function';
+
+export const A = (aA1: number, aA2: number) => (1.0 - 3.0 * aA2 + 3.0 * aA1);
+export const B = (aA1: number, aA2: number) => (3.0 * aA2 - 6.0 * aA1);
+export const C = (aA1: number) => (3.0 * aA1);
+
+// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
+export const calcBezier = (aT: number, aA1: number, aA2: number) => ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
+
+// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
+export const getSlope = (aT: number, aA1: number, aA2: number) => 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
+export const binarySubdivide = (aX: number, aA: number, aB: number, mX1: number, mX2: number) => {
+ let currentX: number, currentT: number, i = 0;
+ do {
+ currentT = aA + (aB - aA) / 2.0;
+ currentX = calcBezier(currentT, mX1, mX2) - aX;
+ if (currentX > 0.0)
+ aB = currentT;
+ else aA = currentT;
+ } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
+ return currentT;
+}
+
+export const newtonRaphsonIterate = (aX: number, aGuessT: number, mX1: number, mX2: number) => {
+ for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
+ let currentSlope = getSlope(aGuessT, mX1, mX2);
+ if (currentSlope === 0.0) return aGuessT;
+
+ let currentX = calcBezier(aGuessT, mX1, mX2) - aX;
+ aGuessT -= currentX / currentSlope;
+ }
+
+ return aGuessT;
+}
+
+export const bezier = (mX1: number, mY1: number, mX2: number, mY2: number) => {
+ if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1))
+ throw new Error('bezier x values must be in [0, 1] range');
+
+ if (mX1 === mY1 && mX2 === mY2) return (t: number) => t;
+
+ // Precompute samples table
+ var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
+ for (var i = 0; i < kSplineTableSize; ++i) {
+ sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
+ }
+
+ const getTForX = (aX: number) => {
+ let intervalStart = 0.0;
+ let currentSample = 1;
+ let lastSample = kSplineTableSize - 1;
+
+ for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample)
+ intervalStart += kSampleStepSize;
+ --currentSample;
+
+ // Interpolate to provide an initial guess for t
+ let dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
+ let guessForT = intervalStart + dist * kSampleStepSize;
+
+ let initialSlope = getSlope(guessForT, mX1, mX2);
+ if (initialSlope >= NEWTON_MIN_SLOPE)
+ return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
+ else if (initialSlope === 0.0)
+ return guessForT;
+ else {
+ return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
+ }
+ }
+
+ return (t: number) => {
+ // Because JavaScript number are imprecise, we should guarantee the extremes are right.
+ if (t === 0 || t === 1) return t;
+ return calcBezier(getTForX(t), mY1, mY2);
+ };
+};
+
+export default bezier;
\ No newline at end of file
diff --git a/packages/animate/src/builtin-effects.ts b/packages/animate/src/builtin-effects.ts
index a884eea..5176481 100644
--- a/packages/animate/src/builtin-effects.ts
+++ b/packages/animate/src/builtin-effects.ts
@@ -68,9 +68,11 @@ export const KeyframeParse = (input: object): Keyframe[] => {
/**
* I don't really want to put in the effort to create a complete list, so instead just look through the `animate.css` github and copy and paste the effects you need, into using a CSS Keyframe style JSON object, make sure to read the documentation for {@link KeyframeParse}
*
+ * I suggest [@shoelace-style/animations](https://www.npmjs.com/package/@shoelace-style/animations) for all your animate.css needs.
+ *
* or
- *
- * if you just need some quick effects go to [github.com/wellyshen/use-web-animations/](https://github.com/wellyshen/use-web-animations/tree/master/src/animations) and copy the `keyframes` array for the effect you want, remember to say thank you to @wellyshen for all his hardwork, 😂
+ *
+ * if you just need some quick effects go to [github.com/wellyshen/use-web-animations/](https://github.com/wellyshen/use-web-animations/tree/master/src/animations) and copy the `keyframes` array for the effect you want, remember to say thank you to @wellyshen for all his hardwork, 😂.
*
* @internal
*/
diff --git a/packages/animate/src/color-rgba.ts b/packages/animate/src/color-rgba.ts
new file mode 100644
index 0000000..64de4fc
--- /dev/null
+++ b/packages/animate/src/color-rgba.ts
@@ -0,0 +1,250 @@
+/**
+ * Based on color-rgba https://github.com/colorjs/color-rgba
+ */
+import names from './colors';
+
+export const hsl = {
+ name: 'hsl',
+ min: [0,0,0],
+ max: [360,100,100],
+ channel: ['hue', 'saturation', 'lightness'],
+ alias: ['HSL'],
+
+ rgb: function(hsl) {
+ var h = hsl[0] / 360,
+ s = hsl[1] / 100,
+ l = hsl[2] / 100,
+ t1, t2, t3, rgb, val;
+
+ if (s === 0) {
+ val = l * 255;
+ return [val, val, val];
+ }
+
+ if (l < 0.5) {
+ t2 = l * (1 + s);
+ }
+ else {
+ t2 = l + s - l * s;
+ }
+ t1 = 2 * l - t2;
+
+ rgb = [0, 0, 0];
+ for (var i = 0; i < 3; i++) {
+ t3 = h + 1 / 3 * - (i - 1);
+ if (t3 < 0) {
+ t3++;
+ }
+ else if (t3 > 1) {
+ t3--;
+ }
+
+ if (6 * t3 < 1) {
+ val = t1 + (t2 - t1) * 6 * t3;
+ }
+ else if (2 * t3 < 1) {
+ val = t2;
+ }
+ else if (3 * t3 < 2) {
+ val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
+ }
+ else {
+ val = t1;
+ }
+
+ rgb[i] = val * 255;
+ }
+
+ return rgb;
+ }
+};
+
+
+ /**
+ * Base hues
+ * http://dev.w3.org/csswg/css-color/#typedef-named-hue
+ */
+ //FIXME: use external hue detector
+ var baseHues = {
+ red: 0,
+ orange: 60,
+ yellow: 120,
+ green: 180,
+ blue: 240,
+ purple: 300
+ }
+
+ /**
+ * Parse color from the string passed
+ *
+ * @return {Object} A space indicator `space`, an array `values` and `alpha`
+ */
+ export const parse = (cstr) => {
+ var m, parts = [], alpha = 1, space
+ if (typeof cstr === 'string') {
+ //keyword
+ if (names[cstr]) {
+ parts = names[cstr].slice()
+ space = 'rgb'
+ }
+
+ //reserved words
+ else if (cstr === 'transparent') {
+ alpha = 0
+ space = 'rgb'
+ parts = [0,0,0]
+ }
+
+ //hex
+ else if (/^#[A-Fa-f0-9]+$/.test(cstr)) {
+ var base = cstr.slice(1)
+ var size = base.length
+ var isShort = size <= 4
+ alpha = 1
+
+ if (isShort) {
+ parts = [
+ parseInt(base[0] + base[0], 16),
+ parseInt(base[1] + base[1], 16),
+ parseInt(base[2] + base[2], 16)
+ ]
+ if (size === 4) {
+ alpha = parseInt(base[3] + base[3], 16) / 255
+ }
+ }
+ else {
+ parts = [
+ parseInt(base[0] + base[1], 16),
+ parseInt(base[2] + base[3], 16),
+ parseInt(base[4] + base[5], 16)
+ ]
+ if (size === 8) {
+ alpha = parseInt(base[6] + base[7], 16) / 255
+ }
+ }
+
+ if (!parts[0]) parts[0] = 0
+ if (!parts[1]) parts[1] = 0
+ if (!parts[2]) parts[2] = 0
+
+ space = 'rgb'
+ }
+
+ //color space
+ else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) {
+ var name = m[1]
+ var isRGB = name === 'rgb'
+ var base: string = name.replace(/a$/, '');
+ space = base
+ var size = base === 'cmyk' ? 4 : base === 'gray' ? 1 : 3
+ parts = m[2].trim()
+ .split(/\s*[,\/]\s*|\s+/)
+ .map(function (x, i) {
+ //
+ if (/%$/.test(x)) {
+ //alpha
+ if (i === size) return parseFloat(x) / 100
+ //rgb
+ if (base === 'rgb') return parseFloat(x) * 255 / 100
+ return parseFloat(x)
+ }
+ //hue
+ else if (base[i] === 'h') {
+ //
+ if (/deg$/.test(x)) {
+ return parseFloat(x)
+ }
+ //
+ else if (baseHues[x] !== undefined) {
+ return baseHues[x]
+ }
+ }
+ return parseFloat(x)
+ })
+
+ if (name === base) parts.push(1)
+ alpha = (isRGB) ? 1 : (parts[size] === undefined) ? 1 : parts[size]
+ parts = parts.slice(0, size)
+ }
+
+ //named channels case
+ else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) {
+ parts = cstr.match(/([0-9]+)/g).map(function (value) {
+ return parseFloat(value)
+ })
+
+ space = cstr.match(/([a-z])/ig).join('').toLowerCase()
+ }
+ }
+
+ //numeric case
+ else if (!Number.isNaN(cstr)) {
+ space = 'rgb'
+ parts = [cstr >>> 16, (cstr & 0x00ff00) >>> 8, cstr & 0x0000ff]
+ }
+
+ //array-like
+ else if (Array.isArray(cstr) || cstr.length) {
+ parts = [cstr[0], cstr[1], cstr[2]]
+ space = 'rgb'
+ alpha = cstr.length === 4 ? cstr[3] : 1
+ }
+
+ //object case - detects css cases of rgb and hsl
+ else if (cstr instanceof Object) {
+ if (cstr.r != null || cstr.red != null || cstr.R != null) {
+ space = 'rgb'
+ parts = [
+ cstr.r || cstr.red || cstr.R || 0,
+ cstr.g || cstr.green || cstr.G || 0,
+ cstr.b || cstr.blue || cstr.B || 0
+ ]
+ }
+ else {
+ space = 'hsl'
+ parts = [
+ cstr.h || cstr.hue || cstr.H || 0,
+ cstr.s || cstr.saturation || cstr.S || 0,
+ cstr.l || cstr.lightness || cstr.L || cstr.b || cstr.brightness
+ ]
+ }
+
+ alpha = cstr.a || cstr.alpha || cstr.opacity || 1
+
+ if (cstr.opacity != null) alpha /= 100
+ }
+
+ return {
+ space: space,
+ values: parts,
+ alpha: alpha
+ }
+ }
+
+export const rgba = (color) => {
+ // template literals
+ // @ts-ignore
+ if (Array.isArray(color) && color.raw) color = String.raw(...arguments)
+
+ var values, i, l
+
+ //attempt to parse non-array arguments
+ var parsed = parse(color)
+
+ if (!parsed.space) return []
+
+ values = Array(3)
+ values[0] = Math.min(Math.max(parsed.values[0], 0), 255)
+ values[1] = Math.min(Math.max(parsed.values[1], 0), 255)
+ values[2] = Math.min(Math.max(parsed.values[2], 0), 255)
+
+ if (parsed.space[0] === 'h') {
+ values = hsl.rgb(values)
+ }
+
+ values.push(Math.min(Math.max(parsed.alpha, 0), 1))
+
+ return values
+}
+
+export default rgba;
\ No newline at end of file
diff --git a/packages/animate/src/colors.ts b/packages/animate/src/colors.ts
new file mode 100644
index 0000000..6633dd9
--- /dev/null
+++ b/packages/animate/src/colors.ts
@@ -0,0 +1,150 @@
+export default {
+ "aliceblue": [240, 248, 255],
+ "antiquewhite": [250, 235, 215],
+ "aqua": [0, 255, 255],
+ "aquamarine": [127, 255, 212],
+ "azure": [240, 255, 255],
+ "beige": [245, 245, 220],
+ "bisque": [255, 228, 196],
+ "black": [0, 0, 0],
+ "blanchedalmond": [255, 235, 205],
+ "blue": [0, 0, 255],
+ "blueviolet": [138, 43, 226],
+ "brown": [165, 42, 42],
+ "burlywood": [222, 184, 135],
+ "cadetblue": [95, 158, 160],
+ "chartreuse": [127, 255, 0],
+ "chocolate": [210, 105, 30],
+ "coral": [255, 127, 80],
+ "cornflowerblue": [100, 149, 237],
+ "cornsilk": [255, 248, 220],
+ "crimson": [220, 20, 60],
+ "cyan": [0, 255, 255],
+ "darkblue": [0, 0, 139],
+ "darkcyan": [0, 139, 139],
+ "darkgoldenrod": [184, 134, 11],
+ "darkgray": [169, 169, 169],
+ "darkgreen": [0, 100, 0],
+ "darkgrey": [169, 169, 169],
+ "darkkhaki": [189, 183, 107],
+ "darkmagenta": [139, 0, 139],
+ "darkolivegreen": [85, 107, 47],
+ "darkorange": [255, 140, 0],
+ "darkorchid": [153, 50, 204],
+ "darkred": [139, 0, 0],
+ "darksalmon": [233, 150, 122],
+ "darkseagreen": [143, 188, 143],
+ "darkslateblue": [72, 61, 139],
+ "darkslategray": [47, 79, 79],
+ "darkslategrey": [47, 79, 79],
+ "darkturquoise": [0, 206, 209],
+ "darkviolet": [148, 0, 211],
+ "deeppink": [255, 20, 147],
+ "deepskyblue": [0, 191, 255],
+ "dimgray": [105, 105, 105],
+ "dimgrey": [105, 105, 105],
+ "dodgerblue": [30, 144, 255],
+ "firebrick": [178, 34, 34],
+ "floralwhite": [255, 250, 240],
+ "forestgreen": [34, 139, 34],
+ "fuchsia": [255, 0, 255],
+ "gainsboro": [220, 220, 220],
+ "ghostwhite": [248, 248, 255],
+ "gold": [255, 215, 0],
+ "goldenrod": [218, 165, 32],
+ "gray": [128, 128, 128],
+ "green": [0, 128, 0],
+ "greenyellow": [173, 255, 47],
+ "grey": [128, 128, 128],
+ "honeydew": [240, 255, 240],
+ "hotpink": [255, 105, 180],
+ "indianred": [205, 92, 92],
+ "indigo": [75, 0, 130],
+ "ivory": [255, 255, 240],
+ "khaki": [240, 230, 140],
+ "lavender": [230, 230, 250],
+ "lavenderblush": [255, 240, 245],
+ "lawngreen": [124, 252, 0],
+ "lemonchiffon": [255, 250, 205],
+ "lightblue": [173, 216, 230],
+ "lightcoral": [240, 128, 128],
+ "lightcyan": [224, 255, 255],
+ "lightgoldenrodyellow": [250, 250, 210],
+ "lightgray": [211, 211, 211],
+ "lightgreen": [144, 238, 144],
+ "lightgrey": [211, 211, 211],
+ "lightpink": [255, 182, 193],
+ "lightsalmon": [255, 160, 122],
+ "lightseagreen": [32, 178, 170],
+ "lightskyblue": [135, 206, 250],
+ "lightslategray": [119, 136, 153],
+ "lightslategrey": [119, 136, 153],
+ "lightsteelblue": [176, 196, 222],
+ "lightyellow": [255, 255, 224],
+ "lime": [0, 255, 0],
+ "limegreen": [50, 205, 50],
+ "linen": [250, 240, 230],
+ "magenta": [255, 0, 255],
+ "maroon": [128, 0, 0],
+ "mediumaquamarine": [102, 205, 170],
+ "mediumblue": [0, 0, 205],
+ "mediumorchid": [186, 85, 211],
+ "mediumpurple": [147, 112, 219],
+ "mediumseagreen": [60, 179, 113],
+ "mediumslateblue": [123, 104, 238],
+ "mediumspringgreen": [0, 250, 154],
+ "mediumturquoise": [72, 209, 204],
+ "mediumvioletred": [199, 21, 133],
+ "midnightblue": [25, 25, 112],
+ "mintcream": [245, 255, 250],
+ "mistyrose": [255, 228, 225],
+ "moccasin": [255, 228, 181],
+ "navajowhite": [255, 222, 173],
+ "navy": [0, 0, 128],
+ "oldlace": [253, 245, 230],
+ "olive": [128, 128, 0],
+ "olivedrab": [107, 142, 35],
+ "orange": [255, 165, 0],
+ "orangered": [255, 69, 0],
+ "orchid": [218, 112, 214],
+ "palegoldenrod": [238, 232, 170],
+ "palegreen": [152, 251, 152],
+ "paleturquoise": [175, 238, 238],
+ "palevioletred": [219, 112, 147],
+ "papayawhip": [255, 239, 213],
+ "peachpuff": [255, 218, 185],
+ "peru": [205, 133, 63],
+ "pink": [255, 192, 203],
+ "plum": [221, 160, 221],
+ "powderblue": [176, 224, 230],
+ "purple": [128, 0, 128],
+ "rebeccapurple": [102, 51, 153],
+ "red": [255, 0, 0],
+ "rosybrown": [188, 143, 143],
+ "royalblue": [65, 105, 225],
+ "saddlebrown": [139, 69, 19],
+ "salmon": [250, 128, 114],
+ "sandybrown": [244, 164, 96],
+ "seagreen": [46, 139, 87],
+ "seashell": [255, 245, 238],
+ "sienna": [160, 82, 45],
+ "silver": [192, 192, 192],
+ "skyblue": [135, 206, 235],
+ "slateblue": [106, 90, 205],
+ "slategray": [112, 128, 144],
+ "slategrey": [112, 128, 144],
+ "snow": [255, 250, 250],
+ "springgreen": [0, 255, 127],
+ "steelblue": [70, 130, 180],
+ "tan": [210, 180, 140],
+ "teal": [0, 128, 128],
+ "thistle": [216, 191, 216],
+ "tomato": [255, 99, 71],
+ "turquoise": [64, 224, 208],
+ "violet": [238, 130, 238],
+ "wheat": [245, 222, 179],
+ "white": [255, 255, 255],
+ "whitesmoke": [245, 245, 245],
+ "yellow": [255, 255, 0],
+ "yellowgreen": [154, 205, 50]
+};
\ No newline at end of file
diff --git a/packages/animate/src/css-properties.ts b/packages/animate/src/css-properties.ts
index f6b7b37..98f57dc 100644
--- a/packages/animate/src/css-properties.ts
+++ b/packages/animate/src/css-properties.ts
@@ -1,5 +1,6 @@
-import { mapObject } from "./api";
-import { TypeSingleValueCSSProperty, ICSSComputedTransformableProperties } from "./types";
+import { camelCase, isValid, mapObject, omit, toArr, toStr, transpose } from "./utils";
+
+import type { TypeSingleValueCSSProperty, ICSSComputedTransformableProperties } from "./types";
/**
* Returns a closure Function, which adds a unit to numbers but simply returns strings with no edits assuming the value has a unit if it's a string
@@ -22,36 +23,6 @@ export const UnitPX = addCSSUnit("px");
/** Function adds "deg" unit to numbers */
export const UnitDEG = addCSSUnit("deg");
-/**
- * Convert the input to an array
- * For strings split them at commas
- * For array do nothing
- * For everything else wrap the input in an array
- */
-export const toArr = (input: any): any[] => {
- if (Array.isArray(input) || typeof input == "string") {
- if (typeof input == "string") input = input.split(",");
- return input;
- }
-
- return [input];
-}
-
-/**
- * Checks if value is valid/truthy; it counts empty arrays and strings as falsey,
- * as well as null and undefined everything else is valid
- *
- * _**Note:** 0 counts as valid_
- *
- * @param value - anything
- * @returns true or false
- */
-export const isValid = (value: any) => {
- if (Array.isArray(value) || typeof value == "string")
- return Boolean(value.length);
- return value != null && value != undefined;
-}
-
/**
* Returns a closure function, which adds units to numbers, strings or arrays of both
*
@@ -76,57 +47,6 @@ export const CSSValue = (unit: typeof UnitLess) => {
};
}
-/**
- * Flips the rows and columns of 2-dimensional arrays
- *
- * Read more on [underscorejs.org](https://underscorejs.org/#zip) & [lodash.com](https://lodash.com/docs/4.17.15#zip)
- *
- * @example
- * ```ts
- * transpose(
- * ['moe', 'larry', 'curly'],
- * [30, 40, 50],
- * [true, false, false]
- * );
- * // [
- * // ["moe", 30, true],
- * // ["larry", 40, false],
- * // ["curly", 50, false]
- * // ]
- * ```
- * @param [...args] - the arrays to process as a set of arguments
- * @returns
- * returns the new array of grouped elements
- */
-export const transpose = (...args: TypeSingleValueCSSProperty[] | TypeSingleValueCSSProperty[][]) => {
- let largestArrLen = 0;
- args = args.map(arr => {
- // Convert all values in arrays to an array
- // This ensures that `arrays` is an array of arrays
- let result = toArr(arr);
-
- // Finds the largest array
- let len = result.length;
- if (len > largestArrLen) largestArrLen = len;
- return result;
- });
-
- // Flip the rows and columns of arrays
- let result = [];
- let len = args.length;
- for (let col = 0; col < largestArrLen; col++) {
- result[col] = [];
-
- for (let row = 0; row < len; row++) {
- let val = args[row][col];
- if (isValid(val))
- result[col][row] = val;
- }
- }
-
- return result;
-}
-
/**
* Takes `TypeSingleValueCSSProperty` or an array of `TypeSingleValueCSSProperty` and adds units approriately
*
@@ -149,44 +69,6 @@ export const CSSArrValue = (arr: TypeSingleValueCSSProperty | TypeSingleValueCSS
return toArr(arr).map(CSSValue(unit)) as TypeSingleValueCSSProperty[];
}
-export const TransformFunctionNames = [
- "translate",
- "translate3d",
- "translateX",
- "translateY",
- "translateZ",
- "rotate",
- "rotate3d",
- "rotateX",
- "rotateY",
- "rotateZ",
- "scale",
- "scale3d",
- "scaleX",
- "scaleY",
- "scaleZ",
- "skew",
- "skewX",
- "skewY",
- "perspective"
-];
-
-/**
- * Creates the transform property text
- */
-export const createTransformProperty = (arr) => {
- let result = "";
- let len = TransformFunctionNames.length;
- for (let i = 0; i < len; i++) {
- let name = TransformFunctionNames[i];
- let value = arr[i];
- if (isValid(value))
- result += `${name}(${Array.isArray(value) ? value.join(", ") : value}) `;
- }
-
- return result.trim();
-}
-
/** Parses CSSValues without adding any units */
export const UnitLessCSSValue = CSSValue(UnitLess);
@@ -196,13 +78,6 @@ export const UnitPXCSSValue = CSSValue(UnitPX);
/** Parses CSSValues and adds the "deg" unit if required */
export const UnitDEGCSSValue = CSSValue(UnitDEG);
-/** Convert a dash-separated string into camelCase strings */
-export const camelCase = (str: string) => {
- if (str.includes("--")) return str;
- let result = `${str}`.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
- return result;
-}
-
/**
* Removes dashes from CSS properties & maps the values to the camelCase keys
*/
@@ -218,17 +93,70 @@ export const ParseCSSProperties = (obj: object) => {
return result;
}
-/** Converts values to strings */
-export const toStr = (input: any) => `` + input;
+export interface ITransformFunctions {
+ [key: string]: (value: TypeSingleValueCSSProperty | Array) => TypeSingleValueCSSProperty | Array;
+}
+
+/**
+ * Details how to compute each transform function
+ */
+export const TransformFunctions: ITransformFunctions = {
+ "translate": value => CSSArrValue(value, UnitPX),
+ "translate3d": value => CSSArrValue(value, UnitPX),
+ "translateX": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
+ "translateY": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
+ "translateZ": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
+
+ "rotate": value => CSSArrValue(value, UnitDEG),
+ "rotate3d": value => CSSArrValue(value, UnitLess),
+ "rotateX": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
+ "rotateY": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
+ "rotateZ": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
+
+ "scale": value => CSSArrValue(value, UnitLess),
+ "scale3d": value => CSSArrValue(value, UnitLess),
+ "scaleX": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value),
+ "scaleY": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value),
+ "scaleZ": (value: TypeSingleValueCSSProperty) => UnitLessCSSValue(value),
+
+ "skew": value => CSSArrValue(value, UnitDEG),
+ "skewX": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
+ "skewY": (value: TypeSingleValueCSSProperty) => UnitDEGCSSValue(value),
+
+ "perspective": (value: TypeSingleValueCSSProperty) => UnitPXCSSValue(value),
+};
+
+/**
+ * Store all the supported transform functions as an Array
+ */
+export const TransformFunctionNames = Object.keys(TransformFunctions);
+
+/**
+ * Creates the transform property text
+ */
+export const createTransformProperty = (transformFnNames: string[], arr: any[]) => {
+ let result = "";
+ let len = transformFnNames.length;
+ for (let i = 0; i < len; i++) {
+ let name = transformFnNames[i];
+ let value = arr[i];
+ if (isValid(value))
+ result += `${name}(${Array.isArray(value) ? value.join(", ") : value}) `;
+ }
+
+ return result.trim();
+}
/** Common CSS Property names with the units "px" as an acceptable value */
-export const CSSPXDataType = ["margin", "padding", "size", "width", "height", "left", "right", "top", "bottom", "radius", "gap", "basis", "inset", "outline-offset", "perspective", "thickness", "position", "distance", "spacing"].join("|");
+export const CSSPXDataType = ["margin", "padding", "size", "width", "height", "left", "right", "top", "bottom", "radius", "gap", "basis", "inset", "outline-offset", "perspective", "thickness", "position", "distance", "spacing"].map(camelCase).join("|");
/**
* 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
* Also, adds the ability to use single string or number values for transform functions
*
* _**Note**: the `transform` animation option will override all transform function properties_
+ *
+ * _**Note**: the order of where/when you define transform function matters, for example, depending on the order you define `translate`, and `rotate`, you can create change the radius of the rotation_
*
* @param properties - the CSS properties to transform
*
@@ -290,71 +218,30 @@ export const CSSPXDataType = ["margin", "padding", "size", "width", "height", "l
* ```
*/
export const ParseTransformableCSSProperties = (properties: ICSSComputedTransformableProperties) => {
- let {
- perspective,
- rotate,
- rotate3d,
- rotateX,
- rotateY,
- rotateZ,
- translate,
- translate3d,
- translateX,
- translateY,
- translateZ,
- scale,
- scale3d,
- scaleX,
- scaleY,
- scaleZ,
- skew,
- skewX,
- skewY,
- ...rest
-
- // Convert dash seperated strings to camelCase strings
- } = ParseCSSProperties(properties) as ICSSComputedTransformableProperties;
-
- translate = CSSArrValue(translate, UnitPX);
- translate3d = CSSArrValue(translate3d, UnitPX);
- translateX = UnitPXCSSValue(translateX);
- translateY = UnitPXCSSValue(translateY);
- translateZ = UnitPXCSSValue(translateZ);
-
- rotate = CSSArrValue(rotate, UnitDEG);
- rotate3d = CSSArrValue(rotate3d, UnitLess);
- rotateX = UnitDEGCSSValue(rotateX);
- rotateY = UnitDEGCSSValue(rotateY);
- rotateZ = UnitDEGCSSValue(rotateZ);
-
- scale = CSSArrValue(scale, UnitLess);
- scale3d = CSSArrValue(scale3d, UnitLess);
- scaleX = UnitLessCSSValue(scaleX);
- scaleY = UnitLessCSSValue(scaleY);
- scaleZ = UnitLessCSSValue(scaleZ);
-
- skew = CSSArrValue(skew, UnitDEG);
- skewX = UnitDEGCSSValue(skewX);
- skewY = UnitDEGCSSValue(skewY);
-
- perspective = UnitPXCSSValue(perspective);
-
- let transform = transpose(
- translate, translate3d, translateX, translateY, translateZ,
- rotate, rotate3d, rotateX, rotateY, rotateZ,
- scale, scale3d, scaleX, scaleY, scaleZ,
- skew, skewX, skewY,
- perspective
- ).filter(isValid).map(createTransformProperty);
+ // Convert dash seperated strings to camelCase strings
+ let AllCSSProperties = ParseCSSProperties(properties) as ICSSComputedTransformableProperties;
+ let rest = omit(TransformFunctionNames, AllCSSProperties);
+
+ // Adds support for ordered transforms
+ let transformFunctionNames = Object.keys(AllCSSProperties)
+ .filter(key => TransformFunctionNames.includes(key));
+
+ let transformFunctionValues = transformFunctionNames
+ .map((key) => TransformFunctions[key](AllCSSProperties[key]));
+
+ // The transform string
+ let transform = transpose(...transformFunctionValues)
+ .filter(isValid)
+ .map(arr => createTransformProperty(transformFunctionNames, arr));
// Wrap non array CSS property values in an array
rest = mapObject(rest, (value, key) => {
let unit: typeof UnitDEGCSSValue | typeof UnitPXCSSValue;
// If key doesn't have the word color in it, try to add the default "px" or "deg" to it
- if (!/color/gi.test(key)) {
- let isAngle = /rotate/gi.test(key);
- let isLength = new RegExp(CSSPXDataType, "gi").test(key);
+ if (!/color/i.test(key)) {
+ let isAngle = /rotate/i.test(key);
+ let isLength = new RegExp(CSSPXDataType, "i").test(key);
// There is an intresting bug that occurs if you test a string againt the same instance of a Regular Expression
// where the answer will be different every test
@@ -460,14 +347,14 @@ export const ParseTransformableCSSKeyframes = (keyframes: ICSSComputedTransforma
perspective
];
}).map(([rest, ...transformFunctions]) => {
- let transform = createTransformProperty(transformFunctions);
+ let transform = createTransformProperty(TransformFunctionNames, transformFunctions);
rest = mapObject(rest as object, (value, key) => {
let unit: typeof UnitDEGCSSValue | typeof UnitPXCSSValue;
// If key doesn't have the word color in it, try to add the default "px" or "deg" to it
- if (!/color/gi.test(key)) {
- let isAngle = /rotate/gi.test(key);
- let isLength = new RegExp(CSSPXDataType, "gi").test(key);
+ if (!/color/i.test(key)) {
+ let isAngle = /rotate/i.test(key);
+ let isLength = new RegExp(CSSPXDataType, "i").test(key);
// There is an intresting bug that occurs if you test a string againt the same instance of a Regular Expression
// where the answer will be different every test
diff --git a/packages/animate/src/custom-easing.ts b/packages/animate/src/custom-easing.ts
new file mode 100644
index 0000000..bc9df99
--- /dev/null
+++ b/packages/animate/src/custom-easing.ts
@@ -0,0 +1,765 @@
+import { isValid, transpose, toStr, convertToDash, mapObject } from "./utils";
+import bezier from "./bezier-easing";
+import rgba from "./color-rgba";
+
+export const limit = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);
+
+/**
+ * The format to use when defining custom easing functions
+ */
+export type TypeEasingFunction = (t: number, params?: (string | number)[], duration?: number) => number;
+export type TypeColor = string | number | Array;
+export type TypeRGBAFunction = (color: TypeColor) => number[];
+
+/**
+ Easing Functions from anime.js, they are tried and true, so, its better to use them instead of other alternatives
+*/
+export const Quad: TypeEasingFunction = t => Math.pow(t, 2);
+export const Cubic: TypeEasingFunction = t => Math.pow(t, 3);
+export const Quart: TypeEasingFunction = t => Math.pow(t, 4);
+export const Quint: TypeEasingFunction = t => Math.pow(t, 5);
+export const Expo: TypeEasingFunction = t => Math.pow(t, 6);
+export const Sine: TypeEasingFunction = t => 1 - Math.cos((t * Math.PI) / 2);
+export const Circ: TypeEasingFunction = t => 1 - Math.sqrt(1 - t * t);
+export const Back: TypeEasingFunction = t => t * t * (3 * t - 2);
+
+export const Bounce: TypeEasingFunction = t => {
+ let pow2: number, b = 4;
+ while (t < ((pow2 = Math.pow(2, --b)) - 1) / 11) { }
+ return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - t, 2);
+};
+
+export const Elastic: TypeEasingFunction = (t, params: number[] = []) => {
+ let [amplitude = 1, period = 0.5] = params;
+ const a = limit(amplitude, 1, 10);
+ const p = limit(period, 0.1, 2);
+ if (t === 0 || t === 1) return t;
+ return -a *
+ Math.pow(2, 10 * (t - 1)) *
+ Math.sin(
+ ((t - 1 - (p / (Math.PI * 2)) * Math.asin(1 / a)) * (Math.PI * 2)) / p
+ );
+};
+
+export const Spring: TypeEasingFunction = (
+ t: number,
+ params: number[] = [],
+ duration?: number
+) => {
+ let [
+ mass = 1,
+ stiffness = 100,
+ damping = 10,
+ velocity = 0
+ ] = params;
+
+ mass = limit(mass, 0.1, 1000);
+ stiffness = limit(stiffness, 0.1, 1000);
+ damping = limit(damping, 0.1, 1000);
+ velocity = limit(velocity, 0.1, 1000);
+
+ const w0 = Math.sqrt(stiffness / mass);
+ const zeta = damping / (2 * Math.sqrt(stiffness * mass));
+ const wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
+ const a = 1;
+ const b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
+
+ let progress = duration ? (duration * t) / 1000 : t;
+ if (zeta < 1) {
+ progress =
+ Math.exp(-progress * zeta * w0) *
+ (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
+ } else {
+ progress = (a + b * progress) * Math.exp(-progress * w0);
+ }
+
+ if (t === 0 || t === 1) return t;
+ return 1 - progress;
+};
+
+/**
+ * Cache the durations at set easing parameters
+ */
+export const EasingDurationCache: Map = new Map();
+
+/**
+ * The threshold for an infinite loop
+ */
+export const INTINITE_LOOP_LIMIT = 10000;
+
+/**
+ * The spring easing function will only look smooth at certain durations, with certain parameters.
+ * This functions returns the optimal duration to create a smooth springy animation based on physics
+ *
+ * Note: it can also be used to determine the optimal duration of other types of easing function, but be careful of "in-"
+ * easing functions, because of the nature of the function it can sometimes create an infinite loop, I suggest only using
+ * `getEasingDuration` for `spring`, specifically "out-spring" and "spring"
+ */
+export const getEasingDuration = (easing: string | TypeEasingFunction = "spring") => {
+ if (EasingDurationCache.has(easing))
+ return EasingDurationCache.get(easing);
+
+ const easingFunction = typeof easing == "function" ? easing : GetEasingFunction(easing as string);
+ const params = typeof easing == "function" ? [] : parseEasingParameters(easing);
+ const frame = 1 / 6;
+
+ let elapsed = 0;
+ let rest = 0;
+ let count = 0;
+
+ while (++count < INTINITE_LOOP_LIMIT) {
+ elapsed += frame;
+ if (easingFunction(elapsed, params, null) === 1) {
+ rest++;
+ if (rest >= 16) break;
+ } else {
+ rest = 0;
+ }
+ }
+
+ const duration = elapsed * frame * 1000;
+ EasingDurationCache.set(easing, duration);
+ return duration;
+}
+
+/**
+ These Easing Functions are based off of the Sozi Project's easing functions
+ https://github.com/sozi-projects/Sozi/blob/d72e44ebd580dc7579d1e177406ad41e632f961d/src/js/player/Timing.js
+*/
+export const Steps: TypeEasingFunction = (t: number, params = []) => {
+ let [steps = 10, type] = params as [number, string];
+ const trunc = type == "start" ? Math.ceil : Math.floor;
+ return trunc(limit(t, 0, 1) * steps) / steps;
+};
+
+export const Bezier: TypeEasingFunction = (t: number, params: number[] = []) => {
+ let [mX1, mY1, mX2, mY2] = params;
+ return bezier(mX1, mY1, mX2, mY2)(t);
+};
+
+/** The default `ease-in` easing function */
+export const easein: TypeEasingFunction = bezier(0.42, 0.0, 1.0, 1.0);
+
+/** Converts easing functions to their `out`counter parts */
+export const EaseOut = (ease: TypeEasingFunction): TypeEasingFunction => {
+ return (t, params = [], duration?: number) => 1 - ease(1 - t, params, duration);
+}
+
+/** Converts easing functions to their `in-out` counter parts */
+export const EaseInOut = (ease: TypeEasingFunction): TypeEasingFunction => {
+ return (t, params = [], duration?: number) =>
+ t < 0.5 ? ease(t * 2, params, duration) / 2 : 1 - ease(t * -2 + 2, params, duration) / 2;
+}
+
+/** Converts easing functions to their `out-in` counter parts */
+export const EaseOutIn = (ease: TypeEasingFunction): TypeEasingFunction => {
+ return (t, params = [], duration?: number) => {
+ return t < 0.5
+ ? (1 - ease(1 - t * 2, params, duration)) / 2
+ : (ease(t * 2 - 1, params, duration) + 1) / 2;
+ };
+}
+
+/**
+ * The default list of easing functions, do note this is different from {@link EASING}
+ */
+export const EasingFunctions: { [key: string]: TypeEasingFunction } = {
+ steps: Steps,
+ "step-start": t => Steps(t, [1, "start"]),
+ "step-end": t => Steps(t, [1, "end"]),
+
+ linear: t => t,
+ "cubic-bezier": Bezier,
+ ease: t => Bezier(t, [0.25, 0.1, 0.25, 1.0]),
+
+ in: easein,
+ out: EaseOut(easein),
+ "in-out": EaseInOut(easein),
+ "out-in": EaseOutIn(easein),
+
+ "in-quad": Quad,
+ "out-quad": EaseOut(Quad),
+ "in-out-quad": EaseInOut(Quad),
+ "out-in-quad": EaseOutIn(Quad),
+
+ "in-cubic": Cubic,
+ "out-cubic": EaseOut(Cubic),
+ "in-out-cubic": EaseInOut(Cubic),
+ "out-in-cubic": EaseOutIn(Cubic),
+
+ "in-quart": Quart,
+ "out-quart": EaseOut(Quart),
+ "in-out-quart": EaseInOut(Quart),
+ "out-in-quart": EaseOutIn(Quart),
+
+ "in-quint": Quint,
+ "out-quint": EaseOut(Quint),
+ "in-out-quint": EaseInOut(Quint),
+ "out-in-quint": EaseOutIn(Quint),
+
+ "in-expo": Expo,
+ "out-expo": EaseOut(Expo),
+ "in-out-expo": EaseInOut(Expo),
+ "out-in-expo": EaseOutIn(Expo),
+
+ "in-sine": Sine,
+ "out-sine": EaseOut(Sine),
+ "in-out-sine": EaseInOut(Sine),
+ "out-in-sine": EaseOutIn(Sine),
+
+ "in-circ": Circ,
+ "out-circ": EaseOut(Circ),
+ "in-out-circ": EaseInOut(Circ),
+ "out-in-circ": EaseOutIn(Circ),
+
+ "in-back": Back,
+ "out-back": EaseOut(Back),
+ "in-out-back": EaseInOut(Back),
+ "out-in-back": EaseOutIn(Back),
+
+ "in-bounce": Bounce,
+ "out-bounce": EaseOut(Bounce),
+ "in-out-bounce": EaseInOut(Bounce),
+ "out-in-bounce": EaseOutIn(Bounce),
+
+ "in-elastic": Elastic,
+ "out-elastic": EaseOut(Elastic),
+ "in-out-elastic": EaseInOut(Elastic),
+ "out-in-elastic": EaseOutIn(Elastic),
+
+ spring: Spring,
+ "spring-in": Spring,
+ "spring-out": EaseOut(Spring),
+ "spring-in-out": EaseInOut(Spring),
+ "spring-out-in": EaseOutIn(Spring)
+};
+
+export let EasingFunctionKeys = Object.keys(EasingFunctions);
+
+/**
+ * Allows you to register new easing functions
+ */
+export const registerEasingFunction = (key: string, fn: TypeEasingFunction) => {
+ Object.assign(EasingFunctions, {
+ [key]: fn
+ });
+
+ EasingFunctionKeys = Object.keys(EasingFunctions);
+}
+
+/**
+ * Allows you to register multiple new easing functions
+ */
+export const registerEasingFunctions = (...obj: Array) => {
+ Object.assign(EasingFunctions, ...obj);
+ EasingFunctionKeys = Object.keys(EasingFunctions);
+}
+
+/**
+ * Convert string easing to their proper form
+ */
+export const ComplexEasingSyntax = (ease: string) =>
+ convertToDash(ease)
+ .replace(/^ease-/, "") // Remove the "ease-" keyword
+ .replace(/(\(|\s).+/, "") // Remove the function brackets and parameters
+ .toLowerCase()
+ .trim();
+
+/** Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. */
+export const GetEasingFunction = (ease: string) => {
+ let search = ComplexEasingSyntax(ease);
+
+ if (EasingFunctionKeys.includes(search))
+ return EasingFunctions[search];
+ return null;
+};
+
+/** Convert easing parameters to Array of numbers, e.g. "spring(2, 500)" to [2, 500] */
+export const parseEasingParameters = (str: string) => {
+ const match = /(\(|\s)([^)]+)\)?/.exec(str);
+ return match ? match[2].split(",").map(value => {
+ let num = parseFloat(value);
+ return !Number.isNaN(num) ? num : value.trim();
+ }) : [];
+};
+
+/** map `t` from 0 to 1, to `start` to `end` */
+export const scale = (t: number, start: number, end: number) => start + (end - start) * t;
+
+/** Rounds numbers to a fixed decimal place */
+export const toFixed = (value: number, decimal: number) =>
+ Math.round(value * 10 ** decimal) / 10 ** decimal;
+
+/**
+ Given an Array of numbers, estimate the resulting number, at a `t` value between 0 to 1
+ Based on d3.interpolateBasis [https://github.com/d3/d3-interpolate#interpolateBasis],
+ check out the link above for more detail.
+
+ Basic interpolation works by scaling `t` from 0 - 1, to some start number and end number, in this case lets use
+ 0 as our start number and 100 as our end number, so, basic interpolation would interpolate between 0 to 100.
+
+ If we use a `t` of 0.5, the interpolated value between 0 to 100, is 50.
+ {@link interpolateNumber} takes it further, by allowing you to interpolate with more than 2 values,
+ it allows for multiple values.
+
+ E.g. Given an Array of values [0, 100, 0], and a `t` of 0.5, the interpolated value would become 100.
+*/
+export const interpolateNumber = (t: number, values: number[], decimal = 3) => {
+ // nth index
+ let n = values.length - 1;
+
+ // The current index given t
+ let i = limit(Math.floor(t * n), 0, n - 1);
+
+ let start = values[i];
+ let end = values[i + 1];
+ let progress = (t - i / n) * n;
+
+ return toFixed(scale(progress, start, end), decimal);
+};
+
+/** If a value can be converted to a valid number, then it's most likely a number */
+export const isNumberLike = (num: string | number) => {
+ let value = parseFloat(num as string);
+ return typeof value == "number" && !Number.isNaN(value);
+};
+
+/**
+ Given an Array of values, find a value using `t` (`t` goes from 0 to 1), by
+ using `t` to estimate the index of said value in the array of `values`
+*/
+export const interpolateUsingIndex = (t: number, values: (string | number)[]) => {
+ // limit `t`, to a min of 0 and a max of 1
+ t = limit(t, 0, 1);
+
+ // nth index
+ let n = values.length - 1;
+
+ // The current index given t
+ let i = Math.round(t * n);
+ return values[i];
+};
+
+/**
+ Functions the same way {@link interpolateNumber} works.
+ Convert strings to numbers, and then interpolates the numbers,
+ at the end if there are units on the first value in the `values` array,
+ it will use that unit for the interpolated result.
+
+ Make sure to read {@link interpolateNumber}.
+*/
+export const interpolateString = (t: number, values: (string | number)[], decimal = 3) => {
+ let units = "";
+
+ // If the first value looks like a number with a unit
+ if (isNumberLike(values[0]))
+ units = toStr(values[0]).replace(/^\d+/, "");
+
+ return interpolateNumber(t, values.map(parseFloat), decimal) + units;
+};
+
+/**
+ Use the `color-rgba` npm package, to convert all color formats to an Array of rgba values,
+ e.g. `[red, green, blue, alpha]`. Then, use the {@link interpolateNumber} functions to interpolate over the array
+
+ _**Note**: the red, green, and blue colors are rounded to intergers with no decimal places,
+ while the alpha color gets rounded to a specific decimal place_
+
+ Make sure to read {@link interpolateNumber}.
+*/
+export const interpolateColor = (t: number, values: TypeColor[], decimal = 3) => {
+ return transpose(...values.map(rgba as TypeRGBAFunction)).map((colors: number[], i) => {
+ let result = interpolateNumber(t, colors);
+ return i < 3 ? Math.round(result) : toFixed(result, decimal);
+ });
+};
+
+/**
+ Convert value to string, then trim any extra white space and line terminator characters from the string.
+*/
+export const trim = (str: string) => toStr(str).trim();
+
+/**
+ Converts "10px solid red #555 rgba(255, 0,5,6, 7) "
+ to [ '10px', 'solid', 'red', '#555', 'rgba(255, 0,5,6, 7)' ]
+*/
+export const ComplexStrtoArr = (str: string) => {
+ return (
+ trim(str)
+ .replace(/(\d|\)|\w)\s/g, (match) => match[0] + "__")
+ .split("__")
+ .map(trim)
+
+ // Remove invalid values
+ .filter(isValid)
+ );
+};
+
+/**
+ Interpolates all types of values including number, string, color, and complex values.
+ Complex values are values like "10px solid red", that border, and other CSS Properties use.
+
+ Make sure to read {@link interpolateNumber}, {@link interpolateString}, {@link interpolateColor}, and {@link interpolateUsingIndex}.
+*/
+export const interpolateComplex = (t: number, values: (string | number | TypeColor)[], decimal = 3) => {
+ // Interpolate numbers
+ let isNumber = values.every(v => typeof v == "number");
+ if (isNumber)
+ return interpolateNumber(t, values as number[], decimal);
+
+ // Interpolate colors
+ let isColor = values.every(v => isValid(rgba(v ?? null)));
+ if (isColor)
+ return `rgba(${interpolateColor(t, values, decimal)})`;
+
+ // Interpolate complex values and strings
+ let isString = values.some(v => typeof v == "string");
+ if (isString) {
+ // Interpolate complex values like "10px solid red"
+ let isComplex = values.some(v => /(\d|\)|\w)\s/.test(trim(v as string)));
+ if (isComplex) {
+ return transpose(...values.map(ComplexStrtoArr))
+ .map((value) => interpolateComplex(t, value, decimal))
+ .join(" ");
+ }
+
+ // Interpolate strings with numbers, e.g. "5px"
+ let isLikeNumber = values.every(v => isNumberLike(v as string));
+ if (isLikeNumber)
+ return interpolateString(t, values as (number | string)[], decimal);
+
+ // Interpolate pure strings, e.g. "inherit", "solid", etc...
+ else return interpolateUsingIndex(t, values as string[]);
+ }
+};
+
+/**
+ * Custom Easing has 3 properties they are `easing` (all the easings from [#easing](#easing) are supported on top of custom easing functions, like spring, bounce, etc...), `numPoints` (the size of the Array the Custom Easing function should create), and `decimal` (the number of decimal places of the values within said Array).
+ *
+ * | Properties | Default Value |
+ * | ----------- | ----------------------- |
+ * | `easing` | `spring(1, 100, 10, 0)` |
+ * | `numPoints` | `50` |
+ * | `decimal` | `3` |
+ */
+export type TypeCustomEasingOptions = {
+ /**
+ *
+ * By default, Custom Easing support easing functions, in the form,
+ *
+ * | constant | accelerate | decelerate | accelerate-decelerate | decelerate-accelerate |
+ * | :--------- | :----------------- | :------------- | :-------------------- | :-------------------- |
+ * | linear | ease-in / in | ease-out / out | ease-in-out / in-out | ease-out-in / out-in |
+ * | ease | in-sine | out-sine | in-out-sine | out-in-sine |
+ * | steps | in-quad | out-quad | in-out-quad | out-in-quad |
+ * | step-start | in-cubic | out-cubic | in-out-cubic | out-in-cubic |
+ * | step-end | in-quart | out-quart | in-out-quart | out-in-quart |
+ * | | in-quint | out-quint | in-out-quint | out-in-quint |
+ * | | in-expo | out-expo | in-out-expo | out-in-expo |
+ * | | in-circ | out-circ | in-out-circ | out-in-circ |
+ * | | in-back | out-back | in-out-back | out-in-back |
+ * | | in-bounce | out-bounce | in-out-bounce | out-in-bounce |
+ * | | in-elastic | out-elastic | in-out-elastic | out-in-elastic |
+ * | | spring / spring-in | spring-out | spring-in-out | spring-out-in |
+ *
+ * All **Elastic** easing's can be configured using theses parameters,
+ *
+ * `*-elastic(amplitude, period)`
+ *
+ * Each parameter comes with these defaults
+ *
+ * | Parameter | Default Value |
+ * | --------- | ------------- |
+ * | amplitude | `1` |
+ * | period | `0.5` |
+ *
+ * ***
+ *
+ * All **Spring** easing's can be configured using theses parameters,
+ *
+ * `spring-*(mass, stiffness, damping, velocity)`
+ *
+ * Each parameter comes with these defaults
+ *
+ * | Parameter | Default Value |
+ * | --------- | ------------- |
+ * | mass | `1` |
+ * | stiffness | `100` |
+ * | damping | `10` |
+ * | velocity | `0` |
+ *
+ * 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**: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`_
+ *
+ */
+ easing?: string | TypeEasingFunction,
+ numPoints?: number,
+ decimal?: number,
+ duration?: number
+};
+
+/**
+ * returns a CustomEasingOptions object from a easing "string", or function
+ */
+export const CustomEasingOptions = (options: TypeCustomEasingOptions | string | TypeEasingFunction = {}) => {
+ let isEasing = typeof options == "string" || typeof options == "function";
+ let {
+ easing = "spring(1, 100, 10, 0)",
+ numPoints = 100,
+ decimal = 3,
+ duration
+ } = (isEasing ? { easing: options } : options) as TypeCustomEasingOptions;
+ return { easing, numPoints, decimal, duration };
+}
+
+/**
+ Cache calculated tween points for commonly used easing functions
+*/
+export const TweenCache = new Map();
+
+/**
+ * Create an Array of tween points using easing functions.
+ * The array is `numPoints` large, which is by default 50.
+ * Easing function can be custom defined, so, instead of string you can use functions,
+ * e.g.
+ * ```ts
+ * tweenPts({
+ * easing: t => t,
+ * numPoints: 50
+ * })
+ * ```
+
+ Based on https://github.com/w3c/csswg-drafts/issues/229#issuecomment-861415901
+*/
+export const EasingPts = ({ easing, numPoints, duration }: TypeCustomEasingOptions = {}): number[] => {
+ const pts = [];
+ const key = `${easing}${numPoints}`;
+ if (TweenCache.has(key)) return TweenCache.get(key);
+
+ const easingFunction = typeof easing == "function" ? easing : GetEasingFunction(easing as string);
+ const params = typeof easing == "function" ? [] : parseEasingParameters(easing);
+
+ for (let i = 0; i < numPoints; i++) {
+ pts[i] = easingFunction(i / (numPoints - 1), params, duration);
+ }
+
+ TweenCache.set(key, pts);
+ return pts;
+};
+
+/**
+ * Update the duration of `spring` and `spring-in` easings ot use optimal durations
+ */
+const updateDuration = (optionsObj: TypeCustomEasingOptions = {}) => {
+ if (typeof optionsObj.easing == "string") {
+ let easing = ComplexEasingSyntax(optionsObj.easing as string);
+ if (/(spring|spring-in)$/i.test(easing)) {
+ optionsObj.duration = getEasingDuration(optionsObj.easing);
+ }
+ }
+}
+
+/**
+ * Generates an Array of values using easing functions which in turn create the effect of custom easing.
+ * To use this properly make sure to set the easing animation option to "linear".
+ * Check out a demo of CustomEasing at
+ *
+ * Custom Easing has 3 properties they are `easing` (all the easings from {@link EasingFunctions} are supported on top of custom easing functions like spring, bounce, etc...), `numPoints` (the size of the Array the Custom Easing function should create), and `decimal` (the number of decimal places of the values within said Array).
+ *
+ * | Properties | Default Value |
+ * | ----------- | ----------------------- |
+ * | `easing` | `spring(1, 100, 10, 0)` |
+ * | `numPoints` | `50` |
+ * | `decimal` | `3` |
+ *
+ * By default, Custom Easing support easing functions, in the form,
+ *
+ * | constant | accelerate | decelerate | accelerate-decelerate | decelerate-accelerate |
+ * | :--------- | :----------------- | :------------- | :-------------------- | :-------------------- |
+ * | linear | ease-in / in | ease-out / out | ease-in-out / in-out | ease-out-in / out-in |
+ * | ease | in-sine | out-sine | in-out-sine | out-in-sine |
+ * | steps | in-quad | out-quad | in-out-quad | out-in-quad |
+ * | step-start | in-cubic | out-cubic | in-out-cubic | out-in-cubic |
+ * | step-end | in-quart | out-quart | in-out-quart | out-in-quart |
+ * | | in-quint | out-quint | in-out-quint | out-in-quint |
+ * | | in-expo | out-expo | in-out-expo | out-in-expo |
+ * | | in-circ | out-circ | in-out-circ | out-in-circ |
+ * | | in-back | out-back | in-out-back | out-in-back |
+ * | | in-bounce | out-bounce | in-out-bounce | out-in-bounce |
+ * | | in-elastic | out-elastic | in-out-elastic | out-in-elastic |
+ * | | spring / spring-in | spring-out | spring-in-out | spring-out-in |
+ *
+ * All **Elastic** easing's can be configured using theses parameters,
+ *
+ * `*-elastic(amplitude, period)`
+ *
+ * Each parameter comes with these defaults
+ *
+ * | Parameter | Default Value |
+ * | --------- | ------------- |
+ * | amplitude | `1` |
+ * | period | `0.5` |
+ *
+ * ***
+ *
+ * All **Spring** easing's can be configured using theses parameters,
+ *
+ * `spring-*(mass, stiffness, damping, velocity)`
+ *
+ * Each parameter comes with these defaults
+ *
+ * | Parameter | Default Value |
+ * | --------- | ------------- |
+ * | mass | `1` |
+ * | stiffness | `100` |
+ * | damping | `10` |
+ * | velocity | `0` |
+ *
+ * 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**: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`_
+ *
+ * e.g.
+ * ```ts
+ * import { animate, CustomEasing, EaseOut, Quad } from "@okikio/animate";
+ * animate({
+ * target: "div",
+ *
+ * // Notice how only, the first value in the Array uses the "px" unit
+ * border: CustomEasing(["1px solid red", "3 dashed green", "2 solid black"], {
+ * // This is a custom easing function
+ * easing: EaseOut(Quad)
+ * }),
+ *
+ * translateX: CustomEasing([0, 250], {
+ * easing: "linear",
+ *
+ * // You can change the size of Array for the CustomEasing function to generate
+ * numPoints: 200,
+ *
+ * // The number of decimal places to round, final values in the generated Array
+ * decimal: 5,
+ * }),
+ *
+ * // You can set the easing without an object
+ * // Also, if units are detected in the values Array,
+ * // the unit of the first value in the values Array are
+ * // applied to other values in the values Array, even if they
+ * // have prior units
+ * rotate: CustomEasing(["0turn", 1, 0, 0.5], "out"),
+ * "background-color": CustomEasing(["#616aff", "white"]),
+ * easing: "linear"
+ * }),
+ *
+ * // TIP... Use linear easing for the proper effect
+ * easing: "linear"
+ * })
+ * ```
+*/
+export const CustomEasing = (values: (string | number)[], options: TypeCustomEasingOptions | string | TypeEasingFunction = {}) => {
+ let optionsObj = CustomEasingOptions(options);
+ updateDuration(optionsObj);
+
+ return EasingPts(optionsObj).map((t) =>
+ interpolateComplex(t, values, optionsObj.decimal)
+ );
+};
+
+/**
+ * Returns an array containing `[easing pts, duration]`, it's meant to be a self enclosed way to create spring easing.
+ * Springs have an optimal duration; using `getEasingDuration()` we are able to have the determine the optimal duration for a spring with given parameters.
+ *
+ * By default it will only give the optimal duration for `spring` or `spring-in` easing, this is to avoid infinite loops caused by the `getEasingDuration()` function.
+ *
+ * Internally the `SpringEasing` uses {@link CustomEasing}, read more on it, to understand how the `SpringEasing` function works.
+ *
+ * e.g.
+ * ```ts
+ * import { animate, SpringEasing } from "@okikio/animate";
+ *
+ * // `duration` is the optimal duration for the spring with the set parameters
+ * let [translateX, duration] = SpringEasing([0, 250], "spring(5, 100, 10, 1)");
+ * // or
+ * // `duration` is 5000 here
+ * let [translateX, duration] = SpringEasing([0, 250], {
+ * easing: "spring(5, 100, 10, 1)",
+ * numPoints: 50,
+ * duration: 5000,
+ * decimal: 3
+ * });
+ *
+ * animate({
+ * target: "div",
+ * translateX,
+ * duration
+ * });
+ * ```
+ */
+export const SpringEasing = (values: (string | number)[], options: TypeCustomEasingOptions = {}) => {
+ let optionsObj = CustomEasingOptions(options);
+
+ let { duration } = optionsObj;
+ updateDuration(optionsObj);
+
+ return [
+ CustomEasing(values, optionsObj),
+ isValid(duration) ? duration : optionsObj.duration
+ ]
+};
+
+/**
+ * Applies the same custom easings to all properties of the object and returns an object with each property having an array of custom eased values
+ *
+ * If you use the `spring` or `spring-in` easings it will also return the optimal duration as a key in the object it returns.
+ * If you set `duration` to a number, it will prioritize that `duration` over optimal duration given by the spring easings.
+ *
+ * Read more about {@link CustomEasing}
+ *
+ * e.g.
+ * ```ts
+ * import { animate, ApplyCustomEasing } from "@okikio/animate";
+ * animate({
+ * target: "div",
+ *
+ * ...ApplyCustomEasing({
+ * border: ["1px solid red", "3 dashed green", "2 solid black"],
+ * translateX: [0, 250],
+ * rotate: ["0turn", 1, 0, 0.5],
+ * "background-color": ["#616aff", "white"],
+ *
+ * // You don't need to enter any parameters, you can just use the default values
+ * easing: "spring",
+ *
+ * // You can change the size of Array for the CustomEasing function to generate
+ * numPoints: 200,
+ *
+ * // The number of decimal places to round, final values in the generated Array
+ * decimal: 5,
+ *
+ * // You can also set the duration from here.
+ * // When using spring animations, the duration you set here is not nesscary,
+ * // since by default springs will try to determine the most appropriate duration for the spring animation.
+ * // But the duration value here will override `spring` easings optimal duration value
+ * duration: 3000
+ * })
+ * })
+ * ```
+ */
+export const ApplyCustomEasing = (options: TypeCustomEasingOptions & { [key: string]: number | string | TypeEasingFunction | (number | string)[] } = {}) => {
+ let { easing, numPoints, decimal, duration, ...rest } = options;
+ let optionsObj = { easing, numPoints, decimal, duration };
+ updateDuration(optionsObj);
+
+ let properties = mapObject(rest, (value: (string | number)[]) => CustomEasing(value, optionsObj));
+
+ let durationObj = {};
+ if (isValid(duration)) durationObj = { duration };
+ else if (isValid(optionsObj.duration)) durationObj = { duration: optionsObj.duration };
+
+ return Object.assign({}, properties, durationObj);
+}
\ No newline at end of file
diff --git a/packages/animate/src/empty-tween.ts b/packages/animate/src/empty-tween.ts
new file mode 100644
index 0000000..0f1a035
--- /dev/null
+++ b/packages/animate/src/empty-tween.ts
@@ -0,0 +1,163 @@
+
+import { ApplyCustomEasing, ComplexEasingSyntax, EasingFunctionKeys, GetEasingFunction, interpolateComplex, TypeCustomEasingOptions, TypeEasingFunction } from "./custom-easing";
+import { Animate, parseOptions, ALL_TIMING_KEYS, EasingKeys, GetEase, getTargets } from "./animate";
+import { pick, omit, mapObject } from "./utils";
+
+import type { IAnimationOptions } from "./types";
+
+/** Keeps track of all the empty tween elements */
+export let UIDCount = 0;
+
+/** Creates a new empty tween element */
+export const createEmptyEl = () => {
+ let el = document.createElement("div");
+ el.id = `empty-animate-el-${UIDCount++}`;
+ el.style.setProperty("display", "none");
+ document.body.appendChild(el);
+ return el;
+}
+
+/** Extends {@link Animate} stop method, so, it automatically removes the target elements from the dom */
+export const DestroyableAnimate = class extends Animate {
+ constructor(options: IAnimationOptions = {}) {
+ super(options);
+ }
+
+ public stop() {
+ /** Detach element from DOM */
+ this.targets.forEach((target: HTMLElement) => target?.remove?.());
+ super.stop();
+ }
+}
+
+/**
+ * - create a empty new element,
+ * - attach it to the DOM,
+ * - animate the opacity of said element
+ * - You can then use the "update" event to watch for changes in opacity and
+ * use the opacity as a progress bar of values between 0 to 1
+*/
+export const tween = (options: IAnimationOptions & TypeCustomEasingOptions = {}) => {
+ let el = createEmptyEl();
+ let { target, easing, decimal, numPoints, ...optionsObj } = parseOptions(options) as IAnimationOptions & TypeCustomEasingOptions;
+ let AnimationOptions = pick(ALL_TIMING_KEYS, optionsObj) as IAnimationOptions;
+ let EasingFunction = easing as (string | string[] | TypeEasingFunction);
+
+ if (typeof easing == "string") {
+ let ease = ComplexEasingSyntax(easing);
+
+ if (EasingKeys.includes(ease) || ["linear", "steps", "step-start", "step-end"].includes(ease))
+ EasingFunction = GetEase(easing);
+ else if (EasingFunctionKeys.includes(ease))
+ EasingFunction = GetEasingFunction(easing);
+ else
+ EasingFunction = easing;
+ }
+
+ let opacityObj = typeof EasingFunction == "function" ? ApplyCustomEasing({
+ opacity: [0, 1],
+ easing: easing as (string | TypeEasingFunction),
+ decimal: decimal as number,
+ numPoints: numPoints as number
+ }) : { opacity: [0, 1], easing };
+
+ let animation = new DestroyableAnimate({
+ target: el,
+ ...opacityObj,
+ ...AnimationOptions
+ });
+
+ return animation;
+}
+
+/**
+ * Uses the change in opacity (from the {@link tween} function) to interpolate the value of other elements
+ *
+ * e.g.
+ * ```ts
+ * import { tweenAttr } from "@okikio/animate";
+ * import { interpolate } from "polymorph-js";
+ *
+ * let startPath = usingPolymorphPathEl.getAttribute("d");
+ * let endPath = "M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z";
+ *
+ * // This is an svg path interpolate function
+ * // If used in tandem with `tweenAttr`, you can create morphing animations
+ * let morph = interpolate([startPath, endPath], {
+ * addPoints: 0,
+ * origin: { x: 0, y: 0 },
+ * optimize: "fill",
+ * precision: 3
+ * });
+ *
+ * // `tweenAttr` supports all Animation Options.
+ * // The first argument in Animation Options callbacks are set to the progress of the animation beteen 0 and 1, while the other arguments are moved 1 right
+ *
+ * // So, animation options can look like this
+ * // `(progress: number, i: number, len: number, el: HTMLElement) => {
+ * // return progress;
+ * // }`
+ *
+ * tweenAttr({
+ * target: "svg path",
+ * d: progress => morph(progress)
+ * });
+ *
+ * // `tweenAttr` can automatically choose between custom easing functions and or normal easings
+ * tweenAttr({
+ * target: ".div",
+ * targets: ".el",
+ * width: 250,
+ * height: ["500px", 600],
+ * easing: "spring"
+ *
+ * // If you want to update styles instead of attributes,
+ * // you can change this to "style"
+ * }, "style");
+ * ```
+ *
+ * Read more about {@link tween}
+ */
+export const tweenAttr = (options: IAnimationOptions & TypeCustomEasingOptions = {}, type = "attribute") => {
+ let optionsObj = parseOptions(options) as IAnimationOptions & TypeCustomEasingOptions;
+ let Properties = omit([...ALL_TIMING_KEYS, "opacity", "decimal", "numPoints"], optionsObj);
+ let animation = tween(optionsObj);
+
+ let { target, targets } = optionsObj;
+ let targetArr = [...new Set([...getTargets(targets), ...getTargets(target)])];
+
+ try {
+ let len = targetArr.length;
+ let emptyEl = animation.targets.get(0) as HTMLElement;
+ let emptyElstyle = getComputedStyle(emptyEl);
+
+ targetArr.forEach((el: HTMLElement, i) => {
+ let styleObj = /style/i.test(type) ? getComputedStyle(el) : null;
+
+ mapObject(Properties, (tweenPts, name) => {
+ let intialValue = /style/i.test(type) ? styleObj?.getPropertyValue(name) : el.getAttribute(name);
+
+ animation.on("update", () => {
+ let progress = Number(emptyElstyle.getPropertyValue("opacity"));
+ let value: any;
+
+ if (typeof tweenPts == "function")
+ value = tweenPts(progress, i, len, el);
+ else
+ value = interpolateComplex(progress, Array.isArray(tweenPts) ? tweenPts : [intialValue, tweenPts], options.decimal);
+
+
+ if (/style/i.test(type))
+ (el as HTMLElement).style.setProperty(name, `` + value);
+ else
+ (el as HTMLElement).setAttribute(name, `` + value);
+ });
+ });
+ });
+ } catch (e) {
+ animation?.stopLoop();
+ console.error(e);
+ }
+
+ return animation;
+};
\ No newline at end of file
diff --git a/packages/animate/src/types.ts b/packages/animate/src/types.ts
index bd961dc..7f8fd46 100644
--- a/packages/animate/src/types.ts
+++ b/packages/animate/src/types.ts
@@ -63,18 +63,23 @@ export interface IAnimationOptions extends ICSSTransformableProperties {
* Read More about easings on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing)
*
*
- * | constant | accelerate | decelerate | accelerate-decelerate |
- * | :------- | :--------- | :--------- | :-------------------- |
- * | linear | in-cubic | out-cubic | in-out-cubic |
- * | ease | in-quart | out-quart | in-out-quart |
- * | | in-quint | out-quint | in-out-quint |
- * | | in-expo | out-expo | in-out-expo |
- * | | in-circ | out-circ | in-out-circ |
- * | | in-back | out-back | in-out-back |
+ * | constant | accelerate | decelerate | accelerate-decelerate |
+ * | :--------- | :----------- | :------------- | :-------------------- |
+ * | linear | ease-in / in | ease-out / out | ease-in-out / in-out |
+ * | ease | in-sine | out-sine | in-out-sine |
+ * | steps | in-quad | out-quad | in-out-quad |
+ * | step-start | in-cubic | out-cubic | in-out-cubic |
+ * | step-end | in-quart | out-quart | in-out-quart |
+ * | | in-quint | out-quint | in-out-quint |
+ * | | in-expo | out-expo | in-out-expo |
+ * | | in-circ | out-circ | in-out-circ |
+ * | | in-back | out-back | in-out-back |
*
* 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: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`*
*
* @example
* ```ts
@@ -85,6 +90,10 @@ export interface IAnimationOptions extends ICSSTransformableProperties {
*
* // or
* easing: "in-sine",
+ *
+ * // or
+ * easing: "inSine",
+ *
* transform: ["translate(0px)", "translate(500px)"],
* });
* ```
@@ -430,6 +439,20 @@ export interface IAnimationOptions extends ICSSTransformableProperties {
*/
keyframes?: TypeCSSLikeKeyframe | ICSSComputedTransformableProperties[] & Keyframe[] | object[] | TypeCallback,
+ /**
+ * The `composite` property of a `KeyframeEffect` resolves how an element's animation impacts its underlying property values.
+ *
+ * To understand these values, take the example of a `keyframeEffect` value of `blur(2)` working on an underlying property value of `blur(3)`.
+ * - `replace` - The keyframeEffect overrides the underlying value it is combined with: `blur(2)` replaces `blur(3)`.
+ * - `add` - The keyframeEffect is added to the underlying value with which it is combined (aka additive): `blur(2) blur(3)`.
+ * - `accumulate` - The keyframeEffect is accumulated on to the underlying value: `blur(5)`.
+ *
+ * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/composite)
+ *
+ * I recommend reading [web.dev](https://web.dev)'s article on [web-animations](https://web.dev/web-animations/#smoother-animations-with-composite-modes).
+ */
+ composite?: TypeCallback | string,
+
/**
* 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`.
*
@@ -448,7 +471,6 @@ export interface IAnimationOptions extends ICSSTransformableProperties {
* // etc...
* fill: "both", // This overrides fillMode
* iteration: 2, // This overrides loop
- * composite: "add"
* }
* });
* ```
diff --git a/packages/animate/src/utils.ts b/packages/animate/src/utils.ts
new file mode 100644
index 0000000..b6fe4e7
--- /dev/null
+++ b/packages/animate/src/utils.ts
@@ -0,0 +1,157 @@
+
+// TypeAnimationTarget
+/** Merges 2-dimensional Arrays into a single 1-dimensional array */
+export const flatten = (arr: any[]) => [].concat(...arr);
+
+/**
+ * Acts like array.map(...) but for functions
+ */
+ export const mapObject = (obj: object, fn: (value, key, obj) => any) => {
+ let keys = Object.keys(obj);
+ let key, value, result = {};
+ for (let i = 0, len = keys.length; i < len; i++) {
+ key = keys[i];
+ value = obj[key];
+ result[key] = fn(value, key, obj);
+ }
+
+ return result;
+};
+
+/** Converts values to strings */
+export const toStr = (input: any) => `` + input;
+
+/**
+ * Convert the input to an array
+ * For strings split them at commas
+ * For array do nothing
+ * For everything else wrap the input in an array
+ */
+export const toArr = (input: any): any[] => {
+ if (Array.isArray(input) || typeof input == "string") {
+ if (typeof input == "string") input = input.split(",");
+ return input;
+ }
+
+ return [input];
+}
+
+/**
+ * Checks if a value is valid/truthy; it counts empty arrays and strings as falsey,
+ * as well as null, undefined, and NaN, everything else is valid
+ *
+ * _**Note:** 0 counts as valid_
+ *
+ * @param value - anything
+ * @returns true or false
+ */
+export const isValid = (value: any) => {
+ if (Array.isArray(value) || typeof value == "string")
+ return Boolean(value.length);
+ return value != null && value != undefined && !Number.isNaN(value);
+}
+
+/** Convert a camelCase string to a dash-separated string (opposite of {@link camelCase}) */
+export const convertToDash = (str: string) => {
+ str = str.replace(/([A-Z])/g, letter => `-${letter.toLowerCase()}`);
+
+ // Remove first dash
+ return (str.charAt(0) == '-') ? str.substr(1) : str;
+}
+
+/** Convert a dash-separated string into camelCase strings (opposite of {@link convertToDash}) */
+export const camelCase = (str: string) => {
+ if (str.includes("--")) return str;
+ let result = `${str}`.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
+ return result;
+}
+
+/**
+ * Return a copy of the object without the keys specified in the keys argument
+ *
+ * @param keys - arrays of keys to remove from the object
+ * @param obj - the object in question
+ * @returns
+ * a copy of the object without certain keys
+ */
+ export const omit = (keys: string[], obj: { [key: string]: any }) => {
+ let arr = [...keys];
+ let rest = { ...obj };
+ while (arr.length) {
+ let { [arr.pop()]: omitted, ...remaining } = rest;
+ rest = remaining;
+ }
+ return rest;
+}
+
+/**
+ * Return a copy of the object with only the keys specified in the keys argument
+ *
+ * @param keys - arrays of keys to keep from the object
+ * @param obj - the object in question
+ * @returns
+ * a copy of the object with only certain keys
+ */
+export const pick = (keys: string[], obj: { [key: string]: any }) => {
+ let arr = [...keys];
+ let rest = {};
+
+ for (let key of arr) {
+ if (isValid(obj[key]))
+ rest[key] = obj[key];
+ }
+
+ return rest;
+}
+
+/**
+ * Flips the rows and columns of 2-dimensional arrays
+ *
+ * Read more on [underscorejs.org](https://underscorejs.org/#zip) & [lodash.com](https://lodash.com/docs/4.17.15#zip)
+ *
+ * @example
+ * ```ts
+ * transpose(
+ * ['moe', 'larry', 'curly'],
+ * [30, 40, 50],
+ * [true, false, false]
+ * );
+ * // [
+ * // ["moe", 30, true],
+ * // ["larry", 40, false],
+ * // ["curly", 50, false]
+ * // ]
+ * ```
+ * @param [...args] - the arrays to process as a set of arguments
+ * @returns
+ * returns the new array of grouped elements
+ */
+// (TypeSingleValueCSSProperty | TypeSingleValueCSSProperty[])[]
+export const transpose = (...args: (any | any[])[]) => {
+ let largestArrLen = 0;
+ args = args.map(arr => {
+ // Convert all values in arrays to an array
+ // This ensures that `arrays` is an array of arrays
+ let result = toArr(arr);
+
+ // Finds the largest array
+ let len = result.length;
+ if (len > largestArrLen) largestArrLen = len;
+ return result;
+ });
+
+ // Flip the rows and columns of arrays
+ let result = [];
+ let len = args.length;
+ for (let col = 0; col < largestArrLen; col++) {
+ result[col] = [];
+
+ for (let row = 0; row < len; row++) {
+ let val = args[row][col];
+ if (isValid(val))
+ result[col][row] = val;
+ }
+ }
+
+ return result;
+}