Middleware

Tweening can only work between two numbers. For example, imagine we want to tween from 0 to 1. At 80% completion (of a linear tween) the resulting value would be 0.8.

How, though, do we tween from a fill value of red to #E54?

Enter Middleware 💪.

In Wilderness, Middleware is just a fancy way to say "some functions".

The role of each Middleware is to turn non-numeric values (untweenable) into numeric values (tweenable) before a tween is carried out. Then, after a tween has been performed, to return those values back to their initial format.

Wilderness ships with two Middlewares.

  • 🎨 Color Middleware – allows for the tweening of color strings. e.g. #E54.
  • 📐 Unit Middleware – allows for the tweening of unit strings. e.g. 50px.

These are both enabled by default on every Timeline.

Enable/disable Middleware

Middleware can be enabled or disabled on a Timeline by Timeline basis.

The timeline function takes a final options argument. This options object can take an optional middleware property, whose value is an array of Middlewares to enable.


import { shape, timeline, colorMiddleware } from 'wilderness'

const keyframe1 = { shape: 'circle', cx: 5, cy: 5, r: 3, fill: 'red' }
const keyframe2 = { shape: 'circle', cx: 5, cy: 5, r: 3, fill: '#E54' }

const morph = shape(keyframe1, keyframe2)

const animation = timeline(morph, {
  Middleware: [ colorMiddleware ]
})
    

If no middleware property is defined then by default both color and unit Middleware will be enabled.

To remove these default Middlewares we can simply pass an empty array to middleware.

Custom Middleware

It's simple to create our own Middleware.

Each Middleware must have three named exports.

  1. name a unique string.
  2. input a function that transforms non-numeric values to numeric values pre-tween.
  3. output a function that reverts transformed values back to their initial format post-tween.

For a detailed example, take a look at how the built in Color Middleware works.

We mention above that Middleware is used to transform non-numeric values to numeric values for tweening. However, there is no technical reason as to why our Middleware couldn't manipulate numeric values instead.