PageRenderTime 143ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 2ms

/libs/amazeui/1.0.1/js/amazeui.basic.js

https://gitlab.com/mba811/static
JavaScript | 10824 lines | 9909 code | 38 blank | 877 comment | 1030 complexity | b3bb59741c14fe8b70cd7c44a332a35f MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. /*! Amaze UI v1.0.1 ~ basic | by Amaze UI Team | (c) 2014 AllMobilize, Inc. | Licensed under MIT | 2014-11-07T07:11:14 UTC */
  2. /*! Sea.js 2.2.1 | seajs.org/LICENSE.md */
  3. !function(a,b){function c(a){return function(b){return{}.toString.call(b)=="[object "+a+"]"}}function d(){return A++}function e(a){return a.match(D)[0]}function f(a){for(a=a.replace(E,"/");a.match(F);)a=a.replace(F,"/");return a=a.replace(G,"$1/")}function g(a){var b=a.length-1,c=a.charAt(b);return"#"===c?a.substring(0,b):".js"===a.substring(b-2)||a.indexOf("?")>0||".css"===a.substring(b-3)||"/"===c?a:a+".js"}function h(a){var b=v.alias;return b&&x(b[a])?b[a]:a}function i(a){var b=v.paths,c;return b&&(c=a.match(H))&&x(b[c[1]])&&(a=b[c[1]]+c[2]),a}function j(a){var b=v.vars;return b&&a.indexOf("{")>-1&&(a=a.replace(I,function(a,c){return x(b[c])?b[c]:a})),a}function k(a){var b=v.map,c=a;if(b)for(var d=0,e=b.length;e>d;d++){var f=b[d];if(c=z(f)?f(a)||a:a.replace(f[0],f[1]),c!==a)break}return c}function l(a,b){var c,d=a.charAt(0);if(J.test(a))c=a;else if("."===d)c=f((b?e(b):v.cwd)+a);else if("/"===d){var g=v.cwd.match(K);c=g?g[0]+a.substring(1):a}else c=v.base+a;return 0===c.indexOf("//")&&(c=location.protocol+c),c}function m(a,b){if(!a)return"";a=h(a),a=i(a),a=j(a),a=g(a);var c=l(a,b);return c=k(c)}function n(a){return a.hasAttribute?a.src:a.getAttribute("src",4)}function o(a,b,c){var d=S.test(a),e=L.createElement(d?"link":"script");if(c){var f=z(c)?c(a):c;f&&(e.charset=f)}p(e,b,d,a),d?(e.rel="stylesheet",e.href=a):(e.async=!0,e.src=a),T=e,R?Q.insertBefore(e,R):Q.appendChild(e),T=null}function p(a,c,d,e){function f(){a.onload=a.onerror=a.onreadystatechange=null,d||v.debug||Q.removeChild(a),a=null,c()}var g="onload"in a;return!d||!V&&g?(g?(a.onload=f,a.onerror=function(){C("error",{uri:e,node:a}),f()}):a.onreadystatechange=function(){/loaded|complete/.test(a.readyState)&&f()},b):(setTimeout(function(){q(a,c)},1),b)}function q(a,b){var c=a.sheet,d;if(V)c&&(d=!0);else if(c)try{c.cssRules&&(d=!0)}catch(e){"NS_ERROR_DOM_SECURITY_ERR"===e.name&&(d=!0)}setTimeout(function(){d?b():q(a,b)},20)}function r(){if(T)return T;if(U&&"interactive"===U.readyState)return U;for(var a=Q.getElementsByTagName("script"),b=a.length-1;b>=0;b--){var c=a[b];if("interactive"===c.readyState)return U=c}}function s(a){var b=[];return a.replace(X,"").replace(W,function(a,c,d){d&&b.push(d)}),b}function t(a,b){this.uri=a,this.dependencies=b||[],this.exports=null,this.status=0,this._waitings={},this._remain=0}if(!a.seajs){var u=a.seajs={version:"2.2.1"},v=u.data={},w=c("Object"),x=c("String"),y=Array.isArray||c("Array"),z=c("Function"),A=0,B=v.events={};u.on=function(a,b){var c=B[a]||(B[a]=[]);return c.push(b),u},u.off=function(a,b){if(!a&&!b)return B=v.events={},u;var c=B[a];if(c)if(b)for(var d=c.length-1;d>=0;d--)c[d]===b&&c.splice(d,1);else delete B[a];return u};var C=u.emit=function(a,b){var c=B[a],d;if(c)for(c=c.slice();d=c.shift();)d(b);return u},D=/[^?#]*\//,E=/\/\.\//g,F=/\/[^/]+\/\.\.\//,G=/([^:/])\/\//g,H=/^([^/:]+)(\/.+)$/,I=/{([^{]+)}/g,J=/^\/\/.|:\//,K=/^.*?\/\/.*?\//,L=document,M=e(L.URL),N=L.scripts,O=L.getElementById("seajsnode")||N[N.length-1],P=e(n(O)||M);u.resolve=m;var Q=L.head||L.getElementsByTagName("head")[0]||L.documentElement,R=Q.getElementsByTagName("base")[0],S=/\.css(?:\?|$)/i,T,U,V=+navigator.userAgent.replace(/.*(?:AppleWebKit|AndroidWebKit)\/(\d+).*/,"$1")<536;u.request=o;var W=/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\/\*[\S\s]*?\*\/|\/(?:\\\/|[^\/\r\n])+\/(?=[^\/])|\/\/.*|\.\s*require|(?:^|[^$])\brequire\s*\(\s*(["'])(.+?)\1\s*\)/g,X=/\\\\/g,Y=u.cache={},Z,$={},_={},ab={},bb=t.STATUS={FETCHING:1,SAVED:2,LOADING:3,LOADED:4,EXECUTING:5,EXECUTED:6};t.prototype.resolve=function(){for(var a=this,b=a.dependencies,c=[],d=0,e=b.length;e>d;d++)c[d]=t.resolve(b[d],a.uri);return c},t.prototype.load=function(){var a=this;if(!(a.status>=bb.LOADING)){a.status=bb.LOADING;var c=a.resolve();C("load",c);for(var d=a._remain=c.length,e,f=0;d>f;f++)e=t.get(c[f]),e.status<bb.LOADED?e._waitings[a.uri]=(e._waitings[a.uri]||0)+1:a._remain--;if(0===a._remain)return a.onload(),b;var g={};for(f=0;d>f;f++)e=Y[c[f]],e.status<bb.FETCHING?e.fetch(g):e.status===bb.SAVED&&e.load();for(var h in g)g.hasOwnProperty(h)&&g[h]()}},t.prototype.onload=function(){var a=this;a.status=bb.LOADED,a.callback&&a.callback();var b=a._waitings,c,d;for(c in b)b.hasOwnProperty(c)&&(d=Y[c],d._remain-=b[c],0===d._remain&&d.onload());delete a._waitings,delete a._remain},t.prototype.fetch=function(a){function c(){u.request(g.requestUri,g.onRequest,g.charset)}function d(){delete $[h],_[h]=!0,Z&&(t.save(f,Z),Z=null);var a,b=ab[h];for(delete ab[h];a=b.shift();)a.load()}var e=this,f=e.uri;e.status=bb.FETCHING;var g={uri:f};C("fetch",g);var h=g.requestUri||f;return!h||_[h]?(e.load(),b):$[h]?(ab[h].push(e),b):($[h]=!0,ab[h]=[e],C("request",g={uri:f,requestUri:h,onRequest:d,charset:v.charset}),g.requested||(a?a[g.requestUri]=c:c()),b)},t.prototype.exec=function(){function a(b){return t.get(a.resolve(b)).exec()}var c=this;if(c.status>=bb.EXECUTING)return c.exports;c.status=bb.EXECUTING;var e=c.uri;a.resolve=function(a){return t.resolve(a,e)},a.async=function(b,c){return t.use(b,c,e+"_async_"+d()),a};var f=c.factory,g=z(f)?f(a,c.exports={},c):f;return g===b&&(g=c.exports),delete c.factory,c.exports=g,c.status=bb.EXECUTED,C("exec",c),g},t.resolve=function(a,b){var c={id:a,refUri:b};return C("resolve",c),c.uri||u.resolve(c.id,b)},t.define=function(a,c,d){var e=arguments.length;1===e?(d=a,a=b):2===e&&(d=c,y(a)?(c=a,a=b):c=b),!y(c)&&z(d)&&(c=s(""+d));var f={id:a,uri:t.resolve(a),deps:c,factory:d};if(!f.uri&&L.attachEvent){var g=r();g&&(f.uri=g.src)}C("define",f),f.uri?t.save(f.uri,f):Z=f},t.save=function(a,b){var c=t.get(a);c.status<bb.SAVED&&(c.id=b.id||a,c.dependencies=b.deps||[],c.factory=b.factory,c.status=bb.SAVED)},t.get=function(a,b){return Y[a]||(Y[a]=new t(a,b))},t.use=function(b,c,d){var e=t.get(d,y(b)?b:[b]);e.callback=function(){for(var b=[],d=e.resolve(),f=0,g=d.length;g>f;f++)b[f]=Y[d[f]].exec();c&&c.apply(a,b),delete e.callback},e.load()},t.preload=function(a){var b=v.preload,c=b.length;c?t.use(b,function(){b.splice(0,c),t.preload(a)},v.cwd+"_preload_"+d()):a()},u.use=function(a,b){return t.preload(function(){t.use(a,b,v.cwd+"_use_"+d())}),u},t.define.cmd={},a.define=t.define,u.Module=t,v.fetchedList=_,v.cid=d,u.require=function(a){var b=t.get(t.resolve(a));return b.status<bb.EXECUTING&&(b.onload(),b.exec()),b.exports};var cb=/^(.+?\/)(\?\?)?(seajs\/)+/;v.base=(P.match(cb)||["",P])[1],v.dir=P,v.cwd=M,v.charset="utf-8",v.preload=function(){var a=[],b=location.search.replace(/(seajs-\w+)(&|$)/g,"$1=1$2");return b+=" "+L.cookie,b.replace(/(seajs-\w+)=1/g,function(b,c){a.push(c)}),a}(),u.config=function(a){for(var b in a){var c=a[b],d=v[b];if(d&&w(d))for(var e in c)d[e]=c[e];else y(d)?c=d.concat(c):"base"===b&&("/"!==c.slice(-1)&&(c+="/"),c=l(c)),v[b]=c}return C("config",a),u}}}(this);
  4. define("core", [ "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5. "use strict";
  6. // Zepto animate extend
  7. require("zepto.extend.fx");
  8. // Zepto data extend
  9. require("zepto.extend.data");
  10. // Zeptzo selector extend
  11. require("zepto.extend.selector");
  12. /* jshint -W040 */
  13. var $ = window.Zepto;
  14. var UI = $.AMUI || {};
  15. var $win = $(window);
  16. var doc = window.document;
  17. var FastClick = require("util.fastclick");
  18. var $html = $("html");
  19. UI.support = {};
  20. UI.support.transition = function() {
  21. var transitionEnd = function() {
  22. // https://developer.mozilla.org/en-US/docs/Web/Events/transitionend#Browser_compatibility
  23. var element = doc.body || doc.documentElement;
  24. var transEndEventNames = {
  25. WebkitTransition: "webkitTransitionEnd",
  26. MozTransition: "transitionend",
  27. OTransition: "oTransitionEnd otransitionend",
  28. transition: "transitionend"
  29. };
  30. var name;
  31. for (name in transEndEventNames) {
  32. if (element.style[name] !== undefined) {
  33. return transEndEventNames[name];
  34. }
  35. }
  36. }();
  37. return transitionEnd && {
  38. end: transitionEnd
  39. };
  40. }();
  41. UI.support.animation = function() {
  42. var animationEnd = function() {
  43. var element = doc.body || doc.documentElement;
  44. var animEndEventNames = {
  45. WebkitAnimation: "webkitAnimationEnd",
  46. MozAnimation: "animationend",
  47. OAnimation: "oAnimationEnd oanimationend",
  48. animation: "animationend"
  49. };
  50. var name;
  51. for (name in animEndEventNames) {
  52. if (element.style[name] !== undefined) {
  53. return animEndEventNames[name];
  54. }
  55. }
  56. }();
  57. return animationEnd && {
  58. end: animationEnd
  59. };
  60. }();
  61. UI.support.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function(callback) {
  62. window.setTimeout(callback, 1e3 / 60);
  63. };
  64. /* jshint -W069 */
  65. UI.support.touch = "ontouchstart" in window && navigator.userAgent.toLowerCase().match(/mobile|tablet/) || window.DocumentTouch && document instanceof window.DocumentTouch || window.navigator["msPointerEnabled"] && window.navigator["msMaxTouchPoints"] > 0 || //IE 10
  66. window.navigator["pointerEnabled"] && window.navigator["maxTouchPoints"] > 0 || //IE >=11
  67. false;
  68. // https://developer.mozilla.org/zh-CN/docs/DOM/MutationObserver
  69. UI.support.mutationobserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver || null;
  70. UI.utils = {};
  71. /**
  72. * Debounce function
  73. * @param {function} func Function to be debounced
  74. * @param {number} wait Function execution threshold in milliseconds
  75. * @param {bool} immediate Whether the function should be called at
  76. * the beginning of the delay instead of the
  77. * end. Default is false.
  78. * @desc Executes a function when it stops being invoked for n seconds
  79. * @via _.debounce() http://underscorejs.org
  80. */
  81. UI.utils.debounce = function(func, wait, immediate) {
  82. var timeout;
  83. return function() {
  84. var context = this;
  85. var args = arguments;
  86. var later = function() {
  87. timeout = null;
  88. if (!immediate) {
  89. func.apply(context, args);
  90. }
  91. };
  92. var callNow = immediate && !timeout;
  93. clearTimeout(timeout);
  94. timeout = setTimeout(later, wait);
  95. if (callNow) {
  96. func.apply(context, args);
  97. }
  98. };
  99. };
  100. UI.utils.isInView = function(element, options) {
  101. var $element = $(element);
  102. var visible = !!($element.width() || $element.height()) && $element.css("display") !== "none";
  103. if (!visible) {
  104. return false;
  105. }
  106. var windowLeft = $win.scrollLeft();
  107. var windowTop = $win.scrollTop();
  108. var offset = $element.offset();
  109. var left = offset.left;
  110. var top = offset.top;
  111. options = $.extend({
  112. topOffset: 0,
  113. leftOffset: 0
  114. }, options);
  115. return top + $element.height() >= windowTop && top - options.topOffset <= windowTop + $win.height() && left + $element.width() >= windowLeft && left - options.leftOffset <= windowLeft + $win.width();
  116. };
  117. /* jshint -W054 */
  118. UI.utils.parseOptions = UI.utils.options = function(string) {
  119. if ($.isPlainObject(string)) {
  120. return string;
  121. }
  122. var start = string ? string.indexOf("{") : -1;
  123. var options = {};
  124. if (start != -1) {
  125. try {
  126. options = new Function("", "var json = " + string.substr(start) + "; return JSON.parse(JSON.stringify(json));")();
  127. } catch (e) {}
  128. }
  129. return options;
  130. };
  131. /* jshint +W054 */
  132. UI.utils.generateGUID = function(namespace) {
  133. var uid = namespace + "-" || "am-";
  134. do {
  135. uid += Math.random().toString(36).substring(2, 7);
  136. } while (document.getElementById(uid));
  137. return uid;
  138. };
  139. // http://blog.alexmaccaw.com/css-transitions
  140. $.fn.emulateTransitionEnd = function(duration) {
  141. var called = false;
  142. var $el = this;
  143. $(this).one(UI.support.transition.end, function() {
  144. called = true;
  145. });
  146. var callback = function() {
  147. if (!called) {
  148. $($el).trigger(UI.support.transition.end);
  149. }
  150. $el.transitionEndTimmer = undefined;
  151. };
  152. this.transitionEndTimmer = setTimeout(callback, duration);
  153. return this;
  154. };
  155. $.fn.redraw = function() {
  156. $(this).each(function() {
  157. /* jshint unused:false */
  158. var redraw = this.offsetHeight;
  159. });
  160. return this;
  161. };
  162. /* jshint unused:true */
  163. $.fn.transitionEnd = function(callback) {
  164. var endEvent = UI.support.transition.end;
  165. var dom = this;
  166. function fireCallBack(e) {
  167. callback.call(this, e);
  168. endEvent && dom.off(endEvent, fireCallBack);
  169. }
  170. if (callback && endEvent) {
  171. dom.on(endEvent, fireCallBack);
  172. }
  173. return this;
  174. };
  175. $.fn.removeClassRegEx = function() {
  176. return this.each(function(regex) {
  177. var classes = $(this).attr("class");
  178. if (!classes || !regex) {
  179. return false;
  180. }
  181. var classArray = [];
  182. classes = classes.split(" ");
  183. for (var i = 0, len = classes.length; i < len; i++) {
  184. if (!classes[i].match(regex)) {
  185. classArray.push(classes[i]);
  186. }
  187. }
  188. $(this).attr("class", classArray.join(" "));
  189. });
  190. };
  191. //
  192. $.fn.alterClass = function(removals, additions) {
  193. var self = this;
  194. if (removals.indexOf("*") === -1) {
  195. // Use native jQuery methods if there is no wildcard matching
  196. self.removeClass(removals);
  197. return !additions ? self : self.addClass(additions);
  198. }
  199. var classPattern = new RegExp("\\s" + removals.replace(/\*/g, "[A-Za-z0-9-_]+").split(" ").join("\\s|\\s") + "\\s", "g");
  200. self.each(function(i, it) {
  201. var cn = " " + it.className + " ";
  202. while (classPattern.test(cn)) {
  203. cn = cn.replace(classPattern, " ");
  204. }
  205. it.className = $.trim(cn);
  206. });
  207. return !additions ? self : self.addClass(additions);
  208. };
  209. $.fn.getHeight = function() {
  210. var $ele = $(this);
  211. var height = "auto";
  212. if ($ele.is(":visible")) {
  213. height = $ele.height();
  214. } else {
  215. var tmp = {
  216. position: $ele.css("position"),
  217. visibility: $ele.css("visibility"),
  218. display: $ele.css("display")
  219. };
  220. height = $ele.css({
  221. position: "absolute",
  222. visibility: "hidden",
  223. display: "block"
  224. }).height();
  225. $ele.css(tmp);
  226. }
  227. return height;
  228. };
  229. $.fn.getSize = function() {
  230. var $el = $(this);
  231. if ($el.css("display") !== "none") {
  232. return {
  233. width: $el.width(),
  234. height: $el.height()
  235. };
  236. }
  237. var old = {
  238. position: $el.css("position"),
  239. visibility: $el.css("visibility"),
  240. display: $el.css("display")
  241. };
  242. var tmpStyle = {
  243. display: "block",
  244. position: "absolute",
  245. visibility: "hidden"
  246. };
  247. var width;
  248. var height;
  249. $el.css(tmpStyle);
  250. width = $el.width();
  251. height = $el.height();
  252. $el.css(old);
  253. return {
  254. width: width,
  255. height: height
  256. };
  257. };
  258. // adding :visible and :hidden to zepto
  259. // https://github.com/jquery/jquery/blob/73e120116ce13b992d5229b3e10fcc19f9505a15/src/css/hiddenVisibleSelectors.js
  260. var _is = $.fn.is;
  261. var _filter = $.fn.filter;
  262. function visible(elem) {
  263. elem = $(elem);
  264. return !!(elem.width() || elem.height()) && elem.css("display") !== "none";
  265. }
  266. $.fn.is = function(sel) {
  267. if (sel === ":visible") {
  268. return visible(this);
  269. }
  270. if (sel === ":hidden") {
  271. return !visible(this);
  272. }
  273. return _is.call(this, sel);
  274. };
  275. $.fn.filter = function(sel) {
  276. if (sel === ":visible") {
  277. return $([].filter.call(this, visible));
  278. }
  279. if (sel === ":hidden") {
  280. return $([].filter.call(this, function(elem) {
  281. return !visible(elem);
  282. }));
  283. }
  284. return _filter.call(this, sel);
  285. };
  286. // handle multiple browsers for requestAnimationFrame()
  287. // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
  288. // https://github.com/gnarf/jquery-requestAnimationFrame
  289. UI.utils.rAF = function() {
  290. return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || // if all else fails, use setTimeout
  291. function(callback) {
  292. return window.setTimeout(callback, 1e3 / 60);
  293. };
  294. }();
  295. // handle multiple browsers for cancelAnimationFrame()
  296. UI.utils.cancelAF = function() {
  297. return window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.oCancelAnimationFrame || function(id) {
  298. window.clearTimeout(id);
  299. };
  300. }();
  301. // via http://davidwalsh.name/detect-scrollbar-width
  302. UI.utils.measureScrollbar = function() {
  303. if (document.body.clientWidth >= window.innerWidth) {
  304. return 0;
  305. }
  306. // if ($html.width() >= window.innerWidth) return;
  307. // var scrollbarWidth = window.innerWidth - $html.width();
  308. var $measure = $("<div " + 'style="width: 100px;height: 100px;overflow: scroll;' + 'position: absolute;top: -9999px;"></div>');
  309. $(document.body).append($measure);
  310. var scrollbarWidth = $measure[0].offsetWidth - $measure[0].clientWidth;
  311. $measure.remove();
  312. return scrollbarWidth;
  313. };
  314. UI.utils.imageLoader = function($image, callback) {
  315. function loaded() {
  316. callback($image[0]);
  317. }
  318. function bindLoad() {
  319. this.one("load", loaded);
  320. if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
  321. var src = this.attr("src"), param = src.match(/\?/) ? "&" : "?";
  322. param += "random=" + new Date().getTime();
  323. this.attr("src", src + param);
  324. }
  325. }
  326. if (!$image.attr("src")) {
  327. loaded();
  328. return;
  329. }
  330. if ($image[0].complete || $image[0].readyState === 4) {
  331. loaded();
  332. } else {
  333. bindLoad.call($image);
  334. }
  335. };
  336. /**
  337. * https://github.com/cho45/micro-template.js
  338. * (c) cho45 http://cho45.github.com/mit-license
  339. */
  340. /* jshint -W109 */
  341. UI.template = function(id, data) {
  342. var me = UI.template;
  343. if (!me.cache[id]) {
  344. me.cache[id] = function() {
  345. var name = id;
  346. var string = /^[\w\-]+$/.test(id) ? me.get(id) : (name = "template(string)", id);
  347. // no warnings
  348. var line = 1;
  349. var body = ("try { " + (me.variable ? "var " + me.variable + " = this.stash;" : "with (this.stash) { ") + "this.ret += '" + string.replace(/<%/g, "").replace(/%>/g, "").replace(/'(?![^\x11\x13]+?\x13)/g, "\\x27").replace(/^\s*|\s*$/g, "").replace(/\n/g, function() {
  350. return "';\nthis.line = " + ++line + "; this.ret += '\\n";
  351. }).replace(/\x11-(.+?)\x13/g, "' + ($1) + '").replace(/\x11=(.+?)\x13/g, "' + this.escapeHTML($1) + '").replace(/\x11(.+?)\x13/g, "'; $1; this.ret += '") + "'; " + (me.variable ? "" : "}") + "return this.ret;" + "} catch (e) { throw 'TemplateError: ' + e + ' (on " + name + "' + ' line ' + this.line + ')'; } " + "//@ sourceURL=" + name + "\n").replace(/this\.ret \+= '';/g, "");
  352. /* jshint -W054 */
  353. var func = new Function(body);
  354. var map = {
  355. "&": "&amp;",
  356. "<": "&lt;",
  357. ">": "&gt;",
  358. '"': "&#x22;",
  359. "'": "&#x27;"
  360. };
  361. var escapeHTML = function(string) {
  362. return ("" + string).replace(/[&<>\'\"]/g, function(_) {
  363. return map[_];
  364. });
  365. };
  366. return function(stash) {
  367. return func.call(me.context = {
  368. escapeHTML: escapeHTML,
  369. line: 1,
  370. ret: "",
  371. stash: stash
  372. });
  373. };
  374. }();
  375. }
  376. return data ? me.cache[id](data) : me.cache[id];
  377. };
  378. /* jshint +W109 */
  379. /* jshint +W054 */
  380. UI.template.cache = {};
  381. UI.template.get = function(id) {
  382. if (id) {
  383. var element = document.getElementById(id);
  384. return element && element.innerHTML || "";
  385. }
  386. };
  387. // Attach FastClick on touch devices
  388. if (UI.support.touch) {
  389. $html.addClass("am-touch");
  390. $(function() {
  391. FastClick.attach(document.body);
  392. });
  393. }
  394. $(function() {
  395. var $body = $("body");
  396. // trigger DOM ready event
  397. $(document).trigger("domready:amui");
  398. $html.removeClass("no-js").addClass("js");
  399. UI.support.animation && $html.addClass("cssanimations");
  400. // iOS standalone mode
  401. if (window.navigator.standalone) {
  402. $html.addClass("am-standalone");
  403. }
  404. $(".am-topbar-fixed-top").length && $body.addClass("am-with-topbar-fixed-top");
  405. $(".am-topbar-fixed-bottom").length && $body.addClass("am-with-topbar-fixed-bottom");
  406. // Remove responsive classes in .am-layout
  407. var $layout = $(".am-layout");
  408. $layout.find('[class*="md-block-grid"]').alterClass("md-block-grid-*");
  409. $layout.find('[class*="lg-block-grid"]').alterClass("lg-block-grid");
  410. // widgets not in .am-layout
  411. $("[data-am-widget]").each(function() {
  412. var $widget = $(this);
  413. // console.log($widget.parents('.am-layout').length)
  414. if ($widget.parents(".am-layout").length === 0) {
  415. $widget.addClass("am-no-layout");
  416. }
  417. });
  418. });
  419. $.AMUI = UI;
  420. module.exports = UI;
  421. });
  422. define("util.fastclick", [], function(require, exports, module) {
  423. "use strict";
  424. var $ = window.Zepto;
  425. /**
  426. * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
  427. *
  428. * @version 1.0.3
  429. * @codingstandard ftlabs-jsv2
  430. * @copyright The Financial Times Limited [All Rights Reserved]
  431. * @license MIT License (see LICENSE.txt)
  432. */
  433. /*jslint browser:true, node:true*/
  434. /*global define, Event, Node*/
  435. /**
  436. * Instantiate fast-clicking listeners on the specified layer.
  437. *
  438. * @constructor
  439. * @param {Element} layer The layer to listen on
  440. * @param {Object} options The options to override the defaults
  441. */
  442. function FastClick(layer, options) {
  443. var oldOnClick;
  444. options = options || {};
  445. /**
  446. * Whether a click is currently being tracked.
  447. *
  448. * @type boolean
  449. */
  450. this.trackingClick = false;
  451. /**
  452. * Timestamp for when click tracking started.
  453. *
  454. * @type number
  455. */
  456. this.trackingClickStart = 0;
  457. /**
  458. * The element being tracked for a click.
  459. *
  460. * @type EventTarget
  461. */
  462. this.targetElement = null;
  463. /**
  464. * X-coordinate of touch start event.
  465. *
  466. * @type number
  467. */
  468. this.touchStartX = 0;
  469. /**
  470. * Y-coordinate of touch start event.
  471. *
  472. * @type number
  473. */
  474. this.touchStartY = 0;
  475. /**
  476. * ID of the last touch, retrieved from Touch.identifier.
  477. *
  478. * @type number
  479. */
  480. this.lastTouchIdentifier = 0;
  481. /**
  482. * Touchmove boundary, beyond which a click will be cancelled.
  483. *
  484. * @type number
  485. */
  486. this.touchBoundary = options.touchBoundary || 10;
  487. /**
  488. * The FastClick layer.
  489. *
  490. * @type Element
  491. */
  492. this.layer = layer;
  493. /**
  494. * The minimum time between tap(touchstart and touchend) events
  495. *
  496. * @type number
  497. */
  498. this.tapDelay = options.tapDelay || 200;
  499. if (FastClick.notNeeded(layer)) {
  500. return;
  501. }
  502. // Some old versions of Android don't have Function.prototype.bind
  503. function bind(method, context) {
  504. return function() {
  505. return method.apply(context, arguments);
  506. };
  507. }
  508. var methods = [ "onMouse", "onClick", "onTouchStart", "onTouchMove", "onTouchEnd", "onTouchCancel" ];
  509. var context = this;
  510. for (var i = 0, l = methods.length; i < l; i++) {
  511. context[methods[i]] = bind(context[methods[i]], context);
  512. }
  513. // Set up event handlers as required
  514. if (deviceIsAndroid) {
  515. layer.addEventListener("mouseover", this.onMouse, true);
  516. layer.addEventListener("mousedown", this.onMouse, true);
  517. layer.addEventListener("mouseup", this.onMouse, true);
  518. }
  519. layer.addEventListener("click", this.onClick, true);
  520. layer.addEventListener("touchstart", this.onTouchStart, false);
  521. layer.addEventListener("touchmove", this.onTouchMove, false);
  522. layer.addEventListener("touchend", this.onTouchEnd, false);
  523. layer.addEventListener("touchcancel", this.onTouchCancel, false);
  524. // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  525. // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
  526. // layer when they are cancelled.
  527. if (!Event.prototype.stopImmediatePropagation) {
  528. layer.removeEventListener = function(type, callback, capture) {
  529. var rmv = Node.prototype.removeEventListener;
  530. if (type === "click") {
  531. rmv.call(layer, type, callback.hijacked || callback, capture);
  532. } else {
  533. rmv.call(layer, type, callback, capture);
  534. }
  535. };
  536. layer.addEventListener = function(type, callback, capture) {
  537. var adv = Node.prototype.addEventListener;
  538. if (type === "click") {
  539. adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
  540. if (!event.propagationStopped) {
  541. callback(event);
  542. }
  543. }), capture);
  544. } else {
  545. adv.call(layer, type, callback, capture);
  546. }
  547. };
  548. }
  549. // If a handler is already declared in the element's onclick attribute, it will be fired before
  550. // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
  551. // adding it as listener.
  552. if (typeof layer.onclick === "function") {
  553. // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
  554. // - the old one won't work if passed to addEventListener directly.
  555. oldOnClick = layer.onclick;
  556. layer.addEventListener("click", function(event) {
  557. oldOnClick(event);
  558. }, false);
  559. layer.onclick = null;
  560. }
  561. }
  562. /**
  563. * Android requires exceptions.
  564. *
  565. * @type boolean
  566. */
  567. var deviceIsAndroid = navigator.userAgent.indexOf("Android") > 0;
  568. /**
  569. * iOS requires exceptions.
  570. *
  571. * @type boolean
  572. */
  573. var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
  574. /**
  575. * iOS 4 requires an exception for select elements.
  576. *
  577. * @type boolean
  578. */
  579. var deviceIsIOS4 = deviceIsIOS && /OS 4_\d(_\d)?/.test(navigator.userAgent);
  580. /**
  581. * iOS 6.0(+?) requires the target element to be manually derived
  582. *
  583. * @type boolean
  584. */
  585. var deviceIsIOSWithBadTarget = deviceIsIOS && /OS ([6-9]|\d{2})_\d/.test(navigator.userAgent);
  586. /**
  587. * BlackBerry requires exceptions.
  588. *
  589. * @type boolean
  590. */
  591. var deviceIsBlackBerry10 = navigator.userAgent.indexOf("BB10") > 0;
  592. /**
  593. * Determine whether a given element requires a native click.
  594. *
  595. * @param {EventTarget|Element} target Target DOM element
  596. * @returns {boolean} Returns true if the element needs a native click
  597. */
  598. FastClick.prototype.needsClick = function(target) {
  599. switch (target.nodeName.toLowerCase()) {
  600. // Don't send a synthetic click to disabled inputs (issue #62)
  601. case "button":
  602. case "select":
  603. case "textarea":
  604. if (target.disabled) {
  605. return true;
  606. }
  607. break;
  608. case "input":
  609. // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
  610. if (deviceIsIOS && target.type === "file" || target.disabled) {
  611. return true;
  612. }
  613. break;
  614. case "label":
  615. case "video":
  616. return true;
  617. }
  618. return /\bneedsclick\b/.test(target.className);
  619. };
  620. /**
  621. * Determine whether a given element requires a call to focus to simulate click into element.
  622. *
  623. * @param {EventTarget|Element} target Target DOM element
  624. * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
  625. */
  626. FastClick.prototype.needsFocus = function(target) {
  627. switch (target.nodeName.toLowerCase()) {
  628. case "textarea":
  629. return true;
  630. case "select":
  631. return !deviceIsAndroid;
  632. case "input":
  633. switch (target.type) {
  634. case "button":
  635. case "checkbox":
  636. case "file":
  637. case "image":
  638. case "radio":
  639. case "submit":
  640. return false;
  641. }
  642. // No point in attempting to focus disabled inputs
  643. return !target.disabled && !target.readOnly;
  644. default:
  645. return /\bneedsfocus\b/.test(target.className);
  646. }
  647. };
  648. /**
  649. * Send a click event to the specified element.
  650. *
  651. * @param {EventTarget|Element} targetElement
  652. * @param {Event} event
  653. */
  654. FastClick.prototype.sendClick = function(targetElement, event) {
  655. var clickEvent, touch;
  656. // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
  657. if (document.activeElement && document.activeElement !== targetElement) {
  658. document.activeElement.blur();
  659. }
  660. touch = event.changedTouches[0];
  661. // Synthesise a click event, with an extra attribute so it can be tracked
  662. clickEvent = document.createEvent("MouseEvents");
  663. clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
  664. clickEvent.forwardedTouchEvent = true;
  665. targetElement.dispatchEvent(clickEvent);
  666. };
  667. FastClick.prototype.determineEventType = function(targetElement) {
  668. //Issue #159: Android Chrome Select Box does not open with a synthetic click event
  669. if (deviceIsAndroid && targetElement.tagName.toLowerCase() === "select") {
  670. return "mousedown";
  671. }
  672. return "click";
  673. };
  674. /**
  675. * @param {EventTarget|Element} targetElement
  676. */
  677. FastClick.prototype.focus = function(targetElement) {
  678. var length;
  679. // Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
  680. if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf("date") !== 0 && targetElement.type !== "time") {
  681. length = targetElement.value.length;
  682. targetElement.setSelectionRange(length, length);
  683. } else {
  684. targetElement.focus();
  685. }
  686. };
  687. /**
  688. * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
  689. *
  690. * @param {EventTarget|Element} targetElement
  691. */
  692. FastClick.prototype.updateScrollParent = function(targetElement) {
  693. var scrollParent, parentElement;
  694. scrollParent = targetElement.fastClickScrollParent;
  695. // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
  696. // target element was moved to another parent.
  697. if (!scrollParent || !scrollParent.contains(targetElement)) {
  698. parentElement = targetElement;
  699. do {
  700. if (parentElement.scrollHeight > parentElement.offsetHeight) {
  701. scrollParent = parentElement;
  702. targetElement.fastClickScrollParent = parentElement;
  703. break;
  704. }
  705. parentElement = parentElement.parentElement;
  706. } while (parentElement);
  707. }
  708. // Always update the scroll top tracker if possible.
  709. if (scrollParent) {
  710. scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
  711. }
  712. };
  713. /**
  714. * @param {EventTarget} targetElement
  715. * @returns {Element|EventTarget}
  716. */
  717. FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
  718. // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
  719. if (eventTarget.nodeType === Node.TEXT_NODE) {
  720. return eventTarget.parentNode;
  721. }
  722. return eventTarget;
  723. };
  724. /**
  725. * On touch start, record the position and scroll offset.
  726. *
  727. * @param {Event} event
  728. * @returns {boolean}
  729. */
  730. FastClick.prototype.onTouchStart = function(event) {
  731. var targetElement, touch, selection;
  732. // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
  733. if (event.targetTouches.length > 1) {
  734. return true;
  735. }
  736. targetElement = this.getTargetElementFromEventTarget(event.target);
  737. touch = event.targetTouches[0];
  738. if (deviceIsIOS) {
  739. // Only trusted events will deselect text on iOS (issue #49)
  740. selection = window.getSelection();
  741. if (selection.rangeCount && !selection.isCollapsed) {
  742. return true;
  743. }
  744. if (!deviceIsIOS4) {
  745. // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
  746. // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
  747. // with the same identifier as the touch event that previously triggered the click that triggered the alert.
  748. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
  749. // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
  750. // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
  751. // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
  752. // random integers, it's safe to to continue if the identifier is 0 here.
  753. if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
  754. event.preventDefault();
  755. return false;
  756. }
  757. this.lastTouchIdentifier = touch.identifier;
  758. // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
  759. // 1) the user does a fling scroll on the scrollable layer
  760. // 2) the user stops the fling scroll with another tap
  761. // then the event.target of the last 'touchend' event will be the element that was under the user's finger
  762. // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
  763. // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
  764. this.updateScrollParent(targetElement);
  765. }
  766. }
  767. this.trackingClick = true;
  768. this.trackingClickStart = event.timeStamp;
  769. this.targetElement = targetElement;
  770. this.touchStartX = touch.pageX;
  771. this.touchStartY = touch.pageY;
  772. // Prevent phantom clicks on fast double-tap (issue #36)
  773. if (event.timeStamp - this.lastClickTime < this.tapDelay) {
  774. event.preventDefault();
  775. }
  776. return true;
  777. };
  778. /**
  779. * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
  780. *
  781. * @param {Event} event
  782. * @returns {boolean}
  783. */
  784. FastClick.prototype.touchHasMoved = function(event) {
  785. var touch = event.changedTouches[0], boundary = this.touchBoundary;
  786. if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
  787. return true;
  788. }
  789. return false;
  790. };
  791. /**
  792. * Update the last position.
  793. *
  794. * @param {Event} event
  795. * @returns {boolean}
  796. */
  797. FastClick.prototype.onTouchMove = function(event) {
  798. if (!this.trackingClick) {
  799. return true;
  800. }
  801. // If the touch has moved, cancel the click tracking
  802. if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
  803. this.trackingClick = false;
  804. this.targetElement = null;
  805. }
  806. return true;
  807. };
  808. /**
  809. * Attempt to find the labelled control for the given label element.
  810. *
  811. * @param {EventTarget|HTMLLabelElement} labelElement
  812. * @returns {Element|null}
  813. */
  814. FastClick.prototype.findControl = function(labelElement) {
  815. // Fast path for newer browsers supporting the HTML5 control attribute
  816. if (labelElement.control !== undefined) {
  817. return labelElement.control;
  818. }
  819. // All browsers under test that support touch events also support the HTML5 htmlFor attribute
  820. if (labelElement.htmlFor) {
  821. return document.getElementById(labelElement.htmlFor);
  822. }
  823. // If no for attribute exists, attempt to retrieve the first labellable descendant element
  824. // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
  825. return labelElement.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea");
  826. };
  827. /**
  828. * On touch end, determine whether to send a click event at once.
  829. *
  830. * @param {Event} event
  831. * @returns {boolean}
  832. */
  833. FastClick.prototype.onTouchEnd = function(event) {
  834. var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
  835. if (!this.trackingClick) {
  836. return true;
  837. }
  838. // Prevent phantom clicks on fast double-tap (issue #36)
  839. if (event.timeStamp - this.lastClickTime < this.tapDelay) {
  840. this.cancelNextClick = true;
  841. return true;
  842. }
  843. // Reset to prevent wrong click cancel on input (issue #156).
  844. this.cancelNextClick = false;
  845. this.lastClickTime = event.timeStamp;
  846. trackingClickStart = this.trackingClickStart;
  847. this.trackingClick = false;
  848. this.trackingClickStart = 0;
  849. // On some iOS devices, the targetElement supplied with the event is invalid if the layer
  850. // is performing a transition or scroll, and has to be re-detected manually. Note that
  851. // for this to function correctly, it must be called *after* the event target is checked!
  852. // See issue #57; also filed as rdar://13048589 .
  853. if (deviceIsIOSWithBadTarget) {
  854. touch = event.changedTouches[0];
  855. // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
  856. targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
  857. targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
  858. }
  859. targetTagName = targetElement.tagName.toLowerCase();
  860. if (targetTagName === "label") {
  861. forElement = this.findControl(targetElement);
  862. if (forElement) {
  863. this.focus(targetElement);
  864. if (deviceIsAndroid) {
  865. return false;
  866. }
  867. targetElement = forElement;
  868. }
  869. } else if (this.needsFocus(targetElement)) {
  870. // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
  871. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
  872. if (event.timeStamp - trackingClickStart > 100 || deviceIsIOS && window.top !== window && targetTagName === "input") {
  873. this.targetElement = null;
  874. return false;
  875. }
  876. this.focus(targetElement);
  877. this.sendClick(targetElement, event);
  878. // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
  879. // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
  880. if (!deviceIsIOS || targetTagName !== "select") {
  881. this.targetElement = null;
  882. event.preventDefault();
  883. }
  884. return false;
  885. }
  886. if (deviceIsIOS && !deviceIsIOS4) {
  887. // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
  888. // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
  889. scrollParent = targetElement.fastClickScrollParent;
  890. if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
  891. return true;
  892. }
  893. }
  894. // Prevent the actual click from going though - unless the target node is marked as requiring
  895. // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
  896. if (!this.needsClick(targetElement)) {
  897. event.preventDefault();
  898. this.sendClick(targetElement, event);
  899. }
  900. return false;
  901. };
  902. /**
  903. * On touch cancel, stop tracking the click.
  904. *
  905. * @returns {void}
  906. */
  907. FastClick.prototype.onTouchCancel = function() {
  908. this.trackingClick = false;
  909. this.targetElement = null;
  910. };
  911. /**
  912. * Determine mouse events which should be permitted.
  913. *
  914. * @param {Event} event
  915. * @returns {boolean}
  916. */
  917. FastClick.prototype.onMouse = function(event) {
  918. // If a target element was never set (because a touch event was never fired) allow the event
  919. if (!this.targetElement) {
  920. return true;
  921. }
  922. if (event.forwardedTouchEvent) {
  923. return true;
  924. }
  925. // Programmatically generated events targeting a specific element should be permitted
  926. if (!event.cancelable) {
  927. return true;
  928. }
  929. // Derive and check the target element to see whether the mouse event needs to be permitted;
  930. // unless explicitly enabled, prevent non-touch click events from triggering actions,
  931. // to prevent ghost/doubleclicks.
  932. if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
  933. // Prevent any user-added listeners declared on FastClick element from being fired.
  934. if (event.stopImmediatePropagation) {
  935. event.stopImmediatePropagation();
  936. } else {
  937. // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
  938. event.propagationStopped = true;
  939. }
  940. // Cancel the event
  941. event.stopPropagation();
  942. event.preventDefault();
  943. return false;
  944. }
  945. // If the mouse event is permitted, return true for the action to go through.
  946. return true;
  947. };
  948. /**
  949. * On actual clicks, determine whether this is a touch-generated click, a click action occurring
  950. * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
  951. * an actual click which should be permitted.
  952. *
  953. * @param {Event} event
  954. * @returns {boolean}
  955. */
  956. FastClick.prototype.onClick = function(event) {
  957. var permitted;
  958. // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
  959. if (this.trackingClick) {
  960. this.targetElement = null;
  961. this.trackingClick = false;
  962. return true;
  963. }
  964. // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
  965. if (event.target.type === "submit" && event.detail === 0) {
  966. return true;
  967. }
  968. permitted = this.onMouse(event);
  969. // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
  970. if (!permitted) {
  971. this.targetElement = null;
  972. }
  973. // If clicks are permitted, return true for the action to go through.
  974. return permitted;
  975. };
  976. /**
  977. * Remove all FastClick's event listeners.
  978. *
  979. * @returns {void}
  980. */
  981. FastClick.prototype.destroy = function() {
  982. var layer = this.layer;
  983. if (deviceIsAndroid) {
  984. layer.removeEventListener("mouseover", this.onMouse, true);
  985. layer.removeEventListener("mousedown", this.onMouse, true);
  986. layer.removeEventListener("mouseup", this.onMouse, true);
  987. }
  988. layer.removeEventListener("click", this.onClick, true);
  989. layer.removeEventListener("touchstart", this.onTouchStart, false);
  990. layer.removeEventListener("touchmove", this.onTouchMove, false);
  991. layer.removeEventListener("touchend", this.onTouchEnd, false);
  992. layer.removeEventListener("touchcancel", this.onTouchCancel, false);
  993. };
  994. /**
  995. * Check whether FastClick is needed.
  996. *
  997. * @param {Element} layer The layer to listen on
  998. */
  999. FastClick.notNeeded = function(layer) {
  1000. var metaViewport;
  1001. var chromeVersion;
  1002. var blackberryVersion;
  1003. // Devices that don't support touch don't need FastClick
  1004. if (typeof window.ontouchstart === "undefined") {
  1005. return true;
  1006. }
  1007. // Chrome version - zero for other browsers
  1008. chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [ , 0 ])[1];
  1009. if (chromeVersion) {
  1010. if (deviceIsAndroid) {
  1011. metaViewport = document.querySelector("meta[name=viewport]");
  1012. if (metaViewport) {
  1013. // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
  1014. if (metaViewport.content.indexOf("user-scalable=no") !== -1) {
  1015. return true;
  1016. }
  1017. // Chrome 32 and above with width=device-width or less don't need FastClick
  1018. if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
  1019. return true;
  1020. }
  1021. }
  1022. } else {
  1023. return true;
  1024. }
  1025. }
  1026. if (deviceIsBlackBerry10) {
  1027. blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/);
  1028. // BlackBerry 10.3+ does not require Fastclick library.
  1029. // https://github.com/ftlabs/fastclick/issues/251
  1030. if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
  1031. metaViewport = document.querySelector("meta[name=viewport]");
  1032. if (metaViewport) {
  1033. // user-scalable=no eliminates click delay.
  1034. if (metaViewport.content.indexOf("user-scalable=no") !== -1) {
  1035. return true;
  1036. }
  1037. // width=device-width (or less than device-width) eliminates click delay.
  1038. if (document.documentElement.scrollWidth <= window.outerWidth) {
  1039. return true;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
  1045. if (layer.style.msTouchAction === "none") {
  1046. return true;
  1047. }
  1048. return false;
  1049. };
  1050. /**
  1051. * Factory method for creating a FastClick object
  1052. *
  1053. * @param {Element} layer The layer to listen on
  1054. * @param {Object} options The options to override the defaults
  1055. */
  1056. FastClick.attach = function(layer, options) {
  1057. return new FastClick(layer, options);
  1058. };
  1059. module.exports = FastClick;
  1060. });
  1061. define("util.hammer", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  1062. "use strict";
  1063. require("core");
  1064. var $ = window.Zepto;
  1065. var UI = $.AMUI;
  1066. /**
  1067. * Hammer.js
  1068. * @via https://github.com/hammerjs/hammer.js
  1069. * @copyright Copyright (C) 2011-2014 by Jorik Tangelder (Eight Media)
  1070. * @license https://github.com/hammerjs/hammer.js/blob/master/LICENSE.md
  1071. */
  1072. var VENDOR_PREFIXES = [ "", "webkit", "moz", "MS", "ms", "o" ];
  1073. var TEST_ELEMENT = document.createElement("div");
  1074. var TYPE_FUNCTION = "function";
  1075. var round = Math.round;
  1076. var abs = Math.abs;
  1077. var now = Date.now;
  1078. /**
  1079. * set a timeout with a given scope
  1080. * @param {Function} fn
  1081. * @param {Number} timeout
  1082. * @param {Object} context
  1083. * @returns {number}
  1084. */
  1085. function setTimeoutContext(fn, timeout, context) {
  1086. return setTimeout(bindFn(fn, context), timeout);
  1087. }
  1088. /**
  1089. * if the argument is an array, we want to execute the fn on each entry
  1090. * if it aint an array we don't want to do a thing.
  1091. * this is used by all the methods that accept a single and array argument.
  1092. * @param {*|Array} arg
  1093. * @param {String} fn
  1094. * @param {Object} [context]
  1095. * @returns {Boolean}
  1096. */
  1097. function invokeArrayArg(arg, fn, context) {
  1098. if (Array.isArray(arg)) {
  1099. each(arg, context[fn], context);
  1100. return true;
  1101. }
  1102. return false;
  1103. }
  1104. /**
  1105. * walk objects and arrays
  1106. * @param {Object} obj
  1107. * @param {Function} iterator
  1108. * @param {Object} context
  1109. */
  1110. function each(obj, iterator, context) {
  1111. var i;
  1112. if (!obj) {
  1113. return;
  1114. }
  1115. if (obj.forEach) {
  1116. obj.forEach(iterator, context);
  1117. } else if (obj.length !== undefined) {
  1118. i = 0;
  1119. while (i < obj.length) {
  1120. iterator.call(context, obj[i], i, obj);
  1121. i++;
  1122. }
  1123. } else {
  1124. for (i in obj) {
  1125. obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
  1126. }
  1127. }
  1128. }
  1129. /**
  1130. * extend object.
  1131. * means that properties in dest will be overwritten by the ones in src.
  1132. * @param {Object} dest
  1133. * @param {Object} src
  1134. * @param {Boolean} [merge]
  1135. * @returns {Object} dest
  1136. */
  1137. function extend(dest, src, merge) {
  1138. var keys = Object.keys(src);
  1139. var i = 0;
  1140. while (i < keys.length) {
  1141. if (!merge || merge && dest[keys[i]] === undefined) {
  1142. dest[keys[i]] = src[keys[i]];
  1143. }
  1144. i++;
  1145. }
  1146. return dest;
  1147. }
  1148. /**
  1149. * merge the values from src in the dest.
  1150. * means that properties that exist in dest will not be overwritten by src
  1151. * @param {Object} dest
  1152. * @param {Object} src
  1153. * @returns {Object} dest
  1154. */
  1155. function merge(dest, src) {
  1156. return extend(dest, src, true);
  1157. }
  1158. /**
  1159. * simple class inheritance
  1160. * @param {Function} child
  1161. * @param {Function} base
  1162. * @param {Object} [properties]
  1163. */
  1164. function inherit(child, base, properties) {
  1165. var baseP = base.prototype, childP;
  1166. childP = child.prototype = Object.create(baseP);
  1167. childP.constructor = child;
  1168. childP._super = baseP;
  1169. if (properties) {
  1170. extend(childP, properties);
  1171. }
  1172. }
  1173. /**
  1174. * simple function bind
  1175. * @param {Function} fn
  1176. * @param {Object} context
  1177. * @returns {Function}
  1178. */
  1179. function bindFn(fn, context) {
  1180. return function boundFn() {
  1181. return fn.apply(context, arguments);
  1182. };
  1183. }
  1184. /**
  1185. * let a boolean value also be a function that must return a boolean
  1186. * this first item in args will be used as the context
  1187. * @param {Boolean|Function} val
  1188. * @param {Array} [args]
  1189. * @returns {Boolean}
  1190. */
  1191. function boolOrFn(val, args) {
  1192. if (typeof val == TYPE_FUNCTION) {
  1193. return val.apply(args ? args[0] || undefined : undefined, args);
  1194. }
  1195. return val;
  1196. }
  1197. /**
  1198. * use the val2 when val1 is undefined
  1199. * @param {*} val1
  1200. * @param {*} val2
  1201. * @returns {*}
  1202. */
  1203. function ifUndefined(val1, val2) {
  1204. return val1 === undefined ? val2 : val1;
  1205. }
  1206. /**
  1207. * addEventListener with multiple events at once
  1208. * @param {EventTarget} target
  1209. * @param {String} types
  1210. * @param {Function} handler
  1211. */
  1212. function addEventListeners(target, types, handler) {
  1213. each(splitStr(types), function(type) {
  1214. target.addEventListener(type, handler, false);
  1215. });
  1216. }
  1217. /**
  1218. * removeEventListener with multiple events at once
  1219. * @param {EventTarget} target
  1220. * @param {String} types
  1221. * @param {Function} handler
  1222. */
  1223. function removeEventListeners(target, types, handler) {
  1224. each(splitStr(types), function(type) {
  1225. target.removeEventListener(type, handler, false);
  1226. });
  1227. }
  1228. /**
  1229. * find if a node is in the given parent
  1230. * @method hasParent
  1231. * @param {HTMLElement} node
  1232. * @param {HTMLElement} parent
  1233. * @return {Boolean} found
  1234. */
  1235. function hasParent(node, parent) {
  1236. while (node) {
  1237. if (node == parent) {
  1238. return true;
  1239. }
  1240. node = node.parentNode;
  1241. }
  1242. return false;
  1243. }
  1244. /**
  1245. * small indexOf wrapper
  1246. * @param {String} str
  1247. * @param {String} find
  1248. * @returns {Boolean} found
  1249. */
  1250. function inStr(str, find) {
  1251. return str.indexOf(find) > -1;
  1252. }
  1253. /**
  1254. * split string on whitespace
  1255. * @param {String} str
  1256. * @returns {Array} words
  1257. */
  1258. function splitStr(str) {
  1259. return str.trim().split(/\s+/g);
  1260. }
  1261. /**
  1262. * find if a array contains the object using indexOf or a simple polyFill
  1263. * @param {Array} src
  1264. * @param {String} find
  1265. * @param {String} [findByKey]
  1266. * @return {Boolean|Number} false when not found, or the index
  1267. */
  1268. function inArray(src, find, findByKey) {
  1269. if (src.indexOf && !findByKey) {
  1270. return src.indexOf(find);
  1271. } else {
  1272. var i = 0;
  1273. while (i < src.length) {
  1274. if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {
  1275. return i;
  1276. }
  1277. i++;
  1278. }
  1279. return -1;
  1280. }
  1281. }
  1282. /**
  1283. * convert array-like objects to real arrays
  1284. * @param {Object} obj
  1285. * @returns {Array}
  1286. */
  1287. function toArray(obj) {
  1288. return Array.prototype.slice.call(obj, 0);
  1289. }
  1290. /**
  1291. * unique array with objects based on a key (like 'id') or just by the array's value
  1292. * @param {Array} src [{id:1},{id:2},{id:1}]
  1293. * @param {String} [key]
  1294. * @param {Boolean} [sort=False]
  1295. * @returns {Array} [{id:1},{id:2}]
  1296. */
  1297. function uniqueArray(src, key, sort) {
  1298. var results = [];
  1299. var values = [];
  1300. var i = 0;
  1301. while (i < src.length) {
  1302. var val = key ? src[i][key] : src[i];
  1303. if (inArray(values, val) < 0) {
  1304. results.push(src[i]);
  1305. }
  1306. values[i] = val;
  1307. i++;
  1308. }
  1309. if (sort) {
  1310. if (!key) {
  1311. results = results.sort();
  1312. } else {
  1313. results = results.sort(function sortUniqueArray(a, b) {
  1314. return a[key] > b[key];
  1315. });
  1316. }
  1317. }
  1318. return results;
  1319. }
  1320. /**
  1321. * get the prefixed property
  1322. * @param {Object} obj
  1323. * @param {String} property
  1324. * @returns {String|Undefined} prefixed
  1325. */
  1326. function prefixed(obj, property) {
  1327. var prefix, prop;
  1328. var camelProp = property[0].toUpperCase() + property.slice(1);
  1329. var i = 0;
  1330. while (i < VENDOR_PREFIXES.length) {
  1331. prefix = VENDOR_PREFIXES[i];
  1332. prop = prefix ? prefix + camelProp : property;
  1333. if (prop in obj) {
  1334. return prop;
  1335. }
  1336. i++;
  1337. }
  1338. return undefined;
  1339. }
  1340. /**
  1341. * get a unique id
  1342. * @returns {number} uniqueId
  1343. */
  1344. var _uniqueId = 1;
  1345. function uniqueId() {
  1346. return _uniqueId++;
  1347. }
  1348. /**
  1349. * get the window object of an element
  1350. * @param {HTMLElement} element
  1351. * @returns {DocumentView|Window}
  1352. */
  1353. function getWindowForElement(element) {
  1354. var doc = element.ownerDocument;
  1355. return doc.defaultView || doc.parentWindow;
  1356. }
  1357. var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
  1358. var SUPPORT_TOUCH = "ontouchstart" in window;
  1359. var SUPPORT_POINTER_EVENTS = prefixed(window, "PointerEvent") !== undefined;
  1360. var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
  1361. var INPUT_TYPE_TOUCH = "touch";
  1362. var INPUT_TYPE_PEN = "pen";
  1363. var INPUT_TYPE_MOUSE = "mouse";
  1364. var INPUT_TYPE_KINECT = "kinect";
  1365. var COMPUTE_INTERVAL = 25;
  1366. var INPUT_START = 1;
  1367. var INPUT_MOVE = 2;
  1368. var INPUT_END = 4;
  1369. var INPUT_CANCEL = 8;
  1370. var DIRECTION_NONE = 1;
  1371. var DIRECTION_LEFT = 2;
  1372. var DIRECTION_RIGHT = 4;
  1373. var DIRECTION_UP = 8;
  1374. var DIRECTION_DOWN = 16;
  1375. var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
  1376. var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
  1377. var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
  1378. var PROPS_XY = [ "x", "y" ];
  1379. var PROPS_CLIENT_XY = [ "clientX", "clientY" ];
  1380. /**
  1381. * create new input type manager
  1382. * @param {Manager} manager
  1383. * @param {Function} callback
  1384. * @returns {Input}
  1385. * @constructor
  1386. */
  1387. function Input(manager, callback) {
  1388. var self = this;
  1389. this.manager = manager;
  1390. this.callback = callback;
  1391. this.element = manager.element;
  1392. this.target = manager.options.inputTarget;
  1393. // smaller wrapper around the handler, for the scope and the enabled state of the manager,
  1394. // so when disabled the input events are completely bypassed.
  1395. this.domHandler = function(ev) {
  1396. if (boolOrFn(manager.options.enable, [ manager ])) {
  1397. self.handler(ev);
  1398. }
  1399. };
  1400. this.init();
  1401. }
  1402. Input.prototype = {
  1403. /**
  1404. * should handle the inputEvent data and trigger the callback
  1405. * @virtual
  1406. */
  1407. handler: function() {},
  1408. /**
  1409. * bind the events
  1410. */
  1411. init: function() {
  1412. this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
  1413. this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
  1414. this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  1415. },
  1416. /**
  1417. * unbind the events
  1418. */
  1419. destroy: function() {
  1420. this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
  1421. this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
  1422. this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
  1423. }
  1424. };
  1425. /**
  1426. * create new input type manager
  1427. * called by the Manager constructor
  1428. * @param {Hammer} manager
  1429. * @returns {Input}
  1430. */
  1431. function createInputInstance(manager) {
  1432. var Type;
  1433. var inputClass = manager.options.inputClass;
  1434. if (inputClass) {
  1435. Type = inputClass;
  1436. } else if (SUPPORT_POINTER_EVENTS) {
  1437. Type = PointerEventInput;
  1438. } else if (SUPPORT_ONLY_TOUCH) {
  1439. Type = TouchInput;
  1440. } else if (!SUPPORT_TOUCH) {
  1441. Type = MouseInput;
  1442. } else {
  1443. Type = TouchMouseInput;
  1444. }
  1445. return new Type(manager, inputHandler);
  1446. }
  1447. /**
  1448. * handle input events
  1449. * @param {Manager} manager
  1450. * @param {String} eventType
  1451. * @param {Object} input
  1452. */
  1453. function inputHandler(manager, eventType, input) {
  1454. var pointersLen = input.pointers.length;
  1455. var changedPointersLen = input.changedPointers.length;
  1456. var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
  1457. var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;
  1458. input.isFirst = !!isFirst;
  1459. input.isFinal = !!isFinal;
  1460. if (isFirst) {
  1461. manager.session = {};
  1462. }
  1463. // source event is the normalized value of the domEvents
  1464. // like 'touchstart, mouseup, pointerdown'
  1465. input.eventType = eventType;
  1466. // compute scale, rotation etc
  1467. computeInputData(manager, input);
  1468. // emit secret event
  1469. manager.emit("hammer.input", input);
  1470. manager.recognize(input);
  1471. manager.session.prevInput = input;
  1472. }
  1473. /**
  1474. * extend the data with some usable properties like scale, rotate, velocity etc
  1475. * @param {Object} manager
  1476. * @param {Object} input
  1477. */
  1478. function computeInputData(manager, input) {
  1479. var session = manager.session;
  1480. var pointers = input.pointers;
  1481. var pointersLength = pointers.length;
  1482. // store the first input to calculate the distance and direction
  1483. if (!session.firstInput) {
  1484. session.firstInput = simpleCloneInputData(input);
  1485. }
  1486. // to compute scale and rotation we need to store the multiple touches
  1487. if (pointersLength > 1 && !session.firstMultiple) {
  1488. session.firstMultiple = simpleCloneInputData(input);
  1489. } else if (pointersLength === 1) {
  1490. session.firstMultiple = false;
  1491. }
  1492. var firstInput = session.firstInput;
  1493. var firstMultiple = session.firstMultiple;
  1494. var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
  1495. var center = input.center = getCenter(pointers);
  1496. input.timeStamp = now();
  1497. input.deltaTime = input.timeStamp - firstInput.timeStamp;
  1498. input.angle = getAngle(offsetCenter, center);
  1499. input.distance = getDistance(offsetCenter, center);
  1500. computeDeltaXY(session, input);
  1501. input.offsetDirection = getDirection(input.deltaX, input.deltaY);
  1502. input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
  1503. input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
  1504. computeIntervalInputData(session, input);
  1505. // find the correct target
  1506. var target = manager.element;
  1507. if (hasParent(input.srcEvent.target, target)) {
  1508. target = input.srcEvent.target;
  1509. }
  1510. input.target = target;
  1511. }
  1512. function computeDeltaXY(session, input) {
  1513. var center = input.center;
  1514. var offset = session.offsetDelta || {};
  1515. var prevDelta = session.prevDelta || {};
  1516. var prevInput = session.prevInput || {};
  1517. if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
  1518. prevDelta = session.prevDelta = {
  1519. x: prevInput.deltaX || 0,
  1520. y: prevInput.deltaY || 0
  1521. };
  1522. offset = session.offsetDelta = {
  1523. x: center.x,
  1524. y: center.y
  1525. };
  1526. }
  1527. input.deltaX = prevDelta.x + (center.x - offset.x);
  1528. input.deltaY = prevDelta.y + (center.y - offset.y);
  1529. }
  1530. /**
  1531. * velocity is calculated every x ms
  1532. * @param {Object} session
  1533. * @param {Object} input
  1534. */
  1535. function computeIntervalInputData(session, input) {
  1536. var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction;
  1537. if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
  1538. var deltaX = last.deltaX - input.deltaX;
  1539. var deltaY = last.deltaY - input.deltaY;
  1540. var v = getVelocity(deltaTime, deltaX, deltaY);
  1541. velocityX = v.x;
  1542. velocityY = v.y;
  1543. velocity = abs(v.x) > abs(v.y) ? v.x : v.y;
  1544. direction = getDirection(deltaX, deltaY);
  1545. session.lastInterval = input;
  1546. } else {
  1547. // use latest velocity info if it doesn't overtake a minimum period
  1548. velocity = last.velocity;
  1549. velocityX = last.velocityX;
  1550. velocityY = last.velocityY;
  1551. direction = last.direction;
  1552. }
  1553. input.velocity = velocity;
  1554. input.velocityX = velocityX;
  1555. input.velocityY = velocityY;
  1556. input.direction = direction;
  1557. }
  1558. /**
  1559. * create a simple clone from the input used for storage of firstInput and firstMultiple
  1560. * @param {Object} input
  1561. * @returns {Object} clonedInputData
  1562. */
  1563. function simpleCloneInputData(input) {
  1564. // make a simple copy of the pointers because we will get a reference if we don't
  1565. // we only need clientXY for the calculations
  1566. var pointers = [];
  1567. var i = 0;
  1568. while (i < input.pointers.length) {
  1569. pointers[i] = {
  1570. clientX: round(input.pointers[i].clientX),
  1571. clientY: round(input.pointers[i].clientY)
  1572. };
  1573. i++;
  1574. }
  1575. return {
  1576. timeStamp: now(),
  1577. pointers: pointers,
  1578. center: getCenter(pointers),
  1579. deltaX: input.deltaX,
  1580. deltaY: input.deltaY
  1581. };
  1582. }
  1583. /**
  1584. * get the center of all the pointers
  1585. * @param {Array} pointers
  1586. * @return {Object} center contains `x` and `y` properties
  1587. */
  1588. function getCenter(pointers) {
  1589. var pointersLength = pointers.length;
  1590. // no need to loop when only one touch
  1591. if (pointersLength === 1) {
  1592. return {
  1593. x: round(pointers[0].clientX),
  1594. y: round(pointers[0].clientY)
  1595. };
  1596. }
  1597. var x = 0, y = 0, i = 0;
  1598. while (i < pointersLength) {
  1599. x += pointers[i].clientX;
  1600. y += pointers[i].clientY;
  1601. i++;
  1602. }
  1603. return {
  1604. x: round(x / pointersLength),
  1605. y: round(y / pointersLength)
  1606. };
  1607. }
  1608. /**
  1609. * calculate the velocity between two points. unit is in px per ms.
  1610. * @param {Number} deltaTime
  1611. * @param {Number} x
  1612. * @param {Number} y
  1613. * @return {Object} velocity `x` and `y`
  1614. */
  1615. function getVelocity(deltaTime, x, y) {
  1616. return {
  1617. x: x / deltaTime || 0,
  1618. y: y / deltaTime || 0
  1619. };
  1620. }
  1621. /**
  1622. * get the direction between two points
  1623. * @param {Number} x
  1624. * @param {Number} y
  1625. * @return {Number} direction
  1626. */
  1627. function getDirection(x, y) {
  1628. if (x === y) {
  1629. return DIRECTION_NONE;
  1630. }
  1631. if (abs(x) >= abs(y)) {
  1632. return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  1633. }
  1634. return y > 0 ? DIRECTION_UP : DIRECTION_DOWN;
  1635. }
  1636. /**
  1637. * calculate the absolute distance between two points
  1638. * @param {Object} p1 {x, y}
  1639. * @param {Object} p2 {x, y}
  1640. * @param {Array} [props] containing x and y keys
  1641. * @return {Number} distance
  1642. */
  1643. function getDistance(p1, p2, props) {
  1644. if (!props) {
  1645. props = PROPS_XY;
  1646. }
  1647. var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
  1648. return Math.sqrt(x * x + y * y);
  1649. }
  1650. /**
  1651. * calculate the angle between two coordinates
  1652. * @param {Object} p1
  1653. * @param {Object} p2
  1654. * @param {Array} [props] containing x and y keys
  1655. * @return {Number} angle
  1656. */
  1657. function getAngle(p1, p2, props) {
  1658. if (!props) {
  1659. props = PROPS_XY;
  1660. }
  1661. var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]];
  1662. return Math.atan2(y, x) * 180 / Math.PI;
  1663. }
  1664. /**
  1665. * calculate the rotation degrees between two pointersets
  1666. * @param {Array} start array of pointers
  1667. * @param {Array} end array of pointers
  1668. * @return {Number} rotation
  1669. */
  1670. function getRotation(start, end) {
  1671. return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY);
  1672. }
  1673. /**
  1674. * calculate the scale factor between two pointersets
  1675. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  1676. * @param {Array} start array of pointers
  1677. * @param {Array} end array of pointers
  1678. * @return {Number} scale
  1679. */
  1680. function getScale(start, end) {
  1681. return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
  1682. }
  1683. var MOUSE_INPUT_MAP = {
  1684. mousedown: INPUT_START,
  1685. mousemove: INPUT_MOVE,
  1686. mouseup: INPUT_END
  1687. };
  1688. var MOUSE_ELEMENT_EVENTS = "mousedown";
  1689. var MOUSE_WINDOW_EVENTS = "mousemove mouseup";
  1690. /**
  1691. * Mouse events input
  1692. * @constructor
  1693. * @extends Input
  1694. */
  1695. function MouseInput() {
  1696. this.evEl = MOUSE_ELEMENT_EVENTS;
  1697. this.evWin = MOUSE_WINDOW_EVENTS;
  1698. this.allow = true;
  1699. // used by Input.TouchMouse to disable mouse events
  1700. this.pressed = false;
  1701. // mousedown state
  1702. Input.apply(this, arguments);
  1703. }
  1704. inherit(MouseInput, Input, {
  1705. /**
  1706. * handle mouse events
  1707. * @param {Object} ev
  1708. */
  1709. handler: function MEhandler(ev) {
  1710. var eventType = MOUSE_INPUT_MAP[ev.type];
  1711. // on start we want to have the left mouse button down
  1712. if (eventType & INPUT_START && ev.button === 0) {
  1713. this.pressed = true;
  1714. }
  1715. if (eventType & INPUT_MOVE && ev.which !== 1) {
  1716. eventType = INPUT_END;
  1717. }
  1718. // mouse must be down, and mouse events are allowed (see the TouchMouse input)
  1719. if (!this.pressed || !this.allow) {
  1720. return;
  1721. }
  1722. if (eventType & INPUT_END) {
  1723. this.pressed = false;
  1724. }
  1725. this.callback(this.manager, eventType, {
  1726. pointers: [ ev ],
  1727. changedPointers: [ ev ],
  1728. pointerType: INPUT_TYPE_MOUSE,
  1729. srcEvent: ev
  1730. });
  1731. }
  1732. });
  1733. var POINTER_INPUT_MAP = {
  1734. pointerdown: INPUT_START,
  1735. pointermove: INPUT_MOVE,
  1736. pointerup: INPUT_END,
  1737. pointercancel: INPUT_CANCEL,
  1738. pointerout: INPUT_CANCEL
  1739. };
  1740. // in IE10 the pointer types is defined as an enum
  1741. var IE10_POINTER_TYPE_ENUM = {
  1742. 2: INPUT_TYPE_TOUCH,
  1743. 3: INPUT_TYPE_PEN,
  1744. 4: INPUT_TYPE_MOUSE,
  1745. 5: INPUT_TYPE_KINECT
  1746. };
  1747. var POINTER_ELEMENT_EVENTS = "pointerdown";
  1748. var POINTER_WINDOW_EVENTS = "pointermove pointerup pointercancel";
  1749. // IE10 has prefixed support, and case-sensitive
  1750. if (window.MSPointerEvent) {
  1751. POINTER_ELEMENT_EVENTS = "MSPointerDown";
  1752. POINTER_WINDOW_EVENTS = "MSPointerMove MSPointerUp MSPointerCancel";
  1753. }
  1754. /**
  1755. * Pointer events input
  1756. * @constructor
  1757. * @extends Input
  1758. */
  1759. function PointerEventInput() {
  1760. this.evEl = POINTER_ELEMENT_EVENTS;
  1761. this.evWin = POINTER_WINDOW_EVENTS;
  1762. Input.apply(this, arguments);
  1763. this.store = this.manager.session.pointerEvents = [];
  1764. }
  1765. inherit(PointerEventInput, Input, {
  1766. /**
  1767. * handle mouse events
  1768. * @param {Object} ev
  1769. */
  1770. handler: function PEhandler(ev) {
  1771. var store = this.store;
  1772. var removePointer = false;
  1773. var eventTypeNormalized = ev.type.toLowerCase().replace("ms", "");
  1774. var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
  1775. var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
  1776. var isTouch = pointerType == INPUT_TYPE_TOUCH;
  1777. // start and mouse must be down
  1778. if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
  1779. store.push(ev);
  1780. } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
  1781. removePointer = true;
  1782. }
  1783. // get index of the event in the store
  1784. // it not found, so the pointer hasn't been down (so it's probably a hover)
  1785. var storeIndex = inArray(store, ev.pointerId, "pointerId");
  1786. if (storeIndex < 0) {
  1787. return;
  1788. }
  1789. // update the event in the store
  1790. store[storeIndex] = ev;
  1791. this.callback(this.manager, eventType, {
  1792. pointers: store,
  1793. changedPointers: [ ev ],
  1794. pointerType: pointerType,
  1795. srcEvent: ev
  1796. });
  1797. if (removePointer) {
  1798. // remove from the store
  1799. store.splice(storeIndex, 1);
  1800. }
  1801. }
  1802. });
  1803. var TOUCH_INPUT_MAP = {
  1804. touchstart: INPUT_START,
  1805. touchmove: INPUT_MOVE,
  1806. touchend: INPUT_END,
  1807. touchcancel: INPUT_CANCEL
  1808. };
  1809. var TOUCH_TARGET_EVENTS = "touchstart touchmove touchend touchcancel";
  1810. /**
  1811. * Touch events input
  1812. * @constructor
  1813. * @extends Input
  1814. */
  1815. function TouchInput() {
  1816. this.evTarget = TOUCH_TARGET_EVENTS;
  1817. this.targetIds = {};
  1818. Input.apply(this, arguments);
  1819. }
  1820. inherit(TouchInput, Input, {
  1821. /**
  1822. * handle touch events
  1823. * @param {Object} ev
  1824. */
  1825. handler: function TEhandler(ev) {
  1826. var type = TOUCH_INPUT_MAP[ev.type];
  1827. var touches = getTouches.call(this, ev, type);
  1828. if (!touches) {
  1829. return;
  1830. }
  1831. this.callback(this.manager, type, {
  1832. pointers: touches[0],
  1833. changedPointers: touches[1],
  1834. pointerType: INPUT_TYPE_TOUCH,
  1835. srcEvent: ev
  1836. });
  1837. }
  1838. });
  1839. /**
  1840. * @this {TouchInput}
  1841. * @param {Object} ev
  1842. * @param {Number} type flag
  1843. * @returns {undefined|Array} [all, changed]
  1844. */
  1845. function getTouches(ev, type) {
  1846. var allTouches = toArray(ev.touches);
  1847. var targetIds = this.targetIds;
  1848. // when there is only one touch, the process can be simplified
  1849. if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
  1850. targetIds[allTouches[0].identifier] = true;
  1851. return [ allTouches, allTouches ];
  1852. }
  1853. var i, targetTouches = toArray(ev.targetTouches), changedTouches = toArray(ev.changedTouches), changedTargetTouches = [];
  1854. // collect touches
  1855. if (type === INPUT_START) {
  1856. i = 0;
  1857. while (i < targetTouches.length) {
  1858. targetIds[targetTouches[i].identifier] = true;
  1859. i++;
  1860. }
  1861. }
  1862. // filter changed touches to only contain touches that exist in the collected target ids
  1863. i = 0;
  1864. while (i < changedTouches.length) {
  1865. if (targetIds[changedTouches[i].identifier]) {
  1866. changedTargetTouches.push(changedTouches[i]);
  1867. }
  1868. // cleanup removed touches
  1869. if (type & (INPUT_END | INPUT_CANCEL)) {
  1870. delete targetIds[changedTouches[i].identifier];
  1871. }
  1872. i++;
  1873. }
  1874. if (!changedTargetTouches.length) {
  1875. return;
  1876. }
  1877. return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
  1878. uniqueArray(targetTouches.concat(changedTargetTouches), "identifier", true), changedTargetTouches ];
  1879. }
  1880. /**
  1881. * Combined touch and mouse input
  1882. *
  1883. * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
  1884. * This because touch devices also emit mouse events while doing a touch.
  1885. *
  1886. * @constructor
  1887. * @extends Input
  1888. */
  1889. function TouchMouseInput() {
  1890. Input.apply(this, arguments);
  1891. var handler = bindFn(this.handler, this);
  1892. this.touch = new TouchInput(this.manager, handler);
  1893. this.mouse = new MouseInput(this.manager, handler);
  1894. }
  1895. inherit(TouchMouseInput, Input, {
  1896. /**
  1897. * handle mouse and touch events
  1898. * @param {Hammer} manager
  1899. * @param {String} inputEvent
  1900. * @param {Object} inputData
  1901. */
  1902. handler: function TMEhandler(manager, inputEvent, inputData) {
  1903. var isTouch = inputData.pointerType == INPUT_TYPE_TOUCH, isMouse = inputData.pointerType == INPUT_TYPE_MOUSE;
  1904. // when we're in a touch event, so block all upcoming mouse events
  1905. // most mobile browser also emit mouseevents, right after touchstart
  1906. if (isTouch) {
  1907. this.mouse.allow = false;
  1908. } else if (isMouse && !this.mouse.allow) {
  1909. return;
  1910. }
  1911. // reset the allowMouse when we're done
  1912. if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
  1913. this.mouse.allow = true;
  1914. }
  1915. this.callback(manager, inputEvent, inputData);
  1916. },
  1917. /**
  1918. * remove the event listeners
  1919. */
  1920. destroy: function destroy() {
  1921. this.touch.destroy();
  1922. this.mouse.destroy();
  1923. }
  1924. });
  1925. var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, "touchAction");
  1926. var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
  1927. // magical touchAction value
  1928. var TOUCH_ACTION_COMPUTE = "compute";
  1929. var TOUCH_ACTION_AUTO = "auto";
  1930. var TOUCH_ACTION_MANIPULATION = "manipulation";
  1931. // not implemented
  1932. var TOUCH_ACTION_NONE = "none";
  1933. var TOUCH_ACTION_PAN_X = "pan-x";
  1934. var TOUCH_ACTION_PAN_Y = "pan-y";
  1935. /**
  1936. * Touch Action
  1937. * sets the touchAction property or uses the js alternative
  1938. * @param {Manager} manager
  1939. * @param {String} value
  1940. * @constructor
  1941. */
  1942. function TouchAction(manager, value) {
  1943. this.manager = manager;
  1944. this.set(value);
  1945. }
  1946. TouchAction.prototype = {
  1947. /**
  1948. * set the touchAction value on the element or enable the polyfill
  1949. * @param {String} value
  1950. */
  1951. set: function(value) {
  1952. // find out the touch-action by the event handlers
  1953. if (value == TOUCH_ACTION_COMPUTE) {
  1954. value = this.compute();
  1955. }
  1956. if (NATIVE_TOUCH_ACTION) {
  1957. this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
  1958. }
  1959. this.actions = value.toLowerCase().trim();
  1960. },
  1961. /**
  1962. * just re-set the touchAction value
  1963. */
  1964. update: function() {
  1965. this.set(this.manager.options.touchAction);
  1966. },
  1967. /**
  1968. * compute the value for the touchAction property based on the recognizer's settings
  1969. * @returns {String} value
  1970. */
  1971. compute: function() {
  1972. var actions = [];
  1973. each(this.manager.recognizers, function(recognizer) {
  1974. if (boolOrFn(recognizer.options.enable, [ recognizer ])) {
  1975. actions = actions.concat(recognizer.getTouchAction());
  1976. }
  1977. });
  1978. return cleanTouchActions(actions.join(" "));
  1979. },
  1980. /**
  1981. * this method is called on each input cycle and provides the preventing of the browser behavior
  1982. * @param {Object} input
  1983. */
  1984. preventDefaults: function(input) {
  1985. // not needed with native support for the touchAction property
  1986. if (NATIVE_TOUCH_ACTION) {
  1987. return;
  1988. }
  1989. var srcEvent = input.srcEvent;
  1990. var direction = input.offsetDirection;
  1991. // if the touch action did prevented once this session
  1992. if (this.manager.session.prevented) {
  1993. srcEvent.preventDefault();
  1994. return;
  1995. }
  1996. var actions = this.actions;
  1997. var hasNone = inStr(actions, TOUCH_ACTION_NONE);
  1998. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  1999. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  2000. if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
  2001. return this.preventSrc(srcEvent);
  2002. }
  2003. },
  2004. /**
  2005. * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
  2006. * @param {Object} srcEvent
  2007. */
  2008. preventSrc: function(srcEvent) {
  2009. this.manager.session.prevented = true;
  2010. srcEvent.preventDefault();
  2011. }
  2012. };
  2013. /**
  2014. * when the touchActions are collected they are not a valid value, so we need to clean things up. *
  2015. * @param {String} actions
  2016. * @returns {*}
  2017. */
  2018. function cleanTouchActions(actions) {
  2019. // none
  2020. if (inStr(actions, TOUCH_ACTION_NONE)) {
  2021. return TOUCH_ACTION_NONE;
  2022. }
  2023. var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
  2024. var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
  2025. // pan-x and pan-y can be combined
  2026. if (hasPanX && hasPanY) {
  2027. return TOUCH_ACTION_PAN_X + " " + TOUCH_ACTION_PAN_Y;
  2028. }
  2029. // pan-x OR pan-y
  2030. if (hasPanX || hasPanY) {
  2031. return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
  2032. }
  2033. // manipulation
  2034. if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
  2035. return TOUCH_ACTION_MANIPULATION;
  2036. }
  2037. return TOUCH_ACTION_AUTO;
  2038. }
  2039. /**
  2040. * Recognizer flow explained; *
  2041. * All recognizers have the initial state of POSSIBLE when a input session starts.
  2042. * The definition of a input session is from the first input until the last input, with all it's movement in it. *
  2043. * Example session for mouse-input: mousedown -> mousemove -> mouseup
  2044. *
  2045. * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
  2046. * which determines with state it should be.
  2047. *
  2048. * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
  2049. * POSSIBLE to give it another change on the next cycle.
  2050. *
  2051. * Possible
  2052. * |
  2053. * +-----+---------------+
  2054. * | |
  2055. * +-----+-----+ |
  2056. * | | |
  2057. * Failed Cancelled |
  2058. * +-------+------+
  2059. * | |
  2060. * Recognized Began
  2061. * |
  2062. * Changed
  2063. * |
  2064. * Ended/Recognized
  2065. */
  2066. var STATE_POSSIBLE = 1;
  2067. var STATE_BEGAN = 2;
  2068. var STATE_CHANGED = 4;
  2069. var STATE_ENDED = 8;
  2070. var STATE_RECOGNIZED = STATE_ENDED;
  2071. var STATE_CANCELLED = 16;
  2072. var STATE_FAILED = 32;
  2073. /**
  2074. * Recognizer
  2075. * Every recognizer needs to extend from this class.
  2076. * @constructor
  2077. * @param {Object} options
  2078. */
  2079. function Recognizer(options) {
  2080. this.id = uniqueId();
  2081. this.manager = null;
  2082. this.options = merge(options || {}, this.defaults);
  2083. // default is enable true
  2084. this.options.enable = ifUndefined(this.options.enable, true);
  2085. this.state = STATE_POSSIBLE;
  2086. this.simultaneous = {};
  2087. this.requireFail = [];
  2088. }
  2089. Recognizer.prototype = {
  2090. /**
  2091. * @virtual
  2092. * @type {Object}
  2093. */
  2094. defaults: {},
  2095. /**
  2096. * set options
  2097. * @param {Object} options
  2098. * @return {Recognizer}
  2099. */
  2100. set: function(options) {
  2101. extend(this.options, options);
  2102. // also update the touchAction, in case something changed about the directions/enabled state
  2103. this.manager && this.manager.touchAction.update();
  2104. return this;
  2105. },
  2106. /**
  2107. * recognize simultaneous with an other recognizer.
  2108. * @param {Recognizer} otherRecognizer
  2109. * @returns {Recognizer} this
  2110. */
  2111. recognizeWith: function(otherRecognizer) {
  2112. if (invokeArrayArg(otherRecognizer, "recognizeWith", this)) {
  2113. return this;
  2114. }
  2115. var simultaneous = this.simultaneous;
  2116. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2117. if (!simultaneous[otherRecognizer.id]) {
  2118. simultaneous[otherRecognizer.id] = otherRecognizer;
  2119. otherRecognizer.recognizeWith(this);
  2120. }
  2121. return this;
  2122. },
  2123. /**
  2124. * drop the simultaneous link. it doesnt remove the link on the other recognizer.
  2125. * @param {Recognizer} otherRecognizer
  2126. * @returns {Recognizer} this
  2127. */
  2128. dropRecognizeWith: function(otherRecognizer) {
  2129. if (invokeArrayArg(otherRecognizer, "dropRecognizeWith", this)) {
  2130. return this;
  2131. }
  2132. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2133. delete this.simultaneous[otherRecognizer.id];
  2134. return this;
  2135. },
  2136. /**
  2137. * recognizer can only run when an other is failing
  2138. * @param {Recognizer} otherRecognizer
  2139. * @returns {Recognizer} this
  2140. */
  2141. requireFailure: function(otherRecognizer) {
  2142. if (invokeArrayArg(otherRecognizer, "requireFailure", this)) {
  2143. return this;
  2144. }
  2145. var requireFail = this.requireFail;
  2146. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2147. if (inArray(requireFail, otherRecognizer) === -1) {
  2148. requireFail.push(otherRecognizer);
  2149. otherRecognizer.requireFailure(this);
  2150. }
  2151. return this;
  2152. },
  2153. /**
  2154. * drop the requireFailure link. it does not remove the link on the other recognizer.
  2155. * @param {Recognizer} otherRecognizer
  2156. * @returns {Recognizer} this
  2157. */
  2158. dropRequireFailure: function(otherRecognizer) {
  2159. if (invokeArrayArg(otherRecognizer, "dropRequireFailure", this)) {
  2160. return this;
  2161. }
  2162. otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
  2163. var index = inArray(this.requireFail, otherRecognizer);
  2164. if (index > -1) {
  2165. this.requireFail.splice(index, 1);
  2166. }
  2167. return this;
  2168. },
  2169. /**
  2170. * has require failures boolean
  2171. * @returns {boolean}
  2172. */
  2173. hasRequireFailures: function() {
  2174. return this.requireFail.length > 0;
  2175. },
  2176. /**
  2177. * if the recognizer can recognize simultaneous with an other recognizer
  2178. * @param {Recognizer} otherRecognizer
  2179. * @returns {Boolean}
  2180. */
  2181. canRecognizeWith: function(otherRecognizer) {
  2182. return !!this.simultaneous[otherRecognizer.id];
  2183. },
  2184. /**
  2185. * You should use `tryEmit` instead of `emit` directly to check
  2186. * that all the needed recognizers has failed before emitting.
  2187. * @param {Object} input
  2188. */
  2189. emit: function(input) {
  2190. var self = this;
  2191. var state = this.state;
  2192. function emit(withState) {
  2193. self.manager.emit(self.options.event + (withState ? stateStr(state) : ""), input);
  2194. }
  2195. // 'panstart' and 'panmove'
  2196. if (state < STATE_ENDED) {
  2197. emit(true);
  2198. }
  2199. emit();
  2200. // simple 'eventName' events
  2201. // panend and pancancel
  2202. if (state >= STATE_ENDED) {
  2203. emit(true);
  2204. }
  2205. },
  2206. /**
  2207. * Check that all the require failure recognizers has failed,
  2208. * if true, it emits a gesture event,
  2209. * otherwise, setup the state to FAILED.
  2210. * @param {Object} input
  2211. */
  2212. tryEmit: function(input) {
  2213. if (this.canEmit()) {
  2214. return this.emit(input);
  2215. }
  2216. // it's failing anyway
  2217. this.state = STATE_FAILED;
  2218. },
  2219. /**
  2220. * can we emit?
  2221. * @returns {boolean}
  2222. */
  2223. canEmit: function() {
  2224. var i = 0;
  2225. while (i < this.requireFail.length) {
  2226. if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
  2227. return false;
  2228. }
  2229. i++;
  2230. }
  2231. return true;
  2232. },
  2233. /**
  2234. * update the recognizer
  2235. * @param {Object} inputData
  2236. */
  2237. recognize: function(inputData) {
  2238. // make a new copy of the inputData
  2239. // so we can change the inputData without messing up the other recognizers
  2240. var inputDataClone = extend({}, inputData);
  2241. // is is enabled and allow recognizing?
  2242. if (!boolOrFn(this.options.enable, [ this, inputDataClone ])) {
  2243. this.reset();
  2244. this.state = STATE_FAILED;
  2245. return;
  2246. }
  2247. // reset when we've reached the end
  2248. if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
  2249. this.state = STATE_POSSIBLE;
  2250. }
  2251. this.state = this.process(inputDataClone);
  2252. // the recognizer has recognized a gesture
  2253. // so trigger an event
  2254. if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
  2255. this.tryEmit(inputDataClone);
  2256. }
  2257. },
  2258. /**
  2259. * return the state of the recognizer
  2260. * the actual recognizing happens in this method
  2261. * @virtual
  2262. * @param {Object} inputData
  2263. * @returns {Const} STATE
  2264. */
  2265. process: function(inputData) {},
  2266. // jshint ignore:line
  2267. /**
  2268. * return the preferred touch-action
  2269. * @virtual
  2270. * @returns {Array}
  2271. */
  2272. getTouchAction: function() {},
  2273. /**
  2274. * called when the gesture isn't allowed to recognize
  2275. * like when another is being recognized or it is disabled
  2276. * @virtual
  2277. */
  2278. reset: function() {}
  2279. };
  2280. /**
  2281. * get a usable string, used as event postfix
  2282. * @param {Const} state
  2283. * @returns {String} state
  2284. */
  2285. function stateStr(state) {
  2286. if (state & STATE_CANCELLED) {
  2287. return "cancel";
  2288. } else if (state & STATE_ENDED) {
  2289. return "end";
  2290. } else if (state & STATE_CHANGED) {
  2291. return "move";
  2292. } else if (state & STATE_BEGAN) {
  2293. return "start";
  2294. }
  2295. return "";
  2296. }
  2297. /**
  2298. * direction cons to string
  2299. * @param {Const} direction
  2300. * @returns {String}
  2301. */
  2302. function directionStr(direction) {
  2303. if (direction == DIRECTION_DOWN) {
  2304. return "down";
  2305. } else if (direction == DIRECTION_UP) {
  2306. return "up";
  2307. } else if (direction == DIRECTION_LEFT) {
  2308. return "left";
  2309. } else if (direction == DIRECTION_RIGHT) {
  2310. return "right";
  2311. }
  2312. return "";
  2313. }
  2314. /**
  2315. * get a recognizer by name if it is bound to a manager
  2316. * @param {Recognizer|String} otherRecognizer
  2317. * @param {Recognizer} recognizer
  2318. * @returns {Recognizer}
  2319. */
  2320. function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
  2321. var manager = recognizer.manager;
  2322. if (manager) {
  2323. return manager.get(otherRecognizer);
  2324. }
  2325. return otherRecognizer;
  2326. }
  2327. /**
  2328. * This recognizer is just used as a base for the simple attribute recognizers.
  2329. * @constructor
  2330. * @extends Recognizer
  2331. */
  2332. function AttrRecognizer() {
  2333. Recognizer.apply(this, arguments);
  2334. }
  2335. inherit(AttrRecognizer, Recognizer, {
  2336. /**
  2337. * @namespace
  2338. * @memberof AttrRecognizer
  2339. */
  2340. defaults: {
  2341. /**
  2342. * @type {Number}
  2343. * @default 1
  2344. */
  2345. pointers: 1
  2346. },
  2347. /**
  2348. * Used to check if it the recognizer receives valid input, like input.distance > 10.
  2349. * @memberof AttrRecognizer
  2350. * @param {Object} input
  2351. * @returns {Boolean} recognized
  2352. */
  2353. attrTest: function(input) {
  2354. var optionPointers = this.options.pointers;
  2355. return optionPointers === 0 || input.pointers.length === optionPointers;
  2356. },
  2357. /**
  2358. * Process the input and return the state for the recognizer
  2359. * @memberof AttrRecognizer
  2360. * @param {Object} input
  2361. * @returns {*} State
  2362. */
  2363. process: function(input) {
  2364. var state = this.state;
  2365. var eventType = input.eventType;
  2366. var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
  2367. var isValid = this.attrTest(input);
  2368. // on cancel input and we've recognized before, return STATE_CANCELLED
  2369. if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
  2370. return state | STATE_CANCELLED;
  2371. } else if (isRecognized || isValid) {
  2372. if (eventType & INPUT_END) {
  2373. return state | STATE_ENDED;
  2374. } else if (!(state & STATE_BEGAN)) {
  2375. return STATE_BEGAN;
  2376. }
  2377. return state | STATE_CHANGED;
  2378. }
  2379. return STATE_FAILED;
  2380. }
  2381. });
  2382. /**
  2383. * Pan
  2384. * Recognized when the pointer is down and moved in the allowed direction.
  2385. * @constructor
  2386. * @extends AttrRecognizer
  2387. */
  2388. function PanRecognizer() {
  2389. AttrRecognizer.apply(this, arguments);
  2390. this.pX = null;
  2391. this.pY = null;
  2392. }
  2393. inherit(PanRecognizer, AttrRecognizer, {
  2394. /**
  2395. * @namespace
  2396. * @memberof PanRecognizer
  2397. */
  2398. defaults: {
  2399. event: "pan",
  2400. threshold: 10,
  2401. pointers: 1,
  2402. direction: DIRECTION_ALL
  2403. },
  2404. getTouchAction: function() {
  2405. var direction = this.options.direction;
  2406. var actions = [];
  2407. if (direction & DIRECTION_HORIZONTAL) {
  2408. actions.push(TOUCH_ACTION_PAN_Y);
  2409. }
  2410. if (direction & DIRECTION_VERTICAL) {
  2411. actions.push(TOUCH_ACTION_PAN_X);
  2412. }
  2413. return actions;
  2414. },
  2415. directionTest: function(input) {
  2416. var options = this.options;
  2417. var hasMoved = true;
  2418. var distance = input.distance;
  2419. var direction = input.direction;
  2420. var x = input.deltaX;
  2421. var y = input.deltaY;
  2422. // lock to axis?
  2423. if (!(direction & options.direction)) {
  2424. if (options.direction & DIRECTION_HORIZONTAL) {
  2425. direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
  2426. hasMoved = x != this.pX;
  2427. distance = Math.abs(input.deltaX);
  2428. } else {
  2429. direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
  2430. hasMoved = y != this.pY;
  2431. distance = Math.abs(input.deltaY);
  2432. }
  2433. }
  2434. input.direction = direction;
  2435. return hasMoved && distance > options.threshold && direction & options.direction;
  2436. },
  2437. attrTest: function(input) {
  2438. return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));
  2439. },
  2440. emit: function(input) {
  2441. this.pX = input.deltaX;
  2442. this.pY = input.deltaY;
  2443. var direction = directionStr(input.direction);
  2444. if (direction) {
  2445. this.manager.emit(this.options.event + direction, input);
  2446. }
  2447. this._super.emit.call(this, input);
  2448. }
  2449. });
  2450. /**
  2451. * Pinch
  2452. * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
  2453. * @constructor
  2454. * @extends AttrRecognizer
  2455. */
  2456. function PinchRecognizer() {
  2457. AttrRecognizer.apply(this, arguments);
  2458. }
  2459. inherit(PinchRecognizer, AttrRecognizer, {
  2460. /**
  2461. * @namespace
  2462. * @memberof PinchRecognizer
  2463. */
  2464. defaults: {
  2465. event: "pinch",
  2466. threshold: 0,
  2467. pointers: 2
  2468. },
  2469. getTouchAction: function() {
  2470. return [ TOUCH_ACTION_NONE ];
  2471. },
  2472. attrTest: function(input) {
  2473. return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
  2474. },
  2475. emit: function(input) {
  2476. this._super.emit.call(this, input);
  2477. if (input.scale !== 1) {
  2478. var inOut = input.scale < 1 ? "in" : "out";
  2479. this.manager.emit(this.options.event + inOut, input);
  2480. }
  2481. }
  2482. });
  2483. /**
  2484. * Press
  2485. * Recognized when the pointer is down for x ms without any movement.
  2486. * @constructor
  2487. * @extends Recognizer
  2488. */
  2489. function PressRecognizer() {
  2490. Recognizer.apply(this, arguments);
  2491. this._timer = null;
  2492. this._input = null;
  2493. }
  2494. inherit(PressRecognizer, Recognizer, {
  2495. /**
  2496. * @namespace
  2497. * @memberof PressRecognizer
  2498. */
  2499. defaults: {
  2500. event: "press",
  2501. pointers: 1,
  2502. time: 500,
  2503. // minimal time of the pointer to be pressed
  2504. threshold: 5
  2505. },
  2506. getTouchAction: function() {
  2507. return [ TOUCH_ACTION_AUTO ];
  2508. },
  2509. process: function(input) {
  2510. var options = this.options;
  2511. var validPointers = input.pointers.length === options.pointers;
  2512. var validMovement = input.distance < options.threshold;
  2513. var validTime = input.deltaTime > options.time;
  2514. this._input = input;
  2515. // we only allow little movement
  2516. // and we've reached an end event, so a tap is possible
  2517. if (!validMovement || !validPointers || input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime) {
  2518. this.reset();
  2519. } else if (input.eventType & INPUT_START) {
  2520. this.reset();
  2521. this._timer = setTimeoutContext(function() {
  2522. this.state = STATE_RECOGNIZED;
  2523. this.tryEmit();
  2524. }, options.time, this);
  2525. } else if (input.eventType & INPUT_END) {
  2526. return STATE_RECOGNIZED;
  2527. }
  2528. return STATE_FAILED;
  2529. },
  2530. reset: function() {
  2531. clearTimeout(this._timer);
  2532. },
  2533. emit: function(input) {
  2534. if (this.state !== STATE_RECOGNIZED) {
  2535. return;
  2536. }
  2537. if (input && input.eventType & INPUT_END) {
  2538. this.manager.emit(this.options.event + "up", input);
  2539. } else {
  2540. this._input.timeStamp = now();
  2541. this.manager.emit(this.options.event, this._input);
  2542. }
  2543. }
  2544. });
  2545. /**
  2546. * Rotate
  2547. * Recognized when two or more pointer are moving in a circular motion.
  2548. * @constructor
  2549. * @extends AttrRecognizer
  2550. */
  2551. function RotateRecognizer() {
  2552. AttrRecognizer.apply(this, arguments);
  2553. }
  2554. inherit(RotateRecognizer, AttrRecognizer, {
  2555. /**
  2556. * @namespace
  2557. * @memberof RotateRecognizer
  2558. */
  2559. defaults: {
  2560. event: "rotate",
  2561. threshold: 0,
  2562. pointers: 2
  2563. },
  2564. getTouchAction: function() {
  2565. return [ TOUCH_ACTION_NONE ];
  2566. },
  2567. attrTest: function(input) {
  2568. return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
  2569. }
  2570. });
  2571. /**
  2572. * Swipe
  2573. * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
  2574. * @constructor
  2575. * @extends AttrRecognizer
  2576. */
  2577. function SwipeRecognizer() {
  2578. AttrRecognizer.apply(this, arguments);
  2579. }
  2580. inherit(SwipeRecognizer, AttrRecognizer, {
  2581. /**
  2582. * @namespace
  2583. * @memberof SwipeRecognizer
  2584. */
  2585. defaults: {
  2586. event: "swipe",
  2587. threshold: 10,
  2588. velocity: .65,
  2589. direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
  2590. pointers: 1
  2591. },
  2592. getTouchAction: function() {
  2593. return PanRecognizer.prototype.getTouchAction.call(this);
  2594. },
  2595. attrTest: function(input) {
  2596. var direction = this.options.direction;
  2597. var velocity;
  2598. if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
  2599. velocity = input.velocity;
  2600. } else if (direction & DIRECTION_HORIZONTAL) {
  2601. velocity = input.velocityX;
  2602. } else if (direction & DIRECTION_VERTICAL) {
  2603. velocity = input.velocityY;
  2604. }
  2605. return this._super.attrTest.call(this, input) && direction & input.direction && input.distance > this.options.threshold && abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
  2606. },
  2607. emit: function(input) {
  2608. var direction = directionStr(input.direction);
  2609. if (direction) {
  2610. this.manager.emit(this.options.event + direction, input);
  2611. }
  2612. this.manager.emit(this.options.event, input);
  2613. }
  2614. });
  2615. /**
  2616. * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
  2617. * between the given interval and position. The delay option can be used to recognize multi-taps without firing
  2618. * a single tap.
  2619. *
  2620. * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
  2621. * multi-taps being recognized.
  2622. * @constructor
  2623. * @extends Recognizer
  2624. */
  2625. function TapRecognizer() {
  2626. Recognizer.apply(this, arguments);
  2627. // previous time and center,
  2628. // used for tap counting
  2629. this.pTime = false;
  2630. this.pCenter = false;
  2631. this._timer = null;
  2632. this._input = null;
  2633. this.count = 0;
  2634. }
  2635. inherit(TapRecognizer, Recognizer, {
  2636. /**
  2637. * @namespace
  2638. * @memberof PinchRecognizer
  2639. */
  2640. defaults: {
  2641. event: "tap",
  2642. pointers: 1,
  2643. taps: 1,
  2644. interval: 300,
  2645. // max time between the multi-tap taps
  2646. time: 250,
  2647. // max time of the pointer to be down (like finger on the screen)
  2648. threshold: 2,
  2649. // a minimal movement is ok, but keep it low
  2650. posThreshold: 10
  2651. },
  2652. getTouchAction: function() {
  2653. return [ TOUCH_ACTION_MANIPULATION ];
  2654. },
  2655. process: function(input) {
  2656. var options = this.options;
  2657. var validPointers = input.pointers.length === options.pointers;
  2658. var validMovement = input.distance < options.threshold;
  2659. var validTouchTime = input.deltaTime < options.time;
  2660. this.reset();
  2661. if (input.eventType & INPUT_START && this.count === 0) {
  2662. return this.failTimeout();
  2663. }
  2664. // we only allow little movement
  2665. // and we've reached an end event, so a tap is possible
  2666. if (validMovement && validTouchTime && validPointers) {
  2667. if (input.eventType != INPUT_END) {
  2668. return this.failTimeout();
  2669. }
  2670. var validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;
  2671. var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
  2672. this.pTime = input.timeStamp;
  2673. this.pCenter = input.center;
  2674. if (!validMultiTap || !validInterval) {
  2675. this.count = 1;
  2676. } else {
  2677. this.count += 1;
  2678. }
  2679. this._input = input;
  2680. // if tap count matches we have recognized it,
  2681. // else it has began recognizing...
  2682. var tapCount = this.count % options.taps;
  2683. if (tapCount === 0) {
  2684. // no failing requirements, immediately trigger the tap event
  2685. // or wait as long as the multitap interval to trigger
  2686. if (!this.hasRequireFailures()) {
  2687. return STATE_RECOGNIZED;
  2688. } else {
  2689. this._timer = setTimeoutContext(function() {
  2690. this.state = STATE_RECOGNIZED;
  2691. this.tryEmit();
  2692. }, options.interval, this);
  2693. return STATE_BEGAN;
  2694. }
  2695. }
  2696. }
  2697. return STATE_FAILED;
  2698. },
  2699. failTimeout: function() {
  2700. this._timer = setTimeoutContext(function() {
  2701. this.state = STATE_FAILED;
  2702. }, this.options.interval, this);
  2703. return STATE_FAILED;
  2704. },
  2705. reset: function() {
  2706. clearTimeout(this._timer);
  2707. },
  2708. emit: function() {
  2709. if (this.state == STATE_RECOGNIZED) {
  2710. this._input.tapCount = this.count;
  2711. this.manager.emit(this.options.event, this._input);
  2712. }
  2713. }
  2714. });
  2715. /**
  2716. * Simple way to create an manager with a default set of recognizers.
  2717. * @param {HTMLElement} element
  2718. * @param {Object} [options]
  2719. * @constructor
  2720. */
  2721. function Hammer(element, options) {
  2722. options = options || {};
  2723. options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
  2724. return new Manager(element, options);
  2725. }
  2726. /**
  2727. * @const {string}
  2728. */
  2729. Hammer.VERSION = "2.0.3";
  2730. /**
  2731. * default settings
  2732. * @namespace
  2733. */
  2734. Hammer.defaults = {
  2735. /**
  2736. * set if DOM events are being triggered.
  2737. * But this is slower and unused by simple implementations, so disabled by default.
  2738. * @type {Boolean}
  2739. * @default false
  2740. */
  2741. domEvents: false,
  2742. /**
  2743. * The value for the touchAction property/fallback.
  2744. * When set to `compute` it will magically set the correct value based on the added recognizers.
  2745. * @type {String}
  2746. * @default compute
  2747. */
  2748. touchAction: TOUCH_ACTION_COMPUTE,
  2749. /**
  2750. * @type {Boolean}
  2751. * @default true
  2752. */
  2753. enable: true,
  2754. /**
  2755. * EXPERIMENTAL FEATURE -- can be removed/changed
  2756. * Change the parent input target element.
  2757. * If Null, then it is being set the to main element.
  2758. * @type {Null|EventTarget}
  2759. * @default null
  2760. */
  2761. inputTarget: null,
  2762. /**
  2763. * force an input class
  2764. * @type {Null|Function}
  2765. * @default null
  2766. */
  2767. inputClass: null,
  2768. /**
  2769. * Default recognizer setup when calling `Hammer()`
  2770. * When creating a new Manager these will be skipped.
  2771. * @type {Array}
  2772. */
  2773. preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
  2774. [ RotateRecognizer, {
  2775. enable: false
  2776. } ], [ PinchRecognizer, {
  2777. enable: false
  2778. }, [ "rotate" ] ], [ SwipeRecognizer, {
  2779. direction: DIRECTION_HORIZONTAL
  2780. } ], [ PanRecognizer, {
  2781. direction: DIRECTION_HORIZONTAL
  2782. }, [ "swipe" ] ], [ TapRecognizer ], [ TapRecognizer, {
  2783. event: "doubletap",
  2784. taps: 2
  2785. }, [ "tap" ] ], [ PressRecognizer ] ],
  2786. /**
  2787. * Some CSS properties can be used to improve the working of Hammer.
  2788. * Add them to this method and they will be set when creating a new Manager.
  2789. * @namespace
  2790. */
  2791. cssProps: {
  2792. /**
  2793. * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
  2794. * @type {String}
  2795. * @default 'none'
  2796. */
  2797. userSelect: "none",
  2798. /**
  2799. * Disable the Windows Phone grippers when pressing an element.
  2800. * @type {String}
  2801. * @default 'none'
  2802. */
  2803. touchSelect: "none",
  2804. /**
  2805. * Disables the default callout shown when you touch and hold a touch target.
  2806. * On iOS, when you touch and hold a touch target such as a link, Safari displays
  2807. * a callout containing information about the link. This property allows you to disable that callout.
  2808. * @type {String}
  2809. * @default 'none'
  2810. */
  2811. touchCallout: "none",
  2812. /**
  2813. * Specifies whether zooming is enabled. Used by IE10>
  2814. * @type {String}
  2815. * @default 'none'
  2816. */
  2817. contentZooming: "none",
  2818. /**
  2819. * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
  2820. * @type {String}
  2821. * @default 'none'
  2822. */
  2823. userDrag: "none",
  2824. /**
  2825. * Overrides the highlight color shown when the user taps a link or a JavaScript
  2826. * clickable element in iOS. This property obeys the alpha value, if specified.
  2827. * @type {String}
  2828. * @default 'rgba(0,0,0,0)'
  2829. */
  2830. tapHighlightColor: "rgba(0,0,0,0)"
  2831. }
  2832. };
  2833. var STOP = 1;
  2834. var FORCED_STOP = 2;
  2835. /**
  2836. * Manager
  2837. * @param {HTMLElement} element
  2838. * @param {Object} [options]
  2839. * @constructor
  2840. */
  2841. function Manager(element, options) {
  2842. options = options || {};
  2843. this.options = merge(options, Hammer.defaults);
  2844. this.options.inputTarget = this.options.inputTarget || element;
  2845. this.handlers = {};
  2846. this.session = {};
  2847. this.recognizers = [];
  2848. this.element = element;
  2849. this.input = createInputInstance(this);
  2850. this.touchAction = new TouchAction(this, this.options.touchAction);
  2851. toggleCssProps(this, true);
  2852. each(options.recognizers, function(item) {
  2853. var recognizer = this.add(new item[0](item[1]));
  2854. item[2] && recognizer.recognizeWith(item[2]);
  2855. item[3] && recognizer.requireFailure(item[3]);
  2856. }, this);
  2857. }
  2858. Manager.prototype = {
  2859. /**
  2860. * set options
  2861. * @param {Object} options
  2862. * @returns {Manager}
  2863. */
  2864. set: function(options) {
  2865. extend(this.options, options);
  2866. // Options that need a little more setup
  2867. if (options.touchAction) {
  2868. this.touchAction.update();
  2869. }
  2870. if (options.inputTarget) {
  2871. // Clean up existing event listeners and reinitialize
  2872. this.input.destroy();
  2873. this.input.target = options.inputTarget;
  2874. this.input.init();
  2875. }
  2876. return this;
  2877. },
  2878. /**
  2879. * stop recognizing for this session.
  2880. * This session will be discarded, when a new [input]start event is fired.
  2881. * When forced, the recognizer cycle is stopped immediately.
  2882. * @param {Boolean} [force]
  2883. */
  2884. stop: function(force) {
  2885. this.session.stopped = force ? FORCED_STOP : STOP;
  2886. },
  2887. /**
  2888. * run the recognizers!
  2889. * called by the inputHandler function on every movement of the pointers (touches)
  2890. * it walks through all the recognizers and tries to detect the gesture that is being made
  2891. * @param {Object} inputData
  2892. */
  2893. recognize: function(inputData) {
  2894. var session = this.session;
  2895. if (session.stopped) {
  2896. return;
  2897. }
  2898. // run the touch-action polyfill
  2899. this.touchAction.preventDefaults(inputData);
  2900. var recognizer;
  2901. var recognizers = this.recognizers;
  2902. // this holds the recognizer that is being recognized.
  2903. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
  2904. // if no recognizer is detecting a thing, it is set to `null`
  2905. var curRecognizer = session.curRecognizer;
  2906. // reset when the last recognizer is recognized
  2907. // or when we're in a new session
  2908. if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {
  2909. curRecognizer = session.curRecognizer = null;
  2910. }
  2911. var i = 0;
  2912. while (i < recognizers.length) {
  2913. recognizer = recognizers[i];
  2914. // find out if we are allowed try to recognize the input for this one.
  2915. // 1. allow if the session is NOT forced stopped (see the .stop() method)
  2916. // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
  2917. // that is being recognized.
  2918. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
  2919. // this can be setup with the `recognizeWith()` method on the recognizer.
  2920. if (session.stopped !== FORCED_STOP && (// 1
  2921. !curRecognizer || recognizer == curRecognizer || // 2
  2922. recognizer.canRecognizeWith(curRecognizer))) {
  2923. // 3
  2924. recognizer.recognize(inputData);
  2925. } else {
  2926. recognizer.reset();
  2927. }
  2928. // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
  2929. // current active recognizer. but only if we don't already have an active recognizer
  2930. if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
  2931. curRecognizer = session.curRecognizer = recognizer;
  2932. }
  2933. i++;
  2934. }
  2935. },
  2936. /**
  2937. * get a recognizer by its event name.
  2938. * @param {Recognizer|String} recognizer
  2939. * @returns {Recognizer|Null}
  2940. */
  2941. get: function(recognizer) {
  2942. if (recognizer instanceof Recognizer) {
  2943. return recognizer;
  2944. }
  2945. var recognizers = this.recognizers;
  2946. for (var i = 0; i < recognizers.length; i++) {
  2947. if (recognizers[i].options.event == recognizer) {
  2948. return recognizers[i];
  2949. }
  2950. }
  2951. return null;
  2952. },
  2953. /**
  2954. * add a recognizer to the manager
  2955. * existing recognizers with the same event name will be removed
  2956. * @param {Recognizer} recognizer
  2957. * @returns {Recognizer|Manager}
  2958. */
  2959. add: function(recognizer) {
  2960. if (invokeArrayArg(recognizer, "add", this)) {
  2961. return this;
  2962. }
  2963. // remove existing
  2964. var existing = this.get(recognizer.options.event);
  2965. if (existing) {
  2966. this.remove(existing);
  2967. }
  2968. this.recognizers.push(recognizer);
  2969. recognizer.manager = this;
  2970. this.touchAction.update();
  2971. return recognizer;
  2972. },
  2973. /**
  2974. * remove a recognizer by name or instance
  2975. * @param {Recognizer|String} recognizer
  2976. * @returns {Manager}
  2977. */
  2978. remove: function(recognizer) {
  2979. if (invokeArrayArg(recognizer, "remove", this)) {
  2980. return this;
  2981. }
  2982. var recognizers = this.recognizers;
  2983. recognizer = this.get(recognizer);
  2984. recognizers.splice(inArray(recognizers, recognizer), 1);
  2985. this.touchAction.update();
  2986. return this;
  2987. },
  2988. /**
  2989. * bind event
  2990. * @param {String} events
  2991. * @param {Function} handler
  2992. * @returns {EventEmitter} this
  2993. */
  2994. on: function(events, handler) {
  2995. var handlers = this.handlers;
  2996. each(splitStr(events), function(event) {
  2997. handlers[event] = handlers[event] || [];
  2998. handlers[event].push(handler);
  2999. });
  3000. return this;
  3001. },
  3002. /**
  3003. * unbind event, leave emit blank to remove all handlers
  3004. * @param {String} events
  3005. * @param {Function} [handler]
  3006. * @returns {EventEmitter} this
  3007. */
  3008. off: function(events, handler) {
  3009. var handlers = this.handlers;
  3010. each(splitStr(events), function(event) {
  3011. if (!handler) {
  3012. delete handlers[event];
  3013. } else {
  3014. handlers[event].splice(inArray(handlers[event], handler), 1);
  3015. }
  3016. });
  3017. return this;
  3018. },
  3019. /**
  3020. * emit event to the listeners
  3021. * @param {String} event
  3022. * @param {Object} data
  3023. */
  3024. emit: function(event, data) {
  3025. // we also want to trigger dom events
  3026. if (this.options.domEvents) {
  3027. triggerDomEvent(event, data);
  3028. }
  3029. // no handlers, so skip it all
  3030. var handlers = this.handlers[event] && this.handlers[event].slice();
  3031. if (!handlers || !handlers.length) {
  3032. return;
  3033. }
  3034. data.type = event;
  3035. data.preventDefault = function() {
  3036. data.srcEvent.preventDefault();
  3037. };
  3038. var i = 0;
  3039. while (i < handlers.length) {
  3040. handlers[i](data);
  3041. i++;
  3042. }
  3043. },
  3044. /**
  3045. * destroy the manager and unbinds all events
  3046. * it doesn't unbind dom events, that is the user own responsibility
  3047. */
  3048. destroy: function() {
  3049. this.element && toggleCssProps(this, false);
  3050. this.handlers = {};
  3051. this.session = {};
  3052. this.input.destroy();
  3053. this.element = null;
  3054. }
  3055. };
  3056. /**
  3057. * add/remove the css properties as defined in manager.options.cssProps
  3058. * @param {Manager} manager
  3059. * @param {Boolean} add
  3060. */
  3061. function toggleCssProps(manager, add) {
  3062. var element = manager.element;
  3063. each(manager.options.cssProps, function(value, name) {
  3064. element.style[prefixed(element.style, name)] = add ? value : "";
  3065. });
  3066. }
  3067. /**
  3068. * trigger dom event
  3069. * @param {String} event
  3070. * @param {Object} data
  3071. */
  3072. function triggerDomEvent(event, data) {
  3073. var gestureEvent = document.createEvent("Event");
  3074. gestureEvent.initEvent(event, true, true);
  3075. gestureEvent.gesture = data;
  3076. data.target.dispatchEvent(gestureEvent);
  3077. }
  3078. extend(Hammer, {
  3079. INPUT_START: INPUT_START,
  3080. INPUT_MOVE: INPUT_MOVE,
  3081. INPUT_END: INPUT_END,
  3082. INPUT_CANCEL: INPUT_CANCEL,
  3083. STATE_POSSIBLE: STATE_POSSIBLE,
  3084. STATE_BEGAN: STATE_BEGAN,
  3085. STATE_CHANGED: STATE_CHANGED,
  3086. STATE_ENDED: STATE_ENDED,
  3087. STATE_RECOGNIZED: STATE_RECOGNIZED,
  3088. STATE_CANCELLED: STATE_CANCELLED,
  3089. STATE_FAILED: STATE_FAILED,
  3090. DIRECTION_NONE: DIRECTION_NONE,
  3091. DIRECTION_LEFT: DIRECTION_LEFT,
  3092. DIRECTION_RIGHT: DIRECTION_RIGHT,
  3093. DIRECTION_UP: DIRECTION_UP,
  3094. DIRECTION_DOWN: DIRECTION_DOWN,
  3095. DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
  3096. DIRECTION_VERTICAL: DIRECTION_VERTICAL,
  3097. DIRECTION_ALL: DIRECTION_ALL,
  3098. Manager: Manager,
  3099. Input: Input,
  3100. TouchAction: TouchAction,
  3101. TouchInput: TouchInput,
  3102. MouseInput: MouseInput,
  3103. PointerEventInput: PointerEventInput,
  3104. TouchMouseInput: TouchMouseInput,
  3105. Recognizer: Recognizer,
  3106. AttrRecognizer: AttrRecognizer,
  3107. Tap: TapRecognizer,
  3108. Pan: PanRecognizer,
  3109. Swipe: SwipeRecognizer,
  3110. Pinch: PinchRecognizer,
  3111. Rotate: RotateRecognizer,
  3112. Press: PressRecognizer,
  3113. on: addEventListeners,
  3114. off: removeEventListeners,
  3115. each: each,
  3116. merge: merge,
  3117. extend: extend,
  3118. inherit: inherit,
  3119. bindFn: bindFn,
  3120. prefixed: prefixed
  3121. });
  3122. UI.hammer = Hammer;
  3123. module.exports = Hammer;
  3124. function hammerify(el, options) {
  3125. var $el = $(el);
  3126. if (!$el.data("hammer")) {
  3127. $el.data("hammer", new Hammer($el[0], options));
  3128. }
  3129. }
  3130. // extend the emit method to also trigger jQuery events
  3131. Hammer.Manager.prototype.emit = function(originalEmit) {
  3132. return function(type, data) {
  3133. originalEmit.call(this, type, data);
  3134. // console.log('trigger....%s', type);
  3135. $(this.element).trigger({
  3136. type: type,
  3137. gesture: data
  3138. });
  3139. };
  3140. }(Hammer.Manager.prototype.emit);
  3141. $.fn.hammer = function(options) {
  3142. return this.each(function() {
  3143. hammerify(this, options);
  3144. });
  3145. };
  3146. });
  3147. define("zepto.outerdemension", [], function(require, exports, module) {
  3148. var $ = window.Zepto;
  3149. // Create outerHeight and outerWidth methods
  3150. [ "width", "height" ].forEach(function(dimension) {
  3151. var offset, Dimension = dimension.replace(/./, function(m) {
  3152. return m[0].toUpperCase();
  3153. });
  3154. $.fn["outer" + Dimension] = function(margin) {
  3155. var elem = this;
  3156. if (elem) {
  3157. var size = elem[dimension]();
  3158. var sides = {
  3159. width: [ "left", "right" ],
  3160. height: [ "top", "bottom" ]
  3161. };
  3162. sides[dimension].forEach(function(side) {
  3163. if (margin) size += parseInt(elem.css("margin-" + side), 10);
  3164. });
  3165. return size;
  3166. } else {
  3167. return null;
  3168. }
  3169. };
  3170. });
  3171. });
  3172. define("zepto.extend.data", [], function(require, exports, module) {
  3173. var $ = window.Zepto;
  3174. // Zepto.js
  3175. // (c) 2010-2014 Thomas Fuchs
  3176. // Zepto.js may be freely distributed under the MIT license.
  3177. // The following code is heavily inspired by jQuery's $.fn.data()
  3178. var data = {}, dataAttr = $.fn.data, camelize = $.camelCase, exp = $.expando = "Zepto" + +new Date(), emptyArray = [];
  3179. // Get value from node:
  3180. // 1. first try key as given,
  3181. // 2. then try camelized key,
  3182. // 3. fall back to reading "data-*" attribute.
  3183. function getData(node, name) {
  3184. var id = node[exp], store = id && data[id];
  3185. if (name === undefined) return store || setData(node); else {
  3186. if (store) {
  3187. if (name in store) return store[name];
  3188. var camelName = camelize(name);
  3189. if (camelName in store) return store[camelName];
  3190. }
  3191. return dataAttr.call($(node), name);
  3192. }
  3193. }
  3194. // Store value under camelized key on node
  3195. function setData(node, name, value) {
  3196. var id = node[exp] || (node[exp] = ++$.uuid), store = data[id] || (data[id] = attributeData(node));
  3197. if (name !== undefined) store[camelize(name)] = value;
  3198. return store;
  3199. }
  3200. // Read all "data-*" attributes from a node
  3201. function attributeData(node) {
  3202. var store = {};
  3203. $.each(node.attributes || emptyArray, function(i, attr) {
  3204. if (attr.name.indexOf("data-") == 0) store[camelize(attr.name.replace("data-", ""))] = $.zepto.deserializeValue(attr.value);
  3205. });
  3206. return store;
  3207. }
  3208. $.fn.data = function(name, value) {
  3209. return value === undefined ? // set multiple values via object
  3210. $.isPlainObject(name) ? this.each(function(i, node) {
  3211. $.each(name, function(key, value) {
  3212. setData(node, key, value);
  3213. });
  3214. }) : // get value from first element
  3215. 0 in this ? getData(this[0], name) : undefined : // set value on all elements
  3216. this.each(function() {
  3217. setData(this, name, value);
  3218. });
  3219. };
  3220. $.fn.removeData = function(names) {
  3221. if (typeof names == "string") names = names.split(/\s+/);
  3222. return this.each(function() {
  3223. var id = this[exp], store = id && data[id];
  3224. if (store) $.each(names || store, function(key) {
  3225. delete store[names ? camelize(this) : key];
  3226. });
  3227. });
  3228. };
  3229. [ "remove", "empty" ].forEach(function(methodName) {
  3230. var origFn = $.fn[methodName];
  3231. $.fn[methodName] = function() {
  3232. var elements = this.find("*");
  3233. if (methodName === "remove") elements = elements.add(this);
  3234. elements.removeData();
  3235. return origFn.call(this);
  3236. };
  3237. });
  3238. });
  3239. define("zepto.extend.fx", [], function(require, exports, module) {
  3240. var $ = window.Zepto;
  3241. // Zepto.js
  3242. // (c) 2010-2014 Thomas Fuchs
  3243. // Zepto.js may be freely distributed under the MIT license.
  3244. var prefix = "", eventPrefix, endEventName, endAnimationName, vendors = {
  3245. Webkit: "webkit",
  3246. Moz: "",
  3247. O: "o"
  3248. }, document = window.document, testEl = document.createElement("div"), supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i, transform, transitionProperty, transitionDuration, transitionTiming, transitionDelay, animationName, animationDuration, animationTiming, animationDelay, cssReset = {};
  3249. function dasherize(str) {
  3250. return str.replace(/([a-z])([A-Z])/, "$1-$2").toLowerCase();
  3251. }
  3252. function normalizeEvent(name) {
  3253. return eventPrefix ? eventPrefix + name : name.toLowerCase();
  3254. }
  3255. $.each(vendors, function(vendor, event) {
  3256. if (testEl.style[vendor + "TransitionProperty"] !== undefined) {
  3257. prefix = "-" + vendor.toLowerCase() + "-";
  3258. eventPrefix = event;
  3259. return false;
  3260. }
  3261. });
  3262. transform = prefix + "transform";
  3263. cssReset[transitionProperty = prefix + "transition-property"] = cssReset[transitionDuration = prefix + "transition-duration"] = cssReset[transitionDelay = prefix + "transition-delay"] = cssReset[transitionTiming = prefix + "transition-timing-function"] = cssReset[animationName = prefix + "animation-name"] = cssReset[animationDuration = prefix + "animation-duration"] = cssReset[animationDelay = prefix + "animation-delay"] = cssReset[animationTiming = prefix + "animation-timing-function"] = "";
  3264. $.fx = {
  3265. off: eventPrefix === undefined && testEl.style.transitionProperty === undefined,
  3266. speeds: {
  3267. _default: 400,
  3268. fast: 200,
  3269. slow: 600
  3270. },
  3271. cssPrefix: prefix,
  3272. transitionEnd: normalizeEvent("TransitionEnd"),
  3273. animationEnd: normalizeEvent("AnimationEnd")
  3274. };
  3275. $.fn.animate = function(properties, duration, ease, callback, delay) {
  3276. if ($.isFunction(duration)) callback = duration, ease = undefined, duration = undefined;
  3277. if ($.isFunction(ease)) callback = ease, ease = undefined;
  3278. if ($.isPlainObject(duration)) ease = duration.easing, callback = duration.complete,
  3279. delay = duration.delay, duration = duration.duration;
  3280. if (duration) duration = (typeof duration == "number" ? duration : $.fx.speeds[duration] || $.fx.speeds._default) / 1e3;
  3281. if (delay) delay = parseFloat(delay) / 1e3;
  3282. return this.anim(properties, duration, ease, callback, delay);
  3283. };
  3284. $.fn.anim = function(properties, duration, ease, callback, delay) {
  3285. var key, cssValues = {}, cssProperties, transforms = "", that = this, wrappedCallback, endEvent = $.fx.transitionEnd, fired = false;
  3286. if (duration === undefined) duration = $.fx.speeds._default / 1e3;
  3287. if (delay === undefined) delay = 0;
  3288. if ($.fx.off) duration = 0;
  3289. if (typeof properties == "string") {
  3290. // keyframe animation
  3291. cssValues[animationName] = properties;
  3292. cssValues[animationDuration] = duration + "s";
  3293. cssValues[animationDelay] = delay + "s";
  3294. cssValues[animationTiming] = ease || "linear";
  3295. endEvent = $.fx.animationEnd;
  3296. } else {
  3297. cssProperties = [];
  3298. // CSS transitions
  3299. for (key in properties) if (supportedTransforms.test(key)) transforms += key + "(" + properties[key] + ") "; else cssValues[key] = properties[key],
  3300. cssProperties.push(dasherize(key));
  3301. if (transforms) cssValues[transform] = transforms, cssProperties.push(transform);
  3302. if (duration > 0 && typeof properties === "object") {
  3303. cssValues[transitionProperty] = cssProperties.join(", ");
  3304. cssValues[transitionDuration] = duration + "s";
  3305. cssValues[transitionDelay] = delay + "s";
  3306. cssValues[transitionTiming] = ease || "linear";
  3307. }
  3308. }
  3309. wrappedCallback = function(event) {
  3310. if (typeof event !== "undefined") {
  3311. if (event.target !== event.currentTarget) return;
  3312. // makes sure the event didn't bubble from "below"
  3313. $(event.target).unbind(endEvent, wrappedCallback);
  3314. } else $(this).unbind(endEvent, wrappedCallback);
  3315. // triggered by setTimeout
  3316. fired = true;
  3317. $(this).css(cssReset);
  3318. callback && callback.call(this);
  3319. };
  3320. if (duration > 0) {
  3321. this.bind(endEvent, wrappedCallback);
  3322. // transitionEnd is not always firing on older Android phones
  3323. // so make sure it gets fired
  3324. setTimeout(function() {
  3325. if (fired) return;
  3326. wrappedCallback.call(that);
  3327. }, duration * 1e3 + 25);
  3328. }
  3329. // trigger page reflow so new elements can animate
  3330. this.size() && this.get(0).clientLeft;
  3331. this.css(cssValues);
  3332. if (duration <= 0) setTimeout(function() {
  3333. that.each(function() {
  3334. wrappedCallback.call(this);
  3335. });
  3336. }, 0);
  3337. return this;
  3338. };
  3339. testEl = null;
  3340. });
  3341. define("zepto.extend.selector", [], function(require, exports, module) {
  3342. var $ = window.Zepto;
  3343. // Zepto.js
  3344. // (c) 2010-2014 Thomas Fuchs
  3345. // Zepto.js may be freely distributed under the MIT license.
  3346. var zepto = $.zepto, oldQsa = zepto.qsa, oldMatches = zepto.matches;
  3347. function visible(elem) {
  3348. elem = $(elem);
  3349. return !!(elem.width() || elem.height()) && elem.css("display") !== "none";
  3350. }
  3351. // Implements a subset from:
  3352. // http://api.jquery.com/category/selectors/jquery-selector-extensions/
  3353. //
  3354. // Each filter function receives the current index, all nodes in the
  3355. // considered set, and a value if there were parentheses. The value
  3356. // of `this` is the node currently being considered. The function returns the
  3357. // resulting node(s), null, or undefined.
  3358. //
  3359. // Complex selectors are not supported:
  3360. // li:has(label:contains("foo")) + li:has(label:contains("bar"))
  3361. // ul.inner:first > li
  3362. var filters = $.expr[":"] = {
  3363. visible: function() {
  3364. if (visible(this)) return this;
  3365. },
  3366. hidden: function() {
  3367. if (!visible(this)) return this;
  3368. },
  3369. selected: function() {
  3370. if (this.selected) return this;
  3371. },
  3372. checked: function() {
  3373. if (this.checked) return this;
  3374. },
  3375. parent: function() {
  3376. return this.parentNode;
  3377. },
  3378. first: function(idx) {
  3379. if (idx === 0) return this;
  3380. },
  3381. last: function(idx, nodes) {
  3382. if (idx === nodes.length - 1) return this;
  3383. },
  3384. eq: function(idx, _, value) {
  3385. if (idx === value) return this;
  3386. },
  3387. contains: function(idx, _, text) {
  3388. if ($(this).text().indexOf(text) > -1) return this;
  3389. },
  3390. has: function(idx, _, sel) {
  3391. if (zepto.qsa(this, sel).length) return this;
  3392. }
  3393. };
  3394. var filterRe = new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"), childRe = /^\s*>/, classTag = "Zepto" + +new Date();
  3395. function process(sel, fn) {
  3396. // quote the hash in `a[href^=#]` expression
  3397. sel = sel.replace(/=#\]/g, '="#"]');
  3398. var filter, arg, match = filterRe.exec(sel);
  3399. if (match && match[2] in filters) {
  3400. filter = filters[match[2]], arg = match[3];
  3401. sel = match[1];
  3402. if (arg) {
  3403. var num = Number(arg);
  3404. if (isNaN(num)) arg = arg.replace(/^["']|["']$/g, ""); else arg = num;
  3405. }
  3406. }
  3407. return fn(sel, filter, arg);
  3408. }
  3409. zepto.qsa = function(node, selector) {
  3410. return process(selector, function(sel, filter, arg) {
  3411. try {
  3412. var taggedParent;
  3413. if (!sel && filter) sel = "*"; else if (childRe.test(sel)) // support "> *" child queries by tagging the parent node with a
  3414. // unique class and prepending that classname onto the selector
  3415. taggedParent = $(node).addClass(classTag), sel = "." + classTag + " " + sel;
  3416. var nodes = oldQsa(node, sel);
  3417. } catch (e) {
  3418. console.error("error performing selector: %o", selector);
  3419. throw e;
  3420. } finally {
  3421. if (taggedParent) taggedParent.removeClass(classTag);
  3422. }
  3423. return !filter ? nodes : zepto.uniq($.map(nodes, function(n, i) {
  3424. return filter.call(n, i, nodes, arg);
  3425. }));
  3426. });
  3427. };
  3428. zepto.matches = function(node, selector) {
  3429. return process(selector, function(sel, filter, arg) {
  3430. return (!sel || oldMatches(node, sel)) && (!filter || filter.call(node, null, arg) === node);
  3431. });
  3432. };
  3433. });
  3434. define("ui.add2home", [], function(require, exports, module) {
  3435. "use strict";
  3436. var $ = window.Zepto;
  3437. /* jshint -W101, -W106 */
  3438. /* Add to Homescreen v3.0.8 ~ (c) 2014 Matteo Spinelli ~ @license: http://cubiq.org/license */
  3439. // Check if document is loaded, needed by autostart
  3440. var _DOMReady = false;
  3441. if (document.readyState === "complete") {
  3442. _DOMReady = true;
  3443. } else {
  3444. window.addEventListener("load", loaded, false);
  3445. }
  3446. function loaded() {
  3447. window.removeEventListener("load", loaded, false);
  3448. _DOMReady = true;
  3449. }
  3450. // regex used to detect if app has been added to the homescreen
  3451. var _reSmartURL = /\/ath(\/)?$/;
  3452. var _reQueryString = /([\?&]ath=[^&]*$|&ath=[^&]*(&))/;
  3453. // singleton
  3454. var _instance;
  3455. function ath(options) {
  3456. _instance = _instance || new ath.Class(options);
  3457. return _instance;
  3458. }
  3459. // message in all supported languages
  3460. ath.intl = {
  3461. en_us: {
  3462. message: "To add this web app to the home screen: tap %icon and then <strong>%action</strong>.",
  3463. action: {
  3464. ios: "Add to Home Screen",
  3465. android: "Add to homescreen",
  3466. windows: "pin to start"
  3467. }
  3468. },
  3469. zh_cn: {
  3470. message: "如要把应用程式加至主屏幕,请点击%icon, 然后<strong>%action</strong>",
  3471. action: {
  3472. ios: "加至主屏幕",
  3473. android: "加至主屏幕",
  3474. windows: "按住启动"
  3475. }
  3476. },
  3477. zh_tw: {
  3478. message: "如要把應用程式加至主屏幕, 請點擊%icon, 然後<strong>%action</strong>.",
  3479. action: {
  3480. ios: "加至主屏幕",
  3481. android: "加至主屏幕",
  3482. windows: "按住啟動"
  3483. }
  3484. }
  3485. };
  3486. // Add 2 characters language support (Android mostly)
  3487. for (var lang in ath.intl) {
  3488. ath.intl[lang.substr(0, 2)] = ath.intl[lang];
  3489. }
  3490. // default options
  3491. ath.defaults = {
  3492. appID: "org.cubiq.addtohome",
  3493. // local storage name (no need to change)
  3494. fontSize: 15,
  3495. // base font size, used to properly resize the popup based on viewport scale factor
  3496. debug: false,
  3497. // override browser checks
  3498. modal: false,
  3499. // prevent further actions until the message is closed
  3500. mandatory: false,
  3501. // you can't proceed if you don't add the app to the homescreen
  3502. autostart: true,
  3503. // show the message automatically
  3504. skipFirstVisit: false,
  3505. // show only to returning visitors (ie: skip the first time you visit)
  3506. startDelay: 1,
  3507. // display the message after that many seconds from page load
  3508. lifespan: 15,
  3509. // life of the message in seconds
  3510. displayPace: 1440,
  3511. // minutes before the message is shown again (0: display every time, default 24 hours)
  3512. maxDisplayCount: 0,
  3513. // absolute maximum number of times the message will be shown to the user (0: no limit)
  3514. icon: true,
  3515. // add touch icon to the message
  3516. message: "",
  3517. // the message can be customized
  3518. validLocation: [],
  3519. // list of pages where the message will be shown (array of regexes)
  3520. onInit: null,
  3521. // executed on instance creation
  3522. onShow: null,
  3523. // executed when the message is shown
  3524. onRemove: null,
  3525. // executed when the message is removed
  3526. onAdd: null,
  3527. // when the application is launched the first time from the homescreen (guesstimate)
  3528. onPrivate: null,
  3529. // executed if user is in private mode
  3530. detectHomescreen: false
  3531. };
  3532. // browser info and capability
  3533. var _ua = window.navigator.userAgent;
  3534. var _nav = window.navigator;
  3535. _extend(ath, {
  3536. hasToken: document.location.hash == "#ath" || _reSmartURL.test(document.location.href) || _reQueryString.test(document.location.search),
  3537. isRetina: window.devicePixelRatio && window.devicePixelRatio > 1,
  3538. isIDevice: /iphone|ipod|ipad/i.test(_ua),
  3539. isMobileChrome: _ua.indexOf("Android") > -1 && /Chrome\/[.0-9]*/.test(_ua),
  3540. isMobileIE: _ua.indexOf("Windows Phone") > -1,
  3541. language: _nav.language && _nav.language.toLowerCase().replace("-", "_") || ""
  3542. });
  3543. // falls back to en_us if language is unsupported
  3544. ath.language = ath.language && ath.language in ath.intl ? ath.language : "en_us";
  3545. ath.isMobileSafari = ath.isIDevice && _ua.indexOf("Safari") > -1 && _ua.indexOf("CriOS") < 0;
  3546. ath.OS = ath.isIDevice ? "ios" : ath.isMobileChrome ? "android" : ath.isMobileIE ? "windows" : "unsupported";
  3547. ath.OSVersion = _ua.match(/(OS|Android) (\d+[_\.]\d+)/);
  3548. ath.OSVersion = ath.OSVersion && ath.OSVersion[2] ? +ath.OSVersion[2].replace("_", ".") : 0;
  3549. ath.isStandalone = window.navigator.standalone || ath.isMobileChrome && screen.height - document.documentElement.clientHeight < 40;
  3550. // TODO: check the lame polyfill
  3551. ath.isTablet = ath.isMobileSafari && _ua.indexOf("iPad") > -1 || ath.isMobileChrome && _ua.indexOf("Mobile") < 0;
  3552. ath.isCompatible = ath.isMobileSafari && ath.OSVersion >= 6 || ath.isMobileChrome;
  3553. // TODO: add winphone
  3554. var _defaultSession = {
  3555. lastDisplayTime: 0,
  3556. // last time we displayed the message
  3557. returningVisitor: false,
  3558. // is this the first time you visit
  3559. displayCount: 0,
  3560. // number of times the message has been shown
  3561. optedout: false,
  3562. // has the user opted out
  3563. added: false
  3564. };
  3565. ath.removeSession = function(appID) {
  3566. try {
  3567. localStorage.removeItem(appID || ath.defaults.appID);
  3568. } catch (e) {}
  3569. };
  3570. ath.Class = function(options) {
  3571. // merge default options with user config
  3572. this.options = _extend({}, ath.defaults);
  3573. _extend(this.options, options);
  3574. // normalize some options
  3575. this.options.mandatory = this.options.mandatory && ("standalone" in window.navigator || this.options.debug);
  3576. this.options.modal = this.options.modal || this.options.mandatory;
  3577. if (this.options.mandatory) {
  3578. this.options.startDelay = -.5;
  3579. }
  3580. this.options.detectHomescreen = this.options.detectHomescreen === true ? "hash" : this.options.detectHomescreen;
  3581. // setup the debug environment
  3582. if (this.options.debug) {
  3583. ath.isCompatible = true;
  3584. ath.OS = typeof this.options.debug == "string" ? this.options.debug : ath.OS == "unsupported" ? "android" : ath.OS;
  3585. ath.OSVersion = ath.OS == "ios" ? "8" : "4";
  3586. }
  3587. // the element the message will be appended to
  3588. this.container = document.documentElement;
  3589. // load session
  3590. this.session = localStorage.getItem(this.options.appID);
  3591. this.session = this.session ? JSON.parse(this.session) : undefined;
  3592. // user most likely came from a direct link containing our token, we don't need it and we remove it
  3593. if (ath.hasToken && (!ath.isCompatible || !this.session)) {
  3594. ath.hasToken = false;
  3595. _removeToken();
  3596. }
  3597. // the device is not supported
  3598. if (!ath.isCompatible) {
  3599. return;
  3600. }
  3601. this.session = this.session || _defaultSession;
  3602. // check if we can use the local storage
  3603. try {
  3604. localStorage.setItem(this.options.appID, JSON.stringify(this.session));
  3605. ath.hasLocalStorage = true;
  3606. } catch (e) {
  3607. // we are most likely in private mode
  3608. ath.hasLocalStorage = false;
  3609. if (this.options.onPrivate) {
  3610. this.options.onPrivate.call(this);
  3611. }
  3612. }
  3613. // check if this is a valid location
  3614. var isValidLocation = !this.options.validLocation.length;
  3615. for (var i = this.options.validLocation.length; i--; ) {
  3616. if (this.options.validLocation[i].test(document.location.href)) {
  3617. isValidLocation = true;
  3618. break;
  3619. }
  3620. }
  3621. // check compatibility with old versions of add to homescreen. Opt-out if an old session is found
  3622. if (localStorage.getItem("addToHome")) {
  3623. this.optOut();
  3624. }
  3625. // critical errors:
  3626. // user opted out, already added to the homescreen, not a valid location
  3627. if (this.session.optedout || this.session.added || !isValidLocation) {
  3628. return;
  3629. }
  3630. // check if the app is in stand alone mode
  3631. if (ath.isStandalone) {
  3632. // execute the onAdd event if we haven't already
  3633. if (!this.session.added) {
  3634. this.session.added = true;
  3635. this.updateSession();
  3636. if (this.options.onAdd && ath.hasLocalStorage) {
  3637. // double check on localstorage to avoid multiple calls to the custom event
  3638. this.options.onAdd.call(this);
  3639. }
  3640. }
  3641. return;
  3642. }
  3643. // (try to) check if the page has been added to the homescreen
  3644. if (this.options.detectHomescreen) {
  3645. // the URL has the token, we are likely coming from the homescreen
  3646. if (ath.hasToken) {
  3647. _removeToken();
  3648. // we don't actually need the token anymore, we remove it to prevent redistribution
  3649. // this is called the first time the user opens the app from the homescreen
  3650. if (!this.session.added) {
  3651. this.session.added = true;
  3652. this.updateSession();
  3653. if (this.options.onAdd && ath.hasLocalStorage) {
  3654. // double check on localstorage to avoid multiple calls to the custom event
  3655. this.options.onAdd.call(this);
  3656. }
  3657. }
  3658. return;
  3659. }
  3660. // URL doesn't have the token, so add it
  3661. if (this.options.detectHomescreen == "hash") {
  3662. history.replaceState("", window.document.title, document.location.href + "#ath");
  3663. } else if (this.options.detectHomescreen == "smartURL") {
  3664. history.replaceState("", window.document.title, document.location.href.replace(/(\/)?$/, "/ath$1"));
  3665. } else {
  3666. history.replaceState("", window.document.title, document.location.href + (document.location.search ? "&" : "?") + "ath=");
  3667. }
  3668. }
  3669. // check if this is a returning visitor
  3670. if (!this.session.returningVisitor) {
  3671. this.session.returningVisitor = true;
  3672. this.updateSession();
  3673. // we do not show the message if this is your first visit
  3674. if (this.options.skipFirstVisit) {
  3675. return;
  3676. }
  3677. }
  3678. // we do no show the message in private mode
  3679. if (!ath.hasLocalStorage) {
  3680. return;
  3681. }
  3682. // all checks passed, ready to display
  3683. this.ready = true;
  3684. if (this.options.onInit) {
  3685. this.options.onInit.call(this);
  3686. }
  3687. if (this.options.autostart) {
  3688. this.show();
  3689. }
  3690. };
  3691. ath.Class.prototype = {
  3692. // event type to method conversion
  3693. events: {
  3694. load: "_delayedShow",
  3695. error: "_delayedShow",
  3696. orientationchange: "resize",
  3697. resize: "resize",
  3698. scroll: "resize",
  3699. click: "remove",
  3700. touchmove: "_preventDefault",
  3701. transitionend: "_removeElements",
  3702. webkitTransitionEnd: "_removeElements",
  3703. MSTransitionEnd: "_removeElements"
  3704. },
  3705. handleEvent: function(e) {
  3706. var type = this.events[e.type];
  3707. if (type) {
  3708. this[type](e);
  3709. }
  3710. },
  3711. show: function(force) {
  3712. // in autostart mode wait for the document to be ready
  3713. if (this.options.autostart && !_DOMReady) {
  3714. setTimeout(this.show.bind(this), 50);
  3715. return;
  3716. }
  3717. // message already on screen
  3718. if (this.shown) {
  3719. return;
  3720. }
  3721. var now = Date.now();
  3722. var lastDisplayTime = this.session.lastDisplayTime;
  3723. if (force !== true) {
  3724. // this is needed if autostart is disabled and you programmatically call the show() method
  3725. if (!this.ready) {
  3726. return;
  3727. }
  3728. // we obey the display pace (prevent the message to popup too often)
  3729. if (now - lastDisplayTime < this.options.displayPace * 6e4) {
  3730. return;
  3731. }
  3732. // obey the maximum number of display count
  3733. if (this.options.maxDisplayCount && this.session.displayCount >= this.options.maxDisplayCount) {
  3734. return;
  3735. }
  3736. }
  3737. this.shown = true;
  3738. // increment the display count
  3739. this.session.lastDisplayTime = now;
  3740. this.session.displayCount++;
  3741. this.updateSession();
  3742. // try to get the highest resolution application icon
  3743. if (!this.applicationIcon) {
  3744. if (ath.OS == "ios") {
  3745. this.applicationIcon = document.querySelector('head link[rel^=apple-touch-icon][sizes="152x152"],head link[rel^=apple-touch-icon][sizes="144x144"],head link[rel^=apple-touch-icon][sizes="120x120"],head link[rel^=apple-touch-icon][sizes="114x114"],head link[rel^=apple-touch-icon]');
  3746. } else {
  3747. this.applicationIcon = document.querySelector('head link[rel^="shortcut icon"][sizes="196x196"],head link[rel^=apple-touch-icon]');
  3748. }
  3749. }
  3750. var message = "";
  3751. if (this.options.message in ath.intl) {
  3752. // you can force the locale
  3753. message = ath.intl[this.options.message].message.replace("%action", ath.intl[this.options.message].action[ath.OS]);
  3754. } else if (this.options.message !== "") {
  3755. // or use a custom message
  3756. message = this.options.message;
  3757. } else {
  3758. // otherwise we use our message
  3759. message = ath.intl[ath.language].message.replace("%action", ath.intl[ath.language].action[ath.OS]);
  3760. }
  3761. // add the action icon
  3762. message = "<p>" + message.replace("%icon", '<span class="ath-action-icon">icon</span>') + "</p>";
  3763. // create the message container
  3764. this.viewport = document.createElement("div");
  3765. this.viewport.className = "ath-viewport";
  3766. if (this.options.modal) {
  3767. this.viewport.className += " ath-modal";
  3768. }
  3769. if (this.options.mandatory) {
  3770. this.viewport.className += " ath-mandatory";
  3771. }
  3772. this.viewport.style.position = "absolute";
  3773. // create the actual message element
  3774. this.element = document.createElement("div");
  3775. this.element.className = "ath-container ath-" + ath.OS + " ath-" + ath.OS + (ath.OSVersion + "").substr(0, 1) + " ath-" + (ath.isTablet ? "tablet" : "phone");
  3776. this.element.style.cssText = "-webkit-transition-property:-webkit-transform,opacity;-webkit-transition-duration:0;-webkit-transform:translate3d(0,0,0);transition-property:transform,opacity;transition-duration:0;transform:translate3d(0,0,0);-webkit-transition-timing-function:ease-out";
  3777. this.element.style.webkitTransform = "translate3d(0,-" + window.innerHeight + "px,0)";
  3778. this.element.style.webkitTransitionDuration = "0s";
  3779. // add the application icon
  3780. if (this.options.icon && this.applicationIcon) {
  3781. this.element.className += " ath-icon";
  3782. this.img = document.createElement("img");
  3783. this.img.className = "ath-application-icon";
  3784. this.img.addEventListener("load", this, false);
  3785. this.img.addEventListener("error", this, false);
  3786. this.img.src = this.applicationIcon.href;
  3787. this.element.appendChild(this.img);
  3788. }
  3789. this.element.innerHTML += message;
  3790. // we are not ready to show, place the message out of sight
  3791. this.viewport.style.left = "-99999em";
  3792. // attach all elements to the DOM
  3793. this.viewport.appendChild(this.element);
  3794. this.container.appendChild(this.viewport);
  3795. // if we don't have to wait for an image to load, show the message right away
  3796. if (!this.img) {
  3797. this._delayedShow();
  3798. }
  3799. },
  3800. _delayedShow: function(e) {
  3801. setTimeout(this._show.bind(this), this.options.startDelay * 1e3 + 500);
  3802. },
  3803. _show: function() {
  3804. var that = this;
  3805. // update the viewport size and orientation
  3806. this.updateViewport();
  3807. // reposition/resize the message on orientation change
  3808. window.addEventListener("resize", this, false);
  3809. window.addEventListener("scroll", this, false);
  3810. window.addEventListener("orientationchange", this, false);
  3811. if (this.options.modal) {
  3812. // lock any other interaction
  3813. document.addEventListener("touchmove", this, true);
  3814. }
  3815. // Enable closing after 1 second
  3816. if (!this.options.mandatory) {
  3817. setTimeout(function() {
  3818. that.element.addEventListener("click", that, true);
  3819. }, 1e3);
  3820. }
  3821. // kick the animation
  3822. setTimeout(function() {
  3823. that.element.style.webkitTransform = "translate3d(0,0,0)";
  3824. that.element.style.webkitTransitionDuration = "1.2s";
  3825. }, 0);
  3826. // set the destroy timer
  3827. if (this.options.lifespan) {
  3828. this.removeTimer = setTimeout(this.remove.bind(this), this.options.lifespan * 1e3);
  3829. }
  3830. // fire the custom onShow event
  3831. if (this.options.onShow) {
  3832. this.options.onShow.call(this);
  3833. }
  3834. },
  3835. remove: function() {
  3836. clearTimeout(this.removeTimer);
  3837. // clear up the event listeners
  3838. if (this.img) {
  3839. this.img.removeEventListener("load", this, false);
  3840. this.img.removeEventListener("error", this, false);
  3841. }
  3842. window.removeEventListener("resize", this, false);
  3843. window.removeEventListener("scroll", this, false);
  3844. window.removeEventListener("orientationchange", this, false);
  3845. document.removeEventListener("touchmove", this, true);
  3846. this.element.removeEventListener("click", this, true);
  3847. // remove the message element on transition end
  3848. this.element.addEventListener("transitionend", this, false);
  3849. this.element.addEventListener("webkitTransitionEnd", this, false);
  3850. this.element.addEventListener("MSTransitionEnd", this, false);
  3851. // start the fade out animation
  3852. this.element.style.webkitTransitionDuration = "0.3s";
  3853. this.element.style.opacity = "0";
  3854. },
  3855. _removeElements: function() {
  3856. this.element.removeEventListener("transitionend", this, false);
  3857. this.element.removeEventListener("webkitTransitionEnd", this, false);
  3858. this.element.removeEventListener("MSTransitionEnd", this, false);
  3859. // remove the message from the DOM
  3860. this.container.removeChild(this.viewport);
  3861. this.shown = false;
  3862. // fire the custom onRemove event
  3863. if (this.options.onRemove) {
  3864. this.options.onRemove.call(this);
  3865. }
  3866. },
  3867. updateViewport: function() {
  3868. if (!this.shown) {
  3869. return;
  3870. }
  3871. this.viewport.style.width = window.innerWidth + "px";
  3872. this.viewport.style.height = window.innerHeight + "px";
  3873. this.viewport.style.left = window.scrollX + "px";
  3874. this.viewport.style.top = window.scrollY + "px";
  3875. var clientWidth = document.documentElement.clientWidth;
  3876. this.orientation = clientWidth > document.documentElement.clientHeight ? "landscape" : "portrait";
  3877. var screenWidth = ath.OS == "ios" ? this.orientation == "portrait" ? screen.width : screen.height : screen.width;
  3878. this.scale = screen.width > clientWidth ? 1 : screenWidth / window.innerWidth;
  3879. this.element.style.fontSize = this.options.fontSize / this.scale + "px";
  3880. },
  3881. resize: function() {
  3882. clearTimeout(this.resizeTimer);
  3883. this.resizeTimer = setTimeout(this.updateViewport.bind(this), 100);
  3884. },
  3885. updateSession: function() {
  3886. if (ath.hasLocalStorage === false) {
  3887. return;
  3888. }
  3889. localStorage.setItem(this.options.appID, JSON.stringify(this.session));
  3890. },
  3891. clearSession: function() {
  3892. this.session = _defaultSession;
  3893. this.updateSession();
  3894. },
  3895. optOut: function() {
  3896. this.session.optedout = true;
  3897. this.updateSession();
  3898. },
  3899. optIn: function() {
  3900. this.session.optedout = false;
  3901. this.updateSession();
  3902. },
  3903. clearDisplayCount: function() {
  3904. this.session.displayCount = 0;
  3905. this.updateSession();
  3906. },
  3907. _preventDefault: function(e) {
  3908. e.preventDefault();
  3909. e.stopPropagation();
  3910. }
  3911. };
  3912. // utility
  3913. function _extend(target, obj) {
  3914. for (var i in obj) {
  3915. target[i] = obj[i];
  3916. }
  3917. return target;
  3918. }
  3919. function _removeToken() {
  3920. if (document.location.hash == "#ath") {
  3921. history.replaceState("", window.document.title, document.location.href.split("#")[0]);
  3922. }
  3923. if (_reSmartURL.test(document.location.href)) {
  3924. history.replaceState("", window.document.title, document.location.href.replace(_reSmartURL, "$1"));
  3925. }
  3926. if (_reQueryString.test(document.location.search)) {
  3927. history.replaceState("", window.document.title, document.location.href.replace(_reQueryString, "$2"));
  3928. }
  3929. }
  3930. /* jshint +W101, +W106 */
  3931. $.AMUI.addToHomescreen = ath;
  3932. module.exports = ath;
  3933. });
  3934. define("ui.alert", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  3935. "use strict";
  3936. require("core");
  3937. var $ = window.Zepto;
  3938. var UI = $.AMUI;
  3939. /**
  3940. * @via https://github.com/Minwe/bootstrap/blob/master/js/alert.js
  3941. * @copyright Copyright 2013 Twitter, Inc.
  3942. * @license Apache 2.0
  3943. */
  3944. // Alert Class
  3945. // NOTE: removeElement option is unavailable now
  3946. var Alert = function(element, options) {
  3947. this.options = $.extend({}, Alert.DEFAULTS, options);
  3948. this.$element = $(element);
  3949. this.$element.addClass("am-fade am-in").on("click.alert.amui", ".am-close", $.proxy(this.close, this));
  3950. };
  3951. Alert.DEFAULTS = {
  3952. removeElement: true
  3953. };
  3954. Alert.prototype.close = function() {
  3955. var $this = $(this);
  3956. var $target = $this.hasClass("am-alert") ? $this : $this.parent(".am-alert");
  3957. $target.trigger("close:alert:amui");
  3958. $target.removeClass("am-in");
  3959. function processAlert() {
  3960. $target.trigger("closed:alert:amui").remove();
  3961. }
  3962. UI.support.transition && $target.hasClass("am-fade") ? $target.one(UI.support.transition.end, processAlert).emulateTransitionEnd(200) : processAlert();
  3963. };
  3964. // Alert Plugin
  3965. $.fn.alert = function(option) {
  3966. return this.each(function() {
  3967. var $this = $(this);
  3968. var data = $this.data("amui.alert");
  3969. var options = typeof option == "object" && option;
  3970. if (!data) {
  3971. $this.data("amui.alert", data = new Alert(this, options || {}));
  3972. }
  3973. if (typeof option == "string") {
  3974. data[option].call($this);
  3975. }
  3976. });
  3977. };
  3978. // Init code
  3979. $(document).on("click.alert.amui", "[data-am-alert]", function(e) {
  3980. var $target = $(e.target);
  3981. $(this).addClass("am-fade am-in");
  3982. $target.is(".am-close") && $(this).alert("close");
  3983. });
  3984. UI.alert = Alert;
  3985. module.exports = Alert;
  3986. });
  3987. define("ui.button", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  3988. "use strict";
  3989. require("core");
  3990. var $ = window.Zepto;
  3991. var UI = $.AMUI;
  3992. /**
  3993. * @via https://github.com/twbs/bootstrap/blob/master/js/button.js
  3994. * @copyright (c) 2011-2014 Twitter, Inc
  3995. * @license The MIT License
  3996. */
  3997. var Button = function(element, options) {
  3998. this.$element = $(element);
  3999. this.options = $.extend({}, Button.DEFAULTS, options);
  4000. this.isLoading = false;
  4001. this.hasSpinner = false;
  4002. };
  4003. Button.DEFAULTS = {
  4004. loadingText: "loading...",
  4005. className: {
  4006. loading: "am-btn-loading",
  4007. disabled: "am-disabled"
  4008. },
  4009. spinner: undefined
  4010. };
  4011. Button.prototype.setState = function(state) {
  4012. var disabled = "disabled";
  4013. var $element = this.$element;
  4014. var options = this.options;
  4015. var val = $element.is("input") ? "val" : "html";
  4016. var loadingClassName = options.className.disabled + " " + options.className.loading;
  4017. state = state + "Text";
  4018. if (!options.resetText) {
  4019. options.resetText = $element[val]();
  4020. }
  4021. // add spinner for element with html()
  4022. if (UI.support.animation && options.spinner && val === "html" && !this.hasSpinner) {
  4023. options.loadingText = '<span class="am-icon-' + options.spinner + ' am-icon-spin"></span>' + options.loadingText;
  4024. this.hasSpinner = true;
  4025. }
  4026. $element[val](options[state]);
  4027. // push to event loop to allow forms to submit
  4028. setTimeout($.proxy(function() {
  4029. if (state == "loadingText") {
  4030. $element.addClass(loadingClassName).attr(disabled, disabled);
  4031. this.isLoading = true;
  4032. } else if (this.isLoading) {
  4033. $element.removeClass(loadingClassName).removeAttr(disabled);
  4034. this.isLoading = false;
  4035. }
  4036. }, this), 0);
  4037. };
  4038. Button.prototype.toggle = function() {
  4039. var changed = true;
  4040. var $element = this.$element;
  4041. var $parent = this.$element.parent(".am-btn-group");
  4042. if ($parent.length) {
  4043. var $input = this.$element.find("input");
  4044. if ($input.prop("type") == "radio") {
  4045. if ($input.prop("checked") && $element.hasClass("am-active")) {
  4046. changed = false;
  4047. } else {
  4048. $parent.find(".am-active").removeClass("am-active");
  4049. }
  4050. }
  4051. if (changed) {
  4052. $input.prop("checked", !$element.hasClass("am-active")).trigger("change");
  4053. }
  4054. }
  4055. if (changed) {
  4056. $element.toggleClass("am-active");
  4057. if (!$element.hasClass("am-active")) {
  4058. $element.blur();
  4059. }
  4060. }
  4061. };
  4062. // Button plugin
  4063. function Plugin(option) {
  4064. return this.each(function() {
  4065. var $this = $(this);
  4066. var data = $this.data("amui.button");
  4067. var options = typeof option == "object" && option || {};
  4068. if (!data) {
  4069. $this.data("amui.button", data = new Button(this, options));
  4070. }
  4071. if (option == "toggle") {
  4072. data.toggle();
  4073. } else if (typeof option == "string") {
  4074. data.setState(option);
  4075. }
  4076. });
  4077. }
  4078. $.fn.button = Plugin;
  4079. // Init code
  4080. $(document).on("click.button.amui", "[data-am-button]", function(e) {
  4081. var $btn = $(e.target);
  4082. if (!$btn.hasClass("am-btn")) {
  4083. $btn = $btn.closest(".am-btn");
  4084. }
  4085. Plugin.call($btn, "toggle");
  4086. e.preventDefault();
  4087. });
  4088. $(function() {
  4089. $("[data-am-loading]").each(function() {
  4090. $(this).button(UI.utils.parseOptions($(this).data("amLoading")));
  4091. });
  4092. });
  4093. UI.button = Button;
  4094. module.exports = Button;
  4095. });
  4096. define("ui.collapse", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  4097. "use strict";
  4098. require("core");
  4099. var $ = window.Zepto;
  4100. var UI = $.AMUI;
  4101. /**
  4102. * @via https://github.com/twbs/bootstrap/blob/master/js/collapse.js
  4103. * @copyright (c) 2011-2014 Twitter, Inc
  4104. * @license The MIT License
  4105. */
  4106. var Collapse = function(element, options) {
  4107. this.$element = $(element);
  4108. this.options = $.extend({}, Collapse.DEFAULTS, options);
  4109. this.transitioning = null;
  4110. if (this.options.parent) {
  4111. this.$parent = $(this.options.parent);
  4112. }
  4113. if (this.options.toggle) {
  4114. this.toggle();
  4115. }
  4116. };
  4117. Collapse.DEFAULTS = {
  4118. toggle: true
  4119. };
  4120. Collapse.prototype.open = function() {
  4121. if (this.transitioning || this.$element.hasClass("am-in")) {
  4122. return;
  4123. }
  4124. var startEvent = $.Event("open:collapse:amui");
  4125. this.$element.trigger(startEvent);
  4126. if (startEvent.isDefaultPrevented()) {
  4127. return;
  4128. }
  4129. var actives = this.$parent && this.$parent.find("> .am-panel > .am-in");
  4130. if (actives && actives.length) {
  4131. var hasData = actives.data("amui.collapse");
  4132. if (hasData && hasData.transitioning) {
  4133. return;
  4134. }
  4135. Plugin.call(actives, "close");
  4136. hasData || actives.data("amui.collapse", null);
  4137. }
  4138. this.$element.removeClass("am-collapse").addClass("am-collapsing").height(0);
  4139. this.transitioning = 1;
  4140. var complete = function() {
  4141. this.$element.removeClass("am-collapsing").addClass("am-collapse am-in").height("");
  4142. this.transitioning = 0;
  4143. this.$element.trigger("opened:collapse:amui");
  4144. };
  4145. if (!UI.support.transition) {
  4146. return complete.call(this);
  4147. }
  4148. this.$element.one(UI.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd(300).height(this.$element[0].scrollHeight);
  4149. };
  4150. Collapse.prototype.close = function() {
  4151. if (this.transitioning || !this.$element.hasClass("am-in")) {
  4152. return;
  4153. }
  4154. var startEvent = $.Event("close:collapse:amui");
  4155. this.$element.trigger(startEvent);
  4156. if (startEvent.isDefaultPrevented()) {
  4157. return;
  4158. }
  4159. this.$element.height(this.$element.height());
  4160. this.$element[0].offsetHeight;
  4161. this.$element.addClass("am-collapsing").removeClass("am-collapse").removeClass("am-in");
  4162. this.transitioning = 1;
  4163. var complete = function() {
  4164. this.transitioning = 0;
  4165. this.$element.trigger("closed:collapse:amui").removeClass("am-collapsing").addClass("am-collapse");
  4166. };
  4167. if (!UI.support.transition) {
  4168. return complete.call(this);
  4169. }
  4170. this.$element.height(0).one(UI.support.transition.end, $.proxy(complete, this)).emulateTransitionEnd(350);
  4171. };
  4172. Collapse.prototype.toggle = function() {
  4173. this[this.$element.hasClass("am-in") ? "close" : "open"]();
  4174. };
  4175. // Collapse Plugin
  4176. function Plugin(option) {
  4177. return this.each(function() {
  4178. var $this = $(this);
  4179. var data = $this.data("amui.collapse");
  4180. var options = $.extend({}, Collapse.DEFAULTS, UI.utils.options($this.attr("data-am-collapse")), typeof option == "object" && option);
  4181. if (!data && options.toggle && option == "open") {
  4182. option = !option;
  4183. }
  4184. if (!data) {
  4185. $this.data("amui.collapse", data = new Collapse(this, options));
  4186. }
  4187. if (typeof option == "string") {
  4188. data[option]();
  4189. }
  4190. });
  4191. }
  4192. $.fn.collapse = Plugin;
  4193. // Init code
  4194. $(document).on("click.collapse.amui", "[data-am-collapse]", function(e) {
  4195. var href;
  4196. var $this = $(this);
  4197. var options = UI.utils.options($this.attr("data-am-collapse"));
  4198. var target = options.target || e.preventDefault() || (href = $this.attr("href")) && href.replace(/.*(?=#[^\s]+$)/, "");
  4199. var $target = $(target);
  4200. var data = $target.data("amui.collapse");
  4201. var option = data ? "toggle" : options;
  4202. var parent = options.parent;
  4203. var $parent = parent && $(parent);
  4204. if (!data || !data.transitioning) {
  4205. if ($parent) {
  4206. // '[data-am-collapse*="{parent: \'' + parent + '"]
  4207. $parent.find("[data-am-collapse]").not($this).addClass("am-collapsed");
  4208. }
  4209. $this[$target.hasClass("am-in") ? "addClass" : "removeClass"]("am-collapsed");
  4210. }
  4211. Plugin.call($target, option);
  4212. });
  4213. UI.collapse = Collapse;
  4214. module.exports = Collapse;
  4215. });
  4216. define("ui.dimmer", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  4217. "use strict";
  4218. require("core");
  4219. var $ = window.Zepto;
  4220. var UI = $.AMUI;
  4221. var $doc = $(document);
  4222. var transition = UI.support.transition;
  4223. var Dimmer = function() {
  4224. this.id = UI.utils.generateGUID("am-dimmer");
  4225. this.$element = $(Dimmer.DEFAULTS.tpl, {
  4226. id: this.id
  4227. });
  4228. this.inited = false;
  4229. this.scrollbarWidth = 0;
  4230. this.used = $([]);
  4231. };
  4232. Dimmer.DEFAULTS = {
  4233. tpl: '<div class="am-dimmer" data-am-dimmer></div>'
  4234. };
  4235. Dimmer.prototype.init = function() {
  4236. if (!this.inited) {
  4237. $(document.body).append(this.$element);
  4238. this.inited = true;
  4239. $doc.trigger("init:dimmer:amui");
  4240. }
  4241. return this;
  4242. };
  4243. Dimmer.prototype.open = function(relatedElement) {
  4244. if (!this.inited) {
  4245. this.init();
  4246. }
  4247. var $element = this.$element;
  4248. // 用于多重调用
  4249. if (relatedElement) {
  4250. this.used = this.used.add($(relatedElement));
  4251. }
  4252. this.checkScrollbar().setScrollbar();
  4253. $element.show().trigger("open:dimmer:amui");
  4254. setTimeout(function() {
  4255. $element.addClass("am-active");
  4256. }, 0);
  4257. return this;
  4258. };
  4259. Dimmer.prototype.close = function(relatedElement, force) {
  4260. this.used = this.used.not($(relatedElement));
  4261. if (!force && this.used.length) {
  4262. return this;
  4263. }
  4264. var $element = this.$element;
  4265. $element.removeClass("am-active").trigger("close:dimmer:amui");
  4266. function complete() {
  4267. this.resetScrollbar();
  4268. $element.hide();
  4269. }
  4270. transition ? $element.one(transition.end, $.proxy(complete, this)).emulateTransitionEnd(150) : complete.call(this);
  4271. return this;
  4272. };
  4273. Dimmer.prototype.checkScrollbar = function() {
  4274. this.scrollbarWidth = UI.utils.measureScrollbar();
  4275. return this;
  4276. };
  4277. Dimmer.prototype.setScrollbar = function() {
  4278. var $body = $(document.body);
  4279. var bodyPaddingRight = parseInt($body.css("padding-right") || 0, 10);
  4280. if (this.scrollbarWidth) {
  4281. $body.css("padding-right", bodyPaddingRight + this.scrollbarWidth);
  4282. }
  4283. $body.addClass("am-dimmer-active");
  4284. return this;
  4285. };
  4286. Dimmer.prototype.resetScrollbar = function() {
  4287. $(document.body).css("padding-right", "").removeClass("am-dimmer-active");
  4288. return this;
  4289. };
  4290. var dimmer = new Dimmer();
  4291. UI.dimmer = dimmer;
  4292. module.exports = dimmer;
  4293. });
  4294. define("ui.dropdown", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  4295. "use strict";
  4296. require("core");
  4297. var $ = window.Zepto;
  4298. var UI = $.AMUI;
  4299. var animation = UI.support.animation;
  4300. /**
  4301. * @via https://github.com/Minwe/bootstrap/blob/master/js/dropdown.js
  4302. * @copyright (c) 2011-2014 Twitter, Inc
  4303. * @license The MIT License
  4304. */
  4305. // var toggle = '[data-am-dropdown] > .am-dropdown-toggle';
  4306. var Dropdown = function(element, options) {
  4307. this.options = $.extend({}, Dropdown.DEFAULTS, options);
  4308. options = this.options;
  4309. this.$element = $(element);
  4310. this.$toggle = this.$element.find(options.selector.toggle);
  4311. this.$dropdown = this.$element.find(options.selector.dropdown);
  4312. this.$boundary = options.boundary === window ? $(window) : this.$element.closest(options.boundary);
  4313. this.$justify = options.justify && $(options.justify).length && $(options.justify) || undefined;
  4314. !this.$boundary.length && (this.$boundary = $(window));
  4315. this.active = this.$element.hasClass("am-active") ? true : false;
  4316. this.animating = null;
  4317. this.events();
  4318. };
  4319. Dropdown.DEFAULTS = {
  4320. animation: "am-animation-slide-top-fixed",
  4321. boundary: window,
  4322. justify: undefined,
  4323. selector: {
  4324. dropdown: ".am-dropdown-content",
  4325. toggle: ".am-dropdown-toggle"
  4326. },
  4327. trigger: "click"
  4328. };
  4329. Dropdown.prototype.toggle = function() {
  4330. this.clear();
  4331. if (this.animating) {
  4332. return;
  4333. }
  4334. this[this.active ? "close" : "open"]();
  4335. };
  4336. Dropdown.prototype.open = function(e) {
  4337. var $toggle = this.$toggle;
  4338. var $element = this.$element;
  4339. var $dropdown = this.$dropdown;
  4340. if ($toggle.is(".am-disabled, :disabled")) {
  4341. return;
  4342. }
  4343. if (this.active) {
  4344. return;
  4345. }
  4346. $element.trigger("open:dropdown:amui").addClass("am-active");
  4347. $toggle.trigger("focus");
  4348. this.checkDimensions();
  4349. var complete = $.proxy(function() {
  4350. $element.trigger("opened:dropdown:amui");
  4351. this.active = true;
  4352. this.animating = 0;
  4353. }, this);
  4354. if (animation) {
  4355. this.animating = 1;
  4356. $dropdown.addClass(this.options.animation).on(animation.end + ".open.dropdown.amui", $.proxy(function() {
  4357. complete();
  4358. $dropdown.removeClass(this.options.animation);
  4359. }, this));
  4360. } else {
  4361. complete();
  4362. }
  4363. };
  4364. Dropdown.prototype.close = function() {
  4365. if (!this.active) {
  4366. return;
  4367. }
  4368. var animationName = this.options.animation + " am-animation-reverse";
  4369. var $element = this.$element;
  4370. var $dropdown = this.$dropdown;
  4371. $element.trigger("close:dropdown:amui");
  4372. var complete = $.proxy(function complete() {
  4373. $element.removeClass("am-active").trigger("closed:dropdown:amui");
  4374. this.active = false;
  4375. this.animating = 0;
  4376. this.$toggle.blur();
  4377. }, this);
  4378. if (animation) {
  4379. $dropdown.addClass(animationName);
  4380. this.animating = 1;
  4381. // animation
  4382. $dropdown.one(animation.end + ".close.dropdown.amui", function() {
  4383. complete();
  4384. $dropdown.removeClass(animationName);
  4385. });
  4386. } else {
  4387. complete();
  4388. }
  4389. };
  4390. Dropdown.prototype.checkDimensions = function() {
  4391. if (!this.$dropdown.length) {
  4392. return;
  4393. }
  4394. var $dropdown = this.$dropdown;
  4395. var offset = $dropdown.offset();
  4396. var width = $dropdown.outerWidth();
  4397. var boundaryWidth = this.$boundary.width();
  4398. var boundaryOffset = $.isWindow(this.boundary) && this.$boundary.offset() ? this.$boundary.offset().left : 0;
  4399. if (this.$justify) {
  4400. $dropdown.css({
  4401. "min-width": this.$justify.width()
  4402. });
  4403. }
  4404. if (width + (offset.left - boundaryOffset) > boundaryWidth) {
  4405. this.$element.addClass("am-dropdown-flip");
  4406. }
  4407. };
  4408. Dropdown.prototype.clear = function() {
  4409. $("[data-am-dropdown]").not(this.$element).each(function() {
  4410. var data = $(this).data("amui.dropdown");
  4411. data && data["close"]();
  4412. });
  4413. };
  4414. Dropdown.prototype.events = function() {
  4415. var eventNS = "dropdown.amui";
  4416. // triggers = this.options.trigger.split(' '),
  4417. var $toggle = this.$toggle;
  4418. $toggle.on("click." + eventNS, $.proxy(this.toggle, this));
  4419. /*for (var i = triggers.length; i--;) {
  4420. var trigger = triggers[i];
  4421. if (trigger === 'click') {
  4422. $toggle.on('click.' + eventNS, $.proxy(this.toggle, this))
  4423. }
  4424. if (trigger === 'focus' || trigger === 'hover') {
  4425. var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin';
  4426. var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout';
  4427. this.$element.on(eventIn + '.' + eventNS, $.proxy(this.open, this))
  4428. .on(eventOut + '.' + eventNS, $.proxy(this.close, this));
  4429. }
  4430. }*/
  4431. $(document).on("keydown.dropdown.amui", $.proxy(function(e) {
  4432. e.keyCode === 27 && this.active && this.close();
  4433. }, this)).on("click.outer.dropdown.amui", $.proxy(function(e) {
  4434. // var $target = $(e.target);
  4435. if (this.active && (this.$element[0] === e.target || !this.$element.find(e.target).length)) {
  4436. this.close();
  4437. }
  4438. }, this));
  4439. };
  4440. // Dropdown Plugin
  4441. function Plugin(option) {
  4442. return this.each(function() {
  4443. var $this = $(this);
  4444. var data = $this.data("amui.dropdown");
  4445. var options = $.extend({}, UI.utils.parseOptions($this.attr("data-am-dropdown")), typeof option == "object" && option);
  4446. if (!data) {
  4447. $this.data("amui.dropdown", data = new Dropdown(this, options));
  4448. }
  4449. if (typeof option == "string") {
  4450. data[option]();
  4451. }
  4452. });
  4453. }
  4454. $.fn.dropdown = Plugin;
  4455. // Init code
  4456. $(function() {
  4457. $("[data-am-dropdown]").dropdown();
  4458. });
  4459. $(document).on("click.dropdown.amui", ".am-dropdown form", function(e) {
  4460. e.stopPropagation();
  4461. });
  4462. UI.dropdown = Dropdown;
  4463. module.exports = Dropdown;
  4464. });
  4465. define("ui.iscroll-lite", [], function(require, exports, module) {
  4466. "use strict";
  4467. /* jshint unused: false */
  4468. /* jshint -W101, -W116, -W109 */
  4469. /*! iScroll v5.1.3
  4470. * (c) 2008-2014 Matteo Spinelli
  4471. * http://cubiq.org/license
  4472. */
  4473. (function(window, document, Math) {
  4474. var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
  4475. window.setTimeout(callback, 1e3 / 60);
  4476. };
  4477. var utils = function() {
  4478. var me = {};
  4479. var _elementStyle = document.createElement("div").style;
  4480. var _vendor = function() {
  4481. var vendors = [ "t", "webkitT", "MozT", "msT", "OT" ], transform, i = 0, l = vendors.length;
  4482. for (;i < l; i++) {
  4483. transform = vendors[i] + "ransform";
  4484. if (transform in _elementStyle) return vendors[i].substr(0, vendors[i].length - 1);
  4485. }
  4486. return false;
  4487. }();
  4488. function _prefixStyle(style) {
  4489. if (_vendor === false) return false;
  4490. if (_vendor === "") return style;
  4491. return _vendor + style.charAt(0).toUpperCase() + style.substr(1);
  4492. }
  4493. me.getTime = Date.now || function getTime() {
  4494. return new Date().getTime();
  4495. };
  4496. me.extend = function(target, obj) {
  4497. for (var i in obj) {
  4498. target[i] = obj[i];
  4499. }
  4500. };
  4501. me.addEvent = function(el, type, fn, capture) {
  4502. el.addEventListener(type, fn, !!capture);
  4503. };
  4504. me.removeEvent = function(el, type, fn, capture) {
  4505. el.removeEventListener(type, fn, !!capture);
  4506. };
  4507. me.prefixPointerEvent = function(pointerEvent) {
  4508. return window.MSPointerEvent ? "MSPointer" + pointerEvent.charAt(9).toUpperCase() + pointerEvent.substr(10) : pointerEvent;
  4509. };
  4510. me.momentum = function(current, start, time, lowerMargin, wrapperSize, deceleration) {
  4511. var distance = current - start, speed = Math.abs(distance) / time, destination, duration;
  4512. deceleration = deceleration === undefined ? 6e-4 : deceleration;
  4513. destination = current + speed * speed / (2 * deceleration) * (distance < 0 ? -1 : 1);
  4514. duration = speed / deceleration;
  4515. if (destination < lowerMargin) {
  4516. destination = wrapperSize ? lowerMargin - wrapperSize / 2.5 * (speed / 8) : lowerMargin;
  4517. distance = Math.abs(destination - current);
  4518. duration = distance / speed;
  4519. } else if (destination > 0) {
  4520. destination = wrapperSize ? wrapperSize / 2.5 * (speed / 8) : 0;
  4521. distance = Math.abs(current) + destination;
  4522. duration = distance / speed;
  4523. }
  4524. return {
  4525. destination: Math.round(destination),
  4526. duration: duration
  4527. };
  4528. };
  4529. var _transform = _prefixStyle("transform");
  4530. me.extend(me, {
  4531. hasTransform: _transform !== false,
  4532. hasPerspective: _prefixStyle("perspective") in _elementStyle,
  4533. hasTouch: "ontouchstart" in window,
  4534. hasPointer: window.PointerEvent || window.MSPointerEvent,
  4535. // IE10 is prefixed
  4536. hasTransition: _prefixStyle("transition") in _elementStyle
  4537. });
  4538. // This should find all Android browsers lower than build 535.19 (both stock browser and webview)
  4539. me.isBadAndroid = /Android /.test(window.navigator.appVersion) && !/Chrome\/\d/.test(window.navigator.appVersion);
  4540. me.extend(me.style = {}, {
  4541. transform: _transform,
  4542. transitionTimingFunction: _prefixStyle("transitionTimingFunction"),
  4543. transitionDuration: _prefixStyle("transitionDuration"),
  4544. transitionDelay: _prefixStyle("transitionDelay"),
  4545. transformOrigin: _prefixStyle("transformOrigin")
  4546. });
  4547. me.hasClass = function(e, c) {
  4548. var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
  4549. return re.test(e.className);
  4550. };
  4551. me.addClass = function(e, c) {
  4552. if (me.hasClass(e, c)) {
  4553. return;
  4554. }
  4555. var newclass = e.className.split(" ");
  4556. newclass.push(c);
  4557. e.className = newclass.join(" ");
  4558. };
  4559. me.removeClass = function(e, c) {
  4560. if (!me.hasClass(e, c)) {
  4561. return;
  4562. }
  4563. var re = new RegExp("(^|\\s)" + c + "(\\s|$)", "g");
  4564. e.className = e.className.replace(re, " ");
  4565. };
  4566. me.offset = function(el) {
  4567. var left = -el.offsetLeft, top = -el.offsetTop;
  4568. // jshint -W084
  4569. while (el = el.offsetParent) {
  4570. left -= el.offsetLeft;
  4571. top -= el.offsetTop;
  4572. }
  4573. // jshint +W084
  4574. return {
  4575. left: left,
  4576. top: top
  4577. };
  4578. };
  4579. me.preventDefaultException = function(el, exceptions) {
  4580. for (var i in exceptions) {
  4581. if (exceptions[i].test(el[i])) {
  4582. return true;
  4583. }
  4584. }
  4585. return false;
  4586. };
  4587. me.extend(me.eventType = {}, {
  4588. touchstart: 1,
  4589. touchmove: 1,
  4590. touchend: 1,
  4591. mousedown: 2,
  4592. mousemove: 2,
  4593. mouseup: 2,
  4594. pointerdown: 3,
  4595. pointermove: 3,
  4596. pointerup: 3,
  4597. MSPointerDown: 3,
  4598. MSPointerMove: 3,
  4599. MSPointerUp: 3
  4600. });
  4601. me.extend(me.ease = {}, {
  4602. quadratic: {
  4603. style: "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
  4604. fn: function(k) {
  4605. return k * (2 - k);
  4606. }
  4607. },
  4608. circular: {
  4609. style: "cubic-bezier(0.1, 0.57, 0.1, 1)",
  4610. // Not properly "circular" but this looks better, it should be (0.075, 0.82, 0.165, 1)
  4611. fn: function(k) {
  4612. return Math.sqrt(1 - --k * k);
  4613. }
  4614. },
  4615. back: {
  4616. style: "cubic-bezier(0.175, 0.885, 0.32, 1.275)",
  4617. fn: function(k) {
  4618. var b = 4;
  4619. return (k = k - 1) * k * ((b + 1) * k + b) + 1;
  4620. }
  4621. },
  4622. bounce: {
  4623. style: "",
  4624. fn: function(k) {
  4625. if ((k /= 1) < 1 / 2.75) {
  4626. return 7.5625 * k * k;
  4627. } else if (k < 2 / 2.75) {
  4628. return 7.5625 * (k -= 1.5 / 2.75) * k + .75;
  4629. } else if (k < 2.5 / 2.75) {
  4630. return 7.5625 * (k -= 2.25 / 2.75) * k + .9375;
  4631. } else {
  4632. return 7.5625 * (k -= 2.625 / 2.75) * k + .984375;
  4633. }
  4634. }
  4635. },
  4636. elastic: {
  4637. style: "",
  4638. fn: function(k) {
  4639. var f = .22, e = .4;
  4640. if (k === 0) {
  4641. return 0;
  4642. }
  4643. if (k == 1) {
  4644. return 1;
  4645. }
  4646. return e * Math.pow(2, -10 * k) * Math.sin((k - f / 4) * 2 * Math.PI / f) + 1;
  4647. }
  4648. }
  4649. });
  4650. me.tap = function(e, eventName) {
  4651. var ev = document.createEvent("Event");
  4652. ev.initEvent(eventName, true, true);
  4653. ev.pageX = e.pageX;
  4654. ev.pageY = e.pageY;
  4655. e.target.dispatchEvent(ev);
  4656. };
  4657. me.click = function(e) {
  4658. var target = e.target, ev;
  4659. if (!/(SELECT|INPUT|TEXTAREA)/i.test(target.tagName)) {
  4660. ev = document.createEvent("MouseEvents");
  4661. ev.initMouseEvent("click", true, true, e.view, 1, target.screenX, target.screenY, target.clientX, target.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null);
  4662. ev._constructed = true;
  4663. target.dispatchEvent(ev);
  4664. }
  4665. };
  4666. return me;
  4667. }();
  4668. function IScroll(el, options) {
  4669. this.wrapper = typeof el == "string" ? document.querySelector(el) : el;
  4670. this.scroller = this.wrapper.children[0];
  4671. this.scrollerStyle = this.scroller.style;
  4672. // cache style for better performance
  4673. this.options = {
  4674. // INSERT POINT: OPTIONS
  4675. startX: 0,
  4676. startY: 0,
  4677. scrollY: true,
  4678. directionLockThreshold: 5,
  4679. momentum: true,
  4680. bounce: true,
  4681. bounceTime: 600,
  4682. bounceEasing: "",
  4683. preventDefault: true,
  4684. preventDefaultException: {
  4685. tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT)$/
  4686. },
  4687. HWCompositing: true,
  4688. useTransition: true,
  4689. useTransform: true
  4690. };
  4691. for (var i in options) {
  4692. this.options[i] = options[i];
  4693. }
  4694. // Normalize options
  4695. this.translateZ = this.options.HWCompositing && utils.hasPerspective ? " translateZ(0)" : "";
  4696. this.options.useTransition = utils.hasTransition && this.options.useTransition;
  4697. this.options.useTransform = utils.hasTransform && this.options.useTransform;
  4698. this.options.eventPassthrough = this.options.eventPassthrough === true ? "vertical" : this.options.eventPassthrough;
  4699. this.options.preventDefault = !this.options.eventPassthrough && this.options.preventDefault;
  4700. // If you want eventPassthrough I have to lock one of the axes
  4701. this.options.scrollY = this.options.eventPassthrough == "vertical" ? false : this.options.scrollY;
  4702. this.options.scrollX = this.options.eventPassthrough == "horizontal" ? false : this.options.scrollX;
  4703. // With eventPassthrough we also need lockDirection mechanism
  4704. this.options.freeScroll = this.options.freeScroll && !this.options.eventPassthrough;
  4705. this.options.directionLockThreshold = this.options.eventPassthrough ? 0 : this.options.directionLockThreshold;
  4706. this.options.bounceEasing = typeof this.options.bounceEasing == "string" ? utils.ease[this.options.bounceEasing] || utils.ease.circular : this.options.bounceEasing;
  4707. this.options.resizePolling = this.options.resizePolling === undefined ? 60 : this.options.resizePolling;
  4708. if (this.options.tap === true) {
  4709. this.options.tap = "tap";
  4710. }
  4711. // INSERT POINT: NORMALIZATION
  4712. // Some defaults
  4713. this.x = 0;
  4714. this.y = 0;
  4715. this.directionX = 0;
  4716. this.directionY = 0;
  4717. this._events = {};
  4718. // INSERT POINT: DEFAULTS
  4719. this._init();
  4720. this.refresh();
  4721. this.scrollTo(this.options.startX, this.options.startY);
  4722. this.enable();
  4723. }
  4724. IScroll.prototype = {
  4725. version: "5.1.3",
  4726. _init: function() {
  4727. this._initEvents();
  4728. },
  4729. destroy: function() {
  4730. this._initEvents(true);
  4731. this._execEvent("destroy");
  4732. },
  4733. _transitionEnd: function(e) {
  4734. if (e.target != this.scroller || !this.isInTransition) {
  4735. return;
  4736. }
  4737. this._transitionTime();
  4738. if (!this.resetPosition(this.options.bounceTime)) {
  4739. this.isInTransition = false;
  4740. this._execEvent("scrollEnd");
  4741. }
  4742. },
  4743. _start: function(e) {
  4744. // React to left mouse button only
  4745. if (utils.eventType[e.type] != 1) {
  4746. if (e.button !== 0) {
  4747. return;
  4748. }
  4749. }
  4750. if (!this.enabled || this.initiated && utils.eventType[e.type] !== this.initiated) {
  4751. return;
  4752. }
  4753. if (this.options.preventDefault && !utils.isBadAndroid && !utils.preventDefaultException(e.target, this.options.preventDefaultException)) {
  4754. e.preventDefault();
  4755. }
  4756. var point = e.touches ? e.touches[0] : e, pos;
  4757. this.initiated = utils.eventType[e.type];
  4758. this.moved = false;
  4759. this.distX = 0;
  4760. this.distY = 0;
  4761. this.directionX = 0;
  4762. this.directionY = 0;
  4763. this.directionLocked = 0;
  4764. this._transitionTime();
  4765. this.startTime = utils.getTime();
  4766. if (this.options.useTransition && this.isInTransition) {
  4767. this.isInTransition = false;
  4768. pos = this.getComputedPosition();
  4769. this._translate(Math.round(pos.x), Math.round(pos.y));
  4770. this._execEvent("scrollEnd");
  4771. } else if (!this.options.useTransition && this.isAnimating) {
  4772. this.isAnimating = false;
  4773. this._execEvent("scrollEnd");
  4774. }
  4775. this.startX = this.x;
  4776. this.startY = this.y;
  4777. this.absStartX = this.x;
  4778. this.absStartY = this.y;
  4779. this.pointX = point.pageX;
  4780. this.pointY = point.pageY;
  4781. this._execEvent("beforeScrollStart");
  4782. },
  4783. _move: function(e) {
  4784. if (!this.enabled || utils.eventType[e.type] !== this.initiated) {
  4785. return;
  4786. }
  4787. if (this.options.preventDefault) {
  4788. // increases performance on Android? TODO: check!
  4789. e.preventDefault();
  4790. }
  4791. var point = e.touches ? e.touches[0] : e, deltaX = point.pageX - this.pointX, deltaY = point.pageY - this.pointY, timestamp = utils.getTime(), newX, newY, absDistX, absDistY;
  4792. this.pointX = point.pageX;
  4793. this.pointY = point.pageY;
  4794. this.distX += deltaX;
  4795. this.distY += deltaY;
  4796. absDistX = Math.abs(this.distX);
  4797. absDistY = Math.abs(this.distY);
  4798. // We need to move at least 10 pixels for the scrolling to initiate
  4799. if (timestamp - this.endTime > 300 && absDistX < 10 && absDistY < 10) {
  4800. return;
  4801. }
  4802. // If you are scrolling in one direction lock the other
  4803. if (!this.directionLocked && !this.options.freeScroll) {
  4804. if (absDistX > absDistY + this.options.directionLockThreshold) {
  4805. this.directionLocked = "h";
  4806. } else if (absDistY >= absDistX + this.options.directionLockThreshold) {
  4807. this.directionLocked = "v";
  4808. } else {
  4809. this.directionLocked = "n";
  4810. }
  4811. }
  4812. if (this.directionLocked == "h") {
  4813. if (this.options.eventPassthrough == "vertical") {
  4814. e.preventDefault();
  4815. } else if (this.options.eventPassthrough == "horizontal") {
  4816. this.initiated = false;
  4817. return;
  4818. }
  4819. deltaY = 0;
  4820. } else if (this.directionLocked == "v") {
  4821. if (this.options.eventPassthrough == "horizontal") {
  4822. e.preventDefault();
  4823. } else if (this.options.eventPassthrough == "vertical") {
  4824. this.initiated = false;
  4825. return;
  4826. }
  4827. deltaX = 0;
  4828. }
  4829. deltaX = this.hasHorizontalScroll ? deltaX : 0;
  4830. deltaY = this.hasVerticalScroll ? deltaY : 0;
  4831. newX = this.x + deltaX;
  4832. newY = this.y + deltaY;
  4833. // Slow down if outside of the boundaries
  4834. if (newX > 0 || newX < this.maxScrollX) {
  4835. newX = this.options.bounce ? this.x + deltaX / 3 : newX > 0 ? 0 : this.maxScrollX;
  4836. }
  4837. if (newY > 0 || newY < this.maxScrollY) {
  4838. newY = this.options.bounce ? this.y + deltaY / 3 : newY > 0 ? 0 : this.maxScrollY;
  4839. }
  4840. this.directionX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
  4841. this.directionY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
  4842. if (!this.moved) {
  4843. this._execEvent("scrollStart");
  4844. }
  4845. this.moved = true;
  4846. this._translate(newX, newY);
  4847. /* REPLACE START: _move */
  4848. if (timestamp - this.startTime > 300) {
  4849. this.startTime = timestamp;
  4850. this.startX = this.x;
  4851. this.startY = this.y;
  4852. }
  4853. },
  4854. _end: function(e) {
  4855. if (!this.enabled || utils.eventType[e.type] !== this.initiated) {
  4856. return;
  4857. }
  4858. if (this.options.preventDefault && !utils.preventDefaultException(e.target, this.options.preventDefaultException)) {
  4859. e.preventDefault();
  4860. }
  4861. var point = e.changedTouches ? e.changedTouches[0] : e, momentumX, momentumY, duration = utils.getTime() - this.startTime, newX = Math.round(this.x), newY = Math.round(this.y), distanceX = Math.abs(newX - this.startX), distanceY = Math.abs(newY - this.startY), time = 0, easing = "";
  4862. this.isInTransition = 0;
  4863. this.initiated = 0;
  4864. this.endTime = utils.getTime();
  4865. // reset if we are outside of the boundaries
  4866. if (this.resetPosition(this.options.bounceTime)) {
  4867. return;
  4868. }
  4869. this.scrollTo(newX, newY);
  4870. // ensures that the last position is rounded
  4871. // we scrolled less than 10 pixels
  4872. if (!this.moved) {
  4873. if (this.options.tap) {
  4874. utils.tap(e, this.options.tap);
  4875. }
  4876. if (this.options.click) {
  4877. utils.click(e);
  4878. }
  4879. this._execEvent("scrollCancel");
  4880. return;
  4881. }
  4882. if (this._events.flick && duration < 200 && distanceX < 100 && distanceY < 100) {
  4883. this._execEvent("flick");
  4884. return;
  4885. }
  4886. // start momentum animation if needed
  4887. if (this.options.momentum && duration < 300) {
  4888. momentumX = this.hasHorizontalScroll ? utils.momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options.deceleration) : {
  4889. destination: newX,
  4890. duration: 0
  4891. };
  4892. momentumY = this.hasVerticalScroll ? utils.momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options.deceleration) : {
  4893. destination: newY,
  4894. duration: 0
  4895. };
  4896. newX = momentumX.destination;
  4897. newY = momentumY.destination;
  4898. time = Math.max(momentumX.duration, momentumY.duration);
  4899. this.isInTransition = 1;
  4900. }
  4901. // INSERT POINT: _end
  4902. if (newX != this.x || newY != this.y) {
  4903. // change easing function when scroller goes out of the boundaries
  4904. if (newX > 0 || newX < this.maxScrollX || newY > 0 || newY < this.maxScrollY) {
  4905. easing = utils.ease.quadratic;
  4906. }
  4907. this.scrollTo(newX, newY, time, easing);
  4908. return;
  4909. }
  4910. this._execEvent("scrollEnd");
  4911. },
  4912. _resize: function() {
  4913. var that = this;
  4914. clearTimeout(this.resizeTimeout);
  4915. this.resizeTimeout = setTimeout(function() {
  4916. that.refresh();
  4917. }, this.options.resizePolling);
  4918. },
  4919. resetPosition: function(time) {
  4920. var x = this.x, y = this.y;
  4921. time = time || 0;
  4922. if (!this.hasHorizontalScroll || this.x > 0) {
  4923. x = 0;
  4924. } else if (this.x < this.maxScrollX) {
  4925. x = this.maxScrollX;
  4926. }
  4927. if (!this.hasVerticalScroll || this.y > 0) {
  4928. y = 0;
  4929. } else if (this.y < this.maxScrollY) {
  4930. y = this.maxScrollY;
  4931. }
  4932. if (x == this.x && y == this.y) {
  4933. return false;
  4934. }
  4935. this.scrollTo(x, y, time, this.options.bounceEasing);
  4936. return true;
  4937. },
  4938. disable: function() {
  4939. this.enabled = false;
  4940. },
  4941. enable: function() {
  4942. this.enabled = true;
  4943. },
  4944. refresh: function() {
  4945. var rf = this.wrapper.offsetHeight;
  4946. // Force reflow
  4947. this.wrapperWidth = this.wrapper.clientWidth;
  4948. this.wrapperHeight = this.wrapper.clientHeight;
  4949. /* REPLACE START: refresh */
  4950. this.scrollerWidth = this.scroller.offsetWidth;
  4951. this.scrollerHeight = this.scroller.offsetHeight;
  4952. this.maxScrollX = this.wrapperWidth - this.scrollerWidth;
  4953. this.maxScrollY = this.wrapperHeight - this.scrollerHeight;
  4954. /* REPLACE END: refresh */
  4955. this.hasHorizontalScroll = this.options.scrollX && this.maxScrollX < 0;
  4956. this.hasVerticalScroll = this.options.scrollY && this.maxScrollY < 0;
  4957. if (!this.hasHorizontalScroll) {
  4958. this.maxScrollX = 0;
  4959. this.scrollerWidth = this.wrapperWidth;
  4960. }
  4961. if (!this.hasVerticalScroll) {
  4962. this.maxScrollY = 0;
  4963. this.scrollerHeight = this.wrapperHeight;
  4964. }
  4965. this.endTime = 0;
  4966. this.directionX = 0;
  4967. this.directionY = 0;
  4968. this.wrapperOffset = utils.offset(this.wrapper);
  4969. this._execEvent("refresh");
  4970. this.resetPosition();
  4971. },
  4972. on: function(type, fn) {
  4973. if (!this._events[type]) {
  4974. this._events[type] = [];
  4975. }
  4976. this._events[type].push(fn);
  4977. },
  4978. off: function(type, fn) {
  4979. if (!this._events[type]) {
  4980. return;
  4981. }
  4982. var index = this._events[type].indexOf(fn);
  4983. if (index > -1) {
  4984. this._events[type].splice(index, 1);
  4985. }
  4986. },
  4987. _execEvent: function(type) {
  4988. if (!this._events[type]) {
  4989. return;
  4990. }
  4991. var i = 0, l = this._events[type].length;
  4992. if (!l) {
  4993. return;
  4994. }
  4995. for (;i < l; i++) {
  4996. this._events[type][i].apply(this, [].slice.call(arguments, 1));
  4997. }
  4998. },
  4999. scrollBy: function(x, y, time, easing) {
  5000. x = this.x + x;
  5001. y = this.y + y;
  5002. time = time || 0;
  5003. this.scrollTo(x, y, time, easing);
  5004. },
  5005. scrollTo: function(x, y, time, easing) {
  5006. easing = easing || utils.ease.circular;
  5007. this.isInTransition = this.options.useTransition && time > 0;
  5008. if (!time || this.options.useTransition && easing.style) {
  5009. this._transitionTimingFunction(easing.style);
  5010. this._transitionTime(time);
  5011. this._translate(x, y);
  5012. } else {
  5013. this._animate(x, y, time, easing.fn);
  5014. }
  5015. },
  5016. scrollToElement: function(el, time, offsetX, offsetY, easing) {
  5017. el = el.nodeType ? el : this.scroller.querySelector(el);
  5018. if (!el) {
  5019. return;
  5020. }
  5021. var pos = utils.offset(el);
  5022. pos.left -= this.wrapperOffset.left;
  5023. pos.top -= this.wrapperOffset.top;
  5024. // if offsetX/Y are true we center the element to the screen
  5025. if (offsetX === true) {
  5026. offsetX = Math.round(el.offsetWidth / 2 - this.wrapper.offsetWidth / 2);
  5027. }
  5028. if (offsetY === true) {
  5029. offsetY = Math.round(el.offsetHeight / 2 - this.wrapper.offsetHeight / 2);
  5030. }
  5031. pos.left -= offsetX || 0;
  5032. pos.top -= offsetY || 0;
  5033. pos.left = pos.left > 0 ? 0 : pos.left < this.maxScrollX ? this.maxScrollX : pos.left;
  5034. pos.top = pos.top > 0 ? 0 : pos.top < this.maxScrollY ? this.maxScrollY : pos.top;
  5035. time = time === undefined || time === null || time === "auto" ? Math.max(Math.abs(this.x - pos.left), Math.abs(this.y - pos.top)) : time;
  5036. this.scrollTo(pos.left, pos.top, time, easing);
  5037. },
  5038. _transitionTime: function(time) {
  5039. time = time || 0;
  5040. this.scrollerStyle[utils.style.transitionDuration] = time + "ms";
  5041. if (!time && utils.isBadAndroid) {
  5042. this.scrollerStyle[utils.style.transitionDuration] = "0.001s";
  5043. }
  5044. },
  5045. _transitionTimingFunction: function(easing) {
  5046. this.scrollerStyle[utils.style.transitionTimingFunction] = easing;
  5047. },
  5048. _translate: function(x, y) {
  5049. if (this.options.useTransform) {
  5050. /* REPLACE START: _translate */
  5051. this.scrollerStyle[utils.style.transform] = "translate(" + x + "px," + y + "px)" + this.translateZ;
  5052. } else {
  5053. x = Math.round(x);
  5054. y = Math.round(y);
  5055. this.scrollerStyle.left = x + "px";
  5056. this.scrollerStyle.top = y + "px";
  5057. }
  5058. this.x = x;
  5059. this.y = y;
  5060. },
  5061. _initEvents: function(remove) {
  5062. var eventType = remove ? utils.removeEvent : utils.addEvent, target = this.options.bindToWrapper ? this.wrapper : window;
  5063. eventType(window, "orientationchange", this);
  5064. eventType(window, "resize", this);
  5065. if (this.options.click) {
  5066. eventType(this.wrapper, "click", this, true);
  5067. }
  5068. if (!this.options.disableMouse) {
  5069. eventType(this.wrapper, "mousedown", this);
  5070. eventType(target, "mousemove", this);
  5071. eventType(target, "mousecancel", this);
  5072. eventType(target, "mouseup", this);
  5073. }
  5074. if (utils.hasPointer && !this.options.disablePointer) {
  5075. eventType(this.wrapper, utils.prefixPointerEvent("pointerdown"), this);
  5076. eventType(target, utils.prefixPointerEvent("pointermove"), this);
  5077. eventType(target, utils.prefixPointerEvent("pointercancel"), this);
  5078. eventType(target, utils.prefixPointerEvent("pointerup"), this);
  5079. }
  5080. if (utils.hasTouch && !this.options.disableTouch) {
  5081. eventType(this.wrapper, "touchstart", this);
  5082. eventType(target, "touchmove", this);
  5083. eventType(target, "touchcancel", this);
  5084. eventType(target, "touchend", this);
  5085. }
  5086. eventType(this.scroller, "transitionend", this);
  5087. eventType(this.scroller, "webkitTransitionEnd", this);
  5088. eventType(this.scroller, "oTransitionEnd", this);
  5089. eventType(this.scroller, "MSTransitionEnd", this);
  5090. },
  5091. getComputedPosition: function() {
  5092. var matrix = window.getComputedStyle(this.scroller, null), x, y;
  5093. if (this.options.useTransform) {
  5094. matrix = matrix[utils.style.transform].split(")")[0].split(", ");
  5095. x = +(matrix[12] || matrix[4]);
  5096. y = +(matrix[13] || matrix[5]);
  5097. } else {
  5098. x = +matrix.left.replace(/[^-\d.]/g, "");
  5099. y = +matrix.top.replace(/[^-\d.]/g, "");
  5100. }
  5101. return {
  5102. x: x,
  5103. y: y
  5104. };
  5105. },
  5106. _animate: function(destX, destY, duration, easingFn) {
  5107. var that = this, startX = this.x, startY = this.y, startTime = utils.getTime(), destTime = startTime + duration;
  5108. function step() {
  5109. var now = utils.getTime(), newX, newY, easing;
  5110. if (now >= destTime) {
  5111. that.isAnimating = false;
  5112. that._translate(destX, destY);
  5113. if (!that.resetPosition(that.options.bounceTime)) {
  5114. that._execEvent("scrollEnd");
  5115. }
  5116. return;
  5117. }
  5118. now = (now - startTime) / duration;
  5119. easing = easingFn(now);
  5120. newX = (destX - startX) * easing + startX;
  5121. newY = (destY - startY) * easing + startY;
  5122. that._translate(newX, newY);
  5123. if (that.isAnimating) {
  5124. rAF(step);
  5125. }
  5126. }
  5127. this.isAnimating = true;
  5128. step();
  5129. },
  5130. handleEvent: function(e) {
  5131. switch (e.type) {
  5132. case "touchstart":
  5133. case "pointerdown":
  5134. case "MSPointerDown":
  5135. case "mousedown":
  5136. this._start(e);
  5137. break;
  5138. case "touchmove":
  5139. case "pointermove":
  5140. case "MSPointerMove":
  5141. case "mousemove":
  5142. this._move(e);
  5143. break;
  5144. case "touchend":
  5145. case "pointerup":
  5146. case "MSPointerUp":
  5147. case "mouseup":
  5148. case "touchcancel":
  5149. case "pointercancel":
  5150. case "MSPointerCancel":
  5151. case "mousecancel":
  5152. this._end(e);
  5153. break;
  5154. case "orientationchange":
  5155. case "resize":
  5156. this._resize();
  5157. break;
  5158. case "transitionend":
  5159. case "webkitTransitionEnd":
  5160. case "oTransitionEnd":
  5161. case "MSTransitionEnd":
  5162. this._transitionEnd(e);
  5163. break;
  5164. case "wheel":
  5165. case "DOMMouseScroll":
  5166. case "mousewheel":
  5167. this._wheel(e);
  5168. break;
  5169. case "keydown":
  5170. this._key(e);
  5171. break;
  5172. case "click":
  5173. if (!e._constructed) {
  5174. e.preventDefault();
  5175. e.stopPropagation();
  5176. }
  5177. break;
  5178. }
  5179. }
  5180. };
  5181. IScroll.utils = utils;
  5182. if (typeof module != "undefined" && module.exports) {
  5183. module.exports = IScroll;
  5184. } else {
  5185. window.IScroll = IScroll;
  5186. }
  5187. })(window, document, Math);
  5188. });
  5189. define("ui.modal", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.dimmer" ], function(require, exports, module) {
  5190. "use strict";
  5191. require("core");
  5192. var dimmer = require("ui.dimmer");
  5193. var $ = window.Zepto;
  5194. var UI = $.AMUI;
  5195. var $doc = $(document);
  5196. var supportTransition = UI.support.transition;
  5197. /**
  5198. * @reference https://github.com/nolimits4web/Framework7/blob/master/src/js/modals.js
  5199. * @license https://github.com/nolimits4web/Framework7/blob/master/LICENSE
  5200. */
  5201. var Modal = function(element, options) {
  5202. this.options = $.extend({}, Modal.DEFAULTS, options || {});
  5203. this.$element = $(element);
  5204. if (!this.$element.attr("id")) {
  5205. this.$element.attr("id", UI.utils.generateGUID("am-modal"));
  5206. }
  5207. this.isPopup = this.$element.hasClass("am-popup");
  5208. this.active = this.transitioning = null;
  5209. this.events();
  5210. };
  5211. Modal.DEFAULTS = {
  5212. className: {
  5213. active: "am-modal-active",
  5214. out: "am-modal-out"
  5215. },
  5216. selector: {
  5217. modal: ".am-modal",
  5218. active: ".am-modal-active"
  5219. },
  5220. cancelable: true,
  5221. onConfirm: function() {},
  5222. onCancel: function() {},
  5223. duration: 300,
  5224. // must equal the CSS transition duration
  5225. transitionEnd: supportTransition.end && supportTransition.end + ".modal.amui"
  5226. };
  5227. Modal.prototype.toggle = function(relatedElement) {
  5228. return this.active ? this.close() : this.open(relatedElement);
  5229. };
  5230. Modal.prototype.open = function(relatedElement) {
  5231. var $element = this.$element;
  5232. var options = this.options;
  5233. var isPopup = this.isPopup;
  5234. if (this.active) {
  5235. return;
  5236. }
  5237. if (!this.$element.length) {
  5238. return;
  5239. }
  5240. // 判断如果还在动画,就先触发之前的closed事件
  5241. if (this.transitioning) {
  5242. clearTimeout($element.transitionEndTimmer);
  5243. $element.transitionEndTimmer = null;
  5244. $element.trigger(options.transitionEnd).off(options.transitionEnd);
  5245. }
  5246. isPopup && this.$element.show();
  5247. this.active = true;
  5248. $element.trigger($.Event("open:modal:amui", {
  5249. relatedElement: relatedElement
  5250. }));
  5251. dimmer.open($element);
  5252. $element.show().redraw();
  5253. !isPopup && $element.css({
  5254. marginTop: -parseInt($element.height() / 2, 10) + "px"
  5255. });
  5256. $element.removeClass(options.className.out).addClass(options.className.active);
  5257. this.transitioning = 1;
  5258. var complete = function() {
  5259. $element.trigger($.Event("opened:modal:amui", {
  5260. relatedElement: relatedElement
  5261. }));
  5262. this.transitioning = 0;
  5263. };
  5264. if (!supportTransition) {
  5265. return complete.call(this);
  5266. }
  5267. $element.one(options.transitionEnd, $.proxy(complete, this)).emulateTransitionEnd(options.duration);
  5268. };
  5269. Modal.prototype.close = function(relatedElement) {
  5270. if (!this.active) {
  5271. return;
  5272. }
  5273. var $element = this.$element;
  5274. var options = this.options;
  5275. var isPopup = this.isPopup;
  5276. // 判断如果还在动画,就先触发之前的opened事件
  5277. if (this.transitioning) {
  5278. clearTimeout($element.transitionEndTimmer);
  5279. $element.transitionEndTimmer = null;
  5280. $element.trigger(options.transitionEnd).off(options.transitionEnd);
  5281. dimmer.close($element, true);
  5282. }
  5283. this.$element.trigger($.Event("close:modal:amui", {
  5284. relatedElement: relatedElement
  5285. }));
  5286. this.transitioning = 1;
  5287. var complete = function() {
  5288. $element.trigger("closed:modal:amui");
  5289. isPopup && $element.removeClass(options.className.out);
  5290. $element.hide();
  5291. this.transitioning = 0;
  5292. };
  5293. $element.removeClass(options.className.active).addClass(options.className.out);
  5294. if (!supportTransition) {
  5295. return complete.call(this);
  5296. }
  5297. $element.one(options.transitionEnd, $.proxy(complete, this)).emulateTransitionEnd(options.duration);
  5298. // 不强制关闭 Dimmer,以便多个 Modal 可以共享 Dimmer
  5299. dimmer.close($element, false);
  5300. this.active = false;
  5301. };
  5302. Modal.prototype.events = function() {
  5303. var that = this;
  5304. var $element = this.$element;
  5305. var $ipt = $element.find(".am-modal-prompt-input");
  5306. if (this.options.cancelable) {
  5307. $element.on("keyup.modal.amui", $.proxy(function(e) {
  5308. if (this.active && e.which === 27) {
  5309. this.options.onCancel();
  5310. this.close();
  5311. }
  5312. }, that));
  5313. dimmer.$element.on("click", function(e) {
  5314. that.close();
  5315. });
  5316. }
  5317. // Close button
  5318. $element.find("[data-am-modal-close]").on("click.modal.amui", function(e) {
  5319. e.preventDefault();
  5320. that.close();
  5321. });
  5322. $element.find(".am-modal-btn").on("click.modal.amui", function(e) {
  5323. that.close();
  5324. });
  5325. $element.find("[data-am-modal-confirm]").on("click.modal.amui", function() {
  5326. that.options.onConfirm($ipt.val());
  5327. });
  5328. $element.find("[data-am-modal-cancel]").on("click.modal.amui", function() {
  5329. that.options.onCancel($ipt.val());
  5330. });
  5331. };
  5332. function Plugin(option, relatedElement) {
  5333. return this.each(function() {
  5334. var $this = $(this);
  5335. var data = $this.data("am.modal");
  5336. var options = $.extend({}, Modal.DEFAULTS, typeof option == "object" && option);
  5337. if (!data) {
  5338. $this.data("am.modal", data = new Modal(this, options));
  5339. }
  5340. if (typeof option == "string") {
  5341. data[option](relatedElement);
  5342. } else {
  5343. data.toggle(option && option.relatedElement || undefined);
  5344. }
  5345. });
  5346. }
  5347. $.fn.modal = Plugin;
  5348. $doc.on("click", "[data-am-modal]", function() {
  5349. var $this = $(this);
  5350. var options = UI.utils.parseOptions($this.attr("data-am-modal"));
  5351. var $target = $(options.target || this.href && this.href.replace(/.*(?=#[^\s]+$)/, ""));
  5352. var option = $target.data("am.modal") ? "toggle" : options;
  5353. Plugin.call($target, option, this);
  5354. });
  5355. UI.modal = Modal;
  5356. module.exports = Modal;
  5357. });
  5358. define("ui.offcanvas", [ "zepto.outerdemension", "zepto.extend.data", "core", "zepto.extend.fx", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5359. "use strict";
  5360. require("zepto.outerdemension");
  5361. require("zepto.extend.data");
  5362. require("core");
  5363. var $ = window.Zepto;
  5364. var UI = $.AMUI;
  5365. var $win = $(window);
  5366. var $doc = $(document);
  5367. var scrollPos;
  5368. /**
  5369. * @via https://github.com/uikit/uikit/blob/master/src/js/offcanvas.js
  5370. * @license https://github.com/uikit/uikit/blob/master/LICENSE.md
  5371. */
  5372. var OffCanvas = function(element, options) {
  5373. this.$element = $(element);
  5374. this.options = options;
  5375. this.active = null;
  5376. this.events();
  5377. };
  5378. OffCanvas.DEFAULTS = {
  5379. duration: 300,
  5380. effect: "overlay"
  5381. };
  5382. OffCanvas.prototype.open = function(relatedElement) {
  5383. var $element = this.$element;
  5384. if (!$element.length || $element.hasClass("am-active")) {
  5385. return;
  5386. }
  5387. var effect = this.options.effect;
  5388. var $html = $("html");
  5389. var $body = $("body");
  5390. var $bar = $element.find(".am-offcanvas-bar").first();
  5391. var dir = $bar.hasClass("am-offcanvas-bar-flip") ? -1 : 1;
  5392. $bar.addClass("am-offcanvas-bar-" + effect);
  5393. scrollPos = {
  5394. x: window.scrollX,
  5395. y: window.scrollY
  5396. };
  5397. $element.addClass("am-active");
  5398. $body.css({
  5399. width: window.innerWidth,
  5400. height: $win.height()
  5401. }).addClass("am-offcanvas-page");
  5402. if (effect !== "overlay") {
  5403. $body.css({
  5404. "margin-left": $bar.outerWidth() * dir
  5405. }).width();
  5406. }
  5407. $html.css("margin-top", scrollPos.y * -1);
  5408. setTimeout(function() {
  5409. $bar.addClass("am-offcanvas-bar-active").width();
  5410. }, 0);
  5411. $doc.trigger("open:offcanvas:amui");
  5412. this.active = 1;
  5413. $element.off(".offcanvas.amui").on("click.offcanvas.amui swipe.offcanvas.amui", $.proxy(function(e) {
  5414. var $target = $(e.target);
  5415. if (!e.type.match(/swipe/)) {
  5416. if ($target.hasClass("am-offcanvas-bar")) {
  5417. return;
  5418. }
  5419. if ($target.parents(".am-offcanvas-bar").first().length) {
  5420. return;
  5421. }
  5422. }
  5423. // https://developer.mozilla.org/zh-CN/docs/DOM/event.stopImmediatePropagation
  5424. e.stopImmediatePropagation();
  5425. this.close();
  5426. }, this));
  5427. $html.on("keydown.offcanvas.amui", $.proxy(function(e) {
  5428. if (e.keyCode === 27) {
  5429. // ESC
  5430. this.close();
  5431. }
  5432. }, this));
  5433. };
  5434. OffCanvas.prototype.close = function(relatedElement) {
  5435. var me = this;
  5436. var $html = $("html");
  5437. var $body = $("body");
  5438. var $element = this.$element;
  5439. var $bar = $element.find(".am-offcanvas-bar").first();
  5440. if (!$element.length || !$element.hasClass("am-active")) {
  5441. return;
  5442. }
  5443. $doc.trigger("close:offcanvas:amui");
  5444. function complete() {
  5445. $body.removeClass("am-offcanvas-page").css({
  5446. width: "",
  5447. height: "",
  5448. "margin-left": "",
  5449. "margin-right": ""
  5450. });
  5451. $element.removeClass("am-active");
  5452. $bar.removeClass("am-offcanvas-bar-active");
  5453. $html.css("margin-top", "");
  5454. window.scrollTo(scrollPos.x, scrollPos.y);
  5455. $doc.trigger("closed:offcanvas:amui");
  5456. me.active = 0;
  5457. }
  5458. if (UI.support.transition) {
  5459. setTimeout(function() {
  5460. $bar.removeClass("am-offcanvas-bar-active");
  5461. }, 0);
  5462. $body.css("margin-left", "").one(UI.support.transition.end, function() {
  5463. complete();
  5464. }).emulateTransitionEnd(this.options.duration);
  5465. } else {
  5466. complete();
  5467. }
  5468. $element.off(".offcanvas.amui");
  5469. $html.off(".offcanvas.amui");
  5470. };
  5471. OffCanvas.prototype.events = function() {
  5472. $doc.on("click.offcanvas.amui", '[data-am-dismiss="offcanvas"]', $.proxy(function(e) {
  5473. e.preventDefault();
  5474. this.close();
  5475. }, this));
  5476. $win.on("resize.offcanvas.amui orientationchange.offcanvas.amui", $.proxy(function(e) {
  5477. this.active && this.close();
  5478. }, this));
  5479. return this;
  5480. };
  5481. function Plugin(option, relatedElement) {
  5482. return this.each(function() {
  5483. var $this = $(this);
  5484. var data = $this.data("am.offcanvas");
  5485. var options = $.extend({}, OffCanvas.DEFAULTS, typeof option == "object" && option);
  5486. if (!data) {
  5487. $this.data("am.offcanvas", data = new OffCanvas(this, options));
  5488. data.open(relatedElement);
  5489. }
  5490. if (typeof option == "string") {
  5491. data[option] && data[option](relatedElement);
  5492. }
  5493. });
  5494. }
  5495. $.fn.offCanvas = Plugin;
  5496. // Init code
  5497. $doc.on("click.offcanvas.amui", "[data-am-offcanvas]", function(e) {
  5498. e.preventDefault();
  5499. var $this = $(this);
  5500. var options = UI.utils.parseOptions($this.data("amOffcanvas"));
  5501. var $target = $(options.target || this.href && this.href.replace(/.*(?=#[^\s]+$)/, ""));
  5502. var option = $target.data("am.offcanvas") ? "open" : options;
  5503. Plugin.call($target, option, this);
  5504. });
  5505. UI.offcanvas = OffCanvas;
  5506. module.exports = OffCanvas;
  5507. });
  5508. define("ui.popover", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5509. "use strict";
  5510. require("core");
  5511. var $ = window.Zepto;
  5512. var UI = $.AMUI;
  5513. var $w = $(window);
  5514. /**
  5515. * @reference https://github.com/nolimits4web/Framework7/blob/master/src/js/modals.js
  5516. * @license https://github.com/nolimits4web/Framework7/blob/master/LICENSE
  5517. */
  5518. var Popover = function(element, options) {
  5519. this.options = $.extend({}, Popover.DEFAULTS, options || {});
  5520. this.$element = $(element);
  5521. this.active = null;
  5522. this.$popover = this.options.target && $(this.options.target) || null;
  5523. this.init();
  5524. this.events();
  5525. };
  5526. Popover.DEFAULTS = {
  5527. trigger: "click",
  5528. content: "",
  5529. open: false,
  5530. target: undefined,
  5531. tpl: '<div class="am-popover">' + '<div class="am-popover-inner"></div>' + '<div class="am-popover-caret"></div></div>'
  5532. };
  5533. Popover.prototype.init = function() {
  5534. var me = this;
  5535. var $element = this.$element;
  5536. var $popover;
  5537. if (!this.options.target) {
  5538. this.$popover = this.getPopover();
  5539. this.setContent();
  5540. }
  5541. $popover = this.$popover;
  5542. $popover.appendTo($("body"));
  5543. this.sizePopover();
  5544. function sizePopover() {
  5545. me.sizePopover();
  5546. }
  5547. $(window).on("resize:popover:amui", UI.utils.debounce(sizePopover, 50));
  5548. $element.on("open:popover:amui", function() {
  5549. $(window).on("resize:popover:amui", UI.utils.debounce(sizePopover, 50));
  5550. });
  5551. $element.on("close:popover:amui", function() {
  5552. $(window).off("resize:popover:amui", sizePopover);
  5553. });
  5554. this.options.open && this.open();
  5555. };
  5556. Popover.prototype.sizePopover = function sizePopover() {
  5557. var $element = this.$element;
  5558. var $popover = this.$popover;
  5559. if (!$popover || !$popover.length) {
  5560. return;
  5561. }
  5562. var popSize = $popover.getSize();
  5563. var popWidth = $popover.width() || popSize.width;
  5564. var popHeight = $popover.height() || popSize.height;
  5565. var $popCaret = $popover.find(".am-popover-caret");
  5566. var popCaretSize = $popCaret.width() / 2 || 10;
  5567. var popTotalHeight = popHeight + popCaretSize;
  5568. var triggerWidth = $element.outerWidth();
  5569. var triggerHeight = $element.outerHeight();
  5570. var triggerOffset = $element.offset();
  5571. var triggerRect = $element[0].getBoundingClientRect();
  5572. var winHeight = $w.height();
  5573. var winWidth = $w.width();
  5574. var popTop = 0;
  5575. var popLeft = 0;
  5576. var diff = 0;
  5577. var spacing = 3;
  5578. var popPosition = "top";
  5579. $popover.css({
  5580. left: "",
  5581. top: ""
  5582. }).removeClass("am-popover-left am-popover-right am-popover-top am-popover-bottom");
  5583. $popCaret.css({
  5584. left: "",
  5585. top: ""
  5586. });
  5587. if (popTotalHeight - spacing < triggerRect.top + spacing) {
  5588. // on Top
  5589. popTop = triggerOffset.top - popTotalHeight - spacing;
  5590. } else if (popTotalHeight < winHeight - triggerRect.top - triggerRect.height) {
  5591. // On bottom
  5592. popPosition = "bottom";
  5593. popTop = triggerOffset.top + triggerHeight + popCaretSize + spacing;
  5594. } else {
  5595. // On middle
  5596. popPosition = "middle";
  5597. popTop = triggerHeight / 2 + triggerOffset.top - popHeight / 2;
  5598. }
  5599. // Horizontal Position
  5600. if (popPosition === "top" || popPosition === "bottom") {
  5601. popLeft = triggerWidth / 2 + triggerOffset.left - popWidth / 2;
  5602. diff = popLeft;
  5603. if (popLeft < 5) {
  5604. popLeft = 5;
  5605. }
  5606. if (popLeft + popWidth > winWidth) {
  5607. popLeft = winWidth - popWidth - 20;
  5608. }
  5609. if (popPosition === "top") {
  5610. $popover.addClass("am-popover-bottom");
  5611. }
  5612. if (popPosition === "bottom") {
  5613. $popover.addClass("am-popover-top");
  5614. }
  5615. diff = diff - popLeft;
  5616. $popCaret.css({
  5617. left: popWidth / 2 - popCaretSize + diff + "px"
  5618. });
  5619. } else if (popPosition === "middle") {
  5620. popLeft = triggerOffset.left - popWidth - popCaretSize;
  5621. $popover.addClass("am-popover-left");
  5622. if (popLeft < 5) {
  5623. popLeft = triggerOffset.left + triggerWidth + popCaretSize;
  5624. $popover.removeClass("am-popover-left").addClass("am-popover-right");
  5625. }
  5626. if (popLeft + popWidth > winWidth) {
  5627. popLeft = winWidth - popWidth - 5;
  5628. $popover.removeClass("am-popover-left").addClass("am-popover-right");
  5629. }
  5630. $popCaret.css({
  5631. top: popHeight / 2 - popCaretSize / 2 + "px"
  5632. });
  5633. }
  5634. // Apply position style
  5635. $popover.css({
  5636. top: popTop + "px",
  5637. left: popLeft + "px"
  5638. });
  5639. };
  5640. Popover.prototype.toggle = function() {
  5641. return this[this.active ? "close" : "open"]();
  5642. };
  5643. Popover.prototype.open = function() {
  5644. var $popover = this.$popover;
  5645. this.$element.trigger("open:popover:amui");
  5646. this.sizePopover();
  5647. $popover.show().addClass("am-active");
  5648. this.active = true;
  5649. };
  5650. Popover.prototype.close = function() {
  5651. var $popover = this.$popover;
  5652. this.$element.trigger("close:popover:amui");
  5653. $popover.removeClass("am-active").trigger("closed:popover:amui").hide();
  5654. this.active = false;
  5655. };
  5656. Popover.prototype.getPopover = function() {
  5657. var uid = UI.utils.generateGUID("am-popover");
  5658. return $(this.options.tpl, {
  5659. id: uid
  5660. });
  5661. };
  5662. Popover.prototype.setContent = function() {
  5663. this.$popover && this.$popover.find(".am-popover-inner").empty().html(this.options.content);
  5664. };
  5665. Popover.prototype.events = function() {
  5666. var eventNS = "popover.amui";
  5667. var triggers = this.options.trigger.split(" ");
  5668. for (var i = triggers.length; i--; ) {
  5669. var trigger = triggers[i];
  5670. if (trigger === "click") {
  5671. this.$element.on("click." + eventNS, $.proxy(this.toggle, this));
  5672. } else {
  5673. // hover or focus
  5674. var eventIn = trigger == "hover" ? "mouseenter" : "focusin";
  5675. var eventOut = trigger == "hover" ? "mouseleave" : "focusout";
  5676. this.$element.on(eventIn + "." + eventNS, $.proxy(this.open, this));
  5677. this.$element.on(eventOut + "." + eventNS, $.proxy(this.close, this));
  5678. }
  5679. }
  5680. };
  5681. function Plugin(option) {
  5682. return this.each(function() {
  5683. var $this = $(this);
  5684. var data = $this.data("am.popover");
  5685. var options = $.extend({}, UI.utils.parseOptions($this.attr("data-am-popover")), typeof option == "object" && option);
  5686. if (!data) {
  5687. $this.data("am.popover", data = new Popover(this, options));
  5688. }
  5689. if (typeof option == "string") {
  5690. data[option]();
  5691. }
  5692. });
  5693. }
  5694. $.fn.popover = Plugin;
  5695. // Init code
  5696. $(function() {
  5697. $("[data-am-popover]").popover();
  5698. });
  5699. UI.popover = Popover;
  5700. module.exports = Popover;
  5701. });
  5702. define("ui.progress", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  5703. "use strict";
  5704. require("core");
  5705. var $ = window.Zepto;
  5706. var UI = $.AMUI;
  5707. var Progress = function() {
  5708. /**
  5709. * NProgress (c) 2013, Rico Sta. Cruz
  5710. * @via http://ricostacruz.com/nprogress
  5711. */
  5712. var NProgress = {};
  5713. var $html = $("html");
  5714. NProgress.version = "0.1.6";
  5715. var Settings = NProgress.settings = {
  5716. minimum: .08,
  5717. easing: "ease",
  5718. positionUsing: "",
  5719. speed: 200,
  5720. trickle: true,
  5721. trickleRate: .02,
  5722. trickleSpeed: 800,
  5723. showSpinner: true,
  5724. parent: "body",
  5725. barSelector: '[role="nprogress-bar"]',
  5726. spinnerSelector: '[role="nprogress-spinner"]',
  5727. template: '<div class="nprogress-bar" role="nprogress-bar">' + '<div class="nprogress-peg"></div></div>' + '<div class="nprogress-spinner" role="nprogress-spinner">' + '<div class="nprogress-spinner-icon"></div></div>'
  5728. };
  5729. /**
  5730. * Updates configuration.
  5731. *
  5732. * NProgress.configure({
  5733. * minimum: 0.1
  5734. * });
  5735. */
  5736. NProgress.configure = function(options) {
  5737. var key, value;
  5738. for (key in options) {
  5739. value = options[key];
  5740. if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value;
  5741. }
  5742. return this;
  5743. };
  5744. /**
  5745. * Last number.
  5746. */
  5747. NProgress.status = null;
  5748. /**
  5749. * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
  5750. *
  5751. * NProgress.set(0.4);
  5752. * NProgress.set(1.0);
  5753. */
  5754. NProgress.set = function(n) {
  5755. var started = NProgress.isStarted();
  5756. n = clamp(n, Settings.minimum, 1);
  5757. NProgress.status = n === 1 ? null : n;
  5758. var progress = NProgress.render(!started), bar = progress.querySelector(Settings.barSelector), speed = Settings.speed, ease = Settings.easing;
  5759. progress.offsetWidth;
  5760. /* Repaint */
  5761. queue(function(next) {
  5762. // Set positionUsing if it hasn't already been set
  5763. if (Settings.positionUsing === "") Settings.positionUsing = NProgress.getPositioningCSS();
  5764. // Add transition
  5765. css(bar, barPositionCSS(n, speed, ease));
  5766. if (n === 1) {
  5767. // Fade out
  5768. css(progress, {
  5769. transition: "none",
  5770. opacity: 1
  5771. });
  5772. progress.offsetWidth;
  5773. /* Repaint */
  5774. setTimeout(function() {
  5775. css(progress, {
  5776. transition: "all " + speed + "ms linear",
  5777. opacity: 0
  5778. });
  5779. setTimeout(function() {
  5780. NProgress.remove();
  5781. next();
  5782. }, speed);
  5783. }, speed);
  5784. } else {
  5785. setTimeout(next, speed);
  5786. }
  5787. });
  5788. return this;
  5789. };
  5790. NProgress.isStarted = function() {
  5791. return typeof NProgress.status === "number";
  5792. };
  5793. /**
  5794. * Shows the progress bar.
  5795. * This is the same as setting the status to 0%, except that it doesn't go backwards.
  5796. *
  5797. * NProgress.start();
  5798. *
  5799. */
  5800. NProgress.start = function() {
  5801. if (!NProgress.status) NProgress.set(0);
  5802. var work = function() {
  5803. setTimeout(function() {
  5804. if (!NProgress.status) return;
  5805. NProgress.trickle();
  5806. work();
  5807. }, Settings.trickleSpeed);
  5808. };
  5809. if (Settings.trickle) work();
  5810. return this;
  5811. };
  5812. /**
  5813. * Hides the progress bar.
  5814. * This is the *sort of* the same as setting the status to 100%, with the
  5815. * difference being `done()` makes some placebo effect of some realistic motion.
  5816. *
  5817. * NProgress.done();
  5818. *
  5819. * If `true` is passed, it will show the progress bar even if its hidden.
  5820. *
  5821. * NProgress.done(true);
  5822. */
  5823. NProgress.done = function(force) {
  5824. if (!force && !NProgress.status) return this;
  5825. return NProgress.inc(.3 + .5 * Math.random()).set(1);
  5826. };
  5827. /**
  5828. * Increments by a random amount.
  5829. */
  5830. NProgress.inc = function(amount) {
  5831. var n = NProgress.status;
  5832. if (!n) {
  5833. return NProgress.start();
  5834. } else {
  5835. if (typeof amount !== "number") {
  5836. amount = (1 - n) * clamp(Math.random() * n, .1, .95);
  5837. }
  5838. n = clamp(n + amount, 0, .994);
  5839. return NProgress.set(n);
  5840. }
  5841. };
  5842. NProgress.trickle = function() {
  5843. return NProgress.inc(Math.random() * Settings.trickleRate);
  5844. };
  5845. /**
  5846. * (Internal) renders the progress bar markup based on the `template`
  5847. * setting.
  5848. */
  5849. NProgress.render = function(fromStart) {
  5850. if (NProgress.isRendered()) return document.getElementById("nprogress");
  5851. $html.addClass("nprogress-busy");
  5852. var progress = document.createElement("div");
  5853. progress.id = "nprogress";
  5854. progress.innerHTML = Settings.template;
  5855. var bar = progress.querySelector(Settings.barSelector), perc = fromStart ? "-100" : toBarPerc(NProgress.status || 0), parent = document.querySelector(Settings.parent), spinner;
  5856. css(bar, {
  5857. transition: "all 0 linear",
  5858. transform: "translate3d(" + perc + "%,0,0)"
  5859. });
  5860. if (!Settings.showSpinner) {
  5861. spinner = progress.querySelector(Settings.spinnerSelector);
  5862. spinner && $(spinner).remove();
  5863. }
  5864. if (parent != document.body) {
  5865. $(parent).addClass("nprogress-custom-parent");
  5866. }
  5867. parent.appendChild(progress);
  5868. return progress;
  5869. };
  5870. /**
  5871. * Removes the element. Opposite of render().
  5872. */
  5873. NProgress.remove = function() {
  5874. $html.removeClass("nprogress-busy");
  5875. $(Settings.parent).removeClass("nprogress-custom-parent");
  5876. var progress = document.getElementById("nprogress");
  5877. progress && $(progress).remove();
  5878. };
  5879. /**
  5880. * Checks if the progress bar is rendered.
  5881. */
  5882. NProgress.isRendered = function() {
  5883. return !!document.getElementById("nprogress");
  5884. };
  5885. /**
  5886. * Determine which positioning CSS rule to use.
  5887. */
  5888. NProgress.getPositioningCSS = function() {
  5889. // Sniff on document.body.style
  5890. var bodyStyle = document.body.style;
  5891. // Sniff prefixes
  5892. var vendorPrefix = "WebkitTransform" in bodyStyle ? "Webkit" : "MozTransform" in bodyStyle ? "Moz" : "msTransform" in bodyStyle ? "ms" : "OTransform" in bodyStyle ? "O" : "";
  5893. if (vendorPrefix + "Perspective" in bodyStyle) {
  5894. // Modern browsers with 3D support, e.g. Webkit, IE10
  5895. return "translate3d";
  5896. } else if (vendorPrefix + "Transform" in bodyStyle) {
  5897. // Browsers without 3D support, e.g. IE9
  5898. return "translate";
  5899. } else {
  5900. // Browsers without translate() support, e.g. IE7-8
  5901. return "margin";
  5902. }
  5903. };
  5904. /**
  5905. * Helpers
  5906. */
  5907. function clamp(n, min, max) {
  5908. if (n < min) return min;
  5909. if (n > max) return max;
  5910. return n;
  5911. }
  5912. /**
  5913. * (Internal) converts a percentage (`0..1`) to a bar translateX
  5914. * percentage (`-100%..0%`).
  5915. */
  5916. function toBarPerc(n) {
  5917. return (-1 + n) * 100;
  5918. }
  5919. /**
  5920. * (Internal) returns the correct CSS for changing the bar's
  5921. * position given an n percentage, and speed and ease from Settings
  5922. */
  5923. function barPositionCSS(n, speed, ease) {
  5924. var barCSS;
  5925. if (Settings.positionUsing === "translate3d") {
  5926. barCSS = {
  5927. transform: "translate3d(" + toBarPerc(n) + "%,0,0)"
  5928. };
  5929. } else if (Settings.positionUsing === "translate") {
  5930. barCSS = {
  5931. transform: "translate(" + toBarPerc(n) + "%,0)"
  5932. };
  5933. } else {
  5934. barCSS = {
  5935. "margin-left": toBarPerc(n) + "%"
  5936. };
  5937. }
  5938. barCSS.transition = "all " + speed + "ms " + ease;
  5939. return barCSS;
  5940. }
  5941. /**
  5942. * (Internal) Queues a function to be executed.
  5943. */
  5944. var queue = function() {
  5945. var pending = [];
  5946. function next() {
  5947. var fn = pending.shift();
  5948. if (fn) {
  5949. fn(next);
  5950. }
  5951. }
  5952. return function(fn) {
  5953. pending.push(fn);
  5954. if (pending.length == 1) next();
  5955. };
  5956. }();
  5957. /**
  5958. * (Internal) Applies css properties to an element, similar to the jQuery
  5959. * css method.
  5960. *
  5961. * While this helper does assist with vendor prefixed property names, it
  5962. * does not perform any manipulation of values prior to setting styles.
  5963. */
  5964. var css = function() {
  5965. var cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], cssProps = {};
  5966. function camelCase(string) {
  5967. return string.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function(match, letter) {
  5968. return letter.toUpperCase();
  5969. });
  5970. }
  5971. function getVendorProp(name) {
  5972. var style = document.body.style;
  5973. if (name in style) return name;
  5974. var i = cssPrefixes.length, capName = name.charAt(0).toUpperCase() + name.slice(1), vendorName;
  5975. while (i--) {
  5976. vendorName = cssPrefixes[i] + capName;
  5977. if (vendorName in style) return vendorName;
  5978. }
  5979. return name;
  5980. }
  5981. function getStyleProp(name) {
  5982. name = camelCase(name);
  5983. return cssProps[name] || (cssProps[name] = getVendorProp(name));
  5984. }
  5985. function applyCss(element, prop, value) {
  5986. prop = getStyleProp(prop);
  5987. element.style[prop] = value;
  5988. }
  5989. return function(element, properties) {
  5990. var args = arguments, prop, value;
  5991. if (args.length == 2) {
  5992. for (prop in properties) {
  5993. value = properties[prop];
  5994. if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
  5995. }
  5996. } else {
  5997. applyCss(element, args[1], args[2]);
  5998. }
  5999. };
  6000. }();
  6001. return NProgress;
  6002. }();
  6003. UI.progress = Progress;
  6004. module.exports = Progress;
  6005. });
  6006. define("ui.pureview", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "zepto.pinchzoom", "util.hammer" ], function(require, exports, module) {
  6007. "use strict";
  6008. require("core");
  6009. var PinchZoom = require("zepto.pinchzoom");
  6010. var Hammer = require("util.hammer");
  6011. var $ = window.Zepto;
  6012. var UI = $.AMUI;
  6013. var animation = UI.support.animation;
  6014. var transition = UI.support.transition;
  6015. /**
  6016. * PureView
  6017. * @desc Image browser for Mobile
  6018. * @param element
  6019. * @param options
  6020. * @constructor
  6021. */
  6022. var PureView = function(element, options) {
  6023. this.$element = $(element);
  6024. this.$body = $(document.body);
  6025. this.options = $.extend({}, PureView.DEFAULTS, options);
  6026. this.$pureview = $(this.options.tpl, {
  6027. id: UI.utils.generateGUID("am-pureview")
  6028. });
  6029. this.$slides = null;
  6030. this.transitioning = null;
  6031. this.scrollbarWidth = 0;
  6032. this.init();
  6033. };
  6034. PureView.DEFAULTS = {
  6035. tpl: '<div class="am-pureview am-pureview-bar-active">' + '<ul class="am-pureview-slider"></ul>' + '<ul class="am-pureview-direction">' + '<li class="am-pureview-prev"><a href=""></a></li>' + '<li class="am-pureview-next"><a href=""></a></li></ul>' + '<ol class="am-pureview-nav"></ol>' + '<div class="am-pureview-bar am-active">' + '<span class="am-pureview-title"></span>' + '<span class="am-pureview-current"></span> / ' + '<span class="am-pureview-total"></span></div>' + '<div class="am-pureview-actions am-active">' + '<a href="javascript: void(0)" class="am-icon-chevron-left" ' + 'data-am-close="pureview"></a></div>' + "</div>",
  6036. className: {
  6037. prevSlide: "am-pureview-slide-prev",
  6038. nextSlide: "am-pureview-slide-next",
  6039. onlyOne: "am-pureview-only",
  6040. active: "am-active",
  6041. barActive: "am-pureview-bar-active",
  6042. activeBody: "am-pureview-active"
  6043. },
  6044. selector: {
  6045. slider: ".am-pureview-slider",
  6046. close: '[data-am-close="pureview"]',
  6047. total: ".am-pureview-total",
  6048. current: ".am-pureview-current",
  6049. title: ".am-pureview-title",
  6050. actions: ".am-pureview-actions",
  6051. bar: ".am-pureview-bar",
  6052. pinchZoom: ".am-pinch-zoom",
  6053. nav: ".am-pureview-nav"
  6054. },
  6055. shareBtn: false,
  6056. // 从何处获取图片,img 可以使用 data-rel 指定大图
  6057. target: "img",
  6058. // 微信 Webview 中调用微信的图片浏览器
  6059. // 实现图片保存、分享好友、收藏图片等功能
  6060. weChatImagePreview: true
  6061. };
  6062. PureView.prototype.init = function() {
  6063. var me = this;
  6064. var options = this.options;
  6065. var $element = this.$element;
  6066. var $pureview = this.$pureview;
  6067. var $slider = $pureview.find(options.selector.slider);
  6068. var $nav = $pureview.find(options.selector.nav);
  6069. var $slides = $([]);
  6070. var $navItems = $([]);
  6071. var $images = $element.find(options.target);
  6072. var total = $images.length;
  6073. var imgUrls = [];
  6074. if (!total) {
  6075. return;
  6076. }
  6077. if (total === 1) {
  6078. $pureview.addClass(options.className.onlyOne);
  6079. }
  6080. $images.each(function(i, item) {
  6081. var src;
  6082. var title;
  6083. if (options.target == "a") {
  6084. src = item.href;
  6085. // to absolute path
  6086. title = item.title || "";
  6087. } else {
  6088. src = $(item).data("rel") || item.src;
  6089. // <img src='' data-rel='' />
  6090. title = $(item).attr("alt") || "";
  6091. }
  6092. // hide bar: wechat_webview_type=1
  6093. // http://tmt.io/wechat/ not working?
  6094. imgUrls.push(src);
  6095. $slides = $slides.add($('<li><div class="am-pinch-zoom">' + '<img src="' + src + '" alt="' + title + '"/></div></li>'));
  6096. $navItems = $navItems.add($("<li>" + (i + 1) + "</li>"));
  6097. });
  6098. $slider.append($slides);
  6099. $nav.append($navItems);
  6100. $("body").append($pureview);
  6101. $pureview.find(options.selector.total).text(total);
  6102. this.$title = $pureview.find(options.selector.title);
  6103. this.$current = $pureview.find(options.selector.current);
  6104. this.$bar = $pureview.find(options.selector.bar);
  6105. this.$actions = $pureview.find(options.selector.actions);
  6106. this.$navItems = $nav.find("li");
  6107. this.$slides = $slider.find("li");
  6108. if (options.shareBtn) {
  6109. this.$actions.append('<a href="javascript: void(0)" ' + 'class="am-icon-share-square-o" data-am-toggle="share"></a>');
  6110. }
  6111. $slider.find(options.selector.pinchZoom).each(function() {
  6112. $(this).data("amui.pinchzoom", new PinchZoom($(this), {}));
  6113. $(this).on("pz_doubletap", function(e) {});
  6114. });
  6115. $images.on("click.pureview.amui", function(e) {
  6116. e.preventDefault();
  6117. var clicked = $images.index(this);
  6118. // Invoke WeChat ImagePreview in WeChat
  6119. // TODO: detect WeChat before init
  6120. if (options.weChatImagePreview && window.WeixinJSBridge) {
  6121. window.WeixinJSBridge.invoke("imagePreview", {
  6122. current: imgUrls[clicked],
  6123. urls: imgUrls
  6124. });
  6125. } else {
  6126. me.open(clicked);
  6127. }
  6128. });
  6129. $pureview.find(".am-pureview-direction a").on("click.direction.pureview.amui", function(e) {
  6130. e.preventDefault();
  6131. var $clicked = $(e.target).parent("li");
  6132. if ($clicked.is(".am-pureview-prev")) {
  6133. me.prevSlide();
  6134. } else {
  6135. me.nextSlide();
  6136. }
  6137. });
  6138. // Nav Contorl
  6139. this.$navItems.on("click.nav.pureview.amui", function() {
  6140. var index = me.$navItems.index($(this));
  6141. me.activate(me.$slides.eq(index));
  6142. });
  6143. // Close Icon
  6144. $pureview.find(options.selector.close).on("click.close.pureview.amui", function(e) {
  6145. e.preventDefault();
  6146. me.close();
  6147. });
  6148. $slider.hammer().on("press.pureview.amui", function(e) {
  6149. e.preventDefault();
  6150. me.toggleToolBar();
  6151. }).on("swipeleft.pureview.amui", function(e) {
  6152. e.preventDefault();
  6153. me.nextSlide();
  6154. }).on("swiperight.pureview.amui", function(e) {
  6155. e.preventDefault();
  6156. me.prevSlide();
  6157. });
  6158. $slider.data("hammer").get("swipe").set({
  6159. direction: Hammer.DIRECTION_HORIZONTAL,
  6160. velocity: .35
  6161. });
  6162. $(document).on("keydown.pureview.amui", $.proxy(function(e) {
  6163. var keyCode = e.keyCode;
  6164. if (keyCode == 37) {
  6165. this.prevSlide();
  6166. } else if (keyCode == 39) {
  6167. this.nextSlide();
  6168. } else if (keyCode == 27) {
  6169. this.close();
  6170. }
  6171. }, this));
  6172. };
  6173. PureView.prototype.activate = function($slide) {
  6174. var options = this.options;
  6175. var $slides = this.$slides;
  6176. var activeIndex = $slides.index($slide);
  6177. var alt = $slide.find("img").attr("alt") || "";
  6178. var active = options.className.active;
  6179. UI.utils.imageLoader($slide.find("img"), function(image) {
  6180. $(image).addClass("am-img-loaded");
  6181. });
  6182. if ($slides.find("." + active).is($slide)) {
  6183. return;
  6184. }
  6185. if (this.transitioning) {
  6186. return;
  6187. }
  6188. this.transitioning = 1;
  6189. this.$title.text(alt);
  6190. this.$current.text(activeIndex + 1);
  6191. $slides.removeClass();
  6192. $slide.addClass(active);
  6193. $slides.eq(activeIndex - 1).addClass(options.className.prevSlide);
  6194. $slides.eq(activeIndex + 1).addClass(options.className.nextSlide);
  6195. this.$navItems.removeClass().eq(activeIndex).addClass(options.className.active);
  6196. if (transition) {
  6197. $slide.one(transition.end, $.proxy(function() {
  6198. this.transitioning = 0;
  6199. }, this)).emulateTransitionEnd(300);
  6200. } else {
  6201. this.transitioning = 0;
  6202. }
  6203. };
  6204. PureView.prototype.nextSlide = function() {
  6205. if (this.$slides.length === 1) {
  6206. return;
  6207. }
  6208. var $slides = this.$slides;
  6209. var $active = $slides.filter(".am-active");
  6210. var activeIndex = $slides.index($active);
  6211. var rightSpring = "am-animation-right-spring";
  6212. if (activeIndex + 1 >= $slides.length) {
  6213. // last one
  6214. animation && $active.addClass(rightSpring).on(animation.end, function() {
  6215. $active.removeClass(rightSpring);
  6216. });
  6217. } else {
  6218. this.activate($slides.eq(activeIndex + 1));
  6219. }
  6220. };
  6221. PureView.prototype.prevSlide = function() {
  6222. if (this.$slides.length === 1) {
  6223. return;
  6224. }
  6225. var $slides = this.$slides;
  6226. var $active = $slides.filter(".am-active");
  6227. var activeIndex = this.$slides.index($active);
  6228. var leftSpring = "am-animation-left-spring";
  6229. if (activeIndex === 0) {
  6230. // first one
  6231. animation && $active.addClass(leftSpring).on(animation.end, function() {
  6232. $active.removeClass(leftSpring);
  6233. });
  6234. } else {
  6235. this.activate($slides.eq(activeIndex - 1));
  6236. }
  6237. };
  6238. PureView.prototype.toggleToolBar = function() {
  6239. this.$pureview.toggleClass(this.options.className.barActive);
  6240. };
  6241. PureView.prototype.open = function(index) {
  6242. var active = index || 0;
  6243. this.checkScrollbar();
  6244. this.setScrollbar();
  6245. this.activate(this.$slides.eq(active));
  6246. this.$pureview.addClass(this.options.className.active);
  6247. this.$body.addClass(this.options.className.activeBody);
  6248. };
  6249. PureView.prototype.close = function() {
  6250. var options = this.options;
  6251. this.$pureview.removeClass(options.className.active);
  6252. this.$slides.removeClass();
  6253. function resetBody() {
  6254. this.$body.removeClass(options.className.activeBody);
  6255. this.resetScrollbar();
  6256. }
  6257. if (transition) {
  6258. this.$pureview.one(transition.end, $.proxy(resetBody, this));
  6259. } else {
  6260. resetBody.call(this);
  6261. }
  6262. };
  6263. PureView.prototype.checkScrollbar = function() {
  6264. this.scrollbarWidth = UI.utils.measureScrollbar();
  6265. };
  6266. PureView.prototype.setScrollbar = function() {
  6267. var bodyPaddingRight = parseInt(this.$body.css("padding-right") || 0, 10);
  6268. if (this.scrollbarWidth) {
  6269. this.$body.css("padding-right", bodyPaddingRight + this.scrollbarWidth);
  6270. }
  6271. };
  6272. PureView.prototype.resetScrollbar = function() {
  6273. this.$body.css("padding-right", "");
  6274. };
  6275. function Plugin(option) {
  6276. return this.each(function() {
  6277. var $this = $(this);
  6278. var data = $this.data("am.pureview");
  6279. var options = $.extend({}, UI.utils.parseOptions($this.data("amPureview")), typeof option == "object" && option);
  6280. if (!data) {
  6281. $this.data("am.pureview", data = new PureView(this, options));
  6282. }
  6283. if (typeof option == "string") {
  6284. data[option]();
  6285. }
  6286. });
  6287. }
  6288. $.fn.pureview = Plugin;
  6289. // Init code
  6290. $(function() {
  6291. $("[data-am-pureview]").pureview();
  6292. });
  6293. UI.pureview = PureView;
  6294. module.exports = PureView;
  6295. });
  6296. define("ui.scrollspy", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  6297. "use strict";
  6298. require("core");
  6299. var $ = window.Zepto;
  6300. var UI = $.AMUI;
  6301. /**
  6302. * @via https://github.com/uikit/uikit/blob/master/src/js/scrollspy.js
  6303. * @license https://github.com/uikit/uikit/blob/master/LICENSE.md
  6304. */
  6305. var ScrollSpy = function(element, options) {
  6306. if (!UI.support.animation) {
  6307. return;
  6308. }
  6309. this.options = $.extend({}, ScrollSpy.DEFAULTS, options);
  6310. this.$element = $(element);
  6311. var checkViewRAF = function() {
  6312. UI.utils.rAF.call(window, $.proxy(this.checkView, this));
  6313. }.bind(this);
  6314. this.$window = $(window).on("scroll.scrollspy.amui", checkViewRAF).on("resize.scrollspy.amui orientationchange.scrollspy.amui", UI.utils.debounce(checkViewRAF, 50));
  6315. this.timer = this.inViewState = this.initInView = null;
  6316. checkViewRAF();
  6317. };
  6318. ScrollSpy.DEFAULTS = {
  6319. animation: "fade",
  6320. className: {
  6321. inView: "am-scrollspy-inview",
  6322. init: "am-scrollspy-init"
  6323. },
  6324. repeat: true,
  6325. delay: 0,
  6326. topOffset: 0,
  6327. leftOffset: 0
  6328. };
  6329. ScrollSpy.prototype.checkView = function() {
  6330. var $element = this.$element;
  6331. var options = this.options;
  6332. var inView = UI.utils.isInView($element, options);
  6333. var animation = options.animation ? " am-animation-" + options.animation : "";
  6334. if (inView && !this.inViewState) {
  6335. if (this.timer) {
  6336. clearTimeout(this.timer);
  6337. }
  6338. if (!this.initInView) {
  6339. $element.addClass(options.className.init);
  6340. this.offset = $element.offset();
  6341. this.initInView = true;
  6342. $element.trigger("init:scrollspy:amui");
  6343. }
  6344. this.timer = setTimeout(function() {
  6345. if (inView) {
  6346. $element.addClass(options.className.inView + animation).width();
  6347. }
  6348. }, options.delay);
  6349. this.inViewState = true;
  6350. $element.trigger("inview:scrollspy:amui");
  6351. }
  6352. if (!inView && this.inViewState && options.repeat) {
  6353. $element.removeClass(options.className.inView + animation);
  6354. this.inViewState = false;
  6355. $element.trigger("outview:scrollspy:amui");
  6356. }
  6357. };
  6358. ScrollSpy.prototype.check = function() {
  6359. UI.utils.rAF.call(window, $.proxy(this.checkView, this));
  6360. };
  6361. // Sticky Plugin
  6362. function Plugin(option) {
  6363. return this.each(function() {
  6364. var $this = $(this);
  6365. var data = $this.data("am.scrollspy");
  6366. var options = typeof option == "object" && option;
  6367. if (!data) {
  6368. $this.data("am.scrollspy", data = new ScrollSpy(this, options));
  6369. }
  6370. if (typeof option == "string") {
  6371. data[option]();
  6372. }
  6373. });
  6374. }
  6375. $.fn.scrollspy = Plugin;
  6376. // Init code
  6377. $(function() {
  6378. $("[data-am-scrollspy]").each(function() {
  6379. var $this = $(this), options = UI.utils.options($this.attr("data-am-scrollspy"));
  6380. $this.scrollspy(options);
  6381. });
  6382. });
  6383. UI.scrollspy = ScrollSpy;
  6384. module.exports = ScrollSpy;
  6385. });
  6386. define("ui.scrollspynav", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.smooth-scroll" ], function(require, exports, module) {
  6387. "use strict";
  6388. require("core");
  6389. require("ui.smooth-scroll");
  6390. var $ = window.Zepto;
  6391. var UI = $.AMUI;
  6392. /**
  6393. * @via https://github.com/uikit/uikit/
  6394. * @license https://github.com/uikit/uikit/blob/master/LICENSE.md
  6395. */
  6396. // ScrollSpyNav Class
  6397. var ScrollSpyNav = function(element, options) {
  6398. this.options = $.extend({}, ScrollSpyNav.DEFAULTS, options);
  6399. this.$element = $(element);
  6400. this.anchors = [];
  6401. this.$links = this.$element.find('a[href^="#"]').each(function(i, link) {
  6402. this.anchors.push($(link).attr("href"));
  6403. }.bind(this));
  6404. this.$targets = $(this.anchors.join(", "));
  6405. var processRAF = function() {
  6406. UI.utils.rAF.call(window, $.proxy(this.process, this));
  6407. }.bind(this);
  6408. this.$window = $(window).on("scroll.scrollspynav.amui", processRAF).on("resize.scrollspynav.amui orientationchange.scrollspynav.amui", UI.utils.debounce(processRAF, 50));
  6409. processRAF();
  6410. this.scrollProcess();
  6411. };
  6412. ScrollSpyNav.DEFAULTS = {
  6413. className: {
  6414. active: "am-active"
  6415. },
  6416. closest: false,
  6417. smooth: true
  6418. };
  6419. ScrollSpyNav.prototype.process = function() {
  6420. var scrollTop = this.$window.scrollTop();
  6421. var options = this.options;
  6422. var inViews = [];
  6423. var $links = this.$links;
  6424. var $targets = this.$targets;
  6425. $targets.each(function(i, target) {
  6426. if (UI.utils.isInView(target, options)) {
  6427. inViews.push(target);
  6428. }
  6429. });
  6430. // console.log(inViews.length);
  6431. if (inViews.length) {
  6432. var $target;
  6433. $.each(inViews, function(i, item) {
  6434. if ($(item).offset().top >= scrollTop) {
  6435. $target = $(item);
  6436. return false;
  6437. }
  6438. });
  6439. if (!$target) {
  6440. return;
  6441. }
  6442. if (options.closest) {
  6443. $links.closest(options.closest).removeClass(options.className.active);
  6444. $links.filter('a[href="#' + $target.attr("id") + '"]').closest(options.closest).addClass(options.className.active);
  6445. } else {
  6446. $links.removeClass(options.className.active).filter('a[href="#' + $target.attr("id") + '"]').addClass(options.className.active);
  6447. }
  6448. }
  6449. };
  6450. ScrollSpyNav.prototype.scrollProcess = function() {
  6451. var $links = this.$links;
  6452. // smoothScroll
  6453. if (this.options.smooth) {
  6454. $links.on("click", function(e) {
  6455. e.preventDefault();
  6456. var $this = $(this);
  6457. var $target = $($this.attr("href"));
  6458. if (!$target) {
  6459. return;
  6460. }
  6461. $(window).smoothScroll({
  6462. position: $target.offset().top
  6463. });
  6464. });
  6465. }
  6466. };
  6467. // ScrollSpyNav Plugin
  6468. function Plugin(option) {
  6469. return this.each(function() {
  6470. var $this = $(this);
  6471. var data = $this.data("am.scrollspynav");
  6472. var options = typeof option == "object" && option;
  6473. if (!data) {
  6474. $this.data("am.scrollspynav", data = new ScrollSpyNav(this, options));
  6475. }
  6476. if (typeof option == "string") {
  6477. data[option]();
  6478. }
  6479. });
  6480. }
  6481. $.fn.scrollspynav = Plugin;
  6482. // Init code
  6483. $(function() {
  6484. $("[data-am-scrollspy-nav]").each(function() {
  6485. var $this = $(this);
  6486. var options = UI.utils.options($this.attr("data-am-scrollspy-nav"));
  6487. Plugin.call($this, options);
  6488. });
  6489. });
  6490. UI.scrollspynav = ScrollSpyNav;
  6491. module.exports = ScrollSpyNav;
  6492. });
  6493. define("ui.share", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "ui.modal", "ui.dimmer", "util.qrcode" ], function(require, exports, module) {
  6494. "use strict";
  6495. require("core");
  6496. require("ui.modal");
  6497. var QRCode = require("util.qrcode");
  6498. var $ = window.Zepto;
  6499. var UI = $.AMUI;
  6500. var doc = document;
  6501. var $doc = $(doc);
  6502. var Share = function(options) {
  6503. this.options = $.extend({}, Share.DEFAULTS, options || {});
  6504. this.$element = null;
  6505. this.$wechatQr = null;
  6506. this.pics = null;
  6507. this.inited = false;
  6508. this.active = false;
  6509. };
  6510. Share.DEFAULTS = {
  6511. sns: [ "weibo", "qq", "qzone", "tqq", "wechat", "renren" ],
  6512. title: "分享到",
  6513. cancel: "取消",
  6514. closeOnShare: true,
  6515. id: UI.utils.generateGUID("am-share"),
  6516. desc: "Hi,孤夜观天象,发现一个不错的西西,分享一下下 ;-)",
  6517. via: "Amaze UI",
  6518. tpl: '<div class="am-share am-modal-actions" id="<%= id %>">' + '<h3 class="am-share-title"><%= title %></h3>' + '<ul class="am-share-sns sm-block-grid-3">' + "<% for(var i = 0; i < sns.length; i++) {%>" + "<li>" + '<a href="<%= sns[i].shareUrl %>" ' + 'data-am-share-to="<%= sns[i].id %>" >' + '<i class="am-icon-<%= sns[i].icon %>"></i>' + "<span><%= sns[i].title %></span>" + "</a></li>" + "<% } %></ul>" + '<div class="am-share-footer">' + '<button class="am-btn am-btn-default am-btn-block" ' + "data-am-share-close><%= cancel %></button></div>" + "</div>"
  6519. };
  6520. Share.SNS = {
  6521. weibo: {
  6522. title: "新浪微博",
  6523. url: "http://service.weibo.com/share/share.php",
  6524. width: 620,
  6525. height: 450,
  6526. icon: "weibo"
  6527. },
  6528. // url 链接地址
  6529. // title:”, 分享的文字内容(可选,默认为所在页面的title)
  6530. // appkey:”, 您申请的应用appkey,显示分享来源(可选)
  6531. // pic:”, 分享图片的路径(可选)
  6532. // ralateUid:”, 关联用户的UID,分享微博会@该用户(可选)
  6533. // NOTE: 会自动抓取图片,不用指定 pic
  6534. qq: {
  6535. title: "QQ 好友",
  6536. url: "http://connect.qq.com/widget/shareqq/index.html",
  6537. icon: "qq"
  6538. },
  6539. // url:,
  6540. // title:'', 分享标题(可选)
  6541. // pics:'', 分享图片的路径(可选)
  6542. // summary:'', 分享摘要(可选)
  6543. // site:'', 分享来源 如:腾讯网(可选)
  6544. // desc: '' 发送给用户的消息
  6545. // NOTE: 经过测试,最终发给用户的只有 url 和 desc
  6546. qzone: {
  6547. title: "QQ 空间",
  6548. url: "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey",
  6549. icon: "star"
  6550. },
  6551. // http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=xxx&title=xxx&desc=&summary=&site=
  6552. // url:,
  6553. // title:'', 分享标题(可选)
  6554. // desc:'', 默认分享理由(可选)
  6555. // summary:'', 分享摘要(可选)
  6556. // site:'', 分享来源 如:腾讯网(可选)
  6557. // pics:'', 分享图片的路径(可选),不会自动抓取,多个图片用|分隔
  6558. tqq: {
  6559. title: "腾讯微博",
  6560. url: "http://v.t.qq.com/share/share.php",
  6561. icon: "tencent-weibo"
  6562. },
  6563. // url=xx&title=&appkey=801cf76d3cfc44ada52ec13114e84a96
  6564. // url
  6565. // title
  6566. // pic 多个图片用 | 分隔
  6567. // appkey
  6568. // NOTE: 不会自动抓取图片
  6569. wechat: {
  6570. title: "微信",
  6571. url: "[qrcode]",
  6572. icon: "wechat"
  6573. },
  6574. // 生成一个二维码 供用户扫描
  6575. // 相关接口 https://github.com/zxlie/WeixinApi
  6576. renren: {
  6577. title: "人人网",
  6578. url: "http://widget.renren.com/dialog/share",
  6579. icon: "renren"
  6580. },
  6581. // http://widget.renren.com/dialog/share?resourceUrl=www&srcUrl=www&title=ww&description=xxx
  6582. // 550 * 400
  6583. // resourceUrl : '', // 分享的资源Url
  6584. // srcUrl : '', // 分享的资源来源Url,
  6585. // // 默认为header中的Referer,如果分享失败可以调整此值为resourceUrl试试
  6586. // pic : '', // 分享的主题图片,会自动抓取
  6587. // title : '', // 分享的标题
  6588. // description : '' // 分享的详细描述
  6589. // NOTE: 经过测试,直接使用 url 参数即可
  6590. douban: {
  6591. title: "豆瓣",
  6592. url: "http://www.douban.com/recommend/",
  6593. icon: "share-alt"
  6594. },
  6595. // http://www.douban.com/service/sharebutton
  6596. // 450 * 330
  6597. // http://www.douban.com/share/service?bm=1&image=&href=xxx&updated=&name=
  6598. // href 链接
  6599. // name 标题
  6600. /* void (function() {
  6601. var d = document, e = encodeURIComponent,
  6602. s1 = window.getSelection, s2 = d.getSelection,
  6603. s3 = d.selection, s = s1 ? s1()
  6604. : s2 ? s2() : s3 ? s3.createRange().text : '',
  6605. r = 'http://www.douban.com/recommend/?url=&title=&sel=&v=1&r=1'
  6606. })();
  6607. */
  6608. // tsohu: '',
  6609. // http://t.sohu.com/third/post.jsp?url=&title=&content=utf-8&pic=
  6610. // print: '',
  6611. mail: {
  6612. title: "邮件分享",
  6613. url: "mailto:",
  6614. icon: "envelope-o"
  6615. },
  6616. sms: {
  6617. title: "短信分享",
  6618. url: "sms:",
  6619. icon: "comment"
  6620. }
  6621. };
  6622. Share.prototype.render = function() {
  6623. var options = this.options;
  6624. var snsData = [];
  6625. var title = encodeURIComponent(doc.title);
  6626. var link = encodeURIComponent(doc.location);
  6627. var msgBody = "?body=" + title + link;
  6628. options.sns.forEach(function(item, i) {
  6629. if (Share.SNS[item]) {
  6630. var tmp = Share.SNS[item];
  6631. var shareUrl;
  6632. tmp.id = item;
  6633. if (item === "mail") {
  6634. shareUrl = msgBody + "&subject=" + options.desc;
  6635. } else if (item === "sms") {
  6636. shareUrl = msgBody;
  6637. } else {
  6638. shareUrl = "?url=" + link + "&title=" + title;
  6639. }
  6640. tmp.shareUrl = tmp.url + shareUrl;
  6641. snsData.push(tmp);
  6642. }
  6643. });
  6644. return UI.template(options.tpl, $.extend({}, options, {
  6645. sns: snsData
  6646. }));
  6647. };
  6648. Share.prototype.init = function() {
  6649. if (this.inited) {
  6650. return;
  6651. }
  6652. var me = this;
  6653. var shareItem = "[data-am-share-to]";
  6654. $doc.ready($.proxy(function() {
  6655. $("body").append(this.render());
  6656. // append share DOM to body
  6657. this.$element = $("#" + this.options.id);
  6658. this.$element.find("[data-am-share-close]").on("click.share.amui", function() {
  6659. me.close();
  6660. });
  6661. }, this));
  6662. $doc.on("click.share.amui", shareItem, $.proxy(function(e) {
  6663. var $clicked = $(e.target);
  6664. var $target = $clicked.is(shareItem) && $clicked || $clicked.parent(shareItem);
  6665. var sns = $target.attr("data-am-share-to");
  6666. if (!(sns === "mail" || sns === "sms")) {
  6667. e.preventDefault();
  6668. this.shareTo(sns, this.setData(sns));
  6669. }
  6670. this.close();
  6671. }, this));
  6672. this.inited = true;
  6673. };
  6674. Share.prototype.open = function() {
  6675. !this.inited && this.init();
  6676. this.$element && this.$element.modal("open");
  6677. this.$element.trigger("open:share:amui");
  6678. this.active = true;
  6679. };
  6680. Share.prototype.close = function() {
  6681. this.$element && this.$element.modal("close");
  6682. this.$element.trigger("close:share:amui");
  6683. this.active = false;
  6684. };
  6685. Share.prototype.toggle = function() {
  6686. this.active ? this.close() : this.open();
  6687. };
  6688. Share.prototype.setData = function(sns) {
  6689. if (!sns) {
  6690. return;
  6691. }
  6692. var shareData = {
  6693. url: doc.location,
  6694. title: doc.title
  6695. };
  6696. var desc = this.options.desc;
  6697. var imgSrc = this.pics || [];
  6698. var qqReg = /^(qzone|qq|tqq)$/;
  6699. if (qqReg.test(sns) && !imgSrc.length) {
  6700. var allImages = doc.images;
  6701. for (var i = 0; i < allImages.length && i < 10; i++) {
  6702. !!allImages[i].src && imgSrc.push(encodeURIComponent(allImages[i].src));
  6703. }
  6704. this.pics = imgSrc;
  6705. }
  6706. switch (sns) {
  6707. case "qzone":
  6708. shareData.desc = desc;
  6709. shareData.site = this.options.via;
  6710. shareData.pics = imgSrc.join("|");
  6711. // TODO: 抓取图片多张
  6712. break;
  6713. case "qq":
  6714. shareData.desc = desc;
  6715. shareData.site = this.options.via;
  6716. shareData.pics = imgSrc[0];
  6717. // 抓取一张图片
  6718. break;
  6719. case "tqq":
  6720. // 抓取图片多张
  6721. shareData.pic = imgSrc.join("|");
  6722. break;
  6723. }
  6724. return shareData;
  6725. };
  6726. Share.prototype.shareTo = function(sns, data) {
  6727. var snsInfo = Share.SNS[sns];
  6728. if (!snsInfo) {
  6729. return;
  6730. }
  6731. if (sns === "wechat" || sns === "weixin") {
  6732. return this.wechatQr();
  6733. }
  6734. var query = [];
  6735. for (var key in data) {
  6736. if (data[key]) {
  6737. // 避免 encode 图片分隔符 |
  6738. query.push(key.toString() + "=" + (key === "pic" || key === "pics" ? data[key] : encodeURIComponent(data[key])));
  6739. }
  6740. }
  6741. window.open(snsInfo.url + "?" + query.join("&"));
  6742. };
  6743. Share.prototype.wechatQr = function() {
  6744. if (!this.$wechatQr) {
  6745. var qrId = UI.utils.generateGUID("am-share-wechat");
  6746. var $qr = $('<div class="am-modal am-modal-no-btn am-share-wechat-qr">' + '<div class="am-modal-dialog"><div class="am-modal-hd">分享到微信 ' + '<a href="" class="am-close am-close-spin" ' + "data-am-modal-close>&times;</a> </div>" + '<div class="am-modal-bd">' + '<div class="am-share-wx-qr"></div>' + '<div class="am-share-wechat-tip">' + "打开微信,点击底部的<em>发现</em>,<br/> " + "使用<em>扫一扫</em>将网页分享至朋友圈</div></div></div></div>", {
  6747. id: qrId
  6748. });
  6749. var qrNode = new QRCode({
  6750. render: "canvas",
  6751. correctLevel: 0,
  6752. text: doc.location.href,
  6753. width: 180,
  6754. height: 180,
  6755. background: "#fff",
  6756. foreground: "#000"
  6757. });
  6758. $qr.find(".am-share-wx-qr").html(qrNode);
  6759. $qr.appendTo($("body"));
  6760. this.$wechatQr = $("#" + qrId);
  6761. }
  6762. this.$wechatQr.modal("open");
  6763. };
  6764. var share = new Share();
  6765. $doc.on("click.share.amui", '[data-am-toggle="share"]', function(e) {
  6766. e.preventDefault();
  6767. share.toggle();
  6768. });
  6769. UI.share = share;
  6770. module.exports = share;
  6771. });
  6772. define("ui.smooth-scroll", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  6773. "use strict";
  6774. var UI = require("core");
  6775. var rAF = UI.utils.rAF;
  6776. var $ = window.Zepto;
  6777. /**
  6778. * Smooth Scroll
  6779. * @param position
  6780. * @via http://mir.aculo.us/2014/01/19/scrolling-dom-elements-to-the-top-a-zepto-plugin/
  6781. */
  6782. // Usage: $(window).smoothScroll([options])
  6783. // only allow one scroll to top operation to be in progress at a time,
  6784. // which is probably what you want
  6785. var smoothScrollInProgress = false;
  6786. $.fn.smoothScroll = function(options) {
  6787. options = options || {};
  6788. var $this = this, targetY = parseInt(options.position) || 0, initialY = $this.scrollTop(), lastY = initialY, delta = targetY - initialY, // duration in ms, make it a bit shorter for short distances
  6789. // this is not scientific and you might want to adjust this for
  6790. // your preferences
  6791. speed = options.speed || Math.min(750, Math.min(1500, Math.abs(initialY - targetY))), // temp variables (t will be a position between 0 and 1, y is the calculated scrollTop)
  6792. start, t, y, cancelScroll = function() {
  6793. abort();
  6794. };
  6795. // abort if already in progress or nothing to scroll
  6796. if (smoothScrollInProgress) {
  6797. return;
  6798. }
  6799. if (delta === 0) {
  6800. return;
  6801. }
  6802. // quint ease-in-out smoothing, from
  6803. // https://github.com/madrobby/scripty2/blob/master/src/effects/transitions/penner.js#L127-L136
  6804. function smooth(pos) {
  6805. if ((pos /= .5) < 1) {
  6806. return .5 * Math.pow(pos, 5);
  6807. }
  6808. return .5 * (Math.pow(pos - 2, 5) + 2);
  6809. }
  6810. function abort() {
  6811. $this.off("touchstart.smoothscroll.amui", cancelScroll);
  6812. smoothScrollInProgress = false;
  6813. }
  6814. // when there's a touch detected while scrolling is in progress, abort
  6815. // the scrolling (emulates native scrolling behavior)
  6816. $this.on("touchstart.smoothscroll.amui", cancelScroll);
  6817. smoothScrollInProgress = true;
  6818. // start rendering away! note the function given to frame
  6819. // is named "render" so we can reference it again further down
  6820. rAF(function render(now) {
  6821. if (!smoothScrollInProgress) {
  6822. return;
  6823. }
  6824. if (!start) {
  6825. start = now;
  6826. }
  6827. // calculate t, position of animation in [0..1]
  6828. t = Math.min(1, Math.max((now - start) / speed, 0));
  6829. // calculate the new scrollTop position (don't forget to smooth)
  6830. y = Math.round(initialY + delta * smooth(t));
  6831. // bracket scrollTop so we're never over-scrolling
  6832. if (delta > 0 && y > targetY) y = targetY;
  6833. if (delta < 0 && y < targetY) y = targetY;
  6834. // only actually set scrollTop if there was a change fromt he last frame
  6835. if (lastY != y) $this.scrollTop(y);
  6836. lastY = y;
  6837. // if we're not done yet, queue up an other frame to render,
  6838. // or clean up
  6839. if (y !== targetY) {
  6840. rAF(render);
  6841. } else {
  6842. abort();
  6843. }
  6844. });
  6845. };
  6846. // Init code
  6847. $(document).on("click.smoothScroll.amui", "[data-am-smooth-scroll]", function(e) {
  6848. e.preventDefault();
  6849. var options = UI.utils.parseOptions($(this).attr("data-am-smooth-scroll"));
  6850. $(window).smoothScroll(options);
  6851. });
  6852. });
  6853. define("ui.sticky", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  6854. "use strict";
  6855. require("core");
  6856. var $ = window.Zepto;
  6857. var UI = $.AMUI;
  6858. /**
  6859. * @via https://github.com/uikit/uikit/blob/master/src/js/addons/sticky.js
  6860. * @license https://github.com/uikit/uikit/blob/master/LICENSE.md
  6861. */
  6862. // Sticky Class
  6863. var Sticky = function(element, options) {
  6864. var me = this;
  6865. this.options = $.extend({}, Sticky.DEFAULTS, options);
  6866. this.$element = $(element);
  6867. this.sticked = null;
  6868. this.inited = null;
  6869. this.$holder = undefined;
  6870. this.$window = $(window).on("scroll.sticky.amui", UI.utils.debounce($.proxy(this.checkPosition, this), 10)).on("resize.sticky.amui orientationchange.sticky.amui", UI.utils.debounce(function() {
  6871. me.reset(true, function() {
  6872. me.checkPosition();
  6873. });
  6874. }, 50)).on("load.sticky.amui", $.proxy(this.checkPosition, this));
  6875. this.offset = this.$element.offset();
  6876. this.init();
  6877. };
  6878. Sticky.DEFAULTS = {
  6879. top: 0,
  6880. bottom: 0,
  6881. animation: "",
  6882. className: {
  6883. sticky: "am-sticky",
  6884. resetting: "am-sticky-resetting",
  6885. stickyBtm: "am-sticky-bottom",
  6886. animationRev: "am-animation-reverse"
  6887. }
  6888. };
  6889. Sticky.prototype.init = function() {
  6890. var result = this.check();
  6891. if (!result) {
  6892. return false;
  6893. }
  6894. var $element = this.$element;
  6895. var $holder = $('<div class="am-sticky-placeholder"></div>').css({
  6896. height: $element.css("position") != "absolute" ? $element.outerHeight() : "",
  6897. "float": $element.css("float") != "none" ? $element.css("float") : "",
  6898. margin: $element.css("margin")
  6899. });
  6900. this.$holder = $element.css("margin", 0).wrap($holder).parent();
  6901. this.inited = 1;
  6902. return true;
  6903. };
  6904. Sticky.prototype.reset = function(force, cb) {
  6905. var options = this.options;
  6906. var $element = this.$element;
  6907. var animation = options.animation ? " am-animation-" + options.animation : "";
  6908. var complete = function() {
  6909. $element.css({
  6910. position: "",
  6911. top: "",
  6912. width: "",
  6913. left: "",
  6914. margin: 0
  6915. });
  6916. $element.removeClass([ animation, options.className.animationRev, options.className.sticky, options.className.resetting ].join(" "));
  6917. this.animating = false;
  6918. this.sticked = false;
  6919. this.offset = $element.offset();
  6920. cb && cb();
  6921. }.bind(this);
  6922. $element.addClass(options.className.resetting);
  6923. if (!force && options.animation && UI.support.animation) {
  6924. this.animating = true;
  6925. $element.removeClass(animation).one(UI.support.animation.end, function() {
  6926. complete();
  6927. }).width();
  6928. // force redraw
  6929. $element.addClass(animation + " " + options.className.animationRev);
  6930. } else {
  6931. complete();
  6932. }
  6933. };
  6934. Sticky.prototype.check = function() {
  6935. if (!this.$element.is(":visible")) {
  6936. return false;
  6937. }
  6938. var media = this.options.media;
  6939. if (media) {
  6940. switch (typeof media) {
  6941. case "number":
  6942. if (window.innerWidth < media) {
  6943. return false;
  6944. }
  6945. break;
  6946. case "string":
  6947. if (window.matchMedia && !window.matchMedia(media).matches) {
  6948. return false;
  6949. }
  6950. break;
  6951. }
  6952. }
  6953. return true;
  6954. };
  6955. Sticky.prototype.checkPosition = function() {
  6956. if (!this.inited) {
  6957. var initialized = this.init();
  6958. if (!initialized) {
  6959. return;
  6960. }
  6961. }
  6962. var options = this.options;
  6963. var scrollTop = this.$window.scrollTop();
  6964. var offsetTop = options.top;
  6965. var offsetBottom = options.bottom;
  6966. var $element = this.$element;
  6967. var animation = options.animation ? " am-animation-" + options.animation : "";
  6968. var className = [ options.className.sticky, animation ].join(" ");
  6969. if (typeof offsetBottom == "function") {
  6970. offsetBottom = offsetBottom(this.$element);
  6971. }
  6972. var checkResult = scrollTop > this.$holder.offset().top;
  6973. if (!this.sticked && checkResult) {
  6974. $element.addClass(className);
  6975. } else if (this.sticked && !checkResult) {
  6976. this.reset();
  6977. }
  6978. this.$holder.height($element.height());
  6979. if (checkResult) {
  6980. $element.css({
  6981. top: offsetTop,
  6982. left: this.$holder.offset().left,
  6983. width: this.offset.width
  6984. });
  6985. }
  6986. this.sticked = checkResult;
  6987. };
  6988. // Sticky Plugin
  6989. function Plugin(option) {
  6990. return this.each(function() {
  6991. var $this = $(this);
  6992. var data = $this.data("am.sticky");
  6993. var options = typeof option == "object" && option;
  6994. if (!data) {
  6995. $this.data("am.sticky", data = new Sticky(this, options));
  6996. }
  6997. if (typeof option == "string") {
  6998. data[option]();
  6999. }
  7000. });
  7001. }
  7002. $.fn.sticky = Plugin;
  7003. // Init code
  7004. $(window).on("load", function() {
  7005. $("[data-am-sticky]").each(function() {
  7006. var $this = $(this);
  7007. var options = UI.utils.options($this.attr("data-am-sticky"));
  7008. Plugin.call($this, options);
  7009. });
  7010. });
  7011. UI.sticky = Sticky;
  7012. module.exports = Sticky;
  7013. });
  7014. define("ui.tabs", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick", "util.hammer" ], function(require, exports, module) {
  7015. "use strict";
  7016. require("core");
  7017. var Hammer = require("util.hammer");
  7018. var $ = window.Zepto;
  7019. var UI = $.AMUI;
  7020. var supportTransition = UI.support.transition;
  7021. var animation = UI.support.animation;
  7022. /**
  7023. * @via https://github.com/twbs/bootstrap/blob/master/js/tab.js
  7024. * @copyright 2011-2014 Twitter, Inc.
  7025. * @license MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  7026. */
  7027. var Tabs = function(element, options) {
  7028. this.$element = $(element);
  7029. this.options = $.extend({}, Tabs.DEFAULTS, options || {});
  7030. this.$tabNav = this.$element.find(this.options.selector.nav);
  7031. this.$navs = this.$tabNav.find("a");
  7032. this.$content = this.$element.find(this.options.selector.content);
  7033. this.$tabPanels = this.$content.find(this.options.selector.panel);
  7034. this.transitioning = null;
  7035. this.init();
  7036. };
  7037. Tabs.DEFAULTS = {
  7038. selector: {
  7039. nav: ".am-tabs-nav",
  7040. content: ".am-tabs-bd",
  7041. panel: ".am-tab-panel"
  7042. },
  7043. className: {
  7044. active: "am-active"
  7045. }
  7046. };
  7047. Tabs.prototype.init = function() {
  7048. var me = this;
  7049. var options = this.options;
  7050. // Activate the first Tab when no active Tab or multiple active Tabs
  7051. if (this.$tabNav.find("> .am-active").length !== 1) {
  7052. var $tabNav = this.$tabNav;
  7053. this.activate($tabNav.children("li").first(), $tabNav);
  7054. this.activate(this.$tabPanels.first(), this.$content);
  7055. }
  7056. this.$navs.on("click.tabs.amui", function(e) {
  7057. e.preventDefault();
  7058. me.open($(this));
  7059. });
  7060. if (!options.noSwipe) {
  7061. var hammer = new Hammer(this.$content[0]);
  7062. hammer.get("pan").set({
  7063. direction: Hammer.DIRECTION_HORIZONTAL,
  7064. threshold: 120
  7065. });
  7066. hammer.on("panleft", UI.utils.debounce(function(e) {
  7067. e.preventDefault();
  7068. var $target = $(e.target);
  7069. if (!$target.is(options.selector.panel)) {
  7070. $target = $target.closest(options.selector.panel);
  7071. }
  7072. $target.focus();
  7073. var $nav = me.getNextNav($target);
  7074. $nav && me.open($nav);
  7075. }, 100));
  7076. hammer.on("panright", UI.utils.debounce(function(e) {
  7077. e.preventDefault();
  7078. var $target = $(e.target);
  7079. if (!$target.is(options.selector.panel)) {
  7080. $target = $target.closest(options.selector.panel);
  7081. }
  7082. var $nav = me.getPrevNav($target);
  7083. $nav && me.open($nav);
  7084. }, 100));
  7085. }
  7086. };
  7087. Tabs.prototype.open = function($nav) {
  7088. if (!$nav || this.transitioning || $nav.parent("li").hasClass("am-active")) {
  7089. return;
  7090. }
  7091. var $tabNav = this.$tabNav;
  7092. var $navs = this.$navs;
  7093. var $tabContent = this.$content;
  7094. var href = $nav.attr("href");
  7095. var regexHash = /^#.+$/;
  7096. var $target = regexHash.test(href) && this.$content.find(href) || this.$tabPanels.eq($navs.index($nav));
  7097. var previous = $tabNav.find(".am-active a")[0];
  7098. var e = $.Event("open:tabs:amui", {
  7099. relatedTarget: previous
  7100. });
  7101. $nav.trigger(e);
  7102. if (e.isDefaultPrevented()) {
  7103. return;
  7104. }
  7105. // activate Tab nav
  7106. this.activate($nav.closest("li"), $tabNav);
  7107. // activate Tab content
  7108. this.activate($target, $tabContent, function() {
  7109. $nav.trigger({
  7110. type: "opened:tabs:amui",
  7111. relatedTarget: previous
  7112. });
  7113. });
  7114. };
  7115. Tabs.prototype.activate = function($element, $container, callback) {
  7116. this.transitioning = true;
  7117. var $active = $container.find("> .am-active");
  7118. var transition = callback && supportTransition && !!$active.length;
  7119. $active.removeClass("am-active am-in");
  7120. $element.addClass("am-active");
  7121. if (transition) {
  7122. $element.redraw();
  7123. // reflow for transition
  7124. $element.addClass("am-in");
  7125. } else {
  7126. $element.removeClass("am-fade");
  7127. }
  7128. function complete() {
  7129. callback && callback();
  7130. this.transitioning = false;
  7131. }
  7132. transition ? $active.one(supportTransition.end, $.proxy(complete, this)) : $.proxy(complete, this)();
  7133. };
  7134. Tabs.prototype.getNextNav = function($panel) {
  7135. var navIndex = this.$tabPanels.index($panel);
  7136. var rightSpring = "am-animation-right-spring";
  7137. if (navIndex + 1 >= this.$navs.length) {
  7138. // last one
  7139. animation && $panel.addClass(rightSpring).on(animation.end, function() {
  7140. $panel.removeClass(rightSpring);
  7141. });
  7142. return null;
  7143. } else {
  7144. return this.$navs.eq(navIndex + 1);
  7145. }
  7146. };
  7147. Tabs.prototype.getPrevNav = function($panel) {
  7148. var navIndex = this.$tabPanels.index($panel);
  7149. var leftSpring = "am-animation-left-spring";
  7150. if (navIndex === 0) {
  7151. // first one
  7152. animation && $panel.addClass(leftSpring).on(animation.end, function() {
  7153. $panel.removeClass(leftSpring);
  7154. });
  7155. return null;
  7156. } else {
  7157. return this.$navs.eq(navIndex - 1);
  7158. }
  7159. };
  7160. // Plugin
  7161. function Plugin(option) {
  7162. return this.each(function() {
  7163. var $this = $(this);
  7164. var $tabs = $this.is(".am-tabs") && $this || $this.closest(".am-tabs");
  7165. var data = $tabs.data("amui.tabs");
  7166. var options = $.extend({}, $.isPlainObject(option) ? option : {}, UI.utils.parseOptions($this.data("amTabs")));
  7167. if (!data) {
  7168. $tabs.data("amui.tabs", data = new Tabs($tabs[0], options));
  7169. }
  7170. if (typeof option == "string" && $this.is(".am-tabs-nav a")) {
  7171. data[option]($this);
  7172. }
  7173. });
  7174. }
  7175. $.fn.tabs = Plugin;
  7176. // Init code
  7177. $(document).on("ready", function(e) {
  7178. $("[data-am-tabs]").tabs();
  7179. });
  7180. UI.tabs = Tabs;
  7181. module.exports = Tabs;
  7182. });
  7183. define("util.cookie", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  7184. "use strict";
  7185. require("core");
  7186. var $ = window.Zepto;
  7187. var UI = $.AMUI;
  7188. var cookie = {
  7189. get: function(name) {
  7190. var cookieName = encodeURIComponent(name) + "=";
  7191. var cookieStart = document.cookie.indexOf(cookieName);
  7192. var cookieValue = null;
  7193. var cookieEnd;
  7194. if (cookieStart > -1) {
  7195. cookieEnd = document.cookie.indexOf(";", cookieStart);
  7196. if (cookieEnd == -1) {
  7197. cookieEnd = document.cookie.length;
  7198. }
  7199. cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
  7200. }
  7201. return cookieValue;
  7202. },
  7203. set: function(name, value, expires, path, domain, secure) {
  7204. var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
  7205. if (expires instanceof Date) {
  7206. cookieText += "; expires=" + expires.toGMTString();
  7207. }
  7208. if (path) {
  7209. cookieText += "; path=" + path;
  7210. }
  7211. if (domain) {
  7212. cookieText += "; domain=" + domain;
  7213. }
  7214. if (secure) {
  7215. cookieText += "; secure";
  7216. }
  7217. document.cookie = cookieText;
  7218. },
  7219. unset: function(name, path, domain, secure) {
  7220. this.set(name, "", new Date(0), path, domain, secure);
  7221. }
  7222. };
  7223. UI.utils.cookie = cookie;
  7224. module.exports = cookie;
  7225. });
  7226. define("util.fullscreen", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  7227. "use strict";
  7228. require("core");
  7229. var $ = window.Zepto, UI = $.AMUI;
  7230. /**
  7231. * @via https://github.com/sindresorhus/screenfull.js
  7232. * @license MIT © Sindre Sorhus
  7233. * @version 1.2.1
  7234. */
  7235. var keyboardAllowed = typeof Element !== "undefined" && "ALLOW_KEYBOARD_INPUT" in Element;
  7236. var fn = function() {
  7237. var val;
  7238. var valLength;
  7239. var fnMap = [ [ "requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror" ], // new WebKit
  7240. [ "webkitRequestFullscreen", "webkitExitFullscreen", "webkitFullscreenElement", "webkitFullscreenEnabled", "webkitfullscreenchange", "webkitfullscreenerror" ], // old WebKit (Safari 5.1)
  7241. [ "webkitRequestFullScreen", "webkitCancelFullScreen", "webkitCurrentFullScreenElement", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitfullscreenerror" ], [ "mozRequestFullScreen", "mozCancelFullScreen", "mozFullScreenElement", "mozFullScreenEnabled", "mozfullscreenchange", "mozfullscreenerror" ], [ "msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError" ] ];
  7242. var i = 0;
  7243. var l = fnMap.length;
  7244. var ret = {};
  7245. for (;i < l; i++) {
  7246. val = fnMap[i];
  7247. if (val && val[1] in document) {
  7248. for (i = 0, valLength = val.length; i < valLength; i++) {
  7249. ret[fnMap[0][i]] = val[i];
  7250. }
  7251. return ret;
  7252. }
  7253. }
  7254. return false;
  7255. }();
  7256. var fullscreen = {
  7257. request: function(elem) {
  7258. var request = fn.requestFullscreen;
  7259. elem = elem || document.documentElement;
  7260. // Work around Safari 5.1 bug: reports support for
  7261. // keyboard in fullscreen even though it doesn't.
  7262. // Browser sniffing, since the alternative with
  7263. // setTimeout is even worse.
  7264. if (/5\.1[\.\d]* Safari/.test(navigator.userAgent)) {
  7265. elem[request]();
  7266. } else {
  7267. elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
  7268. }
  7269. },
  7270. exit: function() {
  7271. document[fn.exitFullscreen]();
  7272. },
  7273. toggle: function(elem) {
  7274. if (this.isFullscreen) {
  7275. this.exit();
  7276. } else {
  7277. this.request(elem);
  7278. }
  7279. },
  7280. onchange: function() {},
  7281. onerror: function() {},
  7282. raw: fn
  7283. };
  7284. if (!fn) {
  7285. module.exports = false;
  7286. return;
  7287. }
  7288. Object.defineProperties(fullscreen, {
  7289. isFullscreen: {
  7290. get: function() {
  7291. return !!document[fn.fullscreenElement];
  7292. }
  7293. },
  7294. element: {
  7295. enumerable: true,
  7296. get: function() {
  7297. return document[fn.fullscreenElement];
  7298. }
  7299. },
  7300. enabled: {
  7301. enumerable: true,
  7302. get: function() {
  7303. // Coerce to boolean in case of old WebKit
  7304. return !!document[fn.fullscreenEnabled];
  7305. }
  7306. }
  7307. });
  7308. document.addEventListener(fn.fullscreenchange, function(e) {
  7309. fullscreen.onchange.call(fullscreen, e);
  7310. });
  7311. document.addEventListener(fn.fullscreenerror, function(e) {
  7312. fullscreen.onerror.call(fullscreen, e);
  7313. });
  7314. UI.fullscreen = fullscreen;
  7315. module.exports = fullscreen;
  7316. });
  7317. define("util.qrcode", [], function(require, exports, module) {
  7318. var $ = Zepto;
  7319. /**
  7320. * @ver 1.1.0
  7321. * @via https://github.com/aralejs/qrcode/blob/master/src/qrcode.js
  7322. * @license http://aralejs.org/
  7323. */
  7324. var qrcodeAlgObjCache = [];
  7325. /**
  7326. * 二维码构造函数,主要用于绘制
  7327. * @param {参数列表} opt 传递参数
  7328. * @return {}
  7329. */
  7330. var qrcode = function(opt) {
  7331. if (typeof opt === "string") {
  7332. // 只编码ASCII字符串
  7333. opt = {
  7334. text: opt
  7335. };
  7336. }
  7337. //设置默认参数
  7338. this.options = $.extend({}, {
  7339. text: "",
  7340. render: "",
  7341. width: 256,
  7342. height: 256,
  7343. correctLevel: 3,
  7344. background: "#ffffff",
  7345. foreground: "#000000"
  7346. }, opt);
  7347. //使用QRCodeAlg创建二维码结构
  7348. var qrCodeAlg = null;
  7349. for (var i = 0, l = qrcodeAlgObjCache.length; i < l; i++) {
  7350. if (qrcodeAlgObjCache[i].text == this.options.text && qrcodeAlgObjCache[i].text.correctLevel == this.options.correctLevel) {
  7351. qrCodeAlg = qrcodeAlgObjCache[i].obj;
  7352. break;
  7353. }
  7354. }
  7355. if (i == l) {
  7356. qrCodeAlg = new QRCodeAlg(this.options.text, this.options.correctLevel);
  7357. qrcodeAlgObjCache.push({
  7358. text: this.options.text,
  7359. correctLevel: this.options.correctLevel,
  7360. obj: qrCodeAlg
  7361. });
  7362. }
  7363. if (this.options.render) {
  7364. switch (this.options.render) {
  7365. case "canvas":
  7366. return this.createCanvas(qrCodeAlg);
  7367. case "table":
  7368. return this.createTable(qrCodeAlg);
  7369. case "svg":
  7370. return this.createSVG(qrCodeAlg);
  7371. default:
  7372. return this.createDefault(qrCodeAlg);
  7373. }
  7374. }
  7375. return this.createDefault(qrCodeAlg);
  7376. };
  7377. /**
  7378. * 使用Canvas来画二维码
  7379. * @return {}
  7380. */
  7381. qrcode.prototype.createDefault = function(qrCodeAlg) {
  7382. var canvas = document.createElement("canvas");
  7383. if (canvas.getContext) return this.createCanvas(qrCodeAlg);
  7384. if (!!document.createElementNS && !!document.createElementNS(SVG_NS, "svg").createSVGRect) return this.createSVG(qrCodeAlg);
  7385. return this.createTable(qrCodeAlg);
  7386. };
  7387. qrcode.prototype.createCanvas = function(qrCodeAlg) {
  7388. //创建canvas节点
  7389. var canvas = document.createElement("canvas");
  7390. canvas.width = this.options.width;
  7391. canvas.height = this.options.height;
  7392. var ctx = canvas.getContext("2d");
  7393. //计算每个点的长宽
  7394. var tileW = (this.options.width / qrCodeAlg.getModuleCount()).toPrecision(4);
  7395. var tileH = this.options.height / qrCodeAlg.getModuleCount().toPrecision(4);
  7396. //绘制
  7397. for (var row = 0; row < qrCodeAlg.getModuleCount(); row++) {
  7398. for (var col = 0; col < qrCodeAlg.getModuleCount(); col++) {
  7399. ctx.fillStyle = qrCodeAlg.modules[row][col] ? this.options.foreground : this.options.background;
  7400. var w = Math.ceil((col + 1) * tileW) - Math.floor(col * tileW);
  7401. var h = Math.ceil((row + 1) * tileW) - Math.floor(row * tileW);
  7402. ctx.fillRect(Math.round(col * tileW), Math.round(row * tileH), w, h);
  7403. }
  7404. }
  7405. //返回绘制的节点
  7406. return canvas;
  7407. };
  7408. /**
  7409. * 使用table来绘制二维码
  7410. * @return {}
  7411. */
  7412. qrcode.prototype.createTable = function(qrCodeAlg) {
  7413. //创建table节点
  7414. var s = [];
  7415. s.push('<table style="border:0px; margin:0px; padding:0px; border-collapse:collapse; background-color: ' + this.options.background + ';">');
  7416. // 计算每个节点的长宽;取整,防止点之间出现分离
  7417. var tileW = -1, tileH = -1, caculateW = -1, caculateH = -1;
  7418. tileW = caculateW = Math.floor(this.options.width / qrCodeAlg.getModuleCount());
  7419. tileH = caculateH = Math.floor(this.options.height / qrCodeAlg.getModuleCount());
  7420. if (caculateW <= 0) {
  7421. if (qrCodeAlg.getModuleCount() < 80) {
  7422. tileW = 2;
  7423. } else {
  7424. tileW = 1;
  7425. }
  7426. }
  7427. if (caculateH <= 0) {
  7428. if (qrCodeAlg.getModuleCount() < 80) {
  7429. tileH = 2;
  7430. } else {
  7431. tileH = 1;
  7432. }
  7433. }
  7434. // 绘制二维码
  7435. foreTd = '<td style="border:0px; margin:0px; padding:0px; width:' + tileW + "px; background-color: " + this.options.foreground + '"></td>',
  7436. backTd = '<td style="border:0px; margin:0px; padding:0px; width:' + tileW + "px; background-color: " + this.options.background + '"></td>',
  7437. l = qrCodeAlg.getModuleCount();
  7438. for (var row = 0; row < l; row++) {
  7439. s.push('<tr style="border:0px; margin:0px; padding:0px; height: ' + tileH + 'px">');
  7440. for (var col = 0; col < l; col++) {
  7441. s.push(qrCodeAlg.modules[row][col] ? foreTd : backTd);
  7442. }
  7443. s.push("</tr>");
  7444. }
  7445. s.push("</table>");
  7446. var span = document.createElement("span");
  7447. span.innerHTML = s.join("");
  7448. return span.firstChild;
  7449. };
  7450. /**
  7451. * 使用SVG开绘制二维码
  7452. * @return {}
  7453. */
  7454. qrcode.prototype.createSVG = function(qrCodeAlg) {
  7455. var x, dx, y, dy, moduleCount = qrCodeAlg.getModuleCount(), scale = this.options.height / this.options.width, svg = '<svg xmlns="http://www.w3.org/2000/svg" ' + 'width="' + this.options.width + 'px" height="' + this.options.height + 'px" ' + 'viewbox="0 0 ' + moduleCount * 10 + " " + moduleCount * 10 * scale + '">', rectHead = "<path ", foreRect = ' style="stroke-width:0.5;stroke:' + this.options.foreground + ";fill:" + this.options.foreground + ';"></path>', backRect = ' style="stroke-width:0.5;stroke:' + this.options.background + ";fill:" + this.options.background + ';"></path>';
  7456. // draw in the svg
  7457. for (var row = 0; row < moduleCount; row++) {
  7458. for (var col = 0; col < moduleCount; col++) {
  7459. x = col * 10;
  7460. y = row * 10 * scale;
  7461. dx = (col + 1) * 10;
  7462. dy = (row + 1) * 10 * scale;
  7463. svg += rectHead + 'd="M ' + x + "," + y + " L " + dx + "," + y + " L " + dx + "," + dy + " L " + x + "," + dy + ' Z"';
  7464. svg += qrCodeAlg.modules[row][col] ? foreRect : backRect;
  7465. }
  7466. }
  7467. svg += "</svg>";
  7468. // return just built svg
  7469. return $(svg)[0];
  7470. };
  7471. module.exports = qrcode;
  7472. $.AMUI.qrcode = qrcode;
  7473. /**
  7474. * 获取单个字符的utf8编码
  7475. * unicode BMP平面约65535个字符
  7476. * @param {num} code
  7477. * return {array}
  7478. */
  7479. function unicodeFormat8(code) {
  7480. // 1 byte
  7481. if (code < 128) {
  7482. return [ code ];
  7483. } else if (code < 2048) {
  7484. c0 = 192 + (code >> 6);
  7485. c1 = 128 + (code & 63);
  7486. return [ c0, c1 ];
  7487. } else {
  7488. c0 = 224 + (code >> 12);
  7489. c1 = 128 + (code >> 6 & 63);
  7490. c2 = 128 + (code & 63);
  7491. return [ c0, c1, c2 ];
  7492. }
  7493. }
  7494. /**
  7495. * 获取字符串的utf8编码字节串
  7496. * @param {string} string
  7497. * @return {array}
  7498. */
  7499. function getUTF8Bytes(string) {
  7500. var utf8codes = [];
  7501. for (var i = 0; i < string.length; i++) {
  7502. var code = string.charCodeAt(i);
  7503. var utf8 = unicodeFormat8(code);
  7504. for (var j = 0; j < utf8.length; j++) {
  7505. utf8codes.push(utf8[j]);
  7506. }
  7507. }
  7508. return utf8codes;
  7509. }
  7510. /**
  7511. * 二维码算法实现
  7512. * @param {string} data 要编码的信息字符串
  7513. * @param {num} errorCorrectLevel 纠错等级
  7514. */
  7515. function QRCodeAlg(data, errorCorrectLevel) {
  7516. this.typeNumber = -1;
  7517. //版本
  7518. this.errorCorrectLevel = errorCorrectLevel;
  7519. this.modules = null;
  7520. //二维矩阵,存放最终结果
  7521. this.moduleCount = 0;
  7522. //矩阵大小
  7523. this.dataCache = null;
  7524. //数据缓存
  7525. this.rsBlocks = null;
  7526. //版本数据信息
  7527. this.totalDataCount = -1;
  7528. //可使用的数据量
  7529. this.data = data;
  7530. this.utf8bytes = getUTF8Bytes(data);
  7531. this.make();
  7532. }
  7533. QRCodeAlg.prototype = {
  7534. constructor: QRCodeAlg,
  7535. /**
  7536. * 获取二维码矩阵大小
  7537. * @return {num} 矩阵大小
  7538. */
  7539. getModuleCount: function() {
  7540. return this.moduleCount;
  7541. },
  7542. /**
  7543. * 编码
  7544. */
  7545. make: function() {
  7546. this.getRightType();
  7547. this.dataCache = this.createData();
  7548. this.createQrcode();
  7549. },
  7550. /**
  7551. * 设置二位矩阵功能图形
  7552. * @param {bool} test 表示是否在寻找最好掩膜阶段
  7553. * @param {num} maskPattern 掩膜的版本
  7554. */
  7555. makeImpl: function(maskPattern) {
  7556. this.moduleCount = this.typeNumber * 4 + 17;
  7557. this.modules = new Array(this.moduleCount);
  7558. for (var row = 0; row < this.moduleCount; row++) {
  7559. this.modules[row] = new Array(this.moduleCount);
  7560. }
  7561. this.setupPositionProbePattern(0, 0);
  7562. this.setupPositionProbePattern(this.moduleCount - 7, 0);
  7563. this.setupPositionProbePattern(0, this.moduleCount - 7);
  7564. this.setupPositionAdjustPattern();
  7565. this.setupTimingPattern();
  7566. this.setupTypeInfo(true, maskPattern);
  7567. if (this.typeNumber >= 7) {
  7568. this.setupTypeNumber(true);
  7569. }
  7570. this.mapData(this.dataCache, maskPattern);
  7571. },
  7572. /**
  7573. * 设置二维码的位置探测图形
  7574. * @param {num} row 探测图形的中心横坐标
  7575. * @param {num} col 探测图形的中心纵坐标
  7576. */
  7577. setupPositionProbePattern: function(row, col) {
  7578. for (var r = -1; r <= 7; r++) {
  7579. if (row + r <= -1 || this.moduleCount <= row + r) continue;
  7580. for (var c = -1; c <= 7; c++) {
  7581. if (col + c <= -1 || this.moduleCount <= col + c) continue;
  7582. if (0 <= r && r <= 6 && (c == 0 || c == 6) || 0 <= c && c <= 6 && (r == 0 || r == 6) || 2 <= r && r <= 4 && 2 <= c && c <= 4) {
  7583. this.modules[row + r][col + c] = true;
  7584. } else {
  7585. this.modules[row + r][col + c] = false;
  7586. }
  7587. }
  7588. }
  7589. },
  7590. /**
  7591. * 创建二维码
  7592. * @return {[type]} [description]
  7593. */
  7594. createQrcode: function() {
  7595. var minLostPoint = 0;
  7596. var pattern = 0;
  7597. var bestModules = null;
  7598. for (var i = 0; i < 8; i++) {
  7599. this.makeImpl(i);
  7600. var lostPoint = QRUtil.getLostPoint(this);
  7601. if (i == 0 || minLostPoint > lostPoint) {
  7602. minLostPoint = lostPoint;
  7603. pattern = i;
  7604. bestModules = this.modules;
  7605. }
  7606. }
  7607. this.modules = bestModules;
  7608. this.setupTypeInfo(false, pattern);
  7609. if (this.typeNumber >= 7) {
  7610. this.setupTypeNumber(false);
  7611. }
  7612. },
  7613. /**
  7614. * 设置定位图形
  7615. * @return {[type]} [description]
  7616. */
  7617. setupTimingPattern: function() {
  7618. for (var r = 8; r < this.moduleCount - 8; r++) {
  7619. if (this.modules[r][6] != null) {
  7620. continue;
  7621. }
  7622. this.modules[r][6] = r % 2 == 0;
  7623. if (this.modules[6][r] != null) {
  7624. continue;
  7625. }
  7626. this.modules[6][r] = r % 2 == 0;
  7627. }
  7628. },
  7629. /**
  7630. * 设置矫正图形
  7631. * @return {[type]} [description]
  7632. */
  7633. setupPositionAdjustPattern: function() {
  7634. var pos = QRUtil.getPatternPosition(this.typeNumber);
  7635. for (var i = 0; i < pos.length; i++) {
  7636. for (var j = 0; j < pos.length; j++) {
  7637. var row = pos[i];
  7638. var col = pos[j];
  7639. if (this.modules[row][col] != null) {
  7640. continue;
  7641. }
  7642. for (var r = -2; r <= 2; r++) {
  7643. for (var c = -2; c <= 2; c++) {
  7644. if (r == -2 || r == 2 || c == -2 || c == 2 || r == 0 && c == 0) {
  7645. this.modules[row + r][col + c] = true;
  7646. } else {
  7647. this.modules[row + r][col + c] = false;
  7648. }
  7649. }
  7650. }
  7651. }
  7652. }
  7653. },
  7654. /**
  7655. * 设置版本信息(7以上版本才有)
  7656. * @param {bool} test 是否处于判断最佳掩膜阶段
  7657. * @return {[type]} [description]
  7658. */
  7659. setupTypeNumber: function(test) {
  7660. var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
  7661. for (var i = 0; i < 18; i++) {
  7662. var mod = !test && (bits >> i & 1) == 1;
  7663. this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
  7664. this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
  7665. }
  7666. },
  7667. /**
  7668. * 设置格式信息(纠错等级和掩膜版本)
  7669. * @param {bool} test
  7670. * @param {num} maskPattern 掩膜版本
  7671. * @return {}
  7672. */
  7673. setupTypeInfo: function(test, maskPattern) {
  7674. var data = QRErrorCorrectLevel[this.errorCorrectLevel] << 3 | maskPattern;
  7675. var bits = QRUtil.getBCHTypeInfo(data);
  7676. // vertical
  7677. for (var i = 0; i < 15; i++) {
  7678. var mod = !test && (bits >> i & 1) == 1;
  7679. if (i < 6) {
  7680. this.modules[i][8] = mod;
  7681. } else if (i < 8) {
  7682. this.modules[i + 1][8] = mod;
  7683. } else {
  7684. this.modules[this.moduleCount - 15 + i][8] = mod;
  7685. }
  7686. // horizontal
  7687. var mod = !test && (bits >> i & 1) == 1;
  7688. if (i < 8) {
  7689. this.modules[8][this.moduleCount - i - 1] = mod;
  7690. } else if (i < 9) {
  7691. this.modules[8][15 - i - 1 + 1] = mod;
  7692. } else {
  7693. this.modules[8][15 - i - 1] = mod;
  7694. }
  7695. }
  7696. // fixed module
  7697. this.modules[this.moduleCount - 8][8] = !test;
  7698. },
  7699. /**
  7700. * 数据编码
  7701. * @return {[type]} [description]
  7702. */
  7703. createData: function() {
  7704. var buffer = new QRBitBuffer();
  7705. var lengthBits = this.typeNumber > 9 ? 16 : 8;
  7706. buffer.put(4, 4);
  7707. //添加模式
  7708. buffer.put(this.utf8bytes.length, lengthBits);
  7709. for (var i = 0, l = this.utf8bytes.length; i < l; i++) {
  7710. buffer.put(this.utf8bytes[i], 8);
  7711. }
  7712. if (buffer.length + 4 <= this.totalDataCount * 8) {
  7713. buffer.put(0, 4);
  7714. }
  7715. // padding
  7716. while (buffer.length % 8 != 0) {
  7717. buffer.putBit(false);
  7718. }
  7719. // padding
  7720. while (true) {
  7721. if (buffer.length >= this.totalDataCount * 8) {
  7722. break;
  7723. }
  7724. buffer.put(QRCodeAlg.PAD0, 8);
  7725. if (buffer.length >= this.totalDataCount * 8) {
  7726. break;
  7727. }
  7728. buffer.put(QRCodeAlg.PAD1, 8);
  7729. }
  7730. return this.createBytes(buffer);
  7731. },
  7732. /**
  7733. * 纠错码编码
  7734. * @param {buffer} buffer 数据编码
  7735. * @return {[type]}
  7736. */
  7737. createBytes: function(buffer) {
  7738. var offset = 0;
  7739. var maxDcCount = 0;
  7740. var maxEcCount = 0;
  7741. var length = this.rsBlock.length / 3;
  7742. var rsBlocks = new Array();
  7743. for (var i = 0; i < length; i++) {
  7744. var count = this.rsBlock[i * 3 + 0];
  7745. var totalCount = this.rsBlock[i * 3 + 1];
  7746. var dataCount = this.rsBlock[i * 3 + 2];
  7747. for (var j = 0; j < count; j++) {
  7748. rsBlocks.push([ dataCount, totalCount ]);
  7749. }
  7750. }
  7751. var dcdata = new Array(rsBlocks.length);
  7752. var ecdata = new Array(rsBlocks.length);
  7753. for (var r = 0; r < rsBlocks.length; r++) {
  7754. var dcCount = rsBlocks[r][0];
  7755. var ecCount = rsBlocks[r][1] - dcCount;
  7756. maxDcCount = Math.max(maxDcCount, dcCount);
  7757. maxEcCount = Math.max(maxEcCount, ecCount);
  7758. dcdata[r] = new Array(dcCount);
  7759. for (var i = 0; i < dcdata[r].length; i++) {
  7760. dcdata[r][i] = 255 & buffer.buffer[i + offset];
  7761. }
  7762. offset += dcCount;
  7763. var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
  7764. var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
  7765. var modPoly = rawPoly.mod(rsPoly);
  7766. ecdata[r] = new Array(rsPoly.getLength() - 1);
  7767. for (var i = 0; i < ecdata[r].length; i++) {
  7768. var modIndex = i + modPoly.getLength() - ecdata[r].length;
  7769. ecdata[r][i] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
  7770. }
  7771. }
  7772. var data = new Array(this.totalDataCount);
  7773. var index = 0;
  7774. for (var i = 0; i < maxDcCount; i++) {
  7775. for (var r = 0; r < rsBlocks.length; r++) {
  7776. if (i < dcdata[r].length) {
  7777. data[index++] = dcdata[r][i];
  7778. }
  7779. }
  7780. }
  7781. for (var i = 0; i < maxEcCount; i++) {
  7782. for (var r = 0; r < rsBlocks.length; r++) {
  7783. if (i < ecdata[r].length) {
  7784. data[index++] = ecdata[r][i];
  7785. }
  7786. }
  7787. }
  7788. return data;
  7789. },
  7790. /**
  7791. * 布置模块,构建最终信息
  7792. * @param {} data
  7793. * @param {} maskPattern
  7794. * @return {}
  7795. */
  7796. mapData: function(data, maskPattern) {
  7797. var inc = -1;
  7798. var row = this.moduleCount - 1;
  7799. var bitIndex = 7;
  7800. var byteIndex = 0;
  7801. for (var col = this.moduleCount - 1; col > 0; col -= 2) {
  7802. if (col == 6) col--;
  7803. while (true) {
  7804. for (var c = 0; c < 2; c++) {
  7805. if (this.modules[row][col - c] == null) {
  7806. var dark = false;
  7807. if (byteIndex < data.length) {
  7808. dark = (data[byteIndex] >>> bitIndex & 1) == 1;
  7809. }
  7810. var mask = QRUtil.getMask(maskPattern, row, col - c);
  7811. if (mask) {
  7812. dark = !dark;
  7813. }
  7814. this.modules[row][col - c] = dark;
  7815. bitIndex--;
  7816. if (bitIndex == -1) {
  7817. byteIndex++;
  7818. bitIndex = 7;
  7819. }
  7820. }
  7821. }
  7822. row += inc;
  7823. if (row < 0 || this.moduleCount <= row) {
  7824. row -= inc;
  7825. inc = -inc;
  7826. break;
  7827. }
  7828. }
  7829. }
  7830. }
  7831. };
  7832. /**
  7833. * 填充字段
  7834. */
  7835. QRCodeAlg.PAD0 = 236;
  7836. QRCodeAlg.PAD1 = 17;
  7837. //---------------------------------------------------------------------
  7838. // 纠错等级对应的编码
  7839. //---------------------------------------------------------------------
  7840. var QRErrorCorrectLevel = [ 1, 0, 3, 2 ];
  7841. //---------------------------------------------------------------------
  7842. // 掩膜版本
  7843. //---------------------------------------------------------------------
  7844. var QRMaskPattern = {
  7845. PATTERN000: 0,
  7846. PATTERN001: 1,
  7847. PATTERN010: 2,
  7848. PATTERN011: 3,
  7849. PATTERN100: 4,
  7850. PATTERN101: 5,
  7851. PATTERN110: 6,
  7852. PATTERN111: 7
  7853. };
  7854. //---------------------------------------------------------------------
  7855. // 工具类
  7856. //---------------------------------------------------------------------
  7857. var QRUtil = {
  7858. /*
  7859. 每个版本矫正图形的位置
  7860. */
  7861. PATTERN_POSITION_TABLE: [ [], [ 6, 18 ], [ 6, 22 ], [ 6, 26 ], [ 6, 30 ], [ 6, 34 ], [ 6, 22, 38 ], [ 6, 24, 42 ], [ 6, 26, 46 ], [ 6, 28, 50 ], [ 6, 30, 54 ], [ 6, 32, 58 ], [ 6, 34, 62 ], [ 6, 26, 46, 66 ], [ 6, 26, 48, 70 ], [ 6, 26, 50, 74 ], [ 6, 30, 54, 78 ], [ 6, 30, 56, 82 ], [ 6, 30, 58, 86 ], [ 6, 34, 62, 90 ], [ 6, 28, 50, 72, 94 ], [ 6, 26, 50, 74, 98 ], [ 6, 30, 54, 78, 102 ], [ 6, 28, 54, 80, 106 ], [ 6, 32, 58, 84, 110 ], [ 6, 30, 58, 86, 114 ], [ 6, 34, 62, 90, 118 ], [ 6, 26, 50, 74, 98, 122 ], [ 6, 30, 54, 78, 102, 126 ], [ 6, 26, 52, 78, 104, 130 ], [ 6, 30, 56, 82, 108, 134 ], [ 6, 34, 60, 86, 112, 138 ], [ 6, 30, 58, 86, 114, 142 ], [ 6, 34, 62, 90, 118, 146 ], [ 6, 30, 54, 78, 102, 126, 150 ], [ 6, 24, 50, 76, 102, 128, 154 ], [ 6, 28, 54, 80, 106, 132, 158 ], [ 6, 32, 58, 84, 110, 136, 162 ], [ 6, 26, 54, 82, 110, 138, 166 ], [ 6, 30, 58, 86, 114, 142, 170 ] ],
  7862. G15: 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0,
  7863. G18: 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0,
  7864. G15_MASK: 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1,
  7865. /*
  7866. BCH编码格式信息
  7867. */
  7868. getBCHTypeInfo: function(data) {
  7869. var d = data << 10;
  7870. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
  7871. d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);
  7872. }
  7873. return (data << 10 | d) ^ QRUtil.G15_MASK;
  7874. },
  7875. /*
  7876. BCH编码版本信息
  7877. */
  7878. getBCHTypeNumber: function(data) {
  7879. var d = data << 12;
  7880. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
  7881. d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);
  7882. }
  7883. return data << 12 | d;
  7884. },
  7885. /*
  7886. 获取BCH位信息
  7887. */
  7888. getBCHDigit: function(data) {
  7889. var digit = 0;
  7890. while (data != 0) {
  7891. digit++;
  7892. data >>>= 1;
  7893. }
  7894. return digit;
  7895. },
  7896. /*
  7897. 获取版本对应的矫正图形位置
  7898. */
  7899. getPatternPosition: function(typeNumber) {
  7900. return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
  7901. },
  7902. /*
  7903. 掩膜算法
  7904. */
  7905. getMask: function(maskPattern, i, j) {
  7906. switch (maskPattern) {
  7907. case QRMaskPattern.PATTERN000:
  7908. return (i + j) % 2 == 0;
  7909. case QRMaskPattern.PATTERN001:
  7910. return i % 2 == 0;
  7911. case QRMaskPattern.PATTERN010:
  7912. return j % 3 == 0;
  7913. case QRMaskPattern.PATTERN011:
  7914. return (i + j) % 3 == 0;
  7915. case QRMaskPattern.PATTERN100:
  7916. return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
  7917. case QRMaskPattern.PATTERN101:
  7918. return i * j % 2 + i * j % 3 == 0;
  7919. case QRMaskPattern.PATTERN110:
  7920. return (i * j % 2 + i * j % 3) % 2 == 0;
  7921. case QRMaskPattern.PATTERN111:
  7922. return (i * j % 3 + (i + j) % 2) % 2 == 0;
  7923. default:
  7924. throw new Error("bad maskPattern:" + maskPattern);
  7925. }
  7926. },
  7927. /*
  7928. 获取RS的纠错多项式
  7929. */
  7930. getErrorCorrectPolynomial: function(errorCorrectLength) {
  7931. var a = new QRPolynomial([ 1 ], 0);
  7932. for (var i = 0; i < errorCorrectLength; i++) {
  7933. a = a.multiply(new QRPolynomial([ 1, QRMath.gexp(i) ], 0));
  7934. }
  7935. return a;
  7936. },
  7937. /*
  7938. 获取评价
  7939. */
  7940. getLostPoint: function(qrCode) {
  7941. var moduleCount = qrCode.getModuleCount(), lostPoint = 0, darkCount = 0;
  7942. for (var row = 0; row < moduleCount; row++) {
  7943. var sameCount = 0;
  7944. var head = qrCode.modules[row][0];
  7945. for (var col = 0; col < moduleCount; col++) {
  7946. var current = qrCode.modules[row][col];
  7947. //level 3 评价
  7948. if (col < moduleCount - 6) {
  7949. if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) {
  7950. if (col < moduleCount - 10) {
  7951. if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) {
  7952. lostPoint += 40;
  7953. }
  7954. } else if (col > 3) {
  7955. if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) {
  7956. lostPoint += 40;
  7957. }
  7958. }
  7959. }
  7960. }
  7961. //level 2 评价
  7962. if (row < moduleCount - 1 && col < moduleCount - 1) {
  7963. var count = 0;
  7964. if (current) count++;
  7965. if (qrCode.modules[row + 1][col]) count++;
  7966. if (qrCode.modules[row][col + 1]) count++;
  7967. if (qrCode.modules[row + 1][col + 1]) count++;
  7968. if (count == 0 || count == 4) {
  7969. lostPoint += 3;
  7970. }
  7971. }
  7972. //level 1 评价
  7973. if (head ^ current) {
  7974. sameCount++;
  7975. } else {
  7976. head = current;
  7977. if (sameCount >= 5) {
  7978. lostPoint += 3 + sameCount - 5;
  7979. }
  7980. sameCount = 1;
  7981. }
  7982. //level 4 评价
  7983. if (current) {
  7984. darkCount++;
  7985. }
  7986. }
  7987. }
  7988. for (var col = 0; col < moduleCount; col++) {
  7989. var sameCount = 0;
  7990. var head = qrCode.modules[0][col];
  7991. for (var row = 0; row < moduleCount; row++) {
  7992. var current = qrCode.modules[row][col];
  7993. //level 3 评价
  7994. if (row < moduleCount - 6) {
  7995. if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) {
  7996. if (row < moduleCount - 10) {
  7997. if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) {
  7998. lostPoint += 40;
  7999. }
  8000. } else if (row > 3) {
  8001. if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) {
  8002. lostPoint += 40;
  8003. }
  8004. }
  8005. }
  8006. }
  8007. //level 1 评价
  8008. if (head ^ current) {
  8009. sameCount++;
  8010. } else {
  8011. head = current;
  8012. if (sameCount >= 5) {
  8013. lostPoint += 3 + sameCount - 5;
  8014. }
  8015. sameCount = 1;
  8016. }
  8017. }
  8018. }
  8019. // LEVEL4
  8020. var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
  8021. lostPoint += ratio * 10;
  8022. return lostPoint;
  8023. }
  8024. };
  8025. //---------------------------------------------------------------------
  8026. // QRMath使用的数学工具
  8027. //---------------------------------------------------------------------
  8028. var QRMath = {
  8029. /*
  8030. 将n转化为a^m
  8031. */
  8032. glog: function(n) {
  8033. if (n < 1) {
  8034. throw new Error("glog(" + n + ")");
  8035. }
  8036. return QRMath.LOG_TABLE[n];
  8037. },
  8038. /*
  8039. 将a^m转化为n
  8040. */
  8041. gexp: function(n) {
  8042. while (n < 0) {
  8043. n += 255;
  8044. }
  8045. while (n >= 256) {
  8046. n -= 255;
  8047. }
  8048. return QRMath.EXP_TABLE[n];
  8049. },
  8050. EXP_TABLE: new Array(256),
  8051. LOG_TABLE: new Array(256)
  8052. };
  8053. for (var i = 0; i < 8; i++) {
  8054. QRMath.EXP_TABLE[i] = 1 << i;
  8055. }
  8056. for (var i = 8; i < 256; i++) {
  8057. QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
  8058. }
  8059. for (var i = 0; i < 255; i++) {
  8060. QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
  8061. }
  8062. //---------------------------------------------------------------------
  8063. // QRPolynomial 多项式
  8064. //---------------------------------------------------------------------
  8065. /**
  8066. * 多项式类
  8067. * @param {Array} num 系数
  8068. * @param {num} shift a^shift
  8069. */
  8070. function QRPolynomial(num, shift) {
  8071. if (num.length == undefined) {
  8072. throw new Error(num.length + "/" + shift);
  8073. }
  8074. var offset = 0;
  8075. while (offset < num.length && num[offset] == 0) {
  8076. offset++;
  8077. }
  8078. this.num = new Array(num.length - offset + shift);
  8079. for (var i = 0; i < num.length - offset; i++) {
  8080. this.num[i] = num[i + offset];
  8081. }
  8082. }
  8083. QRPolynomial.prototype = {
  8084. get: function(index) {
  8085. return this.num[index];
  8086. },
  8087. getLength: function() {
  8088. return this.num.length;
  8089. },
  8090. /**
  8091. * 多项式乘法
  8092. * @param {QRPolynomial} e 被乘多项式
  8093. * @return {[type]} [description]
  8094. */
  8095. multiply: function(e) {
  8096. var num = new Array(this.getLength() + e.getLength() - 1);
  8097. for (var i = 0; i < this.getLength(); i++) {
  8098. for (var j = 0; j < e.getLength(); j++) {
  8099. num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
  8100. }
  8101. }
  8102. return new QRPolynomial(num, 0);
  8103. },
  8104. /**
  8105. * 多项式模运算
  8106. * @param {QRPolynomial} e 模多项式
  8107. * @return {}
  8108. */
  8109. mod: function(e) {
  8110. var tl = this.getLength(), el = e.getLength();
  8111. if (tl - el < 0) {
  8112. return this;
  8113. }
  8114. var num = new Array(tl);
  8115. for (var i = 0; i < tl; i++) {
  8116. num[i] = this.get(i);
  8117. }
  8118. while (num.length >= el) {
  8119. var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0));
  8120. for (var i = 0; i < e.getLength(); i++) {
  8121. num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
  8122. }
  8123. while (num[0] == 0) {
  8124. num.shift();
  8125. }
  8126. }
  8127. return new QRPolynomial(num, 0);
  8128. }
  8129. };
  8130. //---------------------------------------------------------------------
  8131. // RS_BLOCK_TABLE
  8132. //---------------------------------------------------------------------
  8133. /*
  8134. 二维码各个版本信息[块数, 每块中的数据块数, 每块中的信息块数]
  8135. */
  8136. var RS_BLOCK_TABLE = [ // L
  8137. // M
  8138. // Q
  8139. // H
  8140. // 1
  8141. [ 1, 26, 19 ], [ 1, 26, 16 ], [ 1, 26, 13 ], [ 1, 26, 9 ], // 2
  8142. [ 1, 44, 34 ], [ 1, 44, 28 ], [ 1, 44, 22 ], [ 1, 44, 16 ], // 3
  8143. [ 1, 70, 55 ], [ 1, 70, 44 ], [ 2, 35, 17 ], [ 2, 35, 13 ], // 4
  8144. [ 1, 100, 80 ], [ 2, 50, 32 ], [ 2, 50, 24 ], [ 4, 25, 9 ], // 5
  8145. [ 1, 134, 108 ], [ 2, 67, 43 ], [ 2, 33, 15, 2, 34, 16 ], [ 2, 33, 11, 2, 34, 12 ], // 6
  8146. [ 2, 86, 68 ], [ 4, 43, 27 ], [ 4, 43, 19 ], [ 4, 43, 15 ], // 7
  8147. [ 2, 98, 78 ], [ 4, 49, 31 ], [ 2, 32, 14, 4, 33, 15 ], [ 4, 39, 13, 1, 40, 14 ], // 8
  8148. [ 2, 121, 97 ], [ 2, 60, 38, 2, 61, 39 ], [ 4, 40, 18, 2, 41, 19 ], [ 4, 40, 14, 2, 41, 15 ], // 9
  8149. [ 2, 146, 116 ], [ 3, 58, 36, 2, 59, 37 ], [ 4, 36, 16, 4, 37, 17 ], [ 4, 36, 12, 4, 37, 13 ], // 10
  8150. [ 2, 86, 68, 2, 87, 69 ], [ 4, 69, 43, 1, 70, 44 ], [ 6, 43, 19, 2, 44, 20 ], [ 6, 43, 15, 2, 44, 16 ], // 11
  8151. [ 4, 101, 81 ], [ 1, 80, 50, 4, 81, 51 ], [ 4, 50, 22, 4, 51, 23 ], [ 3, 36, 12, 8, 37, 13 ], // 12
  8152. [ 2, 116, 92, 2, 117, 93 ], [ 6, 58, 36, 2, 59, 37 ], [ 4, 46, 20, 6, 47, 21 ], [ 7, 42, 14, 4, 43, 15 ], // 13
  8153. [ 4, 133, 107 ], [ 8, 59, 37, 1, 60, 38 ], [ 8, 44, 20, 4, 45, 21 ], [ 12, 33, 11, 4, 34, 12 ], // 14
  8154. [ 3, 145, 115, 1, 146, 116 ], [ 4, 64, 40, 5, 65, 41 ], [ 11, 36, 16, 5, 37, 17 ], [ 11, 36, 12, 5, 37, 13 ], // 15
  8155. [ 5, 109, 87, 1, 110, 88 ], [ 5, 65, 41, 5, 66, 42 ], [ 5, 54, 24, 7, 55, 25 ], [ 11, 36, 12 ], // 16
  8156. [ 5, 122, 98, 1, 123, 99 ], [ 7, 73, 45, 3, 74, 46 ], [ 15, 43, 19, 2, 44, 20 ], [ 3, 45, 15, 13, 46, 16 ], // 17
  8157. [ 1, 135, 107, 5, 136, 108 ], [ 10, 74, 46, 1, 75, 47 ], [ 1, 50, 22, 15, 51, 23 ], [ 2, 42, 14, 17, 43, 15 ], // 18
  8158. [ 5, 150, 120, 1, 151, 121 ], [ 9, 69, 43, 4, 70, 44 ], [ 17, 50, 22, 1, 51, 23 ], [ 2, 42, 14, 19, 43, 15 ], // 19
  8159. [ 3, 141, 113, 4, 142, 114 ], [ 3, 70, 44, 11, 71, 45 ], [ 17, 47, 21, 4, 48, 22 ], [ 9, 39, 13, 16, 40, 14 ], // 20
  8160. [ 3, 135, 107, 5, 136, 108 ], [ 3, 67, 41, 13, 68, 42 ], [ 15, 54, 24, 5, 55, 25 ], [ 15, 43, 15, 10, 44, 16 ], // 21
  8161. [ 4, 144, 116, 4, 145, 117 ], [ 17, 68, 42 ], [ 17, 50, 22, 6, 51, 23 ], [ 19, 46, 16, 6, 47, 17 ], // 22
  8162. [ 2, 139, 111, 7, 140, 112 ], [ 17, 74, 46 ], [ 7, 54, 24, 16, 55, 25 ], [ 34, 37, 13 ], // 23
  8163. [ 4, 151, 121, 5, 152, 122 ], [ 4, 75, 47, 14, 76, 48 ], [ 11, 54, 24, 14, 55, 25 ], [ 16, 45, 15, 14, 46, 16 ], // 24
  8164. [ 6, 147, 117, 4, 148, 118 ], [ 6, 73, 45, 14, 74, 46 ], [ 11, 54, 24, 16, 55, 25 ], [ 30, 46, 16, 2, 47, 17 ], // 25
  8165. [ 8, 132, 106, 4, 133, 107 ], [ 8, 75, 47, 13, 76, 48 ], [ 7, 54, 24, 22, 55, 25 ], [ 22, 45, 15, 13, 46, 16 ], // 26
  8166. [ 10, 142, 114, 2, 143, 115 ], [ 19, 74, 46, 4, 75, 47 ], [ 28, 50, 22, 6, 51, 23 ], [ 33, 46, 16, 4, 47, 17 ], // 27
  8167. [ 8, 152, 122, 4, 153, 123 ], [ 22, 73, 45, 3, 74, 46 ], [ 8, 53, 23, 26, 54, 24 ], [ 12, 45, 15, 28, 46, 16 ], // 28
  8168. [ 3, 147, 117, 10, 148, 118 ], [ 3, 73, 45, 23, 74, 46 ], [ 4, 54, 24, 31, 55, 25 ], [ 11, 45, 15, 31, 46, 16 ], // 29
  8169. [ 7, 146, 116, 7, 147, 117 ], [ 21, 73, 45, 7, 74, 46 ], [ 1, 53, 23, 37, 54, 24 ], [ 19, 45, 15, 26, 46, 16 ], // 30
  8170. [ 5, 145, 115, 10, 146, 116 ], [ 19, 75, 47, 10, 76, 48 ], [ 15, 54, 24, 25, 55, 25 ], [ 23, 45, 15, 25, 46, 16 ], // 31
  8171. [ 13, 145, 115, 3, 146, 116 ], [ 2, 74, 46, 29, 75, 47 ], [ 42, 54, 24, 1, 55, 25 ], [ 23, 45, 15, 28, 46, 16 ], // 32
  8172. [ 17, 145, 115 ], [ 10, 74, 46, 23, 75, 47 ], [ 10, 54, 24, 35, 55, 25 ], [ 19, 45, 15, 35, 46, 16 ], // 33
  8173. [ 17, 145, 115, 1, 146, 116 ], [ 14, 74, 46, 21, 75, 47 ], [ 29, 54, 24, 19, 55, 25 ], [ 11, 45, 15, 46, 46, 16 ], // 34
  8174. [ 13, 145, 115, 6, 146, 116 ], [ 14, 74, 46, 23, 75, 47 ], [ 44, 54, 24, 7, 55, 25 ], [ 59, 46, 16, 1, 47, 17 ], // 35
  8175. [ 12, 151, 121, 7, 152, 122 ], [ 12, 75, 47, 26, 76, 48 ], [ 39, 54, 24, 14, 55, 25 ], [ 22, 45, 15, 41, 46, 16 ], // 36
  8176. [ 6, 151, 121, 14, 152, 122 ], [ 6, 75, 47, 34, 76, 48 ], [ 46, 54, 24, 10, 55, 25 ], [ 2, 45, 15, 64, 46, 16 ], // 37
  8177. [ 17, 152, 122, 4, 153, 123 ], [ 29, 74, 46, 14, 75, 47 ], [ 49, 54, 24, 10, 55, 25 ], [ 24, 45, 15, 46, 46, 16 ], // 38
  8178. [ 4, 152, 122, 18, 153, 123 ], [ 13, 74, 46, 32, 75, 47 ], [ 48, 54, 24, 14, 55, 25 ], [ 42, 45, 15, 32, 46, 16 ], // 39
  8179. [ 20, 147, 117, 4, 148, 118 ], [ 40, 75, 47, 7, 76, 48 ], [ 43, 54, 24, 22, 55, 25 ], [ 10, 45, 15, 67, 46, 16 ], // 40
  8180. [ 19, 148, 118, 6, 149, 119 ], [ 18, 75, 47, 31, 76, 48 ], [ 34, 54, 24, 34, 55, 25 ], [ 20, 45, 15, 61, 46, 16 ] ];
  8181. /**
  8182. * 根据数据获取对应版本
  8183. * @return {[type]} [description]
  8184. */
  8185. QRCodeAlg.prototype.getRightType = function() {
  8186. for (var typeNumber = 1; typeNumber < 41; typeNumber++) {
  8187. var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel];
  8188. if (rsBlock == undefined) {
  8189. throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel);
  8190. }
  8191. var length = rsBlock.length / 3;
  8192. var totalDataCount = 0;
  8193. for (var i = 0; i < length; i++) {
  8194. var count = rsBlock[i * 3 + 0];
  8195. var dataCount = rsBlock[i * 3 + 2];
  8196. totalDataCount += dataCount * count;
  8197. }
  8198. var lengthBytes = typeNumber > 9 ? 2 : 1;
  8199. if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) {
  8200. this.typeNumber = typeNumber;
  8201. this.rsBlock = rsBlock;
  8202. this.totalDataCount = totalDataCount;
  8203. break;
  8204. }
  8205. }
  8206. };
  8207. //---------------------------------------------------------------------
  8208. // QRBitBuffer
  8209. //---------------------------------------------------------------------
  8210. function QRBitBuffer() {
  8211. this.buffer = new Array();
  8212. this.length = 0;
  8213. }
  8214. QRBitBuffer.prototype = {
  8215. get: function(index) {
  8216. var bufIndex = Math.floor(index / 8);
  8217. return this.buffer[bufIndex] >>> 7 - index % 8 & 1;
  8218. },
  8219. put: function(num, length) {
  8220. for (var i = 0; i < length; i++) {
  8221. this.putBit(num >>> length - i - 1 & 1);
  8222. }
  8223. },
  8224. putBit: function(bit) {
  8225. var bufIndex = Math.floor(this.length / 8);
  8226. if (this.buffer.length <= bufIndex) {
  8227. this.buffer.push(0);
  8228. }
  8229. if (bit) {
  8230. this.buffer[bufIndex] |= 128 >>> this.length % 8;
  8231. }
  8232. this.length++;
  8233. }
  8234. };
  8235. /**
  8236. * 获取单个字符的utf8编码
  8237. * unicode BMP平面约65535个字符
  8238. * @param {num} code
  8239. * return {array}
  8240. */
  8241. function unicodeFormat8(code) {
  8242. // 1 byte
  8243. if (code < 128) {
  8244. return [ code ];
  8245. } else if (code < 2048) {
  8246. c0 = 192 + (code >> 6);
  8247. c1 = 128 + (code & 63);
  8248. return [ c0, c1 ];
  8249. } else {
  8250. c0 = 224 + (code >> 12);
  8251. c1 = 128 + (code >> 6 & 63);
  8252. c2 = 128 + (code & 63);
  8253. return [ c0, c1, c2 ];
  8254. }
  8255. }
  8256. /**
  8257. * 获取字符串的utf8编码字节串
  8258. * @param {string} string
  8259. * @return {array}
  8260. */
  8261. function getUTF8Bytes(string) {
  8262. var utf8codes = [];
  8263. for (var i = 0; i < string.length; i++) {
  8264. var code = string.charCodeAt(i);
  8265. var utf8 = unicodeFormat8(code);
  8266. for (var j = 0; j < utf8.length; j++) {
  8267. utf8codes.push(utf8[j]);
  8268. }
  8269. }
  8270. return utf8codes;
  8271. }
  8272. /**
  8273. * 二维码算法实现
  8274. * @param {string} data 要编码的信息字符串
  8275. * @param {num} errorCorrectLevel 纠错等级
  8276. */
  8277. function QRCodeAlg(data, errorCorrectLevel) {
  8278. this.typeNumber = -1;
  8279. //版本
  8280. this.errorCorrectLevel = errorCorrectLevel;
  8281. this.modules = null;
  8282. //二维矩阵,存放最终结果
  8283. this.moduleCount = 0;
  8284. //矩阵大小
  8285. this.dataCache = null;
  8286. //数据缓存
  8287. this.rsBlocks = null;
  8288. //版本数据信息
  8289. this.totalDataCount = -1;
  8290. //可使用的数据量
  8291. this.data = data;
  8292. this.utf8bytes = getUTF8Bytes(data);
  8293. this.make();
  8294. }
  8295. QRCodeAlg.prototype = {
  8296. constructor: QRCodeAlg,
  8297. /**
  8298. * 获取二维码矩阵大小
  8299. * @return {num} 矩阵大小
  8300. */
  8301. getModuleCount: function() {
  8302. return this.moduleCount;
  8303. },
  8304. /**
  8305. * 编码
  8306. */
  8307. make: function() {
  8308. this.getRightType();
  8309. this.dataCache = this.createData();
  8310. this.createQrcode();
  8311. },
  8312. /**
  8313. * 设置二位矩阵功能图形
  8314. * @param {bool} test 表示是否在寻找最好掩膜阶段
  8315. * @param {num} maskPattern 掩膜的版本
  8316. */
  8317. makeImpl: function(maskPattern) {
  8318. this.moduleCount = this.typeNumber * 4 + 17;
  8319. this.modules = new Array(this.moduleCount);
  8320. for (var row = 0; row < this.moduleCount; row++) {
  8321. this.modules[row] = new Array(this.moduleCount);
  8322. }
  8323. this.setupPositionProbePattern(0, 0);
  8324. this.setupPositionProbePattern(this.moduleCount - 7, 0);
  8325. this.setupPositionProbePattern(0, this.moduleCount - 7);
  8326. this.setupPositionAdjustPattern();
  8327. this.setupTimingPattern();
  8328. this.setupTypeInfo(true, maskPattern);
  8329. if (this.typeNumber >= 7) {
  8330. this.setupTypeNumber(true);
  8331. }
  8332. this.mapData(this.dataCache, maskPattern);
  8333. },
  8334. /**
  8335. * 设置二维码的位置探测图形
  8336. * @param {num} row 探测图形的中心横坐标
  8337. * @param {num} col 探测图形的中心纵坐标
  8338. */
  8339. setupPositionProbePattern: function(row, col) {
  8340. for (var r = -1; r <= 7; r++) {
  8341. if (row + r <= -1 || this.moduleCount <= row + r) continue;
  8342. for (var c = -1; c <= 7; c++) {
  8343. if (col + c <= -1 || this.moduleCount <= col + c) continue;
  8344. if (0 <= r && r <= 6 && (c == 0 || c == 6) || 0 <= c && c <= 6 && (r == 0 || r == 6) || 2 <= r && r <= 4 && 2 <= c && c <= 4) {
  8345. this.modules[row + r][col + c] = true;
  8346. } else {
  8347. this.modules[row + r][col + c] = false;
  8348. }
  8349. }
  8350. }
  8351. },
  8352. /**
  8353. * 创建二维码
  8354. * @return {[type]} [description]
  8355. */
  8356. createQrcode: function() {
  8357. var minLostPoint = 0;
  8358. var pattern = 0;
  8359. var bestModules = null;
  8360. for (var i = 0; i < 8; i++) {
  8361. this.makeImpl(i);
  8362. var lostPoint = QRUtil.getLostPoint(this);
  8363. if (i == 0 || minLostPoint > lostPoint) {
  8364. minLostPoint = lostPoint;
  8365. pattern = i;
  8366. bestModules = this.modules;
  8367. }
  8368. }
  8369. this.modules = bestModules;
  8370. this.setupTypeInfo(false, pattern);
  8371. if (this.typeNumber >= 7) {
  8372. this.setupTypeNumber(false);
  8373. }
  8374. },
  8375. /**
  8376. * 设置定位图形
  8377. * @return {[type]} [description]
  8378. */
  8379. setupTimingPattern: function() {
  8380. for (var r = 8; r < this.moduleCount - 8; r++) {
  8381. if (this.modules[r][6] != null) {
  8382. continue;
  8383. }
  8384. this.modules[r][6] = r % 2 == 0;
  8385. if (this.modules[6][r] != null) {
  8386. continue;
  8387. }
  8388. this.modules[6][r] = r % 2 == 0;
  8389. }
  8390. },
  8391. /**
  8392. * 设置矫正图形
  8393. * @return {[type]} [description]
  8394. */
  8395. setupPositionAdjustPattern: function() {
  8396. var pos = QRUtil.getPatternPosition(this.typeNumber);
  8397. for (var i = 0; i < pos.length; i++) {
  8398. for (var j = 0; j < pos.length; j++) {
  8399. var row = pos[i];
  8400. var col = pos[j];
  8401. if (this.modules[row][col] != null) {
  8402. continue;
  8403. }
  8404. for (var r = -2; r <= 2; r++) {
  8405. for (var c = -2; c <= 2; c++) {
  8406. if (r == -2 || r == 2 || c == -2 || c == 2 || r == 0 && c == 0) {
  8407. this.modules[row + r][col + c] = true;
  8408. } else {
  8409. this.modules[row + r][col + c] = false;
  8410. }
  8411. }
  8412. }
  8413. }
  8414. }
  8415. },
  8416. /**
  8417. * 设置版本信息(7以上版本才有)
  8418. * @param {bool} test 是否处于判断最佳掩膜阶段
  8419. * @return {[type]} [description]
  8420. */
  8421. setupTypeNumber: function(test) {
  8422. var bits = QRUtil.getBCHTypeNumber(this.typeNumber);
  8423. for (var i = 0; i < 18; i++) {
  8424. var mod = !test && (bits >> i & 1) == 1;
  8425. this.modules[Math.floor(i / 3)][i % 3 + this.moduleCount - 8 - 3] = mod;
  8426. this.modules[i % 3 + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
  8427. }
  8428. },
  8429. /**
  8430. * 设置格式信息(纠错等级和掩膜版本)
  8431. * @param {bool} test
  8432. * @param {num} maskPattern 掩膜版本
  8433. * @return {}
  8434. */
  8435. setupTypeInfo: function(test, maskPattern) {
  8436. var data = QRErrorCorrectLevel[this.errorCorrectLevel] << 3 | maskPattern;
  8437. var bits = QRUtil.getBCHTypeInfo(data);
  8438. // vertical
  8439. for (var i = 0; i < 15; i++) {
  8440. var mod = !test && (bits >> i & 1) == 1;
  8441. if (i < 6) {
  8442. this.modules[i][8] = mod;
  8443. } else if (i < 8) {
  8444. this.modules[i + 1][8] = mod;
  8445. } else {
  8446. this.modules[this.moduleCount - 15 + i][8] = mod;
  8447. }
  8448. // horizontal
  8449. var mod = !test && (bits >> i & 1) == 1;
  8450. if (i < 8) {
  8451. this.modules[8][this.moduleCount - i - 1] = mod;
  8452. } else if (i < 9) {
  8453. this.modules[8][15 - i - 1 + 1] = mod;
  8454. } else {
  8455. this.modules[8][15 - i - 1] = mod;
  8456. }
  8457. }
  8458. // fixed module
  8459. this.modules[this.moduleCount - 8][8] = !test;
  8460. },
  8461. /**
  8462. * 数据编码
  8463. * @return {[type]} [description]
  8464. */
  8465. createData: function() {
  8466. var buffer = new QRBitBuffer();
  8467. var lengthBits = this.typeNumber > 9 ? 16 : 8;
  8468. buffer.put(4, 4);
  8469. //添加模式
  8470. buffer.put(this.utf8bytes.length, lengthBits);
  8471. for (var i = 0, l = this.utf8bytes.length; i < l; i++) {
  8472. buffer.put(this.utf8bytes[i], 8);
  8473. }
  8474. if (buffer.length + 4 <= this.totalDataCount * 8) {
  8475. buffer.put(0, 4);
  8476. }
  8477. // padding
  8478. while (buffer.length % 8 != 0) {
  8479. buffer.putBit(false);
  8480. }
  8481. // padding
  8482. while (true) {
  8483. if (buffer.length >= this.totalDataCount * 8) {
  8484. break;
  8485. }
  8486. buffer.put(QRCodeAlg.PAD0, 8);
  8487. if (buffer.length >= this.totalDataCount * 8) {
  8488. break;
  8489. }
  8490. buffer.put(QRCodeAlg.PAD1, 8);
  8491. }
  8492. return this.createBytes(buffer);
  8493. },
  8494. /**
  8495. * 纠错码编码
  8496. * @param {buffer} buffer 数据编码
  8497. * @return {[type]}
  8498. */
  8499. createBytes: function(buffer) {
  8500. var offset = 0;
  8501. var maxDcCount = 0;
  8502. var maxEcCount = 0;
  8503. var length = this.rsBlock.length / 3;
  8504. var rsBlocks = new Array();
  8505. for (var i = 0; i < length; i++) {
  8506. var count = this.rsBlock[i * 3 + 0];
  8507. var totalCount = this.rsBlock[i * 3 + 1];
  8508. var dataCount = this.rsBlock[i * 3 + 2];
  8509. for (var j = 0; j < count; j++) {
  8510. rsBlocks.push([ dataCount, totalCount ]);
  8511. }
  8512. }
  8513. var dcdata = new Array(rsBlocks.length);
  8514. var ecdata = new Array(rsBlocks.length);
  8515. for (var r = 0; r < rsBlocks.length; r++) {
  8516. var dcCount = rsBlocks[r][0];
  8517. var ecCount = rsBlocks[r][1] - dcCount;
  8518. maxDcCount = Math.max(maxDcCount, dcCount);
  8519. maxEcCount = Math.max(maxEcCount, ecCount);
  8520. dcdata[r] = new Array(dcCount);
  8521. for (var i = 0; i < dcdata[r].length; i++) {
  8522. dcdata[r][i] = 255 & buffer.buffer[i + offset];
  8523. }
  8524. offset += dcCount;
  8525. var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
  8526. var rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
  8527. var modPoly = rawPoly.mod(rsPoly);
  8528. ecdata[r] = new Array(rsPoly.getLength() - 1);
  8529. for (var i = 0; i < ecdata[r].length; i++) {
  8530. var modIndex = i + modPoly.getLength() - ecdata[r].length;
  8531. ecdata[r][i] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
  8532. }
  8533. }
  8534. var data = new Array(this.totalDataCount);
  8535. var index = 0;
  8536. for (var i = 0; i < maxDcCount; i++) {
  8537. for (var r = 0; r < rsBlocks.length; r++) {
  8538. if (i < dcdata[r].length) {
  8539. data[index++] = dcdata[r][i];
  8540. }
  8541. }
  8542. }
  8543. for (var i = 0; i < maxEcCount; i++) {
  8544. for (var r = 0; r < rsBlocks.length; r++) {
  8545. if (i < ecdata[r].length) {
  8546. data[index++] = ecdata[r][i];
  8547. }
  8548. }
  8549. }
  8550. return data;
  8551. },
  8552. /**
  8553. * 布置模块,构建最终信息
  8554. * @param {} data
  8555. * @param {} maskPattern
  8556. * @return {}
  8557. */
  8558. mapData: function(data, maskPattern) {
  8559. var inc = -1;
  8560. var row = this.moduleCount - 1;
  8561. var bitIndex = 7;
  8562. var byteIndex = 0;
  8563. for (var col = this.moduleCount - 1; col > 0; col -= 2) {
  8564. if (col == 6) col--;
  8565. while (true) {
  8566. for (var c = 0; c < 2; c++) {
  8567. if (this.modules[row][col - c] == null) {
  8568. var dark = false;
  8569. if (byteIndex < data.length) {
  8570. dark = (data[byteIndex] >>> bitIndex & 1) == 1;
  8571. }
  8572. var mask = QRUtil.getMask(maskPattern, row, col - c);
  8573. if (mask) {
  8574. dark = !dark;
  8575. }
  8576. this.modules[row][col - c] = dark;
  8577. bitIndex--;
  8578. if (bitIndex == -1) {
  8579. byteIndex++;
  8580. bitIndex = 7;
  8581. }
  8582. }
  8583. }
  8584. row += inc;
  8585. if (row < 0 || this.moduleCount <= row) {
  8586. row -= inc;
  8587. inc = -inc;
  8588. break;
  8589. }
  8590. }
  8591. }
  8592. }
  8593. };
  8594. /**
  8595. * 填充字段
  8596. */
  8597. QRCodeAlg.PAD0 = 236;
  8598. QRCodeAlg.PAD1 = 17;
  8599. //---------------------------------------------------------------------
  8600. // 纠错等级对应的编码
  8601. //---------------------------------------------------------------------
  8602. var QRErrorCorrectLevel = [ 1, 0, 3, 2 ];
  8603. //---------------------------------------------------------------------
  8604. // 掩膜版本
  8605. //---------------------------------------------------------------------
  8606. var QRMaskPattern = {
  8607. PATTERN000: 0,
  8608. PATTERN001: 1,
  8609. PATTERN010: 2,
  8610. PATTERN011: 3,
  8611. PATTERN100: 4,
  8612. PATTERN101: 5,
  8613. PATTERN110: 6,
  8614. PATTERN111: 7
  8615. };
  8616. //---------------------------------------------------------------------
  8617. // 工具类
  8618. //---------------------------------------------------------------------
  8619. var QRUtil = {
  8620. /*
  8621. 每个版本矫正图形的位置
  8622. */
  8623. PATTERN_POSITION_TABLE: [ [], [ 6, 18 ], [ 6, 22 ], [ 6, 26 ], [ 6, 30 ], [ 6, 34 ], [ 6, 22, 38 ], [ 6, 24, 42 ], [ 6, 26, 46 ], [ 6, 28, 50 ], [ 6, 30, 54 ], [ 6, 32, 58 ], [ 6, 34, 62 ], [ 6, 26, 46, 66 ], [ 6, 26, 48, 70 ], [ 6, 26, 50, 74 ], [ 6, 30, 54, 78 ], [ 6, 30, 56, 82 ], [ 6, 30, 58, 86 ], [ 6, 34, 62, 90 ], [ 6, 28, 50, 72, 94 ], [ 6, 26, 50, 74, 98 ], [ 6, 30, 54, 78, 102 ], [ 6, 28, 54, 80, 106 ], [ 6, 32, 58, 84, 110 ], [ 6, 30, 58, 86, 114 ], [ 6, 34, 62, 90, 118 ], [ 6, 26, 50, 74, 98, 122 ], [ 6, 30, 54, 78, 102, 126 ], [ 6, 26, 52, 78, 104, 130 ], [ 6, 30, 56, 82, 108, 134 ], [ 6, 34, 60, 86, 112, 138 ], [ 6, 30, 58, 86, 114, 142 ], [ 6, 34, 62, 90, 118, 146 ], [ 6, 30, 54, 78, 102, 126, 150 ], [ 6, 24, 50, 76, 102, 128, 154 ], [ 6, 28, 54, 80, 106, 132, 158 ], [ 6, 32, 58, 84, 110, 136, 162 ], [ 6, 26, 54, 82, 110, 138, 166 ], [ 6, 30, 58, 86, 114, 142, 170 ] ],
  8624. G15: 1 << 10 | 1 << 8 | 1 << 5 | 1 << 4 | 1 << 2 | 1 << 1 | 1 << 0,
  8625. G18: 1 << 12 | 1 << 11 | 1 << 10 | 1 << 9 | 1 << 8 | 1 << 5 | 1 << 2 | 1 << 0,
  8626. G15_MASK: 1 << 14 | 1 << 12 | 1 << 10 | 1 << 4 | 1 << 1,
  8627. /*
  8628. BCH编码格式信息
  8629. */
  8630. getBCHTypeInfo: function(data) {
  8631. var d = data << 10;
  8632. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
  8633. d ^= QRUtil.G15 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15);
  8634. }
  8635. return (data << 10 | d) ^ QRUtil.G15_MASK;
  8636. },
  8637. /*
  8638. BCH编码版本信息
  8639. */
  8640. getBCHTypeNumber: function(data) {
  8641. var d = data << 12;
  8642. while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
  8643. d ^= QRUtil.G18 << QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18);
  8644. }
  8645. return data << 12 | d;
  8646. },
  8647. /*
  8648. 获取BCH位信息
  8649. */
  8650. getBCHDigit: function(data) {
  8651. var digit = 0;
  8652. while (data != 0) {
  8653. digit++;
  8654. data >>>= 1;
  8655. }
  8656. return digit;
  8657. },
  8658. /*
  8659. 获取版本对应的矫正图形位置
  8660. */
  8661. getPatternPosition: function(typeNumber) {
  8662. return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
  8663. },
  8664. /*
  8665. 掩膜算法
  8666. */
  8667. getMask: function(maskPattern, i, j) {
  8668. switch (maskPattern) {
  8669. case QRMaskPattern.PATTERN000:
  8670. return (i + j) % 2 == 0;
  8671. case QRMaskPattern.PATTERN001:
  8672. return i % 2 == 0;
  8673. case QRMaskPattern.PATTERN010:
  8674. return j % 3 == 0;
  8675. case QRMaskPattern.PATTERN011:
  8676. return (i + j) % 3 == 0;
  8677. case QRMaskPattern.PATTERN100:
  8678. return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
  8679. case QRMaskPattern.PATTERN101:
  8680. return i * j % 2 + i * j % 3 == 0;
  8681. case QRMaskPattern.PATTERN110:
  8682. return (i * j % 2 + i * j % 3) % 2 == 0;
  8683. case QRMaskPattern.PATTERN111:
  8684. return (i * j % 3 + (i + j) % 2) % 2 == 0;
  8685. default:
  8686. throw new Error("bad maskPattern:" + maskPattern);
  8687. }
  8688. },
  8689. /*
  8690. 获取RS的纠错多项式
  8691. */
  8692. getErrorCorrectPolynomial: function(errorCorrectLength) {
  8693. var a = new QRPolynomial([ 1 ], 0);
  8694. for (var i = 0; i < errorCorrectLength; i++) {
  8695. a = a.multiply(new QRPolynomial([ 1, QRMath.gexp(i) ], 0));
  8696. }
  8697. return a;
  8698. },
  8699. /*
  8700. 获取评价
  8701. */
  8702. getLostPoint: function(qrCode) {
  8703. var moduleCount = qrCode.getModuleCount(), lostPoint = 0, darkCount = 0;
  8704. for (var row = 0; row < moduleCount; row++) {
  8705. var sameCount = 0;
  8706. var head = qrCode.modules[row][0];
  8707. for (var col = 0; col < moduleCount; col++) {
  8708. var current = qrCode.modules[row][col];
  8709. //level 3 评价
  8710. if (col < moduleCount - 6) {
  8711. if (current && !qrCode.modules[row][col + 1] && qrCode.modules[row][col + 2] && qrCode.modules[row][col + 3] && qrCode.modules[row][col + 4] && !qrCode.modules[row][col + 5] && qrCode.modules[row][col + 6]) {
  8712. if (col < moduleCount - 10) {
  8713. if (qrCode.modules[row][col + 7] && qrCode.modules[row][col + 8] && qrCode.modules[row][col + 9] && qrCode.modules[row][col + 10]) {
  8714. lostPoint += 40;
  8715. }
  8716. } else if (col > 3) {
  8717. if (qrCode.modules[row][col - 1] && qrCode.modules[row][col - 2] && qrCode.modules[row][col - 3] && qrCode.modules[row][col - 4]) {
  8718. lostPoint += 40;
  8719. }
  8720. }
  8721. }
  8722. }
  8723. //level 2 评价
  8724. if (row < moduleCount - 1 && col < moduleCount - 1) {
  8725. var count = 0;
  8726. if (current) count++;
  8727. if (qrCode.modules[row + 1][col]) count++;
  8728. if (qrCode.modules[row][col + 1]) count++;
  8729. if (qrCode.modules[row + 1][col + 1]) count++;
  8730. if (count == 0 || count == 4) {
  8731. lostPoint += 3;
  8732. }
  8733. }
  8734. //level 1 评价
  8735. if (head ^ current) {
  8736. sameCount++;
  8737. } else {
  8738. head = current;
  8739. if (sameCount >= 5) {
  8740. lostPoint += 3 + sameCount - 5;
  8741. }
  8742. sameCount = 1;
  8743. }
  8744. //level 4 评价
  8745. if (current) {
  8746. darkCount++;
  8747. }
  8748. }
  8749. }
  8750. for (var col = 0; col < moduleCount; col++) {
  8751. var sameCount = 0;
  8752. var head = qrCode.modules[0][col];
  8753. for (var row = 0; row < moduleCount; row++) {
  8754. var current = qrCode.modules[row][col];
  8755. //level 3 评价
  8756. if (row < moduleCount - 6) {
  8757. if (current && !qrCode.modules[row + 1][col] && qrCode.modules[row + 2][col] && qrCode.modules[row + 3][col] && qrCode.modules[row + 4][col] && !qrCode.modules[row + 5][col] && qrCode.modules[row + 6][col]) {
  8758. if (row < moduleCount - 10) {
  8759. if (qrCode.modules[row + 7][col] && qrCode.modules[row + 8][col] && qrCode.modules[row + 9][col] && qrCode.modules[row + 10][col]) {
  8760. lostPoint += 40;
  8761. }
  8762. } else if (row > 3) {
  8763. if (qrCode.modules[row - 1][col] && qrCode.modules[row - 2][col] && qrCode.modules[row - 3][col] && qrCode.modules[row - 4][col]) {
  8764. lostPoint += 40;
  8765. }
  8766. }
  8767. }
  8768. }
  8769. //level 1 评价
  8770. if (head ^ current) {
  8771. sameCount++;
  8772. } else {
  8773. head = current;
  8774. if (sameCount >= 5) {
  8775. lostPoint += 3 + sameCount - 5;
  8776. }
  8777. sameCount = 1;
  8778. }
  8779. }
  8780. }
  8781. // LEVEL4
  8782. var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
  8783. lostPoint += ratio * 10;
  8784. return lostPoint;
  8785. }
  8786. };
  8787. //---------------------------------------------------------------------
  8788. // QRMath使用的数学工具
  8789. //---------------------------------------------------------------------
  8790. var QRMath = {
  8791. /*
  8792. 将n转化为a^m
  8793. */
  8794. glog: function(n) {
  8795. if (n < 1) {
  8796. throw new Error("glog(" + n + ")");
  8797. }
  8798. return QRMath.LOG_TABLE[n];
  8799. },
  8800. /*
  8801. 将a^m转化为n
  8802. */
  8803. gexp: function(n) {
  8804. while (n < 0) {
  8805. n += 255;
  8806. }
  8807. while (n >= 256) {
  8808. n -= 255;
  8809. }
  8810. return QRMath.EXP_TABLE[n];
  8811. },
  8812. EXP_TABLE: new Array(256),
  8813. LOG_TABLE: new Array(256)
  8814. };
  8815. for (var i = 0; i < 8; i++) {
  8816. QRMath.EXP_TABLE[i] = 1 << i;
  8817. }
  8818. for (var i = 8; i < 256; i++) {
  8819. QRMath.EXP_TABLE[i] = QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
  8820. }
  8821. for (var i = 0; i < 255; i++) {
  8822. QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
  8823. }
  8824. //---------------------------------------------------------------------
  8825. // QRPolynomial 多项式
  8826. //---------------------------------------------------------------------
  8827. /**
  8828. * 多项式类
  8829. * @param {Array} num 系数
  8830. * @param {num} shift a^shift
  8831. */
  8832. function QRPolynomial(num, shift) {
  8833. if (num.length == undefined) {
  8834. throw new Error(num.length + "/" + shift);
  8835. }
  8836. var offset = 0;
  8837. while (offset < num.length && num[offset] == 0) {
  8838. offset++;
  8839. }
  8840. this.num = new Array(num.length - offset + shift);
  8841. for (var i = 0; i < num.length - offset; i++) {
  8842. this.num[i] = num[i + offset];
  8843. }
  8844. }
  8845. QRPolynomial.prototype = {
  8846. get: function(index) {
  8847. return this.num[index];
  8848. },
  8849. getLength: function() {
  8850. return this.num.length;
  8851. },
  8852. /**
  8853. * 多项式乘法
  8854. * @param {QRPolynomial} e 被乘多项式
  8855. * @return {[type]} [description]
  8856. */
  8857. multiply: function(e) {
  8858. var num = new Array(this.getLength() + e.getLength() - 1);
  8859. for (var i = 0; i < this.getLength(); i++) {
  8860. for (var j = 0; j < e.getLength(); j++) {
  8861. num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
  8862. }
  8863. }
  8864. return new QRPolynomial(num, 0);
  8865. },
  8866. /**
  8867. * 多项式模运算
  8868. * @param {QRPolynomial} e 模多项式
  8869. * @return {}
  8870. */
  8871. mod: function(e) {
  8872. var tl = this.getLength(), el = e.getLength();
  8873. if (tl - el < 0) {
  8874. return this;
  8875. }
  8876. var num = new Array(tl);
  8877. for (var i = 0; i < tl; i++) {
  8878. num[i] = this.get(i);
  8879. }
  8880. while (num.length >= el) {
  8881. var ratio = QRMath.glog(num[0]) - QRMath.glog(e.get(0));
  8882. for (var i = 0; i < e.getLength(); i++) {
  8883. num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
  8884. }
  8885. while (num[0] == 0) {
  8886. num.shift();
  8887. }
  8888. }
  8889. return new QRPolynomial(num, 0);
  8890. }
  8891. };
  8892. //---------------------------------------------------------------------
  8893. // RS_BLOCK_TABLE
  8894. //---------------------------------------------------------------------
  8895. /*
  8896. 二维码各个版本信息[块数, 每块中的数据块数, 每块中的信息块数]
  8897. */
  8898. RS_BLOCK_TABLE = [ // L
  8899. // M
  8900. // Q
  8901. // H
  8902. // 1
  8903. [ 1, 26, 19 ], [ 1, 26, 16 ], [ 1, 26, 13 ], [ 1, 26, 9 ], // 2
  8904. [ 1, 44, 34 ], [ 1, 44, 28 ], [ 1, 44, 22 ], [ 1, 44, 16 ], // 3
  8905. [ 1, 70, 55 ], [ 1, 70, 44 ], [ 2, 35, 17 ], [ 2, 35, 13 ], // 4
  8906. [ 1, 100, 80 ], [ 2, 50, 32 ], [ 2, 50, 24 ], [ 4, 25, 9 ], // 5
  8907. [ 1, 134, 108 ], [ 2, 67, 43 ], [ 2, 33, 15, 2, 34, 16 ], [ 2, 33, 11, 2, 34, 12 ], // 6
  8908. [ 2, 86, 68 ], [ 4, 43, 27 ], [ 4, 43, 19 ], [ 4, 43, 15 ], // 7
  8909. [ 2, 98, 78 ], [ 4, 49, 31 ], [ 2, 32, 14, 4, 33, 15 ], [ 4, 39, 13, 1, 40, 14 ], // 8
  8910. [ 2, 121, 97 ], [ 2, 60, 38, 2, 61, 39 ], [ 4, 40, 18, 2, 41, 19 ], [ 4, 40, 14, 2, 41, 15 ], // 9
  8911. [ 2, 146, 116 ], [ 3, 58, 36, 2, 59, 37 ], [ 4, 36, 16, 4, 37, 17 ], [ 4, 36, 12, 4, 37, 13 ], // 10
  8912. [ 2, 86, 68, 2, 87, 69 ], [ 4, 69, 43, 1, 70, 44 ], [ 6, 43, 19, 2, 44, 20 ], [ 6, 43, 15, 2, 44, 16 ], // 11
  8913. [ 4, 101, 81 ], [ 1, 80, 50, 4, 81, 51 ], [ 4, 50, 22, 4, 51, 23 ], [ 3, 36, 12, 8, 37, 13 ], // 12
  8914. [ 2, 116, 92, 2, 117, 93 ], [ 6, 58, 36, 2, 59, 37 ], [ 4, 46, 20, 6, 47, 21 ], [ 7, 42, 14, 4, 43, 15 ], // 13
  8915. [ 4, 133, 107 ], [ 8, 59, 37, 1, 60, 38 ], [ 8, 44, 20, 4, 45, 21 ], [ 12, 33, 11, 4, 34, 12 ], // 14
  8916. [ 3, 145, 115, 1, 146, 116 ], [ 4, 64, 40, 5, 65, 41 ], [ 11, 36, 16, 5, 37, 17 ], [ 11, 36, 12, 5, 37, 13 ], // 15
  8917. [ 5, 109, 87, 1, 110, 88 ], [ 5, 65, 41, 5, 66, 42 ], [ 5, 54, 24, 7, 55, 25 ], [ 11, 36, 12 ], // 16
  8918. [ 5, 122, 98, 1, 123, 99 ], [ 7, 73, 45, 3, 74, 46 ], [ 15, 43, 19, 2, 44, 20 ], [ 3, 45, 15, 13, 46, 16 ], // 17
  8919. [ 1, 135, 107, 5, 136, 108 ], [ 10, 74, 46, 1, 75, 47 ], [ 1, 50, 22, 15, 51, 23 ], [ 2, 42, 14, 17, 43, 15 ], // 18
  8920. [ 5, 150, 120, 1, 151, 121 ], [ 9, 69, 43, 4, 70, 44 ], [ 17, 50, 22, 1, 51, 23 ], [ 2, 42, 14, 19, 43, 15 ], // 19
  8921. [ 3, 141, 113, 4, 142, 114 ], [ 3, 70, 44, 11, 71, 45 ], [ 17, 47, 21, 4, 48, 22 ], [ 9, 39, 13, 16, 40, 14 ], // 20
  8922. [ 3, 135, 107, 5, 136, 108 ], [ 3, 67, 41, 13, 68, 42 ], [ 15, 54, 24, 5, 55, 25 ], [ 15, 43, 15, 10, 44, 16 ], // 21
  8923. [ 4, 144, 116, 4, 145, 117 ], [ 17, 68, 42 ], [ 17, 50, 22, 6, 51, 23 ], [ 19, 46, 16, 6, 47, 17 ], // 22
  8924. [ 2, 139, 111, 7, 140, 112 ], [ 17, 74, 46 ], [ 7, 54, 24, 16, 55, 25 ], [ 34, 37, 13 ], // 23
  8925. [ 4, 151, 121, 5, 152, 122 ], [ 4, 75, 47, 14, 76, 48 ], [ 11, 54, 24, 14, 55, 25 ], [ 16, 45, 15, 14, 46, 16 ], // 24
  8926. [ 6, 147, 117, 4, 148, 118 ], [ 6, 73, 45, 14, 74, 46 ], [ 11, 54, 24, 16, 55, 25 ], [ 30, 46, 16, 2, 47, 17 ], // 25
  8927. [ 8, 132, 106, 4, 133, 107 ], [ 8, 75, 47, 13, 76, 48 ], [ 7, 54, 24, 22, 55, 25 ], [ 22, 45, 15, 13, 46, 16 ], // 26
  8928. [ 10, 142, 114, 2, 143, 115 ], [ 19, 74, 46, 4, 75, 47 ], [ 28, 50, 22, 6, 51, 23 ], [ 33, 46, 16, 4, 47, 17 ], // 27
  8929. [ 8, 152, 122, 4, 153, 123 ], [ 22, 73, 45, 3, 74, 46 ], [ 8, 53, 23, 26, 54, 24 ], [ 12, 45, 15, 28, 46, 16 ], // 28
  8930. [ 3, 147, 117, 10, 148, 118 ], [ 3, 73, 45, 23, 74, 46 ], [ 4, 54, 24, 31, 55, 25 ], [ 11, 45, 15, 31, 46, 16 ], // 29
  8931. [ 7, 146, 116, 7, 147, 117 ], [ 21, 73, 45, 7, 74, 46 ], [ 1, 53, 23, 37, 54, 24 ], [ 19, 45, 15, 26, 46, 16 ], // 30
  8932. [ 5, 145, 115, 10, 146, 116 ], [ 19, 75, 47, 10, 76, 48 ], [ 15, 54, 24, 25, 55, 25 ], [ 23, 45, 15, 25, 46, 16 ], // 31
  8933. [ 13, 145, 115, 3, 146, 116 ], [ 2, 74, 46, 29, 75, 47 ], [ 42, 54, 24, 1, 55, 25 ], [ 23, 45, 15, 28, 46, 16 ], // 32
  8934. [ 17, 145, 115 ], [ 10, 74, 46, 23, 75, 47 ], [ 10, 54, 24, 35, 55, 25 ], [ 19, 45, 15, 35, 46, 16 ], // 33
  8935. [ 17, 145, 115, 1, 146, 116 ], [ 14, 74, 46, 21, 75, 47 ], [ 29, 54, 24, 19, 55, 25 ], [ 11, 45, 15, 46, 46, 16 ], // 34
  8936. [ 13, 145, 115, 6, 146, 116 ], [ 14, 74, 46, 23, 75, 47 ], [ 44, 54, 24, 7, 55, 25 ], [ 59, 46, 16, 1, 47, 17 ], // 35
  8937. [ 12, 151, 121, 7, 152, 122 ], [ 12, 75, 47, 26, 76, 48 ], [ 39, 54, 24, 14, 55, 25 ], [ 22, 45, 15, 41, 46, 16 ], // 36
  8938. [ 6, 151, 121, 14, 152, 122 ], [ 6, 75, 47, 34, 76, 48 ], [ 46, 54, 24, 10, 55, 25 ], [ 2, 45, 15, 64, 46, 16 ], // 37
  8939. [ 17, 152, 122, 4, 153, 123 ], [ 29, 74, 46, 14, 75, 47 ], [ 49, 54, 24, 10, 55, 25 ], [ 24, 45, 15, 46, 46, 16 ], // 38
  8940. [ 4, 152, 122, 18, 153, 123 ], [ 13, 74, 46, 32, 75, 47 ], [ 48, 54, 24, 14, 55, 25 ], [ 42, 45, 15, 32, 46, 16 ], // 39
  8941. [ 20, 147, 117, 4, 148, 118 ], [ 40, 75, 47, 7, 76, 48 ], [ 43, 54, 24, 22, 55, 25 ], [ 10, 45, 15, 67, 46, 16 ], // 40
  8942. [ 19, 148, 118, 6, 149, 119 ], [ 18, 75, 47, 31, 76, 48 ], [ 34, 54, 24, 34, 55, 25 ], [ 20, 45, 15, 61, 46, 16 ] ];
  8943. /**
  8944. * 根据数据获取对应版本
  8945. * @return {[type]} [description]
  8946. */
  8947. QRCodeAlg.prototype.getRightType = function() {
  8948. for (var typeNumber = 1; typeNumber < 41; typeNumber++) {
  8949. var rsBlock = RS_BLOCK_TABLE[(typeNumber - 1) * 4 + this.errorCorrectLevel];
  8950. if (rsBlock == undefined) {
  8951. throw new Error("bad rs block @ typeNumber:" + typeNumber + "/errorCorrectLevel:" + this.errorCorrectLevel);
  8952. }
  8953. var length = rsBlock.length / 3;
  8954. var totalDataCount = 0;
  8955. for (var i = 0; i < length; i++) {
  8956. var count = rsBlock[i * 3 + 0];
  8957. var dataCount = rsBlock[i * 3 + 2];
  8958. totalDataCount += dataCount * count;
  8959. }
  8960. var lengthBytes = typeNumber > 9 ? 2 : 1;
  8961. if (this.utf8bytes.length + lengthBytes < totalDataCount || typeNumber == 40) {
  8962. this.typeNumber = typeNumber;
  8963. this.rsBlock = rsBlock;
  8964. this.totalDataCount = totalDataCount;
  8965. break;
  8966. }
  8967. }
  8968. };
  8969. //---------------------------------------------------------------------
  8970. // QRBitBuffer
  8971. //---------------------------------------------------------------------
  8972. function QRBitBuffer() {
  8973. this.buffer = new Array();
  8974. this.length = 0;
  8975. }
  8976. QRBitBuffer.prototype = {
  8977. get: function(index) {
  8978. var bufIndex = Math.floor(index / 8);
  8979. return this.buffer[bufIndex] >>> 7 - index % 8 & 1;
  8980. },
  8981. put: function(num, length) {
  8982. for (var i = 0; i < length; i++) {
  8983. this.putBit(num >>> length - i - 1 & 1);
  8984. }
  8985. },
  8986. putBit: function(bit) {
  8987. var bufIndex = Math.floor(this.length / 8);
  8988. if (this.buffer.length <= bufIndex) {
  8989. this.buffer.push(0);
  8990. }
  8991. if (bit) {
  8992. this.buffer[bufIndex] |= 128 >>> this.length % 8;
  8993. }
  8994. this.length++;
  8995. }
  8996. };
  8997. });
  8998. define("zepto.flexslider", [ "core", "zepto.extend.fx", "zepto.extend.data", "zepto.extend.selector", "util.fastclick" ], function(require, exports, module) {
  8999. var $ = window.Zepto;
  9000. require("core");
  9001. require("zepto.extend.data");
  9002. // Zepto $.data patch
  9003. $.data = function(elem, key, value) {
  9004. return $(elem).data(key, value);
  9005. };
  9006. //scrollLeft
  9007. [ "Left", "Top" ].forEach(function(name, i) {
  9008. var method = "scroll" + name;
  9009. function isWindow(obj) {
  9010. return obj && typeof obj === "object" && "setInterval" in obj;
  9011. }
  9012. function getWindow(elem) {
  9013. return isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
  9014. }
  9015. $.fn[method] = function(val) {
  9016. var elem, win;
  9017. if (val === undefined) {
  9018. elem = this[0];
  9019. if (!elem) {
  9020. return null;
  9021. }
  9022. win = getWindow(elem);
  9023. // Return the scroll offset
  9024. return win ? "pageXOffset" in win ? win[i ? "pageYOffset" : "pageXOffset"] : win.document.documentElement[method] || win.document.body[method] : elem[method];
  9025. }
  9026. // Set the scroll offset
  9027. this.each(function() {
  9028. win = getWindow(this);
  9029. if (win) {
  9030. var xCoord = !i ? val : $(win).scrollLeft();
  9031. var yCoord = i ? val : $(win).scrollTop();
  9032. win.scrollTo(xCoord, yCoord);
  9033. } else {
  9034. this[method] = val;
  9035. }
  9036. });
  9037. };
  9038. });
  9039. // Create outerHeight and outerWidth methods
  9040. [ "width", "height" ].forEach(function(dimension) {
  9041. var offset, Dimension = dimension.replace(/./, function(m) {
  9042. return m[0].toUpperCase();
  9043. });
  9044. $.fn["outer" + Dimension] = function(margin) {
  9045. var elem = this;
  9046. if (elem) {
  9047. var size = elem[dimension]();
  9048. var sides = {
  9049. width: [ "left", "right" ],
  9050. height: [ "top", "bottom" ]
  9051. };
  9052. sides[dimension].forEach(function(side) {
  9053. if (margin) size += parseInt(elem.css("margin-" + side), 10);
  9054. });
  9055. return size;
  9056. } else {
  9057. return null;
  9058. }
  9059. };
  9060. });
  9061. /*
  9062. * Zepto FlexSlider v2.3
  9063. * @desc Porting from jQuery FlexSlider v2.3, Contributing Author: Tyler Smith
  9064. * @license Copyright 2012 WooThemes GPLv2
  9065. */
  9066. //FlexSlider: Object Instance
  9067. $.flexslider = function(el, options) {
  9068. var slider = $(el);
  9069. // making variables public
  9070. slider.vars = $.extend({}, $.flexslider.defaults, options);
  9071. var namespace = slider.vars.namespace, msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, touch = ("ontouchstart" in window || msGesture || window.DocumentTouch && document instanceof DocumentTouch) && slider.vars.touch, // depricating this idea, as devices are being released with both of these events
  9072. //eventType = (touch) ? "touchend" : "click",
  9073. eventType = "click touchend MSPointerUp keyup", watchedEvent = "", watchedEventClearTimer, vertical = slider.vars.direction === "vertical", reverse = slider.vars.reverse, carousel = slider.vars.itemWidth > 0, fade = slider.vars.animation === "fade", asNav = slider.vars.asNavFor !== "", methods = {}, focused = true;
  9074. // Store a reference to the slider object
  9075. $.data(el, "flexslider", slider);
  9076. // Private slider methods
  9077. methods = {
  9078. init: function() {
  9079. slider.animating = false;
  9080. // Get current slide and make sure it is a number
  9081. slider.currentSlide = parseInt(slider.vars.startAt ? slider.vars.startAt : 0, 10);
  9082. if (isNaN(slider.currentSlide)) slider.currentSlide = 0;
  9083. slider.animatingTo = slider.currentSlide;
  9084. slider.atEnd = slider.currentSlide === 0 || slider.currentSlide === slider.last;
  9085. slider.containerSelector = slider.vars.selector.substr(0, slider.vars.selector.search(" "));
  9086. slider.slides = $(slider.vars.selector, slider);
  9087. slider.container = $(slider.containerSelector, slider);
  9088. slider.count = slider.slides.length;
  9089. // SYNC:
  9090. slider.syncExists = $(slider.vars.sync).length > 0;
  9091. // SLIDE:
  9092. if (slider.vars.animation === "slide") slider.vars.animation = "swing";
  9093. slider.prop = vertical ? "top" : "marginLeft";
  9094. slider.args = {};
  9095. // SLIDESHOW:
  9096. slider.manualPause = false;
  9097. slider.stopped = false;
  9098. //PAUSE WHEN INVISIBLE
  9099. slider.started = false;
  9100. slider.startTimeout = null;
  9101. // TOUCH/USECSS:
  9102. slider.transitions = !slider.vars.video && !fade && slider.vars.useCSS && function() {
  9103. var obj = document.createElement("div"), props = [ "perspectiveProperty", "WebkitPerspective", "MozPerspective", "OPerspective", "msPerspective" ];
  9104. for (var i in props) {
  9105. if (obj.style[props[i]] !== undefined) {
  9106. slider.pfx = props[i].replace("Perspective", "").toLowerCase();
  9107. slider.prop = "-" + slider.pfx + "-transform";
  9108. return true;
  9109. }
  9110. }
  9111. return false;
  9112. }();
  9113. slider.ensureAnimationEnd = "";
  9114. // CONTROLSCONTAINER:
  9115. if (slider.vars.controlsContainer !== "") slider.controlsContainer = $(slider.vars.controlsContainer).length > 0 && $(slider.vars.controlsContainer);
  9116. // MANUAL:
  9117. if (slider.vars.manualControls !== "") slider.manualControls = $(slider.vars.manualControls).length > 0 && $(slider.vars.manualControls);
  9118. // RANDOMIZE:
  9119. if (slider.vars.randomize) {
  9120. slider.slides.sort(function() {
  9121. return Math.round(Math.random()) - .5;
  9122. });
  9123. slider.container.empty().append(slider.slides);
  9124. }
  9125. slider.doMath();
  9126. // INIT
  9127. slider.setup("init");
  9128. // CONTROLNAV:
  9129. if (slider.vars.controlNav) methods.controlNav.setup();
  9130. // DIRECTIONNAV:
  9131. if (slider.vars.directionNav) methods.directionNav.setup();
  9132. // KEYBOARD:
  9133. if (slider.vars.keyboard && ($(slider.containerSelector).length === 1 || slider.vars.multipleKeyboard)) {
  9134. $(document).bind("keyup", function(event) {
  9135. var keycode = event.keyCode;
  9136. if (!slider.animating && (keycode === 39 || keycode === 37)) {
  9137. var target = keycode === 39 ? slider.getTarget("next") : keycode === 37 ? slider.getTarget("prev") : false;
  9138. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9139. }
  9140. });
  9141. }
  9142. // MOUSEWHEEL:
  9143. if (slider.vars.mousewheel) {
  9144. slider.bind("mousewheel", function(event, delta, deltaX, deltaY) {
  9145. event.preventDefault();
  9146. var target = delta < 0 ? slider.getTarget("next") : slider.getTarget("prev");
  9147. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9148. });
  9149. }
  9150. // PAUSEPLAY
  9151. if (slider.vars.pausePlay) methods.pausePlay.setup();
  9152. //PAUSE WHEN INVISIBLE
  9153. if (slider.vars.slideshow && slider.vars.pauseInvisible) methods.pauseInvisible.init();
  9154. // SLIDSESHOW
  9155. if (slider.vars.slideshow) {
  9156. if (slider.vars.pauseOnHover) {
  9157. /*slider.hover(function() {
  9158. if (!slider.manualPlay && !slider.manualPause) slider.pause();
  9159. }, function() {
  9160. if (!slider.manualPause && !slider.manualPlay && !slider.stopped) slider.play();
  9161. });*/
  9162. slider.on("mouseover", function() {
  9163. if (!slider.manualPlay && !slider.manualPause) slider.pause();
  9164. });
  9165. slider.on("mouseout", function() {
  9166. if (!slider.manualPause && !slider.manualPlay && !slider.stopped) slider.play();
  9167. });
  9168. }
  9169. // initialize animation
  9170. //If we're visible, or we don't use PageVisibility API
  9171. if (!slider.vars.pauseInvisible || !methods.pauseInvisible.isHidden()) {
  9172. slider.vars.initDelay > 0 ? slider.startTimeout = setTimeout(slider.play, slider.vars.initDelay) : slider.play();
  9173. }
  9174. }
  9175. // ASNAV:
  9176. if (asNav) methods.asNav.setup();
  9177. // TOUCH
  9178. if (touch && slider.vars.touch) methods.touch();
  9179. // FADE&&SMOOTHHEIGHT || SLIDE:
  9180. if (!fade || fade && slider.vars.smoothHeight) $(window).bind("resize orientationchange focus", methods.resize);
  9181. slider.find("img").attr("draggable", "false");
  9182. // API: start() Callback
  9183. setTimeout(function() {
  9184. slider.vars.start(slider);
  9185. }, 200);
  9186. },
  9187. asNav: {
  9188. setup: function() {
  9189. slider.asNav = true;
  9190. slider.animatingTo = Math.floor(slider.currentSlide / slider.move);
  9191. slider.currentItem = slider.currentSlide;
  9192. slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide");
  9193. if (!msGesture) {
  9194. slider.slides.on(eventType, function(e) {
  9195. e.preventDefault();
  9196. var $slide = $(this), target = $slide.index();
  9197. var posFromLeft = $slide.offset().left - $(slider).scrollLeft();
  9198. // Find position of slide relative to left of slider container
  9199. if (posFromLeft <= 0 && $slide.hasClass(namespace + "active-slide")) {
  9200. slider.flexAnimate(slider.getTarget("prev"), true);
  9201. } else if (!$(slider.vars.asNavFor).data("flexslider").animating && !$slide.hasClass(namespace + "active-slide")) {
  9202. slider.direction = slider.currentItem < target ? "next" : "prev";
  9203. slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true);
  9204. }
  9205. });
  9206. } else {
  9207. el._slider = slider;
  9208. slider.slides.each(function() {
  9209. var that = this;
  9210. that._gesture = new MSGesture();
  9211. that._gesture.target = that;
  9212. that.addEventListener("MSPointerDown", function(e) {
  9213. e.preventDefault();
  9214. if (e.currentTarget._gesture) e.currentTarget._gesture.addPointer(e.pointerId);
  9215. }, false);
  9216. that.addEventListener("MSGestureTap", function(e) {
  9217. e.preventDefault();
  9218. var $slide = $(this), target = $slide.index();
  9219. if (!$(slider.vars.asNavFor).data("flexslider").animating && !$slide.hasClass("active")) {
  9220. slider.direction = slider.currentItem < target ? "next" : "prev";
  9221. slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true);
  9222. }
  9223. });
  9224. });
  9225. }
  9226. }
  9227. },
  9228. controlNav: {
  9229. setup: function() {
  9230. if (!slider.manualControls) {
  9231. methods.controlNav.setupPaging();
  9232. } else {
  9233. // MANUALCONTROLS:
  9234. methods.controlNav.setupManual();
  9235. }
  9236. },
  9237. setupPaging: function() {
  9238. var type = slider.vars.controlNav === "thumbnails" ? "control-thumbs" : "control-paging", j = 1, item, slide;
  9239. slider.controlNavScaffold = $('<ol class="' + namespace + "control-nav " + namespace + type + '"></ol>');
  9240. if (slider.pagingCount > 1) {
  9241. for (var i = 0; i < slider.pagingCount; i++) {
  9242. slide = slider.slides.eq(i);
  9243. item = slider.vars.controlNav === "thumbnails" ? '<img src="' + slide.attr("data-thumb") + '"/>' : "<a>" + j + "</a>";
  9244. if ("thumbnails" === slider.vars.controlNav && true === slider.vars.thumbCaptions) {
  9245. var captn = slide.attr("data-thumbcaption");
  9246. if ("" != captn && undefined != captn) item += '<span class="' + namespace + 'caption">' + captn + "</span>";
  9247. }
  9248. //slider.controlNavScaffold.append('<li>' + item + '</li>');
  9249. slider.controlNavScaffold.append("<li>" + item + "<i></i></li>");
  9250. j++;
  9251. }
  9252. }
  9253. // CONTROLSCONTAINER:
  9254. slider.controlsContainer ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
  9255. methods.controlNav.set();
  9256. methods.controlNav.active();
  9257. slider.controlNavScaffold.delegate("a, img", eventType, function(event) {
  9258. event.preventDefault();
  9259. if (watchedEvent === "" || watchedEvent === event.type) {
  9260. var $this = $(this), target = slider.controlNav.index($this);
  9261. if (!$this.hasClass(namespace + "active")) {
  9262. slider.direction = target > slider.currentSlide ? "next" : "prev";
  9263. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9264. }
  9265. }
  9266. // setup flags to prevent event duplication
  9267. if (watchedEvent === "") {
  9268. watchedEvent = event.type;
  9269. }
  9270. methods.setToClearWatchedEvent();
  9271. });
  9272. },
  9273. setupManual: function() {
  9274. slider.controlNav = slider.manualControls;
  9275. methods.controlNav.active();
  9276. slider.controlNav.bind(eventType, function(event) {
  9277. event.preventDefault();
  9278. if (watchedEvent === "" || watchedEvent === event.type) {
  9279. var $this = $(this), target = slider.controlNav.index($this);
  9280. if (!$this.hasClass(namespace + "active")) {
  9281. target > slider.currentSlide ? slider.direction = "next" : slider.direction = "prev";
  9282. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9283. }
  9284. }
  9285. // setup flags to prevent event duplication
  9286. if (watchedEvent === "") {
  9287. watchedEvent = event.type;
  9288. }
  9289. methods.setToClearWatchedEvent();
  9290. });
  9291. },
  9292. set: function() {
  9293. var selector = slider.vars.controlNav === "thumbnails" ? "img" : "a";
  9294. slider.controlNav = $("." + namespace + "control-nav li " + selector, slider.controlsContainer ? slider.controlsContainer : slider);
  9295. },
  9296. active: function() {
  9297. slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active");
  9298. },
  9299. update: function(action, pos) {
  9300. if (slider.pagingCount > 1 && action === "add") {
  9301. slider.controlNavScaffold.append($("<li><a>" + slider.count + "</a></li>"));
  9302. } else if (slider.pagingCount === 1) {
  9303. slider.controlNavScaffold.find("li").remove();
  9304. } else {
  9305. slider.controlNav.eq(pos).closest("li").remove();
  9306. }
  9307. methods.controlNav.set();
  9308. slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length ? slider.update(pos, action) : methods.controlNav.active();
  9309. }
  9310. },
  9311. directionNav: {
  9312. setup: function() {
  9313. var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + slider.vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + slider.vars.nextText + "</a></li></ul>");
  9314. // CONTROLSCONTAINER:
  9315. if (slider.controlsContainer) {
  9316. $(slider.controlsContainer).append(directionNavScaffold);
  9317. slider.directionNav = $("." + namespace + "direction-nav li a", slider.controlsContainer);
  9318. } else {
  9319. slider.append(directionNavScaffold);
  9320. slider.directionNav = $("." + namespace + "direction-nav li a", slider);
  9321. }
  9322. methods.directionNav.update();
  9323. slider.directionNav.bind(eventType, function(event) {
  9324. event.preventDefault();
  9325. var target;
  9326. if (watchedEvent === "" || watchedEvent === event.type) {
  9327. target = $(this).hasClass(namespace + "next") ? slider.getTarget("next") : slider.getTarget("prev");
  9328. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9329. }
  9330. // setup flags to prevent event duplication
  9331. if (watchedEvent === "") {
  9332. watchedEvent = event.type;
  9333. }
  9334. methods.setToClearWatchedEvent();
  9335. });
  9336. },
  9337. update: function() {
  9338. var disabledClass = namespace + "disabled";
  9339. if (slider.pagingCount === 1) {
  9340. slider.directionNav.addClass(disabledClass).attr("tabindex", "-1");
  9341. } else if (!slider.vars.animationLoop) {
  9342. if (slider.animatingTo === 0) {
  9343. slider.directionNav.removeClass(disabledClass).filter("." + namespace + "prev").addClass(disabledClass).attr("tabindex", "-1");
  9344. } else if (slider.animatingTo === slider.last) {
  9345. slider.directionNav.removeClass(disabledClass).filter("." + namespace + "next").addClass(disabledClass).attr("tabindex", "-1");
  9346. } else {
  9347. slider.directionNav.removeClass(disabledClass).removeAttr("tabindex");
  9348. }
  9349. } else {
  9350. slider.directionNav.removeClass(disabledClass).removeAttr("tabindex");
  9351. }
  9352. }
  9353. },
  9354. pausePlay: {
  9355. setup: function() {
  9356. var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a></a></div>');
  9357. // CONTROLSCONTAINER:
  9358. if (slider.controlsContainer) {
  9359. slider.controlsContainer.append(pausePlayScaffold);
  9360. slider.pausePlay = $("." + namespace + "pauseplay a", slider.controlsContainer);
  9361. } else {
  9362. slider.append(pausePlayScaffold);
  9363. slider.pausePlay = $("." + namespace + "pauseplay a", slider);
  9364. }
  9365. methods.pausePlay.update(slider.vars.slideshow ? namespace + "pause" : namespace + "play");
  9366. slider.pausePlay.bind(eventType, function(event) {
  9367. event.preventDefault();
  9368. if (watchedEvent === "" || watchedEvent === event.type) {
  9369. if ($(this).hasClass(namespace + "pause")) {
  9370. slider.manualPause = true;
  9371. slider.manualPlay = false;
  9372. slider.pause();
  9373. } else {
  9374. slider.manualPause = false;
  9375. slider.manualPlay = true;
  9376. slider.play();
  9377. }
  9378. }
  9379. // setup flags to prevent event duplication
  9380. if (watchedEvent === "") {
  9381. watchedEvent = event.type;
  9382. }
  9383. methods.setToClearWatchedEvent();
  9384. });
  9385. },
  9386. update: function(state) {
  9387. state === "play" ? slider.pausePlay.removeClass(namespace + "pause").addClass(namespace + "play").html(slider.vars.playText) : slider.pausePlay.removeClass(namespace + "play").addClass(namespace + "pause").html(slider.vars.pauseText);
  9388. }
  9389. },
  9390. touch: function() {
  9391. var startX, startY, offset, cwidth, dx, startT, scrolling = false, localX = 0, localY = 0, accDx = 0;
  9392. if (!msGesture) {
  9393. el.addEventListener("touchstart", onTouchStart, false);
  9394. function onTouchStart(e) {
  9395. if (slider.animating) {
  9396. e.preventDefault();
  9397. } else if (window.navigator.msPointerEnabled || e.touches.length === 1) {
  9398. slider.pause();
  9399. // CAROUSEL:
  9400. cwidth = vertical ? slider.h : slider.w;
  9401. startT = Number(new Date());
  9402. // CAROUSEL:
  9403. // Local vars for X and Y points.
  9404. localX = e.touches[0].pageX;
  9405. localY = e.touches[0].pageY;
  9406. offset = carousel && reverse && slider.animatingTo === slider.last ? 0 : carousel && reverse ? slider.limit - (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo : carousel && slider.currentSlide === slider.last ? slider.limit : carousel ? (slider.itemW + slider.vars.itemMargin) * slider.move * slider.currentSlide : reverse ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
  9407. startX = vertical ? localY : localX;
  9408. startY = vertical ? localX : localY;
  9409. el.addEventListener("touchmove", onTouchMove, false);
  9410. el.addEventListener("touchend", onTouchEnd, false);
  9411. }
  9412. }
  9413. function onTouchMove(e) {
  9414. // Local vars for X and Y points.
  9415. localX = e.touches[0].pageX;
  9416. localY = e.touches[0].pageY;
  9417. dx = vertical ? startX - localY : startX - localX;
  9418. scrolling = vertical ? Math.abs(dx) < Math.abs(localX - startY) : Math.abs(dx) < Math.abs(localY - startY);
  9419. var fxms = 500;
  9420. if (!scrolling || Number(new Date()) - startT > fxms) {
  9421. e.preventDefault();
  9422. if (!fade && slider.transitions) {
  9423. if (!slider.vars.animationLoop) {
  9424. dx = dx / (slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0 ? Math.abs(dx) / cwidth + 2 : 1);
  9425. }
  9426. slider.setProps(offset + dx, "setTouch");
  9427. }
  9428. }
  9429. }
  9430. function onTouchEnd(e) {
  9431. // finish the touch by undoing the touch session
  9432. el.removeEventListener("touchmove", onTouchMove, false);
  9433. if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
  9434. var updateDx = reverse ? -dx : dx, target = updateDx > 0 ? slider.getTarget("next") : slider.getTarget("prev");
  9435. if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth / 2)) {
  9436. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9437. } else {
  9438. if (!fade) slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true);
  9439. }
  9440. }
  9441. el.removeEventListener("touchend", onTouchEnd, false);
  9442. startX = null;
  9443. startY = null;
  9444. dx = null;
  9445. offset = null;
  9446. }
  9447. } else {
  9448. el.style.msTouchAction = "none";
  9449. el._gesture = new MSGesture();
  9450. el._gesture.target = el;
  9451. el.addEventListener("MSPointerDown", onMSPointerDown, false);
  9452. el._slider = slider;
  9453. el.addEventListener("MSGestureChange", onMSGestureChange, false);
  9454. el.addEventListener("MSGestureEnd", onMSGestureEnd, false);
  9455. function onMSPointerDown(e) {
  9456. e.stopPropagation();
  9457. if (slider.animating) {
  9458. e.preventDefault();
  9459. } else {
  9460. slider.pause();
  9461. el._gesture.addPointer(e.pointerId);
  9462. accDx = 0;
  9463. cwidth = vertical ? slider.h : slider.w;
  9464. startT = Number(new Date());
  9465. // CAROUSEL:
  9466. offset = carousel && reverse && slider.animatingTo === slider.last ? 0 : carousel && reverse ? slider.limit - (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo : carousel && slider.currentSlide === slider.last ? slider.limit : carousel ? (slider.itemW + slider.vars.itemMargin) * slider.move * slider.currentSlide : reverse ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
  9467. }
  9468. }
  9469. function onMSGestureChange(e) {
  9470. e.stopPropagation();
  9471. var slider = e.target._slider;
  9472. if (!slider) {
  9473. return;
  9474. }
  9475. var transX = -e.translationX, transY = -e.translationY;
  9476. //Accumulate translations.
  9477. accDx = accDx + (vertical ? transY : transX);
  9478. dx = accDx;
  9479. scrolling = vertical ? Math.abs(accDx) < Math.abs(-transX) : Math.abs(accDx) < Math.abs(-transY);
  9480. if (e.detail === e.MSGESTURE_FLAG_INERTIA) {
  9481. setImmediate(function() {
  9482. el._gesture.stop();
  9483. });
  9484. return;
  9485. }
  9486. if (!scrolling || Number(new Date()) - startT > 500) {
  9487. e.preventDefault();
  9488. if (!fade && slider.transitions) {
  9489. if (!slider.vars.animationLoop) {
  9490. dx = accDx / (slider.currentSlide === 0 && accDx < 0 || slider.currentSlide === slider.last && accDx > 0 ? Math.abs(accDx) / cwidth + 2 : 1);
  9491. }
  9492. slider.setProps(offset + dx, "setTouch");
  9493. }
  9494. }
  9495. }
  9496. function onMSGestureEnd(e) {
  9497. e.stopPropagation();
  9498. var slider = e.target._slider;
  9499. if (!slider) {
  9500. return;
  9501. }
  9502. if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
  9503. var updateDx = reverse ? -dx : dx, target = updateDx > 0 ? slider.getTarget("next") : slider.getTarget("prev");
  9504. if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth / 2)) {
  9505. slider.flexAnimate(target, slider.vars.pauseOnAction);
  9506. } else {
  9507. if (!fade) slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true);
  9508. }
  9509. }
  9510. startX = null;
  9511. startY = null;
  9512. dx = null;
  9513. offset = null;
  9514. accDx = 0;
  9515. }
  9516. }
  9517. },
  9518. resize: function() {
  9519. if (!slider.animating && slider.is(":visible")) {
  9520. if (!carousel) slider.doMath();
  9521. if (fade) {
  9522. // SMOOTH HEIGHT:
  9523. methods.smoothHeight();
  9524. } else if (carousel) {
  9525. //CAROUSEL:
  9526. slider.slides.width(slider.computedW);
  9527. slider.update(slider.pagingCount);
  9528. slider.setProps();
  9529. } else if (vertical) {
  9530. //VERTICAL:
  9531. slider.viewport.height(slider.h);
  9532. slider.setProps(slider.h, "setTotal");
  9533. } else {
  9534. // SMOOTH HEIGHT:
  9535. if (slider.vars.smoothHeight) methods.smoothHeight();
  9536. slider.newSlides.width(slider.computedW);
  9537. slider.setProps(slider.computedW, "setTotal");
  9538. }
  9539. }
  9540. },
  9541. smoothHeight: function(dur) {
  9542. if (!vertical || fade) {
  9543. var $obj = fade ? slider : slider.viewport;
  9544. dur ? $obj.animate({
  9545. height: slider.slides.eq(slider.animatingTo).height()
  9546. }, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
  9547. }
  9548. },
  9549. sync: function(action) {
  9550. var $obj = $(slider.vars.sync).data("flexslider"), target = slider.animatingTo;
  9551. switch (action) {
  9552. case "animate":
  9553. $obj.flexAnimate(target, slider.vars.pauseOnAction, false, true);
  9554. break;
  9555. case "play":
  9556. if (!$obj.playing && !$obj.asNav) {
  9557. $obj.play();
  9558. }
  9559. break;
  9560. case "pause":
  9561. $obj.pause();
  9562. break;
  9563. }
  9564. },
  9565. uniqueID: function($clone) {
  9566. // Append _clone to current level and children elements with id attributes
  9567. $clone.filter("[id]").add($clone.find("[id]")).each(function() {
  9568. var $this = $(this);
  9569. $this.attr("id", $this.attr("id") + "_clone");
  9570. });
  9571. return $clone;
  9572. },
  9573. pauseInvisible: {
  9574. visProp: null,
  9575. init: function() {
  9576. var prefixes = [ "webkit", "moz", "ms", "o" ];
  9577. if ("hidden" in document) return "hidden";
  9578. for (var i = 0; i < prefixes.length; i++) {
  9579. if (prefixes[i] + "Hidden" in document) methods.pauseInvisible.visProp = prefixes[i] + "Hidden";
  9580. }
  9581. if (methods.pauseInvisible.visProp) {
  9582. var evtname = methods.pauseInvisible.visProp.replace(/[H|h]idden/, "") + "visibilitychange";
  9583. document.addEventListener(evtname, function() {
  9584. if (methods.pauseInvisible.isHidden()) {
  9585. if (slider.startTimeout) clearTimeout(slider.startTimeout); else slider.pause();
  9586. } else {
  9587. if (slider.started) slider.play(); else slider.vars.initDelay > 0 ? setTimeout(slider.play, slider.vars.initDelay) : slider.play();
  9588. }
  9589. });
  9590. }
  9591. },
  9592. isHidden: function() {
  9593. return document[methods.pauseInvisible.visProp] || false;
  9594. }
  9595. },
  9596. setToClearWatchedEvent: function() {
  9597. clearTimeout(watchedEventClearTimer);
  9598. watchedEventClearTimer = setTimeout(function() {
  9599. watchedEvent = "";
  9600. }, 3e3);
  9601. }
  9602. };
  9603. // public methods
  9604. slider.flexAnimate = function(target, pause, override, withSync, fromNav) {
  9605. if (!slider.vars.animationLoop && target !== slider.currentSlide) {
  9606. slider.direction = target > slider.currentSlide ? "next" : "prev";
  9607. }
  9608. if (asNav && slider.pagingCount === 1) slider.direction = slider.currentItem < target ? "next" : "prev";
  9609. if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) {
  9610. if (asNav && withSync) {
  9611. var master = $(slider.vars.asNavFor).data("flexslider");
  9612. slider.atEnd = target === 0 || target === slider.count - 1;
  9613. master.flexAnimate(target, true, false, true, fromNav);
  9614. slider.direction = slider.currentItem < target ? "next" : "prev";
  9615. master.direction = slider.direction;
  9616. if (Math.ceil((target + 1) / slider.visible) - 1 !== slider.currentSlide && target !== 0) {
  9617. slider.currentItem = target;
  9618. slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
  9619. target = Math.floor(target / slider.visible);
  9620. } else {
  9621. slider.currentItem = target;
  9622. slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
  9623. return false;
  9624. }
  9625. }
  9626. slider.animating = true;
  9627. slider.animatingTo = target;
  9628. // SLIDESHOW:
  9629. if (pause) slider.pause();
  9630. // API: before() animation Callback
  9631. slider.vars.before(slider);
  9632. // SYNC:
  9633. if (slider.syncExists && !fromNav) methods.sync("animate");
  9634. // CONTROLNAV
  9635. if (slider.vars.controlNav) methods.controlNav.active();
  9636. // !CAROUSEL:
  9637. // CANDIDATE: slide active class (for add/remove slide)
  9638. if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
  9639. // INFINITE LOOP:
  9640. // CANDIDATE: atEnd
  9641. slider.atEnd = target === 0 || target === slider.last;
  9642. // DIRECTIONNAV:
  9643. if (slider.vars.directionNav) methods.directionNav.update();
  9644. if (target === slider.last) {
  9645. // API: end() of cycle Callback
  9646. slider.vars.end(slider);
  9647. // SLIDESHOW && !INFINITE LOOP:
  9648. if (!slider.vars.animationLoop) slider.pause();
  9649. }
  9650. // SLIDE:
  9651. if (!fade) {
  9652. var dimension = vertical ? slider.slides.filter(":first").height() : slider.computedW, margin, slideString, calcNext;
  9653. // INFINITE LOOP / REVERSE:
  9654. if (carousel) {
  9655. //margin = (slider.vars.itemWidth > slider.w) ? slider.vars.itemMargin * 2 : slider.vars.itemMargin;
  9656. margin = slider.vars.itemMargin;
  9657. calcNext = (slider.itemW + margin) * slider.move * slider.animatingTo;
  9658. slideString = calcNext > slider.limit && slider.visible !== 1 ? slider.limit : calcNext;
  9659. } else if (slider.currentSlide === 0 && target === slider.count - 1 && slider.vars.animationLoop && slider.direction !== "next") {
  9660. slideString = reverse ? (slider.count + slider.cloneOffset) * dimension : 0;
  9661. } else if (slider.currentSlide === slider.last && target === 0 && slider.vars.animationLoop && slider.direction !== "prev") {
  9662. slideString = reverse ? 0 : (slider.count + 1) * dimension;
  9663. } else {
  9664. slideString = reverse ? (slider.count - 1 - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension;
  9665. }
  9666. slider.setProps(slideString, "", slider.vars.animationSpeed);
  9667. if (slider.transitions) {
  9668. if (!slider.vars.animationLoop || !slider.atEnd) {
  9669. slider.animating = false;
  9670. slider.currentSlide = slider.animatingTo;
  9671. }
  9672. // Unbind previous transitionEnd events and re-bind new transitionEnd event
  9673. slider.container.unbind("webkitTransitionEnd transitionend");
  9674. slider.container.bind("webkitTransitionEnd transitionend", function() {
  9675. clearTimeout(slider.ensureAnimationEnd);
  9676. slider.wrapup(dimension);
  9677. });
  9678. // Insurance for the ever-so-fickle transitionEnd event
  9679. clearTimeout(slider.ensureAnimationEnd);
  9680. slider.ensureAnimationEnd = setTimeout(function() {
  9681. slider.wrapup(dimension);
  9682. }, slider.vars.animationSpeed + 100);
  9683. } else {
  9684. slider.container.animate(slider.args, slider.vars.animationSpeed, slider.vars.easing, function() {
  9685. slider.wrapup(dimension);
  9686. });
  9687. }
  9688. } else {
  9689. // FADE:
  9690. if (!touch) {
  9691. //slider.slides.eq(slider.currentSlide).fadeOut(slider.vars.animationSpeed, slider.vars.easing);
  9692. //slider.slides.eq(target).fadeIn(slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
  9693. slider.slides.eq(slider.currentSlide).css({
  9694. zIndex: 1
  9695. }).animate({
  9696. opacity: 0
  9697. }, slider.vars.animationSpeed, slider.vars.easing);
  9698. slider.slides.eq(target).css({
  9699. zIndex: 2
  9700. }).animate({
  9701. opacity: 1
  9702. }, slider.vars.animationSpeed, slider.vars.easing, slider.wrapup);
  9703. } else {
  9704. slider.slides.eq(slider.currentSlide).css({
  9705. opacity: 0,
  9706. zIndex: 1
  9707. });
  9708. slider.slides.eq(target).css({
  9709. opacity: 1,
  9710. zIndex: 2
  9711. });
  9712. slider.wrapup(dimension);
  9713. }
  9714. }
  9715. // SMOOTH HEIGHT:
  9716. if (slider.vars.smoothHeight) methods.smoothHeight(slider.vars.animationSpeed);
  9717. }
  9718. };
  9719. slider.wrapup = function(dimension) {
  9720. // SLIDE:
  9721. if (!fade && !carousel) {
  9722. if (slider.currentSlide === 0 && slider.animatingTo === slider.last && slider.vars.animationLoop) {
  9723. slider.setProps(dimension, "jumpEnd");
  9724. } else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && slider.vars.animationLoop) {
  9725. slider.setProps(dimension, "jumpStart");
  9726. }
  9727. }
  9728. slider.animating = false;
  9729. slider.currentSlide = slider.animatingTo;
  9730. // API: after() animation Callback
  9731. slider.vars.after(slider);
  9732. };
  9733. // SLIDESHOW:
  9734. slider.animateSlides = function() {
  9735. if (!slider.animating && focused) slider.flexAnimate(slider.getTarget("next"));
  9736. };
  9737. // SLIDESHOW:
  9738. slider.pause = function() {
  9739. clearInterval(slider.animatedSlides);
  9740. slider.animatedSlides = null;
  9741. slider.playing = false;
  9742. // PAUSEPLAY:
  9743. if (slider.vars.pausePlay) methods.pausePlay.update("play");
  9744. // SYNC:
  9745. if (slider.syncExists) methods.sync("pause");
  9746. };
  9747. // SLIDESHOW:
  9748. slider.play = function() {
  9749. if (slider.playing) clearInterval(slider.animatedSlides);
  9750. slider.animatedSlides = slider.animatedSlides || setInterval(slider.animateSlides, slider.vars.slideshowSpeed);
  9751. slider.started = slider.playing = true;
  9752. // PAUSEPLAY:
  9753. if (slider.vars.pausePlay) methods.pausePlay.update("pause");
  9754. // SYNC:
  9755. if (slider.syncExists) methods.sync("play");
  9756. };
  9757. // STOP:
  9758. slider.stop = function() {
  9759. slider.pause();
  9760. slider.stopped = true;
  9761. };
  9762. slider.canAdvance = function(target, fromNav) {
  9763. // ASNAV:
  9764. var last = asNav ? slider.pagingCount - 1 : slider.last;
  9765. return fromNav ? true : asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev" ? true : asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next" ? false : target === slider.currentSlide && !asNav ? false : slider.vars.animationLoop ? true : slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next" ? false : slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next" ? false : true;
  9766. };
  9767. slider.getTarget = function(dir) {
  9768. slider.direction = dir;
  9769. if (dir === "next") {
  9770. return slider.currentSlide === slider.last ? 0 : slider.currentSlide + 1;
  9771. } else {
  9772. return slider.currentSlide === 0 ? slider.last : slider.currentSlide - 1;
  9773. }
  9774. };
  9775. // SLIDE:
  9776. slider.setProps = function(pos, special, dur) {
  9777. var target = function() {
  9778. var posCheck = pos ? pos : (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo, posCalc = function() {
  9779. if (carousel) {
  9780. return special === "setTouch" ? pos : reverse && slider.animatingTo === slider.last ? 0 : reverse ? slider.limit - (slider.itemW + slider.vars.itemMargin) * slider.move * slider.animatingTo : slider.animatingTo === slider.last ? slider.limit : posCheck;
  9781. } else {
  9782. switch (special) {
  9783. case "setTotal":
  9784. return reverse ? (slider.count - 1 - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos;
  9785. case "setTouch":
  9786. return reverse ? pos : pos;
  9787. case "jumpEnd":
  9788. return reverse ? pos : slider.count * pos;
  9789. case "jumpStart":
  9790. return reverse ? slider.count * pos : pos;
  9791. default:
  9792. return pos;
  9793. }
  9794. }
  9795. }();
  9796. return posCalc * -1 + "px";
  9797. }();
  9798. if (slider.transitions) {
  9799. target = vertical ? "translate3d(0," + target + ",0)" : "translate3d(" + target + ",0,0)";
  9800. dur = dur !== undefined ? dur / 1e3 + "s" : "0s";
  9801. slider.container.css("-" + slider.pfx + "-transition-duration", dur);
  9802. slider.container.css("transition-duration", dur);
  9803. }
  9804. slider.args[slider.prop] = target;
  9805. if (slider.transitions || dur === undefined) slider.container.css(slider.args);
  9806. slider.container.css("transform", target);
  9807. };
  9808. slider.setup = function(type) {
  9809. // SLIDE:
  9810. if (!fade) {
  9811. var sliderOffset, arr;
  9812. if (type === "init") {
  9813. slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({
  9814. overflow: "hidden",
  9815. position: "relative"
  9816. }).appendTo(slider).append(slider.container);
  9817. // INFINITE LOOP:
  9818. slider.cloneCount = 0;
  9819. slider.cloneOffset = 0;
  9820. // REVERSE:
  9821. if (reverse) {
  9822. arr = $.makeArray(slider.slides).reverse();
  9823. slider.slides = $(arr);
  9824. slider.container.empty().append(slider.slides);
  9825. }
  9826. }
  9827. // INFINITE LOOP && !CAROUSEL:
  9828. if (slider.vars.animationLoop && !carousel) {
  9829. slider.cloneCount = 2;
  9830. slider.cloneOffset = 1;
  9831. // clear out old clones
  9832. if (type !== "init") slider.container.find(".clone").remove();
  9833. slider.container.append(methods.uniqueID(slider.slides.first().clone().addClass("clone")).attr("aria-hidden", "true")).prepend(methods.uniqueID(slider.slides.last().clone().addClass("clone")).attr("aria-hidden", "true"));
  9834. }
  9835. slider.newSlides = $(slider.vars.selector, slider);
  9836. sliderOffset = reverse ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
  9837. // VERTICAL:
  9838. if (vertical && !carousel) {
  9839. slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
  9840. setTimeout(function() {
  9841. slider.newSlides.css({
  9842. display: "block"
  9843. });
  9844. slider.doMath();
  9845. slider.viewport.height(slider.h);
  9846. slider.setProps(sliderOffset * slider.h, "init");
  9847. }, type === "init" ? 100 : 0);
  9848. } else {
  9849. slider.container.width((slider.count + slider.cloneCount) * 200 + "%");
  9850. slider.setProps(sliderOffset * slider.computedW, "init");
  9851. setTimeout(function() {
  9852. slider.doMath();
  9853. slider.newSlides.css({
  9854. width: slider.computedW,
  9855. "float": "left",
  9856. display: "block"
  9857. });
  9858. // SMOOTH HEIGHT:
  9859. if (slider.vars.smoothHeight) methods.smoothHeight();
  9860. }, type === "init" ? 100 : 0);
  9861. }
  9862. } else {
  9863. // FADE:
  9864. slider.slides.css({
  9865. width: "100%",
  9866. "float": "left",
  9867. marginRight: "-100%",
  9868. position: "relative"
  9869. });
  9870. if (type === "init") {
  9871. if (!touch) {
  9872. //slider.slides.eq(slider.currentSlide).fadeIn(slider.vars.animationSpeed, slider.vars.easing);
  9873. if (slider.vars.fadeFirstSlide == false) {
  9874. slider.slides.css({
  9875. opacity: 0,
  9876. display: "block",
  9877. zIndex: 1
  9878. }).eq(slider.currentSlide).css({
  9879. zIndex: 2
  9880. }).css({
  9881. opacity: 1
  9882. });
  9883. } else {
  9884. slider.slides.css({
  9885. opacity: 0,
  9886. display: "block",
  9887. zIndex: 1
  9888. }).eq(slider.currentSlide).css({
  9889. zIndex: 2
  9890. }).animate({
  9891. opacity: 1
  9892. }, slider.vars.animationSpeed, slider.vars.easing);
  9893. }
  9894. } else {
  9895. slider.slides.css({
  9896. opacity: 0,
  9897. display: "block",
  9898. webkitTransition: "opacity " + slider.vars.animationSpeed / 1e3 + "s ease",
  9899. zIndex: 1
  9900. }).eq(slider.currentSlide).css({
  9901. opacity: 1,
  9902. zIndex: 2
  9903. });
  9904. }
  9905. }
  9906. // SMOOTH HEIGHT:
  9907. if (slider.vars.smoothHeight) methods.smoothHeight();
  9908. }
  9909. // !CAROUSEL:
  9910. // CANDIDATE: active slide
  9911. if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide");
  9912. //FlexSlider: init() Callback
  9913. slider.vars.init(slider);
  9914. };
  9915. slider.doMath = function() {
  9916. var slide = slider.slides.first(), slideMargin = slider.vars.itemMargin, minItems = slider.vars.minItems, maxItems = slider.vars.maxItems;
  9917. slider.w = slider.viewport === undefined ? slider.width() : slider.viewport.width();
  9918. slider.h = slide.height();
  9919. slider.boxPadding = slide.outerWidth() - slide.width();
  9920. // CAROUSEL:
  9921. if (carousel) {
  9922. slider.itemT = slider.vars.itemWidth + slideMargin;
  9923. slider.minW = minItems ? minItems * slider.itemT : slider.w;
  9924. slider.maxW = maxItems ? maxItems * slider.itemT - slideMargin : slider.w;
  9925. slider.itemW = slider.minW > slider.w ? (slider.w - slideMargin * (minItems - 1)) / minItems : slider.maxW < slider.w ? (slider.w - slideMargin * (maxItems - 1)) / maxItems : slider.vars.itemWidth > slider.w ? slider.w : slider.vars.itemWidth;
  9926. slider.visible = Math.floor(slider.w / slider.itemW);
  9927. slider.move = slider.vars.move > 0 && slider.vars.move < slider.visible ? slider.vars.move : slider.visible;
  9928. slider.pagingCount = Math.ceil((slider.count - slider.visible) / slider.move + 1);
  9929. slider.last = slider.pagingCount - 1;
  9930. slider.limit = slider.pagingCount === 1 ? 0 : slider.vars.itemWidth > slider.w ? slider.itemW * (slider.count - 1) + slideMargin * (slider.count - 1) : (slider.itemW + slideMargin) * slider.count - slider.w - slideMargin;
  9931. } else {
  9932. slider.itemW = slider.w;
  9933. slider.pagingCount = slider.count;
  9934. slider.last = slider.count - 1;
  9935. }
  9936. slider.computedW = slider.itemW - slider.boxPadding;
  9937. };
  9938. slider.update = function(pos, action) {
  9939. slider.doMath();
  9940. // update currentSlide and slider.animatingTo if necessary
  9941. if (!carousel) {
  9942. if (pos < slider.currentSlide) {
  9943. slider.currentSlide += 1;
  9944. } else if (pos <= slider.currentSlide && pos !== 0) {
  9945. slider.currentSlide -= 1;
  9946. }
  9947. slider.animatingTo = slider.currentSlide;
  9948. }
  9949. // update controlNav
  9950. if (slider.vars.controlNav && !slider.manualControls) {
  9951. if (action === "add" && !carousel || slider.pagingCount > slider.controlNav.length) {
  9952. methods.controlNav.update("add");
  9953. } else if (action === "remove" && !carousel || slider.pagingCount < slider.controlNav.length) {
  9954. if (carousel && slider.currentSlide > slider.last) {
  9955. slider.currentSlide -= 1;
  9956. slider.animatingTo -= 1;
  9957. }
  9958. methods.controlNav.update("remove", slider.last);
  9959. }
  9960. }
  9961. // update directionNav
  9962. if (slider.vars.directionNav) methods.directionNav.update();
  9963. };
  9964. slider.addSlide = function(obj, pos) {
  9965. var $obj = $(obj);
  9966. slider.count += 1;
  9967. slider.last = slider.count - 1;
  9968. // append new slide
  9969. if (vertical && reverse) {
  9970. pos !== undefined ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj);
  9971. } else {
  9972. pos !== undefined ? slider.slides.eq(pos).before($obj) : slider.container.append($obj);
  9973. }
  9974. // update currentSlide, animatingTo, controlNav, and directionNav
  9975. slider.update(pos, "add");
  9976. // update slider.slides
  9977. slider.slides = $(slider.vars.selector + ":not(.clone)", slider);
  9978. // re-setup the slider to accomdate new slide
  9979. slider.setup();
  9980. //FlexSlider: added() Callback
  9981. slider.vars.added(slider);
  9982. };
  9983. slider.removeSlide = function(obj) {
  9984. var pos = isNaN(obj) ? slider.slides.index($(obj)) : obj;
  9985. // update count
  9986. slider.count -= 1;
  9987. slider.last = slider.count - 1;
  9988. // remove slide
  9989. if (isNaN(obj)) {
  9990. $(obj, slider.slides).remove();
  9991. } else {
  9992. vertical && reverse ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove();
  9993. }
  9994. // update currentSlide, animatingTo, controlNav, and directionNav
  9995. slider.doMath();
  9996. slider.update(pos, "remove");
  9997. // update slider.slides
  9998. slider.slides = $(slider.vars.selector + ":not(.clone)", slider);
  9999. // re-setup the slider to accomdate new slide
  10000. slider.setup();
  10001. // FlexSlider: removed() Callback
  10002. slider.vars.removed(slider);
  10003. };
  10004. //FlexSlider: Initialize
  10005. methods.init();
  10006. };
  10007. // Ensure the slider isn't focussed if the window loses focus.
  10008. $(window).blur(function(e) {
  10009. focused = false;
  10010. }).focus(function(e) {
  10011. focused = true;
  10012. });
  10013. //FlexSlider: Default Settings
  10014. $.flexslider.defaults = {
  10015. namespace: "am-",
  10016. //{NEW} String: Prefix string attached to the class of every element generated by the plugin
  10017. selector: ".am-slides > li",
  10018. //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
  10019. animation: "slide",
  10020. //String: Select your animation type, "fade" or "slide"
  10021. easing: "swing",
  10022. //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
  10023. direction: "horizontal",
  10024. //String: Select the sliding direction, "horizontal" or "vertical"
  10025. reverse: false,
  10026. //{NEW} Boolean: Reverse the animation direction
  10027. animationLoop: true,
  10028. //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
  10029. smoothHeight: false,
  10030. //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
  10031. startAt: 0,
  10032. //Integer: The slide that the slider should start on. Array notation (0 = first slide)
  10033. slideshow: true,
  10034. //Boolean: Animate slider automatically
  10035. slideshowSpeed: 5e3,
  10036. //Integer: Set the speed of the slideshow cycling, in milliseconds
  10037. animationSpeed: 600,
  10038. //Integer: Set the speed of animations, in milliseconds
  10039. initDelay: 0,
  10040. //{NEW} Integer: Set an initialization delay, in milliseconds
  10041. randomize: false,
  10042. //Boolean: Randomize slide order
  10043. thumbCaptions: false,
  10044. //Boolean: Whether or not to put captions on thumbnails when using the "thumbnails" controlNav.
  10045. // Usability features
  10046. pauseOnAction: true,
  10047. //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
  10048. pauseOnHover: false,
  10049. //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
  10050. pauseInvisible: true,
  10051. //{NEW} Boolean: Pause the slideshow when tab is invisible, resume when visible. Provides better UX, lower CPU usage.
  10052. useCSS: true,
  10053. //{NEW} Boolean: Slider will use CSS3 transitions if available
  10054. touch: true,
  10055. //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
  10056. video: false,
  10057. //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches
  10058. // Primary Controls
  10059. controlNav: true,
  10060. //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
  10061. directionNav: true,
  10062. //Boolean: Create navigation for previous/next navigation? (true/false)
  10063. prevText: "Previous",
  10064. //String: Set the text for the "previous" directionNav item
  10065. nextText: "Next",
  10066. //String: Set the text for the "next" directionNav item
  10067. // Secondary Navigation
  10068. keyboard: true,
  10069. //Boolean: Allow slider navigating via keyboard left/right keys
  10070. multipleKeyboard: false,
  10071. //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
  10072. mousewheel: false,
  10073. //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
  10074. pausePlay: false,
  10075. //Boolean: Create pause/play dynamic element
  10076. pauseText: "Pause",
  10077. //String: Set the text for the "pause" pausePlay item
  10078. playText: "Play",
  10079. //String: Set the text for the "play" pausePlay item
  10080. // Special properties
  10081. controlsContainer: "",
  10082. //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
  10083. manualControls: "",
  10084. //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
  10085. sync: "",
  10086. //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
  10087. asNavFor: "",
  10088. //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider
  10089. // Carousel Options
  10090. itemWidth: 0,
  10091. //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
  10092. itemMargin: 0,
  10093. //{NEW} Integer: Margin between carousel items.
  10094. minItems: 1,
  10095. //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
  10096. maxItems: 0,
  10097. //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
  10098. move: 0,
  10099. //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.
  10100. allowOneSlide: true,
  10101. //{NEW} Boolean: Whether or not to allow a slider comprised of a single slide
  10102. // Callback API
  10103. start: function() {},
  10104. //Callback: function(slider) - Fires when the slider loads the first slide
  10105. before: function() {},
  10106. //Callback: function(slider) - Fires asynchronously with each slider animation
  10107. after: function() {},
  10108. //Callback: function(slider) - Fires after each slider animation completes
  10109. end: function() {},
  10110. //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
  10111. added: function() {},
  10112. //{NEW} Callback: function(slider) - Fires after a slide is added
  10113. removed: function() {},
  10114. //{NEW} Callback: function(slider) - Fires after a slide is removed
  10115. init: function() {}
  10116. };
  10117. //FlexSlider: Plugin Function
  10118. $.fn.flexslider = function(options) {
  10119. if (options === undefined) options = {};
  10120. if (typeof options === "object") {
  10121. return this.each(function() {
  10122. var $this = $(this), selector = options.selector ? options.selector : ".am-slides > li", $slides = $this.find(selector);
  10123. if ($slides.length === 1 && options.allowOneSlide === true || $slides.length === 0) {
  10124. $slides.animate({
  10125. opacity: 1
  10126. }, 400);
  10127. if (options.start) options.start($this);
  10128. } else if ($this.data("flexslider") === undefined) {
  10129. new $.flexslider(this, options);
  10130. }
  10131. });
  10132. } else {
  10133. // Helper strings to quickly perform functions on the slider
  10134. var $slider = $(this).data("flexslider");
  10135. switch (options) {
  10136. case "play":
  10137. $slider.play();
  10138. break;
  10139. case "pause":
  10140. $slider.pause();
  10141. break;
  10142. case "stop":
  10143. $slider.stop();
  10144. break;
  10145. case "next":
  10146. $slider.flexAnimate($slider.getTarget("next"), true);
  10147. break;
  10148. case "prev":
  10149. case "previous":
  10150. $slider.flexAnimate($slider.getTarget("prev"), true);
  10151. break;
  10152. default:
  10153. if (typeof options === "number") $slider.flexAnimate(options, true);
  10154. }
  10155. }
  10156. };
  10157. });
  10158. define("zepto.pinchzoom", [], function(require, exports, module) {
  10159. "use strict";
  10160. /**
  10161. * @via https://github.com/manuelstofer/pinchzoom/blob/master/src/pinchzoom.js
  10162. * @license the MIT License.
  10163. */
  10164. var definePinchZoom = function($) {
  10165. /**
  10166. * Pinch zoom using jQuery
  10167. * @version 0.0.2
  10168. * @author Manuel Stofer <mst@rtp.ch>
  10169. * @param el
  10170. * @param options
  10171. * @constructor
  10172. */
  10173. var PinchZoom = function(el, options) {
  10174. this.el = $(el);
  10175. this.zoomFactor = 1;
  10176. this.lastScale = 1;
  10177. this.offset = {
  10178. x: 0,
  10179. y: 0
  10180. };
  10181. this.options = $.extend({}, this.defaults, options);
  10182. this.setupMarkup();
  10183. this.bindEvents();
  10184. this.update();
  10185. // default enable.
  10186. this.enable();
  10187. }, sum = function(a, b) {
  10188. return a + b;
  10189. }, isCloseTo = function(value, expected) {
  10190. return value > expected - .01 && value < expected + .01;
  10191. };
  10192. PinchZoom.prototype = {
  10193. defaults: {
  10194. tapZoomFactor: 2,
  10195. zoomOutFactor: 1.3,
  10196. animationDuration: 300,
  10197. animationInterval: 5,
  10198. maxZoom: 5,
  10199. minZoom: .5,
  10200. lockDragAxis: false,
  10201. use2d: false,
  10202. zoomStartEventName: "pz_zoomstart",
  10203. zoomEndEventName: "pz_zoomend",
  10204. dragStartEventName: "pz_dragstart",
  10205. dragEndEventName: "pz_dragend",
  10206. doubleTapEventName: "pz_doubletap"
  10207. },
  10208. /**
  10209. * Event handler for 'dragstart'
  10210. * @param event
  10211. */
  10212. handleDragStart: function(event) {
  10213. this.el.trigger(this.options.dragStartEventName);
  10214. this.stopAnimation();
  10215. this.lastDragPosition = false;
  10216. this.hasInteraction = true;
  10217. this.handleDrag(event);
  10218. },
  10219. /**
  10220. * Event handler for 'drag'
  10221. * @param event
  10222. */
  10223. handleDrag: function(event) {
  10224. if (this.zoomFactor > 1) {
  10225. var touch = this.getTouches(event)[0];
  10226. this.drag(touch, this.lastDragPosition);
  10227. this.offset = this.sanitizeOffset(this.offset);
  10228. this.lastDragPosition = touch;
  10229. }
  10230. },
  10231. handleDragEnd: function() {
  10232. this.el.trigger(this.options.dragEndEventName);
  10233. this.end();
  10234. },
  10235. /**
  10236. * Event handler for 'zoomstart'
  10237. * @param event
  10238. */
  10239. handleZoomStart: function(event) {
  10240. this.el.trigger(this.options.zoomStartEventName);
  10241. this.stopAnimation();
  10242. this.lastScale = 1;
  10243. this.nthZoom = 0;
  10244. this.lastZoomCenter = false;
  10245. this.hasInteraction = true;
  10246. },
  10247. /**
  10248. * Event handler for 'zoom'
  10249. * @param event
  10250. */
  10251. handleZoom: function(event, newScale) {
  10252. // a relative scale factor is used
  10253. var touchCenter = this.getTouchCenter(this.getTouches(event)), scale = newScale / this.lastScale;
  10254. this.lastScale = newScale;
  10255. // the first touch events are thrown away since they are not precise
  10256. this.nthZoom += 1;
  10257. if (this.nthZoom > 3) {
  10258. this.scale(scale, touchCenter);
  10259. this.drag(touchCenter, this.lastZoomCenter);
  10260. }
  10261. this.lastZoomCenter = touchCenter;
  10262. },
  10263. handleZoomEnd: function() {
  10264. this.el.trigger(this.options.zoomEndEventName);
  10265. this.end();
  10266. },
  10267. /**
  10268. * Event handler for 'doubletap'
  10269. * @param event
  10270. */
  10271. handleDoubleTap: function(event) {
  10272. var center = this.getTouches(event)[0], zoomFactor = this.zoomFactor > 1 ? 1 : this.options.tapZoomFactor, startZoomFactor = this.zoomFactor, updateProgress = function(progress) {
  10273. this.scaleTo(startZoomFactor + progress * (zoomFactor - startZoomFactor), center);
  10274. }.bind(this);
  10275. if (this.hasInteraction) {
  10276. return;
  10277. }
  10278. if (startZoomFactor > zoomFactor) {
  10279. center = this.getCurrentZoomCenter();
  10280. }
  10281. this.animate(this.options.animationDuration, this.options.animationInterval, updateProgress, this.swing);
  10282. this.el.trigger(this.options.doubleTapEventName);
  10283. },
  10284. /**
  10285. * Max / min values for the offset
  10286. * @param offset
  10287. * @return {Object} the sanitized offset
  10288. */
  10289. sanitizeOffset: function(offset) {
  10290. var maxX = (this.zoomFactor - 1) * this.getContainerX(), maxY = (this.zoomFactor - 1) * this.getContainerY(), maxOffsetX = Math.max(maxX, 0), maxOffsetY = Math.max(maxY, 0), minOffsetX = Math.min(maxX, 0), minOffsetY = Math.min(maxY, 0);
  10291. return {
  10292. x: Math.min(Math.max(offset.x, minOffsetX), maxOffsetX),
  10293. y: Math.min(Math.max(offset.y, minOffsetY), maxOffsetY)
  10294. };
  10295. },
  10296. /**
  10297. * Scale to a specific zoom factor (not relative)
  10298. * @param zoomFactor
  10299. * @param center
  10300. */
  10301. scaleTo: function(zoomFactor, center) {
  10302. this.scale(zoomFactor / this.zoomFactor, center);
  10303. },
  10304. /**
  10305. * Scales the element from specified center
  10306. * @param scale
  10307. * @param center
  10308. */
  10309. scale: function(scale, center) {
  10310. scale = this.scaleZoomFactor(scale);
  10311. this.addOffset({
  10312. x: (scale - 1) * (center.x + this.offset.x),
  10313. y: (scale - 1) * (center.y + this.offset.y)
  10314. });
  10315. },
  10316. /**
  10317. * Scales the zoom factor relative to current state
  10318. * @param scale
  10319. * @return the actual scale (can differ because of max min zoom factor)
  10320. */
  10321. scaleZoomFactor: function(scale) {
  10322. var originalZoomFactor = this.zoomFactor;
  10323. this.zoomFactor *= scale;
  10324. this.zoomFactor = Math.min(this.options.maxZoom, Math.max(this.zoomFactor, this.options.minZoom));
  10325. return this.zoomFactor / originalZoomFactor;
  10326. },
  10327. /**
  10328. * Drags the element
  10329. * @param center
  10330. * @param lastCenter
  10331. */
  10332. drag: function(center, lastCenter) {
  10333. if (lastCenter) {
  10334. if (this.options.lockDragAxis) {
  10335. // lock scroll to position that was changed the most
  10336. if (Math.abs(center.x - lastCenter.x) > Math.abs(center.y - lastCenter.y)) {
  10337. this.addOffset({
  10338. x: -(center.x - lastCenter.x),
  10339. y: 0
  10340. });
  10341. } else {
  10342. this.addOffset({
  10343. y: -(center.y - lastCenter.y),
  10344. x: 0
  10345. });
  10346. }
  10347. } else {
  10348. this.addOffset({
  10349. y: -(center.y - lastCenter.y),
  10350. x: -(center.x - lastCenter.x)
  10351. });
  10352. }
  10353. }
  10354. },
  10355. /**
  10356. * Calculates the touch center of multiple touches
  10357. * @param touches
  10358. * @return {Object}
  10359. */
  10360. getTouchCenter: function(touches) {
  10361. return this.getVectorAvg(touches);
  10362. },
  10363. /**
  10364. * Calculates the average of multiple vectors (x, y values)
  10365. */
  10366. getVectorAvg: function(vectors) {
  10367. return {
  10368. x: vectors.map(function(v) {
  10369. return v.x;
  10370. }).reduce(sum) / vectors.length,
  10371. y: vectors.map(function(v) {
  10372. return v.y;
  10373. }).reduce(sum) / vectors.length
  10374. };
  10375. },
  10376. /**
  10377. * Adds an offset
  10378. * @param offset the offset to add
  10379. * @return return true when the offset change was accepted
  10380. */
  10381. addOffset: function(offset) {
  10382. this.offset = {
  10383. x: this.offset.x + offset.x,
  10384. y: this.offset.y + offset.y
  10385. };
  10386. },
  10387. sanitize: function() {
  10388. if (this.zoomFactor < this.options.zoomOutFactor) {
  10389. this.zoomOutAnimation();
  10390. } else if (this.isInsaneOffset(this.offset)) {
  10391. this.sanitizeOffsetAnimation();
  10392. }
  10393. },
  10394. /**
  10395. * Checks if the offset is ok with the current zoom factor
  10396. * @param offset
  10397. * @return {Boolean}
  10398. */
  10399. isInsaneOffset: function(offset) {
  10400. var sanitizedOffset = this.sanitizeOffset(offset);
  10401. return sanitizedOffset.x !== offset.x || sanitizedOffset.y !== offset.y;
  10402. },
  10403. /**
  10404. * Creates an animation moving to a sane offset
  10405. */
  10406. sanitizeOffsetAnimation: function() {
  10407. var targetOffset = this.sanitizeOffset(this.offset), startOffset = {
  10408. x: this.offset.x,
  10409. y: this.offset.y
  10410. }, updateProgress = function(progress) {
  10411. this.offset.x = startOffset.x + progress * (targetOffset.x - startOffset.x);
  10412. this.offset.y = startOffset.y + progress * (targetOffset.y - startOffset.y);
  10413. this.update();
  10414. }.bind(this);
  10415. this.animate(this.options.animationDuration, this.options.animationInterval, updateProgress, this.swing);
  10416. },
  10417. /**
  10418. * Zooms back to the original position,
  10419. * (no offset and zoom factor 1)
  10420. */
  10421. zoomOutAnimation: function() {
  10422. var startZoomFactor = this.zoomFactor, zoomFactor = 1, center = this.getCurrentZoomCenter(), updateProgress = function(progress) {
  10423. this.scaleTo(startZoomFactor + progress * (zoomFactor - startZoomFactor), center);
  10424. }.bind(this);
  10425. this.animate(this.options.animationDuration, this.options.animationInterval, updateProgress, this.swing);
  10426. },
  10427. /**
  10428. * Updates the aspect ratio
  10429. */
  10430. updateAspectRatio: function() {
  10431. // this.setContainerY(this.getContainerX() / this.getAspectRatio());
  10432. // @modified
  10433. this.setContainerY();
  10434. },
  10435. /**
  10436. * Calculates the initial zoom factor (for the element to fit into the container)
  10437. * @return the initial zoom factor
  10438. */
  10439. getInitialZoomFactor: function() {
  10440. // use .offsetWidth instead of width()
  10441. // because jQuery-width() return the original width but Zepto-width() will calculate width with transform.
  10442. // the same as .height()
  10443. return this.container[0].offsetWidth / this.el[0].offsetWidth;
  10444. },
  10445. /**
  10446. * Calculates the aspect ratio of the element
  10447. * @return the aspect ratio
  10448. */
  10449. getAspectRatio: function() {
  10450. return this.el[0].offsetWidth / this.el[0].offsetHeight;
  10451. },
  10452. /**
  10453. * Calculates the virtual zoom center for the current offset and zoom factor
  10454. * (used for reverse zoom)
  10455. * @return {Object} the current zoom center
  10456. */
  10457. getCurrentZoomCenter: function() {
  10458. // uses following formula to calculate the zoom center x value
  10459. // offset_left / offset_right = zoomcenter_x / (container_x - zoomcenter_x)
  10460. var length = this.container[0].offsetWidth * this.zoomFactor, offsetLeft = this.offset.x, offsetRight = length - offsetLeft - this.container[0].offsetWidth, widthOffsetRatio = offsetLeft / offsetRight, centerX = widthOffsetRatio * this.container[0].offsetWidth / (widthOffsetRatio + 1), // the same for the zoomcenter y
  10461. height = this.container[0].offsetHeight * this.zoomFactor, offsetTop = this.offset.y, offsetBottom = height - offsetTop - this.container[0].offsetHeight, heightOffsetRatio = offsetTop / offsetBottom, centerY = heightOffsetRatio * this.container[0].offsetHeight / (heightOffsetRatio + 1);
  10462. // prevents division by zero
  10463. if (offsetRight === 0) {
  10464. centerX = this.container[0].offsetWidth;
  10465. }
  10466. if (offsetBottom === 0) {
  10467. centerY = this.container[0].offsetHeight;
  10468. }
  10469. return {
  10470. x: centerX,
  10471. y: centerY
  10472. };
  10473. },
  10474. canDrag: function() {
  10475. return !isCloseTo(this.zoomFactor, 1);
  10476. },
  10477. /**
  10478. * Returns the touches of an event relative to the container offset
  10479. * @param event
  10480. * @return array touches
  10481. */
  10482. getTouches: function(event) {
  10483. var position = this.container.offset();
  10484. return Array.prototype.slice.call(event.touches).map(function(touch) {
  10485. return {
  10486. x: touch.pageX - position.left,
  10487. y: touch.pageY - position.top
  10488. };
  10489. });
  10490. },
  10491. /**
  10492. * Animation loop
  10493. * does not support simultaneous animations
  10494. * @param duration
  10495. * @param interval
  10496. * @param framefn
  10497. * @param timefn
  10498. * @param callback
  10499. */
  10500. animate: function(duration, interval, framefn, timefn, callback) {
  10501. var startTime = new Date().getTime(), renderFrame = function() {
  10502. if (!this.inAnimation) {
  10503. return;
  10504. }
  10505. var frameTime = new Date().getTime() - startTime, progress = frameTime / duration;
  10506. if (frameTime >= duration) {
  10507. framefn(1);
  10508. if (callback) {
  10509. callback();
  10510. }
  10511. this.update();
  10512. this.stopAnimation();
  10513. this.update();
  10514. } else {
  10515. if (timefn) {
  10516. progress = timefn(progress);
  10517. }
  10518. framefn(progress);
  10519. this.update();
  10520. setTimeout(renderFrame, interval);
  10521. }
  10522. }.bind(this);
  10523. this.inAnimation = true;
  10524. renderFrame();
  10525. },
  10526. /**
  10527. * Stops the animation
  10528. */
  10529. stopAnimation: function() {
  10530. this.inAnimation = false;
  10531. },
  10532. /**
  10533. * Swing timing function for animations
  10534. * @param p
  10535. * @return {Number}
  10536. */
  10537. swing: function(p) {
  10538. return -Math.cos(p * Math.PI) / 2 + .5;
  10539. },
  10540. getContainerX: function() {
  10541. // return this.container[0].offsetWidth;
  10542. // @modified
  10543. return window.innerWidth;
  10544. },
  10545. getContainerY: function() {
  10546. // return this.container[0].offsetHeight;
  10547. // @modified
  10548. return window.innerHeight;
  10549. },
  10550. setContainerY: function(y) {
  10551. // return this.container.height(y);
  10552. // @modified
  10553. var t = window.innerHeight;
  10554. return this.el.css({
  10555. height: t
  10556. }), this.container.height(t);
  10557. },
  10558. /**
  10559. * Creates the expected html structure
  10560. */
  10561. setupMarkup: function() {
  10562. this.container = $('<div class="pinch-zoom-container"></div>');
  10563. this.el.before(this.container);
  10564. this.container.append(this.el);
  10565. this.container.css({
  10566. overflow: "hidden",
  10567. position: "relative"
  10568. });
  10569. // Zepto doesn't recognize `webkitTransform..` style
  10570. this.el.css({
  10571. "-webkit-transform-origin": "0% 0%",
  10572. "-moz-transform-origin": "0% 0%",
  10573. "-ms-transform-origin": "0% 0%",
  10574. "-o-transform-origin": "0% 0%",
  10575. "transform-origin": "0% 0%",
  10576. position: "absolute"
  10577. });
  10578. },
  10579. end: function() {
  10580. this.hasInteraction = false;
  10581. this.sanitize();
  10582. this.update();
  10583. },
  10584. /**
  10585. * Binds all required event listeners
  10586. */
  10587. bindEvents: function() {
  10588. detectGestures(this.container.get(0), this);
  10589. // Zepto and jQuery both know about `on`
  10590. $(window).on("resize", this.update.bind(this));
  10591. $(this.el).find("img").on("load", this.update.bind(this));
  10592. },
  10593. /**
  10594. * Updates the css values according to the current zoom factor and offset
  10595. */
  10596. update: function() {
  10597. if (this.updatePlaned) {
  10598. return;
  10599. }
  10600. this.updatePlaned = true;
  10601. setTimeout(function() {
  10602. this.updatePlaned = false;
  10603. this.updateAspectRatio();
  10604. var zoomFactor = this.getInitialZoomFactor() * this.zoomFactor, offsetX = -this.offset.x / zoomFactor, offsetY = -this.offset.y / zoomFactor, transform3d = "scale3d(" + zoomFactor + ", " + zoomFactor + ",1) " + "translate3d(" + offsetX + "px," + offsetY + "px,0px)", transform2d = "scale(" + zoomFactor + ", " + zoomFactor + ") " + "translate(" + offsetX + "px," + offsetY + "px)", removeClone = function() {
  10605. if (this.clone) {
  10606. this.clone.remove();
  10607. delete this.clone;
  10608. }
  10609. }.bind(this);
  10610. // Scale 3d and translate3d are faster (at least on ios)
  10611. // but they also reduce the quality.
  10612. // PinchZoom uses the 3d transformations during interactions
  10613. // after interactions it falls back to 2d transformations
  10614. if (!this.options.use2d || this.hasInteraction || this.inAnimation) {
  10615. this.is3d = true;
  10616. removeClone();
  10617. this.el.css({
  10618. "-webkit-transform": transform3d,
  10619. "-o-transform": transform2d,
  10620. "-ms-transform": transform2d,
  10621. "-moz-transform": transform2d,
  10622. transform: transform3d
  10623. });
  10624. } else {
  10625. // When changing from 3d to 2d transform webkit has some glitches.
  10626. // To avoid this, a copy of the 3d transformed element is displayed in the
  10627. // foreground while the element is converted from 3d to 2d transform
  10628. if (this.is3d) {
  10629. this.clone = this.el.clone();
  10630. this.clone.css("pointer-events", "none");
  10631. this.clone.appendTo(this.container);
  10632. setTimeout(removeClone, 200);
  10633. }
  10634. this.el.css({
  10635. "-webkit-transform": transform2d,
  10636. "-o-transform": transform2d,
  10637. "-ms-transform": transform2d,
  10638. "-moz-transform": transform2d,
  10639. transform: transform2d
  10640. });
  10641. this.is3d = false;
  10642. }
  10643. }.bind(this), 0);
  10644. },
  10645. /**
  10646. * Enables event handling for gestures
  10647. */
  10648. enable: function() {
  10649. this.enabled = true;
  10650. },
  10651. /**
  10652. * Disables event handling for gestures
  10653. */
  10654. disable: function() {
  10655. this.enabled = false;
  10656. }
  10657. };
  10658. var detectGestures = function(el, target) {
  10659. var interaction = null, fingers = 0, lastTouchStart = null, startTouches = null, setInteraction = function(newInteraction, event) {
  10660. if (interaction !== newInteraction) {
  10661. if (interaction && !newInteraction) {
  10662. switch (interaction) {
  10663. case "zoom":
  10664. target.handleZoomEnd(event);
  10665. break;
  10666. case "drag":
  10667. target.handleDragEnd(event);
  10668. break;
  10669. }
  10670. }
  10671. switch (newInteraction) {
  10672. case "zoom":
  10673. target.handleZoomStart(event);
  10674. break;
  10675. case "drag":
  10676. target.handleDragStart(event);
  10677. break;
  10678. }
  10679. }
  10680. interaction = newInteraction;
  10681. }, updateInteraction = function(event) {
  10682. if (fingers === 2) {
  10683. setInteraction("zoom");
  10684. } else if (fingers === 1 && target.canDrag()) {
  10685. setInteraction("drag", event);
  10686. } else {
  10687. setInteraction(null, event);
  10688. }
  10689. }, targetTouches = function(touches) {
  10690. return Array.prototype.slice.call(touches).map(function(touch) {
  10691. return {
  10692. x: touch.pageX,
  10693. y: touch.pageY
  10694. };
  10695. });
  10696. }, getDistance = function(a, b) {
  10697. var x, y;
  10698. x = a.x - b.x;
  10699. y = a.y - b.y;
  10700. return Math.sqrt(x * x + y * y);
  10701. }, calculateScale = function(startTouches, endTouches) {
  10702. var startDistance = getDistance(startTouches[0], startTouches[1]), endDistance = getDistance(endTouches[0], endTouches[1]);
  10703. return endDistance / startDistance;
  10704. }, cancelEvent = function(event) {
  10705. event.stopPropagation();
  10706. event.preventDefault();
  10707. }, detectDoubleTap = function(event) {
  10708. var time = new Date().getTime();
  10709. if (fingers > 1) {
  10710. lastTouchStart = null;
  10711. }
  10712. if (time - lastTouchStart < 300) {
  10713. cancelEvent(event);
  10714. target.handleDoubleTap(event);
  10715. switch (interaction) {
  10716. case "zoom":
  10717. target.handleZoomEnd(event);
  10718. break;
  10719. case "drag":
  10720. target.handleDragEnd(event);
  10721. break;
  10722. }
  10723. }
  10724. if (fingers === 1) {
  10725. lastTouchStart = time;
  10726. }
  10727. }, firstMove = true;
  10728. el.addEventListener("touchstart", function(event) {
  10729. if (target.enabled) {
  10730. firstMove = true;
  10731. fingers = event.touches.length;
  10732. detectDoubleTap(event);
  10733. }
  10734. });
  10735. el.addEventListener("touchmove", function(event) {
  10736. if (target.enabled) {
  10737. if (firstMove) {
  10738. updateInteraction(event);
  10739. if (interaction) {
  10740. cancelEvent(event);
  10741. }
  10742. startTouches = targetTouches(event.touches);
  10743. } else {
  10744. switch (interaction) {
  10745. case "zoom":
  10746. target.handleZoom(event, calculateScale(startTouches, targetTouches(event.touches)));
  10747. break;
  10748. case "drag":
  10749. target.handleDrag(event);
  10750. break;
  10751. }
  10752. if (interaction) {
  10753. cancelEvent(event);
  10754. target.update();
  10755. }
  10756. }
  10757. firstMove = false;
  10758. }
  10759. });
  10760. el.addEventListener("touchend", function(event) {
  10761. if (target.enabled) {
  10762. fingers = event.touches.length;
  10763. updateInteraction(event);
  10764. }
  10765. });
  10766. };
  10767. return PinchZoom;
  10768. };
  10769. module.exports = definePinchZoom(window.Zepto);
  10770. });
  10771. seajs.use(["core","util.fastclick","util.hammer","zepto.outerdemension","zepto.extend.data","zepto.extend.fx","zepto.extend.selector","ui.add2home","ui.alert","ui.button","ui.collapse","ui.dimmer","ui.dropdown","ui.iscroll-lite","ui.modal","ui.offcanvas","ui.popover","ui.progress","ui.pureview","ui.scrollspy","ui.scrollspynav","ui.share","ui.smooth-scroll","ui.sticky","ui.tabs","util.cookie","util.fullscreen","util.qrcode","zepto.flexslider","zepto.pinchzoom"]);