progressbar.js 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  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. * console.log(interpolatedValues);
  903. * // {opacity: 0.5, width: "150px", color: "rgb(127,127,127)"}
  904. *
  905. * @static
  906. * @method interpolate
  907. * @param {Object} from The starting values to tween from.
  908. * @param {Object} targetState The ending values to tween to.
  909. * @param {number} position The normalized position value (between `0.0` and
  910. * `1.0`) to interpolate the values between `from` and `to` for. `from`
  911. * represents `0` and `to` represents `1`.
  912. * @param {Object.<string|Function>|string|Function} easing The easing
  913. * curve(s) to calculate the midpoint against. You can reference any easing
  914. * function attached to `Tweenable.prototype.formula`, or provide the easing
  915. * function(s) directly. If omitted, this defaults to "linear".
  916. * @param {number=} opt_delay Optional delay to pad the beginning of the
  917. * interpolated tween with. This increases the range of `position` from (`0`
  918. * through `1`) to (`0` through `1 + opt_delay`). So, a delay of `0.5` would
  919. * increase all valid values of `position` to numbers between `0` and `1.5`.
  920. * @return {Object}
  921. */
  922. Tweenable.interpolate = function (
  923. from, targetState, position, easing, opt_delay) {
  924. var current = Tweenable.shallowCopy({}, from);
  925. var delay = opt_delay || 0;
  926. var easingObject = Tweenable.composeEasingObject(
  927. from, easing || 'linear');
  928. mockTweenable.set({});
  929. // Alias and reuse the _filterArgs array instead of recreating it.
  930. var filterArgs = mockTweenable._filterArgs;
  931. filterArgs.length = 0;
  932. filterArgs[0] = current;
  933. filterArgs[1] = from;
  934. filterArgs[2] = targetState;
  935. filterArgs[3] = easingObject;
  936. // Any defined value transformation must be applied
  937. Tweenable.applyFilter(mockTweenable, 'tweenCreated');
  938. Tweenable.applyFilter(mockTweenable, 'beforeTween');
  939. var interpolatedValues = getInterpolatedValues(
  940. from, current, targetState, position, easingObject, delay);
  941. // Transform values back into their original format
  942. Tweenable.applyFilter(mockTweenable, 'afterTween');
  943. return interpolatedValues;
  944. };
  945. }());
  946. /**
  947. * This module adds string interpolation support to Shifty.
  948. *
  949. * The Token extension allows Shifty to tween numbers inside of strings. Among
  950. * other things, this allows you to animate CSS properties. For example, you
  951. * can do this:
  952. *
  953. * var tweenable = new Tweenable();
  954. * tweenable.tween({
  955. * from: { transform: 'translateX(45px)' },
  956. * to: { transform: 'translateX(90xp)' }
  957. * });
  958. *
  959. * `translateX(45)` will be tweened to `translateX(90)`. To demonstrate:
  960. *
  961. * var tweenable = new Tweenable();
  962. * tweenable.tween({
  963. * from: { transform: 'translateX(45px)' },
  964. * to: { transform: 'translateX(90px)' },
  965. * step: function (state) {
  966. * console.log(state.transform);
  967. * }
  968. * });
  969. *
  970. * The above snippet will log something like this in the console:
  971. *
  972. * translateX(60.3px)
  973. * ...
  974. * translateX(76.05px)
  975. * ...
  976. * translateX(90px)
  977. *
  978. * Another use for this is animating colors:
  979. *
  980. * var tweenable = new Tweenable();
  981. * tweenable.tween({
  982. * from: { color: 'rgb(0,255,0)' },
  983. * to: { color: 'rgb(255,0,255)' },
  984. * step: function (state) {
  985. * console.log(state.color);
  986. * }
  987. * });
  988. *
  989. * The above snippet will log something like this:
  990. *
  991. * rgb(84,170,84)
  992. * ...
  993. * rgb(170,84,170)
  994. * ...
  995. * rgb(255,0,255)
  996. *
  997. * This extension also supports hexadecimal colors, in both long (`#ff00ff`)
  998. * and short (`#f0f`) forms. Be aware that hexadecimal input values will be
  999. * converted into the equivalent RGB output values. This is done to optimize
  1000. * for performance.
  1001. *
  1002. * var tweenable = new Tweenable();
  1003. * tweenable.tween({
  1004. * from: { color: '#0f0' },
  1005. * to: { color: '#f0f' },
  1006. * step: function (state) {
  1007. * console.log(state.color);
  1008. * }
  1009. * });
  1010. *
  1011. * This snippet will generate the same output as the one before it because
  1012. * equivalent values were supplied (just in hexadecimal form rather than RGB):
  1013. *
  1014. * rgb(84,170,84)
  1015. * ...
  1016. * rgb(170,84,170)
  1017. * ...
  1018. * rgb(255,0,255)
  1019. *
  1020. * ## Easing support
  1021. *
  1022. * Easing works somewhat differently in the Token extension. This is because
  1023. * some CSS properties have multiple values in them, and you might need to
  1024. * tween each value along its own easing curve. A basic example:
  1025. *
  1026. * var tweenable = new Tweenable();
  1027. * tweenable.tween({
  1028. * from: { transform: 'translateX(0px) translateY(0px)' },
  1029. * to: { transform: 'translateX(100px) translateY(100px)' },
  1030. * easing: { transform: 'easeInQuad' },
  1031. * step: function (state) {
  1032. * console.log(state.transform);
  1033. * }
  1034. * });
  1035. *
  1036. * The above snippet will create values like this:
  1037. *
  1038. * translateX(11.56px) translateY(11.56px)
  1039. * ...
  1040. * translateX(46.24px) translateY(46.24px)
  1041. * ...
  1042. * translateX(100px) translateY(100px)
  1043. *
  1044. * In this case, the values for `translateX` and `translateY` are always the
  1045. * same for each step of the tween, because they have the same start and end
  1046. * points and both use the same easing curve. We can also tween `translateX`
  1047. * and `translateY` along independent curves:
  1048. *
  1049. * var tweenable = new Tweenable();
  1050. * tweenable.tween({
  1051. * from: { transform: 'translateX(0px) translateY(0px)' },
  1052. * to: { transform: 'translateX(100px) translateY(100px)' },
  1053. * easing: { transform: 'easeInQuad bounce' },
  1054. * step: function (state) {
  1055. * console.log(state.transform);
  1056. * }
  1057. * });
  1058. *
  1059. * The above snippet will create values like this:
  1060. *
  1061. * translateX(10.89px) translateY(82.35px)
  1062. * ...
  1063. * translateX(44.89px) translateY(86.73px)
  1064. * ...
  1065. * translateX(100px) translateY(100px)
  1066. *
  1067. * `translateX` and `translateY` are not in sync anymore, because `easeInQuad`
  1068. * was specified for `translateX` and `bounce` for `translateY`. Mixing and
  1069. * matching easing curves can make for some interesting motion in your
  1070. * animations.
  1071. *
  1072. * The order of the space-separated easing curves correspond the token values
  1073. * they apply to. If there are more token values than easing curves listed,
  1074. * the last easing curve listed is used.
  1075. * @submodule Tweenable.token
  1076. */
  1077. // token function is defined above only so that dox-foundation sees it as
  1078. // documentation and renders it. It is never used, and is optimized away at
  1079. // build time.
  1080. ;(function (Tweenable) {
  1081. /**
  1082. * @typedef {{
  1083. * formatString: string
  1084. * chunkNames: Array.<string>
  1085. * }}
  1086. * @private
  1087. */
  1088. var formatManifest;
  1089. // CONSTANTS
  1090. var R_NUMBER_COMPONENT = /(\d|\-|\.)/;
  1091. var R_FORMAT_CHUNKS = /([^\-0-9\.]+)/g;
  1092. var R_UNFORMATTED_VALUES = /[0-9.\-]+/g;
  1093. var R_RGB = new RegExp(
  1094. 'rgb\\(' + R_UNFORMATTED_VALUES.source +
  1095. (/,\s*/.source) + R_UNFORMATTED_VALUES.source +
  1096. (/,\s*/.source) + R_UNFORMATTED_VALUES.source + '\\)', 'g');
  1097. var R_RGB_PREFIX = /^.*\(/;
  1098. var R_HEX = /#([0-9]|[a-f]){3,6}/gi;
  1099. var VALUE_PLACEHOLDER = 'VAL';
  1100. // HELPERS
  1101. /**
  1102. * @param {Array.number} rawValues
  1103. * @param {string} prefix
  1104. *
  1105. * @return {Array.<string>}
  1106. * @private
  1107. */
  1108. function getFormatChunksFrom (rawValues, prefix) {
  1109. var accumulator = [];
  1110. var rawValuesLength = rawValues.length;
  1111. var i;
  1112. for (i = 0; i < rawValuesLength; i++) {
  1113. accumulator.push('_' + prefix + '_' + i);
  1114. }
  1115. return accumulator;
  1116. }
  1117. /**
  1118. * @param {string} formattedString
  1119. *
  1120. * @return {string}
  1121. * @private
  1122. */
  1123. function getFormatStringFrom (formattedString) {
  1124. var chunks = formattedString.match(R_FORMAT_CHUNKS);
  1125. if (!chunks) {
  1126. // chunks will be null if there were no tokens to parse in
  1127. // formattedString (for example, if formattedString is '2'). Coerce
  1128. // chunks to be useful here.
  1129. chunks = ['', ''];
  1130. // If there is only one chunk, assume that the string is a number
  1131. // followed by a token...
  1132. // NOTE: This may be an unwise assumption.
  1133. } else if (chunks.length === 1 ||
  1134. // ...or if the string starts with a number component (".", "-", or a
  1135. // digit)...
  1136. formattedString[0].match(R_NUMBER_COMPONENT)) {
  1137. // ...prepend an empty string here to make sure that the formatted number
  1138. // is properly replaced by VALUE_PLACEHOLDER
  1139. chunks.unshift('');
  1140. }
  1141. return chunks.join(VALUE_PLACEHOLDER);
  1142. }
  1143. /**
  1144. * Convert all hex color values within a string to an rgb string.
  1145. *
  1146. * @param {Object} stateObject
  1147. *
  1148. * @return {Object} The modified obj
  1149. * @private
  1150. */
  1151. function sanitizeObjectForHexProps (stateObject) {
  1152. Tweenable.each(stateObject, function (prop) {
  1153. var currentProp = stateObject[prop];
  1154. if (typeof currentProp === 'string' && currentProp.match(R_HEX)) {
  1155. stateObject[prop] = sanitizeHexChunksToRGB(currentProp);
  1156. }
  1157. });
  1158. }
  1159. /**
  1160. * @param {string} str
  1161. *
  1162. * @return {string}
  1163. * @private
  1164. */
  1165. function sanitizeHexChunksToRGB (str) {
  1166. return filterStringChunks(R_HEX, str, convertHexToRGB);
  1167. }
  1168. /**
  1169. * @param {string} hexString
  1170. *
  1171. * @return {string}
  1172. * @private
  1173. */
  1174. function convertHexToRGB (hexString) {
  1175. var rgbArr = hexToRGBArray(hexString);
  1176. return 'rgb(' + rgbArr[0] + ',' + rgbArr[1] + ',' + rgbArr[2] + ')';
  1177. }
  1178. var hexToRGBArray_returnArray = [];
  1179. /**
  1180. * Convert a hexadecimal string to an array with three items, one each for
  1181. * the red, blue, and green decimal values.
  1182. *
  1183. * @param {string} hex A hexadecimal string.
  1184. *
  1185. * @returns {Array.<number>} The converted Array of RGB values if `hex` is a
  1186. * valid string, or an Array of three 0's.
  1187. * @private
  1188. */
  1189. function hexToRGBArray (hex) {
  1190. hex = hex.replace(/#/, '');
  1191. // If the string is a shorthand three digit hex notation, normalize it to
  1192. // the standard six digit notation
  1193. if (hex.length === 3) {
  1194. hex = hex.split('');
  1195. hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  1196. }
  1197. hexToRGBArray_returnArray[0] = hexToDec(hex.substr(0, 2));
  1198. hexToRGBArray_returnArray[1] = hexToDec(hex.substr(2, 2));
  1199. hexToRGBArray_returnArray[2] = hexToDec(hex.substr(4, 2));
  1200. return hexToRGBArray_returnArray;
  1201. }
  1202. /**
  1203. * Convert a base-16 number to base-10.
  1204. *
  1205. * @param {Number|String} hex The value to convert
  1206. *
  1207. * @returns {Number} The base-10 equivalent of `hex`.
  1208. * @private
  1209. */
  1210. function hexToDec (hex) {
  1211. return parseInt(hex, 16);
  1212. }
  1213. /**
  1214. * Runs a filter operation on all chunks of a string that match a RegExp
  1215. *
  1216. * @param {RegExp} pattern
  1217. * @param {string} unfilteredString
  1218. * @param {function(string)} filter
  1219. *
  1220. * @return {string}
  1221. * @private
  1222. */
  1223. function filterStringChunks (pattern, unfilteredString, filter) {
  1224. var pattenMatches = unfilteredString.match(pattern);
  1225. var filteredString = unfilteredString.replace(pattern, VALUE_PLACEHOLDER);
  1226. if (pattenMatches) {
  1227. var pattenMatchesLength = pattenMatches.length;
  1228. var currentChunk;
  1229. for (var i = 0; i < pattenMatchesLength; i++) {
  1230. currentChunk = pattenMatches.shift();
  1231. filteredString = filteredString.replace(
  1232. VALUE_PLACEHOLDER, filter(currentChunk));
  1233. }
  1234. }
  1235. return filteredString;
  1236. }
  1237. /**
  1238. * Check for floating point values within rgb strings and rounds them.
  1239. *
  1240. * @param {string} formattedString
  1241. *
  1242. * @return {string}
  1243. * @private
  1244. */
  1245. function sanitizeRGBChunks (formattedString) {
  1246. return filterStringChunks(R_RGB, formattedString, sanitizeRGBChunk);
  1247. }
  1248. /**
  1249. * @param {string} rgbChunk
  1250. *
  1251. * @return {string}
  1252. * @private
  1253. */
  1254. function sanitizeRGBChunk (rgbChunk) {
  1255. var numbers = rgbChunk.match(R_UNFORMATTED_VALUES);
  1256. var numbersLength = numbers.length;
  1257. var sanitizedString = rgbChunk.match(R_RGB_PREFIX)[0];
  1258. for (var i = 0; i < numbersLength; i++) {
  1259. sanitizedString += parseInt(numbers[i], 10) + ',';
  1260. }
  1261. sanitizedString = sanitizedString.slice(0, -1) + ')';
  1262. return sanitizedString;
  1263. }
  1264. /**
  1265. * @param {Object} stateObject
  1266. *
  1267. * @return {Object} An Object of formatManifests that correspond to
  1268. * the string properties of stateObject
  1269. * @private
  1270. */
  1271. function getFormatManifests (stateObject) {
  1272. var manifestAccumulator = {};
  1273. Tweenable.each(stateObject, function (prop) {
  1274. var currentProp = stateObject[prop];
  1275. if (typeof currentProp === 'string') {
  1276. var rawValues = getValuesFrom(currentProp);
  1277. manifestAccumulator[prop] = {
  1278. 'formatString': getFormatStringFrom(currentProp)
  1279. ,'chunkNames': getFormatChunksFrom(rawValues, prop)
  1280. };
  1281. }
  1282. });
  1283. return manifestAccumulator;
  1284. }
  1285. /**
  1286. * @param {Object} stateObject
  1287. * @param {Object} formatManifests
  1288. * @private
  1289. */
  1290. function expandFormattedProperties (stateObject, formatManifests) {
  1291. Tweenable.each(formatManifests, function (prop) {
  1292. var currentProp = stateObject[prop];
  1293. var rawValues = getValuesFrom(currentProp);
  1294. var rawValuesLength = rawValues.length;
  1295. for (var i = 0; i < rawValuesLength; i++) {
  1296. stateObject[formatManifests[prop].chunkNames[i]] = +rawValues[i];
  1297. }
  1298. delete stateObject[prop];
  1299. });
  1300. }
  1301. /**
  1302. * @param {Object} stateObject
  1303. * @param {Object} formatManifests
  1304. * @private
  1305. */
  1306. function collapseFormattedProperties (stateObject, formatManifests) {
  1307. Tweenable.each(formatManifests, function (prop) {
  1308. var currentProp = stateObject[prop];
  1309. var formatChunks = extractPropertyChunks(
  1310. stateObject, formatManifests[prop].chunkNames);
  1311. var valuesList = getValuesList(
  1312. formatChunks, formatManifests[prop].chunkNames);
  1313. currentProp = getFormattedValues(
  1314. formatManifests[prop].formatString, valuesList);
  1315. stateObject[prop] = sanitizeRGBChunks(currentProp);
  1316. });
  1317. }
  1318. /**
  1319. * @param {Object} stateObject
  1320. * @param {Array.<string>} chunkNames
  1321. *
  1322. * @return {Object} The extracted value chunks.
  1323. * @private
  1324. */
  1325. function extractPropertyChunks (stateObject, chunkNames) {
  1326. var extractedValues = {};
  1327. var currentChunkName, chunkNamesLength = chunkNames.length;
  1328. for (var i = 0; i < chunkNamesLength; i++) {
  1329. currentChunkName = chunkNames[i];
  1330. extractedValues[currentChunkName] = stateObject[currentChunkName];
  1331. delete stateObject[currentChunkName];
  1332. }
  1333. return extractedValues;
  1334. }
  1335. var getValuesList_accumulator = [];
  1336. /**
  1337. * @param {Object} stateObject
  1338. * @param {Array.<string>} chunkNames
  1339. *
  1340. * @return {Array.<number>}
  1341. * @private
  1342. */
  1343. function getValuesList (stateObject, chunkNames) {
  1344. getValuesList_accumulator.length = 0;
  1345. var chunkNamesLength = chunkNames.length;
  1346. for (var i = 0; i < chunkNamesLength; i++) {
  1347. getValuesList_accumulator.push(stateObject[chunkNames[i]]);
  1348. }
  1349. return getValuesList_accumulator;
  1350. }
  1351. /**
  1352. * @param {string} formatString
  1353. * @param {Array.<number>} rawValues
  1354. *
  1355. * @return {string}
  1356. * @private
  1357. */
  1358. function getFormattedValues (formatString, rawValues) {
  1359. var formattedValueString = formatString;
  1360. var rawValuesLength = rawValues.length;
  1361. for (var i = 0; i < rawValuesLength; i++) {
  1362. formattedValueString = formattedValueString.replace(
  1363. VALUE_PLACEHOLDER, +rawValues[i].toFixed(4));
  1364. }
  1365. return formattedValueString;
  1366. }
  1367. /**
  1368. * Note: It's the duty of the caller to convert the Array elements of the
  1369. * return value into numbers. This is a performance optimization.
  1370. *
  1371. * @param {string} formattedString
  1372. *
  1373. * @return {Array.<string>|null}
  1374. * @private
  1375. */
  1376. function getValuesFrom (formattedString) {
  1377. return formattedString.match(R_UNFORMATTED_VALUES);
  1378. }
  1379. /**
  1380. * @param {Object} easingObject
  1381. * @param {Object} tokenData
  1382. * @private
  1383. */
  1384. function expandEasingObject (easingObject, tokenData) {
  1385. Tweenable.each(tokenData, function (prop) {
  1386. var currentProp = tokenData[prop];
  1387. var chunkNames = currentProp.chunkNames;
  1388. var chunkLength = chunkNames.length;
  1389. var easing = easingObject[prop];
  1390. var i;
  1391. if (typeof easing === 'string') {
  1392. var easingChunks = easing.split(' ');
  1393. var lastEasingChunk = easingChunks[easingChunks.length - 1];
  1394. for (i = 0; i < chunkLength; i++) {
  1395. easingObject[chunkNames[i]] = easingChunks[i] || lastEasingChunk;
  1396. }
  1397. } else {
  1398. for (i = 0; i < chunkLength; i++) {
  1399. easingObject[chunkNames[i]] = easing;
  1400. }
  1401. }
  1402. delete easingObject[prop];
  1403. });
  1404. }
  1405. /**
  1406. * @param {Object} easingObject
  1407. * @param {Object} tokenData
  1408. * @private
  1409. */
  1410. function collapseEasingObject (easingObject, tokenData) {
  1411. Tweenable.each(tokenData, function (prop) {
  1412. var currentProp = tokenData[prop];
  1413. var chunkNames = currentProp.chunkNames;
  1414. var chunkLength = chunkNames.length;
  1415. var firstEasing = easingObject[chunkNames[0]];
  1416. var typeofEasings = typeof firstEasing;
  1417. if (typeofEasings === 'string') {
  1418. var composedEasingString = '';
  1419. for (var i = 0; i < chunkLength; i++) {
  1420. composedEasingString += ' ' + easingObject[chunkNames[i]];
  1421. delete easingObject[chunkNames[i]];
  1422. }
  1423. easingObject[prop] = composedEasingString.substr(1);
  1424. } else {
  1425. easingObject[prop] = firstEasing;
  1426. }
  1427. });
  1428. }
  1429. Tweenable.prototype.filter.token = {
  1430. 'tweenCreated': function (currentState, fromState, toState, easingObject) {
  1431. sanitizeObjectForHexProps(currentState);
  1432. sanitizeObjectForHexProps(fromState);
  1433. sanitizeObjectForHexProps(toState);
  1434. this._tokenData = getFormatManifests(currentState);
  1435. },
  1436. 'beforeTween': function (currentState, fromState, toState, easingObject) {
  1437. expandEasingObject(easingObject, this._tokenData);
  1438. expandFormattedProperties(currentState, this._tokenData);
  1439. expandFormattedProperties(fromState, this._tokenData);
  1440. expandFormattedProperties(toState, this._tokenData);
  1441. },
  1442. 'afterTween': function (currentState, fromState, toState, easingObject) {
  1443. collapseFormattedProperties(currentState, this._tokenData);
  1444. collapseFormattedProperties(fromState, this._tokenData);
  1445. collapseFormattedProperties(toState, this._tokenData);
  1446. collapseEasingObject(easingObject, this._tokenData);
  1447. }
  1448. };
  1449. } (Tweenable));
  1450. }).call(null);
  1451. },{}],2:[function(require,module,exports){
  1452. // Circle shaped progress bar
  1453. var Shape = require('./shape');
  1454. var utils = require('./utils');
  1455. var Circle = function Circle(container, options) {
  1456. // Use two arcs to form a circle
  1457. // See this answer http://stackoverflow.com/a/10477334/1446092
  1458. this._pathTemplate =
  1459. 'M 50,50 m 0,-{radius}' +
  1460. ' a {radius},{radius} 0 1 1 0,{2radius}' +
  1461. ' a {radius},{radius} 0 1 1 0,-{2radius}';
  1462. this.containerAspectRatio = 1;
  1463. Shape.apply(this, arguments);
  1464. };
  1465. Circle.prototype = new Shape();
  1466. Circle.prototype.constructor = Circle;
  1467. Circle.prototype._pathString = function _pathString(opts) {
  1468. var widthOfWider = opts.strokeWidth;
  1469. if (opts.trailWidth && opts.trailWidth > opts.strokeWidth) {
  1470. widthOfWider = opts.trailWidth;
  1471. }
  1472. var r = 50 - widthOfWider / 2;
  1473. return utils.render(this._pathTemplate, {
  1474. radius: r,
  1475. '2radius': r * 2
  1476. });
  1477. };
  1478. Circle.prototype._trailString = function _trailString(opts) {
  1479. return this._pathString(opts);
  1480. };
  1481. module.exports = Circle;
  1482. },{"./shape":7,"./utils":8}],3:[function(require,module,exports){
  1483. // Line shaped progress bar
  1484. var Shape = require('./shape');
  1485. var utils = require('./utils');
  1486. var Line = function Line(container, options) {
  1487. this._pathTemplate = 'M 0,{center} L 100,{center}';
  1488. Shape.apply(this, arguments);
  1489. };
  1490. Line.prototype = new Shape();
  1491. Line.prototype.constructor = Line;
  1492. Line.prototype._initializeSvg = function _initializeSvg(svg, opts) {
  1493. svg.setAttribute('viewBox', '0 0 100 ' + opts.strokeWidth);
  1494. svg.setAttribute('preserveAspectRatio', 'none');
  1495. };
  1496. Line.prototype._pathString = function _pathString(opts) {
  1497. return utils.render(this._pathTemplate, {
  1498. center: opts.strokeWidth / 2
  1499. });
  1500. };
  1501. Line.prototype._trailString = function _trailString(opts) {
  1502. return this._pathString(opts);
  1503. };
  1504. module.exports = Line;
  1505. },{"./shape":7,"./utils":8}],4:[function(require,module,exports){
  1506. module.exports = {
  1507. // Higher level API, different shaped progress bars
  1508. Line: require('./line'),
  1509. Circle: require('./circle'),
  1510. SemiCircle: require('./semicircle'),
  1511. // Lower level API to use any SVG path
  1512. Path: require('./path'),
  1513. // Base-class for creating new custom shapes
  1514. // to be in line with the API of built-in shapes
  1515. // Undocumented.
  1516. Shape: require('./shape'),
  1517. // Internal utils, undocumented.
  1518. utils: require('./utils')
  1519. };
  1520. },{"./circle":2,"./line":3,"./path":5,"./semicircle":6,"./shape":7,"./utils":8}],5:[function(require,module,exports){
  1521. // Lower level API to animate any kind of svg path
  1522. var Tweenable = require('shifty');
  1523. var utils = require('./utils');
  1524. var EASING_ALIASES = {
  1525. easeIn: 'easeInCubic',
  1526. easeOut: 'easeOutCubic',
  1527. easeInOut: 'easeInOutCubic'
  1528. };
  1529. var Path = function Path(path, opts) {
  1530. // Throw a better error if not initialized with `new` keyword
  1531. if (!(this instanceof Path)) {
  1532. throw new Error('Constructor was called without new keyword');
  1533. }
  1534. // Default parameters for animation
  1535. opts = utils.extend({
  1536. duration: 800,
  1537. easing: 'linear',
  1538. from: {},
  1539. to: {},
  1540. step: function() {}
  1541. }, opts);
  1542. var element;
  1543. if (utils.isString(path)) {
  1544. element = document.querySelector(path);
  1545. } else {
  1546. element = path;
  1547. }
  1548. // Reveal .path as public attribute
  1549. this.path = element;
  1550. this._opts = opts;
  1551. this._tweenable = null;
  1552. // Set up the starting positions
  1553. var length = this.path.getTotalLength();
  1554. this.path.style.strokeDasharray = length + ' ' + length;
  1555. this.set(0);
  1556. };
  1557. Path.prototype.value = function value() {
  1558. var offset = this._getComputedDashOffset();
  1559. var length = this.path.getTotalLength();
  1560. var progress = 1 - offset / length;
  1561. // Round number to prevent returning very small number like 1e-30, which
  1562. // is practically 0
  1563. return parseFloat(progress.toFixed(6), 10);
  1564. };
  1565. Path.prototype.set = function set(progress) {
  1566. this.stop();
  1567. this.path.style.strokeDashoffset = this._progressToOffset(progress);
  1568. var step = this._opts.step;
  1569. if (utils.isFunction(step)) {
  1570. var easing = this._easing(this._opts.easing);
  1571. var values = this._calculateTo(progress, easing);
  1572. var reference = this._opts.shape || this;
  1573. step(values, reference, this._opts.attachment);
  1574. }
  1575. };
  1576. Path.prototype.stop = function stop() {
  1577. this._stopTween();
  1578. this.path.style.strokeDashoffset = this._getComputedDashOffset();
  1579. };
  1580. // Method introduced here:
  1581. // http://jakearchibald.com/2013/animated-line-drawing-svg/
  1582. Path.prototype.animate = function animate(progress, opts, cb) {
  1583. opts = opts || {};
  1584. if (utils.isFunction(opts)) {
  1585. cb = opts;
  1586. opts = {};
  1587. }
  1588. var passedOpts = utils.extend({}, opts);
  1589. // Copy default opts to new object so defaults are not modified
  1590. var defaultOpts = utils.extend({}, this._opts);
  1591. opts = utils.extend(defaultOpts, opts);
  1592. var shiftyEasing = this._easing(opts.easing);
  1593. var values = this._resolveFromAndTo(progress, shiftyEasing, passedOpts);
  1594. this.stop();
  1595. // Trigger a layout so styles are calculated & the browser
  1596. // picks up the starting position before animating
  1597. this.path.getBoundingClientRect();
  1598. var offset = this._getComputedDashOffset();
  1599. var newOffset = this._progressToOffset(progress);
  1600. var self = this;
  1601. this._tweenable = new Tweenable();
  1602. this._tweenable.tween({
  1603. from: utils.extend({ offset: offset }, values.from),
  1604. to: utils.extend({ offset: newOffset }, values.to),
  1605. duration: opts.duration,
  1606. easing: shiftyEasing,
  1607. step: function(state) {
  1608. self.path.style.strokeDashoffset = state.offset;
  1609. var reference = opts.shape || self;
  1610. opts.step(state, reference, opts.attachment);
  1611. },
  1612. finish: function(state) {
  1613. if (utils.isFunction(cb)) {
  1614. cb();
  1615. }
  1616. }
  1617. });
  1618. };
  1619. Path.prototype._getComputedDashOffset = function _getComputedDashOffset() {
  1620. var computedStyle = window.getComputedStyle(this.path, null);
  1621. return parseFloat(computedStyle.getPropertyValue('stroke-dashoffset'), 10);
  1622. };
  1623. Path.prototype._progressToOffset = function _progressToOffset(progress) {
  1624. var length = this.path.getTotalLength();
  1625. return length - progress * length;
  1626. };
  1627. // Resolves from and to values for animation.
  1628. Path.prototype._resolveFromAndTo = function _resolveFromAndTo(progress, easing, opts) {
  1629. if (opts.from && opts.to) {
  1630. return {
  1631. from: opts.from,
  1632. to: opts.to
  1633. };
  1634. }
  1635. return {
  1636. from: this._calculateFrom(easing),
  1637. to: this._calculateTo(progress, easing)
  1638. };
  1639. };
  1640. // Calculate `from` values from options passed at initialization
  1641. Path.prototype._calculateFrom = function _calculateFrom(easing) {
  1642. return Tweenable.interpolate(this._opts.from, this._opts.to, this.value(), easing);
  1643. };
  1644. // Calculate `to` values from options passed at initialization
  1645. Path.prototype._calculateTo = function _calculateTo(progress, easing) {
  1646. return Tweenable.interpolate(this._opts.from, this._opts.to, progress, easing);
  1647. };
  1648. Path.prototype._stopTween = function _stopTween() {
  1649. if (this._tweenable !== null) {
  1650. this._tweenable.stop();
  1651. this._tweenable = null;
  1652. }
  1653. };
  1654. Path.prototype._easing = function _easing(easing) {
  1655. if (EASING_ALIASES.hasOwnProperty(easing)) {
  1656. return EASING_ALIASES[easing];
  1657. }
  1658. return easing;
  1659. };
  1660. module.exports = Path;
  1661. },{"./utils":8,"shifty":1}],6:[function(require,module,exports){
  1662. // Semi-SemiCircle shaped progress bar
  1663. var Shape = require('./shape');
  1664. var Circle = require('./circle');
  1665. var utils = require('./utils');
  1666. var SemiCircle = function SemiCircle(container, options) {
  1667. // Use one arc to form a SemiCircle
  1668. // See this answer http://stackoverflow.com/a/10477334/1446092
  1669. this._pathTemplate =
  1670. 'M 50,50 m -{radius},0' +
  1671. ' a {radius},{radius} 0 1 1 {2radius},0';
  1672. this.containerAspectRatio = 2;
  1673. Shape.apply(this, arguments);
  1674. };
  1675. SemiCircle.prototype = new Shape();
  1676. SemiCircle.prototype.constructor = SemiCircle;
  1677. SemiCircle.prototype._initializeSvg = function _initializeSvg(svg, opts) {
  1678. svg.setAttribute('viewBox', '0 0 100 50');
  1679. };
  1680. SemiCircle.prototype._initializeTextContainer = function _initializeTextContainer(
  1681. opts,
  1682. container,
  1683. textContainer
  1684. ) {
  1685. if (opts.text.style) {
  1686. // Reset top style
  1687. textContainer.style.top = 'auto';
  1688. textContainer.style.bottom = '0';
  1689. if (opts.text.alignToBottom) {
  1690. utils.setStyle(textContainer, 'transform', 'translate(-50%, 0)');
  1691. } else {
  1692. utils.setStyle(textContainer, 'transform', 'translate(-50%, 50%)');
  1693. }
  1694. }
  1695. };
  1696. // Share functionality with Circle, just have different path
  1697. SemiCircle.prototype._pathString = Circle.prototype._pathString;
  1698. SemiCircle.prototype._trailString = Circle.prototype._trailString;
  1699. module.exports = SemiCircle;
  1700. },{"./circle":2,"./shape":7,"./utils":8}],7:[function(require,module,exports){
  1701. // Base object for different progress bar shapes
  1702. var Path = require('./path');
  1703. var utils = require('./utils');
  1704. var DESTROYED_ERROR = 'Object is destroyed';
  1705. var Shape = function Shape(container, opts) {
  1706. // Throw a better error if progress bars are not initialized with `new`
  1707. // keyword
  1708. if (!(this instanceof Shape)) {
  1709. throw new Error('Constructor was called without new keyword');
  1710. }
  1711. // Prevent calling constructor without parameters so inheritance
  1712. // works correctly. To understand, this is how Shape is inherited:
  1713. //
  1714. // Line.prototype = new Shape();
  1715. //
  1716. // We just want to set the prototype for Line.
  1717. if (arguments.length === 0) {
  1718. return;
  1719. }
  1720. // Default parameters for progress bar creation
  1721. this._opts = utils.extend({
  1722. color: '#555',
  1723. strokeWidth: 1.0,
  1724. trailColor: null,
  1725. trailWidth: null,
  1726. fill: null,
  1727. text: {
  1728. style: {
  1729. color: null,
  1730. position: 'absolute',
  1731. left: '50%',
  1732. top: '50%',
  1733. padding: 0,
  1734. margin: 0,
  1735. transform: {
  1736. prefix: true,
  1737. value: 'translate(-50%, -50%)'
  1738. }
  1739. },
  1740. autoStyleContainer: true,
  1741. alignToBottom: true,
  1742. value: null,
  1743. className: 'progressbar-text'
  1744. },
  1745. svgStyle: {
  1746. display: 'block',
  1747. width: '100%'
  1748. },
  1749. warnings: false
  1750. }, opts, true); // Use recursive extend
  1751. // If user specifies e.g. svgStyle or text style, the whole object
  1752. // should replace the defaults to make working with styles easier
  1753. if (utils.isObject(opts) && opts.svgStyle !== undefined) {
  1754. this._opts.svgStyle = opts.svgStyle;
  1755. }
  1756. if (utils.isObject(opts) && utils.isObject(opts.text) && opts.text.style !== undefined) {
  1757. this._opts.text.style = opts.text.style;
  1758. }
  1759. var svgView = this._createSvgView(this._opts);
  1760. var element;
  1761. if (utils.isString(container)) {
  1762. element = document.querySelector(container);
  1763. } else {
  1764. element = container;
  1765. }
  1766. if (!element) {
  1767. throw new Error('Container does not exist: ' + container);
  1768. }
  1769. this._container = element;
  1770. this._container.appendChild(svgView.svg);
  1771. if (this._opts.warnings) {
  1772. this._warnContainerAspectRatio(this._container);
  1773. }
  1774. if (this._opts.svgStyle) {
  1775. utils.setStyles(svgView.svg, this._opts.svgStyle);
  1776. }
  1777. // Expose public attributes before Path initialization
  1778. this.svg = svgView.svg;
  1779. this.path = svgView.path;
  1780. this.trail = svgView.trail;
  1781. this.text = null;
  1782. var newOpts = utils.extend({
  1783. attachment: undefined,
  1784. shape: this
  1785. }, this._opts);
  1786. this._progressPath = new Path(svgView.path, newOpts);
  1787. if (utils.isObject(this._opts.text) && this._opts.text.value !== null) {
  1788. this.setText(this._opts.text.value);
  1789. }
  1790. };
  1791. Shape.prototype.animate = function animate(progress, opts, cb) {
  1792. if (this._progressPath === null) {
  1793. throw new Error(DESTROYED_ERROR);
  1794. }
  1795. this._progressPath.animate(progress, opts, cb);
  1796. };
  1797. Shape.prototype.stop = function stop() {
  1798. if (this._progressPath === null) {
  1799. throw new Error(DESTROYED_ERROR);
  1800. }
  1801. // Don't crash if stop is called inside step function
  1802. if (this._progressPath === undefined) {
  1803. return;
  1804. }
  1805. this._progressPath.stop();
  1806. };
  1807. Shape.prototype.destroy = function destroy() {
  1808. if (this._progressPath === null) {
  1809. throw new Error(DESTROYED_ERROR);
  1810. }
  1811. this.stop();
  1812. this.svg.parentNode.removeChild(this.svg);
  1813. this.svg = null;
  1814. this.path = null;
  1815. this.trail = null;
  1816. this._progressPath = null;
  1817. if (this.text !== null) {
  1818. this.text.parentNode.removeChild(this.text);
  1819. this.text = null;
  1820. }
  1821. };
  1822. Shape.prototype.set = function set(progress) {
  1823. if (this._progressPath === null) {
  1824. throw new Error(DESTROYED_ERROR);
  1825. }
  1826. this._progressPath.set(progress);
  1827. };
  1828. Shape.prototype.value = function value() {
  1829. if (this._progressPath === null) {
  1830. throw new Error(DESTROYED_ERROR);
  1831. }
  1832. if (this._progressPath === undefined) {
  1833. return 0;
  1834. }
  1835. return this._progressPath.value();
  1836. };
  1837. Shape.prototype.setText = function setText(newText) {
  1838. if (this._progressPath === null) {
  1839. throw new Error(DESTROYED_ERROR);
  1840. }
  1841. if (this.text === null) {
  1842. // Create new text node
  1843. this.text = this._createTextContainer(this._opts, this._container);
  1844. this._container.appendChild(this.text);
  1845. }
  1846. // Remove previous text and add new
  1847. if (utils.isObject(newText)) {
  1848. utils.removeChildren(this.text);
  1849. this.text.appendChild(newText);
  1850. } else {
  1851. this.text.innerHTML = newText;
  1852. }
  1853. };
  1854. Shape.prototype._createSvgView = function _createSvgView(opts) {
  1855. var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  1856. this._initializeSvg(svg, opts);
  1857. var trailPath = null;
  1858. // Each option listed in the if condition are 'triggers' for creating
  1859. // the trail path
  1860. if (opts.trailColor || opts.trailWidth) {
  1861. trailPath = this._createTrail(opts);
  1862. svg.appendChild(trailPath);
  1863. }
  1864. var path = this._createPath(opts);
  1865. svg.appendChild(path);
  1866. return {
  1867. svg: svg,
  1868. path: path,
  1869. trail: trailPath
  1870. };
  1871. };
  1872. Shape.prototype._initializeSvg = function _initializeSvg(svg, opts) {
  1873. svg.setAttribute('viewBox', '0 0 100 100');
  1874. };
  1875. Shape.prototype._createPath = function _createPath(opts) {
  1876. var pathString = this._pathString(opts);
  1877. return this._createPathElement(pathString, opts);
  1878. };
  1879. Shape.prototype._createTrail = function _createTrail(opts) {
  1880. // Create path string with original passed options
  1881. var pathString = this._trailString(opts);
  1882. // Prevent modifying original
  1883. var newOpts = utils.extend({}, opts);
  1884. // Defaults for parameters which modify trail path
  1885. if (!newOpts.trailColor) {
  1886. newOpts.trailColor = '#eee';
  1887. }
  1888. if (!newOpts.trailWidth) {
  1889. newOpts.trailWidth = newOpts.strokeWidth;
  1890. }
  1891. newOpts.color = newOpts.trailColor;
  1892. newOpts.strokeWidth = newOpts.trailWidth;
  1893. // When trail path is set, fill must be set for it instead of the
  1894. // actual path to prevent trail stroke from clipping
  1895. newOpts.fill = null;
  1896. return this._createPathElement(pathString, newOpts);
  1897. };
  1898. Shape.prototype._createPathElement = function _createPathElement(pathString, opts) {
  1899. var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  1900. path.setAttribute('d', pathString);
  1901. path.setAttribute('stroke', opts.color);
  1902. path.setAttribute('stroke-width', opts.strokeWidth);
  1903. if (opts.fill) {
  1904. path.setAttribute('fill', opts.fill);
  1905. } else {
  1906. path.setAttribute('fill-opacity', '0');
  1907. }
  1908. return path;
  1909. };
  1910. Shape.prototype._createTextContainer = function _createTextContainer(opts, container) {
  1911. var textContainer = document.createElement('div');
  1912. textContainer.className = opts.text.className;
  1913. var textStyle = opts.text.style;
  1914. if (textStyle) {
  1915. if (opts.text.autoStyleContainer) {
  1916. container.style.position = 'relative';
  1917. }
  1918. utils.setStyles(textContainer, textStyle);
  1919. // Default text color to progress bar's color
  1920. if (!textStyle.color) {
  1921. textContainer.style.color = opts.color;
  1922. }
  1923. }
  1924. this._initializeTextContainer(opts, container, textContainer);
  1925. return textContainer;
  1926. };
  1927. // Give custom shapes possibility to modify text element
  1928. Shape.prototype._initializeTextContainer = function(opts, container, element) {
  1929. // By default, no-op
  1930. // Custom shapes should respect API options, such as text.style
  1931. };
  1932. Shape.prototype._pathString = function _pathString(opts) {
  1933. throw new Error('Override this function for each progress bar');
  1934. };
  1935. Shape.prototype._trailString = function _trailString(opts) {
  1936. throw new Error('Override this function for each progress bar');
  1937. };
  1938. Shape.prototype._warnContainerAspectRatio = function _warnContainerAspectRatio(container) {
  1939. if (!this.containerAspectRatio) {
  1940. return;
  1941. }
  1942. var computedStyle = window.getComputedStyle(container, null);
  1943. var width = parseFloat(computedStyle.getPropertyValue('width'), 10);
  1944. var height = parseFloat(computedStyle.getPropertyValue('height'), 10);
  1945. if (!utils.floatEquals(this.containerAspectRatio, width / height)) {
  1946. console.warn(
  1947. 'Incorrect aspect ratio of container',
  1948. '#' + container.id,
  1949. 'detected:',
  1950. computedStyle.getPropertyValue('width') + '(width)',
  1951. '/',
  1952. computedStyle.getPropertyValue('height') + '(height)',
  1953. '=',
  1954. width / height
  1955. );
  1956. console.warn(
  1957. 'Aspect ratio of should be',
  1958. this.containerAspectRatio
  1959. );
  1960. }
  1961. };
  1962. module.exports = Shape;
  1963. },{"./path":5,"./utils":8}],8:[function(require,module,exports){
  1964. // Utility functions
  1965. var PREFIXES = 'Webkit Moz O ms'.split(' ');
  1966. var FLOAT_COMPARISON_EPSILON = 0.001;
  1967. // Copy all attributes from source object to destination object.
  1968. // destination object is mutated.
  1969. function extend(destination, source, recursive) {
  1970. destination = destination || {};
  1971. source = source || {};
  1972. recursive = recursive || false;
  1973. for (var attrName in source) {
  1974. if (source.hasOwnProperty(attrName)) {
  1975. var destVal = destination[attrName];
  1976. var sourceVal = source[attrName];
  1977. if (recursive && isObject(destVal) && isObject(sourceVal)) {
  1978. destination[attrName] = extend(destVal, sourceVal, recursive);
  1979. } else {
  1980. destination[attrName] = sourceVal;
  1981. }
  1982. }
  1983. }
  1984. return destination;
  1985. }
  1986. // Renders templates with given variables. Variables must be surrounded with
  1987. // braces without any spaces, e.g. {variable}
  1988. // All instances of variable placeholders will be replaced with given content
  1989. // Example:
  1990. // render('Hello, {message}!', {message: 'world'})
  1991. function render(template, vars) {
  1992. var rendered = template;
  1993. for (var key in vars) {
  1994. if (vars.hasOwnProperty(key)) {
  1995. var val = vars[key];
  1996. var regExpString = '\\{' + key + '\\}';
  1997. var regExp = new RegExp(regExpString, 'g');
  1998. rendered = rendered.replace(regExp, val);
  1999. }
  2000. }
  2001. return rendered;
  2002. }
  2003. function setStyle(element, style, value) {
  2004. var elStyle = element.style; // cache for performance
  2005. for (var i = 0; i < PREFIXES.length; ++i) {
  2006. var prefix = PREFIXES[i];
  2007. elStyle[prefix + capitalize(style)] = value;
  2008. }
  2009. elStyle[style] = value;
  2010. }
  2011. function setStyles(element, styles) {
  2012. forEachObject(styles, function(styleValue, styleName) {
  2013. // Allow disabling some individual styles by setting them
  2014. // to null or undefined
  2015. if (styleValue === null || styleValue === undefined) {
  2016. return;
  2017. }
  2018. // If style's value is {prefix: true, value: '50%'},
  2019. // Set also browser prefixed styles
  2020. if (isObject(styleValue) && styleValue.prefix === true) {
  2021. setStyle(element, styleName, styleValue.value);
  2022. } else {
  2023. element.style[styleName] = styleValue;
  2024. }
  2025. });
  2026. }
  2027. function capitalize(text) {
  2028. return text.charAt(0).toUpperCase() + text.slice(1);
  2029. }
  2030. function isString(obj) {
  2031. return typeof obj === 'string' || obj instanceof String;
  2032. }
  2033. function isFunction(obj) {
  2034. return typeof obj === 'function';
  2035. }
  2036. function isArray(obj) {
  2037. return Object.prototype.toString.call(obj) === '[object Array]';
  2038. }
  2039. // Returns true if `obj` is object as in {a: 1, b: 2}, not if it's function or
  2040. // array
  2041. function isObject(obj) {
  2042. if (isArray(obj)) {
  2043. return false;
  2044. }
  2045. var type = typeof obj;
  2046. return type === 'object' && !!obj;
  2047. }
  2048. function forEachObject(object, callback) {
  2049. for (var key in object) {
  2050. if (object.hasOwnProperty(key)) {
  2051. var val = object[key];
  2052. callback(val, key);
  2053. }
  2054. }
  2055. }
  2056. function floatEquals(a, b) {
  2057. return Math.abs(a - b) < FLOAT_COMPARISON_EPSILON;
  2058. }
  2059. // https://coderwall.com/p/nygghw/don-t-use-innerhtml-to-empty-dom-elements
  2060. function removeChildren(el) {
  2061. while (el.firstChild) {
  2062. el.removeChild(el.firstChild);
  2063. }
  2064. }
  2065. module.exports = {
  2066. extend: extend,
  2067. render: render,
  2068. setStyle: setStyle,
  2069. setStyles: setStyles,
  2070. capitalize: capitalize,
  2071. isString: isString,
  2072. isFunction: isFunction,
  2073. isObject: isObject,
  2074. forEachObject: forEachObject,
  2075. floatEquals: floatEquals,
  2076. removeChildren: removeChildren
  2077. };
  2078. },{}]},{},[4])(4)
  2079. });