[
  {
    "path": ".gitignore",
    "content": "lib\nnode_modules\n"
  },
  {
    "path": ".npmignore",
    "content": ""
  },
  {
    "path": "README.md",
    "content": "# Dynamics.js\nDynamics.js is a JavaScript library to create physics-based animations\n\nTo see some demos, check out [dynamicsjs.com](http://dynamicsjs.com).\n\n## Usage\nDownload:\n- [GitHub releases](https://github.com/michaelvillar/dynamics.js/releases)\n- [npm](https://www.npmjs.com/package/dynamics.js): `npm install dynamics.js`\n- bower: `bower install dynamics.js`\n\nInclude `dynamics.js` into your page:\n```html\n<script src=\"dynamics.js\"></script>\n```\nYou can animate CSS properties of any DOM element.\n```javascript\nvar el = document.getElementById(\"logo\")\ndynamics.animate(el, {\n  translateX: 350,\n  scale: 2,\n  opacity: 0.5\n}, {\n  type: dynamics.spring,\n  frequency: 200,\n  friction: 200,\n  duration: 1500\n})\n```\n\nYou also can animate SVG properties.\n```javascript\nvar path = document.querySelector(\"path\")\ndynamics.animate(path, {\n  d: \"M0,0 L0,100 L100,50 L0,0 Z\",\n  fill: \"#FF0000\",\n  rotateZ: 45,\n  // rotateCX and rotateCY are the center of the rotation\n  rotateCX: 100,\n  rotateCY: 100\n}, {\n  friction: 800\n})\n```\n\nAnd any JavaScript object.\n```javascript\nvar o = {\n  number: 10,\n  color: \"#FFFFFF\",\n  string: \"10deg\",\n  array: [ 1, 10 ]\n}\ndynamics.animate(o, {\n  number: 20,\n  color: \"#000000\",\n  string: \"90deg\",\n  array: [-9, 99 ]\n})\n```\n\n## Reference\n### dynamics.animate(el, properties, options)\nAnimates an element to the properties with the animation options.\n- `el` is a DOM element, a JavaScript object or an Array of elements\n- `properties` is an object of the properties/values you want to animate\n- `options` is an object representing the animation\n  - `type` is the [animation type](#dynamics-and-properties): `dynamics.spring`, `dynamics.easeInOut`,... (default: `dynamics.easeInOut`)\n  - `frequency`, `friction`, `bounciness`,... are specific to the animation type you are using\n  - `duration` is in milliseconds (default: `1000`)\n  - `delay` is in milliseconds (default: `0`)\n  - `complete` (optional) is the completion callback\n  - `change` (optional) is called at every change. Two arguments are passed to the function. `function(el, progress)`\n    - `el` is the element it's animating\n    - `progress` is the progress of the animation between 0 and 1\n\n### dynamics.stop(el)\nStops the animation applied on the element\n\n### dynamics.css(el, properties)\nThis is applying the CSS properties to your element with the correct browser prefixes.\n- `el` is a DOM element\n- `properties` is an object of the CSS properties\n\n### dynamics.setTimeout(fn, delay)\nDynamics.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.\n- `fn` is the callback\n- `delay` is in milliseconds\n\nReturns a unique id\n\n### dynamics.clearTimeout(id)\nClears a timeout that was defined earlier\n- `id` is the timeout id\n\n### dynamics.toggleSlow()\nToggle a debug mode to slow down every animations and timeouts.\nThis is useful for development mode to tweak your animation.\nThis can be activated using `Shift-Control-D` in the browser.\n\n## Dynamics and properties\n### dynamics.spring\n- `frequency` default is 300\n- `friction` default is 200\n- `anticipationSize` (optional)\n- `anticipationStrength` (optional)\n\n### dynamics.bounce\n- `frequency` default is 300\n- `friction` default is 200\n\n### dynamics.forceWithGravity and dynamics.gravity\n- `bounciness` default is 400\n- `elasticity` default is 200\n\n### dynamics.easeInOut, dynamics.easeIn and dynamics.easeOut\n- `friction` default is 500\n\n### dynamics.linear\nNo properties\n\n### dynamics.bezier\n- `points` array of points and control points\n\nThe easiest way to output this kind of array is to use the [curve creator](http://dynamicsjs.com). Here is an example:\n```javascript\n[{\"x\":0,\"y\":0,\"cp\":[{\"x\":0.2,\"y\":0}]},\n {\"x\":0.5,\"y\":-0.4,\"cp\":[{\"x\":0.4,\"y\":-0.4},{\"x\":0.8,\"y\":-0.4}]},\n {\"x\":1,\"y\":1,\"cp\":[{\"x\":0.8,\"y\":1}]}]\n```\n\n## Contributing\nCompile: `npm run build` or `npm run build:watch`\n\nRun tests: `npm test`\n\n## Browser Support\nWorking on\n- Safari 7+\n- Firefox 35+\n- Chrome 34+\n- IE10+\n\n## Sylvester\nSome code from Sylvester.js has been used (part of Vector and Matrix).\n\n## License\nThe MIT License (MIT)\n\nCopyright (c) 2015 Michael Villar\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE 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.\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"dynamics.js\",\n  \"title\": \"Dynamics.js\",\n  \"description\": \"Javascript library to create physics-related animations\",\n  \"version\": \"1.1.5\",\n  \"homepage\": \"http://dynamicsjs.com\",\n  \"author\": \"Michael Villar <me@michaelvillar.com> (http://twitter.com/michaelvillar)\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/michaelvillar/dynamics.js\"\n  },\n  \"devDependencies\": {\n    \"coffee-script\": \"1.7.1\",\n    \"uglify-js\": \"2.4.14\",\n    \"jsdom\": \"3.x.x\",\n    \"mocha-jsdom\": \"0.4.0\",\n    \"chai\": \"3.0.0\",\n    \"mocha\": \"2.2.5\"\n  },\n  \"scripts\": {\n    \"test\": \"mocha --compilers coffee:coffee-script/register\",\n    \"build\": \"coffee -c -o ./lib/ ./src/dynamics.coffee && ./node_modules/uglify-js/bin/uglifyjs ./lib/dynamics.js -m -c -o ./lib/dynamics.min.js\",\n    \"build:watch\": \"coffee -w -c -o ./lib/ ./src/dynamics.coffee\",\n    \"prepublish\": \"npm run build\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/michaelvillar/dynamics.js/issues\"\n  },\n  \"main\": \"lib/dynamics.js\",\n  \"directories\": {\n    \"test\": \"test\"\n  },\n  \"keywords\": [\n    \"animation\",\n    \"javascript\",\n    \"requestAnimationFrame\",\n    \"spring\",\n    \"physic\"\n  ],\n  \"license\": \"MIT\"\n}\n"
  },
  {
    "path": "src/dynamics.coffee",
    "content": "# Visibility change\nisDocumentVisible = ->\n  document.visibilityState == \"visible\" || dynamics.tests?\n\nobserveVisibilityChange = (() ->\n  fns = []\n  document?.addEventListener(\"visibilitychange\", ->\n    for fn in fns\n      fn(isDocumentVisible())\n  )\n  (fn) ->\n    fns.push(fn)\n)()\n\n# Object helpers\n# Not deep clone and not using JSON.stringify/JSON.parse because\n# We want to keep functions\nclone = (o) ->\n  newO = {}\n  for k, v of o\n    newO[k] = v\n  newO\n\n# Caching\ncacheFn = (func) ->\n  data = {}\n  ->\n    key = \"\"\n    for k in arguments\n      key += k.toString() + \",\"\n    result = data[key]\n    unless result\n      data[key] = result = func.apply(this, arguments)\n    result\n\n# Make a function accept array or single objects for the first argument\nmakeArrayFn = (fn) ->\n  (el) ->\n    if el instanceof Array or el instanceof NodeList or el instanceof HTMLCollection\n      res = for i in [0...el.length]\n        args = Array.prototype.slice.call(arguments, 1)\n        args.splice(0, 0, el[i])\n        fn.apply(this, args)\n      return res\n    fn.apply(this, arguments)\n\n# Properties Helpers\napplyDefaults = (options, defaults) ->\n  for k, v of defaults\n    options[k] ?= v\n\napplyFrame = (el, properties) ->\n  if(el.style?)\n    applyProperties(el, properties)\n  else\n    for k, v of properties\n      el[k] = v.format()\n\napplyProperties = (el, properties) ->\n  properties = parseProperties(properties)\n  transforms = []\n  isSVG = isSVGElement(el)\n  for k, v of properties\n    if transformProperties.contains(k)\n      transforms.push([k, v])\n    else\n      if v.format?\n        v = v.format()\n      if typeof(v) == 'number'\n        v = \"#{v}#{unitForProperty(k, v)}\"\n      if el.hasAttribute? && el.hasAttribute(k)\n        el.setAttribute(k, v)\n      else if el.style?\n        el.style[propertyWithPrefix(k)] = v\n      if k of el\n        el[k] = v\n\n  if transforms.length > 0\n    if isSVG\n      matrix = new Matrix2D()\n      matrix.applyProperties(transforms)\n      el.setAttribute(\"transform\", matrix.decompose().format())\n    else\n      v = (transforms.map (transform) ->\n        transformValueForProperty(transform[0], transform[1])\n      ).join(\" \")\n      el.style[propertyWithPrefix(\"transform\")] = v\n\nisSVGElement = (el) ->\n  if SVGElement? and SVGSVGElement?\n    el instanceof SVGElement && !(el instanceof SVGSVGElement)\n  else\n    dynamics.tests?.isSVG?(el) ? false\n\n# Math\nroundf = (v, decimal) ->\n  d = Math.pow(10, decimal)\n  return Math.round(v * d) / d\n\n# Set\nclass Set\n  constructor: (array) ->\n    @obj = {}\n    for v in array\n      @obj[v] = 1\n\n  contains: (v) ->\n    return @obj[v] == 1\n\n# String Helpers\ntoDashed = (str) ->\n  return str.replace(/([A-Z])/g, ($1) -> \"-\" + $1.toLowerCase())\n\n# CSS Helpers\npxProperties = 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(','))\ndegProperties = new Set('rotate,rotateX,rotateY,rotateZ,skew,skewX,skewY,skewZ'.split(','))\ntransformProperties = new Set('translate,translateX,translateY,translateZ,scale,scaleX,scaleY,scaleZ,rotate,rotateX,rotateY,rotateZ,rotateC,rotateCX,rotateCY,skew,skewX,skewY,skewZ,perspective'.split(','))\nsvgProperties = 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(','))\n\nunitForProperty = (k, v) ->\n  return '' unless typeof v == 'number'\n  if pxProperties.contains(k)\n    return 'px'\n  else if degProperties.contains(k)\n    return 'deg'\n  ''\n\ntransformValueForProperty = (k, v) ->\n  match = \"#{v}\".match(/^([0-9.-]*)([^0-9]*)$/)\n  if match?\n    v = match[1]\n    unit = match[2]\n  else\n    v = parseFloat(v)\n\n  v = roundf(parseFloat(v), 10)\n\n  if !unit? or unit == \"\"\n    unit = unitForProperty(k, v)\n\n  \"#{k}(#{v}#{unit})\"\n\nparseProperties = (properties) ->\n  parsed = {}\n  for property, value of properties\n    if transformProperties.contains(property)\n      match = property.match(/(translate|rotateC|rotate|skew|scale|perspective)(X|Y|Z|)/)\n      if match and match[2].length > 0\n        parsed[property] = value\n      else\n        for axis in ['X', 'Y', 'Z']\n          parsed[match[1] + axis] = value\n    else\n      parsed[property] = value\n  parsed\n\ndefaultValueForKey = (key) ->\n  v = if key == 'opacity' then 1 else 0\n  \"#{v}#{unitForProperty(key, v)}\"\n\ngetCurrentProperties = (el, keys) ->\n  properties = {}\n  isSVG = isSVGElement(el)\n  if el.style?\n    style = window.getComputedStyle(el, null)\n    for key in keys\n      if transformProperties.contains(key)\n        unless properties['transform']?\n          if isSVG\n            matrix = new Matrix2D(el.transform.baseVal.consolidate()?.matrix)\n          else\n            matrix = Matrix.fromTransform(style[propertyWithPrefix('transform')])\n          properties['transform'] = matrix.decompose()\n      else\n        if el.hasAttribute? && el.hasAttribute(key)\n          v = el.getAttribute(key)\n        else if key of el\n          v = el[key]\n        else\n          v = style[key]\n\n        if (!v? or key is 'd') && svgProperties.contains(key)\n          v = el.getAttribute(key)\n        if v == \"\" or !v?\n          v = defaultValueForKey(key)\n        properties[key] = createInterpolable(v)\n  else\n    for key in keys\n      properties[key] = createInterpolable(el[key])\n\n  addUnitsToNumberInterpolables(el, properties)\n\n  properties\n\naddUnitsToNumberInterpolables = (el, properties) ->\n  for k, interpolable of properties\n    if interpolable instanceof InterpolableNumber && el.style? && k of el.style\n      interpolable = new InterpolableString([\n        interpolable,\n        unitForProperty(k, 0),\n      ])\n    properties[k] = interpolable\n  properties\n\n# Interpolable\ncreateInterpolable = (value) ->\n  klasses = [InterpolableArray, InterpolableObject, InterpolableNumber, InterpolableString]\n  for klass in klasses\n    interpolable = klass.create(value)\n    return interpolable if interpolable?\n  null\n\nclass InterpolableString\n  constructor: (@parts) ->\n\n  interpolate: (endInterpolable, t) =>\n    start = @parts\n    end = endInterpolable.parts\n    newParts = []\n    for i in [0...Math.min(start.length, end.length)]\n      if start[i].interpolate?\n        newParts.push(start[i].interpolate(end[i], t))\n      else\n        newParts.push(start[i])\n    new InterpolableString(newParts)\n\n  format: =>\n    parts = @parts.map (val) ->\n      if val.format?\n        val.format()\n      else\n        val\n    parts.join('')\n\n  @create: (value) =>\n    value = \"#{value}\"\n    matches = []\n\n    types = [\n      {\n        re: /(#[a-f\\d]{3,6})/ig,\n        klass: InterpolableColor,\n        parse: (v) -> v,\n      },\n      {\n        re: /(rgba?\\([0-9.]*, ?[0-9.]*, ?[0-9.]*(?:, ?[0-9.]*)?\\))/ig,\n        klass: InterpolableColor,\n        parse: (v) -> v,\n      },\n      {\n        re: /([-+]?[\\d.]+)/ig,\n        klass: InterpolableNumber,\n        parse: parseFloat,\n      },\n    ]\n\n    for type in types\n      re = type.re\n      while match = re.exec(value)\n        matches.push({\n          index: match.index,\n          length: match[1].length,\n          interpolable: type.klass.create(type.parse(match[1])),\n        })\n\n    matches = matches.sort((a, b) ->\n      if a.index > b.index\n        1\n      else\n        -1\n    )\n\n    parts = []\n    index = 0\n    for match in matches\n      continue if match.index < index\n      if match.index > index\n        parts.push(value.substring(index, match.index))\n      parts.push(match.interpolable)\n      index = match.index + match.length\n    if index < value.length\n      parts.push(value.substring(index))\n\n    return new InterpolableString(parts)\n\nclass InterpolableObject\n  constructor: (obj) ->\n    @obj = obj\n\n  interpolate: (endInterpolable, t) =>\n    start = @obj\n    end = endInterpolable.obj\n    newObj = {}\n    for k, v of start\n      if v.interpolate?\n        newObj[k] = v.interpolate(end[k], t)\n      else\n        newObj[k] = v\n    new InterpolableObject(newObj)\n\n  format: =>\n    @obj\n\n  @create: (value) =>\n    if value instanceof Object\n      obj = {}\n      for k, v of value\n        obj[k] = createInterpolable(v)\n      return new InterpolableObject(obj)\n    null\n\nclass InterpolableNumber\n  constructor: (value) ->\n    @value = parseFloat(value)\n\n  interpolate: (endInterpolable, t) =>\n    start = @value\n    end = endInterpolable.value\n    new InterpolableNumber((end - start) * t + start)\n\n  format: =>\n    roundf(@value, 5)\n\n  @create: (value) =>\n    return new InterpolableNumber(value) if typeof(value) == 'number'\n    null\n\nclass InterpolableArray\n  constructor: (@values) ->\n\n  interpolate: (endInterpolable, t) =>\n    start = @values\n    end = endInterpolable.values\n    newValues = []\n    for i in [0...Math.min(start.length, end.length)]\n      if start[i].interpolate?\n        newValues.push(start[i].interpolate(end[i], t))\n      else\n        newValues.push(start[i])\n    new InterpolableArray(newValues)\n\n  format: =>\n    @values.map (val) ->\n      if val.format?\n        val.format()\n      else\n        val\n\n  @createFromArray: (arr) =>\n    values = arr.map (val) ->\n      createInterpolable(val) || val\n    values = values.filter (val) ->\n      val?\n    return new InterpolableArray(values)\n\n  @create: (value) =>\n    return @createFromArray(value) if value instanceof Array\n    null\n\nclass Color\n  constructor: (@rgb={}, @format) ->\n\n  @fromHex: (hex) ->\n    hex3 = hex.match(/^#([a-f\\d]{1})([a-f\\d]{1})([a-f\\d]{1})$/i)\n    if hex3?\n      hex = \"##{hex3[1]}#{hex3[1]}#{hex3[2]}#{hex3[2]}#{hex3[3]}#{hex3[3]}\"\n    result = hex.match(/^#([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i)\n    if result?\n      return new Color({\n        r: parseInt(result[1], 16),\n        g: parseInt(result[2], 16),\n        b: parseInt(result[3], 16),\n        a: 1\n      }, \"hex\")\n    null\n\n  @fromRgb: (rgb) ->\n    match = rgb.match(/^rgba?\\(([0-9.]*), ?([0-9.]*), ?([0-9.]*)(?:, ?([0-9.]*))?\\)$/)\n    if match?\n      return new Color({\n        r: parseFloat(match[1]),\n        g: parseFloat(match[2]),\n        b: parseFloat(match[3]),\n        a: parseFloat(match[4] ? 1)\n      }, if match[4]? then \"rgba\" else \"rgb\")\n    null\n\n  @componentToHex = (c) ->\n    hex = c.toString(16);\n    if hex.length == 1\n      \"0\" + hex\n    else\n      hex\n\n  toHex: =>\n    \"#\" + Color.componentToHex(@rgb.r) + Color.componentToHex(@rgb.g) + Color.componentToHex(@rgb.b)\n\n  toRgb: =>\n    \"rgb(#{@rgb.r}, #{@rgb.g}, #{@rgb.b})\"\n\n  toRgba: =>\n    \"rgba(#{@rgb.r}, #{@rgb.g}, #{@rgb.b}, #{@rgb.a})\"\n\nclass InterpolableColor\n  constructor: (@color) ->\n\n  interpolate: (endInterpolable, t) =>\n    start = @color\n    end = endInterpolable.color\n    rgb = {}\n    for k in ['r', 'g', 'b']\n      v = Math.round((end.rgb[k] - start.rgb[k]) * t + start.rgb[k])\n      rgb[k] = Math.min(255, Math.max(0, v))\n    k = \"a\"\n    v = roundf((end.rgb[k] - start.rgb[k]) * t + start.rgb[k], 5)\n    rgb[k] = Math.min(1, Math.max(0, v))\n    new InterpolableColor(new Color(rgb, end.format))\n\n  format: =>\n    if @color.format == \"hex\"\n      @color.toHex()\n    else if @color.format == \"rgb\"\n      @color.toRgb()\n    else if @color.format == \"rgba\"\n      @color.toRgba()\n\n  @create: (value) =>\n    return unless typeof(value) == \"string\"\n    color = Color.fromHex(value) || Color.fromRgb(value)\n    if color?\n      return new InterpolableColor(color)\n    null\n\n# SVG Matrix2D\nclass DecomposedMatrix2D\n  constructor: (@props) ->\n\n  interpolate: (endMatrix, t) =>\n    newProps = {}\n    for k in ['translate', 'scale', 'rotate']\n      newProps[k] = []\n      for i in [0...@props[k].length]\n        newProps[k][i] = (endMatrix.props[k][i] - @props[k][i]) * t + @props[k][i]\n    for i in [1..2]\n      newProps['rotate'][i] = endMatrix.props['rotate'][i]\n    for k in ['skew']\n      newProps[k] = (endMatrix.props[k] - @props[k]) * t + @props[k]\n\n    new DecomposedMatrix2D(newProps)\n\n  format: =>\n    \"translate(#{@props.translate.join(',')}) rotate(#{@props.rotate.join(',')})\n     skewX(#{@props.skew}) scale(#{@props.scale.join(',')})\"\n\n  applyRotateCenter: (rotateC) =>\n    m = baseSVG.createSVGMatrix()\n    m = m.translate(rotateC[0], rotateC[1])\n    m = m.rotate(@props.rotate[0])\n    m = m.translate(-rotateC[0], -rotateC[1])\n    m2d = new Matrix2D(m)\n\n    negativeTranslate = m2d.decompose().props.translate\n    for i in [0..1]\n      @props.translate[i] -= negativeTranslate[i]\n\nbaseSVG = document?.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\")\nclass Matrix2D\n  constructor: (@m) ->\n    if !@m\n      @m = baseSVG.createSVGMatrix()\n\n  decompose: =>\n    r0 = new Vector([@m.a, @m.b])\n    r1 = new Vector([@m.c, @m.d])\n    kx = r0.length()\n    kz = r0.dot(r1)\n    r0 = r0.normalize()\n    ky = r1.combine(r0, 1, -kz).length()\n    new DecomposedMatrix2D({\n      translate: [@m.e, @m.f],\n      rotate: [Math.atan2(@m.b, @m.a) * 180 / Math.PI, @rotateCX, @rotateCY],\n      scale: [kx, ky],\n      skew: kz / ky * 180 / Math.PI\n    })\n\n  applyProperties: (properties) =>\n    hash = {}\n    for props in properties\n      hash[props[0]] = props[1]\n    for k, v of hash\n      if k == \"translateX\"\n        @m = @m.translate(v, 0)\n      else if k == \"translateY\"\n        @m = @m.translate(0, v)\n      else if k == \"scaleX\"\n        @m = @m.scaleNonUniform(v, 1)\n      else if k == \"scaleY\"\n        @m = @m.scaleNonUniform(1, v)\n      else if k == \"rotateZ\"\n        @m = @m.rotate(v)\n      else if k == \"skewX\"\n        @m = @m.skewX(v)\n      else if k == \"skewY\"\n        @m = @m.skewY(v)\n\n    @rotateCX = hash.rotateCX ? 0\n    @rotateCY = hash.rotateCY ? 0\n\n# Vector\n# Some code has been ported from Sylvester.js https://github.com/jcoglan/sylvester\nclass Vector\n  constructor: (@els) ->\n\n  # Returns element i of the vector\n  e: (i) =>\n    return if (i < 1 || i > this.els.length) then null else this.els[i-1]\n\n  # Returns the scalar product of the vector with the argument\n  # Both vectors must have equal dimensionality\n  dot: (vector) =>\n    V = vector.els || vector\n    product = 0\n    n = this.els.length\n    return null if n != V.length\n    n += 1\n    while --n\n      product += this.els[n-1] * V[n-1]\n    return product\n\n  # Returns the vector product of the vector with the argument\n  # Both vectors must have dimensionality 3\n  cross: (vector) =>\n    B = vector.els || vector\n    return null if this.els.length != 3 || B.length != 3\n    A = this.els\n    return new Vector([\n      (A[1] * B[2]) - (A[2] * B[1]),\n      (A[2] * B[0]) - (A[0] * B[2]),\n      (A[0] * B[1]) - (A[1] * B[0])\n    ])\n\n  length: =>\n    a = 0\n    for e in @els\n      a += Math.pow(e, 2)\n    Math.sqrt(a)\n\n  normalize: =>\n    length = @length()\n    newElements = []\n    for i, e of @els\n      newElements[i] = e / length\n    new Vector(newElements)\n\n  combine: (b, ascl, bscl) =>\n    result = []\n    for i in [0...@els.length]\n      result[i] = (ascl * @els[i]) + (bscl * b.els[i])\n    new Vector(result)\n\n# Matrix\nclass DecomposedMatrix\n  interpolate: (decomposedB, t, only = null) =>\n    decomposedA = @\n    # New decomposedMatrix\n    decomposed = new DecomposedMatrix\n\n    # Linearly interpolate translate, scale, skew and perspective\n    for k in [ 'translate', 'scale', 'skew', 'perspective' ]\n      decomposed[k] = []\n      for i in [0..decomposedA[k].length-1]\n        if !only? or only.indexOf(k) > -1 or only.indexOf(\"#{k}#{['x','y','z'][i]}\") > -1\n          decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i]\n        else\n          decomposed[k][i] = decomposedA[k][i]\n\n    if !only? or only.indexOf('rotate') != -1\n      # Interpolate quaternion\n      qa = decomposedA.quaternion\n      qb = decomposedB.quaternion\n\n      angle = qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3]\n\n      if angle < 0.0\n        for i in [0..3]\n          qa[i] = -qa[i]\n        angle = -angle\n\n      if angle + 1.0 > .05\n        if 1.0 - angle >= .05\n          th = Math.acos(angle)\n          invth = 1.0 / Math.sin(th)\n          scale = Math.sin(th * (1.0 - t)) * invth\n          invscale = Math.sin(th * t) * invth\n        else\n          scale = 1.0 - t\n          invscale = t\n      else\n        qb[0] = -qa[1]\n        qb[1] = qa[0]\n        qb[2] = -qa[3]\n        qb[3] = qa[2]\n        scale = Math.sin(piDouble * (.5 - t))\n        invscale = Math.sin(piDouble * t)\n\n      decomposed.quaternion = []\n      for i in [0..3]\n        decomposed.quaternion[i] = qa[i] * scale + qb[i] * invscale\n    else\n      decomposed.quaternion = decomposedA.quaternion\n\n    return decomposed\n\n  format: =>\n    @toMatrix().toString()\n\n  toMatrix: =>\n    decomposedMatrix = @\n    matrix = Matrix.I(4)\n\n    # apply perspective\n    for i in [0..3]\n      matrix.els[i][3] = decomposedMatrix.perspective[i]\n\n    # apply rotation\n    quaternion = decomposedMatrix.quaternion\n    x = quaternion[0]\n    y = quaternion[1]\n    z = quaternion[2]\n    w = quaternion[3]\n\n    # apply skew\n    # temp is a identity 4x4 matrix initially\n    skew = decomposedMatrix.skew\n    match = [[1,0],[2,0],[2,1]]\n    for i in [2..0]\n      if skew[i]\n        temp = Matrix.I(4)\n        temp.els[match[i][0]][match[i][1]] = skew[i]\n        matrix = matrix.multiply(temp)\n\n    # Construct a composite rotation matrix from the quaternion values\n    matrix = matrix.multiply(new Matrix([[\n      1 - 2 * (y * y + z * z),\n      2 * (x * y - z * w),\n      2 * (x * z + y * w),\n      0\n    ], [\n      2 * (x * y + z * w),\n      1 - 2 * (x * x + z * z),\n      2 * (y * z - x * w),\n      0\n    ], [\n      2 * (x * z - y * w),\n      2 * (y * z + x * w),\n      1 - 2 * (x * x + y * y),\n      0\n    ], [ 0, 0, 0, 1 ]]))\n\n    # apply scale and translation\n    for i in [0..2]\n      for j in [0..2]\n        matrix.els[i][j] *= decomposedMatrix.scale[i]\n      matrix.els[3][i] = decomposedMatrix.translate[i]\n\n    matrix\n\n# Some code has been ported from Sylvester.js https://github.com/jcoglan/sylvester\nclass Matrix\n  constructor: (@els) ->\n\n  # Returns element (i,j) of the matrix\n  e: (i,j) =>\n    return null if (i < 1 || i > this.els.length || j < 1 || j > this.els[0].length)\n    this.els[i-1][j-1]\n\n  # Returns a copy of the matrix\n  dup: () =>\n    return new Matrix(this.els)\n\n  # Returns the result of multiplying the matrix from the right by the argument.\n  # If the argument is a scalar then just multiply all the elements. If the argument is\n  # a vector, a vector is returned, which saves you having to remember calling\n  # col(1) on the result.\n  multiply: (matrix) =>\n    returnVector = if matrix.modulus then true else false\n    M = matrix.els || matrix\n    M = new Matrix(M).els if (typeof(M[0][0]) == 'undefined')\n    ni = this.els.length\n    ki = ni\n    kj = M[0].length\n    cols = this.els[0].length\n    elements = []\n    ni += 1\n    while (--ni)\n      i = ki - ni\n      elements[i] = []\n      nj = kj\n      nj += 1\n      while (--nj)\n        j = kj - nj\n        sum = 0\n        nc = cols\n        nc += 1\n        while (--nc)\n          c = cols - nc\n          sum += this.els[i][c] * M[c][j]\n        elements[i][j] = sum\n\n    M = new Matrix(elements)\n    return if returnVector then M.col(1) else M\n\n  # Returns the transpose of the matrix\n  transpose: =>\n    rows = this.els.length\n    cols = this.els[0].length\n    elements = []\n    ni = cols\n    ni += 1\n    while (--ni)\n      i = cols - ni\n      elements[i] = []\n      nj = rows\n      nj += 1\n      while (--nj)\n        j = rows - nj\n        elements[i][j] = this.els[j][i]\n    return new Matrix(elements)\n\n  # Make the matrix upper (right) triangular by Gaussian elimination.\n  # This method only adds multiples of rows to other rows. No rows are\n  # scaled up or switched, and the determinant is preserved.\n  toRightTriangular: =>\n    M = this.dup()\n    n = this.els.length\n    k = n\n    kp = this.els[0].length\n    while (--n)\n      i = k - n\n      if (M.els[i][i] == 0)\n        for j in [i + 1...k]\n          if (M.els[j][i] != 0)\n            els = []\n            np = kp\n            np += 1\n            while (--np)\n              p = kp - np\n              els.push(M.els[i][p] + M.els[j][p])\n            M.els[i] = els\n            break\n      if (M.els[i][i] != 0)\n        for j in [i + 1...k]\n          multiplier = M.els[j][i] / M.els[i][i]\n          els = []\n          np = kp\n          np += 1\n          while (--np)\n            p = kp - np\n            # Elements with column numbers up to an including the number\n            # of the row that we're subtracting can safely be set straight to\n            # zero, since that's the point of this routine and it avoids having\n            # to loop over and correct rounding errors later\n            els.push(if p <= i then 0 else M.els[j][p] - M.els[i][p] * multiplier)\n          M.els[j] = els\n    return M\n\n  # Returns the result of attaching the given argument to the right-hand side of the matrix\n  augment: (matrix) =>\n    M = matrix.els || matrix\n    M = new Matrix(M).els if (typeof(M[0][0]) == 'undefined')\n    T = this.dup()\n    cols = T.els[0].length\n    ni = T.els.length\n    ki = ni\n    kj = M[0].length\n    return null if (ni != M.length)\n    ni += 1\n    while (--ni)\n      i = ki - ni\n      nj = kj\n      nj += 1\n      while (--nj)\n        j = kj - nj\n        T.els[i][cols + j] = M[i][j]\n\n    return T\n\n  # Returns the inverse (if one exists) using Gauss-Jordan\n  inverse: =>\n    ni = this.els.length\n    ki = ni\n    M = this.augment(Matrix.I(ni)).toRightTriangular()\n    kp = M.els[0].length\n    inverse_elements = []\n    # Matrix is non-singular so there will be no zeros on the diagonal\n    # Cycle through rows from last to first\n    ni += 1\n    while (--ni)\n      i = ni - 1\n      # First, normalise diagonal elements to 1\n      els = []\n      np = kp\n      inverse_elements[i] = []\n      divisor = M.els[i][i]\n      np += 1\n      while (--np)\n        p = kp - np\n        new_element = M.els[i][p] / divisor\n        els.push(new_element)\n        # Shuffle of the current row of the right hand side into the results\n        # array as it will not be modified by later runs through this loop\n        if (p >= ki)\n          inverse_elements[i].push(new_element)\n\n      M.els[i] = els\n      # Then, subtract this row from those above it to\n      # give the identity matrix on the left hand side\n      for j in [0...i]\n        els = []\n        np = kp\n        np += 1\n        while (--np)\n          p = kp - np\n          els.push(M.els[j][p] - M.els[i][p] * M.els[j][i])\n        M.els[j] = els\n\n    return new Matrix(inverse_elements)\n\n  @I = (n) ->\n    els = []\n    k = n\n    n += 1\n    while --n\n      i = k - n\n      els[i] = []\n      nj = k\n      nj += 1\n      while --nj\n        j = k - nj\n        els[i][j] = if (i == j) then 1 else 0\n\n    new Matrix(els)\n\n  decompose: =>\n    matrix = @\n    translate = []\n    scale = []\n    skew = []\n    quaternion = []\n    perspective = []\n\n    # Deep copy\n    els = []\n    for i in [0..3]\n      els[i] = []\n      for j in [0..3]\n        els[i][j] = matrix.els[i][j]\n\n    if (els[3][3] == 0)\n      return false\n\n    # Normalize the matrix.\n    for i in [0..3]\n      for j in [0..3]\n        els[i][j] /= els[3][3]\n\n    # perspectiveMatrix is used to solve for perspective, but it also provides\n    # an easy way to test for singularity of the upper 3x3 component.\n    perspectiveMatrix = matrix.dup()\n\n    for i in [0..2]\n      perspectiveMatrix.els[i][3] = 0\n    perspectiveMatrix.els[3][3] = 1\n\n    # Don't do this anymore, it would return false for scale(0)..\n    # if perspectiveMatrix.determinant() == 0\n    #   return false\n\n    # First, isolate perspective.\n    if els[0][3] != 0 || els[1][3] != 0 || els[2][3] != 0\n      # rightHandSide is the right hand side of the equation.\n      rightHandSide = new Vector(els[0..3][3])\n\n      # Solve the equation by inverting perspectiveMatrix and multiplying\n      # rightHandSide by the inverse.\n      inversePerspectiveMatrix = perspectiveMatrix.inverse()\n      transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose()\n      perspective = transposedInversePerspectiveMatrix.multiply(rightHandSide).els\n\n      # Clear the perspective partition\n      for i in [0..2]\n        els[i][3] = 0\n      els[3][3] = 1\n    else\n      # No perspective.\n      perspective = [0,0,0,1]\n\n    # Next take care of translation\n    for i in [0..2]\n      translate[i] = els[3][i]\n      els[3][i] = 0\n\n    # Now get scale and shear. 'row' is a 3 element array of 3 component vectors\n    row = []\n    for i in [0..2]\n      row[i] = new Vector(els[i][0..2])\n\n    # Compute X scale factor and normalize first row.\n    scale[0] = row[0].length()\n    row[0] = row[0].normalize()\n\n    # Compute XY shear factor and make 2nd row orthogonal to 1st.\n    skew[0] = row[0].dot(row[1])\n    row[1] = row[1].combine(row[0], 1.0, -skew[0])\n\n    # Now, compute Y scale and normalize 2nd row.\n    scale[1] = row[1].length()\n    row[1] = row[1].normalize()\n    skew[0] /= scale[1]\n\n    # Compute XZ and YZ shears, orthogonalize 3rd row\n    skew[1] = row[0].dot(row[2])\n    row[2] = row[2].combine(row[0], 1.0, -skew[1])\n    skew[2] = row[1].dot(row[2])\n    row[2] = row[2].combine(row[1], 1.0, -skew[2])\n\n    # Next, get Z scale and normalize 3rd row.\n    scale[2] = row[2].length()\n    row[2] = row[2].normalize()\n    skew[1] /= scale[2]\n    skew[2] /= scale[2]\n\n    # At this point, the matrix (in rows) is orthonormal.\n    # Check for a coordinate system flip.  If the determinant\n    # is -1, then negate the matrix and the scaling factors.\n    pdum3 = row[1].cross(row[2])\n    if row[0].dot(pdum3) < 0\n      for i in [0..2]\n        scale[i] *= -1\n        for j in [0..2]\n          row[i].els[j] *= -1\n\n    # Get element at row\n    rowElement = (index, elementIndex) ->\n      row[index].els[elementIndex]\n\n    # Euler angles\n    rotate = []\n    rotate[1] = Math.asin(-rowElement(0, 2))\n    if Math.cos(rotate[1]) != 0\n      rotate[0] = Math.atan2(rowElement(1, 2), rowElement(2, 2))\n      rotate[2] = Math.atan2(rowElement(0, 1), rowElement(0, 0))\n    else\n      rotate[0] = Math.atan2(-rowElement(2, 0), rowElement(1, 1))\n      rotate[1] = 0\n\n    # Now, get the rotations out\n    t = rowElement(0, 0) + rowElement(1, 1) + rowElement(2, 2) + 1.0\n    if t > 1e-4\n      s = 0.5 / Math.sqrt(t)\n      w = 0.25 / s\n      x = (rowElement(2, 1) - rowElement(1, 2)) * s\n      y = (rowElement(0, 2) - rowElement(2, 0)) * s\n      z = (rowElement(1, 0) - rowElement(0, 1)) * s\n    else if (rowElement(0, 0) > rowElement(1, 1)) && (rowElement(0, 0) > rowElement(2, 2))\n      s = Math.sqrt(1.0 + rowElement(0, 0) - rowElement(1, 1) - rowElement(2, 2)) * 2.0\n      x = 0.25 * s\n      y = (rowElement(0, 1) + rowElement(1, 0)) / s\n      z = (rowElement(0, 2) + rowElement(2, 0)) / s\n      w = (rowElement(2, 1) - rowElement(1, 2)) / s\n    else if rowElement(1, 1) > rowElement(2, 2)\n      s = Math.sqrt(1.0 + rowElement(1, 1) - rowElement(0, 0) - rowElement(2, 2)) * 2.0\n      x = (rowElement(0, 1) + rowElement(1, 0)) / s\n      y = 0.25 * s\n      z = (rowElement(1, 2) + rowElement(2, 1)) / s\n      w = (rowElement(0, 2) - rowElement(2, 0)) / s\n    else\n      s = Math.sqrt(1.0 + rowElement(2, 2) - rowElement(0, 0) - rowElement(1, 1)) * 2.0\n      x = (rowElement(0, 2) + rowElement(2, 0)) / s\n      y = (rowElement(1, 2) + rowElement(2, 1)) / s\n      z = 0.25 * s\n      w = (rowElement(1, 0) - rowElement(0, 1)) / s\n\n    quaternion = [x, y, z, w]\n\n    result = new DecomposedMatrix\n    result.translate = translate\n    result.scale = scale\n    result.skew = skew\n    result.quaternion = quaternion\n    result.perspective = perspective\n    result.rotate = rotate\n\n    for typeKey, type of result\n      for k, v of type\n        type[k] = 0 if isNaN(v)\n\n    result\n\n  toString: =>\n    str = 'matrix3d('\n    for i in [0..3]\n      for j in [0..3]\n        str += roundf(@els[i][j], 10)\n        str += ',' unless i == 3 and j == 3\n    str += ')'\n    str\n\n  @matrixForTransform: cacheFn (transform) ->\n    matrixEl = document.createElement('div')\n    matrixEl.style.position = 'absolute'\n    matrixEl.style.visibility = 'hidden'\n    matrixEl.style[propertyWithPrefix(\"transform\")] = transform\n    document.body.appendChild(matrixEl)\n    style = window.getComputedStyle(matrixEl, null)\n    result = style.transform ? style[propertyWithPrefix(\"transform\")] ? dynamics.tests?.matrixForTransform(transform)\n    document.body.removeChild(matrixEl)\n    result\n\n  @fromTransform: (transform) ->\n    match = transform?.match /matrix3?d?\\(([-0-9,e \\.]*)\\)/\n    if match\n      digits = match[1].split(',')\n      digits = digits.map(parseFloat)\n      if digits.length == 6\n        # format: matrix(a, c, b, d, tx, ty)\n        elements = [digits[0], digits[1], 0, 0, digits[2], digits[3], 0, 0, 0, 0, 1, 0, digits[4], digits[5], 0, 1]\n      else\n        elements = digits\n    else\n      elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]\n\n    matrixElements = []\n    for i in [0..3]\n      matrixElements.push(elements.slice(i * 4,i * 4 + 4))\n    new Matrix(matrixElements)\n\n# Support\nprefixFor = cacheFn (property) ->\n  return '' if document.body.style[property] != undefined\n  propArray = property.split('-')\n  propertyName = \"\"\n  for prop in propArray\n    propertyName += prop.substring(0, 1).toUpperCase() + prop.substring(1)\n  for prefix in [ \"Webkit\", \"Moz\", \"ms\" ]\n    k = prefix + propertyName\n    if document.body.style[k] != undefined\n      return prefix\n  ''\npropertyWithPrefix = cacheFn (property) ->\n  prefix = prefixFor(property)\n  return \"#{prefix}#{property.substring(0, 1).toUpperCase() + property.substring(1)}\" if prefix == 'Moz'\n  return \"-#{prefix.toLowerCase()}-#{toDashed(property)}\" if prefix != ''\n  toDashed(property)\n\n# Run loop\nrAF = window?.requestAnimationFrame\nanimations = []\nanimationsTimeouts = []\nslow = false\nslowRatio = 1\n\nwindow?.addEventListener 'keyup', (e) ->\n  # Enable slow animations with ctrl+shift+D\n  if e.keyCode == 68 and e.shiftKey and e.ctrlKey\n    dynamics.toggleSlow()\n\nif !rAF?\n  lastTime = 0\n  rAF = (callback) ->\n    currTime = Date.now()\n    timeToCall = Math.max(0, 16 - (currTime - lastTime))\n    id = window.setTimeout ->\n      callback(currTime + timeToCall)\n    , timeToCall\n    lastTime = currTime + timeToCall\n    id\n\nrunLoopRunning = false\nrunLoopPaused = false\nstartRunLoop = ->\n  unless runLoopRunning\n    runLoopRunning = true\n    rAF(runLoopTick)\n\nrunLoopTick = (t) ->\n  if runLoopPaused\n    rAF(runLoopTick)\n    return\n\n  # Animations\n  toRemoveAnimations = []\n  for animation in animations\n    toRemoveAnimations.push(animation) unless animationTick(t, animation)\n  animations = animations.filter (animation) ->\n    toRemoveAnimations.indexOf(animation) == -1\n\n  if animations.length == 0\n    runLoopRunning = false\n  else\n    rAF(runLoopTick)\n\nanimationTick = (t, animation) ->\n  animation.tStart ?= t\n  tt = (t - animation.tStart) / animation.options.duration\n  y = animation.curve(tt)\n\n  properties = {}\n  if tt >= 1\n    if animation.curve.returnsToSelf\n      properties = animation.properties.start\n    else\n      properties = animation.properties.end\n  else\n    for key, property of animation.properties.start\n      properties[key] = interpolate(property, animation.properties.end[key], y)\n\n  applyFrame(animation.el, properties)\n\n  animation.options.change?(animation.el, Math.min(1, tt))\n  if tt >= 1\n    animation.options.complete?(animation.el)\n\n  return tt < 1\n\ninterpolate = (start, end, y) ->\n  if start? and start.interpolate?\n    return start.interpolate(end, y)\n  null\n\n# Animations\nstartAnimation = (el, properties, options, timeoutId) ->\n  if timeoutId?\n    animationsTimeouts = animationsTimeouts.filter (timeout) ->\n      return timeout.id != timeoutId\n\n  dynamics.stop(el, { timeout: false })\n  if !options.animated\n    dynamics.css(el, properties)\n    options.complete?(@)\n    return\n  startProperties = getCurrentProperties(el, Object.keys(properties))\n\n  properties = parseProperties(properties)\n\n  endProperties = {}\n  transforms = []\n  for k, v of properties\n    if el.style? and transformProperties.contains(k)\n      transforms.push([k, v])\n    else\n      endProperties[k] = createInterpolable(v)\n\n  if transforms.length > 0\n    isSVG = isSVGElement(el)\n    if isSVG\n      matrix = new Matrix2D()\n      matrix.applyProperties(transforms)\n    else\n      v = (transforms.map (transform) ->\n        transformValueForProperty(transform[0], transform[1])\n      ).join(\" \")\n      matrix = Matrix.fromTransform(Matrix.matrixForTransform(v))\n    endProperties['transform'] = matrix.decompose()\n\n    if isSVG\n      startProperties.transform.applyRotateCenter(\n        [endProperties.transform.props.rotate[1], endProperties.transform.props.rotate[2]]\n      )\n\n  addUnitsToNumberInterpolables(el, endProperties)\n\n  animations.push({\n    el: el,\n    properties: {\n      start: startProperties,\n      end: endProperties\n    },\n    options: options,\n    curve: options.type.call(options.type, options)\n  })\n  startRunLoop()\n\n# Timeouts\ntimeouts = []\ntimeoutLastId = 0\n\nsetRealTimeout = (timeout) ->\n  return unless isDocumentVisible()\n  # Because in iframe, rAF might not run directly even if tab is visible\n  rAF(->\n    # Timeout might have been cancelled already\n    return if timeouts.indexOf(timeout) == -1\n    timeout.realTimeoutId = setTimeout(->\n      timeout.fn()\n      cancelTimeout(timeout.id)\n    , timeout.delay)\n  )\n\naddTimeout = (fn, delay) ->\n  timeoutLastId += 1\n  timeout = {\n    id: timeoutLastId,\n    tStart: Date.now(),\n    fn: fn,\n    delay: delay,\n    originalDelay: delay\n  }\n  setRealTimeout(timeout)\n  timeouts.push(timeout)\n  timeoutLastId\n\ncancelTimeout = (id) ->\n  timeouts = timeouts.filter (timeout) ->\n    if timeout.id == id && timeout.realTimeoutId\n      clearTimeout(timeout.realTimeoutId)\n    timeout.id != id\n\nleftDelayForTimeout = (time, timeout) ->\n  if time?\n    consumedDelay = time - timeout.tStart\n    timeout.originalDelay - consumedDelay\n  else\n    timeout.originalDelay\n\nwindow?.addEventListener('unload', ->\n  # This is a hack for Safari to fix the case where the user does back/forward\n  # between this page. If this event is not listened to, it seems like safari is keeping\n  # the javascript state but this cause problems with setTimeout/rAF\n)\n\n# Visibility change\n# Need to pause rAF and timeouts\ntimeBeforeVisibilityChange = null\nobserveVisibilityChange (visible) ->\n  runLoopPaused = !visible\n  if !visible\n    timeBeforeVisibilityChange = Date.now()\n\n    for timeout in timeouts\n      clearTimeout(timeout.realTimeoutId)\n  else\n    if runLoopRunning\n      difference = Date.now() - timeBeforeVisibilityChange\n      for animation in animations\n        animation.tStart += difference if animation.tStart?\n\n    for timeout in timeouts\n      timeout.delay = leftDelayForTimeout(timeBeforeVisibilityChange, timeout)\n      setRealTimeout(timeout)\n\n    timeBeforeVisibilityChange = null\n\n# Module\ndynamics = {}\n\n# Curves\ndynamics.linear = ->\n  (t) ->\n    t\n\ndynamics.spring = (options={}) ->\n  applyDefaults(options, dynamics.spring.defaults)\n\n  frequency = Math.max(1, options.frequency / 20)\n  friction = Math.pow(20, options.friction / 100)\n  s = options.anticipationSize / 1000\n  decal = Math.max(0, s)\n\n  # In case of anticipation\n  A1 = (t) ->\n    M = 0.8\n\n    x0 = (s / (1 - s))\n    x1 = 0\n\n    b = (x0 - (M * x1)) / (x0 - x1)\n    a = (M - b) / x0\n\n    (a * t * options.anticipationStrength / 100) + b\n\n  # Normal curve\n  A2 = (t) ->\n    Math.pow(friction / 10,-t) * (1 - t)\n\n  (t) ->\n    frictionT = (t / (1 - s)) - (s / (1 - s))\n\n    if t < s\n      yS = (s / (1 - s)) - (s / (1 - s))\n      y0 = (0 / (1 - s)) - (s / (1 - s))\n      b = Math.acos(1 / A1(yS))\n      a = (Math.acos(1 / A1(y0)) - b) / (frequency * (-s))\n      A = A1\n    else\n      A = A2\n\n      b = 0\n      a = 1\n\n    At = A(frictionT)\n\n    angle = frequency * (t - s) * a + b\n    1 - (At * Math.cos(angle))\n\ndynamics.bounce = (options={}) ->\n  applyDefaults(options, dynamics.bounce.defaults)\n\n  frequency = Math.max(1, options.frequency / 20)\n  friction = Math.pow(20, options.friction / 100)\n  A = (t) ->\n    Math.pow(friction / 10,-t) * (1 - t)\n\n  fn = (t) ->\n\n    b = -3.14/2\n    a = 1\n\n    At = A(t)\n\n    angle = frequency * t * a + b\n    (At * Math.cos(angle))\n  fn.returnsToSelf = true\n  fn\n\ndynamics.gravity = (options={}) ->\n  applyDefaults(options, dynamics.gravity.defaults)\n\n  bounciness = Math.min((options.bounciness / 1250), 0.8)\n  elasticity = options.elasticity / 1000\n  gravity = 100\n\n  curves = []\n  L = do ->\n    b = Math.sqrt(2 / gravity)\n    curve = { a: -b, b: b, H: 1 }\n    if options.returnsToSelf\n      curve.a = 0\n      curve.b = curve.b * 2\n    while curve.H > 0.001\n      L = curve.b - curve.a\n      curve = { a: curve.b, b: curve.b + L * bounciness, H: curve.H * bounciness * bounciness }\n    curve.b\n\n  getPointInCurve = (a, b, H, t) ->\n    L = b - a\n    t2 = (2 / L) * (t) - 1 - (a * 2 / L)\n    c = t2 * t2 * H - H + 1\n    c = 1 - c if options.returnsToSelf\n    c\n\n  # Create curves\n  do ->\n    b = Math.sqrt(2 / (gravity * L * L))\n    curve = { a: -b, b: b, H: 1 }\n    if options.returnsToSelf\n      curve.a = 0\n      curve.b = curve.b * 2\n    curves.push curve\n    L2 = L\n    while curve.b < 1 and curve.H > 0.001\n      L2 = curve.b - curve.a\n      curve = { a: curve.b, b: curve.b + L2 * bounciness, H: curve.H * elasticity }\n      curves.push curve\n\n  fn = (t) ->\n    i = 0\n    curve = curves[i]\n    while(!(t >= curve.a and t <= curve.b))\n      i += 1\n      curve = curves[i]\n      break unless curve\n\n    if !curve\n      v = if options.returnsToSelf then 0 else 1\n    else\n      v = getPointInCurve(curve.a, curve.b, curve.H, t)\n    v\n  fn.returnsToSelf = options.returnsToSelf\n  fn\n\ndynamics.forceWithGravity = (options={}) ->\n  applyDefaults(options, dynamics.forceWithGravity.defaults)\n  options.returnsToSelf = true\n  dynamics.gravity(options)\n\ndynamics.bezier = do ->\n  Bezier_ = (t, p0, p1, p2, p3) ->\n    (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\n\n  Bezier = (t, p0, p1, p2, p3) ->\n    {\n      x: Bezier_(t, p0.x, p1.x, p2.x, p3.x),\n      y: Bezier_(t, p0.y, p1.y, p2.y, p3.y)\n    }\n\n  yForX = (xTarget, Bs, returnsToSelf) ->\n    # Find the right Bezier curve first\n    B = null\n    for aB in Bs\n      if xTarget >= aB(0).x and xTarget <= aB(1).x\n        B = aB\n      break if B != null\n\n    unless B\n      if returnsToSelf\n        return 0\n      else\n        return 1\n\n    # Find the percent with dichotomy\n    xTolerance = 0.0001\n    lower = 0\n    upper = 1\n    percent = (upper + lower) / 2\n\n    x = B(percent).x\n    i = 0\n\n    while Math.abs(xTarget - x) > xTolerance and i < 100\n      if xTarget > x\n        lower = percent\n      else\n        upper = percent\n\n      percent = (upper + lower) / 2\n      x = B(percent).x\n      i += 1\n\n    # Returns y at this specific percent\n    return B(percent).y\n\n  # Actual bezier function\n  (options={}) ->\n    points = options.points\n\n    # Init different curves\n    Bs = do ->\n      Bs = []\n      for i of points\n        k = parseInt(i)\n        break if k >= points.length - 1\n        ((pointA, pointB) ->\n          B2 = (t) ->\n            Bezier(t, pointA, pointA.cp[pointA.cp.length - 1], pointB.cp[0], pointB)\n          Bs.push(B2)\n        )(points[k], points[k + 1])\n      Bs\n\n    fn = (t) ->\n      if t == 0\n        return 0\n      else if t == 1\n        return 1\n      else\n        yForX(t, Bs, @returnsToSelf)\n    fn.returnsToSelf = points[points.length - 1].y == 0\n    fn\n\ndynamics.easeInOut = (options={}) ->\n  friction = options.friction ? dynamics.easeInOut.defaults.friction\n  dynamics.bezier(points: [\n    { x:0, y:0, cp:[{ x:0.92 - (friction / 1000), y:0 }] },\n    { x:1, y:1, cp:[{ x:0.08 + (friction / 1000), y:1 }] }\n  ])\n\ndynamics.easeIn = (options={}) ->\n  friction = options.friction ? dynamics.easeIn.defaults.friction\n  dynamics.bezier(points: [\n    { x:0, y:0, cp:[{ x:0.92 - (friction / 1000), y:0 }] },\n    { x:1, y:1, cp:[{ x:1, y:1 }] }\n  ])\n\ndynamics.easeOut = (options={}) ->\n  friction = options.friction ? dynamics.easeOut.defaults.friction\n  dynamics.bezier(points: [\n    { x:0, y:0, cp:[{ x:0, y:0 }] },\n    { x:1, y:1, cp:[{ x:0.08 + (friction / 1000), y:1 }] }\n  ])\n\n# Default options\ndynamics.spring.defaults =\n  frequency: 300\n  friction: 200\n  anticipationSize: 0\n  anticipationStrength: 0\ndynamics.bounce.defaults =\n  frequency: 300\n  friction: 200\ndynamics.forceWithGravity.defaults = dynamics.gravity.defaults =\n  bounciness: 400\n  elasticity: 200\ndynamics.easeInOut.defaults = dynamics.easeIn.defaults = dynamics.easeOut.defaults =\n  friction: 500\n\n# CSS\ndynamics.css = makeArrayFn (el, properties) ->\n  applyProperties(el, properties, true)\n\n# Animation\ndynamics.animate = makeArrayFn (el, properties, options={}) ->\n  options = clone(options)\n  applyDefaults(options, {\n    type: dynamics.easeInOut,\n    duration: 1000,\n    delay: 0,\n    animated: true\n  })\n  options.duration = Math.max(0, options.duration * slowRatio)\n  options.delay = Math.max(0, options.delay)\n\n  if options.delay == 0\n    startAnimation(el, properties, options)\n  else\n    id = dynamics.setTimeout ->\n      startAnimation(el, properties, options, id)\n    , options.delay\n    animationsTimeouts.push({\n      id: id,\n      el: el\n    })\n\ndynamics.stop = makeArrayFn (el, options={}) ->\n  options.timeout ?= true\n  if options.timeout\n    # Clear timeouts too\n    animationsTimeouts = animationsTimeouts.filter (timeout) ->\n      if timeout.el == el and (!options.filter? or options.filter(timeout))\n        dynamics.clearTimeout(timeout.id)\n        return false\n      true\n\n  animations = animations.filter (animation) ->\n    animation.el != el\n\ndynamics.setTimeout = (fn, delay) ->\n  addTimeout(fn, delay * slowRatio)\n\ndynamics.clearTimeout = (id) ->\n  cancelTimeout(id)\n\ndynamics.toggleSlow = ->\n  slow = !slow\n  if slow\n    slowRatio = 3\n  else\n    slowRatio = 1\n  console?.log?(\"dynamics.js: slow animations #{if slow then \"enabled\" else \"disabled\"}\")\n\n# CommonJS\nif typeof module == \"object\" and typeof module.exports == \"object\"\n  module.exports = dynamics\n# AMD\nelse if typeof define == \"function\"\n  define('dynamics', -> dynamics)\n# Global\nelse\n  window.dynamics = dynamics\n"
  },
  {
    "path": "test/dynamics.coffee",
    "content": "mocha = require('mocha')\njsdom = require('mocha-jsdom')\nexpect = require('chai').expect\nassert = require('chai').assert\ndynamics = require('../src/dynamics')\n\njsdom()\n\ndynamics.tests =\n  matrixForTransform: (transform) ->\n    if transform == \"translateX(50px) rotateZ(45deg)\"\n      return \"matrix3d(0.7071067811865476, 0.7071067811865475, 0, 0, -0.7071067811865475, 0.7071067811865476, 0, 0, 0, 0, 1, 0, 50, 0, 0, 1)\"\n\nexpectEqualMatrix3d = (a, b) ->\n  r = /matrix3?d?\\(([-0-9, \\.]*)\\)/\n  argsA = a.match(r)?[1].split(',')\n  argsB = b.match(r)?[1].split(',')\n  for i in [0...argsA.length]\n    expect(Math.abs(parseFloat(argsA[i]) - parseFloat(argsB[i]))).to.be.below(0.00001)\n\ndescribe 'dynamics.css', ->\n  it 'apply css to a DOM element', ->\n    el = document.createElement('div')\n    dynamics.css(el, {\n      left: 0,\n      top: \"5px\",\n      backgroundColor: \"#FF0000\"\n    })\n    expect(el.style.left).eql('0px')\n    expect(el.style.top).eql('5px')\n    expect(el.style.backgroundColor).eql('rgb(255, 0, 0)')\n\n  it 'apply transform to a DOM element', ->\n    el = document.createElement('div')\n    dynamics.css(el, {\n      translateX: 10,\n      translateY: \"0px\",\n      translateZ: \"25%\",\n      rotateZ: \"90deg\",\n      rotateX: 45,\n      skewX: 10,\n      scale: 2\n    })\n    expect(el.style.transform).eql(\"translateX(10px) translateY(0px) translateZ(25%) rotateZ(90deg) rotateX(45deg) skewX(10deg) scaleX(2) scaleY(2) scaleZ(2)\")\n\n  it 'works with an array of DOM element', ->\n    els = [\n      document.createElement('div'),\n      document.createElement('div')\n    ]\n    dynamics.css(els, {\n      left: \"10px\"\n    })\n    expect(els[0].style.left).eql('10px')\n    expect(els[1].style.left).eql('10px')\n\ndescribe 'dynamics.animate', ->\n  it 'animate position properties of a DOM element', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      left: 100,\n      top: \"50px\",\n      translateX: 50,\n      rotateZ: 45\n    }, {\n      duration: 25,\n      type: dynamics.easeInOut\n    })\n    setTimeout ->\n      expect(el.style.left).eql(\"100px\")\n      expect(el.style.top).eql(\"50px\")\n      expectEqualMatrix3d(el.style.transform, dynamics.tests.matrixForTransform(\"translateX(50px) rotateZ(45deg)\"))\n      done()\n    , 50\n\n  it 'animate scrollTop of a DOM element', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      scrollTop: 100,\n    }, {\n      duration: 25,\n      type: dynamics.easeInOut\n    })\n    setTimeout ->\n      expect(el.scrollTop).eql('100')\n      done()\n    , 50\n\n  it 'animate with a delay', (done) ->\n    el = document.createElement('div')\n    el.style.left = 0\n    dynamics.animate(el, {\n      left: 100\n    }, {\n      duration: 25,\n      delay: 100,\n      type: dynamics.easeInOut\n    })\n    setTimeout ->\n      expect(el.style.left).eql(\"0px\")\n    , 50\n    setTimeout ->\n      expect(el.style.left).not.eql(\"100px\")\n    , 110\n    setTimeout ->\n      expect(el.style.left).eql(\"100px\")\n      done()\n    , 150\n\n  it 'works with an array of elements', (done) ->\n    els = [\n      document.createElement('div'),\n      document.createElement('div')\n    ]\n    el0asserted = false\n    el1asserted = false\n    dynamics.animate(els, {\n      left: 100,\n    }, {\n      duration: 25,\n      complete: (el) ->\n        el0asserted = true if el == els[0]\n        el1asserted = true if el == els[1]\n    })\n    setTimeout ->\n      expect(els[0].style.left).eql(\"100px\")\n      expect(els[1].style.left).eql(\"100px\")\n      assert(el0asserted, \"complete wasn't called with the right element\")\n      assert(el1asserted, \"complete wasn't called with the right element\")\n      done()\n    , 50\n\n  it 'calls change while the animation is running', (done) ->\n    el = document.createElement('div')\n    changeCalls = 0\n    dynamics.animate(el, {\n      left: 100,\n      top: \"50px\"\n    }, {\n      duration: 100,\n      type: dynamics.easeInOut,\n      change: ->\n        changeCalls += 1\n    })\n    setTimeout ->\n      expect(changeCalls).to.be.above(1)\n      done()\n    , 150\n\n  it 'calls change with element being animated', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      left: 100,\n      top: \"50px\"\n    }, {\n      duration: 100,\n      type: dynamics.easeInOut,\n      change: (element) ->\n        assert(el == element, \"Element should be the same\")\n    })\n    setTimeout ->\n      done()\n    , 150\n\n  it 'calls change with progress incrementing', (done) ->\n    el = document.createElement('div')\n    savedProgress = -1\n    dynamics.animate(el, {\n      left: 100,\n      top: \"50px\"\n    }, {\n      duration: 100,\n      type: dynamics.easeInOut,\n      change: (el, progress) ->\n        assert(progress > savedProgress, \"Progress should increment\")\n        assert(progress >= 0 && progress <= 1, \"Progress should be in [0, 1] range\")\n        savedProgress = progress\n    })\n    setTimeout ->\n      assert(savedProgress == 1, \"Progress should end with 1\")\n      done()\n    , 150\n\n  it 'actually animates properties while the animation is running', (done) ->\n    el = document.createElement('div')\n    previous = { left: 0, top: 0, translateX: 0, rotateZ: 0, transform: 'none' }\n    dynamics.animate(el, {\n      left: 100,\n      top: \"50px\",\n      translateX: 50,\n      rotateZ: 45\n    }, {\n      duration: 100,\n      type: dynamics.easeInOut\n    })\n    interval = setInterval ->\n      current = { left: parseFloat(el.style.left), top: parseFloat(el.style.top), transform: el.style.transform }\n      assert(current.left >= previous.left, \"Left should increment\")\n      assert(current.top >= previous.top, \"Top should increment\")\n      assert(current.transform != previous.transform or (current.transform == previous.transform && current.transform != \"none\"), \"Transform should change\")\n      previous = current\n    , 20\n    setTimeout ->\n      clearInterval(interval)\n      done()\n    , 150\n\n  it 'calls complete when the animation is over', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      left: 100,\n      top: \"50px\"\n    }, {\n      duration: 25,\n      complete: ->\n        done()\n    })\n\n  it 'comes back to the original value with dynamics.bounce', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      left: 100\n    }, {\n      duration: 25,\n      type: dynamics.bounce,\n      complete: ->\n        expect(el.style.left).eql(\"0px\")\n        done()\n    })\n\n  it 'animates the points of a svg element correctly', (done) ->\n    regex = /M([.\\d]*),([.\\d]*) C([.\\d]*),([.\\d]*)/\n    dynamics.tests.isSVG = (el) ->\n      true\n    el = document.createElement('polygon')\n    el.setAttribute(\"points\", \"M101.88,22 C101.88,18.25\")\n    previous = el.getAttribute(\"points\").match(regex)\n    dynamics.animate(el, {\n      points: \"M50,10 C88.11,20.45\"\n    }, {\n      duration: 100\n    })\n    interval = setInterval ->\n      current = el.getAttribute(\"points\").match(regex)\n      assert(current?)\n      expect(parseFloat(current[1])).to.at.most(parseFloat(previous[1]))\n      expect(parseFloat(current[2])).to.at.most(parseFloat(previous[2]))\n      expect(parseFloat(current[3])).to.at.most(parseFloat(previous[3]))\n      expect(parseFloat(current[4])).to.at.least(parseFloat(previous[4]))\n      previous = current\n    , 20\n    setTimeout ->\n      clearInterval(interval)\n      expect(el.getAttribute(\"points\")).to.be.equal(\"M50,10 C88.11,20.45\")\n      done()\n    , 150\n\n\n  it 'animates the points of a svg path correctly', (done) ->\n    el = document.createElement('path')\n\n    # On chrome 52 getComputedStyle give a \"d\" property for path\n    # Mock window.getComputedStyle\n    style = window.getComputedStyle(el, null)\n    style.setProperty('d', 'path(10 20 30)')\n    oldComputed = window.getComputedStyle\n    window.getComputedStyle = (el, pseudoElt) -> style\n\n    dynamics.tests.isSVG = (el) -> true\n    el.setAttribute(\"d\", \"M101.88,22 C101.88,18.25\")\n    dynamics.animate(el, {\n      d: \"M50,10 C88.11,20.45\"\n    }, {\n      duration: 100\n    })\n    setTimeout ->\n      expect(el.getAttribute(\"d\")[0]).to.be.equal('M')\n      window.getComputedStyle = oldComputed # remove mock to avoid conflict for the next test\n      done()\n    , 50\n\n  it 'animates properties of an object correctly', (done) ->\n    assertTypes = (object) ->\n      expect(typeof(object.number)).to.be.equal('number', 'object.number has the wrong type')\n      expect(typeof(object.negative)).to.be.equal('number', 'object.negative has the wrong type')\n      expect(typeof(object.string)).to.be.equal('string', 'object.string has the wrong type')\n      expect(typeof(object.stringArray)).to.be.equal('string', 'object.stringArray has the wrong type')\n      assert(object.array instanceof Array, 'object.array has the wrong type')\n      expect(typeof(object.hexColor)).to.be.equal('string', 'object.hexColor has the wrong type')\n      expect(typeof(object.rgbColor)).to.be.equal('string', 'object.rgbColor has the wrong type')\n      expect(typeof(object.rgbaColor)).to.be.equal('string', 'object.rgbaColor has the wrong type')\n      expect(typeof(object.background)).to.be.equal('string', 'object.background has the wrong type')\n\n    assertFormats = (object) ->\n      assert(object.stringArray.match(/^([.\\d]*) ([.\\d]*), d([.\\d]*):([.\\d]*)$/)?, 'object.stringArray has the wrong format')\n      assert(object.array[0].match(/^([.\\d]*)deg$/)?, 'object.array[0] has the wrong format')\n      assert(object.array[2].match(/^([.\\d]*)$/)?, 'object.array[2] has the wrong format')\n      assert(object.array[4].match(/^#([a-zA-Z\\d]{6})$/)?, 'object.array[4] has the wrong format')\n      assert(object.hexColor.match(/^#([a-zA-Z\\d]{6})$/)?, 'object.hexColor has the wrong format')\n      assert(object.rgbColor.match(/^rgb\\(([.\\d]*), ([.\\d]*), ([.\\d]*)\\)$/)?, 'object.rgbColor has the wrong format')\n      assert(object.rgbaColor.match(/^rgba\\(([.\\d]*), ([.\\d]*), ([.\\d]*), ([.\\d]*)\\)$/)?, 'object.rgbaColor has the wrong format')\n      assert(object.background.match(/^linear-gradient\\(#([a-zA-Z\\d]{6}), #([a-zA-Z\\d]{6})\\)$/)?, 'object.background has the wrong format')\n\n    object = {\n      number: 0,\n      negative: -10,\n      string: \"10\",\n      stringArray: \"10 50, d10:50\",\n      array: [\"0deg\", 0, \"1.10\", 10, \"#FFFFFF\"],\n      hexColor: \"#FFFFFF\",\n      rgbColor: \"rgb(255, 255, 255)\",\n      rgbaColor: \"rgba(255, 255, 255, 0)\",\n      translateX: 0,\n      rotateZ: 0,\n      background: \"linear-gradient(#FFFFFF, #000000)\",\n    }\n    previous = JSON.parse(JSON.stringify(object))\n    dynamics.animate(object, {\n      number: 10,\n      negative: 50,\n      string: \"50\",\n      stringArray: \"100 1, d0:100\",\n      array: [\"100deg\", 40, \"2.20\", 20, \"#123456\"],\n      hexColor: \"#123456\",\n      rgbColor: \"rgb(18, 52, 86)\",\n      rgbaColor: \"rgba(18, 52, 86, 1)\",\n      translateX: 10,\n      rotateZ: 1,\n      background: \"linear-gradient(#FF0000, #F0F0F0)\",\n    }, {\n      duration: 100\n    })\n    interval = setInterval ->\n      current = JSON.parse(JSON.stringify(object))\n\n      assertTypes(current)\n      assertFormats(current)\n\n      # Assert values are changing\n      expect(current.number).to.at.least(previous.number)\n      expect(current.negative).to.at.least(previous.negative)\n      expect(parseFloat(current.string)).to.at.least(parseFloat(previous.string))\n      stringArrayArgs = current.stringArray.match(/^([.\\d]*) ([.\\d]*), d([.\\d]*):([.\\d]*)$/)\n      previousStringArrayArgs = previous.stringArray.match(/^([.\\d]*) ([.\\d]*), d([.\\d]*):([.\\d]*)$/)\n      expect(parseFloat(stringArrayArgs[1])).to.at.least(parseFloat(previousStringArrayArgs[1]))\n      expect(parseFloat(stringArrayArgs[2])).to.at.most(parseFloat(previousStringArrayArgs[2]))\n      expect(parseFloat(stringArrayArgs[3])).to.at.most(parseFloat(previousStringArrayArgs[3]))\n      expect(parseFloat(stringArrayArgs[4])).to.at.least(parseFloat(previousStringArrayArgs[4]))\n\n      previous = current\n    , 20\n    setTimeout ->\n      clearInterval(interval)\n      assertTypes(object)\n      assertFormats(object)\n\n      done()\n    , 150\n\n  it 'animates actual properties of an object correctly', (done) ->\n    object = {}\n    Object.defineProperty(object, \"prop\", {\n      set: (v) ->\n        @_prop = v\n      get: ->\n        @_prop\n    })\n    object.prop = 1\n\n    dynamics.animate(object, {\n      prop: 0\n    }, {\n      duration: 100\n    })\n\n    previousProp = object.prop\n\n    interval = setInterval ->\n      assert(object.prop >= 0 && object.prop <= 1, \"prop is between 0 and 1\")\n      assert(object.prop < previousProp || object.prop == 0, \"prop should be decreasing or equal 0\")\n\n      previousProp = object.prop\n    , 20\n\n    setTimeout ->\n      clearInterval(interval)\n      expect(object.prop).to.be.equal(0, 'object.prop has the wrong end value')\n\n      done()\n    , 150\n\n  it 'finishes the animation with the correct end state while using a specific bezier curve', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      left: 100,\n    }, {\n      duration: 25,\n      type: dynamics.bezier,\n      points: [\n        {\"x\":0,\"y\":0,\"cp\":[{\"x\":0,\"y\":1}]},\n        {\"x\":1,\"y\":0,\"cp\":[{\"x\":0.5,\"y\":0}]}\n      ],\n      complete: ->\n        expect(el.style.left).eql('0px')\n        done()\n    })\n\ndescribe 'dynamics.stop', ->\n  it 'actually stops current animation', (done) ->\n    el = document.createElement('div')\n    changeCanBeCalled = true\n    dynamics.animate(el, {\n      left: 100\n    }, {\n      duration: 100,\n      type: dynamics.easeInOut,\n      change: ->\n        assert(changeCanBeCalled, \"change shouldn't be called anymore\")\n      ,\n      complete: ->\n        assert(false, \"complete shouldn't be called\")\n    })\n    setTimeout ->\n      dynamics.stop(el)\n      changeCanBeCalled = false\n    , 50\n    setTimeout ->\n      done()\n    , 150\n\n  it 'also works with a delayed animation', (done) ->\n    el = document.createElement('div')\n    dynamics.animate(el, {\n      left: 100\n    }, {\n      duration: 100,\n      delay: 100,\n      change: ->\n        assert(false, \"change shouldn't be called\")\n      ,\n      complete: ->\n        assert(false, \"complete shouldn't be called\")\n    })\n    setTimeout ->\n      dynamics.stop(el)\n    , 50\n    setTimeout ->\n      done()\n    , 150\n\n  it 'also works with multiple delayed animations', (done) ->\n    els = [document.createElement('div'), document.createElement('div'), document.createElement('div')]\n    delay = 100\n    for el in els\n      dynamics.animate(el, {\n        left: 100\n      }, {\n        duration: 100,\n        delay: delay,\n        change: ->\n          assert(false, \"change shouldn't be called\")\n        ,\n        complete: ->\n          assert(false, \"complete shouldn't be called\")\n      })\n      delay += 50\n    setTimeout ->\n      for el in els\n        dynamics.stop(el)\n    , 50\n    setTimeout ->\n      done()\n    , 450\n\ndescribe 'curves', ->\n  describe 'dynamics.linear', ->\n    it 'works', ->\n      curve = dynamics.linear()\n      expect(curve(0)).eql(0)\n      expect(curve(0.1)).eql(0.1)\n      expect(curve(5)).eql(5)\n      expect(curve(5.6)).eql(5.6)\n      expect(curve(7.8)).eql(7.8)\n      expect(curve(1)).eql(1)\n\n  describe 'dynamics.easeInOut', ->\n    it 'works', ->\n      curve = dynamics.easeInOut()\n      expect(curve(0)).eql(0)\n      assert(curve(0.25) > 0 && curve(0.25) < 0.5)\n      expect(curve(0.5)).eql(0.5)\n      assert(curve(0.75) > 0.5 && curve(0.75) < 1)\n      expect(curve(1)).eql(1)\n\n  describe 'dynamics.easeIn', ->\n    it 'increases exponentially', ->\n      curve = dynamics.easeIn()\n      inter = 0.1\n      diff = 0\n      for i in [1..10]\n        t1 = inter * (i - 1)\n        t2 = inter * i\n        newDiff = curve(t2) - curve(t1)\n        assert(newDiff > diff, \"easeIn should be exponential\")\n        diff = newDiff\n\n  describe 'dynamics.easeOut', ->\n    it 'increases 1/exponentially', ->\n      curve = dynamics.easeOut()\n      inter = 0.1\n      diff = 1\n      for i in [1..10]\n        t1 = inter * (i - 1)\n        t2 = inter * i\n        newDiff = curve(t2) - curve(t1)\n        assert(newDiff < diff, \"easeOut should be 1/exponential\")\n        diff = newDiff\n\n  describe 'dynamics.bounce', ->\n    it 'starts and returns to initial state', ->\n      curve = dynamics.bounce()\n      assert(curve(0) < 0.001 && curve(0) >= 0)\n      assert(curve(1) < 0.001 && curve(1) >= 0)\n\n  describe 'dynamics.forceWithGravity', ->\n    it 'starts and returns to initial state', ->\n      curve = dynamics.forceWithGravity()\n      assert(curve(0) < 0.001 && curve(0) >= 0)\n      assert(curve(1) < 0.001 && curve(1) >= 0)\n\ndescribe 'dynamics.setTimeout', ->\n  it 'works', (done) ->\n    t = Date.now()\n    dynamics.setTimeout(->\n      assert(Math.abs(Date.now() - t - 100) < 30)\n      done()\n    , 100)\n\ndescribe 'dynamics.clearTimeout', ->\n  it 'works', (done) ->\n    i = dynamics.setTimeout(->\n      assert(false)\n    , 100)\n    dynamics.clearTimeout(i)\n    setTimeout(->\n      done()\n    , 200)\n"
  }
]