progressbar.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433
  1. // ProgressBar.js 1.0.1
  2. // https://kimmobrunfeldt.github.io/progressbar.js
  3. // License: MIT
  4. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ProgressBar = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  5. /* shifty - v1.5.2 - 2016-02-10 - http://jeremyckahn.github.io/shifty */
  6. ;(function () {
  7. var root = this || Function('return this')();
  8. /**
  9. * Shifty Core
  10. * By Jeremy Kahn - jeremyckahn@gmail.com
  11. */
  12. var Tweenable = (function () {
  13. 'use strict';
  14. // Aliases that get defined later in this function
  15. var formula;
  16. // CONSTANTS
  17. var DEFAULT_SCHEDULE_FUNCTION;
  18. var DEFAULT_EASING = 'linear';
  19. var DEFAULT_DURATION = 500;
  20. var UPDATE_TIME = 1000 / 60;
  21. var _now = Date.now
  22. ? Date.now
  23. : function () {return +new Date();};
  24. var now = typeof SHIFTY_DEBUG_NOW !== 'undefined' ? SHIFTY_DEBUG_NOW : _now;
  25. if (typeof window !== 'undefined') {
  26. // requestAnimationFrame() shim by Paul Irish (modified for Shifty)
  27. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  28. DEFAULT_SCHEDULE_FUNCTION = window.requestAnimationFrame
  29. || window.webkitRequestAnimationFrame
  30. || window.oRequestAnimationFrame
  31. || window.msRequestAnimationFrame
  32. || (window.mozCancelRequestAnimationFrame
  33. && window.mozRequestAnimationFrame)
  34. || setTimeout;
  35. } else {
  36. DEFAULT_SCHEDULE_FUNCTION = setTimeout;
  37. }
  38. function noop () {
  39. // NOOP!
  40. }
  41. /**
  42. * Handy shortcut for doing a for-in loop. This is not a "normal" each
  43. * function, it is optimized for Shifty. The iterator function only receives
  44. * the property name, not the value.
  45. * @param {Object} obj
  46. * @param {Function(string)} fn
  47. * @private
  48. */
  49. function each (obj, fn) {
  50. var key;
  51. for (key in obj) {
  52. if (Object.hasOwnProperty.call(obj, key)) {
  53. fn(key);
  54. }
  55. }
  56. }
  57. /**
  58. * Perform a shallow copy of Object properties.
  59. * @param {Object} targetObject The object to copy into
  60. * @param {Object} srcObject The object to copy from
  61. * @return {Object} A reference to the augmented `targetObj` Object
  62. * @private
  63. */
  64. function shallowCopy (targetObj, srcObj) {
  65. each(srcObj, function (prop) {
  66. targetObj[prop] = srcObj[prop];
  67. });
  68. return targetObj;
  69. }
  70. /**
  71. * Copies each property from src onto target, but only if the property to
  72. * copy to target is undefined.
  73. * @param {Object} target Missing properties in this Object are filled in
  74. * @param {Object} src
  75. * @private
  76. */
  77. function defaults (target, src) {
  78. each(src, function (prop) {
  79. if (typeof target[prop] === 'undefined') {
  80. target[prop] = src[prop];
  81. }
  82. });
  83. }
  84. /**
  85. * Calculates the interpolated tween values of an Object for a given
  86. * timestamp.
  87. * @param {Number} forPosition The position to compute the state for.
  88. * @param {Object} currentState Current state properties.
  89. * @param {Object} originalState: The original state properties the Object is
  90. * tweening from.
  91. * @param {Object} targetState: The destination state properties the Object
  92. * is tweening to.
  93. * @param {number} duration: The length of the tween in milliseconds.
  94. * @param {number} timestamp: The UNIX epoch time at which the tween began.
  95. * @param {Object} easing: This Object's keys must correspond to the keys in
  96. * targetState.
  97. * @private
  98. */
  99. function tweenProps (forPosition, currentState, originalState, targetState,
  100. duration, timestamp, easing) {
  101. var normalizedPosition =
  102. forPosition < timestamp ? 0 : (forPosition - timestamp) / duration;
  103. var prop;
  104. var easingObjectProp;
  105. var easingFn;
  106. for (prop in currentState) {
  107. if (currentState.hasOwnProperty(prop)) {
  108. easingObjectProp = easing[prop];
  109. easingFn = typeof easingObjectProp === 'function'
  110. ? easingObjectProp
  111. : formula[easingObjectProp];
  112. currentState[prop] = tweenProp(
  113. originalState[prop],
  114. targetState[prop],
  115. easingFn,
  116. normalizedPosition
  117. );
  118. }
  119. }
  120. return currentState;
  121. }
  122. /**
  123. * Tweens a single property.
  124. * @param {number} start The value that the tween started from.
  125. * @param {number} end The value that the tween should end at.
  126. * @param {Function} easingFunc The easing curve to apply to the tween.
  127. * @param {number} position The normalized position (between 0.0 and 1.0) to
  128. * calculate the midpoint of 'start' and 'end' against.
  129. * @return {number} The tweened value.
  130. * @private
  131. */
  132. function tweenProp (start, end, easingFunc, position) {
  133. return start + (end - start) * easingFunc(position);
  134. }
  135. /**
  136. * Applies a filter to Tweenable instance.
  137. * @param {Tweenable} tweenable The `Tweenable` instance to call the filter
  138. * upon.
  139. * @param {String} filterName The name of the filter to apply.
  140. * @private
  141. */
  142. function applyFilter (tweenable, filterName) {
  143. var filters = Tweenable.prototype.filter;
  144. var args = tweenable._filterArgs;
  145. each(filters, function (name) {
  146. if (typeof filters[name][filterName] !== 'undefined') {
  147. filters[name][filterName].apply(tweenable, args);
  148. }
  149. });
  150. }
  151. var timeoutHandler_endTime;
  152. var timeoutHandler_currentTime;
  153. var timeoutHandler_isEnded;
  154. var timeoutHandler_offset;
  155. /**
  156. * Handles the update logic for one step of a tween.
  157. * @param {Tweenable} tweenable
  158. * @param {number} timestamp
  159. * @param {number} delay
  160. * @param {number} duration
  161. * @param {Object} currentState
  162. * @param {Object} originalState
  163. * @param {Object} targetState
  164. * @param {Object} easing
  165. * @param {Function(Object, *, number)} step
  166. * @param {Function(Function,number)}} schedule
  167. * @param {number=} opt_currentTimeOverride Needed for accurate timestamp in
  168. * Tweenable#seek.
  169. * @private
  170. */
  171. function timeoutHandler (tweenable, timestamp, delay, duration, currentState,
  172. originalState, targetState, easing, step, schedule,
  173. opt_currentTimeOverride) {
  174. timeoutHandler_endTime = timestamp + delay + duration;
  175. timeoutHandler_currentTime =
  176. Math.min(opt_currentTimeOverride || now(), timeoutHandler_endTime);
  177. timeoutHandler_isEnded =
  178. timeoutHandler_currentTime >= timeoutHandler_endTime;
  179. timeoutHandler_offset = duration - (
  180. timeoutHandler_endTime - timeoutHandler_currentTime);
  181. if (tweenable.isPlaying()) {
  182. if (timeoutHandler_isEnded) {
  183. step(targetState, tweenable._attachment, timeoutHandler_offset);
  184. tweenable.stop(true);
  185. } else {
  186. tweenable._scheduleId =
  187. schedule(tweenable._timeoutHandler, UPDATE_TIME);
  188. applyFilter(tweenable, 'beforeTween');
  189. // If the animation has not yet reached the start point (e.g., there was
  190. // delay that has not yet completed), just interpolate the starting
  191. // position of the tween.
  192. if (timeoutHandler_currentTime < (timestamp + delay)) {
  193. tweenProps(1, currentState, originalState, targetState, 1, 1, easing);
  194. } else {
  195. tweenProps(timeoutHandler_currentTime, currentState, originalState,
  196. targetState, duration, timestamp + delay, easing);
  197. }
  198. applyFilter(tweenable, 'afterTween');
  199. step(currentState, tweenable._attachment, timeoutHandler_offset);
  200. }
  201. }
  202. }
  203. /**
  204. * Creates a usable easing Object from a string, a function or another easing
  205. * Object. If `easing` is an Object, then this function clones it and fills
  206. * in the missing properties with `"linear"`.
  207. * @param {Object.<string|Function>} fromTweenParams
  208. * @param {Object|string|Function} easing
  209. * @return {Object.<string|Function>}
  210. * @private
  211. */
  212. function composeEasingObject (fromTweenParams, easing) {
  213. var composedEasing = {};
  214. var typeofEasing = typeof easing;
  215. if (typeofEasing === 'string' || typeofEasing === 'function') {
  216. each(fromTweenParams, function (prop) {
  217. composedEasing[prop] = easing;
  218. });
  219. } else {
  220. each(fromTweenParams, function (prop) {
  221. if (!composedEasing[prop]) {
  222. composedEasing[prop] = easing[prop] || DEFAULT_EASING;
  223. }
  224. });
  225. }
  226. return composedEasing;
  227. }
  228. /**
  229. * Tweenable constructor.
  230. * @class Tweenable
  231. * @param {Object=} opt_initialState The values that the initial tween should
  232. * start at if a `from` object is not provided to `{{#crossLink
  233. * "Tweenable/tween:method"}}{{/crossLink}}` or `{{#crossLink
  234. * "Tweenable/setConfig:method"}}{{/crossLink}}`.
  235. * @param {Object=} opt_config Configuration object to be passed to
  236. * `{{#crossLink "Tweenable/setConfig:method"}}{{/crossLink}}`.
  237. * @module Tweenable
  238. * @constructor
  239. */
  240. function Tweenable (opt_initialState, opt_config) {
  241. this._currentState = opt_initialState || {};
  242. this._configured = false;
  243. this._scheduleFunction = DEFAULT_SCHEDULE_FUNCTION;
  244. // To prevent unnecessary calls to setConfig do not set default
  245. // configuration here. Only set default configuration immediately before
  246. // tweening if none has been set.
  247. if (typeof opt_config !== 'undefined') {
  248. this.setConfig(opt_config);
  249. }
  250. }
  251. /**
  252. * Configure and start a tween.
  253. * @method tween
  254. * @param {Object=} opt_config Configuration object to be passed to
  255. * `{{#crossLink "Tweenable/setConfig:method"}}{{/crossLink}}`.
  256. * @chainable
  257. */
  258. Tweenable.prototype.tween = function (opt_config) {
  259. if (this._isTweening) {
  260. return this;
  261. }
  262. // Only set default config if no configuration has been set previously and
  263. // none is provided now.
  264. if (opt_config !== undefined || !this._configured) {
  265. this.setConfig(opt_config);
  266. }
  267. this._timestamp = now();
  268. this._start(this.get(), this._attachment);
  269. return this.resume();
  270. };
  271. /**
  272. * Configure a tween that will start at some point in the future.
  273. *
  274. * @method setConfig
  275. * @param {Object} config The following values are valid:
  276. * - __from__ (_Object=_): Starting position. If omitted, `{{#crossLink
  277. * "Tweenable/get:method"}}get(){{/crossLink}}` is used.
  278. * - __to__ (_Object=_): Ending position.
  279. * - __duration__ (_number=_): How many milliseconds to animate for.
  280. * - __delay__ (_delay=_): How many milliseconds to wait before starting the
  281. * tween.
  282. * - __start__ (_Function(Object, *)_): Function to execute when the tween
  283. * begins. Receives the state of the tween as the first parameter and
  284. * `attachment` as the second parameter.
  285. * - __step__ (_Function(Object, *, number)_): Function to execute on every
  286. * tick. Receives `{{#crossLink
  287. * "Tweenable/get:method"}}get(){{/crossLink}}` as the first parameter,
  288. * `attachment` as the second parameter, and the time elapsed since the
  289. * start of the tween as the third. This function is not called on the
  290. * final step of the animation, but `finish` is.
  291. * - __finish__ (_Function(Object, *)_): Function to execute upon tween
  292. * completion. Receives the state of the tween as the first parameter and
  293. * `attachment` as the second parameter.
  294. * - __easing__ (_Object.<string|Function>|string|Function=_): Easing curve
  295. * name(s) or function(s) to use for the tween.
  296. * - __attachment__ (_*_): Cached value that is passed to the
  297. * `step`/`start`/`finish` methods.
  298. * @chainable
  299. */
  300. Tweenable.prototype.setConfig = function (config) {
  301. config = config || {};
  302. this._configured = true;
  303. // Attach something to this Tweenable instance (e.g.: a DOM element, an
  304. // object, a string, etc.);
  305. this._attachment = config.attachment;
  306. // Init the internal state
  307. this._pausedAtTime = null;
  308. this._scheduleId = null;
  309. this._delay = config.delay || 0;
  310. this._start = config.start || noop;
  311. this._step = config.step || noop;
  312. this._finish = config.finish || noop;
  313. this._duration = config.duration || DEFAULT_DURATION;
  314. this._currentState = shallowCopy({}, config.from) || this.get();
  315. this._originalState = this.get();
  316. this._targetState = shallowCopy({}, config.to) || this.get();
  317. var self = this;
  318. this._timeoutHandler = function () {
  319. timeoutHandler(self,
  320. self._timestamp,
  321. self._delay,
  322. self._duration,
  323. self._currentState,
  324. self._originalState,
  325. self._targetState,
  326. self._easing,
  327. self._step,
  328. self._scheduleFunction
  329. );
  330. };
  331. // Aliases used below
  332. var currentState = this._currentState;
  333. var targetState = this._targetState;
  334. // Ensure that there is always something to tween to.
  335. defaults(targetState, currentState);
  336. this._easing = composeEasingObject(
  337. currentState, config.easing || DEFAULT_EASING);
  338. this._filterArgs =
  339. [currentState, this._originalState, targetState, this._easing];
  340. applyFilter(this, 'tweenCreated');
  341. return this;
  342. };
  343. /**
  344. * @method get
  345. * @return {Object} The current state.
  346. */
  347. Tweenable.prototype.get = function () {
  348. return shallowCopy({}, this._currentState);
  349. };
  350. /**
  351. * @method set
  352. * @param {Object} state The current state.
  353. */
  354. Tweenable.prototype.set = function (state) {
  355. this._currentState = state;
  356. };
  357. /**
  358. * Pause a tween. Paused tweens can be resumed from the point at which they
  359. * were paused. This is different from `{{#crossLink
  360. * "Tweenable/stop:method"}}{{/crossLink}}`, as that method
  361. * causes a tween to start over when it is resumed.
  362. * @method pause
  363. * @chainable
  364. */
  365. Tweenable.prototype.pause = function () {
  366. this._pausedAtTime = now();
  367. this._isPaused = true;
  368. return this;
  369. };
  370. /**
  371. * Resume a paused tween.
  372. * @method resume
  373. * @chainable
  374. */
  375. Tweenable.prototype.resume = function () {
  376. if (this._isPaused) {
  377. this._timestamp += now() - this._pausedAtTime;
  378. }
  379. this._isPaused = false;
  380. this._isTweening = true;
  381. this._timeoutHandler();
  382. return this;
  383. };
  384. /**
  385. * Move the state of the animation to a specific point in the tween's
  386. * timeline. If the animation is not running, this will cause the `step`
  387. * handlers to be called.
  388. * @method seek
  389. * @param {millisecond} millisecond The millisecond of the animation to seek
  390. * to. This must not be less than `0`.
  391. * @chainable
  392. */
  393. Tweenable.prototype.seek = function (millisecond) {
  394. millisecond = Math.max(millisecond, 0);
  395. var currentTime = now();
  396. if ((this._timestamp + millisecond) === 0) {
  397. return this;
  398. }
  399. this._timestamp = currentTime - millisecond;
  400. if (!this.isPlaying()) {
  401. this._isTweening = true;
  402. this._isPaused = false;
  403. // If the animation is not running, call timeoutHandler to make sure that
  404. // any step handlers are run.
  405. timeoutHandler(this,
  406. this._timestamp,
  407. this._delay,
  408. this._duration,
  409. this._currentState,
  410. this._originalState,
  411. this._targetState,
  412. this._easing,
  413. this._step,
  414. this._scheduleFunction,
  415. currentTime
  416. );
  417. this.pause();
  418. }
  419. return this;
  420. };
  421. /**
  422. * Stops and cancels a tween.
  423. * @param {boolean=} gotoEnd If `false` or omitted, the tween just stops at
  424. * its current state, and the `finish` handler is not invoked. If `true`,
  425. * the tweened object's values are instantly set to the target values, and
  426. * `finish` is invoked.
  427. * @method stop
  428. * @chainable
  429. */
  430. Tweenable.prototype.stop = function (gotoEnd) {
  431. this._isTweening = false;
  432. this._isPaused = false;
  433. this._timeoutHandler = noop;
  434. (root.cancelAnimationFrame ||
  435. root.webkitCancelAnimationFrame ||
  436. root.oCancelAnimationFrame ||
  437. root.msCancelAnimationFrame ||
  438. root.mozCancelRequestAnimationFrame ||
  439. root.clearTimeout)(this._scheduleId);
  440. if (gotoEnd) {
  441. applyFilter(this, 'beforeTween');
  442. tweenProps(
  443. 1,
  444. this._currentState,
  445. this._originalState,
  446. this._targetState,
  447. 1,
  448. 0,
  449. this._easing
  450. );
  451. applyFilter(this, 'afterTween');
  452. applyFilter(this, 'afterTweenEnd');
  453. this._finish.call(this, this._currentState, this._attachment);
  454. }
  455. return this;
  456. };
  457. /**
  458. * @method isPlaying
  459. * @return {boolean} Whether or not a tween is running.
  460. */
  461. Tweenable.prototype.isPlaying = function () {
  462. return this._isTweening && !this._isPaused;
  463. };
  464. /**
  465. * Set a custom schedule function.
  466. *
  467. * If a custom function is not set,
  468. * [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame)
  469. * is used if available, otherwise
  470. * [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout)
  471. * is used.
  472. * @method setScheduleFunction
  473. * @param {Function(Function,number)} scheduleFunction The function to be
  474. * used to schedule the next frame to be rendered.
  475. */
  476. Tweenable.prototype.setScheduleFunction = function (scheduleFunction) {
  477. this._scheduleFunction = scheduleFunction;
  478. };
  479. /**
  480. * `delete` all "own" properties. Call this when the `Tweenable` instance
  481. * is no longer needed to free memory.
  482. * @method dispose
  483. */
  484. Tweenable.prototype.dispose = function () {
  485. var prop;
  486. for (prop in this) {
  487. if (this.hasOwnProperty(prop)) {
  488. delete this[prop];
  489. }
  490. }
  491. };
  492. /**
  493. * Filters are used for transforming the properties of a tween at various
  494. * points in a Tweenable's life cycle. See the README for more info on this.
  495. * @private
  496. */
  497. Tweenable.prototype.filter = {};
  498. /**
  499. * This object contains all of the tweens available to Shifty. It is
  500. * extensible - simply attach properties to the `Tweenable.prototype.formula`
  501. * Object following the same format as `linear`.
  502. *
  503. * `pos` should be a normalized `number` (between 0 and 1).
  504. * @property formula
  505. * @type {Object(function)}
  506. */
  507. Tweenable.prototype.formula = {
  508. linear: function (pos) {
  509. return pos;
  510. }
  511. };
  512. formula = Tweenable.prototype.formula;
  513. shallowCopy(Tweenable, {
  514. 'now': now
  515. ,'each': each
  516. ,'tweenProps': tweenProps
  517. ,'tweenProp': tweenProp
  518. ,'applyFilter': applyFilter
  519. ,'shallowCopy': shallowCopy
  520. ,'defaults': defaults
  521. ,'composeEasingObject': composeEasingObject
  522. });
  523. // `root` is provided in the intro/outro files.
  524. // A hook used for unit testing.
  525. if (typeof SHIFTY_DEBUG_NOW === 'function') {
  526. root.timeoutHandler = timeoutHandler;
  527. }
  528. // Bootstrap Tweenable appropriately for the environment.
  529. if (typeof exports === 'object') {
  530. // CommonJS
  531. module.exports = Tweenable;
  532. } else if (typeof define === 'function' && define.amd) {
  533. // AMD
  534. define(function () {return Tweenable;});
  535. } else if (typeof root.Tweenable === 'undefined') {
  536. // Browser: Make `Tweenable` globally accessible.
  537. root.Tweenable = Tweenable;
  538. }
  539. return Tweenable;
  540. } ());
  541. /*!
  542. * All equations are adapted from Thomas Fuchs'
  543. * [Scripty2](https://github.com/madrobby/scripty2/blob/master/src/effects/transitions/penner.js).
  544. *
  545. * Based on Easing Equations (c) 2003 [Robert
  546. * Penner](http://www.robertpenner.com/), all rights reserved. This work is
  547. * [subject to terms](http://www.robertpenner.com/easing_terms_of_use.html).
  548. */
  549. /*!
  550. * TERMS OF USE - EASING EQUATIONS
  551. * Open source under the BSD License.
  552. * Easing Equations (c) 2003 Robert Penner, all rights reserved.
  553. */
  554. ;(function () {
  555. Tweenable.shallowCopy(Tweenable.prototype.formula, {
  556. easeInQuad: function (pos) {
  557. return Math.pow(pos, 2);
  558. },
  559. easeOutQuad: function (pos) {
  560. return -(Math.pow((pos - 1), 2) - 1);
  561. },
  562. easeInOutQuad: function (pos) {
  563. if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos,2);}
  564. return -0.5 * ((pos -= 2) * pos - 2);
  565. },
  566. easeInCubic: function (pos) {
  567. return Math.pow(pos, 3);
  568. },
  569. easeOutCubic: function (pos) {
  570. return (Math.pow((pos - 1), 3) + 1);
  571. },
  572. easeInOutCubic: function (pos) {
  573. if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos,3);}
  574. return 0.5 * (Math.pow((pos - 2),3) + 2);
  575. },
  576. easeInQuart: function (pos) {
  577. return Math.pow(pos, 4);
  578. },
  579. easeOutQuart: function (pos) {
  580. return -(Math.pow((pos - 1), 4) - 1);
  581. },
  582. easeInOutQuart: function (pos) {
  583. if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos,4);}
  584. return -0.5 * ((pos -= 2) * Math.pow(pos,3) - 2);
  585. },
  586. easeInQuint: function (pos) {
  587. return Math.pow(pos, 5);
  588. },
  589. easeOutQuint: function (pos) {
  590. return (Math.pow((pos - 1), 5) + 1);
  591. },
  592. easeInOutQuint: function (pos) {
  593. if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos,5);}
  594. return 0.5 * (Math.pow((pos - 2),5) + 2);
  595. },
  596. easeInSine: function (pos) {
  597. return -Math.cos(pos * (Math.PI / 2)) + 1;
  598. },
  599. easeOutSine: function (pos) {
  600. return Math.sin(pos * (Math.PI / 2));
  601. },
  602. easeInOutSine: function (pos) {
  603. return (-0.5 * (Math.cos(Math.PI * pos) - 1));
  604. },
  605. easeInExpo: function (pos) {
  606. return (pos === 0) ? 0 : Math.pow(2, 10 * (pos - 1));
  607. },
  608. easeOutExpo: function (pos) {
  609. return (pos === 1) ? 1 : -Math.pow(2, -10 * pos) + 1;
  610. },
  611. easeInOutExpo: function (pos) {
  612. if (pos === 0) {return 0;}
  613. if (pos === 1) {return 1;}
  614. if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(2,10 * (pos - 1));}
  615. return 0.5 * (-Math.pow(2, -10 * --pos) + 2);
  616. },
  617. easeInCirc: function (pos) {
  618. return -(Math.sqrt(1 - (pos * pos)) - 1);
  619. },
  620. easeOutCirc: function (pos) {
  621. return Math.sqrt(1 - Math.pow((pos - 1), 2));
  622. },
  623. easeInOutCirc: function (pos) {
  624. if ((pos /= 0.5) < 1) {return -0.5 * (Math.sqrt(1 - pos * pos) - 1);}
  625. return 0.5 * (Math.sqrt(1 - (pos -= 2) * pos) + 1);
  626. },
  627. easeOutBounce: function (pos) {
  628. if ((pos) < (1 / 2.75)) {
  629. return (7.5625 * pos * pos);
  630. } else if (pos < (2 / 2.75)) {
  631. return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
  632. } else if (pos < (2.5 / 2.75)) {
  633. return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
  634. } else {
  635. return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
  636. }
  637. },
  638. easeInBack: function (pos) {
  639. var s = 1.70158;
  640. return (pos) * pos * ((s + 1) * pos - s);
  641. },
  642. easeOutBack: function (pos) {
  643. var s = 1.70158;
  644. return (pos = pos - 1) * pos * ((s + 1) * pos + s) + 1;
  645. },
  646. easeInOutBack: function (pos) {
  647. var s = 1.70158;
  648. if ((pos /= 0.5) < 1) {
  649. return 0.5 * (pos * pos * (((s *= (1.525)) + 1) * pos - s));
  650. }
  651. return 0.5 * ((pos -= 2) * pos * (((s *= (1.525)) + 1) * pos + s) + 2);
  652. },
  653. elastic: function (pos) {
  654. // jshint maxlen:90
  655. return -1 * Math.pow(4,-8 * pos) * Math.sin((pos * 6 - 1) * (2 * Math.PI) / 2) + 1;
  656. },
  657. swingFromTo: function (pos) {
  658. var s = 1.70158;
  659. return ((pos /= 0.5) < 1) ?
  660. 0.5 * (pos * pos * (((s *= (1.525)) + 1) * pos - s)) :
  661. 0.5 * ((pos -= 2) * pos * (((s *= (1.525)) + 1) * pos + s) + 2);
  662. },
  663. swingFrom: function (pos) {
  664. var s = 1.70158;
  665. return pos * pos * ((s + 1) * pos - s);
  666. },
  667. swingTo: function (pos) {
  668. var s = 1.70158;
  669. return (pos -= 1) * pos * ((s + 1) * pos + s) + 1;
  670. },
  671. bounce: function (pos) {
  672. if (pos < (1 / 2.75)) {
  673. return (7.5625 * pos * pos);
  674. } else if (pos < (2 / 2.75)) {
  675. return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
  676. } else if (pos < (2.5 / 2.75)) {
  677. return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
  678. } else {
  679. return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
  680. }
  681. },
  682. bouncePast: function (pos) {
  683. if (pos < (1 / 2.75)) {
  684. return (7.5625 * pos * pos);
  685. } else if (pos < (2 / 2.75)) {
  686. return 2 - (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
  687. } else if (pos < (2.5 / 2.75)) {
  688. return 2 - (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
  689. } else {
  690. return 2 - (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
  691. }
  692. },
  693. easeFromTo: function (pos) {
  694. if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos,4);}
  695. return -0.5 * ((pos -= 2) * Math.pow(pos,3) - 2);
  696. },
  697. easeFrom: function (pos) {
  698. return Math.pow(pos,4);
  699. },
  700. easeTo: function (pos) {
  701. return Math.pow(pos,0.25);
  702. }
  703. });
  704. }());
  705. // jshint maxlen:100
  706. /**
  707. * The Bezier magic in this file is adapted/copied almost wholesale from
  708. * [Scripty2](https://github.com/madrobby/scripty2/blob/master/src/effects/transitions/cubic-bezier.js),
  709. * which was adapted from Apple code (which probably came from
  710. * [here](http://opensource.apple.com/source/WebCore/WebCore-955.66/platform/graphics/UnitBezier.h)).
  711. * Special thanks to Apple and Thomas Fuchs for much of this code.
  712. */
  713. /**
  714. * Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
  715. *
  716. * Redistribution and use in source and binary forms, with or without
  717. * modification, are permitted provided that the following conditions are met:
  718. *
  719. * 1. Redistributions of source code must retain the above copyright notice,
  720. * this list of conditions and the following disclaimer.
  721. *
  722. * 2. Redistributions in binary form must reproduce the above copyright notice,
  723. * this list of conditions and the following disclaimer in the documentation
  724. * and/or other materials provided with the distribution.
  725. *
  726. * 3. Neither the name of the copyright holder(s) nor the names of any
  727. * contributors may be used to endorse or promote products derived from
  728. * this software without specific prior written permission.
  729. *
  730. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  731. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  732. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  733. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  734. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  735. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  736. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  737. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  738. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  739. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  740. * POSSIBILITY OF SUCH DAMAGE.
  741. */
  742. ;(function () {
  743. // port of webkit cubic bezier handling by http://www.netzgesta.de/dev/
  744. function cubicBezierAtTime(t,p1x,p1y,p2x,p2y,duration) {
  745. var ax = 0,bx = 0,cx = 0,ay = 0,by = 0,cy = 0;
  746. function sampleCurveX(t) {
  747. return ((ax * t + bx) * t + cx) * t;
  748. }
  749. function sampleCurveY(t) {
  750. return ((ay * t + by) * t + cy) * t;
  751. }
  752. function sampleCurveDerivativeX(t) {
  753. return (3.0 * ax * t + 2.0 * bx) * t + cx;
  754. }
  755. function solveEpsilon(duration) {
  756. return 1.0 / (200.0 * duration);
  757. }
  758. function solve(x,epsilon) {
  759. return sampleCurveY(solveCurveX(x, epsilon));
  760. }
  761. function fabs(n) {
  762. if (n >= 0) {
  763. return n;
  764. } else {
  765. return 0 - n;
  766. }
  767. }
  768. function solveCurveX(x, epsilon) {
  769. var t0,t1,t2,x2,d2,i;
  770. for (t2 = x, i = 0; i < 8; i++) {
  771. x2 = sampleCurveX(t2) - x;
  772. if (fabs(x2) < epsilon) {
  773. return t2;
  774. }
  775. d2 = sampleCurveDerivativeX(t2);
  776. if (fabs(d2) < 1e-6) {
  777. break;
  778. }
  779. t2 = t2 - x2 / d2;
  780. }
  781. t0 = 0.0;
  782. t1 = 1.0;
  783. t2 = x;
  784. if (t2 < t0) {
  785. return t0;
  786. }
  787. if (t2 > t1) {
  788. return t1;
  789. }
  790. while (t0 < t1) {
  791. x2 = sampleCurveX(t2);
  792. if (fabs(x2 - x) < epsilon) {
  793. return t2;
  794. }
  795. if (x > x2) {
  796. t0 = t2;
  797. }else {
  798. t1 = t2;
  799. }
  800. t2 = (t1 - t0) * 0.5 + t0;
  801. }
  802. return t2; // Failure.
  803. }
  804. cx = 3.0 * p1x;
  805. bx = 3.0 * (p2x - p1x) - cx;
  806. ax = 1.0 - cx - bx;
  807. cy = 3.0 * p1y;
  808. by = 3.0 * (p2y - p1y) - cy;
  809. ay = 1.0 - cy - by;
  810. return solve(t, solveEpsilon(duration));
  811. }
  812. /**
  813. * getCubicBezierTransition(x1, y1, x2, y2) -> Function
  814. *
  815. * Generates a transition easing function that is compatible
  816. * with WebKit's CSS transitions `-webkit-transition-timing-function`
  817. * CSS property.
  818. *
  819. * The W3C has more information about CSS3 transition timing functions:
  820. * http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag
  821. *
  822. * @param {number} x1
  823. * @param {number} y1
  824. * @param {number} x2
  825. * @param {number} y2
  826. * @return {function}
  827. * @private
  828. */
  829. function getCubicBezierTransition (x1, y1, x2, y2) {
  830. return function (pos) {
  831. return cubicBezierAtTime(pos,x1,y1,x2,y2,1);
  832. };
  833. }
  834. // End ported code
  835. /**
  836. * Create a Bezier easing function and attach it to `{{#crossLink
  837. * "Tweenable/formula:property"}}Tweenable#formula{{/crossLink}}`. This
  838. * function gives you total control over the easing curve. Matthew Lein's
  839. * [Ceaser](http://matthewlein.com/ceaser/) is a useful tool for visualizing
  840. * the curves you can make with this function.
  841. * @method setBezierFunction
  842. * @param {string} name The name of the easing curve. Overwrites the old
  843. * easing function on `{{#crossLink
  844. * "Tweenable/formula:property"}}Tweenable#formula{{/crossLink}}` if it
  845. * exists.
  846. * @param {number} x1
  847. * @param {number} y1
  848. * @param {number} x2
  849. * @param {number} y2
  850. * @return {function} The easing function that was attached to
  851. * Tweenable.prototype.formula.
  852. */
  853. Tweenable.setBezierFunction = function (name, x1, y1, x2, y2) {
  854. var cubicBezierTransition = getCubicBezierTransition(x1, y1, x2, y2);
  855. cubicBezierTransition.displayName = name;
  856. cubicBezierTransition.x1 = x1;
  857. cubicBezierTransition.y1 = y1;
  858. cubicBezierTransition.x2 = x2;
  859. cubicBezierTransition.y2 = y2;
  860. return Tweenable.prototype.formula[name] = cubicBezierTransition;
  861. };
  862. /**
  863. * `delete` an easing function from `{{#crossLink
  864. * "Tweenable/formula:property"}}Tweenable#formula{{/crossLink}}`. Be
  865. * careful with this method, as it `delete`s whatever easing formula matches
  866. * `name` (which means you can delete standard Shifty easing functions).
  867. * @method unsetBezierFunction
  868. * @param {string} name The name of the easing function to delete.
  869. * @return {function}
  870. */
  871. Tweenable.unsetBezierFunction = function (name) {
  872. delete Tweenable.prototype.formula[name];
  873. };
  874. })();
  875. ;(function () {
  876. function getInterpolatedValues (
  877. from, current, targetState, position, easing, delay) {
  878. return Tweenable.tweenProps(
  879. position, current, from, targetState, 1, delay, easing);
  880. }
  881. // Fake a Tweenable and patch some internals. This approach allows us to
  882. // skip uneccessary processing and object recreation, cutting down on garbage
  883. // collection pauses.
  884. var mockTweenable = new Tweenable();
  885. mockTweenable._filterArgs = [];
  886. /**
  887. * Compute the midpoint of two Objects. This method effectively calculates a
  888. * specific frame of animation that `{{#crossLink
  889. * "Tweenable/tween:method"}}{{/crossLink}}` does many times over the course
  890. * of a full tween.
  891. *
  892. * var interpolatedValues = Tweenable.interpolate({
  893. * width: '100px',
  894. * opacity: 0,
  895. * color: '#fff'
  896. * }, {
  897. * width: '200px',
  898. * opacity: 1,
  899. * color: '#000'
  900. * }, 0.5);
  901. *
  902. * // {opacity: 0.5, width: "150px", color: "rgb(127,127,127)"}
  903. *
  904. * @static
  905. * @method interpolate
  906. * @param {Object} from The starting values to tween from.
  907. * @param {Object} targetState The ending values to tween to.
  908. * @param {number} position The normalized position value (between `0.0` and
  909. * `1.0`) to interpolate the values between `from` and `to` for. `from`
  910. * represents `0` and `to` represents `1`.
  911. * @param {Object.<string|Function>|string|Function} easing The easing
  912. * curve(s) to calculate the midpoint against. You can reference any easing
  913. * function attached to `Tweenable.prototype.formula`, or provide the easing
  914. * function(s) directly. If omitted, this defaults to "linear".
  915. * @param {number=} opt_delay Optional delay to pad the beginning of the
  916. * interpolated tween with. This increases the range of `position` from (`0`
  917. * through `1`) to (`0` through `1 + opt_delay`). So, a delay of `0.5` would
  918. * increase all valid values of `position` to numbers between `0` and `1.5`.
  919. * @return {Object}
  920. */
  921. Tweenable.interpolate = function (
  922. from, targetState, position, easing, opt_delay) {
  923. var current = Tweenable.shallowCopy({}, from);
  924. var delay = opt_delay || 0;
  925. var easingObject = Tweenable.composeEasingObject(
  926. from, easing || 'linear');
  927. mockTweenable.set({});
  928. // Alias and reuse the _filterArgs array instead of recreating it.
  929. var filterArgs = mockTweenable._filterArgs;
  930. filterArgs.length = 0;
  931. filterArgs[0] = current;
  932. filterArgs[1] = from;
  933. filterArgs[2] = targetState;
  934. filterArgs[3] = easingObject;
  935. // Any defined value transformation must be applied
  936. Tweenable.applyFilter(mockTweenable, 'tweenCreated');
  937. Tweenable.applyFilter(mockTweenable, 'beforeTween');
  938. var interpolatedValues = getInterpolatedValues(
  939. from, current, targetState, position, easingObject, delay);
  940. // Transform values back into their original format
  941. Tweenable.applyFilter(mockTweenable, 'afterTween');
  942. return interpolatedValues;
  943. };
  944. }());
  945. /**
  946. * This module adds string interpolation support to Shifty.
  947. *
  948. * The Token extension allows Shifty to tween numbers inside of strings. Among
  949. * other things, this allows you to animate CSS properties. For example, you
  950. * can do this:
  951. *
  952. * var tweenable = new Tweenable();
  953. * tweenable.tween({
  954. * from: { transform: 'translateX(45px)' },
  955. * to: { transform: 'translateX(90xp)' }
  956. * });
  957. *
  958. * `translateX(45)` will be tweened to `translateX(90)`. To demonstrate:
  959. *
  960. * var tweenable = new Tweenable();
  961. * tweenable.tween({
  962. * from: { transform: 'translateX(45px)' },
  963. * to: { transform: 'translateX(90px)' },
  964. * step: function (state) {
  965. * console.log(state.transform);
  966. * }
  967. * });
  968. *
  969. * The above snippet will log something like this in the console:
  970. *
  971. * translateX(60.3px)
  972. * ...
  973. * translateX(76.05px)
  974. * ...
  975. * translateX(90px)
  976. *
  977. * Another use for this is animating colors:
  978. *
  979. * var tweenable = new Tweenable();
  980. * tweenable.tween({
  981. * from: { color: 'rgb(0,255,0)' },
  982. * to: { color: 'rgb(255,0,255)' },
  983. * step: function (state) {
  984. * console.log(state.color);
  985. * }
  986. * });
  987. *
  988. * The above snippet will log something like this:
  989. *
  990. * rgb(84,170,84)
  991. * ...
  992. * rgb(170,84,170)
  993. * ...
  994. * rgb(255,0,255)
  995. *
  996. * This extension also supports hexadecimal colors, in both long (`#ff00ff`)
  997. * and short (`#f0f`) forms. Be aware that hexadecimal input values will be
  998. * converted into the equivalent RGB output values. This is done to optimize
  999. * for performance.
  1000. *
  1001. * var tweenable = new Tweenable();
  1002. * tweenable.tween({
  1003. * from: { color: '#0f0' },
  1004. * to: { color: '#f0f' },
  1005. * step: function (state) {
  1006. * console.log(state.color);
  1007. * }
  1008. * });
  1009. *
  1010. * This snippet will generate the same output as the one before it because
  1011. * equivalent values were supplied (just in hexadecimal form rather than RGB):
  1012. *
  1013. * rgb(84,170,84)
  1014. * ...
  1015. * rgb(170,84,170)
  1016. * ...
  1017. * rgb(255,0,255)
  1018. *
  1019. * ## Easing support
  1020. *
  1021. * Easing works somewhat differently in the Token extension. This is because
  1022. * some CSS properties have multiple values in them, and you might need to
  1023. * tween each value along its own easing curve. A basic example:
  1024. *
  1025. * var tweenable = new Tweenable();
  1026. * tweenable.tween({
  1027. * from: { transform: 'translateX(0px) translateY(0px)' },
  1028. * to: { transform: 'translateX(100px) translateY(100px)' },
  1029. * easing: { transform: 'easeInQuad' },
  1030. * step: function (state) {
  1031. * console.log(state.transform);
  1032. * }
  1033. * });
  1034. *
  1035. * The above snippet will create values like this:
  1036. *
  1037. * translateX(11.56px) translateY(11.56px)
  1038. * ...
  1039. * translateX(46.24px) translateY(46.24px)
  1040. * ...
  1041. * translateX(100px) translateY(100px)
  1042. *
  1043. * In this case, the values for `translateX` and `translateY` are always the
  1044. * same for each step of the tween, because they have the same start and end
  1045. * points and both use the same easing curve. We can also tween `translateX`
  1046. * and `translateY` along independent curves:
  1047. *
  1048. * var tweenable = new Tweenable();
  1049. * tweenable.tween({
  1050. * from: { transform: 'translateX(0px) translateY(0px)' },
  1051. * to: { transform: 'translateX(100px) translateY(100px)' },
  1052. * easing: { transform: 'easeInQuad bounce' },
  1053. * step: function (state) {
  1054. * console.log(state.transform);
  1055. * }
  1056. * });
  1057. *
  1058. * The above snippet will create values like this:
  1059. *
  1060. * translateX(10.89px) translateY(82.35px)
  1061. * ...
  1062. * translateX(44.89px) translateY(86.73px)
  1063. * ...
  1064. * translateX(100px) translateY(100px)
  1065. *
  1066. * `translateX` and `translateY` are not in sync anymore, because `easeInQuad`
  1067. * was specified for `translateX` and `bounce` for `translateY`. Mixing and
  1068. * matching easing curves can make for some interesting motion in your
  1069. * animations.
  1070. *
  1071. * The order of the space-separated easing curves correspond the token values
  1072. * they apply to. If there are more token values than easing curves listed,
  1073. * the last easing curve listed is used.
  1074. * @submodule Tweenable.token
  1075. */
  1076. // token function is defined above only so that dox-foundation sees it as
  1077. // documentation and renders it. It is never used, and is optimized away at
  1078. // build time.
  1079. ;(function (Tweenable) {
  1080. /**
  1081. * @typedef {{
  1082. * formatString: string
  1083. * chunkNames: Array.<string>
  1084. * }}
  1085. * @private
  1086. */
  1087. var formatManifest;
  1088. // CONSTANTS
  1089. var R_NUMBER_COMPONENT = /(\d|\-|\.)/;
  1090. var R_FORMAT_CHUNKS = /([^\-0-9\.]+)/g;
  1091. var R_UNFORMATTED_VALUES = /[0-9.\-]+/g;
  1092. var R_RGB = new RegExp(
  1093. 'rgb\\(' + R_UNFORMATTED_VALUES.source +
  1094. (/,\s*/.source) + R_UNFORMATTED_VALUES.source +
  1095. (/,\s*/.source) + R_UNFORMATTED_VALUES.source + '\\)', 'g');
  1096. var R_RGB_PREFIX = /^.*\(/;
  1097. var R_HEX = /#([0-9]|[a-f]){3,6}/gi;
  1098. var VALUE_PLACEHOLDER = 'VAL';
  1099. // HELPERS
  1100. /**
  1101. * @param {Array.number} rawValues
  1102. * @param {string} prefix
  1103. *
  1104. * @return {Array.<string>}
  1105. * @private
  1106. */
  1107. function getFormatChunksFrom (rawValues, prefix) {
  1108. var accumulator = [];
  1109. var rawValuesLength = rawValues.length;
  1110. var i;
  1111. for (i = 0; i < rawValuesLength; i++) {
  1112. accumulator.push('_' + prefix + '_' + i);
  1113. }
  1114. return accumulator;
  1115. }
  1116. /**
  1117. * @param {string} formattedString
  1118. *
  1119. * @return {string}
  1120. * @private
  1121. */
  1122. function getFormatStringFrom (formattedString) {
  1123. var chunks = formattedString.match(R_FORMAT_CHUNKS);
  1124. if (!chunks) {
  1125. // chunks will be null if there were no tokens to parse in
  1126. // formattedString (for example, if formattedString is '2'). Coerce
  1127. // chunks to be useful here.
  1128. chunks = ['', ''];
  1129. // If there is only one chunk, assume that the string is a number
  1130. // followed by a token...
  1131. // NOTE: This may be an unwise assumption.
  1132. } else if (chunks.length === 1 ||
  1133. // ...or if the string starts with a number component (".", "-", or a
  1134. // digit)...
  1135. formattedString[0].match(R_NUMBER_COMPONENT)) {
  1136. // ...prepend an empty string here to make sure that the formatted number
  1137. // is properly replaced by VALUE_PLACEHOLDER
  1138. chunks.unshift('');
  1139. }
  1140. return chunks.join(VALUE_PLACEHOLDER);
  1141. }
  1142. /**
  1143. * Convert all hex color values within a string to an rgb string.
  1144. *
  1145. * @param {Object} stateObject
  1146. *
  1147. * @return {Object} The modified obj
  1148. * @private
  1149. */
  1150. function sanitizeObjectForHexProps (stateObject) {
  1151. Tweenable.each(stateObject, function (prop) {
  1152. var currentProp = stateObject[prop];
  1153. if (typeof currentProp === 'string' && currentProp.match(R_HEX)) {
  1154. stateObject[prop] = sanitizeHexChunksToRGB(currentProp);
  1155. }
  1156. });
  1157. }
  1158. /**
  1159. * @param {string} str
  1160. *
  1161. * @return {string}
  1162. * @private
  1163. */
  1164. function sanitizeHexChunksToRGB (str) {
  1165. return filterStringChunks(R_HEX, str, convertHexToRGB);
  1166. }
  1167. /**
  1168. * @param {string} hexString
  1169. *
  1170. * @return {string}
  1171. * @private
  1172. */
  1173. function convertHexToRGB (hexString) {
  1174. var rgbArr = hexToRGBArray(hexString);
  1175. return 'rgb(' + rgbArr[0] + ',' + rgbArr[1] + ',' + rgbArr[2] + ')';
  1176. }
  1177. var hexToRGBArray_returnArray = [];
  1178. /**
  1179. * Convert a hexadecimal string to an array with three items, one each for
  1180. * the red, blue, and green decimal values.
  1181. *
  1182. * @param {string} hex A hexadecimal string.
  1183. *
  1184. * @returns {Array.<number>} The converted Array of RGB values if `hex` is a
  1185. * valid string, or an Array of three 0's.
  1186. * @private
  1187. */
  1188. function hexToRGBArray (hex) {
  1189. hex = hex.replace(/#/, '');
  1190. // If the string is a shorthand three digit hex notation, normalize it to
  1191. // the standard six digit notation
  1192. if (hex.length === 3) {
  1193. hex = hex.split('');
  1194. hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  1195. }
  1196. hexToRGBArray_returnArray[0] = hexToDec(hex.substr(0, 2));
  1197. hexToRGBArray_returnArray[1] = hexToDec(hex.substr(2, 2));
  1198. hexToRGBArray_returnArray[2] = hexToDec(hex.substr(4, 2));
  1199. return hexToRGBArray_returnArray;
  1200. }
  1201. /**
  1202. * Convert a base-16 number to base-10.
  1203. *
  1204. * @param {Number|String} hex The value to convert
  1205. *
  1206. * @returns {Number} The base-10 equivalent of `hex`.
  1207. * @private
  1208. */
  1209. function hexToDec (hex) {
  1210. return parseInt(hex, 16);
  1211. }
  1212. /**
  1213. * Runs a filter operation on all chunks of a string that match a RegExp
  1214. *
  1215. * @param {RegExp} pattern
  1216. * @param {string} unfilteredString
  1217. * @param {function(string)} filter
  1218. *
  1219. * @return {string}
  1220. * @private
  1221. */
  1222. function filterStringChunks (pattern, unfilteredString, filter) {
  1223. var pattenMatches = unfilteredString.match(pattern);
  1224. var filteredString = unfilteredString.replace(pattern, VALUE_PLACEHOLDER);
  1225. if (pattenMatches) {
  1226. var pattenMatchesLength = pattenMatches.length;
  1227. var currentChunk;
  1228. for (var i = 0; i < pattenMatchesLength; i++) {
  1229. currentChunk = pattenMatches.shift();
  1230. filteredString = filteredString.replace(
  1231. VALUE_PLACEHOLDER, filter(currentChunk));
  1232. }
  1233. }
  1234. return filteredString;
  1235. }
  1236. /**
  1237. * Check for floating point values within rgb strings and rounds them.
  1238. *
  1239. * @param {string} formattedString
  1240. *
  1241. * @return {string}
  1242. * @private
  1243. */
  1244. function sanitizeRGBChunks (formattedString) {
  1245. return filterStringChunks(R_RGB, formattedString, sanitizeRGBChunk);
  1246. }
  1247. /**
  1248. * @param {string} rgbChunk
  1249. *
  1250. * @return {string}
  1251. * @private
  1252. */
  1253. function sanitizeRGBChunk (rgbChunk) {
  1254. var numbers = rgbChunk.match(R_UNFORMATTED_VALUES);
  1255. var numbersLength = numbers.length;
  1256. var sanitizedString = rgbChunk.match(R_RGB_PREFIX)[0];
  1257. for (var i = 0; i < numbersLength; i++) {
  1258. sanitizedString += parseInt(numbers[i], 10) + ',';
  1259. }
  1260. sanitizedString = sanitizedString.slice(0, -1) + ')';
  1261. return sanitizedString;
  1262. }
  1263. /**
  1264. * @param {Object} stateObject
  1265. *
  1266. * @return {Object} An Object of formatManifests that correspond to
  1267. * the string properties of stateObject
  1268. * @private
  1269. */
  1270. function getFormatManifests (stateObject) {
  1271. var manifestAccumulator = {};
  1272. Tweenable.each(stateObject, function (prop) {
  1273. var currentProp = stateObject[prop];
  1274. if (typeof currentProp === 'string') {
  1275. var rawValues = getValuesFrom(currentProp);
  1276. manifestAccumulator[prop] = {
  1277. 'formatString': getFormatStringFrom(currentProp)
  1278. ,'chunkNames': getFormatChunksFrom(rawValues, prop)
  1279. };
  1280. }
  1281. });
  1282. return manifestAccumulator;
  1283. }
  1284. /**
  1285. * @param {Object} stateObject
  1286. * @param {Object} formatManifests
  1287. * @private
  1288. */
  1289. function expandFormattedProperties (stateObject, formatManifests) {
  1290. Tweenable.each(formatManifests, function (prop) {
  1291. var currentProp = stateObject[prop];
  1292. var rawValues = getValuesFrom(currentProp);
  1293. var rawValuesLength = rawValues.length;
  1294. for (var i = 0; i < rawValuesLength; i++) {
  1295. stateObject[formatManifests[prop].chunkNames[i]] = +rawValues[i];
  1296. }
  1297. delete stateObject[prop];
  1298. });
  1299. }
  1300. /**
  1301. * @param {Object} stateObject
  1302. * @param {Object} formatManifests
  1303. * @private
  1304. */
  1305. function collapseFormattedProperties (stateObject, formatManifests) {
  1306. Tweenable.each(formatManifests, function (prop) {
  1307. var currentProp = stateObject[prop];
  1308. var formatChunks = extractPropertyChunks(
  1309. stateObject, formatManifests[prop].chunkNames);
  1310. var valuesList = getValuesList(
  1311. formatChunks, formatManifests[prop].chunkNames);
  1312. currentProp = getFormattedValues(
  1313. formatManifests[prop].formatString, valuesList);
  1314. stateObject[prop] = sanitizeRGBChunks(currentProp);
  1315. });
  1316. }
  1317. /**
  1318. * @param {Object} stateObject
  1319. * @param {Array.<string>} chunkNames
  1320. *
  1321. * @return {Object} The extracted value chunks.
  1322. * @private
  1323. */
  1324. function extractPropertyChunks (stateObject, chunkNames) {
  1325. var extractedValues = {};
  1326. var currentChunkName, chunkNamesLength = chunkNames.length;
  1327. for (var i = 0; i < chunkNamesLength; i++) {
  1328. currentChunkName = chunkNames[i];
  1329. extractedValues[currentChunkName] = stateObject[currentChunkName];
  1330. delete stateObject[currentChunkName];
  1331. }
  1332. return extractedValues;
  1333. }
  1334. var getValuesList_accumulator = [];
  1335. /**
  1336. * @param {Object} stateObject
  1337. * @param {Array.<string>} chunkNames
  1338. *
  1339. * @return {Array.<number>}
  1340. * @private
  1341. */
  1342. function getValuesList (stateObject, chunkNames) {
  1343. getValuesList_accumulator.length = 0;
  1344. var chunkNamesLength = chunkNames.length;
  1345. for (var i = 0; i < chunkNamesLength; i++) {
  1346. getValuesList_accumulator.push(stateObject[chunkNames[i]]);
  1347. }
  1348. return getValuesList_accumulator;
  1349. }
  1350. /**
  1351. * @param {string} formatString
  1352. * @param {Array.<number>} rawValues
  1353. *
  1354. * @return {string}
  1355. * @private
  1356. */
  1357. function getFormattedValues (formatString, rawValues) {
  1358. var formattedValueString = formatString;
  1359. var rawValuesLength = rawValues.length;
  1360. for (var i = 0; i < rawValuesLength; i++) {
  1361. formattedValueString = formattedValueString.replace(
  1362. VALUE_PLACEHOLDER, +rawValues[i].toFixed(4));
  1363. }
  1364. return formattedValueString;
  1365. }
  1366. /**
  1367. * Note: It's the duty of the caller to convert the Array elements of the
  1368. * return value into numbers. This is a performance optimization.
  1369. *
  1370. * @param {string} formattedString
  1371. *
  1372. * @return {Array.<string>|null}
  1373. * @private
  1374. */
  1375. function getValuesFrom (formattedString) {
  1376. return formattedString.match(R_UNFORMATTED_VALUES);
  1377. }
  1378. /**
  1379. * @param {Object} easingObject
  1380. * @param {Object} tokenData
  1381. * @private
  1382. */
  1383. function expandEasingObject (easingObject, tokenData) {
  1384. Tweenable.each(tokenData, function (prop) {
  1385. var currentProp = tokenData[prop];
  1386. var chunkNames = currentProp.chunkNames;
  1387. var chunkLength = chunkNames.length;
  1388. var easing = easingObject[prop];
  1389. var i;
  1390. if (typeof easing === 'string') {
  1391. var easingChunks = easing.split(' ');
  1392. var lastEasingChunk = easingChunks[easingChunks.length - 1];
  1393. for (i = 0; i < chunkLength; i++) {
  1394. easingObject[chunkNames[i]] = easingChunks[i] || lastEasingChunk;
  1395. }
  1396. } else {
  1397. for (i = 0; i < chunkLength; i++) {
  1398. easingObject[chunkNames[i]] = easing;
  1399. }
  1400. }
  1401. delete easingObject[prop];
  1402. });
  1403. }
  1404. /**
  1405. * @param {Object} easingObject
  1406. * @param {Object} tokenData
  1407. * @private
  1408. */
  1409. function collapseEasingObject (easingObject, tokenData) {
  1410. Tweenable.each(tokenData, function (prop) {
  1411. var currentProp = tokenData[prop];
  1412. var chunkNames = currentProp.chunkNames;
  1413. var chunkLength = chunkNames.length;
  1414. var firstEasing = easingObject[chunkNames[0]];
  1415. var typeofEasings = typeof firstEasing;
  1416. if (typeofEasings === 'string') {
  1417. var composedEasingString = '';
  1418. for (var i = 0; i < chunkLength; i++) {
  1419. composedEasingString += ' ' + easingObject[chunkNames[i]];
  1420. delete easingObject[chunkNames[i]];
  1421. }
  1422. easingObject[prop] = composedEasingString.substr(1);
  1423. } else {
  1424. easingObject[prop] = firstEasing;
  1425. }
  1426. });
  1427. }
  1428. Tweenable.prototype.filter.token = {
  1429. 'tweenCreated': function (currentState, fromState, toState, easingObject) {
  1430. sanitizeObjectForHexProps(currentState);
  1431. sanitizeObjectForHexProps(fromState);
  1432. sanitizeObjectForHexProps(toState);
  1433. this._tokenData = getFormatManifests(currentState);
  1434. },
  1435. 'beforeTween': function (currentState, fromState, toState, easingObject) {
  1436. expandEasingObject(easingObject, this._tokenData);
  1437. expandFormattedProperties(currentState, this._tokenData);
  1438. expandFormattedProperties(fromState, this._tokenData);
  1439. expandFormattedProperties(toState, this._tokenData);
  1440. },
  1441. 'afterTween': function (currentState, fromState, toState, easingObject) {
  1442. collapseFormattedProperties(currentState, this._tokenData);
  1443. collapseFormattedProperties(fromState, this._tokenData);
  1444. collapseFormattedProperties(toState, this._tokenData);
  1445. collapseEasingObject(easingObject, this._tokenData);
  1446. }
  1447. };
  1448. } (Tweenable));
  1449. }).call(null);
  1450. },{}],2:[function(require,module,exports){
  1451. // Circle shaped progress bar
  1452. var Shape = require('./shape');
  1453. var utils = require('./utils');
  1454. var Circle = function Circle(container, options) {
  1455. // Use two arcs to form a circle
  1456. // See this answer http://stackoverflow.com/a/10477334/1446092
  1457. this._pathTemplate =
  1458. 'M 50,50 m 0,-{radius}' +
  1459. ' a {radius},{radius} 0 1 1 0,{2radius}' +
  1460. ' a {radius},{radius} 0 1 1 0,-{2radius}';
  1461. this.containerAspectRatio = 1;
  1462. Shape.apply(this, arguments);
  1463. };
  1464. Circle.prototype = new Shape();
  1465. Circle.prototype.constructor = Circle;
  1466. Circle.prototype._pathString = function _pathString(opts) {
  1467. var widthOfWider = opts.strokeWidth;
  1468. if (opts.trailWidth && opts.trailWidth > opts.strokeWidth) {
  1469. widthOfWider = opts.trailWidth;
  1470. }
  1471. var r = 50 - widthOfWider / 2;
  1472. return utils.render(this._pathTemplate, {
  1473. radius: r,
  1474. '2radius': r * 2
  1475. });
  1476. };
  1477. Circle.prototype._trailString = function _trailString(opts) {
  1478. return this._pathString(opts);
  1479. };
  1480. module.exports = Circle;
  1481. },{"./shape":7,"./utils":8}],3:[function(require,module,exports){
  1482. // Line shaped progress bar
  1483. var Shape = require('./shape');
  1484. var utils = require('./utils');
  1485. var Line = function Line(container, options) {
  1486. this._pathTemplate = 'M 0,{center} L 100,{center}';
  1487. Shape.apply(this, arguments);
  1488. };
  1489. Line.prototype = new Shape();
  1490. Line.prototype.constructor = Line;
  1491. Line.prototype._initializeSvg = function _initializeSvg(svg, opts) {
  1492. svg.setAttribute('viewBox', '0 0 100 ' + opts.strokeWidth);
  1493. svg.setAttribute('preserveAspectRatio', 'none');
  1494. };
  1495. Line.prototype._pathString = function _pathString(opts) {
  1496. return utils.render(this._pathTemplate, {
  1497. center: opts.strokeWidth / 2
  1498. });
  1499. };
  1500. Line.prototype._trailString = function _trailString(opts) {
  1501. return this._pathString(opts);
  1502. };
  1503. module.exports = Line;
  1504. },{"./shape":7,"./utils":8}],4:[function(require,module,exports){
  1505. module.exports = {
  1506. // Higher level API, different shaped progress bars
  1507. Line: require('./line'),
  1508. Circle: require('./circle'),
  1509. SemiCircle: require('./semicircle'),
  1510. // Lower level API to use any SVG path
  1511. Path: require('./path'),
  1512. // Base-class for creating new custom shapes
  1513. // to be in line with the API of built-in shapes
  1514. // Undocumented.
  1515. Shape: require('./shape'),
  1516. // Internal utils, undocumented.
  1517. utils: require('./utils')
  1518. };
  1519. },{"./circle":2,"./line":3,"./path":5,"./semicircle":6,"./shape":7,"./utils":8}],5:[function(require,module,exports){
  1520. // Lower level API to animate any kind of svg path
  1521. var Tweenable = require('shifty');
  1522. var utils = require('./utils');
  1523. var EASING_ALIASES = {
  1524. easeIn: 'easeInCubic',
  1525. easeOut: 'easeOutCubic',
  1526. easeInOut: 'easeInOutCubic'
  1527. };
  1528. var Path = function Path(path, opts) {
  1529. // Throw a better error if not initialized with `new` keyword
  1530. if (!(this instanceof Path)) {
  1531. throw new Error('Constructor was called without new keyword');
  1532. }
  1533. // Default parameters for animation
  1534. opts = utils.extend({
  1535. duration: 800,
  1536. easing: 'linear',
  1537. from: {},
  1538. to: {},
  1539. step: function() {}
  1540. }, opts);
  1541. var element;
  1542. if (utils.isString(path)) {
  1543. element = document.querySelector(path);
  1544. } else {
  1545. element = path;
  1546. }
  1547. // Reveal .path as public attribute
  1548. this.path = element;
  1549. this._opts = opts;
  1550. this._tweenable = null;
  1551. // Set up the starting positions
  1552. var length = this.path.getTotalLength();
  1553. this.path.style.strokeDasharray = length + ' ' + length;
  1554. this.set(0);
  1555. };
  1556. Path.prototype.value = function value() {
  1557. var offset = this._getComputedDashOffset();
  1558. var length = this.path.getTotalLength();
  1559. var progress = 1 - offset / length;
  1560. // Round number to prevent returning very small number like 1e-30, which
  1561. // is practically 0
  1562. return parseFloat(progress.toFixed(6), 10);
  1563. };
  1564. Path.prototype.set = function set(progress) {
  1565. this.stop();
  1566. this.path.style.strokeDashoffset = this._progressToOffset(progress);
  1567. var step = this._opts.step;
  1568. if (utils.isFunction(step)) {
  1569. var easing = this._easing(this._opts.easing);
  1570. var values = this._calculateTo(progress, easing);
  1571. var reference = this._opts.shape || this;
  1572. step(values, reference, this._opts.attachment);
  1573. }
  1574. };
  1575. Path.prototype.stop = function stop() {
  1576. this._stopTween();
  1577. this.path.style.strokeDashoffset = this._getComputedDashOffset();
  1578. };
  1579. // Method introduced here:
  1580. // http://jakearchibald.com/2013/animated-line-drawing-svg/
  1581. Path.prototype.animate = function animate(progress, opts, cb) {
  1582. opts = opts || {};
  1583. if (utils.isFunction(opts)) {
  1584. cb = opts;
  1585. opts = {};
  1586. }
  1587. var passedOpts = utils.extend({}, opts);
  1588. // Copy default opts to new object so defaults are not modified
  1589. var defaultOpts = utils.extend({}, this._opts);
  1590. opts = utils.extend(defaultOpts, opts);
  1591. var shiftyEasing = this._easing(opts.easing);
  1592. var values = this._resolveFromAndTo(progress, shiftyEasing, passedOpts);
  1593. this.stop();
  1594. // Trigger a layout so styles are calculated & the browser
  1595. // picks up the starting position before animating
  1596. this.path.getBoundingClientRect();
  1597. var offset = this._getComputedDashOffset();
  1598. var newOffset = this._progressToOffset(progress);
  1599. var self = this;
  1600. this._tweenable = new Tweenable();
  1601. this._tweenable.tween({
  1602. from: utils.extend({ offset: offset }, values.from),
  1603. to: utils.extend({ offset: newOffset }, values.to),
  1604. duration: opts.duration,
  1605. easing: shiftyEasing,
  1606. step: function(state) {
  1607. self.path.style.strokeDashoffset = state.offset;
  1608. var reference = opts.shape || self;
  1609. opts.step(state, reference, opts.attachment);
  1610. },
  1611. finish: function(state) {
  1612. if (utils.isFunction(cb)) {
  1613. cb();
  1614. }
  1615. }
  1616. });
  1617. };
  1618. Path.prototype._getComputedDashOffset = function _getComputedDashOffset() {
  1619. var computedStyle = window.getComputedStyle(this.path, null);
  1620. return parseFloat(computedStyle.getPropertyValue('stroke-dashoffset'), 10);
  1621. };
  1622. Path.prototype._progressToOffset = function _progressToOffset(progress) {
  1623. var length = this.path.getTotalLength();
  1624. return length - progress * length;
  1625. };
  1626. // Resolves from and to values for animation.
  1627. Path.prototype._resolveFromAndTo = function _resolveFromAndTo(progress, easing, opts) {
  1628. if (opts.from && opts.to) {
  1629. return {
  1630. from: opts.from,
  1631. to: opts.to
  1632. };
  1633. }
  1634. return {
  1635. from: this._calculateFrom(easing),
  1636. to: this._calculateTo(progress, easing)
  1637. };
  1638. };
  1639. // Calculate `from` values from options passed at initialization
  1640. Path.prototype._calculateFrom = function _calculateFrom(easing) {
  1641. return Tweenable.interpolate(this._opts.from, this._opts.to, this.value(), easing);
  1642. };
  1643. // Calculate `to` values from options passed at initialization
  1644. Path.prototype._calculateTo = function _calculateTo(progress, easing) {
  1645. return Tweenable.interpolate(this._opts.from, this._opts.to, progress, easing);
  1646. };
  1647. Path.prototype._stopTween = function _stopTween() {
  1648. if (this._tweenable !== null) {
  1649. this._tweenable.stop();
  1650. this._tweenable = null;
  1651. }
  1652. };
  1653. Path.prototype._easing = function _easing(easing) {
  1654. if (EASING_ALIASES.hasOwnProperty(easing)) {
  1655. return EASING_ALIASES[easing];
  1656. }
  1657. return easing;
  1658. };
  1659. module.exports = Path;
  1660. },{"./utils":8,"shifty":1}],6:[function(require,module,exports){
  1661. // Semi-SemiCircle shaped progress bar
  1662. var Shape = require('./shape');
  1663. var Circle = require('./circle');
  1664. var utils = require('./utils');
  1665. var SemiCircle = function SemiCircle(container, options) {
  1666. // Use one arc to form a SemiCircle
  1667. // See this answer http://stackoverflow.com/a/10477334/1446092
  1668. this._pathTemplate =
  1669. 'M 50,50 m -{radius},0' +
  1670. ' a {radius},{radius} 0 1 1 {2radius},0';
  1671. this.containerAspectRatio = 2;
  1672. Shape.apply(this, arguments);
  1673. };
  1674. SemiCircle.prototype = new Shape();
  1675. SemiCircle.prototype.constructor = SemiCircle;
  1676. SemiCircle.prototype._initializeSvg = function _initializeSvg(svg, opts) {
  1677. svg.setAttribute('viewBox', '0 0 100 50');
  1678. };
  1679. SemiCircle.prototype._initializeTextContainer = function _initializeTextContainer(
  1680. opts,
  1681. container,
  1682. textContainer
  1683. ) {
  1684. if (opts.text.style) {
  1685. // Reset top style
  1686. textContainer.style.top = 'auto';
  1687. textContainer.style.bottom = '0';
  1688. if (opts.text.alignToBottom) {
  1689. utils.setStyle(textContainer, 'transform', 'translate(-50%, 0)');
  1690. } else {
  1691. utils.setStyle(textContainer, 'transform', 'translate(-50%, 50%)');
  1692. }
  1693. }
  1694. };
  1695. // Share functionality with Circle, just have different path
  1696. SemiCircle.prototype._pathString = Circle.prototype._pathString;
  1697. SemiCircle.prototype._trailString = Circle.prototype._trailString;
  1698. module.exports = SemiCircle;
  1699. },{"./circle":2,"./shape":7,"./utils":8}],7:[function(require,module,exports){
  1700. // Base object for different progress bar shapes
  1701. var Path = require('./path');
  1702. var utils = require('./utils');
  1703. var DESTROYED_ERROR = 'Object is destroyed';
  1704. var Shape = function Shape(container, opts) {
  1705. // Throw a better error if progress bars are not initialized with `new`
  1706. // keyword
  1707. if (!(this instanceof Shape)) {
  1708. throw new Error('Constructor was called without new keyword');
  1709. }
  1710. // Prevent calling constructor without parameters so inheritance
  1711. // works correctly. To understand, this is how Shape is inherited:
  1712. //
  1713. // Line.prototype = new Shape();
  1714. //
  1715. // We just want to set the prototype for Line.
  1716. if (arguments.length === 0) {
  1717. return;
  1718. }
  1719. // Default parameters for progress bar creation
  1720. this._opts = utils.extend({
  1721. color: '#555',
  1722. strokeWidth: 1.0,
  1723. trailColor: null,
  1724. trailWidth: null,
  1725. fill: null,
  1726. text: {
  1727. style: {
  1728. color: null,
  1729. position: 'absolute',
  1730. left: '50%',
  1731. top: '50%',
  1732. padding: 0,
  1733. margin: 0,
  1734. transform: {
  1735. prefix: true,
  1736. value: 'translate(-50%, -50%)'
  1737. }
  1738. },
  1739. autoStyleContainer: true,
  1740. alignToBottom: true,
  1741. value: null,
  1742. className: 'progressbar-text'
  1743. },
  1744. svgStyle: {
  1745. display: 'block',
  1746. width: '100%'
  1747. },
  1748. warnings: false
  1749. }, opts, true); // Use recursive extend
  1750. // If user specifies e.g. svgStyle or text style, the whole object
  1751. // should replace the defaults to make working with styles easier
  1752. if (utils.isObject(opts) && opts.svgStyle !== undefined) {
  1753. this._opts.svgStyle = opts.svgStyle;
  1754. }
  1755. if (utils.isObject(opts) && utils.isObject(opts.text) && opts.text.style !== undefined) {
  1756. this._opts.text.style = opts.text.style;
  1757. }
  1758. var svgView = this._createSvgView(this._opts);
  1759. var element;
  1760. if (utils.isString(container)) {
  1761. element = document.querySelector(container);
  1762. } else {
  1763. element = container;
  1764. }
  1765. if (!element) {
  1766. throw new Error('Container does not exist: ' + container);
  1767. }
  1768. this._container = element;
  1769. this._container.appendChild(svgView.svg);
  1770. if (this._opts.warnings) {
  1771. this._warnContainerAspectRatio(this._container);
  1772. }
  1773. if (this._opts.svgStyle) {
  1774. utils.setStyles(svgView.svg, this._opts.svgStyle);
  1775. }
  1776. // Expose public attributes before Path initialization
  1777. this.svg = svgView.svg;
  1778. this.path = svgView.path;
  1779. this.trail = svgView.trail;
  1780. this.text = null;
  1781. var newOpts = utils.extend({
  1782. attachment: undefined,
  1783. shape: this
  1784. }, this._opts);
  1785. this._progressPath = new Path(svgView.path, newOpts);
  1786. if (utils.isObject(this._opts.text) && this._opts.text.value !== null) {
  1787. this.setText(this._opts.text.value);
  1788. }
  1789. };
  1790. Shape.prototype.animate = function animate(progress, opts, cb) {
  1791. if (this._progressPath === null) {
  1792. throw new Error(DESTROYED_ERROR);
  1793. }
  1794. this._progressPath.animate(progress, opts, cb);
  1795. };
  1796. Shape.prototype.stop = function stop() {
  1797. if (this._progressPath === null) {
  1798. throw new Error(DESTROYED_ERROR);
  1799. }
  1800. // Don't crash if stop is called inside step function
  1801. if (this._progressPath === undefined) {
  1802. return;
  1803. }
  1804. this._progressPath.stop();
  1805. };
  1806. Shape.prototype.destroy = function destroy() {
  1807. if (this._progressPath === null) {
  1808. throw new Error(DESTROYED_ERROR);
  1809. }
  1810. this.stop();
  1811. this.svg.parentNode.removeChild(this.svg);
  1812. this.svg = null;
  1813. this.path = null;
  1814. this.trail = null;
  1815. this._progressPath = null;
  1816. if (this.text !== null) {
  1817. this.text.parentNode.removeChild(this.text);
  1818. this.text = null;
  1819. }
  1820. };
  1821. Shape.prototype.set = function set(progress) {
  1822. if (this._progressPath === null) {
  1823. throw new Error(DESTROYED_ERROR);
  1824. }
  1825. this._progressPath.set(progress);
  1826. };
  1827. Shape.prototype.value = function value() {
  1828. if (this._progressPath === null) {
  1829. throw new Error(DESTROYED_ERROR);
  1830. }
  1831. if (this._progressPath === undefined) {
  1832. return 0;
  1833. }
  1834. return this._progressPath.value();
  1835. };
  1836. Shape.prototype.setText = function setText(newText) {
  1837. if (this._progressPath === null) {
  1838. throw new Error(DESTROYED_ERROR);
  1839. }
  1840. if (this.text === null) {
  1841. // Create new text node
  1842. this.text = this._createTextContainer(this._opts, this._container);
  1843. this._container.appendChild(this.text);
  1844. }
  1845. // Remove previous text and add new
  1846. if (utils.isObject(newText)) {
  1847. utils.removeChildren(this.text);
  1848. this.text.appendChild(newText);
  1849. } else {
  1850. this.text.innerHTML = newText;
  1851. }
  1852. };
  1853. Shape.prototype._createSvgView = function _createSvgView(opts) {
  1854. var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  1855. this._initializeSvg(svg, opts);
  1856. var trailPath = null;
  1857. // Each option listed in the if condition are 'triggers' for creating
  1858. // the trail path
  1859. if (opts.trailColor || opts.trailWidth) {
  1860. trailPath = this._createTrail(opts);
  1861. svg.appendChild(trailPath);
  1862. }
  1863. var path = this._createPath(opts);
  1864. svg.appendChild(path);
  1865. return {
  1866. svg: svg,
  1867. path: path,
  1868. trail: trailPath
  1869. };
  1870. };
  1871. Shape.prototype._initializeSvg = function _initializeSvg(svg, opts) {
  1872. svg.setAttribute('viewBox', '0 0 100 100');
  1873. };
  1874. Shape.prototype._createPath = function _createPath(opts) {
  1875. var pathString = this._pathString(opts);
  1876. return this._createPathElement(pathString, opts);
  1877. };
  1878. Shape.prototype._createTrail = function _createTrail(opts) {
  1879. // Create path string with original passed options
  1880. var pathString = this._trailString(opts);
  1881. // Prevent modifying original
  1882. var newOpts = utils.extend({}, opts);
  1883. // Defaults for parameters which modify trail path
  1884. if (!newOpts.trailColor) {
  1885. newOpts.trailColor = '#eee';
  1886. }
  1887. if (!newOpts.trailWidth) {
  1888. newOpts.trailWidth = newOpts.strokeWidth;
  1889. }
  1890. newOpts.color = newOpts.trailColor;
  1891. newOpts.strokeWidth = newOpts.trailWidth;
  1892. // When trail path is set, fill must be set for it instead of the
  1893. // actual path to prevent trail stroke from clipping
  1894. newOpts.fill = null;
  1895. return this._createPathElement(pathString, newOpts);
  1896. };
  1897. Shape.prototype._createPathElement = function _createPathElement(pathString, opts) {
  1898. var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  1899. path.setAttribute('d', pathString);
  1900. path.setAttribute('stroke', opts.color);
  1901. path.setAttribute('stroke-width', opts.strokeWidth);
  1902. if (opts.fill) {
  1903. path.setAttribute('fill', opts.fill);
  1904. } else {
  1905. path.setAttribute('fill-opacity', '0');
  1906. }
  1907. return path;
  1908. };
  1909. Shape.prototype._createTextContainer = function _createTextContainer(opts, container) {
  1910. var textContainer = document.createElement('div');
  1911. textContainer.className = opts.text.className;
  1912. var textStyle = opts.text.style;
  1913. if (textStyle) {
  1914. if (opts.text.autoStyleContainer) {
  1915. container.style.position = 'relative';
  1916. }
  1917. utils.setStyles(textContainer, textStyle);
  1918. // Default text color to progress bar's color
  1919. if (!textStyle.color) {
  1920. textContainer.style.color = opts.color;
  1921. }
  1922. }
  1923. this._initializeTextContainer(opts, container, textContainer);
  1924. return textContainer;
  1925. };
  1926. // Give custom shapes possibility to modify text element
  1927. Shape.prototype._initializeTextContainer = function(opts, container, element) {
  1928. // By default, no-op
  1929. // Custom shapes should respect API options, such as text.style
  1930. };
  1931. Shape.prototype._pathString = function _pathString(opts) {
  1932. throw new Error('Override this function for each progress bar');
  1933. };
  1934. Shape.prototype._trailString = function _trailString(opts) {
  1935. throw new Error('Override this function for each progress bar');
  1936. };
  1937. Shape.prototype._warnContainerAspectRatio = function _warnContainerAspectRatio(container) {
  1938. if (!this.containerAspectRatio) {
  1939. return;
  1940. }
  1941. var computedStyle = window.getComputedStyle(container, null);
  1942. var width = parseFloat(computedStyle.getPropertyValue('width'), 10);
  1943. var height = parseFloat(computedStyle.getPropertyValue('height'), 10);
  1944. if (!utils.floatEquals(this.containerAspectRatio, width / height)) {
  1945. console.warn(
  1946. 'Incorrect aspect ratio of container',
  1947. '#' + container.id,
  1948. 'detected:',
  1949. computedStyle.getPropertyValue('width') + '(width)',
  1950. '/',
  1951. computedStyle.getPropertyValue('height') + '(height)',
  1952. '=',
  1953. width / height
  1954. );
  1955. console.warn(
  1956. 'Aspect ratio of should be',
  1957. this.containerAspectRatio
  1958. );
  1959. }
  1960. };
  1961. module.exports = Shape;
  1962. },{"./path":5,"./utils":8}],8:[function(require,module,exports){
  1963. // Utility functions
  1964. var PREFIXES = 'Webkit Moz O ms'.split(' ');
  1965. var FLOAT_COMPARISON_EPSILON = 0.001;
  1966. // Copy all attributes from source object to destination object.
  1967. // destination object is mutated.
  1968. function extend(destination, source, recursive) {
  1969. destination = destination || {};
  1970. source = source || {};
  1971. recursive = recursive || false;
  1972. for (var attrName in source) {
  1973. if (source.hasOwnProperty(attrName)) {
  1974. var destVal = destination[attrName];
  1975. var sourceVal = source[attrName];
  1976. if (recursive && isObject(destVal) && isObject(sourceVal)) {
  1977. destination[attrName] = extend(destVal, sourceVal, recursive);
  1978. } else {
  1979. destination[attrName] = sourceVal;
  1980. }
  1981. }
  1982. }
  1983. return destination;
  1984. }
  1985. // Renders templates with given variables. Variables must be surrounded with
  1986. // braces without any spaces, e.g. {variable}
  1987. // All instances of variable placeholders will be replaced with given content
  1988. // Example:
  1989. // render('Hello, {message}!', {message: 'world'})
  1990. function render(template, vars) {
  1991. var rendered = template;
  1992. for (var key in vars) {
  1993. if (vars.hasOwnProperty(key)) {
  1994. var val = vars[key];
  1995. var regExpString = '\\{' + key + '\\}';
  1996. var regExp = new RegExp(regExpString, 'g');
  1997. rendered = rendered.replace(regExp, val);
  1998. }
  1999. }
  2000. return rendered;
  2001. }
  2002. function setStyle(element, style, value) {
  2003. var elStyle = element.style; // cache for performance
  2004. for (var i = 0; i < PREFIXES.length; ++i) {
  2005. var prefix = PREFIXES[i];
  2006. elStyle[prefix + capitalize(style)] = value;
  2007. }
  2008. elStyle[style] = value;
  2009. }
  2010. function setStyles(element, styles) {
  2011. forEachObject(styles, function(styleValue, styleName) {
  2012. // Allow disabling some individual styles by setting them
  2013. // to null or undefined
  2014. if (styleValue === null || styleValue === undefined) {
  2015. return;
  2016. }
  2017. // If style's value is {prefix: true, value: '50%'},
  2018. // Set also browser prefixed styles
  2019. if (isObject(styleValue) && styleValue.prefix === true) {
  2020. setStyle(element, styleName, styleValue.value);
  2021. } else {
  2022. element.style[styleName] = styleValue;
  2023. }
  2024. });
  2025. }
  2026. function capitalize(text) {
  2027. return text.charAt(0).toUpperCase() + text.slice(1);
  2028. }
  2029. function isString(obj) {
  2030. return typeof obj === 'string' || obj instanceof String;
  2031. }
  2032. function isFunction(obj) {
  2033. return typeof obj === 'function';
  2034. }
  2035. function isArray(obj) {
  2036. return Object.prototype.toString.call(obj) === '[object Array]';
  2037. }
  2038. // Returns true if `obj` is object as in {a: 1, b: 2}, not if it's function or
  2039. // array
  2040. function isObject(obj) {
  2041. if (isArray(obj)) {
  2042. return false;
  2043. }
  2044. var type = typeof obj;
  2045. return type === 'object' && !!obj;
  2046. }
  2047. function forEachObject(object, callback) {
  2048. for (var key in object) {
  2049. if (object.hasOwnProperty(key)) {
  2050. var val = object[key];
  2051. callback(val, key);
  2052. }
  2053. }
  2054. }
  2055. function floatEquals(a, b) {
  2056. return Math.abs(a - b) < FLOAT_COMPARISON_EPSILON;
  2057. }
  2058. // https://coderwall.com/p/nygghw/don-t-use-innerhtml-to-empty-dom-elements
  2059. function removeChildren(el) {
  2060. while (el.firstChild) {
  2061. el.removeChild(el.firstChild);
  2062. }
  2063. }
  2064. module.exports = {
  2065. extend: extend,
  2066. render: render,
  2067. setStyle: setStyle,
  2068. setStyles: setStyles,
  2069. capitalize: capitalize,
  2070. isString: isString,
  2071. isFunction: isFunction,
  2072. isObject: isObject,
  2073. forEachObject: forEachObject,
  2074. floatEquals: floatEquals,
  2075. removeChildren: removeChildren
  2076. };
  2077. },{}]},{},[4])(4)
  2078. });