Full Code of michaelvillar/dynamics.js for AI

master c82261d09309 cached
6 files
64.6 KB
19.8k tokens
1 requests
Download .txt
Repository: michaelvillar/dynamics.js
Branch: master
Commit: c82261d09309
Files: 6
Total size: 64.6 KB

Directory structure:
gitextract_khmysplw/

├── .gitignore
├── .npmignore
├── README.md
├── package.json
├── src/
│   └── dynamics.coffee
└── test/
    └── dynamics.coffee

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
lib
node_modules


================================================
FILE: .npmignore
================================================


================================================
FILE: README.md
================================================
# Dynamics.js
Dynamics.js is a JavaScript library to create physics-based animations

To see some demos, check out [dynamicsjs.com](http://dynamicsjs.com).

## Usage
Download:
- [GitHub releases](https://github.com/michaelvillar/dynamics.js/releases)
- [npm](https://www.npmjs.com/package/dynamics.js): `npm install dynamics.js`
- bower: `bower install dynamics.js`

Include `dynamics.js` into your page:
```html
<script src="dynamics.js"></script>
```
You can animate CSS properties of any DOM element.
```javascript
var el = document.getElementById("logo")
dynamics.animate(el, {
  translateX: 350,
  scale: 2,
  opacity: 0.5
}, {
  type: dynamics.spring,
  frequency: 200,
  friction: 200,
  duration: 1500
})
```

You also can animate SVG properties.
```javascript
var path = document.querySelector("path")
dynamics.animate(path, {
  d: "M0,0 L0,100 L100,50 L0,0 Z",
  fill: "#FF0000",
  rotateZ: 45,
  // rotateCX and rotateCY are the center of the rotation
  rotateCX: 100,
  rotateCY: 100
}, {
  friction: 800
})
```

And any JavaScript object.
```javascript
var o = {
  number: 10,
  color: "#FFFFFF",
  string: "10deg",
  array: [ 1, 10 ]
}
dynamics.animate(o, {
  number: 20,
  color: "#000000",
  string: "90deg",
  array: [-9, 99 ]
})
```

## Reference
### dynamics.animate(el, properties, options)
Animates an element to the properties with the animation options.
- `el` is a DOM element, a JavaScript object or an Array of elements
- `properties` is an object of the properties/values you want to animate
- `options` is an object representing the animation
  - `type` is the [animation type](#dynamics-and-properties): `dynamics.spring`, `dynamics.easeInOut`,... (default: `dynamics.easeInOut`)
  - `frequency`, `friction`, `bounciness`,... are specific to the animation type you are using
  - `duration` is in milliseconds (default: `1000`)
  - `delay` is in milliseconds (default: `0`)
  - `complete` (optional) is the completion callback
  - `change` (optional) is called at every change. Two arguments are passed to the function. `function(el, progress)`
    - `el` is the element it's animating
    - `progress` is the progress of the animation between 0 and 1

### dynamics.stop(el)
Stops the animation applied on the element

### dynamics.css(el, properties)
This is applying the CSS properties to your element with the correct browser prefixes.
- `el` is a DOM element
- `properties` is an object of the CSS properties

### dynamics.setTimeout(fn, delay)
Dynamics.js has its own `setTimeout`. The reason is that `requestAnimationFrame` and `setTimeout` have different behaviors. In most browsers, `requestAnimationFrame` will not run in a background tab while `setTimeout` will. This can cause a lot of problems while using `setTimeout` along your animations. I suggest you use Dynamics's `setTimeout` and `clearTimeout` to handle these scenarios.
- `fn` is the callback
- `delay` is in milliseconds

Returns a unique id

### dynamics.clearTimeout(id)
Clears a timeout that was defined earlier
- `id` is the timeout id

### dynamics.toggleSlow()
Toggle a debug mode to slow down every animations and timeouts.
This is useful for development mode to tweak your animation.
This can be activated using `Shift-Control-D` in the browser.

## Dynamics and properties
### dynamics.spring
- `frequency` default is 300
- `friction` default is 200
- `anticipationSize` (optional)
- `anticipationStrength` (optional)

### dynamics.bounce
- `frequency` default is 300
- `friction` default is 200

### dynamics.forceWithGravity and dynamics.gravity
- `bounciness` default is 400
- `elasticity` default is 200

### dynamics.easeInOut, dynamics.easeIn and dynamics.easeOut
- `friction` default is 500

### dynamics.linear
No properties

### dynamics.bezier
- `points` array of points and control points

The easiest way to output this kind of array is to use the [curve creator](http://dynamicsjs.com). Here is an example:
```javascript
[{"x":0,"y":0,"cp":[{"x":0.2,"y":0}]},
 {"x":0.5,"y":-0.4,"cp":[{"x":0.4,"y":-0.4},{"x":0.8,"y":-0.4}]},
 {"x":1,"y":1,"cp":[{"x":0.8,"y":1}]}]
```

## Contributing
Compile: `npm run build` or `npm run build:watch`

Run tests: `npm test`

## Browser Support
Working on
- Safari 7+
- Firefox 35+
- Chrome 34+
- IE10+

## Sylvester
Some code from Sylvester.js has been used (part of Vector and Matrix).

## License
The MIT License (MIT)

Copyright (c) 2015 Michael Villar

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: package.json
================================================
{
  "name": "dynamics.js",
  "title": "Dynamics.js",
  "description": "Javascript library to create physics-related animations",
  "version": "1.1.5",
  "homepage": "http://dynamicsjs.com",
  "author": "Michael Villar <me@michaelvillar.com> (http://twitter.com/michaelvillar)",
  "repository": {
    "type": "git",
    "url": "https://github.com/michaelvillar/dynamics.js"
  },
  "devDependencies": {
    "coffee-script": "1.7.1",
    "uglify-js": "2.4.14",
    "jsdom": "3.x.x",
    "mocha-jsdom": "0.4.0",
    "chai": "3.0.0",
    "mocha": "2.2.5"
  },
  "scripts": {
    "test": "mocha --compilers coffee:coffee-script/register",
    "build": "coffee -c -o ./lib/ ./src/dynamics.coffee && ./node_modules/uglify-js/bin/uglifyjs ./lib/dynamics.js -m -c -o ./lib/dynamics.min.js",
    "build:watch": "coffee -w -c -o ./lib/ ./src/dynamics.coffee",
    "prepublish": "npm run build"
  },
  "bugs": {
    "url": "https://github.com/michaelvillar/dynamics.js/issues"
  },
  "main": "lib/dynamics.js",
  "directories": {
    "test": "test"
  },
  "keywords": [
    "animation",
    "javascript",
    "requestAnimationFrame",
    "spring",
    "physic"
  ],
  "license": "MIT"
}


================================================
FILE: src/dynamics.coffee
================================================
# Visibility change
isDocumentVisible = ->
  document.visibilityState == "visible" || dynamics.tests?

observeVisibilityChange = (() ->
  fns = []
  document?.addEventListener("visibilitychange", ->
    for fn in fns
      fn(isDocumentVisible())
  )
  (fn) ->
    fns.push(fn)
)()

# Object helpers
# Not deep clone and not using JSON.stringify/JSON.parse because
# We want to keep functions
clone = (o) ->
  newO = {}
  for k, v of o
    newO[k] = v
  newO

# Caching
cacheFn = (func) ->
  data = {}
  ->
    key = ""
    for k in arguments
      key += k.toString() + ","
    result = data[key]
    unless result
      data[key] = result = func.apply(this, arguments)
    result

# Make a function accept array or single objects for the first argument
makeArrayFn = (fn) ->
  (el) ->
    if el instanceof Array or el instanceof NodeList or el instanceof HTMLCollection
      res = for i in [0...el.length]
        args = Array.prototype.slice.call(arguments, 1)
        args.splice(0, 0, el[i])
        fn.apply(this, args)
      return res
    fn.apply(this, arguments)

# Properties Helpers
applyDefaults = (options, defaults) ->
  for k, v of defaults
    options[k] ?= v

applyFrame = (el, properties) ->
  if(el.style?)
    applyProperties(el, properties)
  else
    for k, v of properties
      el[k] = v.format()

applyProperties = (el, properties) ->
  properties = parseProperties(properties)
  transforms = []
  isSVG = isSVGElement(el)
  for k, v of properties
    if transformProperties.contains(k)
      transforms.push([k, v])
    else
      if v.format?
        v = v.format()
      if typeof(v) == 'number'
        v = "#{v}#{unitForProperty(k, v)}"
      if el.hasAttribute? && el.hasAttribute(k)
        el.setAttribute(k, v)
      else if el.style?
        el.style[propertyWithPrefix(k)] = v
      if k of el
        el[k] = v

  if transforms.length > 0
    if isSVG
      matrix = new Matrix2D()
      matrix.applyProperties(transforms)
      el.setAttribute("transform", matrix.decompose().format())
    else
      v = (transforms.map (transform) ->
        transformValueForProperty(transform[0], transform[1])
      ).join(" ")
      el.style[propertyWithPrefix("transform")] = v

isSVGElement = (el) ->
  if SVGElement? and SVGSVGElement?
    el instanceof SVGElement && !(el instanceof SVGSVGElement)
  else
    dynamics.tests?.isSVG?(el) ? false

# Math
roundf = (v, decimal) ->
  d = Math.pow(10, decimal)
  return Math.round(v * d) / d

# Set
class Set
  constructor: (array) ->
    @obj = {}
    for v in array
      @obj[v] = 1

  contains: (v) ->
    return @obj[v] == 1

# String Helpers
toDashed = (str) ->
  return str.replace(/([A-Z])/g, ($1) -> "-" + $1.toLowerCase())

# CSS Helpers
pxProperties = new Set('marginTop,marginLeft,marginBottom,marginRight,paddingTop,paddingLeft,paddingBottom,paddingRight,top,left,bottom,right,translateX,translateY,translateZ,perspectiveX,perspectiveY,perspectiveZ,width,height,maxWidth,maxHeight,minWidth,minHeight,borderRadius'.split(','))
degProperties = new Set('rotate,rotateX,rotateY,rotateZ,skew,skewX,skewY,skewZ'.split(','))
transformProperties = new Set('translate,translateX,translateY,translateZ,scale,scaleX,scaleY,scaleZ,rotate,rotateX,rotateY,rotateZ,rotateC,rotateCX,rotateCY,skew,skewX,skewY,skewZ,perspective'.split(','))
svgProperties = new Set('accent-height,ascent,azimuth,baseFrequency,baseline-shift,bias,cx,cy,d,diffuseConstant,divisor,dx,dy,elevation,filterRes,fx,fy,gradientTransform,height,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,letter-spacing,limitingConeAngle,markerHeight,markerWidth,numOctaves,order,overline-position,overline-thickness,pathLength,points,pointsAtX,pointsAtY,pointsAtZ,r,radius,rx,ry,seed,specularConstant,specularExponent,stdDeviation,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,surfaceScale,target,targetX,targetY,transform,underline-position,underline-thickness,viewBox,width,x,x1,x2,y,y1,y2,z'.split(','))

unitForProperty = (k, v) ->
  return '' unless typeof v == 'number'
  if pxProperties.contains(k)
    return 'px'
  else if degProperties.contains(k)
    return 'deg'
  ''

transformValueForProperty = (k, v) ->
  match = "#{v}".match(/^([0-9.-]*)([^0-9]*)$/)
  if match?
    v = match[1]
    unit = match[2]
  else
    v = parseFloat(v)

  v = roundf(parseFloat(v), 10)

  if !unit? or unit == ""
    unit = unitForProperty(k, v)

  "#{k}(#{v}#{unit})"

parseProperties = (properties) ->
  parsed = {}
  for property, value of properties
    if transformProperties.contains(property)
      match = property.match(/(translate|rotateC|rotate|skew|scale|perspective)(X|Y|Z|)/)
      if match and match[2].length > 0
        parsed[property] = value
      else
        for axis in ['X', 'Y', 'Z']
          parsed[match[1] + axis] = value
    else
      parsed[property] = value
  parsed

defaultValueForKey = (key) ->
  v = if key == 'opacity' then 1 else 0
  "#{v}#{unitForProperty(key, v)}"

getCurrentProperties = (el, keys) ->
  properties = {}
  isSVG = isSVGElement(el)
  if el.style?
    style = window.getComputedStyle(el, null)
    for key in keys
      if transformProperties.contains(key)
        unless properties['transform']?
          if isSVG
            matrix = new Matrix2D(el.transform.baseVal.consolidate()?.matrix)
          else
            matrix = Matrix.fromTransform(style[propertyWithPrefix('transform')])
          properties['transform'] = matrix.decompose()
      else
        if el.hasAttribute? && el.hasAttribute(key)
          v = el.getAttribute(key)
        else if key of el
          v = el[key]
        else
          v = style[key]

        if (!v? or key is 'd') && svgProperties.contains(key)
          v = el.getAttribute(key)
        if v == "" or !v?
          v = defaultValueForKey(key)
        properties[key] = createInterpolable(v)
  else
    for key in keys
      properties[key] = createInterpolable(el[key])

  addUnitsToNumberInterpolables(el, properties)

  properties

addUnitsToNumberInterpolables = (el, properties) ->
  for k, interpolable of properties
    if interpolable instanceof InterpolableNumber && el.style? && k of el.style
      interpolable = new InterpolableString([
        interpolable,
        unitForProperty(k, 0),
      ])
    properties[k] = interpolable
  properties

# Interpolable
createInterpolable = (value) ->
  klasses = [InterpolableArray, InterpolableObject, InterpolableNumber, InterpolableString]
  for klass in klasses
    interpolable = klass.create(value)
    return interpolable if interpolable?
  null

class InterpolableString
  constructor: (@parts) ->

  interpolate: (endInterpolable, t) =>
    start = @parts
    end = endInterpolable.parts
    newParts = []
    for i in [0...Math.min(start.length, end.length)]
      if start[i].interpolate?
        newParts.push(start[i].interpolate(end[i], t))
      else
        newParts.push(start[i])
    new InterpolableString(newParts)

  format: =>
    parts = @parts.map (val) ->
      if val.format?
        val.format()
      else
        val
    parts.join('')

  @create: (value) =>
    value = "#{value}"
    matches = []

    types = [
      {
        re: /(#[a-f\d]{3,6})/ig,
        klass: InterpolableColor,
        parse: (v) -> v,
      },
      {
        re: /(rgba?\([0-9.]*, ?[0-9.]*, ?[0-9.]*(?:, ?[0-9.]*)?\))/ig,
        klass: InterpolableColor,
        parse: (v) -> v,
      },
      {
        re: /([-+]?[\d.]+)/ig,
        klass: InterpolableNumber,
        parse: parseFloat,
      },
    ]

    for type in types
      re = type.re
      while match = re.exec(value)
        matches.push({
          index: match.index,
          length: match[1].length,
          interpolable: type.klass.create(type.parse(match[1])),
        })

    matches = matches.sort((a, b) ->
      if a.index > b.index
        1
      else
        -1
    )

    parts = []
    index = 0
    for match in matches
      continue if match.index < index
      if match.index > index
        parts.push(value.substring(index, match.index))
      parts.push(match.interpolable)
      index = match.index + match.length
    if index < value.length
      parts.push(value.substring(index))

    return new InterpolableString(parts)

class InterpolableObject
  constructor: (obj) ->
    @obj = obj

  interpolate: (endInterpolable, t) =>
    start = @obj
    end = endInterpolable.obj
    newObj = {}
    for k, v of start
      if v.interpolate?
        newObj[k] = v.interpolate(end[k], t)
      else
        newObj[k] = v
    new InterpolableObject(newObj)

  format: =>
    @obj

  @create: (value) =>
    if value instanceof Object
      obj = {}
      for k, v of value
        obj[k] = createInterpolable(v)
      return new InterpolableObject(obj)
    null

class InterpolableNumber
  constructor: (value) ->
    @value = parseFloat(value)

  interpolate: (endInterpolable, t) =>
    start = @value
    end = endInterpolable.value
    new InterpolableNumber((end - start) * t + start)

  format: =>
    roundf(@value, 5)

  @create: (value) =>
    return new InterpolableNumber(value) if typeof(value) == 'number'
    null

class InterpolableArray
  constructor: (@values) ->

  interpolate: (endInterpolable, t) =>
    start = @values
    end = endInterpolable.values
    newValues = []
    for i in [0...Math.min(start.length, end.length)]
      if start[i].interpolate?
        newValues.push(start[i].interpolate(end[i], t))
      else
        newValues.push(start[i])
    new InterpolableArray(newValues)

  format: =>
    @values.map (val) ->
      if val.format?
        val.format()
      else
        val

  @createFromArray: (arr) =>
    values = arr.map (val) ->
      createInterpolable(val) || val
    values = values.filter (val) ->
      val?
    return new InterpolableArray(values)

  @create: (value) =>
    return @createFromArray(value) if value instanceof Array
    null

class Color
  constructor: (@rgb={}, @format) ->

  @fromHex: (hex) ->
    hex3 = hex.match(/^#([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i)
    if hex3?
      hex = "##{hex3[1]}#{hex3[1]}#{hex3[2]}#{hex3[2]}#{hex3[3]}#{hex3[3]}"
    result = hex.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i)
    if result?
      return new Color({
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16),
        a: 1
      }, "hex")
    null

  @fromRgb: (rgb) ->
    match = rgb.match(/^rgba?\(([0-9.]*), ?([0-9.]*), ?([0-9.]*)(?:, ?([0-9.]*))?\)$/)
    if match?
      return new Color({
        r: parseFloat(match[1]),
        g: parseFloat(match[2]),
        b: parseFloat(match[3]),
        a: parseFloat(match[4] ? 1)
      }, if match[4]? then "rgba" else "rgb")
    null

  @componentToHex = (c) ->
    hex = c.toString(16);
    if hex.length == 1
      "0" + hex
    else
      hex

  toHex: =>
    "#" + Color.componentToHex(@rgb.r) + Color.componentToHex(@rgb.g) + Color.componentToHex(@rgb.b)

  toRgb: =>
    "rgb(#{@rgb.r}, #{@rgb.g}, #{@rgb.b})"

  toRgba: =>
    "rgba(#{@rgb.r}, #{@rgb.g}, #{@rgb.b}, #{@rgb.a})"

class InterpolableColor
  constructor: (@color) ->

  interpolate: (endInterpolable, t) =>
    start = @color
    end = endInterpolable.color
    rgb = {}
    for k in ['r', 'g', 'b']
      v = Math.round((end.rgb[k] - start.rgb[k]) * t + start.rgb[k])
      rgb[k] = Math.min(255, Math.max(0, v))
    k = "a"
    v = roundf((end.rgb[k] - start.rgb[k]) * t + start.rgb[k], 5)
    rgb[k] = Math.min(1, Math.max(0, v))
    new InterpolableColor(new Color(rgb, end.format))

  format: =>
    if @color.format == "hex"
      @color.toHex()
    else if @color.format == "rgb"
      @color.toRgb()
    else if @color.format == "rgba"
      @color.toRgba()

  @create: (value) =>
    return unless typeof(value) == "string"
    color = Color.fromHex(value) || Color.fromRgb(value)
    if color?
      return new InterpolableColor(color)
    null

# SVG Matrix2D
class DecomposedMatrix2D
  constructor: (@props) ->

  interpolate: (endMatrix, t) =>
    newProps = {}
    for k in ['translate', 'scale', 'rotate']
      newProps[k] = []
      for i in [0...@props[k].length]
        newProps[k][i] = (endMatrix.props[k][i] - @props[k][i]) * t + @props[k][i]
    for i in [1..2]
      newProps['rotate'][i] = endMatrix.props['rotate'][i]
    for k in ['skew']
      newProps[k] = (endMatrix.props[k] - @props[k]) * t + @props[k]

    new DecomposedMatrix2D(newProps)

  format: =>
    "translate(#{@props.translate.join(',')}) rotate(#{@props.rotate.join(',')})
     skewX(#{@props.skew}) scale(#{@props.scale.join(',')})"

  applyRotateCenter: (rotateC) =>
    m = baseSVG.createSVGMatrix()
    m = m.translate(rotateC[0], rotateC[1])
    m = m.rotate(@props.rotate[0])
    m = m.translate(-rotateC[0], -rotateC[1])
    m2d = new Matrix2D(m)

    negativeTranslate = m2d.decompose().props.translate
    for i in [0..1]
      @props.translate[i] -= negativeTranslate[i]

baseSVG = document?.createElementNS("http://www.w3.org/2000/svg", "svg")
class Matrix2D
  constructor: (@m) ->
    if !@m
      @m = baseSVG.createSVGMatrix()

  decompose: =>
    r0 = new Vector([@m.a, @m.b])
    r1 = new Vector([@m.c, @m.d])
    kx = r0.length()
    kz = r0.dot(r1)
    r0 = r0.normalize()
    ky = r1.combine(r0, 1, -kz).length()
    new DecomposedMatrix2D({
      translate: [@m.e, @m.f],
      rotate: [Math.atan2(@m.b, @m.a) * 180 / Math.PI, @rotateCX, @rotateCY],
      scale: [kx, ky],
      skew: kz / ky * 180 / Math.PI
    })

  applyProperties: (properties) =>
    hash = {}
    for props in properties
      hash[props[0]] = props[1]
    for k, v of hash
      if k == "translateX"
        @m = @m.translate(v, 0)
      else if k == "translateY"
        @m = @m.translate(0, v)
      else if k == "scaleX"
        @m = @m.scaleNonUniform(v, 1)
      else if k == "scaleY"
        @m = @m.scaleNonUniform(1, v)
      else if k == "rotateZ"
        @m = @m.rotate(v)
      else if k == "skewX"
        @m = @m.skewX(v)
      else if k == "skewY"
        @m = @m.skewY(v)

    @rotateCX = hash.rotateCX ? 0
    @rotateCY = hash.rotateCY ? 0

# Vector
# Some code has been ported from Sylvester.js https://github.com/jcoglan/sylvester
class Vector
  constructor: (@els) ->

  # Returns element i of the vector
  e: (i) =>
    return if (i < 1 || i > this.els.length) then null else this.els[i-1]

  # Returns the scalar product of the vector with the argument
  # Both vectors must have equal dimensionality
  dot: (vector) =>
    V = vector.els || vector
    product = 0
    n = this.els.length
    return null if n != V.length
    n += 1
    while --n
      product += this.els[n-1] * V[n-1]
    return product

  # Returns the vector product of the vector with the argument
  # Both vectors must have dimensionality 3
  cross: (vector) =>
    B = vector.els || vector
    return null if this.els.length != 3 || B.length != 3
    A = this.els
    return new Vector([
      (A[1] * B[2]) - (A[2] * B[1]),
      (A[2] * B[0]) - (A[0] * B[2]),
      (A[0] * B[1]) - (A[1] * B[0])
    ])

  length: =>
    a = 0
    for e in @els
      a += Math.pow(e, 2)
    Math.sqrt(a)

  normalize: =>
    length = @length()
    newElements = []
    for i, e of @els
      newElements[i] = e / length
    new Vector(newElements)

  combine: (b, ascl, bscl) =>
    result = []
    for i in [0...@els.length]
      result[i] = (ascl * @els[i]) + (bscl * b.els[i])
    new Vector(result)

# Matrix
class DecomposedMatrix
  interpolate: (decomposedB, t, only = null) =>
    decomposedA = @
    # New decomposedMatrix
    decomposed = new DecomposedMatrix

    # Linearly interpolate translate, scale, skew and perspective
    for k in [ 'translate', 'scale', 'skew', 'perspective' ]
      decomposed[k] = []
      for i in [0..decomposedA[k].length-1]
        if !only? or only.indexOf(k) > -1 or only.indexOf("#{k}#{['x','y','z'][i]}") > -1
          decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i]
        else
          decomposed[k][i] = decomposedA[k][i]

    if !only? or only.indexOf('rotate') != -1
      # Interpolate quaternion
      qa = decomposedA.quaternion
      qb = decomposedB.quaternion

      angle = qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3]

      if angle < 0.0
        for i in [0..3]
          qa[i] = -qa[i]
        angle = -angle

      if angle + 1.0 > .05
        if 1.0 - angle >= .05
          th = Math.acos(angle)
          invth = 1.0 / Math.sin(th)
          scale = Math.sin(th * (1.0 - t)) * invth
          invscale = Math.sin(th * t) * invth
        else
          scale = 1.0 - t
          invscale = t
      else
        qb[0] = -qa[1]
        qb[1] = qa[0]
        qb[2] = -qa[3]
        qb[3] = qa[2]
        scale = Math.sin(piDouble * (.5 - t))
        invscale = Math.sin(piDouble * t)

      decomposed.quaternion = []
      for i in [0..3]
        decomposed.quaternion[i] = qa[i] * scale + qb[i] * invscale
    else
      decomposed.quaternion = decomposedA.quaternion

    return decomposed

  format: =>
    @toMatrix().toString()

  toMatrix: =>
    decomposedMatrix = @
    matrix = Matrix.I(4)

    # apply perspective
    for i in [0..3]
      matrix.els[i][3] = decomposedMatrix.perspective[i]

    # apply rotation
    quaternion = decomposedMatrix.quaternion
    x = quaternion[0]
    y = quaternion[1]
    z = quaternion[2]
    w = quaternion[3]

    # apply skew
    # temp is a identity 4x4 matrix initially
    skew = decomposedMatrix.skew
    match = [[1,0],[2,0],[2,1]]
    for i in [2..0]
      if skew[i]
        temp = Matrix.I(4)
        temp.els[match[i][0]][match[i][1]] = skew[i]
        matrix = matrix.multiply(temp)

    # Construct a composite rotation matrix from the quaternion values
    matrix = matrix.multiply(new Matrix([[
      1 - 2 * (y * y + z * z),
      2 * (x * y - z * w),
      2 * (x * z + y * w),
      0
    ], [
      2 * (x * y + z * w),
      1 - 2 * (x * x + z * z),
      2 * (y * z - x * w),
      0
    ], [
      2 * (x * z - y * w),
      2 * (y * z + x * w),
      1 - 2 * (x * x + y * y),
      0
    ], [ 0, 0, 0, 1 ]]))

    # apply scale and translation
    for i in [0..2]
      for j in [0..2]
        matrix.els[i][j] *= decomposedMatrix.scale[i]
      matrix.els[3][i] = decomposedMatrix.translate[i]

    matrix

# Some code has been ported from Sylvester.js https://github.com/jcoglan/sylvester
class Matrix
  constructor: (@els) ->

  # Returns element (i,j) of the matrix
  e: (i,j) =>
    return null if (i < 1 || i > this.els.length || j < 1 || j > this.els[0].length)
    this.els[i-1][j-1]

  # Returns a copy of the matrix
  dup: () =>
    return new Matrix(this.els)

  # Returns the result of multiplying the matrix from the right by the argument.
  # If the argument is a scalar then just multiply all the elements. If the argument is
  # a vector, a vector is returned, which saves you having to remember calling
  # col(1) on the result.
  multiply: (matrix) =>
    returnVector = if matrix.modulus then true else false
    M = matrix.els || matrix
    M = new Matrix(M).els if (typeof(M[0][0]) == 'undefined')
    ni = this.els.length
    ki = ni
    kj = M[0].length
    cols = this.els[0].length
    elements = []
    ni += 1
    while (--ni)
      i = ki - ni
      elements[i] = []
      nj = kj
      nj += 1
      while (--nj)
        j = kj - nj
        sum = 0
        nc = cols
        nc += 1
        while (--nc)
          c = cols - nc
          sum += this.els[i][c] * M[c][j]
        elements[i][j] = sum

    M = new Matrix(elements)
    return if returnVector then M.col(1) else M

  # Returns the transpose of the matrix
  transpose: =>
    rows = this.els.length
    cols = this.els[0].length
    elements = []
    ni = cols
    ni += 1
    while (--ni)
      i = cols - ni
      elements[i] = []
      nj = rows
      nj += 1
      while (--nj)
        j = rows - nj
        elements[i][j] = this.els[j][i]
    return new Matrix(elements)

  # Make the matrix upper (right) triangular by Gaussian elimination.
  # This method only adds multiples of rows to other rows. No rows are
  # scaled up or switched, and the determinant is preserved.
  toRightTriangular: =>
    M = this.dup()
    n = this.els.length
    k = n
    kp = this.els[0].length
    while (--n)
      i = k - n
      if (M.els[i][i] == 0)
        for j in [i + 1...k]
          if (M.els[j][i] != 0)
            els = []
            np = kp
            np += 1
            while (--np)
              p = kp - np
              els.push(M.els[i][p] + M.els[j][p])
            M.els[i] = els
            break
      if (M.els[i][i] != 0)
        for j in [i + 1...k]
          multiplier = M.els[j][i] / M.els[i][i]
          els = []
          np = kp
          np += 1
          while (--np)
            p = kp - np
            # Elements with column numbers up to an including the number
            # of the row that we're subtracting can safely be set straight to
            # zero, since that's the point of this routine and it avoids having
            # to loop over and correct rounding errors later
            els.push(if p <= i then 0 else M.els[j][p] - M.els[i][p] * multiplier)
          M.els[j] = els
    return M

  # Returns the result of attaching the given argument to the right-hand side of the matrix
  augment: (matrix) =>
    M = matrix.els || matrix
    M = new Matrix(M).els if (typeof(M[0][0]) == 'undefined')
    T = this.dup()
    cols = T.els[0].length
    ni = T.els.length
    ki = ni
    kj = M[0].length
    return null if (ni != M.length)
    ni += 1
    while (--ni)
      i = ki - ni
      nj = kj
      nj += 1
      while (--nj)
        j = kj - nj
        T.els[i][cols + j] = M[i][j]

    return T

  # Returns the inverse (if one exists) using Gauss-Jordan
  inverse: =>
    ni = this.els.length
    ki = ni
    M = this.augment(Matrix.I(ni)).toRightTriangular()
    kp = M.els[0].length
    inverse_elements = []
    # Matrix is non-singular so there will be no zeros on the diagonal
    # Cycle through rows from last to first
    ni += 1
    while (--ni)
      i = ni - 1
      # First, normalise diagonal elements to 1
      els = []
      np = kp
      inverse_elements[i] = []
      divisor = M.els[i][i]
      np += 1
      while (--np)
        p = kp - np
        new_element = M.els[i][p] / divisor
        els.push(new_element)
        # Shuffle of the current row of the right hand side into the results
        # array as it will not be modified by later runs through this loop
        if (p >= ki)
          inverse_elements[i].push(new_element)

      M.els[i] = els
      # Then, subtract this row from those above it to
      # give the identity matrix on the left hand side
      for j in [0...i]
        els = []
        np = kp
        np += 1
        while (--np)
          p = kp - np
          els.push(M.els[j][p] - M.els[i][p] * M.els[j][i])
        M.els[j] = els

    return new Matrix(inverse_elements)

  @I = (n) ->
    els = []
    k = n
    n += 1
    while --n
      i = k - n
      els[i] = []
      nj = k
      nj += 1
      while --nj
        j = k - nj
        els[i][j] = if (i == j) then 1 else 0

    new Matrix(els)

  decompose: =>
    matrix = @
    translate = []
    scale = []
    skew = []
    quaternion = []
    perspective = []

    # Deep copy
    els = []
    for i in [0..3]
      els[i] = []
      for j in [0..3]
        els[i][j] = matrix.els[i][j]

    if (els[3][3] == 0)
      return false

    # Normalize the matrix.
    for i in [0..3]
      for j in [0..3]
        els[i][j] /= els[3][3]

    # perspectiveMatrix is used to solve for perspective, but it also provides
    # an easy way to test for singularity of the upper 3x3 component.
    perspectiveMatrix = matrix.dup()

    for i in [0..2]
      perspectiveMatrix.els[i][3] = 0
    perspectiveMatrix.els[3][3] = 1

    # Don't do this anymore, it would return false for scale(0)..
    # if perspectiveMatrix.determinant() == 0
    #   return false

    # First, isolate perspective.
    if els[0][3] != 0 || els[1][3] != 0 || els[2][3] != 0
      # rightHandSide is the right hand side of the equation.
      rightHandSide = new Vector(els[0..3][3])

      # Solve the equation by inverting perspectiveMatrix and multiplying
      # rightHandSide by the inverse.
      inversePerspectiveMatrix = perspectiveMatrix.inverse()
      transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose()
      perspective = transposedInversePerspectiveMatrix.multiply(rightHandSide).els

      # Clear the perspective partition
      for i in [0..2]
        els[i][3] = 0
      els[3][3] = 1
    else
      # No perspective.
      perspective = [0,0,0,1]

    # Next take care of translation
    for i in [0..2]
      translate[i] = els[3][i]
      els[3][i] = 0

    # Now get scale and shear. 'row' is a 3 element array of 3 component vectors
    row = []
    for i in [0..2]
      row[i] = new Vector(els[i][0..2])

    # Compute X scale factor and normalize first row.
    scale[0] = row[0].length()
    row[0] = row[0].normalize()

    # Compute XY shear factor and make 2nd row orthogonal to 1st.
    skew[0] = row[0].dot(row[1])
    row[1] = row[1].combine(row[0], 1.0, -skew[0])

    # Now, compute Y scale and normalize 2nd row.
    scale[1] = row[1].length()
    row[1] = row[1].normalize()
    skew[0] /= scale[1]

    # Compute XZ and YZ shears, orthogonalize 3rd row
    skew[1] = row[0].dot(row[2])
    row[2] = row[2].combine(row[0], 1.0, -skew[1])
    skew[2] = row[1].dot(row[2])
    row[2] = row[2].combine(row[1], 1.0, -skew[2])

    # Next, get Z scale and normalize 3rd row.
    scale[2] = row[2].length()
    row[2] = row[2].normalize()
    skew[1] /= scale[2]
    skew[2] /= scale[2]

    # At this point, the matrix (in rows) is orthonormal.
    # Check for a coordinate system flip.  If the determinant
    # is -1, then negate the matrix and the scaling factors.
    pdum3 = row[1].cross(row[2])
    if row[0].dot(pdum3) < 0
      for i in [0..2]
        scale[i] *= -1
        for j in [0..2]
          row[i].els[j] *= -1

    # Get element at row
    rowElement = (index, elementIndex) ->
      row[index].els[elementIndex]

    # Euler angles
    rotate = []
    rotate[1] = Math.asin(-rowElement(0, 2))
    if Math.cos(rotate[1]) != 0
      rotate[0] = Math.atan2(rowElement(1, 2), rowElement(2, 2))
      rotate[2] = Math.atan2(rowElement(0, 1), rowElement(0, 0))
    else
      rotate[0] = Math.atan2(-rowElement(2, 0), rowElement(1, 1))
      rotate[1] = 0

    # Now, get the rotations out
    t = rowElement(0, 0) + rowElement(1, 1) + rowElement(2, 2) + 1.0
    if t > 1e-4
      s = 0.5 / Math.sqrt(t)
      w = 0.25 / s
      x = (rowElement(2, 1) - rowElement(1, 2)) * s
      y = (rowElement(0, 2) - rowElement(2, 0)) * s
      z = (rowElement(1, 0) - rowElement(0, 1)) * s
    else if (rowElement(0, 0) > rowElement(1, 1)) && (rowElement(0, 0) > rowElement(2, 2))
      s = Math.sqrt(1.0 + rowElement(0, 0) - rowElement(1, 1) - rowElement(2, 2)) * 2.0
      x = 0.25 * s
      y = (rowElement(0, 1) + rowElement(1, 0)) / s
      z = (rowElement(0, 2) + rowElement(2, 0)) / s
      w = (rowElement(2, 1) - rowElement(1, 2)) / s
    else if rowElement(1, 1) > rowElement(2, 2)
      s = Math.sqrt(1.0 + rowElement(1, 1) - rowElement(0, 0) - rowElement(2, 2)) * 2.0
      x = (rowElement(0, 1) + rowElement(1, 0)) / s
      y = 0.25 * s
      z = (rowElement(1, 2) + rowElement(2, 1)) / s
      w = (rowElement(0, 2) - rowElement(2, 0)) / s
    else
      s = Math.sqrt(1.0 + rowElement(2, 2) - rowElement(0, 0) - rowElement(1, 1)) * 2.0
      x = (rowElement(0, 2) + rowElement(2, 0)) / s
      y = (rowElement(1, 2) + rowElement(2, 1)) / s
      z = 0.25 * s
      w = (rowElement(1, 0) - rowElement(0, 1)) / s

    quaternion = [x, y, z, w]

    result = new DecomposedMatrix
    result.translate = translate
    result.scale = scale
    result.skew = skew
    result.quaternion = quaternion
    result.perspective = perspective
    result.rotate = rotate

    for typeKey, type of result
      for k, v of type
        type[k] = 0 if isNaN(v)

    result

  toString: =>
    str = 'matrix3d('
    for i in [0..3]
      for j in [0..3]
        str += roundf(@els[i][j], 10)
        str += ',' unless i == 3 and j == 3
    str += ')'
    str

  @matrixForTransform: cacheFn (transform) ->
    matrixEl = document.createElement('div')
    matrixEl.style.position = 'absolute'
    matrixEl.style.visibility = 'hidden'
    matrixEl.style[propertyWithPrefix("transform")] = transform
    document.body.appendChild(matrixEl)
    style = window.getComputedStyle(matrixEl, null)
    result = style.transform ? style[propertyWithPrefix("transform")] ? dynamics.tests?.matrixForTransform(transform)
    document.body.removeChild(matrixEl)
    result

  @fromTransform: (transform) ->
    match = transform?.match /matrix3?d?\(([-0-9,e \.]*)\)/
    if match
      digits = match[1].split(',')
      digits = digits.map(parseFloat)
      if digits.length == 6
        # format: matrix(a, c, b, d, tx, ty)
        elements = [digits[0], digits[1], 0, 0, digits[2], digits[3], 0, 0, 0, 0, 1, 0, digits[4], digits[5], 0, 1]
      else
        elements = digits
    else
      elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]

    matrixElements = []
    for i in [0..3]
      matrixElements.push(elements.slice(i * 4,i * 4 + 4))
    new Matrix(matrixElements)

# Support
prefixFor = cacheFn (property) ->
  return '' if document.body.style[property] != undefined
  propArray = property.split('-')
  propertyName = ""
  for prop in propArray
    propertyName += prop.substring(0, 1).toUpperCase() + prop.substring(1)
  for prefix in [ "Webkit", "Moz", "ms" ]
    k = prefix + propertyName
    if document.body.style[k] != undefined
      return prefix
  ''
propertyWithPrefix = cacheFn (property) ->
  prefix = prefixFor(property)
  return "#{prefix}#{property.substring(0, 1).toUpperCase() + property.substring(1)}" if prefix == 'Moz'
  return "-#{prefix.toLowerCase()}-#{toDashed(property)}" if prefix != ''
  toDashed(property)

# Run loop
rAF = window?.requestAnimationFrame
animations = []
animationsTimeouts = []
slow = false
slowRatio = 1

window?.addEventListener 'keyup', (e) ->
  # Enable slow animations with ctrl+shift+D
  if e.keyCode == 68 and e.shiftKey and e.ctrlKey
    dynamics.toggleSlow()

if !rAF?
  lastTime = 0
  rAF = (callback) ->
    currTime = Date.now()
    timeToCall = Math.max(0, 16 - (currTime - lastTime))
    id = window.setTimeout ->
      callback(currTime + timeToCall)
    , timeToCall
    lastTime = currTime + timeToCall
    id

runLoopRunning = false
runLoopPaused = false
startRunLoop = ->
  unless runLoopRunning
    runLoopRunning = true
    rAF(runLoopTick)

runLoopTick = (t) ->
  if runLoopPaused
    rAF(runLoopTick)
    return

  # Animations
  toRemoveAnimations = []
  for animation in animations
    toRemoveAnimations.push(animation) unless animationTick(t, animation)
  animations = animations.filter (animation) ->
    toRemoveAnimations.indexOf(animation) == -1

  if animations.length == 0
    runLoopRunning = false
  else
    rAF(runLoopTick)

animationTick = (t, animation) ->
  animation.tStart ?= t
  tt = (t - animation.tStart) / animation.options.duration
  y = animation.curve(tt)

  properties = {}
  if tt >= 1
    if animation.curve.returnsToSelf
      properties = animation.properties.start
    else
      properties = animation.properties.end
  else
    for key, property of animation.properties.start
      properties[key] = interpolate(property, animation.properties.end[key], y)

  applyFrame(animation.el, properties)

  animation.options.change?(animation.el, Math.min(1, tt))
  if tt >= 1
    animation.options.complete?(animation.el)

  return tt < 1

interpolate = (start, end, y) ->
  if start? and start.interpolate?
    return start.interpolate(end, y)
  null

# Animations
startAnimation = (el, properties, options, timeoutId) ->
  if timeoutId?
    animationsTimeouts = animationsTimeouts.filter (timeout) ->
      return timeout.id != timeoutId

  dynamics.stop(el, { timeout: false })
  if !options.animated
    dynamics.css(el, properties)
    options.complete?(@)
    return
  startProperties = getCurrentProperties(el, Object.keys(properties))

  properties = parseProperties(properties)

  endProperties = {}
  transforms = []
  for k, v of properties
    if el.style? and transformProperties.contains(k)
      transforms.push([k, v])
    else
      endProperties[k] = createInterpolable(v)

  if transforms.length > 0
    isSVG = isSVGElement(el)
    if isSVG
      matrix = new Matrix2D()
      matrix.applyProperties(transforms)
    else
      v = (transforms.map (transform) ->
        transformValueForProperty(transform[0], transform[1])
      ).join(" ")
      matrix = Matrix.fromTransform(Matrix.matrixForTransform(v))
    endProperties['transform'] = matrix.decompose()

    if isSVG
      startProperties.transform.applyRotateCenter(
        [endProperties.transform.props.rotate[1], endProperties.transform.props.rotate[2]]
      )

  addUnitsToNumberInterpolables(el, endProperties)

  animations.push({
    el: el,
    properties: {
      start: startProperties,
      end: endProperties
    },
    options: options,
    curve: options.type.call(options.type, options)
  })
  startRunLoop()

# Timeouts
timeouts = []
timeoutLastId = 0

setRealTimeout = (timeout) ->
  return unless isDocumentVisible()
  # Because in iframe, rAF might not run directly even if tab is visible
  rAF(->
    # Timeout might have been cancelled already
    return if timeouts.indexOf(timeout) == -1
    timeout.realTimeoutId = setTimeout(->
      timeout.fn()
      cancelTimeout(timeout.id)
    , timeout.delay)
  )

addTimeout = (fn, delay) ->
  timeoutLastId += 1
  timeout = {
    id: timeoutLastId,
    tStart: Date.now(),
    fn: fn,
    delay: delay,
    originalDelay: delay
  }
  setRealTimeout(timeout)
  timeouts.push(timeout)
  timeoutLastId

cancelTimeout = (id) ->
  timeouts = timeouts.filter (timeout) ->
    if timeout.id == id && timeout.realTimeoutId
      clearTimeout(timeout.realTimeoutId)
    timeout.id != id

leftDelayForTimeout = (time, timeout) ->
  if time?
    consumedDelay = time - timeout.tStart
    timeout.originalDelay - consumedDelay
  else
    timeout.originalDelay

window?.addEventListener('unload', ->
  # This is a hack for Safari to fix the case where the user does back/forward
  # between this page. If this event is not listened to, it seems like safari is keeping
  # the javascript state but this cause problems with setTimeout/rAF
)

# Visibility change
# Need to pause rAF and timeouts
timeBeforeVisibilityChange = null
observeVisibilityChange (visible) ->
  runLoopPaused = !visible
  if !visible
    timeBeforeVisibilityChange = Date.now()

    for timeout in timeouts
      clearTimeout(timeout.realTimeoutId)
  else
    if runLoopRunning
      difference = Date.now() - timeBeforeVisibilityChange
      for animation in animations
        animation.tStart += difference if animation.tStart?

    for timeout in timeouts
      timeout.delay = leftDelayForTimeout(timeBeforeVisibilityChange, timeout)
      setRealTimeout(timeout)

    timeBeforeVisibilityChange = null

# Module
dynamics = {}

# Curves
dynamics.linear = ->
  (t) ->
    t

dynamics.spring = (options={}) ->
  applyDefaults(options, dynamics.spring.defaults)

  frequency = Math.max(1, options.frequency / 20)
  friction = Math.pow(20, options.friction / 100)
  s = options.anticipationSize / 1000
  decal = Math.max(0, s)

  # In case of anticipation
  A1 = (t) ->
    M = 0.8

    x0 = (s / (1 - s))
    x1 = 0

    b = (x0 - (M * x1)) / (x0 - x1)
    a = (M - b) / x0

    (a * t * options.anticipationStrength / 100) + b

  # Normal curve
  A2 = (t) ->
    Math.pow(friction / 10,-t) * (1 - t)

  (t) ->
    frictionT = (t / (1 - s)) - (s / (1 - s))

    if t < s
      yS = (s / (1 - s)) - (s / (1 - s))
      y0 = (0 / (1 - s)) - (s / (1 - s))
      b = Math.acos(1 / A1(yS))
      a = (Math.acos(1 / A1(y0)) - b) / (frequency * (-s))
      A = A1
    else
      A = A2

      b = 0
      a = 1

    At = A(frictionT)

    angle = frequency * (t - s) * a + b
    1 - (At * Math.cos(angle))

dynamics.bounce = (options={}) ->
  applyDefaults(options, dynamics.bounce.defaults)

  frequency = Math.max(1, options.frequency / 20)
  friction = Math.pow(20, options.friction / 100)
  A = (t) ->
    Math.pow(friction / 10,-t) * (1 - t)

  fn = (t) ->

    b = -3.14/2
    a = 1

    At = A(t)

    angle = frequency * t * a + b
    (At * Math.cos(angle))
  fn.returnsToSelf = true
  fn

dynamics.gravity = (options={}) ->
  applyDefaults(options, dynamics.gravity.defaults)

  bounciness = Math.min((options.bounciness / 1250), 0.8)
  elasticity = options.elasticity / 1000
  gravity = 100

  curves = []
  L = do ->
    b = Math.sqrt(2 / gravity)
    curve = { a: -b, b: b, H: 1 }
    if options.returnsToSelf
      curve.a = 0
      curve.b = curve.b * 2
    while curve.H > 0.001
      L = curve.b - curve.a
      curve = { a: curve.b, b: curve.b + L * bounciness, H: curve.H * bounciness * bounciness }
    curve.b

  getPointInCurve = (a, b, H, t) ->
    L = b - a
    t2 = (2 / L) * (t) - 1 - (a * 2 / L)
    c = t2 * t2 * H - H + 1
    c = 1 - c if options.returnsToSelf
    c

  # Create curves
  do ->
    b = Math.sqrt(2 / (gravity * L * L))
    curve = { a: -b, b: b, H: 1 }
    if options.returnsToSelf
      curve.a = 0
      curve.b = curve.b * 2
    curves.push curve
    L2 = L
    while curve.b < 1 and curve.H > 0.001
      L2 = curve.b - curve.a
      curve = { a: curve.b, b: curve.b + L2 * bounciness, H: curve.H * elasticity }
      curves.push curve

  fn = (t) ->
    i = 0
    curve = curves[i]
    while(!(t >= curve.a and t <= curve.b))
      i += 1
      curve = curves[i]
      break unless curve

    if !curve
      v = if options.returnsToSelf then 0 else 1
    else
      v = getPointInCurve(curve.a, curve.b, curve.H, t)
    v
  fn.returnsToSelf = options.returnsToSelf
  fn

dynamics.forceWithGravity = (options={}) ->
  applyDefaults(options, dynamics.forceWithGravity.defaults)
  options.returnsToSelf = true
  dynamics.gravity(options)

dynamics.bezier = do ->
  Bezier_ = (t, p0, p1, p2, p3) ->
    (Math.pow(1 - t, 3) * p0) + (3 * Math.pow(1 - t, 2) * t * p1) + (3 * (1 - t) * Math.pow(t, 2) * p2) + Math.pow(t, 3) * p3

  Bezier = (t, p0, p1, p2, p3) ->
    {
      x: Bezier_(t, p0.x, p1.x, p2.x, p3.x),
      y: Bezier_(t, p0.y, p1.y, p2.y, p3.y)
    }

  yForX = (xTarget, Bs, returnsToSelf) ->
    # Find the right Bezier curve first
    B = null
    for aB in Bs
      if xTarget >= aB(0).x and xTarget <= aB(1).x
        B = aB
      break if B != null

    unless B
      if returnsToSelf
        return 0
      else
        return 1

    # Find the percent with dichotomy
    xTolerance = 0.0001
    lower = 0
    upper = 1
    percent = (upper + lower) / 2

    x = B(percent).x
    i = 0

    while Math.abs(xTarget - x) > xTolerance and i < 100
      if xTarget > x
        lower = percent
      else
        upper = percent

      percent = (upper + lower) / 2
      x = B(percent).x
      i += 1

    # Returns y at this specific percent
    return B(percent).y

  # Actual bezier function
  (options={}) ->
    points = options.points

    # Init different curves
    Bs = do ->
      Bs = []
      for i of points
        k = parseInt(i)
        break if k >= points.length - 1
        ((pointA, pointB) ->
          B2 = (t) ->
            Bezier(t, pointA, pointA.cp[pointA.cp.length - 1], pointB.cp[0], pointB)
          Bs.push(B2)
        )(points[k], points[k + 1])
      Bs

    fn = (t) ->
      if t == 0
        return 0
      else if t == 1
        return 1
      else
        yForX(t, Bs, @returnsToSelf)
    fn.returnsToSelf = points[points.length - 1].y == 0
    fn

dynamics.easeInOut = (options={}) ->
  friction = options.friction ? dynamics.easeInOut.defaults.friction
  dynamics.bezier(points: [
    { x:0, y:0, cp:[{ x:0.92 - (friction / 1000), y:0 }] },
    { x:1, y:1, cp:[{ x:0.08 + (friction / 1000), y:1 }] }
  ])

dynamics.easeIn = (options={}) ->
  friction = options.friction ? dynamics.easeIn.defaults.friction
  dynamics.bezier(points: [
    { x:0, y:0, cp:[{ x:0.92 - (friction / 1000), y:0 }] },
    { x:1, y:1, cp:[{ x:1, y:1 }] }
  ])

dynamics.easeOut = (options={}) ->
  friction = options.friction ? dynamics.easeOut.defaults.friction
  dynamics.bezier(points: [
    { x:0, y:0, cp:[{ x:0, y:0 }] },
    { x:1, y:1, cp:[{ x:0.08 + (friction / 1000), y:1 }] }
  ])

# Default options
dynamics.spring.defaults =
  frequency: 300
  friction: 200
  anticipationSize: 0
  anticipationStrength: 0
dynamics.bounce.defaults =
  frequency: 300
  friction: 200
dynamics.forceWithGravity.defaults = dynamics.gravity.defaults =
  bounciness: 400
  elasticity: 200
dynamics.easeInOut.defaults = dynamics.easeIn.defaults = dynamics.easeOut.defaults =
  friction: 500

# CSS
dynamics.css = makeArrayFn (el, properties) ->
  applyProperties(el, properties, true)

# Animation
dynamics.animate = makeArrayFn (el, properties, options={}) ->
  options = clone(options)
  applyDefaults(options, {
    type: dynamics.easeInOut,
    duration: 1000,
    delay: 0,
    animated: true
  })
  options.duration = Math.max(0, options.duration * slowRatio)
  options.delay = Math.max(0, options.delay)

  if options.delay == 0
    startAnimation(el, properties, options)
  else
    id = dynamics.setTimeout ->
      startAnimation(el, properties, options, id)
    , options.delay
    animationsTimeouts.push({
      id: id,
      el: el
    })

dynamics.stop = makeArrayFn (el, options={}) ->
  options.timeout ?= true
  if options.timeout
    # Clear timeouts too
    animationsTimeouts = animationsTimeouts.filter (timeout) ->
      if timeout.el == el and (!options.filter? or options.filter(timeout))
        dynamics.clearTimeout(timeout.id)
        return false
      true

  animations = animations.filter (animation) ->
    animation.el != el

dynamics.setTimeout = (fn, delay) ->
  addTimeout(fn, delay * slowRatio)

dynamics.clearTimeout = (id) ->
  cancelTimeout(id)

dynamics.toggleSlow = ->
  slow = !slow
  if slow
    slowRatio = 3
  else
    slowRatio = 1
  console?.log?("dynamics.js: slow animations #{if slow then "enabled" else "disabled"}")

# CommonJS
if typeof module == "object" and typeof module.exports == "object"
  module.exports = dynamics
# AMD
else if typeof define == "function"
  define('dynamics', -> dynamics)
# Global
else
  window.dynamics = dynamics


================================================
FILE: test/dynamics.coffee
================================================
mocha = require('mocha')
jsdom = require('mocha-jsdom')
expect = require('chai').expect
assert = require('chai').assert
dynamics = require('../src/dynamics')

jsdom()

dynamics.tests =
  matrixForTransform: (transform) ->
    if transform == "translateX(50px) rotateZ(45deg)"
      return "matrix3d(0.7071067811865476, 0.7071067811865475, 0, 0, -0.7071067811865475, 0.7071067811865476, 0, 0, 0, 0, 1, 0, 50, 0, 0, 1)"

expectEqualMatrix3d = (a, b) ->
  r = /matrix3?d?\(([-0-9, \.]*)\)/
  argsA = a.match(r)?[1].split(',')
  argsB = b.match(r)?[1].split(',')
  for i in [0...argsA.length]
    expect(Math.abs(parseFloat(argsA[i]) - parseFloat(argsB[i]))).to.be.below(0.00001)

describe 'dynamics.css', ->
  it 'apply css to a DOM element', ->
    el = document.createElement('div')
    dynamics.css(el, {
      left: 0,
      top: "5px",
      backgroundColor: "#FF0000"
    })
    expect(el.style.left).eql('0px')
    expect(el.style.top).eql('5px')
    expect(el.style.backgroundColor).eql('rgb(255, 0, 0)')

  it 'apply transform to a DOM element', ->
    el = document.createElement('div')
    dynamics.css(el, {
      translateX: 10,
      translateY: "0px",
      translateZ: "25%",
      rotateZ: "90deg",
      rotateX: 45,
      skewX: 10,
      scale: 2
    })
    expect(el.style.transform).eql("translateX(10px) translateY(0px) translateZ(25%) rotateZ(90deg) rotateX(45deg) skewX(10deg) scaleX(2) scaleY(2) scaleZ(2)")

  it 'works with an array of DOM element', ->
    els = [
      document.createElement('div'),
      document.createElement('div')
    ]
    dynamics.css(els, {
      left: "10px"
    })
    expect(els[0].style.left).eql('10px')
    expect(els[1].style.left).eql('10px')

describe 'dynamics.animate', ->
  it 'animate position properties of a DOM element', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      left: 100,
      top: "50px",
      translateX: 50,
      rotateZ: 45
    }, {
      duration: 25,
      type: dynamics.easeInOut
    })
    setTimeout ->
      expect(el.style.left).eql("100px")
      expect(el.style.top).eql("50px")
      expectEqualMatrix3d(el.style.transform, dynamics.tests.matrixForTransform("translateX(50px) rotateZ(45deg)"))
      done()
    , 50

  it 'animate scrollTop of a DOM element', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      scrollTop: 100,
    }, {
      duration: 25,
      type: dynamics.easeInOut
    })
    setTimeout ->
      expect(el.scrollTop).eql('100')
      done()
    , 50

  it 'animate with a delay', (done) ->
    el = document.createElement('div')
    el.style.left = 0
    dynamics.animate(el, {
      left: 100
    }, {
      duration: 25,
      delay: 100,
      type: dynamics.easeInOut
    })
    setTimeout ->
      expect(el.style.left).eql("0px")
    , 50
    setTimeout ->
      expect(el.style.left).not.eql("100px")
    , 110
    setTimeout ->
      expect(el.style.left).eql("100px")
      done()
    , 150

  it 'works with an array of elements', (done) ->
    els = [
      document.createElement('div'),
      document.createElement('div')
    ]
    el0asserted = false
    el1asserted = false
    dynamics.animate(els, {
      left: 100,
    }, {
      duration: 25,
      complete: (el) ->
        el0asserted = true if el == els[0]
        el1asserted = true if el == els[1]
    })
    setTimeout ->
      expect(els[0].style.left).eql("100px")
      expect(els[1].style.left).eql("100px")
      assert(el0asserted, "complete wasn't called with the right element")
      assert(el1asserted, "complete wasn't called with the right element")
      done()
    , 50

  it 'calls change while the animation is running', (done) ->
    el = document.createElement('div')
    changeCalls = 0
    dynamics.animate(el, {
      left: 100,
      top: "50px"
    }, {
      duration: 100,
      type: dynamics.easeInOut,
      change: ->
        changeCalls += 1
    })
    setTimeout ->
      expect(changeCalls).to.be.above(1)
      done()
    , 150

  it 'calls change with element being animated', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      left: 100,
      top: "50px"
    }, {
      duration: 100,
      type: dynamics.easeInOut,
      change: (element) ->
        assert(el == element, "Element should be the same")
    })
    setTimeout ->
      done()
    , 150

  it 'calls change with progress incrementing', (done) ->
    el = document.createElement('div')
    savedProgress = -1
    dynamics.animate(el, {
      left: 100,
      top: "50px"
    }, {
      duration: 100,
      type: dynamics.easeInOut,
      change: (el, progress) ->
        assert(progress > savedProgress, "Progress should increment")
        assert(progress >= 0 && progress <= 1, "Progress should be in [0, 1] range")
        savedProgress = progress
    })
    setTimeout ->
      assert(savedProgress == 1, "Progress should end with 1")
      done()
    , 150

  it 'actually animates properties while the animation is running', (done) ->
    el = document.createElement('div')
    previous = { left: 0, top: 0, translateX: 0, rotateZ: 0, transform: 'none' }
    dynamics.animate(el, {
      left: 100,
      top: "50px",
      translateX: 50,
      rotateZ: 45
    }, {
      duration: 100,
      type: dynamics.easeInOut
    })
    interval = setInterval ->
      current = { left: parseFloat(el.style.left), top: parseFloat(el.style.top), transform: el.style.transform }
      assert(current.left >= previous.left, "Left should increment")
      assert(current.top >= previous.top, "Top should increment")
      assert(current.transform != previous.transform or (current.transform == previous.transform && current.transform != "none"), "Transform should change")
      previous = current
    , 20
    setTimeout ->
      clearInterval(interval)
      done()
    , 150

  it 'calls complete when the animation is over', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      left: 100,
      top: "50px"
    }, {
      duration: 25,
      complete: ->
        done()
    })

  it 'comes back to the original value with dynamics.bounce', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      left: 100
    }, {
      duration: 25,
      type: dynamics.bounce,
      complete: ->
        expect(el.style.left).eql("0px")
        done()
    })

  it 'animates the points of a svg element correctly', (done) ->
    regex = /M([.\d]*),([.\d]*) C([.\d]*),([.\d]*)/
    dynamics.tests.isSVG = (el) ->
      true
    el = document.createElement('polygon')
    el.setAttribute("points", "M101.88,22 C101.88,18.25")
    previous = el.getAttribute("points").match(regex)
    dynamics.animate(el, {
      points: "M50,10 C88.11,20.45"
    }, {
      duration: 100
    })
    interval = setInterval ->
      current = el.getAttribute("points").match(regex)
      assert(current?)
      expect(parseFloat(current[1])).to.at.most(parseFloat(previous[1]))
      expect(parseFloat(current[2])).to.at.most(parseFloat(previous[2]))
      expect(parseFloat(current[3])).to.at.most(parseFloat(previous[3]))
      expect(parseFloat(current[4])).to.at.least(parseFloat(previous[4]))
      previous = current
    , 20
    setTimeout ->
      clearInterval(interval)
      expect(el.getAttribute("points")).to.be.equal("M50,10 C88.11,20.45")
      done()
    , 150


  it 'animates the points of a svg path correctly', (done) ->
    el = document.createElement('path')

    # On chrome 52 getComputedStyle give a "d" property for path
    # Mock window.getComputedStyle
    style = window.getComputedStyle(el, null)
    style.setProperty('d', 'path(10 20 30)')
    oldComputed = window.getComputedStyle
    window.getComputedStyle = (el, pseudoElt) -> style

    dynamics.tests.isSVG = (el) -> true
    el.setAttribute("d", "M101.88,22 C101.88,18.25")
    dynamics.animate(el, {
      d: "M50,10 C88.11,20.45"
    }, {
      duration: 100
    })
    setTimeout ->
      expect(el.getAttribute("d")[0]).to.be.equal('M')
      window.getComputedStyle = oldComputed # remove mock to avoid conflict for the next test
      done()
    , 50

  it 'animates properties of an object correctly', (done) ->
    assertTypes = (object) ->
      expect(typeof(object.number)).to.be.equal('number', 'object.number has the wrong type')
      expect(typeof(object.negative)).to.be.equal('number', 'object.negative has the wrong type')
      expect(typeof(object.string)).to.be.equal('string', 'object.string has the wrong type')
      expect(typeof(object.stringArray)).to.be.equal('string', 'object.stringArray has the wrong type')
      assert(object.array instanceof Array, 'object.array has the wrong type')
      expect(typeof(object.hexColor)).to.be.equal('string', 'object.hexColor has the wrong type')
      expect(typeof(object.rgbColor)).to.be.equal('string', 'object.rgbColor has the wrong type')
      expect(typeof(object.rgbaColor)).to.be.equal('string', 'object.rgbaColor has the wrong type')
      expect(typeof(object.background)).to.be.equal('string', 'object.background has the wrong type')

    assertFormats = (object) ->
      assert(object.stringArray.match(/^([.\d]*) ([.\d]*), d([.\d]*):([.\d]*)$/)?, 'object.stringArray has the wrong format')
      assert(object.array[0].match(/^([.\d]*)deg$/)?, 'object.array[0] has the wrong format')
      assert(object.array[2].match(/^([.\d]*)$/)?, 'object.array[2] has the wrong format')
      assert(object.array[4].match(/^#([a-zA-Z\d]{6})$/)?, 'object.array[4] has the wrong format')
      assert(object.hexColor.match(/^#([a-zA-Z\d]{6})$/)?, 'object.hexColor has the wrong format')
      assert(object.rgbColor.match(/^rgb\(([.\d]*), ([.\d]*), ([.\d]*)\)$/)?, 'object.rgbColor has the wrong format')
      assert(object.rgbaColor.match(/^rgba\(([.\d]*), ([.\d]*), ([.\d]*), ([.\d]*)\)$/)?, 'object.rgbaColor has the wrong format')
      assert(object.background.match(/^linear-gradient\(#([a-zA-Z\d]{6}), #([a-zA-Z\d]{6})\)$/)?, 'object.background has the wrong format')

    object = {
      number: 0,
      negative: -10,
      string: "10",
      stringArray: "10 50, d10:50",
      array: ["0deg", 0, "1.10", 10, "#FFFFFF"],
      hexColor: "#FFFFFF",
      rgbColor: "rgb(255, 255, 255)",
      rgbaColor: "rgba(255, 255, 255, 0)",
      translateX: 0,
      rotateZ: 0,
      background: "linear-gradient(#FFFFFF, #000000)",
    }
    previous = JSON.parse(JSON.stringify(object))
    dynamics.animate(object, {
      number: 10,
      negative: 50,
      string: "50",
      stringArray: "100 1, d0:100",
      array: ["100deg", 40, "2.20", 20, "#123456"],
      hexColor: "#123456",
      rgbColor: "rgb(18, 52, 86)",
      rgbaColor: "rgba(18, 52, 86, 1)",
      translateX: 10,
      rotateZ: 1,
      background: "linear-gradient(#FF0000, #F0F0F0)",
    }, {
      duration: 100
    })
    interval = setInterval ->
      current = JSON.parse(JSON.stringify(object))

      assertTypes(current)
      assertFormats(current)

      # Assert values are changing
      expect(current.number).to.at.least(previous.number)
      expect(current.negative).to.at.least(previous.negative)
      expect(parseFloat(current.string)).to.at.least(parseFloat(previous.string))
      stringArrayArgs = current.stringArray.match(/^([.\d]*) ([.\d]*), d([.\d]*):([.\d]*)$/)
      previousStringArrayArgs = previous.stringArray.match(/^([.\d]*) ([.\d]*), d([.\d]*):([.\d]*)$/)
      expect(parseFloat(stringArrayArgs[1])).to.at.least(parseFloat(previousStringArrayArgs[1]))
      expect(parseFloat(stringArrayArgs[2])).to.at.most(parseFloat(previousStringArrayArgs[2]))
      expect(parseFloat(stringArrayArgs[3])).to.at.most(parseFloat(previousStringArrayArgs[3]))
      expect(parseFloat(stringArrayArgs[4])).to.at.least(parseFloat(previousStringArrayArgs[4]))

      previous = current
    , 20
    setTimeout ->
      clearInterval(interval)
      assertTypes(object)
      assertFormats(object)

      done()
    , 150

  it 'animates actual properties of an object correctly', (done) ->
    object = {}
    Object.defineProperty(object, "prop", {
      set: (v) ->
        @_prop = v
      get: ->
        @_prop
    })
    object.prop = 1

    dynamics.animate(object, {
      prop: 0
    }, {
      duration: 100
    })

    previousProp = object.prop

    interval = setInterval ->
      assert(object.prop >= 0 && object.prop <= 1, "prop is between 0 and 1")
      assert(object.prop < previousProp || object.prop == 0, "prop should be decreasing or equal 0")

      previousProp = object.prop
    , 20

    setTimeout ->
      clearInterval(interval)
      expect(object.prop).to.be.equal(0, 'object.prop has the wrong end value')

      done()
    , 150

  it 'finishes the animation with the correct end state while using a specific bezier curve', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      left: 100,
    }, {
      duration: 25,
      type: dynamics.bezier,
      points: [
        {"x":0,"y":0,"cp":[{"x":0,"y":1}]},
        {"x":1,"y":0,"cp":[{"x":0.5,"y":0}]}
      ],
      complete: ->
        expect(el.style.left).eql('0px')
        done()
    })

describe 'dynamics.stop', ->
  it 'actually stops current animation', (done) ->
    el = document.createElement('div')
    changeCanBeCalled = true
    dynamics.animate(el, {
      left: 100
    }, {
      duration: 100,
      type: dynamics.easeInOut,
      change: ->
        assert(changeCanBeCalled, "change shouldn't be called anymore")
      ,
      complete: ->
        assert(false, "complete shouldn't be called")
    })
    setTimeout ->
      dynamics.stop(el)
      changeCanBeCalled = false
    , 50
    setTimeout ->
      done()
    , 150

  it 'also works with a delayed animation', (done) ->
    el = document.createElement('div')
    dynamics.animate(el, {
      left: 100
    }, {
      duration: 100,
      delay: 100,
      change: ->
        assert(false, "change shouldn't be called")
      ,
      complete: ->
        assert(false, "complete shouldn't be called")
    })
    setTimeout ->
      dynamics.stop(el)
    , 50
    setTimeout ->
      done()
    , 150

  it 'also works with multiple delayed animations', (done) ->
    els = [document.createElement('div'), document.createElement('div'), document.createElement('div')]
    delay = 100
    for el in els
      dynamics.animate(el, {
        left: 100
      }, {
        duration: 100,
        delay: delay,
        change: ->
          assert(false, "change shouldn't be called")
        ,
        complete: ->
          assert(false, "complete shouldn't be called")
      })
      delay += 50
    setTimeout ->
      for el in els
        dynamics.stop(el)
    , 50
    setTimeout ->
      done()
    , 450

describe 'curves', ->
  describe 'dynamics.linear', ->
    it 'works', ->
      curve = dynamics.linear()
      expect(curve(0)).eql(0)
      expect(curve(0.1)).eql(0.1)
      expect(curve(5)).eql(5)
      expect(curve(5.6)).eql(5.6)
      expect(curve(7.8)).eql(7.8)
      expect(curve(1)).eql(1)

  describe 'dynamics.easeInOut', ->
    it 'works', ->
      curve = dynamics.easeInOut()
      expect(curve(0)).eql(0)
      assert(curve(0.25) > 0 && curve(0.25) < 0.5)
      expect(curve(0.5)).eql(0.5)
      assert(curve(0.75) > 0.5 && curve(0.75) < 1)
      expect(curve(1)).eql(1)

  describe 'dynamics.easeIn', ->
    it 'increases exponentially', ->
      curve = dynamics.easeIn()
      inter = 0.1
      diff = 0
      for i in [1..10]
        t1 = inter * (i - 1)
        t2 = inter * i
        newDiff = curve(t2) - curve(t1)
        assert(newDiff > diff, "easeIn should be exponential")
        diff = newDiff

  describe 'dynamics.easeOut', ->
    it 'increases 1/exponentially', ->
      curve = dynamics.easeOut()
      inter = 0.1
      diff = 1
      for i in [1..10]
        t1 = inter * (i - 1)
        t2 = inter * i
        newDiff = curve(t2) - curve(t1)
        assert(newDiff < diff, "easeOut should be 1/exponential")
        diff = newDiff

  describe 'dynamics.bounce', ->
    it 'starts and returns to initial state', ->
      curve = dynamics.bounce()
      assert(curve(0) < 0.001 && curve(0) >= 0)
      assert(curve(1) < 0.001 && curve(1) >= 0)

  describe 'dynamics.forceWithGravity', ->
    it 'starts and returns to initial state', ->
      curve = dynamics.forceWithGravity()
      assert(curve(0) < 0.001 && curve(0) >= 0)
      assert(curve(1) < 0.001 && curve(1) >= 0)

describe 'dynamics.setTimeout', ->
  it 'works', (done) ->
    t = Date.now()
    dynamics.setTimeout(->
      assert(Math.abs(Date.now() - t - 100) < 30)
      done()
    , 100)

describe 'dynamics.clearTimeout', ->
  it 'works', (done) ->
    i = dynamics.setTimeout(->
      assert(false)
    , 100)
    dynamics.clearTimeout(i)
    setTimeout(->
      done()
    , 200)
Download .txt
gitextract_khmysplw/

├── .gitignore
├── .npmignore
├── README.md
├── package.json
├── src/
│   └── dynamics.coffee
└── test/
    └── dynamics.coffee
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (69K chars).
[
  {
    "path": ".gitignore",
    "chars": 17,
    "preview": "lib\nnode_modules\n"
  },
  {
    "path": ".npmignore",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "README.md",
    "chars": 5438,
    "preview": "# Dynamics.js\nDynamics.js is a JavaScript library to create physics-based animations\n\nTo see some demos, check out [dyna"
  },
  {
    "path": "package.json",
    "chars": 1174,
    "preview": "{\n  \"name\": \"dynamics.js\",\n  \"title\": \"Dynamics.js\",\n  \"description\": \"Javascript library to create physics-related anim"
  },
  {
    "path": "src/dynamics.coffee",
    "chars": 42653,
    "preview": "# Visibility change\nisDocumentVisible = ->\n  document.visibilityState == \"visible\" || dynamics.tests?\n\nobserveVisibility"
  },
  {
    "path": "test/dynamics.coffee",
    "chars": 16857,
    "preview": "mocha = require('mocha')\njsdom = require('mocha-jsdom')\nexpect = require('chai').expect\nassert = require('chai').assert\n"
  }
]

About this extraction

This page contains the full source code of the michaelvillar/dynamics.js GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (64.6 KB), approximately 19.8k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!