├── .babelrc
├── .gitignore
├── .npmignore
├── README.md
├── assets
└── screenshot.png
├── dist
├── Animation.js
├── Choreographer.js
├── choreographer.min.js
├── defaultAnimations.js
├── getInjectedTransformString.js
└── index.js
├── examples
├── one.html
├── three.html
└── two.html
├── index.css
├── index.html
├── index.js
├── package.json
├── src
├── Animation.js
├── Choreographer.js
├── defaultAnimations.js
├── getInjectedTransformString.js
└── index.js
└── webpack.config.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [ "es2015" ]
3 | }
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules/
2 | .DS_Store
3 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | /examples/
2 | /src/
3 | /assets/
4 | webpack.config.js
5 | index.html
6 | index.js
7 | index.css
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Choreographer-js
2 |
3 | [](https://www.npmjs.com/package/choreographer-js)
4 |
5 | A simple library to take care of complex CSS animations.
6 | *(You can also add custom functions that do non-CSS animations!)*
7 |
8 | [See the fancy demo here -->](https://christinecha.github.io/choreographer-js/)
9 |
10 | **Other examples:**
11 | [Basic Example (animating based on scroll location)](https://christinecha.github.io/choreographer-js/examples/one.html)
12 | [Basic Example (animating based on mouse X location)](https://christinecha.github.io/choreographer-js/examples/two.html)
13 | [Basic Example (multiple animations based on mouse X location)](https://christinecha.github.io/choreographer-js/examples/three.html)
14 |
15 |
16 | #### Table of Contents + Useful Links
17 | 1. [Quickstart](#quickstart)
18 | 2. [Use Cases + Snippets](#use-cases--snippets)
19 | 3. [Example Code](examples)
20 | 4. [Full API Reference](#full-api-reference)
21 | 5. [Contributing](#contributing)
22 | 6. [License](#license)
23 |
24 |
25 | ## Quickstart
26 |
27 | Install and save to your `package.json`:
28 | ```
29 | $ npm install --save choreographer-js
30 | ```
31 |
32 | Include it in your Javascript:
33 | ````js
34 | const Choreographer = require('choreographer-js')
35 | ````
36 |
37 |
38 | ## Use Cases + Snippets
39 |
40 | **Brew up some instant scroll animations.** This one would scale a box's `opacity` from `0` to `1` mirroring your scroll location from the top to `1000`. [Full Example >>](examples/one.html)
41 | ````js
42 | let choreographer = new Choreographer({
43 | animations: [
44 | {
45 | range: [-1, 1000],
46 | selector: '#box',
47 | type: 'scale',
48 | style: 'opacity',
49 | from: 0,
50 | to: 1
51 | }
52 | ]
53 | })
54 |
55 | window.addEventListener('scroll', () => {
56 | choreographer.runAnimationsAt(window.pageYOffset)
57 | })
58 | ````
59 |
60 | **What about animations based on mouse movement?** This would make `#box` move `300px` down if your mouse was in the left-half of the browser window.
61 | ````js
62 | let choreographer = new Choreographer({
63 | animations: [
64 | {
65 | range: [-1, window.innerWidth / 2],
66 | selector: '#box',
67 | type: 'change',
68 | style: 'transform:translateY',
69 | to: 300,
70 | unit: 'px'
71 | }
72 | ]
73 | })
74 |
75 | document.body.addEventListener('mousemove', (e) => {
76 | choreographer.runAnimationsAt(e.clientX)
77 | })
78 | ````
79 |
80 |
81 | ## Get Started
82 | You can simply install the package via npm:
83 | ```
84 | $ npm install --save choreographer-js
85 | ```
86 | Or if you're keeping things super simple, just include [this file](dist/choreographer.min.js) as a script like so:
87 | ````html
88 |
89 | ````
90 |
91 | Cool! Now you can create an instance of Choreographer like this, and run the animations based on whatever measurement floats your boat (ex. scroll position, mouse position, timestamp, whatever).
92 | ````js
93 | let choreographer = new Choreographer(config)
94 | choreographer.runAnimationsAt(position)
95 | ````
96 |
97 | More often than not, you'll probably want to wrap that `runAnimationsAt` function in another, like an event handler, for instance:
98 | ````js
99 | window.addEventListener('scroll', () => {
100 | // then, use the scroll position (pageYOffset) to base the animations off of
101 | choreographer.runAnimationsAt(window.pageYOffset)
102 | })
103 | ````
104 |
105 | The easiest way to understand how this all works is to check out the [**examples**](examples). More detailed documentation below!
106 |
107 | ## Full API Reference
108 |
109 | ### `Choreographer`
110 |
111 | `[Class]` | The home base for everything.
112 |
113 | construction:
114 | `new Choreographer(` [`choreographerConfig`](#choreographerconfig) `)`
115 |
116 | public methods:
117 | - [`this.updateAnimations`](#update-animations)
118 | - [`this.runAnimationsAt`](#run-animations-at)
119 |
120 | ---
121 |
122 | ### `choreographerConfig`
123 |
124 | `[Object]` | The object used to configure an instance of Choreographer.
125 |
126 | example structure:
127 | ```
128 | {
129 | customFunctions: {
130 | [animation type]: [animationFunction]
131 | },
132 | animations: [ animationConfig, animationConfig, ... ]
133 | }
134 | ```
135 | related references: [`animationFunction`](#animationfunction), [`animationConfig`](#animationconfig)
136 |
137 | ---
138 |
139 | ### `Choreographer.updateAnimations([ Array of` [`animationConfig`](#animationconfig) `])`
140 |
141 | `[Function]` | Replace `this.animations` with a new Array of `Animations`.
142 |
143 | ---
144 |
145 | ### `Choreographer.runAnimationsAt([ Number ])`
146 |
147 | `[Function]` | Run the animations at a given location marker.
148 |
149 | ---
150 |
151 | ### `Animation`
152 |
153 | `[Class]` | The class that manages each animation's data.
154 |
155 | construction:
156 | `new Animation(` [`animationConfig`](#animationconfig) `)`
157 |
158 | ---
159 |
160 | ### `animationConfig`
161 |
162 | `[Object]` | The object used to configure an instance of Animation.
163 |
164 | example structure:
165 | ```
166 | {
167 | range: [0, 100],
168 | selector: '.box',
169 | type: 'scale',
170 | fn: [animationFunction],
171 | style: 'width',
172 | from: 0,
173 | to: 100,
174 | unit: '%'
175 | }
176 | ```
177 |
178 | **`range`** | `[Array of Number]` or `[Array of Array of Number]`
179 | Either a one- or two-dimensional array of ranges, i.e. [0,5] or [[0,3], [4,5]]
180 | *NOTE: Bugs will occur if you overlap animation ranges that affect the same style properties!*
181 |
182 | **`type`** | `[String]`
183 | The name of the animation function
184 |
185 | **`fn`** | `[animationFunction]`
186 | see `animationFunction`](#animationfunction)
187 |
188 | **`selector`** | `[String]` or `[NodeList]` or `[DOM Element]`
189 | A valid DOM Element, list of elements, or selector string, ex. '.classname' or '#box .thing[data-attr=true]'
190 |
191 | **`selectors`** | `[Array]`
192 | An array of selector strings (as described above).
193 |
194 | *NOTE: Only one of the below (selector or selectors) is necessary. If they both exist, 'selectors' will be used.*
195 |
196 | **`style`** | `[String]`
197 | A valid CSS style property OR the string "class" to toggle a classname instead.
198 | *NOTE: If you are using 'transform', follow it with a colon and the property name, ex. 'transform:scaleX'*
199 |
200 | **`from`** | `[Number]`
201 | The minimum value to set to the style property. Useful when progressively calculating a value.
202 |
203 | **`to`** | `[Number or String]`
204 | If you want progressively calculated (scaled) values, this has to be a **number**. Otherwise, if for something a 'change' animation, this can be a string - whatever the valid type for the relevant `style` property is.
205 |
206 | related references: [`animationFunction`](#animationfunction)
207 |
208 | ---
209 |
210 | ### `animationFunction`
211 |
212 | `[Function]` | A function that takes [`animationData`](#animationdata) and does something with it.
213 |
214 | There are two built-in animation functions available, called 'scale' and 'change'.
215 |
216 | - 'scale' maps a progressively calculated value to the node's style property based on location
217 | - 'change' adds or takes away a style property value if you're in or out of range
218 |
219 | Example animationFunction (this is a simplified version of how 'change' works):
220 | ````js
221 | (data) => {
222 | // where data is an 'animationData' object (see below)
223 | const newValueString = data.to + data.unit
224 |
225 | if (data.progress > 0 && data.progress < 1) {
226 | data.node.style[data.style] = newValueString
227 | }
228 | }
229 | ````
230 |
231 | arguments: [`animationData`](#animationdata)
232 |
233 | ---
234 |
235 | ### `animationData`
236 |
237 | `[Object]` | This is the data passed into an `animationFunction`. A lot of it is taken directly from `animationConfig`.
238 |
239 | Structure:
240 | ```
241 | {
242 | node: [DOM Element] | the element this animation will affect,
243 | progress: [Number] | a number representing the relative location of a node within a range,
244 |
245 | // these are all taken directly from the animationConfig
246 | style: (see above),
247 | from: (see above),
248 | to: (see above),
249 | unit: (see above),
250 | }
251 | ```
252 |
253 | **`Progress` is what allows for progressive scaling of values (ex. smooth fading of opacity, 2d translation, etc.)**
254 | If the value is between 0 and 1, that means you are within a range (given in animationConfig).
255 |
256 | ---
257 |
258 | ## Contributing
259 | 1. Fork it!
260 | 2. Create your feature branch: `git checkout -b my-new-feature`
261 | 3. Commit your changes: `git commit -am 'Add some feature'`
262 | 4. Push to the branch: `git push origin my-new-feature`
263 | 5. Submit a pull request :D
264 |
265 | Found an issue but don't know how to fix it? Submit an issue or email me.
266 |
267 | ---
268 |
269 | ## License
270 |
271 | The MIT License (MIT)
272 | Copyright (c) 2016 Christine Cha
273 |
274 | 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:
275 |
276 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
277 |
278 | 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.
279 |
--------------------------------------------------------------------------------
/assets/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/christinecha/choreographer-js/01694a9ab50e69f7d459b3ca2d9a5f6e4c56c776/assets/screenshot.png
--------------------------------------------------------------------------------
/dist/Animation.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
4 |
5 | var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
6 |
7 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
8 |
9 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
10 |
11 | /** The Animation class.
12 | *
13 | * constructed with the following config object properties:
14 | {String} type | the name of the animation function
15 | {Function} fn | the animation function
16 | {Array} range | either a one- or two-dimensional array of ranges, i.e. [0,5] or [[0,3], [4,5]]
17 | NOTE: Bugs will occur if you overlap animation ranges that affect the same style properties!
18 |
19 | [ Only one of the below (selector or selectors) is necessary. If they both exist, 'selectors' will be used. ]
20 | {String} selector | a valid DOM Element selector string, ex. '.classname' or '#box .thing[data-attr=true]'
21 | {Array} selectors | an array of selector strings (described above).
22 |
23 | {String} style | a valid CSS style property.
24 | NOTE: If you are using 'transform', follow it with a colon and the property name, ex. 'transform:scaleX'
25 |
26 | {Number} from | The minimum value to set to the style property. Useful when progressively calculating a value.
27 | {Number} to | The value to set to the style property. (Or the max, when progressively calculating a value.)
28 | NOTE: If you are ONLY using the 'to' value, like with a 'change' animation, this could also be {String} to.
29 |
30 | {String} unit | The unit string to append to the value, ex. '%', 'px', 'deg'
31 | **/
32 |
33 | var Animation = function () {
34 | function Animation(config) {
35 | _classCallCheck(this, Animation);
36 |
37 | this.config = config;
38 | this.storeNodes();
39 | }
40 |
41 | // Either use 'selector' or 'selectors' to find and store all the DOM nodes.
42 |
43 |
44 | _createClass(Animation, [{
45 | key: 'storeNodes',
46 | value: function storeNodes() {
47 | var _this = this;
48 |
49 | if (this.config.selector) {
50 |
51 | if (typeof this.config.selector === 'string') {
52 | this.nodes = Array.prototype.slice.call(document.querySelectorAll(this.config.selector));
53 | } else if (this.config.selector.length) {
54 | this.nodes = Array.prototype.slice.call(this.config.selector);
55 | } else {
56 | this.nodes = [this.config.selector];
57 | }
58 | }
59 |
60 | if (this.config.selectors) {
61 | this.nodes = [];
62 | this.config.selectors.forEach(function (s) {
63 |
64 | if (typeof s === 'string') {
65 | var nodes = Array.prototype.slice.call(document.querySelectorAll(s));
66 | _this.nodes = _this.nodes.concat(nodes);
67 | } else if (_this.config.selector.length) {
68 | _this.nodes = _this.nodes.concat(Array.prototype.slice.call(s));
69 | } else {
70 | _this.nodes = _this.nodes.push(s);
71 | }
72 | });
73 | }
74 | }
75 |
76 | // Just a helper to get the relative location of a value within a range.
77 | // example: getProgress(1, [0, 2]) = 0.5
78 |
79 | }, {
80 | key: 'getProgress',
81 | value: function getProgress(val, _ref) {
82 | var _ref2 = _slicedToArray(_ref, 2);
83 |
84 | var min = _ref2[0];
85 | var max = _ref2[1];
86 |
87 | return (val - min) / (max - min);
88 | }
89 |
90 | /** Returns the 'progress' - relative position within the animation range.
91 | * @param {Number} position | passed in value from 'runAt' (below)
92 | * @return {Number} progress | the relative location (between 0 and 1 when in range) within a range.
93 | if there are multiple ranges and the position is not in any of them,
94 | return -1. Otherwise, return the value (even if out of range).
95 | **/
96 |
97 | }, {
98 | key: 'getProgressAt',
99 | value: function getProgressAt(position) {
100 | // If there are multiple ranges, then figure out which one is relevant and
101 | // calculate the progress within that one. You can't have multiple active
102 | // ranges unless they're overlapping -- in which case it is YOUR bug, dude.
103 | if (_typeof(this.config.range[0]) === 'object') {
104 |
105 | var activeRange = void 0;
106 |
107 | // If there's a range that is active, store it!
108 | this.config.range.forEach(function (r) {
109 | if (isBetween(postion, r[0], r[1])) activeRange = r;
110 | });
111 |
112 | if (!activeRange) return -1;else return this.getProgress(position, activeRange);
113 | }
114 |
115 | return this.getProgress(position, this.config.range);
116 | }
117 |
118 | /** And this is where all of that work ~finally~ pays off!
119 | * This runs the animation by getting the relative progress and running accordingly.
120 | * @param {Number} position | the location marker - could be a scroll location, a timestamp, a mouseX position...
121 | **/
122 |
123 | }, {
124 | key: 'runAt',
125 | value: function runAt(position) {
126 | var _this2 = this;
127 |
128 | var progress = this.getProgressAt(position);
129 |
130 | // If we are OUT OF RANGE, then we have to do a few extra things.
131 | if (progress < 0 || progress > 1) {
132 |
133 | // First, check if any of our nodes were already animated at this same style prop, at this same location.
134 | var animated = void 0;
135 | this.nodes.forEach(function (node) {
136 | if (node.getAttribute('animated').indexOf(_this2.config.style) > -1) animated = true;
137 | });
138 |
139 | // If NOT, then you can go ahead and animate it here.
140 | // We need this checkpoint to avoid overriding each other.
141 |
142 | // If you're using class instead of style props, it don't matter.
143 | if (this.config.style === 'class' || !animated) {
144 | // If it's a simple 'change' function, we just need a value outside of 0 to 1. Could be -9.87. Doesn't matter.
145 | if (this.config.type === 'change') progress = -1;
146 |
147 | // If it's a 'scale' function, then get the min or max progress.
148 | if (this.config.type === 'scale') {
149 | if (progress < 0) progress = 0;
150 | if (progress > 1) progress = 1;
151 | }
152 | } else {
153 |
154 | // If we are OUT OF RANGE and some of our nodes are already animated, then get out of here!!!!
155 | return;
156 | }
157 | }
158 |
159 | // OK, finally ready? Run that animation, baby.
160 | this.nodes.forEach(function (node) {
161 |
162 | // If in range ---
163 | // (Notice that we're NOT doing >= and <= here. This is because if you're on the edges of the
164 | // range, you should be able to override this animation with another one.)
165 | if (progress > 0 && progress < 1) {
166 | node.setAttribute('animated', node.getAttribute('animated') + '|' + _this2.config.style);
167 | }
168 |
169 | _this2.config.fn({
170 | node: node,
171 | style: _this2.config.style,
172 | from: _this2.config.from,
173 | to: _this2.config.to,
174 | unit: _this2.config.unit,
175 | progress: progress
176 | });
177 | });
178 | }
179 | }]);
180 |
181 | return Animation;
182 | }();
183 |
184 | module.exports = Animation;
--------------------------------------------------------------------------------
/dist/Choreographer.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4 |
5 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6 |
7 | var Animation = require('./Animation');
8 | var defaultAnimations = require('./defaultAnimations');
9 |
10 | // Store a no-op
11 | var noop = function noop() {};
12 |
13 | /** Choreographer
14 | * constructed with a config object with the following keys and values:
15 | {Object} customFunctions | [optional] Keys are function names, values are animation functions.
16 | {Array} animations | An array of Animation class config objects.
17 | **/
18 |
19 | var Choreographer = function () {
20 | function Choreographer(config) {
21 | var _this = this;
22 |
23 | _classCallCheck(this, Choreographer);
24 |
25 | this.customFunctions = config.customFunctions || {};
26 | this.animations = config.animations.map(function (anim) {
27 | anim.fn = _this.getAnimationFn(anim.type);
28 | return new Animation(anim);
29 | });
30 | }
31 |
32 | /** Helper to grab a function by its type. First try the defaults, then custom, then no-op.
33 | * @param {String} type | the name (or key value) of the animation function.
34 | **/
35 |
36 |
37 | _createClass(Choreographer, [{
38 | key: 'getAnimationFn',
39 | value: function getAnimationFn(type) {
40 | return defaultAnimations[type] || this.customFunctions[type] || noop;
41 | }
42 |
43 | /** If you need to update the animation configs at any point.
44 | * @param {Array} animations | An array of your new Animation class config objects.
45 | **/
46 |
47 | }, {
48 | key: 'updateAnimations',
49 | value: function updateAnimations(animations) {
50 | var _this2 = this;
51 |
52 | // Wipe out the old animations and replace 'em.
53 | this.animations = animations.map(function (anim) {
54 | anim.fn = _this2.getAnimationFn(anim.type);
55 | return new Animation(anim);
56 | });
57 | }
58 |
59 | /** Run those animations based on a given location!
60 | * @param {Number} position | the location marker - could be a scroll location, a timestamp, a mouseX position...
61 | **/
62 |
63 | }, {
64 | key: 'runAnimationsAt',
65 | value: function runAnimationsAt(position) {
66 |
67 | // Clear all the nodes' 'animated' attribute.
68 | this.animations.forEach(function (anim) {
69 | anim.nodes.forEach(function (node) {
70 | return node.setAttribute('animated', '');
71 | });
72 | });
73 |
74 | // Run and done.
75 | this.animations.forEach(function (anim) {
76 | return anim.runAt(position);
77 | });
78 | }
79 | }]);
80 |
81 | return Choreographer;
82 | }();
83 |
84 | module.exports = Choreographer;
--------------------------------------------------------------------------------
/dist/choreographer.min.js:
--------------------------------------------------------------------------------
1 | !function(t){function n(r){if(e[r])return e[r].exports;var o=e[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var e={};return n.m=t,n.c=e,n.p="/dist/",n(0)}([function(t,n,e){"use strict";var r=e(1);t.exports=r,window.Choreographer=r},function(t,n,e){"use strict";function r(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}var o=function(){function t(t,n){for(var e=0;e1){var r=void 0;if(this.nodes.forEach(function(t){t.getAttribute("animated").indexOf(n.config.style)>-1&&(r=!0)}),r)return;"change"===this.config.type&&(e=-1),"scale"===this.config.type&&(e<0&&(e=0),e>1&&(e=1))}this.nodes.forEach(function(t){e>0&&e<1&&t.setAttribute("animated",t.getAttribute("animated")+"|"+n.config.style),n.config.fn({node:t,style:n.config.style,from:n.config.from,to:n.config.to,unit:n.config.unit,progress:e})})}}]),t}();t.exports=s},function(t,n,e){"use strict";var r=e(4),o=function(t){var n=(t.to-t.from)*t.progress+t.from,e=t.unit?n+t.unit:n;if(1===t.style.split(":").length)return void(t.node.style[t.style]=e);var o=t.style.split(":")[1];t.node.style.transform=r(t.node,o,e)},i=function(t){var n=t.progress<0?null:t.to,e=n&&t.unit?n+t.unit:n;if(t.progress<0&&"transition"===t.style)return void t.node.addEventListener("transitionend",function(n){n.target===t.node&&(t.node.style[t.style]=null)});if(1===t.style.split(":").length)return void(t.node.style[t.style]=e);var o=t.style.split(":")[1];t.node.style.transform=r(t.node,o,e)};t.exports={scale:o,change:i}},function(t,n){"use strict";var e={translateX:0,translateY:1,translateZ:2},r={scaleX:0,scaleY:1,scaleZ:2},o={transform:"transform",webkitTransform:"-webkit-transform",MozTransform:"-moz-transform",msTransform:"-ms-transform",OTransform:"-o-transform"},i=function(){if(!window.getComputedStyle)return null;var t=document.createElement("div");document.body.insertBefore(t,null);for(var n in o)if(window.getComputedStyle(t)[n])return document.body.removeChild(t),n;return document.body.removeChild(t),null},s=function(){if(!a)return!1;var t=document.createElement("div");document.body.insertBefore(t,null),t.style[a]="translate3d(1px,1px,1px)";var n=!!window.getComputedStyle(t).getPropertyValue(a);return document.body.removeChild(t),n},a=i(),u=s(),f=function(t,n,o){if(a){var i=t.style[a]||"",s=void 0,f=void 0,c=void 0;if(u&&(void 0!==e[n]?(f=e[n],n="translate3d",c=["0","0","0"],null===o&&(o=0)):void 0!==r[n]&&(f=r[n],n="scale3d",c=["1","1","1"],null===o&&(o=1)),void 0!==f)){if(i.indexOf(n)>-1){var l=(i.split(n+"(")[0],i.split(n+"(")[1].split(")")[0]);c=l.split(",")}c[f]=o,s=n+"("+c.join(",")+")"}var d=s||n+"("+o+")",m=i,y=i.indexOf(n)>-1;if(y){var v=i.split(n)[0],p=i.split(n)[1].split(")")[1];m=v+d+p}else m+=" "+d;return m}};t.exports=f}]);
--------------------------------------------------------------------------------
/dist/defaultAnimations.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var getInjectedTransformString = require('./getInjectedTransformString');
4 |
5 | /** @method scale
6 | * [built-in animation function]
7 | * Based on the data provided, your node will receive an updated, scaled style value.
8 | *
9 | * @param {Object} data : {
10 | * {Node} node | the node you want to modify
11 | * {String} style | the style property you want to modify
12 | * {Number} from | minimum value
13 | * {Number} to | maximum value
14 | * {Number} progress | a value between 0 and 1; the proportion of value we should use
15 | * {String} unit | optional - unit value, e.g. 'px' or '%'
16 | * }
17 | **/
18 | var scale = function scale(data) {
19 | // Get the relative value (proportional to the min-max range you gave.)
20 | var scaledValue = (data.to - data.from) * data.progress + data.from;
21 | // Stick on the unit, if there is one.
22 | var scaledValueString = data.unit ? scaledValue + data.unit : scaledValue;
23 |
24 | // If it's a regular old style property, just replace the value. No fuss.
25 | if (data.style.split(':').length === 1) {
26 | data.node.style[data.style] = scaledValueString;
27 | return;
28 | }
29 |
30 | /*~~ If the style is a CSS transform, we gotta do some funky shit. ~~*/
31 | var transformProp = data.style.split(':')[1];
32 | data.node.style.transform = getInjectedTransformString(data.node, transformProp, scaledValueString);
33 | };
34 |
35 | /** @method change
36 | * [built-in animation function]
37 | * Based on the data provided, your node will have the style value assigned or remok
38 | * @param {Object} data : {
39 | * {Node} node | the node you want to modify
40 | * {String} style | the style property you want to modify
41 | * {Value} to | the style value (number, string -- whatever valid type this CSS prop takes)
42 | * {Number} progress | a value between 0 and 1; the proportion of value we should use
43 | * }
44 | **/
45 | var change = function change(data) {
46 | var newValue = data.progress < 0 ? null : data.to;
47 | var newValueString = newValue && data.unit ? newValue + data.unit : newValue;
48 |
49 | // If the progress is less than 0, we just need to nullify this style value.
50 | // But, if the style prop is 'transition', apply it only after the last transition ends.
51 | if (data.progress < 0 && data.style === 'transition') {
52 | data.node.addEventListener('transitionend', function (e) {
53 | if (e.target === data.node) data.node.style[data.style] = null;
54 | });
55 | return;
56 | }
57 |
58 | // If it's a regular old style property, just replace the value. No fuss.
59 | if (data.style.split(':').length === 1) {
60 | if (data.style === 'class') {
61 | data.node.classList[newValue ? 'add' : 'remove'](data.to);
62 | return;
63 | }
64 |
65 | data.node.style[data.style] = newValueString;
66 | return;
67 | }
68 |
69 | /*~~ If the style is a CSS transform, we gotta do some funky shit. ~~*/
70 | var transformProp = data.style.split(':')[1];
71 | data.node.style.transform = getInjectedTransformString(data.node, transformProp, newValueString);
72 | };
73 |
74 | module.exports = { scale: scale, change: change };
--------------------------------------------------------------------------------
/dist/getInjectedTransformString.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var translations = {
4 | translateX: 0,
5 | translateY: 1,
6 | translateZ: 2
7 | };
8 |
9 | var scales = {
10 | scaleX: 0,
11 | scaleY: 1,
12 | scaleZ: 2
13 | };
14 |
15 | var transformKeys = {
16 | 'transform': 'transform',
17 | 'webkitTransform': '-webkit-transform',
18 | 'MozTransform': '-moz-transform',
19 | 'msTransform': '-ms-transform',
20 | 'OTransform': '-o-transform'
21 | };
22 |
23 | // Get the correct transform key value, either plain 'transform' or a prefixed one.
24 | var getTransformKey = function getTransformKey() {
25 | if (!window.getComputedStyle) return null;
26 |
27 | var el = document.createElement('div');
28 | document.body.insertBefore(el, null);
29 |
30 | for (var t in transformKeys) {
31 | if (window.getComputedStyle(el)[t]) {
32 | document.body.removeChild(el);
33 | return t;
34 | }
35 | }
36 |
37 | document.body.removeChild(el);
38 | return null;
39 | };
40 |
41 | // Check if we have 3d support
42 | var getHas3d = function getHas3d() {
43 | if (!transformKey) return false; // No transform, no 3d. GET A NEW BROWSER YO
44 |
45 | var el = document.createElement('div');
46 | document.body.insertBefore(el, null);
47 | el.style[transformKey] = 'translate3d(1px,1px,1px)';
48 |
49 | var has3d = !!window.getComputedStyle(el).getPropertyValue(transformKey);
50 | document.body.removeChild(el);
51 |
52 | return has3d;
53 | };
54 |
55 | // Cache these values
56 | var transformKey = getTransformKey();
57 | var has3d = getHas3d();
58 |
59 | var getInjectedTransformString = function getInjectedTransformString(node, prop, val) {
60 |
61 | // If your browser doesn't support even prefixed transforms... get a new browser. Bye.
62 | if (!transformKey) return;
63 |
64 | // Get the node's previous transform value and store it.
65 | var oldTransformString = node.style[transformKey] || '';
66 |
67 | // set up variable declarations for 3d stuff
68 | var transform3dString = void 0;
69 | var axis = void 0;
70 | var xyz = void 0;
71 |
72 | // If we've got 3d, then USE IT! It's sooo much smoother. #blessed
73 | if (has3d) {
74 |
75 | // If it's a translate or scale, we can 3d-ify that. (I know there's some duplication but I'd rather be explicit here.)
76 |
77 | // Axis is the index of the value we'll want to change (X is 0, Y is 1, Z is 3)
78 | // Prop is the name of the property
79 | // XYZ holds our actual values.
80 | if (translations[prop] !== undefined) {
81 | axis = translations[prop];
82 | prop = 'translate3d';
83 | xyz = ['0', '0', '0'];
84 | if (val === null) val = 0;
85 | } else if (scales[prop] !== undefined) {
86 | axis = scales[prop];
87 | prop = 'scale3d';
88 | xyz = ['1', '1', '1'];
89 | if (val === null) val = 1;
90 | }
91 |
92 | // If everything checks out, we should have our values set!
93 | if (axis !== undefined) {
94 | if (oldTransformString.indexOf(prop) > -1) {
95 | var startOfString = oldTransformString.split(prop + '(')[0];
96 | var extractedValue = oldTransformString.split(prop + '(')[1].split(')')[0];
97 | xyz = extractedValue.split(',');
98 | }
99 |
100 | // Replace the value in the array, then join that sucker together.
101 | xyz[axis] = val;
102 | transform3dString = prop + '(' + xyz.join(',') + ')';
103 | }
104 | }
105 |
106 | // Make a nice new string out of it with the scaled value.
107 | var transformInjection = transform3dString || prop + '(' + val + ')';
108 |
109 | var newTransformString = oldTransformString;
110 |
111 | // Check if the new prop is already declared somehow in the old style value
112 | var transformPropExists = oldTransformString.indexOf(prop) > -1;
113 |
114 | // Because if it is, you don't want to add another copy.
115 | if (transformPropExists) {
116 | var _startOfString = oldTransformString.split(prop)[0];
117 | var endOfString = oldTransformString.split(prop)[1].split(')')[1];
118 | newTransformString = _startOfString + transformInjection + endOfString;
119 | }
120 | // In the same vein, if it isn't, you can't just replace the value because there might
121 | // be some other transform properties hangin' out in there.
122 | else newTransformString += ' ' + transformInjection;
123 |
124 | return newTransformString;
125 | };
126 |
127 | module.exports = getInjectedTransformString;
--------------------------------------------------------------------------------
/dist/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Choreographer = require('./Choreographer');
4 | module.exports = Choreographer;
5 |
6 | window.Choreographer = Choreographer;
--------------------------------------------------------------------------------
/examples/one.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Choreographer-JS | Example One
6 |
7 |
8 |
9 |
31 |
32 |