Files
yunkong2.admin/www/lib/js/materialize.js
2018-09-14 21:27:03 +08:00

9024 lines
268 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Required for Meteor package, the use of window prevents export by Meteor
(function (window) {
if (window.Package) {
M = {};
} else {
window.M = {};
}
// Check for jQuery
M.jQueryLoaded = !!window.jQuery;
})(window);
// AMD
if (typeof define === "function" && define.amd) {
define("M", [], function () {
return M;
});
// Common JS
} else if (typeof exports !== 'undefined' && !exports.nodeType) {
if (typeof module !== 'undefined' && !module.nodeType && module.exports) {
exports = module.exports = M;
}
exports.default = M;
}
M.keys = {
TAB: 9,
ENTER: 13,
ESC: 27,
ARROW_UP: 38,
ARROW_DOWN: 40
};
/**
* TabPress Keydown handler
*/
M.tabPressed = false;
var docHandleKeydown = function (e) {
if (e.which === M.keys.TAB) {
M.tabPressed = true;
}
};
var docHandleKeyup = function (e) {
if (e.which === M.keys.TAB) {
M.tabPressed = false;
}
};
document.addEventListener('keydown', docHandleKeydown);
document.addEventListener('keyup', docHandleKeyup);
/**
* Initialize jQuery wrapper for plugin
* @param {Class} plugin javascript class
* @param {string} pluginName jQuery plugin name
* @param {string} classRef Class reference name
*/
M.initializeJqueryWrapper = function (plugin, pluginName, classRef) {
jQuery.fn[pluginName] = function (methodOrOptions) {
// Call plugin method if valid method name is passed in
if (plugin.prototype[methodOrOptions]) {
var params = Array.prototype.slice.call(arguments, 1);
// Getter methods
if (methodOrOptions.slice(0, 3) === 'get') {
var instance = this.first()[0][classRef];
return instance[methodOrOptions].apply(instance, params);
}
// Void methods
return this.each(function () {
var instance = this[classRef];
instance[methodOrOptions].apply(instance, params);
});
// Initialize plugin if options or no argument is passed in
} else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
plugin.init(this, arguments[0]);
return this;
}
// Return error if an unrecognized method name is passed in
jQuery.error("Method " + methodOrOptions + " does not exist on jQuery." + pluginName);
};
};
/**
* Generate approximated selector string for a jQuery object
* @param {jQuery} obj jQuery object to be parsed
* @returns {string}
*/
M.objectSelectorString = function (obj) {
var tagStr = obj.prop('tagName') || '';
var idStr = obj.attr('id') || '';
var classStr = obj.attr('class') || '';
return (tagStr + idStr + classStr).replace(/\s/g, '');
};
// Unique Random ID
M.guid = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return function () {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
}();
/**
* Escapes hash from special characters
* @param {string} hash String returned from this.hash
* @returns {string}
*/
M.escapeHash = function (hash) {
return hash.replace(/(:|\.|\[|\]|,|=|\/)/g, "\\$1");
};
M.elementOrParentIsFixed = function (element) {
var $element = $(element);
var $checkElements = $element.add($element.parents());
var isFixed = false;
$checkElements.each(function () {
if ($(this).css("position") === "fixed") {
isFixed = true;
return false;
}
});
return isFixed;
};
/**
* @typedef {Object} Edges
* @property {Boolean} top If the top edge was exceeded
* @property {Boolean} right If the right edge was exceeded
* @property {Boolean} bottom If the bottom edge was exceeded
* @property {Boolean} left If the left edge was exceeded
*/
/**
* @typedef {Object} Bounding
* @property {Number} left left offset coordinate
* @property {Number} top top offset coordinate
* @property {Number} width
* @property {Number} height
*/
/**
* Escapes hash from special characters
* @param {Element} container Container element that acts as the boundary
* @param {Bounding} bounding element bounding that is being checked
* @param {Number} offset offset from edge that counts as exceeding
* @returns {Edges}
*/
M.checkWithinContainer = function (container, bounding, offset) {
var edges = {
top: false,
right: false,
bottom: false,
left: false
};
var containerRect = container.getBoundingClientRect();
var scrollLeft = container.scrollLeft;
var scrollTop = container.scrollTop;
var scrolledX = bounding.left - scrollLeft;
var scrolledY = bounding.top - scrollTop;
// Check for container and viewport for each edge
if (scrolledX < containerRect.left + offset || scrolledX < offset) {
edges.left = true;
}
if (scrolledX + bounding.width > containerRect.right - offset || scrolledX + bounding.width > window.innerWidth - offset) {
edges.right = true;
}
if (scrolledY < containerRect.top + offset || scrolledY < offset) {
edges.top = true;
}
if (scrolledY + bounding.height > containerRect.bottom - offset || scrolledY + bounding.height > window.innerHeight - offset) {
edges.bottom = true;
}
return edges;
};
M.checkPossibleAlignments = function (el, container, bounding, offset) {
var canAlign = {
top: true,
right: true,
bottom: true,
left: true,
spaceOnTop: null,
spaceOnRight: null,
spaceOnBottom: null,
spaceOnLeft: null
};
var containerAllowsOverflow = getComputedStyle(container).overflow === 'visible';
var containerRect = container.getBoundingClientRect();
var containerHeight = Math.min(containerRect.height, window.innerHeight);
var containerWidth = Math.min(containerRect.width, window.innerWidth);
var elOffsetRect = el.getBoundingClientRect();
var scrollLeft = container.scrollLeft;
var scrollTop = container.scrollTop;
var scrolledX = bounding.left - scrollLeft;
var scrolledYTopEdge = bounding.top - scrollTop;
var scrolledYBottomEdge = bounding.top + elOffsetRect.height - scrollTop;
// Check for container and viewport for left
canAlign.spaceOnRight = !containerAllowsOverflow ? containerWidth - (scrolledX + bounding.width) : window.innerWidth - (elOffsetRect.left + bounding.width);
if (canAlign.spaceOnRight < 0) {
canAlign.left = false;
}
// Check for container and viewport for Right
canAlign.spaceOnLeft = !containerAllowsOverflow ? scrolledX - bounding.width + elOffsetRect.width : elOffsetRect.right - bounding.width;
if (canAlign.spaceOnLeft < 0) {
canAlign.right = false;
}
// Check for container and viewport for Top
canAlign.spaceOnBottom = !containerAllowsOverflow ? containerHeight - (scrolledYTopEdge + bounding.height + offset) : window.innerHeight - (elOffsetRect.top + bounding.height + offset);
if (canAlign.spaceOnBottom < 0) {
canAlign.top = false;
}
// Check for container and viewport for Bottom
canAlign.spaceOnTop = !containerAllowsOverflow ? scrolledYBottomEdge - (bounding.height - offset) : elOffsetRect.bottom - (bounding.height + offset);
if (canAlign.spaceOnTop < 0) {
canAlign.bottom = false;
}
return canAlign;
};
M.getOverflowParent = function (element) {
if (element == null) {
return null;
}
if (element === document.body || getComputedStyle(element).overflow !== 'visible') {
return element;
}
return M.getOverflowParent(element.parentElement);
};
/**
* Gets id of component from a trigger
* @param {Element} trigger trigger
* @returns {string}
*/
M.getIdFromTrigger = function (trigger) {
var id = trigger.getAttribute('data-target');
if (!id) {
id = trigger.getAttribute('href');
if (id) {
id = id.slice(1);
} else {
id = "";
}
}
return id;
};
/**
* Multi browser support for document scroll top
* @returns {Number}
*/
M.getDocumentScrollTop = function () {
return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
};
/**
* Multi browser support for document scroll left
* @returns {Number}
*/
M.getDocumentScrollLeft = function () {
return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
};
/**
* @typedef {Object} Edges
* @property {Boolean} top If the top edge was exceeded
* @property {Boolean} right If the right edge was exceeded
* @property {Boolean} bottom If the bottom edge was exceeded
* @property {Boolean} left If the left edge was exceeded
*/
/**
* @typedef {Object} Bounding
* @property {Number} left left offset coordinate
* @property {Number} top top offset coordinate
* @property {Number} width
* @property {Number} height
*/
/**
* Get time in ms
* @license https://raw.github.com/jashkenas/underscore/master/LICENSE
* @type {function}
* @return {number}
*/
var getTime = Date.now || function () {
return new Date().getTime();
};
/**
* Returns a function, that, when invoked, will only be triggered at most once
* during a given window of time. Normally, the throttled function will run
* as much as it can, without ever going more than once per `wait` duration;
* but if you'd like to disable the execution on the leading edge, pass
* `{leading: false}`. To disable execution on the trailing edge, ditto.
* @license https://raw.github.com/jashkenas/underscore/master/LICENSE
* @param {function} func
* @param {number} wait
* @param {Object=} options
* @returns {Function}
*/
M.throttle = function (func, wait, options) {
var context = void 0,
args = void 0,
result = void 0;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function () {
previous = options.leading === false ? 0 : getTime();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function () {
var now = getTime();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
var Component = function () {
/**
* Generic constructor for all components
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Component(classDef, el, options) {
_classCallCheck(this, Component);
// Display error if el is valid HTML Element
if (!(el instanceof Element)) {
console.error(Error(el + ' is not an HTML Element'));
}
// If exists, destroy and reinitialize in child
var ins = classDef.getInstance(el);
if (!!ins) {
ins.destroy();
}
this.el = el;
this.$el = cash(el);
}
/**
* Initializes components
* @param {class} classDef
* @param {Element | NodeList | jQuery} els
* @param {Object} options
*/
_createClass(Component, null, [{
key: "init",
value: function init(classDef, els, options) {
var instances = null;
if (els instanceof Element) {
instances = new classDef(els, options);
} else if (!!els.jquery || els instanceof NodeList) {
var instancesArr = [];
for (var i = 0; i < els.length; i++) {
instancesArr.push(new classDef(els[i], options));
}
instances = instancesArr;
}
return instances;
}
}]);
return Component;
}();
/*
v2.2.0
2017 Julian Garnier
Released under the MIT license
*/
var $jscomp = { scope: {} };$jscomp.defineProperty = "function" == typeof Object.defineProperties ? Object.defineProperty : function (e, r, p) {
if (p.get || p.set) throw new TypeError("ES3 does not support getters and setters.");e != Array.prototype && e != Object.prototype && (e[r] = p.value);
};$jscomp.getGlobal = function (e) {
return "undefined" != typeof window && window === e ? e : "undefined" != typeof global && null != global ? global : e;
};$jscomp.global = $jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX = "jscomp_symbol_";
$jscomp.initSymbol = function () {
$jscomp.initSymbol = function () {};$jscomp.global.Symbol || ($jscomp.global.Symbol = $jscomp.Symbol);
};$jscomp.symbolCounter_ = 0;$jscomp.Symbol = function (e) {
return $jscomp.SYMBOL_PREFIX + (e || "") + $jscomp.symbolCounter_++;
};
$jscomp.initSymbolIterator = function () {
$jscomp.initSymbol();var e = $jscomp.global.Symbol.iterator;e || (e = $jscomp.global.Symbol.iterator = $jscomp.global.Symbol("iterator"));"function" != typeof Array.prototype[e] && $jscomp.defineProperty(Array.prototype, e, { configurable: !0, writable: !0, value: function () {
return $jscomp.arrayIterator(this);
} });$jscomp.initSymbolIterator = function () {};
};$jscomp.arrayIterator = function (e) {
var r = 0;return $jscomp.iteratorPrototype(function () {
return r < e.length ? { done: !1, value: e[r++] } : { done: !0 };
});
};
$jscomp.iteratorPrototype = function (e) {
$jscomp.initSymbolIterator();e = { next: e };e[$jscomp.global.Symbol.iterator] = function () {
return this;
};return e;
};$jscomp.array = $jscomp.array || {};$jscomp.iteratorFromArray = function (e, r) {
$jscomp.initSymbolIterator();e instanceof String && (e += "");var p = 0,
m = { next: function () {
if (p < e.length) {
var u = p++;return { value: r(u, e[u]), done: !1 };
}m.next = function () {
return { done: !0, value: void 0 };
};return m.next();
} };m[Symbol.iterator] = function () {
return m;
};return m;
};
$jscomp.polyfill = function (e, r, p, m) {
if (r) {
p = $jscomp.global;e = e.split(".");for (m = 0; m < e.length - 1; m++) {
var u = e[m];u in p || (p[u] = {});p = p[u];
}e = e[e.length - 1];m = p[e];r = r(m);r != m && null != r && $jscomp.defineProperty(p, e, { configurable: !0, writable: !0, value: r });
}
};$jscomp.polyfill("Array.prototype.keys", function (e) {
return e ? e : function () {
return $jscomp.iteratorFromArray(this, function (e) {
return e;
});
};
}, "es6-impl", "es3");var $jscomp$this = this;
(function (r) {
M.anime = r();
})(function () {
function e(a) {
if (!h.col(a)) try {
return document.querySelectorAll(a);
} catch (c) {}
}function r(a, c) {
for (var d = a.length, b = 2 <= arguments.length ? arguments[1] : void 0, f = [], n = 0; n < d; n++) {
if (n in a) {
var k = a[n];c.call(b, k, n, a) && f.push(k);
}
}return f;
}function p(a) {
return a.reduce(function (a, d) {
return a.concat(h.arr(d) ? p(d) : d);
}, []);
}function m(a) {
if (h.arr(a)) return a;
h.str(a) && (a = e(a) || a);return a instanceof NodeList || a instanceof HTMLCollection ? [].slice.call(a) : [a];
}function u(a, c) {
return a.some(function (a) {
return a === c;
});
}function C(a) {
var c = {},
d;for (d in a) {
c[d] = a[d];
}return c;
}function D(a, c) {
var d = C(a),
b;for (b in a) {
d[b] = c.hasOwnProperty(b) ? c[b] : a[b];
}return d;
}function z(a, c) {
var d = C(a),
b;for (b in c) {
d[b] = h.und(a[b]) ? c[b] : a[b];
}return d;
}function T(a) {
a = a.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, function (a, c, d, k) {
return c + c + d + d + k + k;
});var c = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(a);
a = parseInt(c[1], 16);var d = parseInt(c[2], 16),
c = parseInt(c[3], 16);return "rgba(" + a + "," + d + "," + c + ",1)";
}function U(a) {
function c(a, c, b) {
0 > b && (b += 1);1 < b && --b;return b < 1 / 6 ? a + 6 * (c - a) * b : .5 > b ? c : b < 2 / 3 ? a + (c - a) * (2 / 3 - b) * 6 : a;
}var d = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a) || /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(a);a = parseInt(d[1]) / 360;var b = parseInt(d[2]) / 100,
f = parseInt(d[3]) / 100,
d = d[4] || 1;if (0 == b) f = b = a = f;else {
var n = .5 > f ? f * (1 + b) : f + b - f * b,
k = 2 * f - n,
f = c(k, n, a + 1 / 3),
b = c(k, n, a);a = c(k, n, a - 1 / 3);
}return "rgba(" + 255 * f + "," + 255 * b + "," + 255 * a + "," + d + ")";
}function y(a) {
if (a = /([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(a)) return a[2];
}function V(a) {
if (-1 < a.indexOf("translate") || "perspective" === a) return "px";if (-1 < a.indexOf("rotate") || -1 < a.indexOf("skew")) return "deg";
}function I(a, c) {
return h.fnc(a) ? a(c.target, c.id, c.total) : a;
}function E(a, c) {
if (c in a.style) return getComputedStyle(a).getPropertyValue(c.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()) || "0";
}function J(a, c) {
if (h.dom(a) && u(W, c)) return "transform";if (h.dom(a) && (a.getAttribute(c) || h.svg(a) && a[c])) return "attribute";if (h.dom(a) && "transform" !== c && E(a, c)) return "css";if (null != a[c]) return "object";
}function X(a, c) {
var d = V(c),
d = -1 < c.indexOf("scale") ? 1 : 0 + d;a = a.style.transform;if (!a) return d;for (var b = [], f = [], n = [], k = /(\w+)\((.+?)\)/g; b = k.exec(a);) {
f.push(b[1]), n.push(b[2]);
}a = r(n, function (a, b) {
return f[b] === c;
});return a.length ? a[0] : d;
}function K(a, c) {
switch (J(a, c)) {case "transform":
return X(a, c);case "css":
return E(a, c);case "attribute":
return a.getAttribute(c);}return a[c] || 0;
}function L(a, c) {
var d = /^(\*=|\+=|-=)/.exec(a);if (!d) return a;var b = y(a) || 0;c = parseFloat(c);a = parseFloat(a.replace(d[0], ""));switch (d[0][0]) {case "+":
return c + a + b;case "-":
return c - a + b;case "*":
return c * a + b;}
}function F(a, c) {
return Math.sqrt(Math.pow(c.x - a.x, 2) + Math.pow(c.y - a.y, 2));
}function M(a) {
a = a.points;for (var c = 0, d, b = 0; b < a.numberOfItems; b++) {
var f = a.getItem(b);0 < b && (c += F(d, f));d = f;
}return c;
}function N(a) {
if (a.getTotalLength) return a.getTotalLength();switch (a.tagName.toLowerCase()) {case "circle":
return 2 * Math.PI * a.getAttribute("r");case "rect":
return 2 * a.getAttribute("width") + 2 * a.getAttribute("height");case "line":
return F({ x: a.getAttribute("x1"), y: a.getAttribute("y1") }, { x: a.getAttribute("x2"), y: a.getAttribute("y2") });case "polyline":
return M(a);case "polygon":
var c = a.points;return M(a) + F(c.getItem(c.numberOfItems - 1), c.getItem(0));}
}function Y(a, c) {
function d(b) {
b = void 0 === b ? 0 : b;return a.el.getPointAtLength(1 <= c + b ? c + b : 0);
}var b = d(),
f = d(-1),
n = d(1);switch (a.property) {case "x":
return b.x;case "y":
return b.y;
case "angle":
return 180 * Math.atan2(n.y - f.y, n.x - f.x) / Math.PI;}
}function O(a, c) {
var d = /-?\d*\.?\d+/g,
b;b = h.pth(a) ? a.totalLength : a;if (h.col(b)) {
if (h.rgb(b)) {
var f = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(b);b = f ? "rgba(" + f[1] + ",1)" : b;
} else b = h.hex(b) ? T(b) : h.hsl(b) ? U(b) : void 0;
} else f = (f = y(b)) ? b.substr(0, b.length - f.length) : b, b = c && !/\s/g.test(b) ? f + c : f;b += "";return { original: b, numbers: b.match(d) ? b.match(d).map(Number) : [0], strings: h.str(a) || c ? b.split(d) : [] };
}function P(a) {
a = a ? p(h.arr(a) ? a.map(m) : m(a)) : [];return r(a, function (a, d, b) {
return b.indexOf(a) === d;
});
}function Z(a) {
var c = P(a);return c.map(function (a, b) {
return { target: a, id: b, total: c.length };
});
}function aa(a, c) {
var d = C(c);if (h.arr(a)) {
var b = a.length;2 !== b || h.obj(a[0]) ? h.fnc(c.duration) || (d.duration = c.duration / b) : a = { value: a };
}return m(a).map(function (a, b) {
b = b ? 0 : c.delay;a = h.obj(a) && !h.pth(a) ? a : { value: a };h.und(a.delay) && (a.delay = b);return a;
}).map(function (a) {
return z(a, d);
});
}function ba(a, c) {
var d = {},
b;for (b in a) {
var f = I(a[b], c);h.arr(f) && (f = f.map(function (a) {
return I(a, c);
}), 1 === f.length && (f = f[0]));d[b] = f;
}d.duration = parseFloat(d.duration);d.delay = parseFloat(d.delay);return d;
}function ca(a) {
return h.arr(a) ? A.apply(this, a) : Q[a];
}function da(a, c) {
var d;return a.tweens.map(function (b) {
b = ba(b, c);var f = b.value,
e = K(c.target, a.name),
k = d ? d.to.original : e,
k = h.arr(f) ? f[0] : k,
w = L(h.arr(f) ? f[1] : f, k),
e = y(w) || y(k) || y(e);b.from = O(k, e);b.to = O(w, e);b.start = d ? d.end : a.offset;b.end = b.start + b.delay + b.duration;b.easing = ca(b.easing);b.elasticity = (1E3 - Math.min(Math.max(b.elasticity, 1), 999)) / 1E3;b.isPath = h.pth(f);b.isColor = h.col(b.from.original);b.isColor && (b.round = 1);return d = b;
});
}function ea(a, c) {
return r(p(a.map(function (a) {
return c.map(function (b) {
var c = J(a.target, b.name);if (c) {
var d = da(b, a);b = { type: c, property: b.name, animatable: a, tweens: d, duration: d[d.length - 1].end, delay: d[0].delay };
} else b = void 0;return b;
});
})), function (a) {
return !h.und(a);
});
}function R(a, c, d, b) {
var f = "delay" === a;return c.length ? (f ? Math.min : Math.max).apply(Math, c.map(function (b) {
return b[a];
})) : f ? b.delay : d.offset + b.delay + b.duration;
}function fa(a) {
var c = D(ga, a),
d = D(S, a),
b = Z(a.targets),
f = [],
e = z(c, d),
k;for (k in a) {
e.hasOwnProperty(k) || "targets" === k || f.push({ name: k, offset: e.offset, tweens: aa(a[k], d) });
}a = ea(b, f);return z(c, { children: [], animatables: b, animations: a, duration: R("duration", a, c, d), delay: R("delay", a, c, d) });
}function q(a) {
function c() {
return window.Promise && new Promise(function (a) {
return p = a;
});
}function d(a) {
return g.reversed ? g.duration - a : a;
}function b(a) {
for (var b = 0, c = {}, d = g.animations, f = d.length; b < f;) {
var e = d[b],
k = e.animatable,
h = e.tweens,
n = h.length - 1,
l = h[n];n && (l = r(h, function (b) {
return a < b.end;
})[0] || l);for (var h = Math.min(Math.max(a - l.start - l.delay, 0), l.duration) / l.duration, w = isNaN(h) ? 1 : l.easing(h, l.elasticity), h = l.to.strings, p = l.round, n = [], m = void 0, m = l.to.numbers.length, t = 0; t < m; t++) {
var x = void 0,
x = l.to.numbers[t],
q = l.from.numbers[t],
x = l.isPath ? Y(l.value, w * x) : q + w * (x - q);p && (l.isColor && 2 < t || (x = Math.round(x * p) / p));n.push(x);
}if (l = h.length) for (m = h[0], w = 0; w < l; w++) {
p = h[w + 1], t = n[w], isNaN(t) || (m = p ? m + (t + p) : m + (t + " "));
} else m = n[0];ha[e.type](k.target, e.property, m, c, k.id);e.currentValue = m;b++;
}if (b = Object.keys(c).length) for (d = 0; d < b; d++) {
H || (H = E(document.body, "transform") ? "transform" : "-webkit-transform"), g.animatables[d].target.style[H] = c[d].join(" ");
}g.currentTime = a;g.progress = a / g.duration * 100;
}function f(a) {
if (g[a]) g[a](g);
}function e() {
g.remaining && !0 !== g.remaining && g.remaining--;
}function k(a) {
var k = g.duration,
n = g.offset,
w = n + g.delay,
r = g.currentTime,
x = g.reversed,
q = d(a);if (g.children.length) {
var u = g.children,
v = u.length;
if (q >= g.currentTime) for (var G = 0; G < v; G++) {
u[G].seek(q);
} else for (; v--;) {
u[v].seek(q);
}
}if (q >= w || !k) g.began || (g.began = !0, f("begin")), f("run");if (q > n && q < k) b(q);else if (q <= n && 0 !== r && (b(0), x && e()), q >= k && r !== k || !k) b(k), x || e();f("update");a >= k && (g.remaining ? (t = h, "alternate" === g.direction && (g.reversed = !g.reversed)) : (g.pause(), g.completed || (g.completed = !0, f("complete"), "Promise" in window && (p(), m = c()))), l = 0);
}a = void 0 === a ? {} : a;var h,
t,
l = 0,
p = null,
m = c(),
g = fa(a);g.reset = function () {
var a = g.direction,
c = g.loop;g.currentTime = 0;g.progress = 0;g.paused = !0;g.began = !1;g.completed = !1;g.reversed = "reverse" === a;g.remaining = "alternate" === a && 1 === c ? 2 : c;b(0);for (a = g.children.length; a--;) {
g.children[a].reset();
}
};g.tick = function (a) {
h = a;t || (t = h);k((l + h - t) * q.speed);
};g.seek = function (a) {
k(d(a));
};g.pause = function () {
var a = v.indexOf(g);-1 < a && v.splice(a, 1);g.paused = !0;
};g.play = function () {
g.paused && (g.paused = !1, t = 0, l = d(g.currentTime), v.push(g), B || ia());
};g.reverse = function () {
g.reversed = !g.reversed;t = 0;l = d(g.currentTime);
};g.restart = function () {
g.pause();
g.reset();g.play();
};g.finished = m;g.reset();g.autoplay && g.play();return g;
}var ga = { update: void 0, begin: void 0, run: void 0, complete: void 0, loop: 1, direction: "normal", autoplay: !0, offset: 0 },
S = { duration: 1E3, delay: 0, easing: "easeOutElastic", elasticity: 500, round: 0 },
W = "translateX translateY translateZ rotate rotateX rotateY rotateZ scale scaleX scaleY scaleZ skewX skewY perspective".split(" "),
H,
h = { arr: function (a) {
return Array.isArray(a);
}, obj: function (a) {
return -1 < Object.prototype.toString.call(a).indexOf("Object");
},
pth: function (a) {
return h.obj(a) && a.hasOwnProperty("totalLength");
}, svg: function (a) {
return a instanceof SVGElement;
}, dom: function (a) {
return a.nodeType || h.svg(a);
}, str: function (a) {
return "string" === typeof a;
}, fnc: function (a) {
return "function" === typeof a;
}, und: function (a) {
return "undefined" === typeof a;
}, hex: function (a) {
return (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a)
);
}, rgb: function (a) {
return (/^rgb/.test(a)
);
}, hsl: function (a) {
return (/^hsl/.test(a)
);
}, col: function (a) {
return h.hex(a) || h.rgb(a) || h.hsl(a);
} },
A = function () {
function a(a, d, b) {
return (((1 - 3 * b + 3 * d) * a + (3 * b - 6 * d)) * a + 3 * d) * a;
}return function (c, d, b, f) {
if (0 <= c && 1 >= c && 0 <= b && 1 >= b) {
var e = new Float32Array(11);if (c !== d || b !== f) for (var k = 0; 11 > k; ++k) {
e[k] = a(.1 * k, c, b);
}return function (k) {
if (c === d && b === f) return k;if (0 === k) return 0;if (1 === k) return 1;for (var h = 0, l = 1; 10 !== l && e[l] <= k; ++l) {
h += .1;
}--l;var l = h + (k - e[l]) / (e[l + 1] - e[l]) * .1,
n = 3 * (1 - 3 * b + 3 * c) * l * l + 2 * (3 * b - 6 * c) * l + 3 * c;if (.001 <= n) {
for (h = 0; 4 > h; ++h) {
n = 3 * (1 - 3 * b + 3 * c) * l * l + 2 * (3 * b - 6 * c) * l + 3 * c;if (0 === n) break;var m = a(l, c, b) - k,
l = l - m / n;
}k = l;
} else if (0 === n) k = l;else {
var l = h,
h = h + .1,
g = 0;do {
m = l + (h - l) / 2, n = a(m, c, b) - k, 0 < n ? h = m : l = m;
} while (1e-7 < Math.abs(n) && 10 > ++g);k = m;
}return a(k, d, f);
};
}
};
}(),
Q = function () {
function a(a, b) {
return 0 === a || 1 === a ? a : -Math.pow(2, 10 * (a - 1)) * Math.sin(2 * (a - 1 - b / (2 * Math.PI) * Math.asin(1)) * Math.PI / b);
}var c = "Quad Cubic Quart Quint Sine Expo Circ Back Elastic".split(" "),
d = { In: [[.55, .085, .68, .53], [.55, .055, .675, .19], [.895, .03, .685, .22], [.755, .05, .855, .06], [.47, 0, .745, .715], [.95, .05, .795, .035], [.6, .04, .98, .335], [.6, -.28, .735, .045], a], Out: [[.25, .46, .45, .94], [.215, .61, .355, 1], [.165, .84, .44, 1], [.23, 1, .32, 1], [.39, .575, .565, 1], [.19, 1, .22, 1], [.075, .82, .165, 1], [.175, .885, .32, 1.275], function (b, c) {
return 1 - a(1 - b, c);
}], InOut: [[.455, .03, .515, .955], [.645, .045, .355, 1], [.77, 0, .175, 1], [.86, 0, .07, 1], [.445, .05, .55, .95], [1, 0, 0, 1], [.785, .135, .15, .86], [.68, -.55, .265, 1.55], function (b, c) {
return .5 > b ? a(2 * b, c) / 2 : 1 - a(-2 * b + 2, c) / 2;
}] },
b = { linear: A(.25, .25, .75, .75) },
f = {},
e;for (e in d) {
f.type = e, d[f.type].forEach(function (a) {
return function (d, f) {
b["ease" + a.type + c[f]] = h.fnc(d) ? d : A.apply($jscomp$this, d);
};
}(f)), f = { type: f.type };
}return b;
}(),
ha = { css: function (a, c, d) {
return a.style[c] = d;
}, attribute: function (a, c, d) {
return a.setAttribute(c, d);
}, object: function (a, c, d) {
return a[c] = d;
}, transform: function (a, c, d, b, f) {
b[f] || (b[f] = []);b[f].push(c + "(" + d + ")");
} },
v = [],
B = 0,
ia = function () {
function a() {
B = requestAnimationFrame(c);
}function c(c) {
var b = v.length;if (b) {
for (var d = 0; d < b;) {
v[d] && v[d].tick(c), d++;
}a();
} else cancelAnimationFrame(B), B = 0;
}return a;
}();q.version = "2.2.0";q.speed = 1;q.running = v;q.remove = function (a) {
a = P(a);for (var c = v.length; c--;) {
for (var d = v[c], b = d.animations, f = b.length; f--;) {
u(a, b[f].animatable.target) && (b.splice(f, 1), b.length || d.pause());
}
}
};q.getValue = K;q.path = function (a, c) {
var d = h.str(a) ? e(a)[0] : a,
b = c || 100;return function (a) {
return { el: d, property: a, totalLength: N(d) * (b / 100) };
};
};q.setDashoffset = function (a) {
var c = N(a);a.setAttribute("stroke-dasharray", c);return c;
};q.bezier = A;q.easings = Q;q.timeline = function (a) {
var c = q(a);c.pause();c.duration = 0;c.add = function (d) {
c.children.forEach(function (a) {
a.began = !0;a.completed = !0;
});m(d).forEach(function (b) {
var d = z(b, D(S, a || {}));d.targets = d.targets || a.targets;b = c.duration;var e = d.offset;d.autoplay = !1;d.direction = c.direction;d.offset = h.und(e) ? b : L(e, b);c.began = !0;c.completed = !0;c.seek(d.offset);d = q(d);d.began = !0;d.completed = !0;d.duration > b && (c.duration = d.duration);c.children.push(d);
});c.seek(0);c.reset();c.autoplay && c.restart();return c;
};return c;
};q.random = function (a, c) {
return Math.floor(Math.random() * (c - a + 1)) + a;
};return q;
});
/*! cash-dom 1.3.5, https://github.com/kenwheeler/cash @license MIT */
(function (factory) {
window.cash = factory();
})(function () {
var doc = document,
win = window,
ArrayProto = Array.prototype,
slice = ArrayProto.slice,
filter = ArrayProto.filter,
push = ArrayProto.push;
var noop = function () {},
isFunction = function (item) {
// @see https://crbug.com/568448
return typeof item === typeof noop && item.call;
},
isString = function (item) {
return typeof item === typeof "";
};
var idMatch = /^#[\w-]*$/,
classMatch = /^\.[\w-]*$/,
htmlMatch = /<.+>/,
singlet = /^\w+$/;
function find(selector, context) {
context = context || doc;
var elems = classMatch.test(selector) ? context.getElementsByClassName(selector.slice(1)) : singlet.test(selector) ? context.getElementsByTagName(selector) : context.querySelectorAll(selector);
return elems;
}
var frag;
function parseHTML(str) {
if (!frag) {
frag = doc.implementation.createHTMLDocument(null);
var base = frag.createElement("base");
base.href = doc.location.href;
frag.head.appendChild(base);
}
frag.body.innerHTML = str;
return frag.body.childNodes;
}
function onReady(fn) {
if (doc.readyState !== "loading") {
fn();
} else {
doc.addEventListener("DOMContentLoaded", fn);
}
}
function Init(selector, context) {
if (!selector) {
return this;
}
// If already a cash collection, don't do any further processing
if (selector.cash && selector !== win) {
return selector;
}
var elems = selector,
i = 0,
length;
if (isString(selector)) {
elems = idMatch.test(selector) ?
// If an ID use the faster getElementById check
doc.getElementById(selector.slice(1)) : htmlMatch.test(selector) ?
// If HTML, parse it into real elements
parseHTML(selector) :
// else use `find`
find(selector, context);
// If function, use as shortcut for DOM ready
} else if (isFunction(selector)) {
onReady(selector);return this;
}
if (!elems) {
return this;
}
// If a single DOM element is passed in or received via ID, return the single element
if (elems.nodeType || elems === win) {
this[0] = elems;
this.length = 1;
} else {
// Treat like an array and loop through each item.
length = this.length = elems.length;
for (; i < length; i++) {
this[i] = elems[i];
}
}
return this;
}
function cash(selector, context) {
return new Init(selector, context);
}
var fn = cash.fn = cash.prototype = Init.prototype = { // jshint ignore:line
cash: true,
length: 0,
push: push,
splice: ArrayProto.splice,
map: ArrayProto.map,
init: Init
};
Object.defineProperty(fn, "constructor", { value: cash });
cash.parseHTML = parseHTML;
cash.noop = noop;
cash.isFunction = isFunction;
cash.isString = isString;
cash.extend = fn.extend = function (target) {
target = target || {};
var args = slice.call(arguments),
length = args.length,
i = 1;
if (args.length === 1) {
target = this;
i = 0;
}
for (; i < length; i++) {
if (!args[i]) {
continue;
}
for (var key in args[i]) {
if (args[i].hasOwnProperty(key)) {
target[key] = args[i][key];
}
}
}
return target;
};
function each(collection, callback) {
var l = collection.length,
i = 0;
for (; i < l; i++) {
if (callback.call(collection[i], collection[i], i, collection) === false) {
break;
}
}
}
function matches(el, selector) {
var m = el && (el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector || el.oMatchesSelector);
return !!m && m.call(el, selector);
}
function getCompareFunction(selector) {
return (
/* Use browser's `matches` function if string */
isString(selector) ? matches :
/* Match a cash element */
selector.cash ? function (el) {
return selector.is(el);
} :
/* Direct comparison */
function (el, selector) {
return el === selector;
}
);
}
function unique(collection) {
return cash(slice.call(collection).filter(function (item, index, self) {
return self.indexOf(item) === index;
}));
}
cash.extend({
merge: function (first, second) {
var len = +second.length,
i = first.length,
j = 0;
for (; j < len; i++, j++) {
first[i] = second[j];
}
first.length = i;
return first;
},
each: each,
matches: matches,
unique: unique,
isArray: Array.isArray,
isNumeric: function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
var uid = cash.uid = "_cash" + Date.now();
function getDataCache(node) {
return node[uid] = node[uid] || {};
}
function setData(node, key, value) {
return getDataCache(node)[key] = value;
}
function getData(node, key) {
var c = getDataCache(node);
if (c[key] === undefined) {
c[key] = node.dataset ? node.dataset[key] : cash(node).attr("data-" + key);
}
return c[key];
}
function removeData(node, key) {
var c = getDataCache(node);
if (c) {
delete c[key];
} else if (node.dataset) {
delete node.dataset[key];
} else {
cash(node).removeAttr("data-" + name);
}
}
fn.extend({
data: function (name, value) {
if (isString(name)) {
return value === undefined ? getData(this[0], name) : this.each(function (v) {
return setData(v, name, value);
});
}
for (var key in name) {
this.data(key, name[key]);
}
return this;
},
removeData: function (key) {
return this.each(function (v) {
return removeData(v, key);
});
}
});
var notWhiteMatch = /\S+/g;
function getClasses(c) {
return isString(c) && c.match(notWhiteMatch);
}
function hasClass(v, c) {
return v.classList ? v.classList.contains(c) : new RegExp("(^| )" + c + "( |$)", "gi").test(v.className);
}
function addClass(v, c, spacedName) {
if (v.classList) {
v.classList.add(c);
} else if (spacedName.indexOf(" " + c + " ")) {
v.className += " " + c;
}
}
function removeClass(v, c) {
if (v.classList) {
v.classList.remove(c);
} else {
v.className = v.className.replace(c, "");
}
}
fn.extend({
addClass: function (c) {
var classes = getClasses(c);
return classes ? this.each(function (v) {
var spacedName = " " + v.className + " ";
each(classes, function (c) {
addClass(v, c, spacedName);
});
}) : this;
},
attr: function (name, value) {
if (!name) {
return undefined;
}
if (isString(name)) {
if (value === undefined) {
return this[0] ? this[0].getAttribute ? this[0].getAttribute(name) : this[0][name] : undefined;
}
return this.each(function (v) {
if (v.setAttribute) {
v.setAttribute(name, value);
} else {
v[name] = value;
}
});
}
for (var key in name) {
this.attr(key, name[key]);
}
return this;
},
hasClass: function (c) {
var check = false,
classes = getClasses(c);
if (classes && classes.length) {
this.each(function (v) {
check = hasClass(v, classes[0]);
return !check;
});
}
return check;
},
prop: function (name, value) {
if (isString(name)) {
return value === undefined ? this[0][name] : this.each(function (v) {
v[name] = value;
});
}
for (var key in name) {
this.prop(key, name[key]);
}
return this;
},
removeAttr: function (name) {
return this.each(function (v) {
if (v.removeAttribute) {
v.removeAttribute(name);
} else {
delete v[name];
}
});
},
removeClass: function (c) {
if (!arguments.length) {
return this.attr("class", "");
}
var classes = getClasses(c);
return classes ? this.each(function (v) {
each(classes, function (c) {
removeClass(v, c);
});
}) : this;
},
removeProp: function (name) {
return this.each(function (v) {
delete v[name];
});
},
toggleClass: function (c, state) {
if (state !== undefined) {
return this[state ? "addClass" : "removeClass"](c);
}
var classes = getClasses(c);
return classes ? this.each(function (v) {
var spacedName = " " + v.className + " ";
each(classes, function (c) {
if (hasClass(v, c)) {
removeClass(v, c);
} else {
addClass(v, c, spacedName);
}
});
}) : this;
} });
fn.extend({
add: function (selector, context) {
return unique(cash.merge(this, cash(selector, context)));
},
each: function (callback) {
each(this, callback);
return this;
},
eq: function (index) {
return cash(this.get(index));
},
filter: function (selector) {
if (!selector) {
return this;
}
var comparator = isFunction(selector) ? selector : getCompareFunction(selector);
return cash(filter.call(this, function (e) {
return comparator(e, selector);
}));
},
first: function () {
return this.eq(0);
},
get: function (index) {
if (index === undefined) {
return slice.call(this);
}
return index < 0 ? this[index + this.length] : this[index];
},
index: function (elem) {
var child = elem ? cash(elem)[0] : this[0],
collection = elem ? this : cash(child).parent().children();
return slice.call(collection).indexOf(child);
},
last: function () {
return this.eq(-1);
}
});
var camelCase = function () {
var camelRegex = /(?:^\w|[A-Z]|\b\w)/g,
whiteSpace = /[\s-_]+/g;
return function (str) {
return str.replace(camelRegex, function (letter, index) {
return letter[index === 0 ? "toLowerCase" : "toUpperCase"]();
}).replace(whiteSpace, "");
};
}();
var getPrefixedProp = function () {
var cache = {},
doc = document,
div = doc.createElement("div"),
style = div.style;
return function (prop) {
prop = camelCase(prop);
if (cache[prop]) {
return cache[prop];
}
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
prefixes = ["webkit", "moz", "ms", "o"],
props = (prop + " " + prefixes.join(ucProp + " ") + ucProp).split(" ");
each(props, function (p) {
if (p in style) {
cache[p] = prop = cache[prop] = p;
return false;
}
});
return cache[prop];
};
}();
cash.prefixedProp = getPrefixedProp;
cash.camelCase = camelCase;
fn.extend({
css: function (prop, value) {
if (isString(prop)) {
prop = getPrefixedProp(prop);
return arguments.length > 1 ? this.each(function (v) {
return v.style[prop] = value;
}) : win.getComputedStyle(this[0])[prop];
}
for (var key in prop) {
this.css(key, prop[key]);
}
return this;
}
});
function compute(el, prop) {
return parseInt(win.getComputedStyle(el[0], null)[prop], 10) || 0;
}
each(["Width", "Height"], function (v) {
var lower = v.toLowerCase();
fn[lower] = function () {
return this[0].getBoundingClientRect()[lower];
};
fn["inner" + v] = function () {
return this[0]["client" + v];
};
fn["outer" + v] = function (margins) {
return this[0]["offset" + v] + (margins ? compute(this, "margin" + (v === "Width" ? "Left" : "Top")) + compute(this, "margin" + (v === "Width" ? "Right" : "Bottom")) : 0);
};
});
function registerEvent(node, eventName, callback) {
var eventCache = getData(node, "_cashEvents") || setData(node, "_cashEvents", {});
eventCache[eventName] = eventCache[eventName] || [];
eventCache[eventName].push(callback);
node.addEventListener(eventName, callback);
}
function removeEvent(node, eventName, callback) {
var events = getData(node, "_cashEvents"),
eventCache = events && events[eventName],
index;
if (!eventCache) {
return;
}
if (callback) {
node.removeEventListener(eventName, callback);
index = eventCache.indexOf(callback);
if (index >= 0) {
eventCache.splice(index, 1);
}
} else {
each(eventCache, function (event) {
node.removeEventListener(eventName, event);
});
eventCache = [];
}
}
fn.extend({
off: function (eventName, callback) {
return this.each(function (v) {
return removeEvent(v, eventName, callback);
});
},
on: function (eventName, delegate, callback, runOnce) {
// jshint ignore:line
var originalCallback;
if (!isString(eventName)) {
for (var key in eventName) {
this.on(key, delegate, eventName[key]);
}
return this;
}
if (isFunction(delegate)) {
callback = delegate;
delegate = null;
}
if (eventName === "ready") {
onReady(callback);
return this;
}
if (delegate) {
originalCallback = callback;
callback = function (e) {
var t = e.target;
while (!matches(t, delegate)) {
if (t === this || t === null) {
return t = false;
}
t = t.parentNode;
}
if (t) {
originalCallback.call(t, e);
}
};
}
return this.each(function (v) {
var finalCallback = callback;
if (runOnce) {
finalCallback = function () {
callback.apply(this, arguments);
removeEvent(v, eventName, finalCallback);
};
}
registerEvent(v, eventName, finalCallback);
});
},
one: function (eventName, delegate, callback) {
return this.on(eventName, delegate, callback, true);
},
ready: onReady,
/**
* Modified
* Triggers browser event
* @param String eventName
* @param Object data - Add properties to event object
*/
trigger: function (eventName, data) {
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, true, false);
evt = this.extend(evt, data);
return this.each(function (v) {
return v.dispatchEvent(evt);
});
}
}
});
function encode(name, value) {
return "&" + encodeURIComponent(name) + "=" + encodeURIComponent(value).replace(/%20/g, "+");
}
function getSelectMultiple_(el) {
var values = [];
each(el.options, function (o) {
if (o.selected) {
values.push(o.value);
}
});
return values.length ? values : null;
}
function getSelectSingle_(el) {
var selectedIndex = el.selectedIndex;
return selectedIndex >= 0 ? el.options[selectedIndex].value : null;
}
function getValue(el) {
var type = el.type;
if (!type) {
return null;
}
switch (type.toLowerCase()) {
case "select-one":
return getSelectSingle_(el);
case "select-multiple":
return getSelectMultiple_(el);
case "radio":
return el.checked ? el.value : null;
case "checkbox":
return el.checked ? el.value : null;
default:
return el.value ? el.value : null;
}
}
fn.extend({
serialize: function () {
var query = "";
each(this[0].elements || this, function (el) {
if (el.disabled || el.tagName === "FIELDSET") {
return;
}
var name = el.name;
switch (el.type.toLowerCase()) {
case "file":
case "reset":
case "submit":
case "button":
break;
case "select-multiple":
var values = getValue(el);
if (values !== null) {
each(values, function (value) {
query += encode(name, value);
});
}
break;
default:
var value = getValue(el);
if (value !== null) {
query += encode(name, value);
}
}
});
return query.substr(1);
},
val: function (value) {
if (value === undefined) {
return getValue(this[0]);
}
return this.each(function (v) {
return v.value = value;
});
}
});
function insertElement(el, child, prepend) {
if (prepend) {
var first = el.childNodes[0];
el.insertBefore(child, first);
} else {
el.appendChild(child);
}
}
function insertContent(parent, child, prepend) {
var str = isString(child);
if (!str && child.length) {
each(child, function (v) {
return insertContent(parent, v, prepend);
});
return;
}
each(parent, str ? function (v) {
return v.insertAdjacentHTML(prepend ? "afterbegin" : "beforeend", child);
} : function (v, i) {
return insertElement(v, i === 0 ? child : child.cloneNode(true), prepend);
});
}
fn.extend({
after: function (selector) {
cash(selector).insertAfter(this);
return this;
},
append: function (content) {
insertContent(this, content);
return this;
},
appendTo: function (parent) {
insertContent(cash(parent), this);
return this;
},
before: function (selector) {
cash(selector).insertBefore(this);
return this;
},
clone: function () {
return cash(this.map(function (v) {
return v.cloneNode(true);
}));
},
empty: function () {
this.html("");
return this;
},
html: function (content) {
if (content === undefined) {
return this[0].innerHTML;
}
var source = content.nodeType ? content[0].outerHTML : content;
return this.each(function (v) {
return v.innerHTML = source;
});
},
insertAfter: function (selector) {
var _this = this;
cash(selector).each(function (el, i) {
var parent = el.parentNode,
sibling = el.nextSibling;
_this.each(function (v) {
parent.insertBefore(i === 0 ? v : v.cloneNode(true), sibling);
});
});
return this;
},
insertBefore: function (selector) {
var _this2 = this;
cash(selector).each(function (el, i) {
var parent = el.parentNode;
_this2.each(function (v) {
parent.insertBefore(i === 0 ? v : v.cloneNode(true), el);
});
});
return this;
},
prepend: function (content) {
insertContent(this, content, true);
return this;
},
prependTo: function (parent) {
insertContent(cash(parent), this, true);
return this;
},
remove: function () {
return this.each(function (v) {
if (!!v.parentNode) {
return v.parentNode.removeChild(v);
}
});
},
text: function (content) {
if (content === undefined) {
return this[0].textContent;
}
return this.each(function (v) {
return v.textContent = content;
});
}
});
var docEl = doc.documentElement;
fn.extend({
position: function () {
var el = this[0];
return {
left: el.offsetLeft,
top: el.offsetTop
};
},
offset: function () {
var rect = this[0].getBoundingClientRect();
return {
top: rect.top + win.pageYOffset - docEl.clientTop,
left: rect.left + win.pageXOffset - docEl.clientLeft
};
},
offsetParent: function () {
return cash(this[0].offsetParent);
}
});
fn.extend({
children: function (selector) {
var elems = [];
this.each(function (el) {
push.apply(elems, el.children);
});
elems = unique(elems);
return !selector ? elems : elems.filter(function (v) {
return matches(v, selector);
});
},
closest: function (selector) {
if (!selector || this.length < 1) {
return cash();
}
if (this.is(selector)) {
return this.filter(selector);
}
return this.parent().closest(selector);
},
is: function (selector) {
if (!selector) {
return false;
}
var match = false,
comparator = getCompareFunction(selector);
this.each(function (el) {
match = comparator(el, selector);
return !match;
});
return match;
},
find: function (selector) {
if (!selector || selector.nodeType) {
return cash(selector && this.has(selector).length ? selector : null);
}
var elems = [];
this.each(function (el) {
push.apply(elems, find(selector, el));
});
return unique(elems);
},
has: function (selector) {
var comparator = isString(selector) ? function (el) {
return find(selector, el).length !== 0;
} : function (el) {
return el.contains(selector);
};
return this.filter(comparator);
},
next: function () {
return cash(this[0].nextElementSibling);
},
not: function (selector) {
if (!selector) {
return this;
}
var comparator = getCompareFunction(selector);
return this.filter(function (el) {
return !comparator(el, selector);
});
},
parent: function () {
var result = [];
this.each(function (item) {
if (item && item.parentNode) {
result.push(item.parentNode);
}
});
return unique(result);
},
parents: function (selector) {
var last,
result = [];
this.each(function (item) {
last = item;
while (last && last.parentNode && last !== doc.body.parentNode) {
last = last.parentNode;
if (!selector || selector && matches(last, selector)) {
result.push(last);
}
}
});
return unique(result);
},
prev: function () {
return cash(this[0].previousElementSibling);
},
siblings: function (selector) {
var collection = this.parent().children(selector),
el = this[0];
return collection.filter(function (i) {
return i !== el;
});
}
});
return cash;
});
(function ($, anim) {
$(document).on('click', '.card', function (e) {
if ($(this).children('.card-reveal').length) {
var $card = $(e.target).closest('.card');
if ($card.data('initialOverflow') === undefined) {
$card.data('initialOverflow', $card.css('overflow') === undefined ? '' : $card.css('overflow'));
}
var $cardReveal = $(this).find('.card-reveal');
if ($(e.target).is($('.card-reveal .card-title')) || $(e.target).is($('.card-reveal .card-title i'))) {
// Make Reveal animate down and display none
anim({
targets: $cardReveal[0],
translateY: 0,
duration: 225,
easing: 'easeInOutQuad',
complete: function (anim) {
var el = anim.animatables[0].target;
$(el).css({ display: 'none' });
$card.css('overflow', $card.data('initialOverflow'));
}
});
} else if ($(e.target).is($('.card .activator')) || $(e.target).is($('.card .activator i'))) {
$card.css('overflow', 'hidden');
$cardReveal.css({ display: 'block' });
anim({
targets: $cardReveal[0],
translateY: '-100%',
duration: 300,
easing: 'easeInOutQuad'
});
}
}
});
})(cash, M.anime);
(function ($, anim) {
'use strict';
var _defaults = {
duration: 300,
onShow: null,
swipeable: false,
responsiveThreshold: Infinity // breakpoint for swipeable
};
/**
* @class
*
*/
var Tabs = function (_Component) {
_inherits(Tabs, _Component);
/**
* Construct Tabs instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Tabs(el, options) {
_classCallCheck(this, Tabs);
var _this3 = _possibleConstructorReturn(this, (Tabs.__proto__ || Object.getPrototypeOf(Tabs)).call(this, Tabs, el, options));
_this3.el.M_Tabs = _this3;
/**
* Options for the Tabs
* @member Tabs#options
* @prop {Number} duration
* @prop {Function} onShow
* @prop {Boolean} swipeable
* @prop {Number} responsiveThreshold
*/
_this3.options = $.extend({}, Tabs.defaults, options);
// Setup
_this3.$tabLinks = _this3.$el.children('li.tab').children('a');
_this3.index = 0;
_this3._setTabsAndTabWidth();
_this3._setupActiveTabLink();
_this3._createIndicator();
if (_this3.options.swipeable) {
_this3._setupSwipeableTabs();
} else {
_this3._setupNormalTabs();
}
_this3._setupEventHandlers();
return _this3;
}
_createClass(Tabs, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
// iob
if (this._indicator) this._indicator.parentNode.removeChild(this._indicator);
if (this.options.swipeable) {
this._teardownSwipeableTabs();
} else {
this._teardownNormalTabs();
}
this.$el[0].M_Tabs = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleWindowResizeBound = this._handleWindowResize.bind(this);
window.addEventListener('resize', this._handleWindowResizeBound);
this._handleTabClickBound = this._handleTabClick.bind(this);
this.el.addEventListener('click', this._handleTabClickBound);
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
window.removeEventListener('resize', this._handleWindowResizeBound);
this.el.removeEventListener('click', this._handleTabClickBound);
}
/**
* Handle window Resize
*/
}, {
key: "_handleWindowResize",
value: function _handleWindowResize() {
this._setTabsAndTabWidth();
if (this.tabWidth !== 0 && this.tabsWidth !== 0) {
// this._indicator.style.left = this._calcLeftPos(this.$activeTabLink) + 'px'; // iob
// this._indicator.style.right = this._calcRightPos(this.$activeTabLink) + 'px'; // iob
}
}
/**
* Handle tab click
* @param {Event} e
*/
}, {
key: "_handleTabClick",
value: function _handleTabClick(e) {
var _this4 = this;
var tab = $(e.target).closest('li.tab');
var tabLink = $(e.target).closest('a');
// Handle click on tab link only
if (!tabLink.length || !tabLink.parent().hasClass('tab')) {
return;
}
if (tab.hasClass('disabled')) {
e.preventDefault();
return;
}
// Act as regular link if target attribute is specified.
if (!!tabLink.attr("target")) {
return;
}
this._setTabsAndTabWidth();
// Make the old tab inactive.
this.$activeTabLink.removeClass('active');
var $oldContent = this.$content;
// Update the variables with the new link and content
this.$activeTabLink = tabLink;
this.$content = $(M.escapeHash(tabLink[0].hash));
this.$tabLinks = this.$el.children('li.tab').children('a');
// Make the tab active.
this.$activeTabLink.addClass('active');
var prevIndex = this.index;
this.index = Math.max(this.$tabLinks.index(tabLink), 0);
// Swap content
if (this.options.swipeable) {
if (this._tabsCarousel) {
this._tabsCarousel.set(this.index, function () {
if (typeof _this4.options.onShow === "function") {
_this4.options.onShow.call(_this4, _this4.$content[0]);
}
});
}
} else {
if (this.$content.length) {
this.$content[0].style.display = 'block';
this.$content.addClass('active');
if (typeof this.options.onShow === 'function') {
this.options.onShow.call(this, this.$content[0]);
}
if ($oldContent.length && !$oldContent.is(this.$content)) {
$oldContent[0].style.display = 'none';
$oldContent.removeClass('active');
}
}
}
// Update indicator
this._animateIndicator(prevIndex);
// Prevent the anchor's default click action
e.preventDefault();
}
/**
* Generate elements for tab indicator.
*/
}, {
key: "_createIndicator",
value: function _createIndicator() {
var _this5 = this;
// iob
return;
var indicator = document.createElement('li');
indicator.classList.add('indicator');
this.el.appendChild(indicator);
this._indicator = indicator;
setTimeout(function () {
_this5._indicator.style.left = _this5._calcLeftPos(_this5.$activeTabLink) + 'px';
_this5._indicator.style.right = _this5._calcRightPos(_this5.$activeTabLink) + 'px';
}, 0);
}
/**
* Setup first active tab link.
*/
}, {
key: "_setupActiveTabLink",
value: function _setupActiveTabLink() {
// If the location.hash matches one of the links, use that as the active tab.
this.$activeTabLink = $(this.$tabLinks.filter('[href="' + location.hash + '"]'));
// If no match is found, use the first link or any with class 'active' as the initial active tab.
if (this.$activeTabLink.length === 0) {
this.$activeTabLink = this.$el.children('li.tab').children('a.active').first();
}
if (this.$activeTabLink.length === 0) {
this.$activeTabLink = this.$el.children('li.tab').children('a').first();
}
this.$tabLinks.removeClass('active');
this.$activeTabLink[0].classList.add('active');
this.index = Math.max(this.$tabLinks.index(this.$activeTabLink), 0);
if (this.$activeTabLink.length) {
this.$content = $(M.escapeHash(this.$activeTabLink[0].hash));
this.$content.addClass('active');
}
}
/**
* Setup swipeable tabs
*/
}, {
key: "_setupSwipeableTabs",
value: function _setupSwipeableTabs() {
var _this6 = this;
// Change swipeable according to responsive threshold
if (window.innerWidth > this.options.responsiveThreshold) {
this.options.swipeable = false;
}
var $tabsContent = $();
this.$tabLinks.each(function (link) {
var $currContent = $(M.escapeHash(link.hash));
$currContent.addClass('carousel-item');
$tabsContent = $tabsContent.add($currContent);
});
var $tabsWrapper = $('<div class="tabs-content carousel carousel-slider"></div>');
$tabsContent.first().before($tabsWrapper);
$tabsWrapper.append($tabsContent);
$tabsContent[0].style.display = '';
this._tabsCarousel = M.Carousel.init($tabsWrapper[0], {
fullWidth: true,
noWrap: true,
onCycleTo: function (item) {
var prevIndex = _this6.index;
_this6.index = $(item).index();
_this6.$activeTabLink.removeClass('active');
_this6.$activeTabLink = _this6.$tabLinks.eq(_this6.index);
_this6.$activeTabLink.addClass('active');
_this6._animateIndicator(prevIndex);
if (typeof _this6.options.onShow === "function") {
_this6.options.onShow.call(_this6, _this6.$content[0]);
}
}
});
}
/**
* Teardown normal tabs.
*/
}, {
key: "_teardownSwipeableTabs",
value: function _teardownSwipeableTabs() {
var $tabsWrapper = this._tabsCarousel.$el;
this._tabsCarousel.destroy();
// Unwrap
$tabsWrapper.after($tabsWrapper.children());
$tabsWrapper.remove();
}
/**
* Setup normal tabs.
*/
}, {
key: "_setupNormalTabs",
value: function _setupNormalTabs() {
// Hide Tabs Content
this.$tabLinks.not(this.$activeTabLink).each(function (link) {
if (!!link.hash) {
var $currContent = $(M.escapeHash(link.hash));
if ($currContent.length) {
$currContent[0].style.display = 'none';
}
}
});
}
/**
* Teardown normal tabs.
*/
}, {
key: "_teardownNormalTabs",
value: function _teardownNormalTabs() {
// show Tabs Content
this.$tabLinks.each(function (link) {
if (!!link.hash) {
var $currContent = $(M.escapeHash(link.hash));
if ($currContent.length) {
$currContent[0].style.display = '';
}
}
});
}
/**
* set tabs and tab width
*/
}, {
key: "_setTabsAndTabWidth",
value: function _setTabsAndTabWidth() {
this.tabsWidth = this.$el.width();
this.tabWidth = Math.max(this.tabsWidth, this.el.scrollWidth) / this.$tabLinks.length;
}
/**
* Finds right attribute for indicator based on active tab.
* @param {cash} el
*/
}, {
key: "_calcRightPos",
value: function _calcRightPos(el) {
//return Math.ceil(this.tabsWidth - el.position().left - el[0].getBoundingClientRect().width);
// iob
return Math.ceil(this.tabsWidth - el.offset().left - el[0].getBoundingClientRect().width);
}
/**
* Finds left attribute for indicator based on active tab.
* @param {cash} el
*/
}, {
key: "_calcLeftPos",
value: function _calcLeftPos(el) {
//return Math.floor(el.position().left);
// iob
return Math.floor(el.offset().left);
}
}, {
key: "updateTabIndicator",
value: function updateTabIndicator() {
this._animateIndicator(this.index);
}
/**
* Animates Indicator to active tab.
* @param {Number} prevIndex
*/
}, {
key: "_animateIndicator",
value: function _animateIndicator(prevIndex) {
// iob
return;
var leftDelay = 0,
rightDelay = 0;
if (this.index - prevIndex >= 0) {
leftDelay = 90;
} else {
rightDelay = 90;
}
// Animate
var animOptions = {
targets: this._indicator,
left: {
value: this._calcLeftPos(this.$activeTabLink),
delay: leftDelay
},
right: {
value: this._calcRightPos(this.$activeTabLink),
delay: rightDelay
},
duration: this.options.duration,
easing: 'easeOutQuad'
};
anim.remove(this._indicator);
anim(animOptions);
}
/**
* Select tab.
* @param {String} tabId
*/
}, {
key: "select",
value: function select(tabId) {
var tab = this.$tabLinks.filter('[href="#' + tabId + '"]');
if (tab.length) {
tab.trigger('click');
}
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Tabs.__proto__ || Object.getPrototypeOf(Tabs), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Tabs;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Tabs;
}(Component);
window.M.Tabs = Tabs;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Tabs, 'mtabs', 'M_Tabs'); // iob tabs => mtabs
}
})(cash, M.anime);
(function ($, anim) {
'use strict';
var _defaults = {
alignment: 'left',
autoFocus: true,
constrainWidth: true,
container: null,
coverTrigger: true,
closeOnClick: true,
hover: false,
inDuration: 150,
outDuration: 250,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
onItemClick: null
};
/**
* @class
*/
var Dropdown = function (_Component2) {
_inherits(Dropdown, _Component2);
function Dropdown(el, options) {
_classCallCheck(this, Dropdown);
var _this7 = _possibleConstructorReturn(this, (Dropdown.__proto__ || Object.getPrototypeOf(Dropdown)).call(this, Dropdown, el, options));
_this7.el.M_Dropdown = _this7;
Dropdown._dropdowns.push(_this7);
_this7.id = M.getIdFromTrigger(el);
_this7.dropdownEl = document.getElementById(_this7.id);
_this7.$dropdownEl = $(_this7.dropdownEl);
/**
* Options for the dropdown
* @member Dropdown#options
* @prop {String} [alignment='left'] - Edge which the dropdown is aligned to
* @prop {Boolean} [autoFocus=true] - Automatically focus dropdown el for keyboard
* @prop {Boolean} [constrainWidth=true] - Constrain width to width of the button
* @prop {Element} container - Container element to attach dropdown to (optional)
* @prop {Boolean} [coverTrigger=true] - Place dropdown over trigger
* @prop {Boolean} [closeOnClick=true] - Close on click of dropdown item
* @prop {Boolean} [hover=false] - Open dropdown on hover
* @prop {Number} [inDuration=150] - Duration of open animation in ms
* @prop {Number} [outDuration=250] - Duration of close animation in ms
* @prop {Function} onOpenStart - Function called when dropdown starts opening
* @prop {Function} onOpenEnd - Function called when dropdown finishes opening
* @prop {Function} onCloseStart - Function called when dropdown starts closing
* @prop {Function} onCloseEnd - Function called when dropdown finishes closing
*/
_this7.options = $.extend({}, Dropdown.defaults, options);
/**
* Describes open/close state of dropdown
* @type {Boolean}
*/
_this7.isOpen = false;
/**
* Describes if dropdown content is scrollable
* @type {Boolean}
*/
_this7.isScrollable = false;
/**
* Describes if touch moving on dropdown content
* @type {Boolean}
*/
_this7.isTouchMoving = false;
_this7.focusedIndex = -1;
_this7.filterQuery = [];
// Move dropdown-content after dropdown-trigger
if (!!_this7.options.container) {
$(_this7.options.container).append(_this7.dropdownEl);
} else {
_this7.$el.after(_this7.dropdownEl);
}
_this7._makeDropdownFocusable();
_this7._resetFilterQueryBound = _this7._resetFilterQuery.bind(_this7);
_this7._handleDocumentClickBound = _this7._handleDocumentClick.bind(_this7);
_this7._handleDocumentTouchmoveBound = _this7._handleDocumentTouchmove.bind(_this7);
_this7._handleDropdownClickBound = _this7._handleDropdownClick.bind(_this7);
_this7._handleDropdownKeydownBound = _this7._handleDropdownKeydown.bind(_this7);
_this7._handleTriggerKeydownBound = _this7._handleTriggerKeydown.bind(_this7);
_this7._setupEventHandlers();
return _this7;
}
_createClass(Dropdown, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._resetDropdownStyles();
this._removeEventHandlers();
Dropdown._dropdowns.splice(Dropdown._dropdowns.indexOf(this), 1);
this.el.M_Dropdown = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
// Trigger keydown handler
this.el.addEventListener('keydown', this._handleTriggerKeydownBound);
// Item click handler
this.dropdownEl.addEventListener('click', this._handleDropdownClickBound);
this.dropdownEl.addEventListener('touchend', this._handleDropdownClickBound); //iob
// Hover event handlers
if (this.options.hover) {
this._handleMouseEnterBound = this._handleMouseEnter.bind(this);
this.el.addEventListener('mouseenter', this._handleMouseEnterBound);
this._handleMouseLeaveBound = this._handleMouseLeave.bind(this);
this.el.addEventListener('mouseleave', this._handleMouseLeaveBound);
this.dropdownEl.addEventListener('mouseleave', this._handleMouseLeaveBound);
// Click event handlers
} else {
this._handleClickBound = this._handleClick.bind(this);
this.el.addEventListener('click', this._handleClickBound);
}
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('keydown', this._handleTriggerKeydownBound);
this.dropdownEl.removeEventListener('click', this._handleDropdownClickBound);
this.dropdownEl.removeEventListener('touchend', this._handleDropdownClickBound); //iob
if (this.options.hover) {
this.el.removeEventListener('mouseenter', this._handleMouseEnterBound);
this.el.removeEventListener('mouseleave', this._handleMouseLeaveBound);
this.dropdownEl.removeEventListener('mouseleave', this._handleMouseLeaveBound);
} else {
this.el.removeEventListener('click', this._handleClickBound);
}
}
}, {
key: "_setupTemporaryEventHandlers",
value: function _setupTemporaryEventHandlers() {
// Use capture phase event handler to prevent click
document.body.addEventListener('click', this._handleDocumentClickBound, true);
document.body.addEventListener('touchend', this._handleDocumentClickBound);
document.body.addEventListener('touchmove', this._handleDocumentTouchmoveBound);
this.dropdownEl.addEventListener('keydown', this._handleDropdownKeydownBound);
}
}, {
key: "_removeTemporaryEventHandlers",
value: function _removeTemporaryEventHandlers() {
// Use capture phase event handler to prevent click
document.body.removeEventListener('click', this._handleDocumentClickBound, true);
document.body.removeEventListener('touchend', this._handleDocumentClickBound);
document.body.removeEventListener('touchmove', this._handleDocumentTouchmoveBound);
this.dropdownEl.removeEventListener('keydown', this._handleDropdownKeydownBound);
}
}, {
key: "_handleClick",
value: function _handleClick(e) {
e.preventDefault();
this.open();
}
}, {
key: "_handleMouseEnter",
value: function _handleMouseEnter() {
this.open();
}
}, {
key: "_handleMouseLeave",
value: function _handleMouseLeave(e) {
var toEl = e.toElement || e.relatedTarget;
var leaveToDropdownContent = !!$(toEl).closest('.dropdown-content').length;
var leaveToActiveDropdownTrigger = false;
var $closestTrigger = $(toEl).closest('.dropdown-trigger');
if ($closestTrigger.length && !!$closestTrigger[0].M_Dropdown && $closestTrigger[0].M_Dropdown.isOpen) {
leaveToActiveDropdownTrigger = true;
}
// Close hover dropdown if mouse did not leave to either active dropdown-trigger or dropdown-content
if (!leaveToActiveDropdownTrigger && !leaveToDropdownContent) {
this.close();
}
}
}, {
key: "_handleDocumentClick",
value: function _handleDocumentClick(e) {
var _this8 = this;
var $target = $(e.target);
if (this.options.closeOnClick && $target.closest('.dropdown-content').length && !this.isTouchMoving) {
// isTouchMoving to check if scrolling on mobile.
setTimeout(function () {
_this8.close();
}, 0);
} else if ($target.closest('.dropdown-trigger').length || !$target.closest('.dropdown-content').length) {
setTimeout(function () {
_this8.close();
}, 0);
}
this.isTouchMoving = false;
}
}, {
key: "_handleTriggerKeydown",
value: function _handleTriggerKeydown(e) {
// ARROW DOWN OR ENTER WHEN SELECT IS CLOSED - open Dropdown
if ((e.which === M.keys.ARROW_DOWN || e.which === M.keys.ENTER) && !this.isOpen) {
e.preventDefault();
this.open();
}
}
/**
* Handle Document Touchmove
* @param {Event} e
*/
}, {
key: "_handleDocumentTouchmove",
value: function _handleDocumentTouchmove(e) {
var $target = $(e.target);
if ($target.closest('.dropdown-content').length) {
this.isTouchMoving = true;
}
}
/**
* Handle Dropdown Click
* @param {Event} e
*/
}, {
key: "_handleDropdownClick",
value: function _handleDropdownClick(e) {
// onItemClick callback
if (typeof this.options.onItemClick === 'function') {
var itemEl = $(e.target).closest('li')[0];
this.options.onItemClick.call(this, itemEl);
}
}
/**
* Handle Dropdown Keydown
* @param {Event} e
*/
}, {
key: "_handleDropdownKeydown",
value: function _handleDropdownKeydown(e) {
if (e.which === M.keys.TAB) {
e.preventDefault();
this.close();
// Navigate down dropdown list
} else if ((e.which === M.keys.ARROW_DOWN || e.which === M.keys.ARROW_UP) && this.isOpen) {
e.preventDefault();
var direction = e.which === M.keys.ARROW_DOWN ? 1 : -1;
var newFocusedIndex = this.focusedIndex;
var foundNewIndex = false;
do {
newFocusedIndex = newFocusedIndex + direction;
if (!!this.dropdownEl.children[newFocusedIndex] && this.dropdownEl.children[newFocusedIndex].tabIndex !== -1) {
foundNewIndex = true;
break;
}
} while (newFocusedIndex < this.dropdownEl.children.length && newFocusedIndex >= 0);
if (foundNewIndex) {
this.focusedIndex = newFocusedIndex;
this._focusFocusedItem();
}
// ENTER selects choice on focused item
} else if (e.which === M.keys.ENTER && this.isOpen) {
// Search for <a> and <button>
var focusedElement = this.dropdownEl.children[this.focusedIndex];
var $activatableElement = $(focusedElement).find('a, button').first();
// Click a or button tag if exists, otherwise click li tag
if (!!$activatableElement.length) {
$activatableElement[0].click();
} else if (!!focusedElement) {
focusedElement.click();
}
// Close dropdown on ESC
} else if (e.which === M.keys.ESC && this.isOpen) {
e.preventDefault();
this.close();
}
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9, 13, 27, 38, 40];
if (letter && nonLetters.indexOf(e.which) === -1) {
this.filterQuery.push(letter);
var string = this.filterQuery.join(''),
newOptionEl = $(this.dropdownEl).find('li').filter(function (el) {
return $(el).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOptionEl) {
this.focusedIndex = $(newOptionEl).index();
this._focusFocusedItem();
}
}
this.filterTimeout = setTimeout(this._resetFilterQueryBound, 1000);
}
/**
* Setup dropdown
*/
}, {
key: "_resetFilterQuery",
value: function _resetFilterQuery() {
this.filterQuery = [];
}
}, {
key: "_resetDropdownStyles",
value: function _resetDropdownStyles() {
this.$dropdownEl.css({
display: '',
width: '',
height: '',
left: '',
top: '',
'transform-origin': '',
transform: '',
opacity: ''
});
}
}, {
key: "_makeDropdownFocusable",
value: function _makeDropdownFocusable() {
// Needed for arrow key navigation
this.dropdownEl.tabIndex = 0;
// Only set tabindex if it hasn't been set by user
$(this.dropdownEl).children().each(function (el) {
if (!el.getAttribute('tabindex')) {
el.setAttribute('tabindex', 0);
}
});
}
}, {
key: "_focusFocusedItem",
value: function _focusFocusedItem() {
if (this.focusedIndex >= 0 && this.focusedIndex < this.dropdownEl.children.length && this.options.autoFocus) {
this.dropdownEl.children[this.focusedIndex].focus();
}
}
}, {
key: "_getDropdownPosition",
value: function _getDropdownPosition() {
var offsetParentBRect = this.el.offsetParent.getBoundingClientRect();
var triggerBRect = this.el.getBoundingClientRect();
var dropdownBRect = this.dropdownEl.getBoundingClientRect();
var idealHeight = dropdownBRect.height;
var idealWidth = dropdownBRect.width;
var idealXPos = triggerBRect.left - dropdownBRect.left;
var idealYPos = triggerBRect.top - dropdownBRect.top;
var dropdownBounds = {
left: idealXPos,
top: idealYPos,
height: idealHeight,
width: idealWidth
};
// Container here will be closest ancestor with overflow: hidden
var closestOverflowParent = !!this.dropdownEl.offsetParent ? this.dropdownEl.offsetParent : this.dropdownEl.parentNode;
var alignments = M.checkPossibleAlignments(this.el, closestOverflowParent, dropdownBounds, this.options.coverTrigger ? 0 : triggerBRect.height);
var verticalAlignment = 'top';
var horizontalAlignment = this.options.alignment;
idealYPos += this.options.coverTrigger ? 0 : triggerBRect.height;
// Reset isScrollable
this.isScrollable = false;
if (!alignments.top) {
if (alignments.bottom) {
verticalAlignment = 'bottom';
} else {
this.isScrollable = true;
// Determine which side has most space and cutoff at correct height
if (alignments.spaceOnTop > alignments.spaceOnBottom) {
verticalAlignment = 'bottom';
idealHeight += alignments.spaceOnTop;
idealYPos -= alignments.spaceOnTop;
} else {
idealHeight += alignments.spaceOnBottom;
}
}
}
// If preferred horizontal alignment is possible
if (!alignments[horizontalAlignment]) {
var oppositeAlignment = horizontalAlignment === 'left' ? 'right' : 'left';
if (alignments[oppositeAlignment]) {
horizontalAlignment = oppositeAlignment;
} else {
// Determine which side has most space and cutoff at correct height
if (alignments.spaceOnLeft > alignments.spaceOnRight) {
horizontalAlignment = 'right';
idealWidth += alignments.spaceOnLeft;
idealXPos -= alignments.spaceOnLeft;
} else {
horizontalAlignment = 'left';
idealWidth += alignments.spaceOnRight;
}
}
}
if (verticalAlignment === 'bottom') {
idealYPos = idealYPos - dropdownBRect.height + (this.options.coverTrigger ? triggerBRect.height : 0);
}
if (horizontalAlignment === 'right') {
idealXPos = idealXPos - dropdownBRect.width + triggerBRect.width;
}
return {
x: idealXPos,
y: idealYPos,
verticalAlignment: verticalAlignment,
horizontalAlignment: horizontalAlignment,
height: idealHeight,
width: idealWidth
};
}
/**
* Animate in dropdown
*/
}, {
key: "_animateIn",
value: function _animateIn() {
var _this9 = this;
anim.remove(this.dropdownEl);
anim({
targets: this.dropdownEl,
opacity: {
value: [0, 1],
easing: 'easeOutQuad'
},
scaleX: [0.3, 1],
scaleY: [0.3, 1],
duration: this.options.inDuration,
easing: 'easeOutQuint',
complete: function (anim) {
if (_this9.options.autoFocus) {
_this9.dropdownEl.focus();
}
// onOpenEnd callback
if (typeof _this9.options.onOpenEnd === 'function') {
_this9.options.onOpenEnd.call(_this9, _this9.el);
}
}
});
}
/**
* Animate out dropdown
*/
}, {
key: "_animateOut",
value: function _animateOut() {
var _this10 = this;
anim.remove(this.dropdownEl);
anim({
targets: this.dropdownEl,
opacity: {
value: 0,
easing: 'easeOutQuint'
},
scaleX: 0.3,
scaleY: 0.3,
duration: this.options.outDuration,
easing: 'easeOutQuint',
complete: function (anim) {
_this10._resetDropdownStyles();
// onCloseEnd callback
if (typeof _this10.options.onCloseEnd === 'function') {
_this10.options.onCloseEnd.call(_this10, _this10.el);
}
}
});
}
/**
* Place dropdown
*/
}, {
key: "_placeDropdown",
value: function _placeDropdown() {
// Set width before calculating positionInfo
var idealWidth = this.options.constrainWidth ? this.el.getBoundingClientRect().width : this.dropdownEl.getBoundingClientRect().width;
this.dropdownEl.style.width = idealWidth + 'px';
var positionInfo = this._getDropdownPosition();
this.dropdownEl.style.left = positionInfo.x + 'px';
this.dropdownEl.style.top = positionInfo.y + 'px';
this.dropdownEl.style.height = positionInfo.height + 'px';
this.dropdownEl.style.width = positionInfo.width + 'px';
this.dropdownEl.style.transformOrigin = (positionInfo.horizontalAlignment === 'left' ? '0' : '100%') + " " + (positionInfo.verticalAlignment === 'top' ? '0' : '100%');
}
/**
* Open Dropdown
*/
}, {
key: "open",
value: function open() {
if (this.isOpen) {
return;
}
this.isOpen = true;
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el);
}
// Reset styles
this._resetDropdownStyles();
this.dropdownEl.style.display = 'block';
this._placeDropdown();
this._animateIn();
this._setupTemporaryEventHandlers();
}
/**
* Close Dropdown
*/
}, {
key: "close",
value: function close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
this.focusedIndex = -1;
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
this._animateOut();
this._removeTemporaryEventHandlers();
if (this.options.autoFocus) {
this.el.focus();
}
}
/**
* Recalculate dimensions
*/
}, {
key: "recalculateDimensions",
value: function recalculateDimensions() {
if (this.isOpen) {
this.$dropdownEl.css({
width: '',
height: '',
left: '',
top: '',
'transform-origin': ''
});
this._placeDropdown();
}
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Dropdown.__proto__ || Object.getPrototypeOf(Dropdown), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Dropdown;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Dropdown;
}(Component);
/**
* @static
* @memberof Dropdown
*/
Dropdown._dropdowns = [];
window.M.Dropdown = Dropdown;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Dropdown, 'dropdown', 'M_Dropdown');
}
})(cash, M.anime);
(function ($, anim) {
'use strict';
var _defaults = {
html: '',
displayLength: 4000,
inDuration: 300,
outDuration: 375,
classes: '',
completeCallback: null,
activationPercent: 0.8
};
var Toast = function () {
function Toast(options) {
_classCallCheck(this, Toast);
/**
* Options for the toast
* @member Toast#options
*/
this.options = $.extend({}, Toast.defaults, options);
this.message = this.options.html;
/**
* Describes current pan state toast
* @type {Boolean}
*/
this.panning = false;
/**
* Time remaining until toast is removed
*/
this.timeRemaining = this.options.displayLength;
if (Toast._toasts.length === 0) {
Toast._createContainer(options); // iob
}
// Create new toast
Toast._toasts.push(this);
var toastElement = this._createToast();
toastElement.M_Toast = this;
this.el = toastElement;
this._animateIn();
this._setTimer();
}
_createClass(Toast, [{
key: "_createToast",
/**
* Create toast and append it to toast container
*/
value: function _createToast() {
var toast = document.createElement('div');
toast.classList.add('toast');
// Add custom classes onto toast
if (!!this.options.classes.length) {
$(toast).addClass(this.options.classes);
}
// Set content
if (typeof HTMLElement === 'object' ? this.message instanceof HTMLElement : this.message && typeof this.message === 'object' && this.message !== null && this.message.nodeType === 1 && typeof this.message.nodeName === 'string') {
toast.appendChild(this.message);
// Check if it is jQuery object
} else if (!!this.message.jquery) {
$(toast).append(this.message[0]);
// Insert as html;
} else {
toast.innerHTML = this.message;
}
// Append toasft
Toast._container.appendChild(toast);
return toast;
}
/**
* Animate in toast
*/
}, {
key: "_animateIn",
value: function _animateIn() {
// Animate toast in
anim({
targets: this.el,
top: 0,
opacity: 1,
duration: 300,
easing: 'easeOutCubic'
});
}
/**
* Create setInterval which automatically removes toast when timeRemaining >= 0
* has been reached
*/
}, {
key: "_setTimer",
value: function _setTimer() {
var _this11 = this;
if (this.timeRemaining !== Infinity) {
this.counterInterval = setInterval(function () {
// If toast is not being dragged, decrease its time remaining
if (!_this11.panning) {
_this11.timeRemaining -= 20;
}
// Animate toast out
if (_this11.timeRemaining <= 0) {
_this11.dismiss();
}
}, 20);
}
}
/**
* Dismiss toast with animation
*/
}, {
key: "dismiss",
value: function dismiss() {
var _this12 = this;
window.clearInterval(this.counterInterval);
var activationDistance = this.el.offsetWidth * this.options.activationPercent;
if (this.wasSwiped) {
this.el.style.transition = 'transform .05s, opacity .05s';
this.el.style.transform = "translateX(" + activationDistance + "px)";
this.el.style.opacity = 0;
}
anim({
targets: this.el,
opacity: 0,
marginTop: -40,
duration: this.options.outDuration,
easing: 'easeOutExpo',
complete: function () {
// Call the optional callback
if (typeof _this12.options.completeCallback === 'function') {
_this12.options.completeCallback();
}
// Remove toast from DOM
_this12.el.parentNode.removeChild(_this12.el);
Toast._toasts.splice(Toast._toasts.indexOf(_this12), 1);
if (Toast._toasts.length === 0) {
Toast._removeContainer();
}
}
});
}
}], [{
key: "getInstance",
/**
* Get Instance
*/
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Toast;
}
/**
* Append toast container and add event handlers
*/
}, {
key: "_createContainer",
value: function _createContainer(options) {
// iob
var container = document.createElement('div');
container.setAttribute('id', 'toast-container');
// Add event handler
container.addEventListener('touchstart', Toast._onDragStart);
container.addEventListener('touchmove', Toast._onDragMove);
container.addEventListener('touchend', Toast._onDragEnd);
container.addEventListener('mousedown', Toast._onDragStart);
document.addEventListener('mousemove', Toast._onDragMove);
document.addEventListener('mouseup', Toast._onDragEnd);
if (options.parentSelector) {
// iob start
options.parentSelector.appendChild(container);
} else {
document.body.appendChild(container);
} // iob end
Toast._container = container;
}
/**
* Remove toast container and event handlers
*/
}, {
key: "_removeContainer",
value: function _removeContainer() {
// Add event handler
document.removeEventListener('mousemove', Toast._onDragMove);
document.removeEventListener('mouseup', Toast._onDragEnd);
Toast._container.parentNode.removeChild(Toast._container);
Toast._container = null;
}
/**
* Begin drag handler
* @param {Event} e
*/
}, {
key: "_onDragStart",
value: function _onDragStart(e) {
if (e.target && $(e.target).closest('.toast').length) {
var $toast = $(e.target).closest('.toast');
var toast = $toast[0].M_Toast;
toast.panning = true;
Toast._draggedToast = toast;
toast.el.classList.add('panning');
toast.el.style.transition = '';
toast.startingXPos = Toast._xPos(e);
toast.time = Date.now();
toast.xPos = Toast._xPos(e);
}
}
/**
* Drag move handler
* @param {Event} e
*/
}, {
key: "_onDragMove",
value: function _onDragMove(e) {
if (!!Toast._draggedToast) {
e.preventDefault();
var toast = Toast._draggedToast;
toast.deltaX = Math.abs(toast.xPos - Toast._xPos(e));
toast.xPos = Toast._xPos(e);
toast.velocityX = toast.deltaX / (Date.now() - toast.time);
toast.time = Date.now();
var totalDeltaX = toast.xPos - toast.startingXPos;
var activationDistance = toast.el.offsetWidth * toast.options.activationPercent;
toast.el.style.transform = "translateX(" + totalDeltaX + "px)";
toast.el.style.opacity = 1 - Math.abs(totalDeltaX / activationDistance);
}
}
/**
* End drag handler
*/
}, {
key: "_onDragEnd",
value: function _onDragEnd() {
if (!!Toast._draggedToast) {
var toast = Toast._draggedToast;
toast.panning = false;
toast.el.classList.remove('panning');
var totalDeltaX = toast.xPos - toast.startingXPos;
var activationDistance = toast.el.offsetWidth * toast.options.activationPercent;
var shouldBeDismissed = Math.abs(totalDeltaX) > activationDistance || toast.velocityX > 1;
// Remove toast
if (shouldBeDismissed) {
toast.wasSwiped = true;
toast.dismiss();
// Animate toast back to original position
} else {
toast.el.style.transition = 'transform .2s, opacity .2s';
toast.el.style.transform = '';
toast.el.style.opacity = '';
}
Toast._draggedToast = null;
}
}
/**
* Get x position of mouse or touch event
* @param {Event} e
*/
}, {
key: "_xPos",
value: function _xPos(e) {
if (e.targetTouches && e.targetTouches.length >= 1) {
return e.targetTouches[0].clientX;
}
// mouse event
return e.clientX;
}
/**
* Remove all toasts
*/
}, {
key: "dismissAll",
value: function dismissAll() {
for (var toastIndex in Toast._toasts) {
Toast._toasts[toastIndex].dismiss();
}
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Toast;
}();
/**
* @static
* @memberof Toast
* @type {Array.<Toast>}
*/
Toast._toasts = [];
/**
* @static
* @memberof Toast
*/
Toast._container = null;
/**
* @static
* @memberof Toast
* @type {Toast}
*/
Toast._draggedToast = null;
M.Toast = Toast;
M.toast = function (options) {
return new Toast(options);
};
})(cash, M.anime);
(function ($, anim) {
'use strict';
var _defaults = {
opacity: 0.5,
inDuration: 250,
outDuration: 250,
onOpenStart: null,
onOpenEnd: null,
onCloseStart: null,
onCloseEnd: null,
dismissible: true,
startingTop: '4%',
endingTop: '10%'
};
/**
* @class
*
*/
var Modal = function (_Component3) {
_inherits(Modal, _Component3);
/**
* Construct Modal instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Modal(el, options) {
_classCallCheck(this, Modal);
var _this13 = _possibleConstructorReturn(this, (Modal.__proto__ || Object.getPrototypeOf(Modal)).call(this, Modal, el, options));
_this13.el.M_Modal = _this13;
/**
* Options for the modal
* @member Modal#options
* @prop {Number} [opacity=0.5] - Opacity of the modal overlay
* @prop {Number} [inDuration=250] - Length in ms of enter transition
* @prop {Number} [outDuration=250] - Length in ms of exit transition
* @prop {Function} onOpenStart - Callback function called before modal is opened
* @prop {Function} onOpenEnd - Callback function called after modal is opened
* @prop {Function} onCloseStart - Callback function called before modal is closed
* @prop {Function} onCloseEnd - Callback function called after modal is closed
* @prop {Boolean} [dismissible=true] - Allow modal to be dismissed by keyboard or overlay click
* @prop {String} [startingTop='4%'] - startingTop
* @prop {String} [endingTop='10%'] - endingTop
*/
_this13.options = $.extend({}, Modal.defaults, options);
/**
* Describes open/close state of modal
* @type {Boolean}
*/
_this13.isOpen = false;
_this13.id = _this13.$el.attr('id');
_this13._openingTrigger = undefined;
_this13.$overlay = $('<div class="modal-overlay"></div>');
Modal._increment++;
Modal._count++;
_this13.$overlay[0].style.zIndex = 1000 + Modal._increment * 2;
_this13.el.style.zIndex = 1000 + Modal._increment * 2 + 1;
_this13._setupEventHandlers();
return _this13;
}
_createClass(Modal, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
Modal._count--;
this._removeEventHandlers();
this.el.removeAttribute('style');
this.$overlay.remove();
this.el.M_Modal = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleOverlayClickBound = this._handleOverlayClick.bind(this);
this._handleModalCloseClickBound = this._handleModalCloseClick.bind(this);
if (Modal._count === 1) {
document.body.addEventListener('click', this._handleTriggerClick);
}
this.$overlay[0].addEventListener('click', this._handleOverlayClickBound);
this.el.addEventListener('click', this._handleModalCloseClickBound);
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
if (Modal._count === 0) {
document.body.removeEventListener('click', this._handleTriggerClick);
}
this.$overlay[0].removeEventListener('click', this._handleOverlayClickBound);
this.el.removeEventListener('click', this._handleModalCloseClickBound);
}
/**
* Handle Trigger Click
* @param {Event} e
*/
}, {
key: "_handleTriggerClick",
value: function _handleTriggerClick(e) {
var $trigger = $(e.target).closest('.modal-trigger');
if ($trigger.length) {
var modalId = M.getIdFromTrigger($trigger[0]);
var modalInstance = document.getElementById(modalId).M_Modal;
if (modalInstance) {
modalInstance.open($trigger);
}
e.preventDefault();
}
}
/**
* Handle Overlay Click
*/
}, {
key: "_handleOverlayClick",
value: function _handleOverlayClick() {
if (this.options.dismissible) {
this.close();
}
}
/**
* Handle Modal Close Click
* @param {Event} e
*/
}, {
key: "_handleModalCloseClick",
value: function _handleModalCloseClick(e) {
var $closeTrigger = $(e.target).closest('.modal-close');
if ($closeTrigger.length) {
this.close();
}
}
/**
* Handle Keydown
* @param {Event} e
*/
}, {
key: "_handleKeydown",
value: function _handleKeydown(e) {
// ESC key
if (e.keyCode === 27 && this.options.dismissible) {
this.close();
}
}
/**
* Animate in modal
*/
}, {
key: "_animateIn",
value: function _animateIn() {
var _this14 = this;
// Set initial styles
$.extend(this.el.style, {
display: 'block',
opacity: 0
});
$.extend(this.$overlay[0].style, {
display: 'block',
opacity: 0
});
// Animate overlay
anim({
targets: this.$overlay[0],
opacity: this.options.opacity,
duration: this.options.inDuration,
easing: 'easeOutQuad'
});
// Define modal animation options
var enterAnimOptions = {
targets: this.el,
duration: this.options.inDuration,
easing: 'easeOutCubic',
// Handle modal onOpenEnd callback
complete: function () {
if (typeof _this14.options.onOpenEnd === 'function') {
_this14.options.onOpenEnd.call(_this14, _this14.el, _this14._openingTrigger);
}
}
};
// Bottom sheet animation
if (this.el.classList.contains('bottom-sheet')) {
$.extend(enterAnimOptions, {
bottom: 0,
opacity: 1
});
anim(enterAnimOptions);
// Normal modal animation
} else {
$.extend(enterAnimOptions, {
top: [this.options.startingTop, this.options.endingTop],
opacity: 1,
scaleX: [.8, 1],
scaleY: [.8, 1]
});
anim(enterAnimOptions);
}
}
/**
* Animate out modal
*/
}, {
key: "_animateOut",
value: function _animateOut() {
var _this15 = this;
// Animate overlay
anim({
targets: this.$overlay[0],
opacity: 0,
duration: this.options.outDuration,
easing: 'easeOutQuart'
});
// Define modal animation options
var exitAnimOptions = {
targets: this.el,
duration: this.options.outDuration,
easing: 'easeOutCubic',
// Handle modal ready callback
complete: function () {
_this15.el.style.display = 'none';
_this15.$overlay.remove();
// Call onCloseEnd callback
if (typeof _this15.options.onCloseEnd === 'function') {
_this15.options.onCloseEnd.call(_this15, _this15.el);
}
}
};
// Bottom sheet animation
if (this.el.classList.contains('bottom-sheet')) {
$.extend(exitAnimOptions, {
bottom: '-100%',
opacity: 0
});
anim(exitAnimOptions);
// Normal modal animation
} else {
$.extend(exitAnimOptions, {
top: [this.options.endingTop, this.options.startingTop],
opacity: 0,
scaleX: 0.8,
scaleY: 0.8
});
anim(exitAnimOptions);
}
}
/**
* Open Modal
* @param {cash} [$trigger]
*/
}, {
key: "open",
value: function open($trigger) {
if (this.isOpen) {
return;
}
this.isOpen = true;
// Set opening trigger, undefined indicates modal was opened by javascript
this._openingTrigger = !!$trigger ? $trigger[0] : undefined;
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, this.el, this._openingTrigger);
}
var body = document.body;
body.style.overflow = 'hidden';
this.el.classList.add('open');
this.el.insertAdjacentElement('afterend', this.$overlay[0]);
if (this.options.dismissible) {
this._handleKeydownBound = this._handleKeydown.bind(this);
document.addEventListener('keydown', this._handleKeydownBound);
}
anim.remove(this.el);
anim.remove(this.$overlay[0]);
this._animateIn();
return this;
}
/**
* Close Modal
*/
}, {
key: "close",
value: function close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
// Call onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, this.el);
}
this.el.classList.remove('open');
document.body.style.overflow = '';
if (this.options.dismissible) {
document.removeEventListener('keydown', this._handleKeydownBound);
}
anim.remove(this.el);
anim.remove(this.$overlay[0]);
this._animateOut();
return this;
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Modal.__proto__ || Object.getPrototypeOf(Modal), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Modal;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Modal;
}(Component);
/**
* @static
* @memberof Modal
*/
Modal._increment = 0;
/**
* @static
* @memberof Modal
*/
Modal._count = 0;
M.Modal = Modal;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Modal, 'modal', 'M_Modal');
}
})(cash, M.anime);
(function ($) {
'use strict';
var _defaults = {
classes: '',
dropdownOptions: {}
};
/**
* @class
*
*/
var FormSelect = function (_Component4) {
_inherits(FormSelect, _Component4);
/**
* Construct FormSelect instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
function FormSelect(el, options) {
_classCallCheck(this, FormSelect);
// Don't init if browser default version
var _this16 = _possibleConstructorReturn(this, (FormSelect.__proto__ || Object.getPrototypeOf(FormSelect)).call(this, FormSelect, el, options));
if (_this16.$el.hasClass('browser-default')) {
return _possibleConstructorReturn(_this16);
}
_this16.el.M_FormSelect = _this16;
/**
* Options for the select
* @member FormSelect#options
*/
_this16.options = $.extend({}, FormSelect.defaults, options);
_this16.isMultiple = _this16.$el.prop('multiple');
// Setup
_this16.el.tabIndex = -1;
_this16._keysSelected = {};
_this16._valueDict = {}; // Maps key to original and generated option element.
_this16._setupDropdown();
_this16._setupEventHandlers();
return _this16;
}
_createClass(FormSelect, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
this._removeDropdown();
this.el.M_FormSelect = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
var _this17 = this;
this._handleSelectChangeBound = this._handleSelectChange.bind(this);
this._handleOptionClickBound = this._handleOptionClick.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
$(this.dropdownOptions).find('li:not(.optgroup)').each(function (el) {
el.addEventListener('click', _this17._handleOptionClickBound);
el.addEventListener('touchend', _this17._handleOptionClickBound); //iob
});
this.el.addEventListener('change', this._handleSelectChangeBound);
this.input.addEventListener('click', this._handleInputClickBound);
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
var _this18 = this;
$(this.dropdownOptions).find('li:not(.optgroup)').each(function (el) {
el.removeEventListener('click', _this18._handleOptionClickBound);
el.addEventListener('touchend', _this18._handleOptionClickBound); //iob
});
this.el.removeEventListener('change', this._handleSelectChangeBound);
this.input.removeEventListener('click', this._handleInputClickBound);
}
/**
* Handle Select Change
* @param {Event} e
*/
}, {
key: "_handleSelectChange",
value: function _handleSelectChange(e) {
this._setValueToInput();
}
/**
* Handle Option Click
* @param {Event} e
*/
}, {
key: "_handleOptionClick",
value: function _handleOptionClick(e) {
//e.preventDefault();
var option = $(e.target).closest('li')[0];
var key = option.id;
if (!$(option).hasClass('disabled') && !$(option).hasClass('optgroup') && key.length) {
var selected = true;
if (this.isMultiple) {
// Deselect placeholder option if still selected.
var placeholderOption = $(this.dropdownOptions).find('li.disabled.selected');
if (placeholderOption.length) {
placeholderOption.removeClass('selected');
placeholderOption.find('input[type="checkbox"]').prop('checked', false);
this._toggleEntryFromArray(placeholderOption[0].id);
}
selected = this._toggleEntryFromArray(key);
} else {
$(this.dropdownOptions).find('li').removeClass('selected');
$(option).toggleClass('selected', selected);
}
// Set selected on original select option
// Only trigger if selected state changed
var prevSelected = $(this._valueDict[key].el).prop('selected');
if (prevSelected !== selected) {
$(this._valueDict[key].el).prop('selected', selected);
this.$el.trigger('change');
}
}
e.stopPropagation();
}
/**
* Handle Input Click
*/
}, {
key: "_handleInputClick",
value: function _handleInputClick() {
if (this.dropdown && this.dropdown.isOpen) {
this._setValueToInput();
this._setSelectedStates();
}
}
/**
* Setup dropdown
*/
}, {
key: "_setupDropdown",
value: function _setupDropdown() {
var _this19 = this;
this.wrapper = document.createElement('div');
$(this.wrapper).addClass('select-wrapper ' + this.options.classes);
this.$el.before($(this.wrapper));
this.wrapper.appendChild(this.el);
if (this.el.disabled) {
this.wrapper.classList.add('disabled');
}
// Create dropdown
this.$selectOptions = this.$el.children('option, optgroup');
this.dropdownOptions = document.createElement('ul');
this.dropdownOptions.id = "select-options-" + M.guid();
$(this.dropdownOptions).addClass('dropdown-content select-dropdown ' + (this.isMultiple ? 'multiple-select-dropdown' : ''));
// Create dropdown structure.
if (this.$selectOptions.length) {
this.$selectOptions.each(function (el) {
if ($(el).is('option')) {
// Direct descendant option.
var optionEl = void 0;
if (_this19.isMultiple) {
optionEl = _this19._appendOptionWithIcon(_this19.$el, el, 'multiple');
} else {
optionEl = _this19._appendOptionWithIcon(_this19.$el, el);
}
_this19._addOptionToValueDict(el, optionEl);
} else if ($(el).is('optgroup')) {
// Optgroup.
var selectOptions = $(el).children('option');
$(_this19.dropdownOptions).append($('<li class="optgroup"><span>' + el.getAttribute('label') + '</span></li>')[0]);
selectOptions.each(function (el) {
var optionEl = _this19._appendOptionWithIcon(_this19.$el, el, 'optgroup-option');
_this19._addOptionToValueDict(el, optionEl);
});
}
});
}
this.$el.after(this.dropdownOptions);
// Add input dropdown
this.input = document.createElement('input');
$(this.input).addClass('select-dropdown dropdown-trigger');
this.input.setAttribute('type', 'text');
this.input.setAttribute('readonly', 'true');
this.input.setAttribute('data-target', this.dropdownOptions.id);
if (this.el.disabled) {
$(this.input).prop('disabled', 'true');
}
this.$el.before(this.input);
this._setValueToInput();
// Add caret
var dropdownIcon = $('<svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>');
this.$el.before(dropdownIcon[0]);
// Initialize dropdown
if (!this.el.disabled) {
var dropdownOptions = $.extend({}, this.options.dropdownOptions);
// Add callback for centering selected option when dropdown content is scrollable
dropdownOptions.onOpenEnd = function (el) {
var selectedOption = $(_this19.dropdownOptions).find('.selected').first();
if (selectedOption.length) {
// Focus selected option in dropdown
M.keyDown = true;
_this19.dropdown.focusedIndex = selectedOption.index();
_this19.dropdown._focusFocusedItem();
M.keyDown = false;
// Handle scrolling to selected option
if (_this19.dropdown.isScrollable) {
var scrollOffset = selectedOption[0].getBoundingClientRect().top - _this19.dropdownOptions.getBoundingClientRect().top; // scroll to selected option
scrollOffset -= _this19.dropdownOptions.clientHeight / 2; // center in dropdown
_this19.dropdownOptions.scrollTop = scrollOffset;
}
}
};
if (this.isMultiple) {
dropdownOptions.closeOnClick = false;
}
this.dropdown = M.Dropdown.init(this.input, dropdownOptions);
}
// Add initial selections
this._setSelectedStates();
}
/**
* Add option to value dict
* @param {Element} el original option element
* @param {Element} optionEl generated option element
*/
}, {
key: "_addOptionToValueDict",
value: function _addOptionToValueDict(el, optionEl) {
var index = Object.keys(this._valueDict).length;
var key = this.dropdownOptions.id + index;
var obj = {};
optionEl.id = key;
obj.el = el;
obj.optionEl = optionEl;
this._valueDict[key] = obj;
}
/**
* Remove dropdown
*/
}, {
key: "_removeDropdown",
value: function _removeDropdown() {
$(this.wrapper).find('.caret').remove();
$(this.input).remove();
$(this.dropdownOptions).remove();
$(this.wrapper).before(this.$el);
$(this.wrapper).remove();
}
/**
* Setup dropdown
* @param {Element} select select element
* @param {Element} option option element from select
* @param {String} type
* @return {Element} option element added
*/
}, {
key: "_appendOptionWithIcon",
value: function _appendOptionWithIcon(select, option, type) {
// Add disabled attr if disabled
var disabledClass = option.disabled ? 'disabled ' : '';
var optgroupClass = type === 'optgroup-option' ? 'optgroup-option ' : '';
var multipleCheckbox = this.isMultiple ? "<label><input type=\"checkbox\"" + disabledClass + "\"/><span>" + option.innerHTML + "</span></label>" : option.innerHTML;
var liEl = $('<li></li>');
var spanEl = $('<span></span>');
spanEl.html(multipleCheckbox);
liEl.addClass(disabledClass + " " + optgroupClass);
liEl.append(spanEl);
// add icons
var iconUrl = option.getAttribute('data-icon');
if (!!iconUrl) {
var imgEl = $("<img alt=\"\" src=\"" + iconUrl + "\">");
liEl.prepend(imgEl);
}
// Check for multiple type.
$(this.dropdownOptions).append(liEl[0]);
return liEl[0];
}
/**
* Toggle entry from option
* @param {String} key Option key
* @return {Boolean} if entry was added or removed
*/
}, {
key: "_toggleEntryFromArray",
value: function _toggleEntryFromArray(key) {
var notAdded = !this._keysSelected.hasOwnProperty(key);
var $optionLi = $(this._valueDict[key].optionEl);
if (notAdded) {
this._keysSelected[key] = true;
} else {
delete this._keysSelected[key];
}
$optionLi.toggleClass('selected', notAdded);
// Set checkbox checked value
$optionLi.find('input[type="checkbox"]').prop('checked', notAdded);
// use notAdded instead of true (to detect if the option is selected or not)
$optionLi.prop('selected', notAdded);
return notAdded;
}
/**
* Set text value to input
*/
}, {
key: "_setValueToInput",
value: function _setValueToInput() {
var values = [];
var options = this.$el.find('option');
options.each(function (el) {
if ($(el).prop('selected')) {
var text = $(el).text();
values.push(text);
}
});
if (!values.length) {
var firstDisabled = this.$el.find('option:disabled').eq(0);
if (firstDisabled.length && firstDisabled[0].value === '') {
values.push(firstDisabled.text());
}
}
this.input.value = values.join(', ');
}
/**
* Set selected state of dropdown to match actual select element
*/
}, {
key: "_setSelectedStates",
value: function _setSelectedStates() {
this._keysSelected = {};
for (var key in this._valueDict) {
var option = this._valueDict[key];
var optionIsSelected = $(option.el).prop('selected');
$(option.optionEl).find('input[type="checkbox"]').prop('checked', optionIsSelected);
if (optionIsSelected) {
this._activateOption($(this.dropdownOptions), $(option.optionEl));
this._keysSelected[key] = true;
} else {
$(option.optionEl).removeClass('selected');
}
}
}
/**
* Make option as selected and scroll to selected position
* @param {jQuery} collection Select options jQuery element
* @param {Element} newOption element of the new option
*/
}, {
key: "_activateOption",
value: function _activateOption(collection, newOption) {
if (newOption) {
if (!this.isMultiple) {
collection.find('li.selected').removeClass('selected');
}
var option = $(newOption);
option.addClass('selected');
}
}
/**
* Get Selected Values
* @return {Array} Array of selected values
*/
}, {
key: "getSelectedValues",
value: function getSelectedValues() {
var selectedValues = [];
for (var key in this._keysSelected) {
selectedValues.push(this._valueDict[key].el.value);
}
return selectedValues;
}
}], [{
key: "init",
value: function init(els, options) {
return _get(FormSelect.__proto__ || Object.getPrototypeOf(FormSelect), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_FormSelect;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return FormSelect;
}(Component);
M.FormSelect = FormSelect;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(FormSelect, 'select', 'M_FormSelect'); //iob
}
})(cash);
(function ($) {
// Function to update labels of text fields
M.updateTextFields = function (formSelector) {
//iob
var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], input[type=date], input[type=time], textarea';
var $body = void 0; // iob start
if (formSelector) {
$body = $(formSelector);
} else {
$body = $('body');
}
$body.find(input_selector).each(function (element, index) {
// iob end
var $this = $(this);
if (element.value.length > 0 || $(element).is(':focus') || element.autofocus || $this.attr('placeholder') !== null) {
$this.siblings('label').addClass('active');
} else if (element.validity) {
$this.siblings('label').toggleClass('active', element.validity.badInput === true);
} else {
$this.siblings('label').removeClass('active');
}
});
};
M.validate_field = function (object) {
var hasLength = object.attr('data-length') !== null;
var lenAttr = parseInt(object.attr('data-length'));
var len = object[0].value.length;
if (len === 0 && object[0].validity.badInput === false && !object.is(':required')) {
if (object.hasClass('validate')) {
object.removeClass('valid');
object.removeClass('invalid');
}
} else {
if (object.hasClass('validate')) {
// Check for character counter attributes
if (object.is(':valid') && hasLength && len <= lenAttr || object.is(':valid') && !hasLength) {
object.removeClass('invalid');
object.addClass('valid');
} else {
object.removeClass('valid');
object.addClass('invalid');
}
}
}
};
M.textareaAutoResize = function ($textarea) {
// Wrap if native element
if ($textarea instanceof Element) {
$textarea = $($textarea);
}
if (!$textarea.length) {
console.error('No textarea element found');
return;
}
// Textarea Auto Resize
var hiddenDiv = $('.hiddendiv').first();
if (!hiddenDiv.length) {
hiddenDiv = $('<div class="hiddendiv common"></div>');
$('body').append(hiddenDiv);
}
// Set font properties of hiddenDiv
var fontFamily = $textarea.css('font-family');
var fontSize = $textarea.css('font-size');
var lineHeight = $textarea.css('line-height');
// Firefox can't handle padding shorthand.
var paddingTop = $textarea.css('padding-top');
var paddingRight = $textarea.css('padding-right');
var paddingBottom = $textarea.css('padding-bottom');
var paddingLeft = $textarea.css('padding-left');
if (fontSize) {
hiddenDiv.css('font-size', fontSize);
}
if (fontFamily) {
hiddenDiv.css('font-family', fontFamily);
}
if (lineHeight) {
hiddenDiv.css('line-height', lineHeight);
}
if (paddingTop) {
hiddenDiv.css('padding-top', paddingTop);
}
if (paddingRight) {
hiddenDiv.css('padding-right', paddingRight);
}
if (paddingBottom) {
hiddenDiv.css('padding-bottom', paddingBottom);
}
if (paddingLeft) {
hiddenDiv.css('padding-left', paddingLeft);
}
// Set original-height, if none
if (!$textarea.data('original-height')) {
$textarea.data('original-height', $textarea.height());
}
if ($textarea.attr('wrap') === 'off') {
hiddenDiv.css('overflow-wrap', 'normal').css('white-space', 'pre');
}
hiddenDiv.text($textarea[0].value + '\n');
var content = hiddenDiv.html().replace(/\n/g, '<br>');
hiddenDiv.html(content);
// When textarea is hidden, width goes crazy.
// Approximate with half of window size
if ($textarea[0].offsetWidth > 0 && $textarea[0].offsetHeight > 0) {
hiddenDiv.css('width', $textarea.width() + 'px');
} else {
hiddenDiv.css('width', window.innerWidth / 2 + 'px');
}
/**
* Resize if the new height is greater than the
* original height of the textarea
*/
if ($textarea.data('original-height') <= hiddenDiv.innerHeight()) {
$textarea.css('height', hiddenDiv.innerHeight() + 'px');
} else if ($textarea[0].value.length < $textarea.data('previous-length')) {
/**
* In case the new height is less than original height, it
* means the textarea has less text than before
* So we set the height to the original one
*/
$textarea.css('height', $textarea.data('original-height') + 'px');
}
$textarea.data('previous-length', $textarea[0].value.length);
};
$(document).ready(function () {
// Text based inputs
var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], input[type=date], input[type=time], textarea';
// Add active if form auto complete
$(document).on('change', input_selector, function () {
if (this.value.length !== 0 || $(this).attr('placeholder') !== null) {
$(this).siblings('label').addClass('active');
}
M.validate_field($(this));
});
// Add active if input element has been pre-populated on document ready
// iob: disable autoinit
// $(document).ready(function() {
// M.updateTextFields();
// });
// HTML DOM FORM RESET handling
$(document).on('reset', function (e) {
var formReset = $(e.target);
if (formReset.is('form')) {
formReset.find(input_selector).removeClass('valid').removeClass('invalid');
formReset.find(input_selector).each(function (e) {
if (this.value.length) {
$(this).siblings('label').removeClass('active');
}
});
// Reset select (after native reset)
setTimeout(function () {
formReset.find('select').each(function () {
// check if initialized
if (this.M_FormSelect) {
$(this).trigger('change');
}
});
}, 0);
}
});
/**
* Add active when element has focus
* @param {Event} e
*/
document.addEventListener('focus', function (e) {
if ($(e.target).is(input_selector)) {
$(e.target).siblings('label, .prefix').addClass('active');
}
}, true);
/**
* Remove active when element is blurred
* @param {Event} e
*/
document.addEventListener('blur', function (e) {
var $inputElement = $(e.target);
if ($inputElement.is(input_selector)) {
var selector = '.prefix';
if ($inputElement[0].value.length === 0 && $inputElement[0].validity.badInput !== true && $inputElement.attr('placeholder') === null) {
selector += ', label';
}
$inputElement.siblings(selector).removeClass('active');
M.validate_field($inputElement);
}
}, true);
// Radio and Checkbox focus class
var radio_checkbox = 'input[type=radio], input[type=checkbox]';
$(document).on('keyup', radio_checkbox, function (e) {
// TAB, check if tabbing to radio or checkbox.
if (e.which === M.keys.TAB) {
$(this).addClass('tabbed');
var $this = $(this);
$this.one('blur', function (e) {
$(this).removeClass('tabbed');
});
return;
}
});
var text_area_selector = '.materialize-textarea';
$(text_area_selector).each(function () {
var $textarea = $(this);
/**
* Resize textarea on document load after storing
* the original height and the original length
*/
$textarea.data('original-height', $textarea.height());
$textarea.data('previous-length', this.value.length);
M.textareaAutoResize($textarea);
});
$(document).on('keyup', text_area_selector, function () {
M.textareaAutoResize($(this));
});
$(document).on('keydown', text_area_selector, function () {
M.textareaAutoResize($(this));
});
// File Input Path
$(document).on('change', '.file-field input[type="file"]', function () {
var file_field = $(this).closest('.file-field');
var path_input = file_field.find('input.file-path');
var files = $(this)[0].files;
var file_names = [];
for (var i = 0; i < files.length; i++) {
file_names.push(files[i].name);
}
path_input[0].value = file_names.join(', ');
path_input.trigger('change');
});
}); // End of $(document).ready
})(cash);
(function ($, anim) {
'use strict';
var _defaults = {};
/**
* @class
*
*/
var Range = function (_Component5) {
_inherits(Range, _Component5);
/**
* Construct Range instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Range(el, options) {
_classCallCheck(this, Range);
var _this20 = _possibleConstructorReturn(this, (Range.__proto__ || Object.getPrototypeOf(Range)).call(this, Range, el, options));
_this20.el.M_Range = _this20;
/**
* Options for the range
* @member Range#options
*/
_this20.options = $.extend({}, Range.defaults, options);
_this20._mousedown = false;
// Setup
_this20._setupThumb();
_this20._setupEventHandlers();
return _this20;
}
_createClass(Range, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
this._removeThumb();
this.el.M_Range = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleRangeChangeBound = this._handleRangeChange.bind(this);
this._handleRangeFocusBound = this._handleRangeFocus.bind(this);
this._handleRangeMousedownTouchstartBound = this._handleRangeMousedownTouchstart.bind(this);
this._handleRangeInputMousemoveTouchmoveBound = this._handleRangeInputMousemoveTouchmove.bind(this);
this._handleRangeMouseupTouchendBound = this._handleRangeMouseupTouchend.bind(this);
this._handleRangeBlurMouseoutTouchleaveBound = this._handleRangeBlurMouseoutTouchleave.bind(this);
this.el.addEventListener('change', this._handleRangeChangeBound);
this.el.addEventListener('focus', this._handleRangeFocusBound);
this.el.addEventListener('mousedown', this._handleRangeMousedownTouchstartBound);
this.el.addEventListener('touchstart', this._handleRangeMousedownTouchstartBound);
this.el.addEventListener('input', this._handleRangeInputMousemoveTouchmoveBound);
this.el.addEventListener('mousemove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.addEventListener('touchmove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.addEventListener('mouseup', this._handleRangeMouseupTouchendBound);
this.el.addEventListener('touchend', this._handleRangeMouseupTouchendBound);
this.el.addEventListener('blur', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.addEventListener('mouseout', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.addEventListener('touchleave', this._handleRangeBlurMouseoutTouchleaveBound);
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('change', this._handleRangeChangeBound);
this.el.removeEventListener('focus', this._handleRangeFocusBound);
this.el.removeEventListener('mousedown', this._handleRangeMousedownTouchstartBound);
this.el.removeEventListener('touchstart', this._handleRangeMousedownTouchstartBound);
this.el.removeEventListener('input', this._handleRangeInputMousemoveTouchmoveBound);
this.el.removeEventListener('mousemove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.removeEventListener('touchmove', this._handleRangeInputMousemoveTouchmoveBound);
this.el.removeEventListener('mouseup', this._handleRangeMouseupTouchendBound);
this.el.removeEventListener('touchend', this._handleRangeMouseupTouchendBound);
this.el.removeEventListener('blur', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.removeEventListener('mouseout', this._handleRangeBlurMouseoutTouchleaveBound);
this.el.removeEventListener('touchleave', this._handleRangeBlurMouseoutTouchleaveBound);
}
/**
* Handle Range Change
* @param {Event} e
*/
}, {
key: "_handleRangeChange",
value: function _handleRangeChange() {
$(this.value).html(this.$el.val());
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
var offsetLeft = this._calcRangeOffset();
$(this.thumb).addClass('active').css('left', offsetLeft + 'px');
}
/**
* Handle Range Focus
* @param {Event} e
*/
}, {
key: "_handleRangeFocus",
value: function _handleRangeFocus() {
if (M.tabPressed) {
this.$el.addClass('focused');
}
}
/**
* Handle Range Mousedown and Touchstart
* @param {Event} e
*/
}, {
key: "_handleRangeMousedownTouchstart",
value: function _handleRangeMousedownTouchstart(e) {
// Set indicator value
$(this.value).html(this.$el.val());
this._mousedown = true;
this.$el.addClass('active');
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
if (e.type !== 'input') {
var offsetLeft = this._calcRangeOffset();
$(this.thumb).addClass('active').css('left', offsetLeft + 'px');
}
}
/**
* Handle Range Input, Mousemove and Touchmove
*/
}, {
key: "_handleRangeInputMousemoveTouchmove",
value: function _handleRangeInputMousemoveTouchmove() {
if (this._mousedown) {
if (!$(this.thumb).hasClass('active')) {
this._showRangeBubble();
}
var offsetLeft = this._calcRangeOffset();
$(this.thumb).addClass('active').css('left', offsetLeft + 'px');
$(this.value).html(this.$el.val());
}
}
/**
* Handle Range Mouseup and Touchend
*/
}, {
key: "_handleRangeMouseupTouchend",
value: function _handleRangeMouseupTouchend() {
this._mousedown = false;
this.$el.removeClass('active');
}
/**
* Handle Range Blur, Mouseout and Touchleave
*/
}, {
key: "_handleRangeBlurMouseoutTouchleave",
value: function _handleRangeBlurMouseoutTouchleave() {
if (!this._mousedown) {
this.$el.removeClass('focused');
var paddingLeft = parseInt(this.$el.css('padding-left'));
var marginLeft = 7 + paddingLeft + 'px';
if ($(this.thumb).hasClass('active')) {
anim.remove(this.thumb);
anim({
targets: this.thumb,
height: 0,
width: 0,
top: 10,
easing: 'easeOutQuad',
marginLeft: marginLeft,
duration: 100
});
}
$(this.thumb).removeClass('active');
}
}
/**
* Setup dropdown
*/
}, {
key: "_setupThumb",
value: function _setupThumb() {
this.thumb = document.createElement('span');
this.value = document.createElement('span');
$(this.thumb).addClass('thumb');
$(this.value).addClass('value');
$(this.thumb).append(this.value);
this.$el.after(this.thumb);
}
/**
* Remove dropdown
*/
}, {
key: "_removeThumb",
value: function _removeThumb() {
$(this.thumb).remove();
}
/**
* morph thumb into bubble
*/
}, {
key: "_showRangeBubble",
value: function _showRangeBubble() {
var paddingLeft = parseInt($(this.thumb).parent().css('padding-left'));
var marginLeft = -7 + paddingLeft + 'px'; // TODO: fix magic number?
anim.remove(this.thumb);
anim({
targets: this.thumb,
height: 30,
width: 30,
top: -30,
marginLeft: marginLeft,
duration: 300,
easing: 'easeOutQuint'
});
}
/**
* Calculate the offset of the thumb
* @return {Number} offset in pixels
*/
}, {
key: "_calcRangeOffset",
value: function _calcRangeOffset() {
var width = this.$el.width() - 15;
var max = parseFloat(this.$el.attr('max'));
var min = parseFloat(this.$el.attr('min'));
var percent = (parseFloat(this.$el.val()) - min) / (max - min);
return percent * width;
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Range.__proto__ || Object.getPrototypeOf(Range), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Range;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Range;
}(Component);
M.Range = Range;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Range, 'range', 'M_Range');
}
Range.init($('input[type=range]'));
})(cash, M.anime);
(function ($, anim) {
'use strict';
var _defaults = {
accordion: true,
onOpenStart: undefined,
onOpenEnd: undefined,
onCloseStart: undefined,
onCloseEnd: undefined,
inDuration: 300,
outDuration: 300
};
/**
* @class
*
*/
var Collapsible = function (_Component6) {
_inherits(Collapsible, _Component6);
/**
* Construct Collapsible instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Collapsible(el, options) {
_classCallCheck(this, Collapsible);
var _this21 = _possibleConstructorReturn(this, (Collapsible.__proto__ || Object.getPrototypeOf(Collapsible)).call(this, Collapsible, el, options));
_this21.el.M_Collapsible = _this21;
/**
* Options for the collapsible
* @member Collapsible#options
* @prop {Boolean} [accordion=false] - Type of the collapsible
* @prop {Function} onOpenStart - Callback function called before collapsible is opened
* @prop {Function} onOpenEnd - Callback function called after collapsible is opened
* @prop {Function} onCloseStart - Callback function called before collapsible is closed
* @prop {Function} onCloseEnd - Callback function called after collapsible is closed
* @prop {Number} inDuration - Transition in duration in milliseconds.
* @prop {Number} outDuration - Transition duration in milliseconds.
*/
_this21.options = $.extend({}, Collapsible.defaults, options);
_this21._setupEventHandlers();
// Open first active
var $activeBodies = _this21.$el.children('li.active').children('.collapsible-body');
if (_this21.options.accordion) {
// Handle Accordion
$activeBodies.first().css('display', 'block');
} else {
// Handle Expandables
$activeBodies.css('display', 'block');
}
return _this21;
}
_createClass(Collapsible, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
this.el.M_Collapsible = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleCollapsibleClickBound = this._handleCollapsibleClick.bind(this);
this.el.addEventListener('click', this._handleCollapsibleClickBound);
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('click', this._handleCollapsibleClickBound);
}
/**
* Handle Collapsible Click
* @param {Event} e
*/
}, {
key: "_handleCollapsibleClick",
value: function _handleCollapsibleClick(e) {
var $header = $(e.target).closest('.collapsible-header');
if (e.target && $header.length) {
var $collapsible = $header.closest('.collapsible');
if ($collapsible[0] === this.el) {
var $collapsibleLi = $header.closest('li');
var $collapsibleLis = $collapsible.children('li');
var isActive = $collapsibleLi[0].classList.contains('active');
var index = $collapsibleLis.index($collapsibleLi);
if (isActive) {
this.close(index);
} else {
this.open(index);
}
}
}
}
/**
* Animate in collapsible slide
* @param {Number} index - 0th index of slide
*/
}, {
key: "_animateIn",
value: function _animateIn(index) {
var _this22 = this;
var $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length) {
var $body = $collapsibleLi.children('.collapsible-body');
anim.remove($body[0]);
$body.css({
display: 'block',
overflow: 'hidden',
height: 0,
paddingTop: '',
paddingBottom: ''
});
var pTop = $body.css('padding-top');
var pBottom = $body.css('padding-bottom');
var finalHeight = $body[0].scrollHeight;
$body.css({
paddingTop: 0,
paddingBottom: 0
});
anim({
targets: $body[0],
height: finalHeight,
paddingTop: pTop,
paddingBottom: pBottom,
duration: this.options.inDuration,
easing: 'easeInOutCubic',
complete: function (anim) {
$body.css({
overflow: '',
paddingTop: '',
paddingBottom: '',
height: ''
});
// onOpenEnd callback
if (typeof _this22.options.onOpenEnd === 'function') {
_this22.options.onOpenEnd.call(_this22, $collapsibleLi[0]);
}
}
});
}
}
/**
* Animate out collapsible slide
* @param {Number} index - 0th index of slide to open
*/
}, {
key: "_animateOut",
value: function _animateOut(index) {
var _this23 = this;
var $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length) {
var $body = $collapsibleLi.children('.collapsible-body');
anim.remove($body[0]);
$body.css('overflow', 'hidden');
anim({
targets: $body[0],
height: 0,
paddingTop: 0,
paddingBottom: 0,
duration: this.options.outDuration,
easing: 'easeInOutCubic',
complete: function () {
$body.css({
height: '',
overflow: '',
padding: '',
display: ''
});
// onCloseEnd callback
if (typeof _this23.options.onCloseEnd === 'function') {
_this23.options.onCloseEnd.call(_this23, $collapsibleLi[0]);
}
}
});
}
}
/**
* Open Collapsible
* @param {Number} index - 0th index of slide
*/
}, {
key: "open",
value: function open(index) {
var _this24 = this;
var $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length && !$collapsibleLi[0].classList.contains('active')) {
// onOpenStart callback
if (typeof this.options.onOpenStart === 'function') {
this.options.onOpenStart.call(this, $collapsibleLi[0]);
}
// Handle accordion behavior
if (this.options.accordion) {
var $collapsibleLis = this.$el.children('li');
var $activeLis = this.$el.children('li.active');
$activeLis.each(function (el) {
var index = $collapsibleLis.index($(el));
_this24.close(index);
});
}
// Animate in
$collapsibleLi[0].classList.add('active');
this._animateIn(index);
}
}
/**
* Close Collapsible
* @param {Number} index - 0th index of slide
*/
}, {
key: "close",
value: function close(index) {
var $collapsibleLi = this.$el.children('li').eq(index);
if ($collapsibleLi.length && $collapsibleLi[0].classList.contains('active')) {
// onCloseStart callback
if (typeof this.options.onCloseStart === 'function') {
this.options.onCloseStart.call(this, $collapsibleLi[0]);
}
// Animate out
$collapsibleLi[0].classList.remove('active');
this._animateOut(index);
}
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Collapsible.__proto__ || Object.getPrototypeOf(Collapsible), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Collapsible;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Collapsible;
}(Component);
M.Collapsible = Collapsible;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Collapsible, 'collapsible', 'M_Collapsible');
}
})(cash, M.anime);
(function ($) {
'use strict';
var _defaults = {
data: [],
placeholder: '',
secondaryPlaceholder: '',
autocompleteOptions: {},
limit: Infinity,
onChipAdd: null,
onChipSelect: null,
onChipDelete: null
};
/**
* @typedef {Object} chip
* @property {String} tag chip tag string
* @property {String} [image] chip avatar image string
*/
/**
* @class
*
*/
var Chips = function (_Component7) {
_inherits(Chips, _Component7);
/**
* Construct Chips instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Chips(el, options) {
_classCallCheck(this, Chips);
var _this25 = _possibleConstructorReturn(this, (Chips.__proto__ || Object.getPrototypeOf(Chips)).call(this, Chips, el, options));
_this25.el.M_Chips = _this25;
/**
* Options for the modal
* @member Chips#options
* @prop {Array} data
* @prop {String} placeholder
* @prop {String} secondaryPlaceholder
* @prop {Object} autocompleteOptions
*/
_this25.options = $.extend({}, Chips.defaults, options);
_this25.$el.addClass('chips input-field');
_this25.chipsData = [];
_this25.$chips = $();
_this25._setupInput();
_this25.hasAutocomplete = Object.keys(_this25.options.autocompleteOptions).length > 0;
// Set input id
if (!_this25.$input.attr('id')) {
_this25.$input.attr('id', M.guid());
}
// Render initial chips
if (_this25.options.data.length) {
_this25.chipsData = _this25.options.data;
_this25._renderChips(_this25.chipsData);
}
// Setup autocomplete if needed
if (_this25.hasAutocomplete) {
_this25._setupAutocomplete();
}
_this25._setPlaceholder();
_this25._setupLabel();
_this25._setupEventHandlers();
return _this25;
}
_createClass(Chips, [{
key: "getData",
/**
* Get Chips Data
*/
value: function getData() {
return this.chipsData;
}
/**
* Teardown component
*/
}, {
key: "destroy",
value: function destroy() {
this._removeEventHandlers();
this.$chips.remove();
this.el.M_Chips = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleChipClickBound = this._handleChipClick.bind(this);
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputFocusBound = this._handleInputFocus.bind(this);
this._handleInputBlurBound = this._handleInputBlur.bind(this);
this.el.addEventListener('click', this._handleChipClickBound);
document.addEventListener('keydown', Chips._handleChipsKeydown);
document.addEventListener('keyup', Chips._handleChipsKeyup);
this.el.addEventListener('blur', Chips._handleChipsBlur, true);
this.$input[0].addEventListener('focus', this._handleInputFocusBound);
this.$input[0].addEventListener('blur', this._handleInputBlurBound);
this.$input[0].addEventListener('keydown', this._handleInputKeydownBound);
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('click', this._handleChipClickBound);
document.removeEventListener('keydown', Chips._handleChipsKeydown);
document.removeEventListener('keyup', Chips._handleChipsKeyup);
this.el.removeEventListener('blur', Chips._handleChipsBlur, true);
this.$input[0].removeEventListener('focus', this._handleInputFocusBound);
this.$input[0].removeEventListener('blur', this._handleInputBlurBound);
this.$input[0].removeEventListener('keydown', this._handleInputKeydownBound);
}
/**
* Handle Chip Click
* @param {Event} e
*/
}, {
key: "_handleChipClick",
value: function _handleChipClick(e) {
var $chip = $(e.target).closest('.chip');
var clickedClose = $(e.target).is('.close');
if ($chip.length) {
var index = $chip.index();
if (clickedClose) {
// delete chip
this.deleteChip(index);
this.$input[0].focus();
} else {
// select chip
this.selectChip(index);
}
// Default handle click to focus on input
} else {
this.$input[0].focus();
}
}
/**
* Handle Chips Keydown
* @param {Event} e
*/
}, {
key: "_handleInputFocus",
/**
* Handle Input Focus
*/
value: function _handleInputFocus() {
this.$el.addClass('focus');
}
/**
* Handle Input Blur
*/
}, {
key: "_handleInputBlur",
value: function _handleInputBlur() {
this.addChip({
tag: this.$input[0].value
});
this.$input[0].value = '';
this.$el.removeClass('focus');
}
/**
* Handle Input Keydown
* @param {Event} e
*/
}, {
key: "_handleInputKeydown",
value: function _handleInputKeydown(e) {
Chips._keydown = true;
// enter - comma - semicolon - space
if (e.keyCode === 13 || e.keyCode === 188 || e.keyCode === 32) {
// Override enter if autocompleting.
if (this.hasAutocomplete && this.autocomplete && this.autocomplete.isOpen) {
return;
}
e.preventDefault();
this.addChip({
tag: this.$input[0].value
});
this.$input[0].value = '';
// delete or left
} else if ((e.keyCode === 8 || e.keyCode === 37) && this.$input[0].value === '' && this.chipsData.length) {
e.preventDefault();
this.selectChip(this.chipsData.length - 1);
}
}
/**
* Render Chip
* @param {chip} chip
* @return {Element}
*/
}, {
key: "_renderChip",
value: function _renderChip(chip) {
if (!chip.tag) {
return;
}
var renderedChip = document.createElement('div');
var closeIcon = document.createElement('i');
renderedChip.classList.add('chip');
renderedChip.textContent = chip.tag;
renderedChip.setAttribute('tabindex', 0);
$(closeIcon).addClass('material-icons close');
closeIcon.textContent = 'close';
// attach image if needed
if (chip.image) {
var img = document.createElement('img');
img.setAttribute('src', chip.image);
renderedChip.insertBefore(img, renderedChip.firstChild);
}
renderedChip.appendChild(closeIcon);
return renderedChip;
}
/**
* Render Chips
*/
}, {
key: "_renderChips",
value: function _renderChips() {
this.$chips.remove();
for (var i = 0; i < this.chipsData.length; i++) {
var chipEl = this._renderChip(this.chipsData[i]);
this.$el.append(chipEl);
this.$chips.add(chipEl);
}
// move input to end
this.$el.append(this.$input[0]);
}
/**
* Setup Autocomplete
*/
}, {
key: "_setupAutocomplete",
value: function _setupAutocomplete() {
var _this26 = this;
this.options.autocompleteOptions.onAutocomplete = function (val) {
_this26.addChip({
tag: val
});
_this26.$input[0].value = '';
_this26.$input[0].focus();
};
this.autocomplete = M.Autocomplete.init(this.$input[0], this.options.autocompleteOptions);
}
/**
* Setup Input
*/
}, {
key: "_setupInput",
value: function _setupInput() {
this.$input = this.$el.find('input');
if (!this.$input.length) {
this.$input = $('<input></input>');
this.$el.append(this.$input);
}
this.$input.addClass('input');
}
/**
* Setup Label
*/
}, {
key: "_setupLabel",
value: function _setupLabel() {
this.$label = this.$el.find('label');
if (this.$label.length) {
this.$label.setAttribute('for', this.$input.attr('id'));
}
}
/**
* Set placeholder
*/
}, {
key: "_setPlaceholder",
value: function _setPlaceholder() {
if (this.chipsData !== undefined && !this.chipsData.length && this.options.placeholder) {
$(this.$input).prop('placeholder', this.options.placeholder);
} else if ((this.chipsData === undefined || !!this.chipsData.length) && this.options.secondaryPlaceholder) {
$(this.$input).prop('placeholder', this.options.secondaryPlaceholder);
}
}
/**
* Check if chip is valid
* @param {chip} chip
*/
}, {
key: "_isValid",
value: function _isValid(chip) {
if (chip.hasOwnProperty('tag') && chip.tag !== '') {
var exists = false;
for (var i = 0; i < this.chipsData.length; i++) {
if (this.chipsData[i].tag === chip.tag) {
exists = true;
break;
}
}
return !exists;
}
return false;
}
/**
* Add chip
* @param {chip} chip
*/
}, {
key: "addChip",
value: function addChip(chip) {
if (!this._isValid(chip) || this.chipsData.length >= this.options.limit) {
return;
}
var renderedChip = this._renderChip(chip);
this.$chips.add(renderedChip);
this.chipsData.push(chip);
$(this.$input).before(renderedChip);
this._setPlaceholder();
// fire chipAdd callback
if (typeof this.options.onChipAdd === 'function') {
this.options.onChipAdd.call(this, this.$el, renderedChip);
}
}
/**
* Delete chip
* @param {Number} chip
*/
}, {
key: "deleteChip",
value: function deleteChip(chipIndex) {
var $chip = this.$chips.eq(chipIndex);
this.$chips.eq(chipIndex).remove();
this.$chips = this.$chips.filter(function (el) {
return $(el).index() >= 0;
});
this.chipsData.splice(chipIndex, 1);
this._setPlaceholder();
// fire chipDelete callback
if (typeof this.options.onChipDelete === 'function') {
this.options.onChipDelete.call(this, this.$el, $chip[0]);
}
}
/**
* Select chip
* @param {Number} chip
*/
}, {
key: "selectChip",
value: function selectChip(chipIndex) {
var $chip = this.$chips.eq(chipIndex);
this._selectedChip = $chip;
$chip[0].focus();
// fire chipSelect callback
if (typeof this.options.onChipSelect === 'function') {
this.options.onChipSelect.call(this, this.$el, $chip[0]);
}
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Chips.__proto__ || Object.getPrototypeOf(Chips), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Chips;
}
}, {
key: "_handleChipsKeydown",
value: function _handleChipsKeydown(e) {
Chips._keydown = true;
var $chips = $(e.target).closest('.chips');
var chipsKeydown = e.target && $chips.length;
// Don't handle keydown inputs on input and textarea
if ($(e.target).is('input, textarea') || !chipsKeydown) {
return;
}
var currChips = $chips[0].M_Chips;
// backspace and delete
if (e.keyCode === 8 || e.keyCode === 46) {
e.preventDefault();
var selectIndex = currChips.chipsData.length;
if (currChips._selectedChip) {
var index = currChips._selectedChip.index();
currChips.deleteChip(index);
currChips._selectedChip = null;
selectIndex = index - 1;
}
if (currChips.chipsData.length) {
currChips.selectChip(selectIndex);
}
// left arrow key
} else if (e.keyCode === 37) {
if (currChips._selectedChip) {
var _selectIndex = currChips._selectedChip.index() - 1;
if (_selectIndex < 0) {
return;
}
currChips.selectChip(_selectIndex);
}
// right arrow key
} else if (e.keyCode === 39) {
if (currChips._selectedChip) {
var _selectIndex2 = currChips._selectedChip.index() + 1;
if (_selectIndex2 >= currChips.chipsData.length) {
currChips.$input[0].focus();
} else {
currChips.selectChip(_selectIndex2);
}
}
}
}
/**
* Handle Chips Keyup
* @param {Event} e
*/
}, {
key: "_handleChipsKeyup",
value: function _handleChipsKeyup(e) {
Chips._keydown = false;
}
/**
* Handle Chips Blur
* @param {Event} e
*/
}, {
key: "_handleChipsBlur",
value: function _handleChipsBlur(e) {
if (!Chips._keydown) {
var $chips = $(e.target).closest('.chips');
var currChips = $chips[0].M_Chips;
currChips._selectedChip = null;
}
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Chips;
}(Component);
/**
* @static
* @memberof Chips
*/
Chips._keydown = false;
M.Chips = Chips;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Chips, 'chips', 'M_Chips');
}
$(document).ready(function () {
// Handle removal of static chips.
$(document.body).on('click', '.chip .close', function () {
var $chips = $(this).closest('.chips');
if ($chips.length && $chips[0].M_Chips) {
return;
}
$(this).closest('.chip').remove();
});
});
})(cash);
(function ($) {
'use strict';
var _defaults = {
// the default output format for the input field value
format: 'mmm dd, yyyy',
// Used to create date object from current input string
parse: null,
// The initial date to view when first opened
defaultDate: null,
// Make the `defaultDate` the initial selected value
setDefaultDate: false,
disableWeekends: false,
disableDayFn: null,
// First day of week (0: Sunday, 1: Monday etc)
firstDay: 0,
// The earliest date that can be selected
minDate: null,
// Thelatest date that can be selected
maxDate: null,
// Number of years either side, or array of upper/lower range
yearRange: 10,
// used internally (don't config outside)
minYear: 0,
maxYear: 9999,
minMonth: undefined,
maxMonth: undefined,
startRange: null,
endRange: null,
isRTL: false,
// Render the month after year in the calendar title
showMonthAfterYear: false,
// Render days of the calendar grid that fall in the next or previous month
showDaysInNextAndPreviousMonths: false,
// Specify a DOM element to render the calendar in
container: null,
// internationalization
i18n: {
clear: 'Clear',
today: 'Today',
done: 'Ok',
previousMonth: '',
nextMonth: '',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
weekdaysAbbrev: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
},
// events array
events: [],
// callback function
onSelect: null,
onOpen: null,
onClose: null,
onDraw: null
};
/**
* @class
*
*/
var Datepicker = function (_Component8) {
_inherits(Datepicker, _Component8);
/**
* Construct Datepicker instance and set up overlay
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Datepicker(el, options) {
_classCallCheck(this, Datepicker);
var _this27 = _possibleConstructorReturn(this, (Datepicker.__proto__ || Object.getPrototypeOf(Datepicker)).call(this, Datepicker, el, options));
_this27.el.M_Datepicker = _this27;
_this27.options = $.extend({}, Datepicker.defaults, options);
// Remove time component from minDate and maxDate options
if (_this27.options.minDate) _this27.options.minDate.setHours(0, 0, 0, 0);
if (_this27.options.maxDate) _this27.options.maxDate.setHours(0, 0, 0, 0);
_this27.id = M.guid();
_this27._setupVariables();
_this27._insertHTMLIntoDOM();
_this27._setupModal();
_this27._setupEventHandlers();
if (!_this27.options.defaultDate) {
_this27.options.defaultDate = new Date(Date.parse(_this27.el.value));
_this27.options.setDefaultDate = true;
}
var defDate = _this27.options.defaultDate;
if (Datepicker._isDate(defDate)) {
if (_this27.options.setDefaultDate) {
_this27.setDate(defDate, true);
} else {
_this27.gotoDate(defDate);
}
} else {
_this27.gotoDate(new Date());
}
/**
* Describes open/close state of datepicker
* @type {Boolean}
*/
_this27.isOpen = false;
return _this27;
}
_createClass(Datepicker, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
this.modal.destroy();
$(this.modalEl).remove();
this.el.M_Datepicker = undefined;
}
}, {
key: "_insertHTMLIntoDOM",
value: function _insertHTMLIntoDOM() {
this.clearBtn.innerHTML = this.options.i18n.clear;
this.todayBtn.innerHTML = this.options.i18n.today;
this.doneBtn.innerHTML = this.options.i18n.done;
var containerEl = document.querySelector(this.options.container);
if (this.options.container && !!containerEl) {
this.$modalEl.appendTo(containerEl);
} else {
this.$modalEl.insertBefore(this.el);
}
}
}, {
key: "_setupModal",
value: function _setupModal() {
var _this28 = this;
this.modalEl.id = 'modal-' + this.id;
this.modal = M.Modal.init(this.modalEl, {
onCloseEnd: function () {
_this28.isOpen = false;
}
});
}
}, {
key: "toString",
value: function toString(format) {
var _this29 = this;
format = format || this.options.format;
if (!Datepicker._isDate(this.date)) {
return '';
}
var formatArray = format.split(/(d{1,4}|m{1,4}|y{4}|yy|!.)/g);
var formattedDate = formatArray.map(function (label) {
if (_this29.formats[label]) {
return _this29.formats[label]();
}
return label;
}).join('');
return formattedDate;
}
}, {
key: "setDate",
value: function setDate(date, preventOnSelect) {
if (!date) {
this.date = null;
this._renderDateDisplay();
return this.draw();
}
if (typeof date === 'string') {
date = new Date(Date.parse(date));
}
if (!Datepicker._isDate(date)) {
return;
}
var min = this.options.minDate,
max = this.options.maxDate;
if (Datepicker._isDate(min) && date < min) {
date = min;
} else if (Datepicker._isDate(max) && date > max) {
date = max;
}
this.date = new Date(date.getTime());
this._renderDateDisplay();
Datepicker._setToStartOfDay(this.date);
this.gotoDate(this.date);
if (!preventOnSelect && typeof this.options.onSelect === 'function') {
this.options.onSelect.call(this, this.date);
}
}
}, {
key: "setInputValue",
value: function setInputValue() {
this.el.value = this.toString();
this.$el.trigger('change', { firedBy: this });
}
}, {
key: "_renderDateDisplay",
value: function _renderDateDisplay() {
var displayDate = Datepicker._isDate(this.date) ? this.date : new Date();
var i18n = this.options.i18n;
var day = i18n.weekdaysShort[displayDate.getDay()];
var month = i18n.monthsShort[displayDate.getMonth()];
var date = displayDate.getDate();
this.yearTextEl.innerHTML = displayDate.getFullYear();
this.dateTextEl.innerHTML = day + ", " + month + " " + date;
}
/**
* change view to a specific date
*/
}, {
key: "gotoDate",
value: function gotoDate(date) {
var newCalendar = true;
if (!Datepicker._isDate(date)) {
return;
}
if (this.calendars) {
var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
lastVisibleDate = new Date(this.calendars[this.calendars.length - 1].year, this.calendars[this.calendars.length - 1].month, 1),
visibleDate = date.getTime();
// get the end of the month
lastVisibleDate.setMonth(lastVisibleDate.getMonth() + 1);
lastVisibleDate.setDate(lastVisibleDate.getDate() - 1);
newCalendar = visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate;
}
if (newCalendar) {
this.calendars = [{
month: date.getMonth(),
year: date.getFullYear()
}];
// if (this.options.mainCalendar === 'right') {
// this.calendars[0].month += 1 - this.options.numberOfMonths;
// }
}
this.adjustCalendars();
}
}, {
key: "adjustCalendars",
value: function adjustCalendars() {
this.calendars[0] = this.adjustCalendar(this.calendars[0]);
// for (let c = 1; c < this.options.numberOfMonths; c++) {
// this.calendars[c] = this.adjustCalendar({
// month: this.calendars[0].month + c,
// year: this.calendars[0].year
// });
// }
this.draw();
}
}, {
key: "adjustCalendar",
value: function adjustCalendar(calendar) {
if (calendar.month < 0) {
calendar.year -= Math.ceil(Math.abs(calendar.month) / 12);
calendar.month += 12;
}
if (calendar.month > 11) {
calendar.year += Math.floor(Math.abs(calendar.month) / 12);
calendar.month -= 12;
}
return calendar;
}
}, {
key: "nextMonth",
value: function nextMonth() {
this.calendars[0].month++;
this.adjustCalendars();
}
}, {
key: "prevMonth",
value: function prevMonth() {
this.calendars[0].month--;
this.adjustCalendars();
}
}, {
key: "render",
value: function render(year, month, randId) {
var opts = this.options,
now = new Date(),
days = Datepicker._getDaysInMonth(year, month),
before = new Date(year, month, 1).getDay(),
data = [],
row = [];
Datepicker._setToStartOfDay(now);
if (opts.firstDay > 0) {
before -= opts.firstDay;
if (before < 0) {
before += 7;
}
}
var previousMonth = month === 0 ? 11 : month - 1,
nextMonth = month === 11 ? 0 : month + 1,
yearOfPreviousMonth = month === 0 ? year - 1 : year,
yearOfNextMonth = month === 11 ? year + 1 : year,
daysInPreviousMonth = Datepicker._getDaysInMonth(yearOfPreviousMonth, previousMonth);
var cells = days + before,
after = cells;
while (after > 7) {
after -= 7;
}
cells += 7 - after;
var isWeekSelected = false;
for (var i = 0, r = 0; i < cells; i++) {
var day = new Date(year, month, 1 + (i - before)),
isSelected = Datepicker._isDate(this.date) ? Datepicker._compareDates(day, this.date) : false,
isToday = Datepicker._compareDates(day, now),
hasEvent = opts.events.indexOf(day.toDateString()) !== -1 ? true : false,
isEmpty = i < before || i >= days + before,
dayNumber = 1 + (i - before),
monthNumber = month,
yearNumber = year,
isStartRange = opts.startRange && Datepicker._compareDates(opts.startRange, day),
isEndRange = opts.endRange && Datepicker._compareDates(opts.endRange, day),
isInRange = opts.startRange && opts.endRange && opts.startRange < day && day < opts.endRange,
isDisabled = opts.minDate && day < opts.minDate || opts.maxDate && day > opts.maxDate || opts.disableWeekends && Datepicker._isWeekend(day) || opts.disableDayFn && opts.disableDayFn(day);
if (isEmpty) {
if (i < before) {
dayNumber = daysInPreviousMonth + dayNumber;
monthNumber = previousMonth;
yearNumber = yearOfPreviousMonth;
} else {
dayNumber = dayNumber - days;
monthNumber = nextMonth;
yearNumber = yearOfNextMonth;
}
}
var dayConfig = {
day: dayNumber,
month: monthNumber,
year: yearNumber,
hasEvent: hasEvent,
isSelected: isSelected,
isToday: isToday,
isDisabled: isDisabled,
isEmpty: isEmpty,
isStartRange: isStartRange,
isEndRange: isEndRange,
isInRange: isInRange,
showDaysInNextAndPreviousMonths: opts.showDaysInNextAndPreviousMonths
};
row.push(this.renderDay(dayConfig));
if (++r === 7) {
data.push(this.renderRow(row, opts.isRTL, isWeekSelected));
row = [];
r = 0;
isWeekSelected = false;
}
}
return this.renderTable(opts, data, randId);
}
}, {
key: "renderDay",
value: function renderDay(opts) {
var arr = [];
var ariaSelected = 'false';
if (opts.isEmpty) {
if (opts.showDaysInNextAndPreviousMonths) {
arr.push('is-outside-current-month');
arr.push('is-selection-disabled');
} else {
return '<td class="is-empty"></td>';
}
}
if (opts.isDisabled) {
arr.push('is-disabled');
}
if (opts.isToday) {
arr.push('is-today');
}
if (opts.isSelected) {
arr.push('is-selected');
ariaSelected = 'true';
}
if (opts.hasEvent) {
arr.push('has-event');
}
if (opts.isInRange) {
arr.push('is-inrange');
}
if (opts.isStartRange) {
arr.push('is-startrange');
}
if (opts.isEndRange) {
arr.push('is-endrange');
}
return '<td data-day="' + opts.day + '" class="' + arr.join(' ') + '" aria-selected="' + ariaSelected + '">' + '<button class="datepicker-day-button" type="button" ' + 'data-pika-year="' + opts.year + '" data-pika-month="' + opts.month + '" data-pika-day="' + opts.day + '">' + opts.day + '</button>' + '</td>';
}
}, {
key: "renderRow",
value: function renderRow(days, isRTL, isRowSelected) {
return '<tr class="pika-row' + (isRowSelected ? ' is-selected' : '') + '">' + (isRTL ? days.reverse() : days).join('') + '</tr>';
}
}, {
key: "renderTable",
value: function renderTable(opts, data, randId) {
return '<div class="datepicker-table-wrapper"><table cellpadding="0" cellspacing="0" class="datepicker-table" role="grid" aria-labelledby="' + randId + '">' + this.renderHead(opts) + this.renderBody(data) + '</table></div>';
}
}, {
key: "renderHead",
value: function renderHead(opts) {
var i = void 0,
arr = [];
for (i = 0; i < 7; i++) {
arr.push('<th scope="col"><abbr title="' + this.renderDayName(opts, i) + '">' + this.renderDayName(opts, i, true) + '</abbr></th>');
}
return '<thead><tr>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</tr></thead>';
}
}, {
key: "renderBody",
value: function renderBody(rows) {
return '<tbody>' + rows.join('') + '</tbody>';
}
}, {
key: "renderTitle",
value: function renderTitle(instance, c, year, month, refYear, randId) {
var i = void 0,
j = void 0,
arr = void 0,
opts = this.options,
isMinYear = year === opts.minYear,
isMaxYear = year === opts.maxYear,
html = '<div id="' + randId + '" class="datepicker-controls" role="heading" aria-live="assertive">',
monthHtml = void 0,
yearHtml = void 0,
prev = true,
next = true;
for (arr = [], i = 0; i < 12; i++) {
arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' + (i === month ? ' selected="selected"' : '') + (isMinYear && i < opts.minMonth || isMaxYear && i > opts.maxMonth ? 'disabled="disabled"' : '') + '>' + opts.i18n.months[i] + '</option>');
}
monthHtml = '<select class="pika-select pika-select-month" tabindex="-1">' + arr.join('') + '</select>';
if ($.isArray(opts.yearRange)) {
i = opts.yearRange[0];
j = opts.yearRange[1] + 1;
} else {
i = year - opts.yearRange;
j = 1 + year + opts.yearRange;
}
for (arr = []; i < j && i <= opts.maxYear; i++) {
if (i >= opts.minYear) {
arr.push('<option value="' + i + '"' + (i === year ? ' selected="selected"' : '') + '>' + i + '</option>');
}
}
yearHtml = '<select class="pika-select pika-select-year" tabindex="-1">' + arr.join('') + '</select>';
var leftArrow = '<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/><path d="M0-.5h24v24H0z" fill="none"/></svg>';
html += '<button class="month-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + leftArrow + '</button>';
html += '<div class="selects-container">';
if (opts.showMonthAfterYear) {
html += yearHtml + monthHtml;
} else {
html += monthHtml + yearHtml;
}
html += '</div>';
if (isMinYear && (month === 0 || opts.minMonth >= month)) {
prev = false;
}
if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
next = false;
}
// if (c === (this.options.numberOfMonths - 1) ) {
var rightArrow = '<svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"/><path d="M0-.25h24v24H0z" fill="none"/></svg>';
html += '<button class="month-next' + (next ? '' : ' is-disabled') + '" type="button">' + rightArrow + '</button>';
// }
return html += '</div>';
}
/**
* refresh the HTML
*/
}, {
key: "draw",
value: function draw(force) {
if (!this.isOpen && !force) {
return;
}
var opts = this.options,
minYear = opts.minYear,
maxYear = opts.maxYear,
minMonth = opts.minMonth,
maxMonth = opts.maxMonth,
html = '',
randId = void 0;
if (this._y <= minYear) {
this._y = minYear;
if (!isNaN(minMonth) && this._m < minMonth) {
this._m = minMonth;
}
}
if (this._y >= maxYear) {
this._y = maxYear;
if (!isNaN(maxMonth) && this._m > maxMonth) {
this._m = maxMonth;
}
}
randId = 'pika-title-' + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 2);
for (var c = 0; c < 1; c++) {
this._renderDateDisplay();
html += this.renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year, randId) + this.render(this.calendars[c].year, this.calendars[c].month, randId);
}
this.calendarEl.innerHTML = html;
// Init Materialize Select
var yearSelect = this.calendarEl.querySelector('.pika-select-year');
var monthSelect = this.calendarEl.querySelector('.pika-select-month');
M.Select.init(yearSelect, { classes: 'select-year', dropdownOptions: { container: document.body, constrainWidth: false } });
M.Select.init(monthSelect, { classes: 'select-month', dropdownOptions: { container: document.body, constrainWidth: false } });
// Add change handlers for select
yearSelect.addEventListener('change', this._handleYearChange.bind(this));
monthSelect.addEventListener('change', this._handleMonthChange.bind(this));
if (typeof this.options.onDraw === 'function') {
this.options.onDraw(this);
}
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
this._handleInputChangeBound = this._handleInputChange.bind(this);
this._handleCalendarClickBound = this._handleCalendarClick.bind(this);
this._finishSelectionBound = this._finishSelection.bind(this);
this._handleTodayClickBound = this._handleTodayClick.bind(this);
this._handleClearClickBound = this._handleClearClick.bind(this);
this._handleMonthChange = this._handleMonthChange.bind(this);
this.el.addEventListener('click', this._handleInputClickBound);
this.el.addEventListener('keydown', this._handleInputKeydownBound);
this.el.addEventListener('change', this._handleInputChangeBound);
this.calendarEl.addEventListener('click', this._handleCalendarClickBound);
this.doneBtn.addEventListener('click', this._finishSelectionBound);
this.todayBtn.addEventListener('click', this._handleTodayClickBound);
this.clearBtn.addEventListener('click', this._handleClearClickBound);
}
}, {
key: "_setupVariables",
value: function _setupVariables() {
var _this30 = this;
this.$modalEl = $(Datepicker._template);
this.modalEl = this.$modalEl[0];
this.calendarEl = this.modalEl.querySelector('.pika-single');
this.yearTextEl = this.modalEl.querySelector('.year-text');
this.dateTextEl = this.modalEl.querySelector('.date-text');
this.clearBtn = this.modalEl.querySelector('.datepicker-clear');
this.todayBtn = this.modalEl.querySelector('.datepicker-today');
this.doneBtn = this.modalEl.querySelector('.datepicker-done');
this.formats = {
d: function () {
return _this30.date.getDate();
},
dd: function () {
var d = _this30.date.getDate();
return (d < 10 ? '0' : '') + d;
},
ddd: function () {
return _this30.options.i18n.weekdaysShort[_this30.date.getDay()];
},
dddd: function () {
return _this30.options.i18n.weekdays[_this30.date.getDay()];
},
m: function () {
return _this30.date.getMonth() + 1;
},
mm: function () {
var m = _this30.date.getMonth() + 1;
return (m < 10 ? '0' : '') + m;
},
mmm: function () {
return _this30.options.i18n.monthsShort[_this30.date.getMonth()];
},
mmmm: function () {
return _this30.options.i18n.months[_this30.date.getMonth()];
},
yy: function () {
return ('' + _this30.date.getFullYear()).slice(2);
},
yyyy: function () {
return _this30.date.getFullYear();
}
};
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('click', this._handleInputClickBound);
this.el.removeEventListener('keydown', this._handleInputKeydownBound);
this.el.removeEventListener('change', this._handleInputChangeBound);
this.calendarEl.removeEventListener('click', this._handleCalendarClickBound);
}
}, {
key: "_handleInputClick",
value: function _handleInputClick() {
this.open();
}
}, {
key: "_handleInputKeydown",
value: function _handleInputKeydown(e) {
if (e.which === M.keys.ENTER) {
e.preventDefault();
this.open();
}
}
}, {
key: "_handleCalendarClick",
value: function _handleCalendarClick(e) {
if (!this.isOpen) {
return;
}
var $target = $(e.target);
if (!$target.hasClass('is-disabled')) {
if ($target.hasClass('datepicker-day-button') && !$target.hasClass('is-empty') && !$target.parent().hasClass('is-disabled')) {
this.setDate(new Date(e.target.getAttribute('data-pika-year'), e.target.getAttribute('data-pika-month'), e.target.getAttribute('data-pika-day')));
} else if ($target.closest('.month-prev').length) {
this.prevMonth();
} else if ($target.closest('.month-next').length) {
this.nextMonth();
}
}
// if (!$target.hasClass('pika-select')) {
// // if this is touch event prevent mouse events emulation
// // if (e.preventDefault) {
// // e.preventDefault();
// // } else {
// // e.returnValue = false;
// // return false;
// // }
// } else {
// this._c = true;
// }
}
}, {
key: "_handleTodayClick",
value: function _handleTodayClick() {
this.date = new Date();
this.setInputValue();
this.close();
}
}, {
key: "_handleClearClick",
value: function _handleClearClick() {
this.date = null;
this.setInputValue();
this.close();
}
}, {
key: "_handleMonthChange",
value: function _handleMonthChange(e) {
this.gotoMonth(e.target.value);
}
}, {
key: "_handleYearChange",
value: function _handleYearChange(e) {
this.gotoYear(e.target.value);
}
/**
* change view to a specific month (zero-index, e.g. 0: January)
*/
}, {
key: "gotoMonth",
value: function gotoMonth(month) {
if (!isNaN(month)) {
this.calendars[0].month = parseInt(month, 10);
this.adjustCalendars();
}
}
/**
* change view to a specific full year (e.g. "2012")
*/
}, {
key: "gotoYear",
value: function gotoYear(year) {
if (!isNaN(year)) {
this.calendars[0].year = parseInt(year, 10);
this.adjustCalendars();
}
}
}, {
key: "_handleInputChange",
value: function _handleInputChange(e) {
var date = void 0;
// Prevent change event from being fired when triggered by the plugin
if (e.firedBy === this) {
return;
}
if (this.options.parse) {
date = this.options.parse(this.el.value, this.options.format);
} else {
date = new Date(Date.parse(this.el.value));
}
if (Datepicker._isDate(date)) {
this.setDate(date);
}
// if (!self._v) {
// self.show();
// }
}
}, {
key: "renderDayName",
value: function renderDayName(opts, day, abbr) {
day += opts.firstDay;
while (day >= 7) {
day -= 7;
}
return abbr ? opts.i18n.weekdaysAbbrev[day] : opts.i18n.weekdays[day];
}
/**
* Set input value to the selected date and close Datepicker
*/
}, {
key: "_finishSelection",
value: function _finishSelection() {
this.setInputValue();
this.close();
}
/**
* Open Datepicker
*/
}, {
key: "open",
value: function open() {
if (this.isOpen) {
return;
}
this.isOpen = true;
if (typeof this.options.onOpen === 'function') {
this.options.onOpen.call(this);
}
this.draw();
this.modal.open();
return this;
}
/**
* Close Datepicker
*/
}, {
key: "close",
value: function close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
if (typeof this.options.onClose === 'function') {
this.options.onClose.call(this);
}
this.modal.close();
return this;
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Datepicker.__proto__ || Object.getPrototypeOf(Datepicker), "init", this).call(this, this, els, options);
}
}, {
key: "_isDate",
value: function _isDate(obj) {
return (/Date/.test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime())
);
}
}, {
key: "_isWeekend",
value: function _isWeekend(date) {
var day = date.getDay();
return day === 0 || day === 6;
}
}, {
key: "_setToStartOfDay",
value: function _setToStartOfDay(date) {
if (Datepicker._isDate(date)) date.setHours(0, 0, 0, 0);
}
}, {
key: "_getDaysInMonth",
value: function _getDaysInMonth(year, month) {
return [31, Datepicker._isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
}, {
key: "_isLeapYear",
value: function _isLeapYear(year) {
// solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
}
}, {
key: "_compareDates",
value: function _compareDates(a, b) {
// weak date comparison (use setToStartOfDay(date) to ensure correct result)
return a.getTime() === b.getTime();
}
}, {
key: "_setToStartOfDay",
value: function _setToStartOfDay(date) {
if (Datepicker._isDate(date)) date.setHours(0, 0, 0, 0);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Datepicker;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Datepicker;
}(Component);
Datepicker._template = ['<div class= "modal datepicker-modal">', '<div class="modal-content datepicker-container">', '<div class="datepicker-date-display">', '<span class="year-text"></span>', '<span class="date-text"></span>', '</div>', '<div class="datepicker-calendar-container">', '<div class="pika-single"></div>', '<div class="datepicker-footer">', '<button class="btn-flat datepicker-clear waves-effect" type="button"></button>', '<div class="confirmation-btns">', '<button class="btn-flat datepicker-today waves-effect" type="button"></button>', '<button class="btn-flat datepicker-done waves-effect" type="button"></button>', '</div>', '</div>', '</div>', '</div>', '</div>'].join('');
M.Datepicker = Datepicker;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Datepicker, 'datepicker', 'M_Datepicker');
}
})(cash);
(function ($) {
'use strict';
var _defaults = {
data: {}, // Autocomplete data set
limit: Infinity, // Limit of results the autocomplete shows
onAutocomplete: null, // Callback for when autocompleted
minLength: 1, // Min characters before autocomplete starts
sortFunction: function (a, b, inputString) {
// Sort function for sorting autocomplete results
return a.indexOf(inputString) - b.indexOf(inputString);
}
};
/**
* @class
*
*/
var Autocomplete = function (_Component9) {
_inherits(Autocomplete, _Component9);
/**
* Construct Autocomplete instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Autocomplete(el, options) {
_classCallCheck(this, Autocomplete);
var _this31 = _possibleConstructorReturn(this, (Autocomplete.__proto__ || Object.getPrototypeOf(Autocomplete)).call(this, Autocomplete, el, options));
_this31.el.M_Autocomplete = _this31;
/**
* Options for the autocomplete
* @member Autocomplete#options
* @prop {Number} duration
* @prop {Number} dist
* @prop {number} shift
* @prop {number} padding
* @prop {Boolean} fullWidth
* @prop {Boolean} indicators
* @prop {Boolean} noWrap
* @prop {Function} onCycleTo
*/
_this31.options = $.extend({}, Autocomplete.defaults, options);
// Setup
_this31.isOpen = false;
_this31.count = 0;
_this31.activeIndex = -1;
_this31.oldVal;
_this31.$inputField = _this31.$el.closest('.input-field');
_this31.$active = $();
_this31._mousedown = false;
_this31._setupDropdown();
_this31._setupEventHandlers();
_this31.$inputField.removeClass('opened').addClass('closed'); //iob
return _this31;
}
_createClass(Autocomplete, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
this._removeDropdown();
this.el.M_Autocomplete = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleInputBlurBound = this._handleInputBlur.bind(this);
this._handleInputKeyupAndFocusBound = this._handleInputKeyupAndFocus.bind(this);
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
this._handleContainerMousedownAndTouchstartBound = this._handleContainerMousedownAndTouchstart.bind(this);
this._handleContainerMouseupAndTouchendBound = this._handleContainerMouseupAndTouchend.bind(this);
this.el.addEventListener('blur', this._handleInputBlurBound);
this.el.addEventListener('keyup', this._handleInputKeyupAndFocusBound);
this.el.addEventListener('focus', this._handleInputKeyupAndFocusBound);
this.el.addEventListener('keydown', this._handleInputKeydownBound);
this.el.addEventListener('click', this._handleInputClickBound);
this.container.addEventListener('mousedown', this._handleContainerMousedownAndTouchstartBound);
this.container.addEventListener('mouseup', this._handleContainerMouseupAndTouchendBound);
if (typeof window.ontouchstart !== 'undefined') {
this.container.addEventListener('touchstart', this._handleContainerMousedownAndTouchstartBound);
this.container.addEventListener('touchend', this._handleContainerMouseupAndTouchendBound);
}
}
/**
* Remove Event Handlers
*/
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('blur', this._handleInputBlurBound);
this.el.removeEventListener('keyup', this._handleInputKeyupAndFocusBound);
this.el.removeEventListener('focus', this._handleInputKeyupAndFocusBound);
this.el.removeEventListener('keydown', this._handleInputKeydownBound);
this.el.removeEventListener('click', this._handleInputClickBound);
this.container.removeEventListener('mousedown', this._handleContainerMousedownAndTouchstartBound);
this.container.removeEventListener('mouseup', this._handleContainerMouseupAndTouchendBound);
if (typeof window.ontouchstart !== 'undefined') {
this.container.removeEventListener('touchstart', this._handleContainerMousedownAndTouchstartBound);
this.container.removeEventListener('touchend', this._handleContainerMouseupAndTouchendBound);
}
}
/**
* Setup dropdown
*/
}, {
key: "_setupDropdown",
value: function _setupDropdown() {
var _this32 = this;
this.container = document.createElement('ul');
this.container.id = "autocomplete-options-" + M.guid();
$(this.container).addClass('autocomplete-content dropdown-content');
this.$inputField.append(this.container);
this.el.setAttribute('data-target', this.container.id);
this.dropdown = M.Dropdown.init(this.el, {
autoFocus: false,
closeOnClick: false,
coverTrigger: false,
onItemClick: function (itemEl) {
_this32.selectOption($(itemEl));
}
});
// Sketchy removal of dropdown click handler
this.el.removeEventListener('click', this.dropdown._handleClickBound);
}
/**
* Remove dropdown
*/
}, {
key: "_removeDropdown",
value: function _removeDropdown() {
this.container.parentNode.removeChild(this.container);
}
/**
* Handle Input Blur
*/
}, {
key: "_handleInputBlur",
value: function _handleInputBlur() {
if (!this._mousedown) {
this.close();
this._resetAutocomplete();
}
}
/**
* Handle Input Keyup and Focus
* @param {Event} e
*/
}, {
key: "_handleInputKeyupAndFocus",
value: function _handleInputKeyupAndFocus(e) {
if (e.type === 'keyup') {
Autocomplete._keydown = false;
}
this.count = 0;
var val = this.el.value.toLowerCase();
// Don't capture enter or arrow key usage.
if (e.keyCode === 13 || e.keyCode === 38 || e.keyCode === 40) {
return;
}
// Check if the input isn't empty
// Check if focus triggered by tab
if (this.oldVal !== val && (M.tabPressed || e.type !== 'focus')) {
this.open();
}
// Update oldVal
this.oldVal = val;
}
/**
* Handle Input Keydown
* @param {Event} e
*/
}, {
key: "_handleInputKeydown",
value: function _handleInputKeydown(e) {
Autocomplete._keydown = true;
// Arrow keys and enter key usage
var keyCode = e.keyCode,
liElement = void 0,
numItems = $(this.container).children('li').length;
// select element on Enter
if (keyCode === M.keys.ENTER && this.activeIndex >= 0) {
liElement = $(this.container).children('li').eq(this.activeIndex);
if (liElement.length) {
this.selectOption(liElement);
e.preventDefault();
}
return;
}
// Capture up and down key
if (keyCode === M.keys.ARROW_UP || keyCode === M.keys.ARROW_DOWN) {
e.preventDefault();
if (keyCode === M.keys.ARROW_UP && this.activeIndex > 0) {
this.activeIndex--;
}
if (keyCode === M.keys.ARROW_DOWN && this.activeIndex < numItems - 1) {
this.activeIndex++;
}
this.$active.removeClass('active');
if (this.activeIndex >= 0) {
this.$active = $(this.container).children('li').eq(this.activeIndex);
this.$active.addClass('active');
}
}
}
/**
* Handle Input Click
* @param {Event} e
*/
}, {
key: "_handleInputClick",
value: function _handleInputClick(e) {
this.open();
}
/**
* Handle Container Mousedown and Touchstart
* @param {Event} e
*/
}, {
key: "_handleContainerMousedownAndTouchstart",
value: function _handleContainerMousedownAndTouchstart(e) {
this._mousedown = true;
}
/**
* Handle Container Mouseup and Touchend
* @param {Event} e
*/
}, {
key: "_handleContainerMouseupAndTouchend",
value: function _handleContainerMouseupAndTouchend(e) {
this._mousedown = false;
}
/**
* Highlight partial match
*/
}, {
key: "_highlight",
value: function _highlight(string, $el) {
var img = $el.find('img');
var matchStart = $el.text().toLowerCase().indexOf('' + string.toLowerCase() + ''),
matchEnd = matchStart + string.length - 1,
beforeMatch = $el.text().slice(0, matchStart),
matchText = $el.text().slice(matchStart, matchEnd + 1),
afterMatch = $el.text().slice(matchEnd + 1);
$el.html("<span>" + beforeMatch + "<span class='highlight'>" + matchText + "</span>" + afterMatch + "</span>");
if (img.length) {
$el.prepend(img);
}
}
/**
* Reset current element position
*/
}, {
key: "_resetCurrentElement",
value: function _resetCurrentElement() {
this.activeIndex = -1;
this.$active.removeClass('active');
}
/**
* Reset autocomplete elements
*/
}, {
key: "_resetAutocomplete",
value: function _resetAutocomplete() {
$(this.container).empty();
this._resetCurrentElement();
this.oldVal = null;
this.isOpen = false;
this._mousedown = false;
}
/**
* Select autocomplete option
* @param {Element} el Autocomplete option list item element
*/
}, {
key: "selectOption",
value: function selectOption(el) {
var text = el.text().trim();
this.el.value = text;
this.$el.trigger('change');
this._resetAutocomplete();
this.close();
// Handle onAutocomplete callback.
if (typeof this.options.onAutocomplete === 'function') {
this.options.onAutocomplete.call(this, text);
}
}
/**
* Render dropdown content
* @param {Object} data data set
* @param {String} val current input value
*/
}, {
key: "_renderDropdown",
value: function _renderDropdown(data, val) {
var _this33 = this;
this._resetAutocomplete();
var matchingData = [];
// Gather all matching data
for (var key in data) {
if (data.hasOwnProperty(key) && key.toLowerCase().indexOf(val) !== -1) {
// Break if past limit
if (this.count >= this.options.limit) {
break;
}
var entry = {
data: data[key],
key: key
};
matchingData.push(entry);
this.count++;
}
}
// Sort
if (this.options.sortFunction) {
var sortFunctionBound = function (a, b) {
return _this33.options.sortFunction(a.key.toLowerCase(), b.key.toLowerCase(), val.toLowerCase());
};
matchingData.sort(sortFunctionBound);
}
// Render
for (var i = 0; i < matchingData.length; i++) {
var _entry = matchingData[i];
var $autocompleteOption = $('<li></li>');
if (!!_entry.data) {
$autocompleteOption.append("<img src=\"" + _entry.data + "\" class=\"right circle\"><span>" + _entry.key + "</span>");
} else {
$autocompleteOption.append('<span>' + _entry.key + '</span>');
}
$(this.container).append($autocompleteOption);
this._highlight(val, $autocompleteOption);
}
}
/**
* Open Autocomplete Dropdown
*/
}, {
key: "open",
value: function open() {
var val = this.el.value.toLowerCase();
this._resetAutocomplete();
if (val.length >= this.options.minLength) {
this.isOpen = true;
this._renderDropdown(this.options.data, val);
}
// Open dropdown
if (!this.dropdown.isOpen) {
this.$inputField.removeClass('closed').addClass('opened'); //iob
this.dropdown.open();
} else {
// Recalculate dropdown when its already open
this.dropdown.recalculateDimensions();
}
}
/**
* Close Autocomplete Dropdown
*/
}, {
key: "close",
value: function close() {
this.$inputField.removeClass('opened').addClass('closed'); //iob
this.dropdown.close();
}
/**
* Update Data
* @param {Object} data
*/
}, {
key: "updateData",
value: function updateData(data) {
var val = this.el.value.toLowerCase();
this.options.data = data;
if (this.isOpen) {
this._renderDropdown(data, val);
}
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Autocomplete.__proto__ || Object.getPrototypeOf(Autocomplete), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Autocomplete;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Autocomplete;
}(Component);
/**
* @static
* @memberof Autocomplete
*/
Autocomplete._keydown = false;
M.Autocomplete = Autocomplete;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Autocomplete, 'mautocomplete', 'M_Autocomplete'); //iob
}
})(cash);
(function ($) {
'use strict';
var _defaults = {
dialRadius: 135,
outerRadius: 105,
innerRadius: 70,
tickRadius: 20,
duration: 350,
container: null,
defaultTime: 'now', // default time, 'now' or '13:14' e.g.
fromnow: 0, // Millisecond offset from the defaultTime
// internationalization
i18n: {
done: 'Ok',
clear: 'Clear',
cancel: 'Cancel'
},
autoClose: false, // auto close when minute is selected
twelveHour: true, // change to 12 hour AM/PM clock from 24 hour
vibrate: true // vibrate the device when dragging clock hand
};
/**
* @class
*
*/
var Timepicker = function (_Component10) {
_inherits(Timepicker, _Component10);
function Timepicker(el, options) {
_classCallCheck(this, Timepicker);
var _this34 = _possibleConstructorReturn(this, (Timepicker.__proto__ || Object.getPrototypeOf(Timepicker)).call(this, Timepicker, el, options));
_this34.el.M_Timepicker = _this34;
_this34.options = $.extend({}, Timepicker.defaults, options);
_this34.id = M.guid();
_this34._insertHTMLIntoDOM();
_this34._setupModal();
_this34._setupVariables();
_this34._setupEventHandlers();
_this34._clockSetup();
_this34._pickerSetup();
return _this34;
}
_createClass(Timepicker, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
this._removeEventHandlers();
this.modal.destroy();
$(this.modalEl).remove();
this.el.M_Timepicker = undefined;
}
/**
* Setup Event Handlers
*/
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this._handleInputKeydownBound = this._handleInputKeydown.bind(this);
this._handleInputClickBound = this._handleInputClick.bind(this);
this._handleClockClickStartBound = this._handleClockClickStart.bind(this);
this._handleDocumentClickMoveBound = this._handleDocumentClickMove.bind(this);
this._handleDocumentClickEndBound = this._handleDocumentClickEnd.bind(this);
this.el.addEventListener('click', this._handleInputClickBound);
this.el.addEventListener('keydown', this._handleInputKeydownBound);
this.plate.addEventListener('mousedown', this._handleClockClickStartBound);
this.plate.addEventListener('touchstart', this._handleClockClickStartBound);
$(this.spanHours).on('click', this.showView.bind(this, 'hours'));
$(this.spanMinutes).on('click', this.showView.bind(this, 'minutes'));
}
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.el.removeEventListener('click', this._handleInputClickBound);
this.el.removeEventListener('keydown', this._handleInputKeydownBound);
}
}, {
key: "_handleInputClick",
value: function _handleInputClick() {
this.open();
}
}, {
key: "_handleInputKeydown",
value: function _handleInputKeydown(e) {
if (e.which === M.keys.ENTER) {
e.preventDefault();
this.open();
}
}
}, {
key: "_handleClockClickStart",
value: function _handleClockClickStart(e) {
e.preventDefault();
var clockPlateBR = this.plate.getBoundingClientRect();
var offset = { x: clockPlateBR.left, y: clockPlateBR.top };
this.x0 = offset.x + this.options.dialRadius;
this.y0 = offset.y + this.options.dialRadius;
this.moved = false;
var clickPos = Timepicker._Pos(e);
this.dx = clickPos.x - this.x0;
this.dy = clickPos.y - this.y0;
// Set clock hands
this.setHand(this.dx, this.dy, false);
// Mousemove on document
document.addEventListener('mousemove', this._handleDocumentClickMoveBound);
document.addEventListener('touchmove', this._handleDocumentClickMoveBound);
// Mouseup on document
document.addEventListener('mouseup', this._handleDocumentClickEndBound);
document.addEventListener('touchend', this._handleDocumentClickEndBound);
}
}, {
key: "_handleDocumentClickMove",
value: function _handleDocumentClickMove(e) {
e.preventDefault();
var clickPos = Timepicker._Pos(e);
var x = clickPos.x - this.x0;
var y = clickPos.y - this.y0;
this.moved = true;
this.setHand(x, y, false, true);
}
}, {
key: "_handleDocumentClickEnd",
value: function _handleDocumentClickEnd(e) {
var _this35 = this;
e.preventDefault();
document.removeEventListener('mouseup', this._handleDocumentClickEndBound);
document.removeEventListener('touchend', this._handleDocumentClickEndBound);
var clickPos = Timepicker._Pos(e);
var x = clickPos.x - this.x0;
var y = clickPos.y - this.y0;
if (this.moved && x === this.dx && y === this.dy) {
this.setHand(x, y);
}
if (this.currentView === 'hours') {
this.showView('minutes', this.options.duration / 2);
} else if (this.options.autoClose) {
$(this.minutesView).addClass('timepicker-dial-out'); // iob
setTimeout(function () {
// iob
_this35.done();
}, this.options.duration / 2);
}
// Unbind mousemove event
document.removeEventListener('mousemove', this._handleDocumentClickMoveBound);
document.removeEventListener('touchmove', this._handleDocumentClickMoveBound);
}
}, {
key: "_insertHTMLIntoDOM",
value: function _insertHTMLIntoDOM() {
this.$modalEl = $(Timepicker._template);
this.modalEl = this.$modalEl[0];
this.modalEl.id = 'modal-' + this.id;
// Append popover to input by default
var containerEl = document.querySelector(this.options.container);
if (this.options.container && !!containerEl) {
this.$modalEl.appendTo(containerEl);
} else {
this.$modalEl.insertBefore(this.el);
}
}
}, {
key: "_setupModal",
value: function _setupModal() {
var _this36 = this;
this.modal = M.Modal.init(this.modalEl, {
onCloseEnd: function () {
_this36.isOpen = false;
}
});
}
}, {
key: "_setupVariables",
value: function _setupVariables() {
this.currentView = 'hours';
this.vibrate = navigator.vibrate ? 'vibrate' : navigator.webkitVibrate ? 'webkitVibrate' : null;
this._canvas = this.modalEl.querySelector('.timepicker-canvas');
this.plate = this.modalEl.querySelector('.timepicker-plate');
this.hoursView = this.modalEl.querySelector('.timepicker-hours');
this.minutesView = this.modalEl.querySelector('.timepicker-minutes');
this.spanHours = this.modalEl.querySelector('.timepicker-span-hours');
this.spanMinutes = this.modalEl.querySelector('.timepicker-span-minutes');
this.spanAmPm = this.modalEl.querySelector('.timepicker-span-am-pm');
this.footer = this.modalEl.querySelector('.timepicker-footer');
this.amOrPm = 'PM';
}
}, {
key: "_pickerSetup",
value: function _pickerSetup() {
$('<button class="btn-flat timepicker-clear waves-effect" type="button" tabindex="' + (this.options.twelveHour ? '3' : '1') + '">' + this.options.i18n.clear + '</button>').appendTo(this.footer).on('click', this.clear.bind(this));
var confirmationBtnsContainer = $('<div class="confirmation-btns"></div>');
$('<button class="btn-flat timepicker-close waves-effect" type="button" tabindex="' + (this.options.twelveHour ? '3' : '1') + '">' + this.options.i18n.cancel + '</button>').appendTo(confirmationBtnsContainer).on('click', this.close.bind(this));
$('<button class="btn-flat timepicker-close waves-effect" type="button" tabindex="' + (this.options.twelveHour ? '3' : '1') + '">' + this.options.i18n.done + '</button>').appendTo(confirmationBtnsContainer).on('click', this.done.bind(this));
confirmationBtnsContainer.appendTo(this.footer);
}
}, {
key: "_clockSetup",
value: function _clockSetup() {
if (this.options.twelveHour) {
this.$amBtn = $('<div class="am-btn">AM</div>');
this.$pmBtn = $('<div class="pm-btn">PM</div>');
this.$amBtn.on('click', this._handleAmPmClick.bind(this)).appendTo(this.spanAmPm);
this.$pmBtn.on('click', this._handleAmPmClick.bind(this)).appendTo(this.spanAmPm);
}
this._buildHoursView();
this._buildMinutesView();
this._buildSVGClock();
}
}, {
key: "_buildSVGClock",
value: function _buildSVGClock() {
// Draw clock hands and others
var dialRadius = this.options.dialRadius;
var tickRadius = this.options.tickRadius;
var diameter = dialRadius * 2;
var svg = Timepicker._createSVGEl('svg');
svg.setAttribute('class', 'timepicker-svg');
svg.setAttribute('width', diameter);
svg.setAttribute('height', diameter);
var g = Timepicker._createSVGEl('g');
g.setAttribute('transform', 'translate(' + dialRadius + ',' + dialRadius + ')');
var bearing = Timepicker._createSVGEl('circle');
bearing.setAttribute('class', 'timepicker-canvas-bearing');
bearing.setAttribute('cx', 0);
bearing.setAttribute('cy', 0);
bearing.setAttribute('r', 4);
var hand = Timepicker._createSVGEl('line');
hand.setAttribute('x1', 0);
hand.setAttribute('y1', 0);
var bg = Timepicker._createSVGEl('circle');
bg.setAttribute('class', 'timepicker-canvas-bg');
bg.setAttribute('r', tickRadius);
g.appendChild(hand);
g.appendChild(bg);
g.appendChild(bearing);
svg.appendChild(g);
this._canvas.appendChild(svg);
this.hand = hand;
this.bg = bg;
this.bearing = bearing;
this.g = g;
}
}, {
key: "_buildHoursView",
value: function _buildHoursView() {
var $tick = $('<div class="timepicker-tick"></div>');
// Hours view
if (this.options.twelveHour) {
for (var i = 1; i < 13; i += 1) {
var tick = $tick.clone();
var radian = i / 6 * Math.PI;
var radius = this.options.outerRadius;
tick.css({
left: this.options.dialRadius + Math.sin(radian) * radius - this.options.tickRadius + 'px',
top: this.options.dialRadius - Math.cos(radian) * radius - this.options.tickRadius + 'px'
});
tick.html(i === 0 ? '00' : i);
this.hoursView.appendChild(tick[0]);
// tick.on(mousedownEvent, mousedown);
}
} else {
for (var _i = 0; _i < 24; _i += 1) {
var _tick = $tick.clone();
var _radian = _i / 6 * Math.PI;
var inner = _i > 0 && _i < 13;
var _radius = inner ? this.options.innerRadius : this.options.outerRadius;
_tick.css({
left: this.options.dialRadius + Math.sin(_radian) * _radius - this.options.tickRadius + 'px',
top: this.options.dialRadius - Math.cos(_radian) * _radius - this.options.tickRadius + 'px'
});
_tick.html(_i === 0 ? '00' : _i);
this.hoursView.appendChild(_tick[0]);
// tick.on(mousedownEvent, mousedown);
}
}
}
}, {
key: "_buildMinutesView",
value: function _buildMinutesView() {
var $tick = $('<div class="timepicker-tick"></div>');
// Minutes view
for (var i = 0; i < 60; i += 5) {
var tick = $tick.clone();
var radian = i / 30 * Math.PI;
tick.css({
left: this.options.dialRadius + Math.sin(radian) * this.options.outerRadius - this.options.tickRadius + 'px',
top: this.options.dialRadius - Math.cos(radian) * this.options.outerRadius - this.options.tickRadius + 'px'
});
tick.html(Timepicker._addLeadingZero(i));
this.minutesView.appendChild(tick[0]);
}
}
}, {
key: "_handleAmPmClick",
value: function _handleAmPmClick(e) {
var $btnClicked = $(e.target);
this.amOrPm = $btnClicked.hasClass('am-btn') ? 'AM' : 'PM';
this._updateAmPmView();
}
}, {
key: "_updateAmPmView",
value: function _updateAmPmView() {
if (this.options.twelveHour) {
this.$amBtn.toggleClass('text-primary', this.amOrPm === 'AM');
this.$pmBtn.toggleClass('text-primary', this.amOrPm === 'PM');
}
}
}, {
key: "_updateTimeFromInput",
value: function _updateTimeFromInput() {
// Get the time
var value = ((this.el.value || this.options.defaultTime || '') + '').split(':');
if (this.options.twelveHour && !(typeof value[1] === 'undefined')) {
if (value[1].toUpperCase().indexOf("AM") > 0) {
this.amOrPm = 'AM';
} else {
this.amOrPm = 'PM';
}
value[1] = value[1].replace("AM", "").replace("PM", "");
}
if (value[0] === 'now') {
var now = new Date(+new Date() + this.options.fromnow);
value = [now.getHours(), now.getMinutes()];
if (this.options.twelveHour) {
this.amOrPm = value[0] >= 12 && value[0] < 24 ? 'PM' : 'AM';
}
}
this.hours = +value[0] || 0;
this.minutes = +value[1] || 0;
this.spanHours.innerHTML = this.hours;
this.spanMinutes.innerHTML = Timepicker._addLeadingZero(this.minutes);
this._updateAmPmView();
}
}, {
key: "showView",
value: function showView(view, delay) {
if (view === 'minutes' && $(this.hoursView).css("visibility") === "visible") {
// raiseCallback(this.options.beforeHourSelect);
}
var isHours = view === 'hours',
nextView = isHours ? this.hoursView : this.minutesView,
hideView = isHours ? this.minutesView : this.hoursView;
this.currentView = view;
$(this.spanHours).toggleClass('text-primary', isHours);
$(this.spanMinutes).toggleClass('text-primary', !isHours);
// Transition view
hideView.classList.add('timepicker-dial-out');
$(nextView).css('visibility', 'visible').removeClass('timepicker-dial-out');
// Reset clock hand
this.resetClock(delay);
// After transitions ended
clearTimeout(this.toggleViewTimer);
this.toggleViewTimer = setTimeout(function () {
$(hideView).css('visibility', 'hidden');
}, this.options.duration);
}
}, {
key: "resetClock",
value: function resetClock(delay) {
var view = this.currentView,
value = this[view],
isHours = view === 'hours',
unit = Math.PI / (isHours ? 6 : 30),
radian = value * unit,
radius = isHours && value > 0 && value < 13 ? this.options.innerRadius : this.options.outerRadius,
x = Math.sin(radian) * radius,
y = -Math.cos(radian) * radius,
self = this;
if (delay) {
$(this.canvas).addClass('timepicker-canvas-out');
setTimeout(function () {
$(self.canvas).removeClass('timepicker-canvas-out');
self.setHand(x, y);
}, delay);
} else {
this.setHand(x, y);
}
}
}, {
key: "setHand",
value: function setHand(x, y, roundBy5) {
var _this37 = this;
var radian = Math.atan2(x, -y),
isHours = this.currentView === 'hours',
unit = Math.PI / (isHours || roundBy5 ? 6 : 30),
z = Math.sqrt(x * x + y * y),
inner = isHours && z < (this.options.outerRadius + this.options.innerRadius) / 2,
radius = inner ? this.options.innerRadius : this.options.outerRadius;
if (this.options.twelveHour) {
radius = this.options.outerRadius;
}
// Radian should in range [0, 2PI]
if (radian < 0) {
radian = Math.PI * 2 + radian;
}
// Get the round value
var value = Math.round(radian / unit);
// Get the round radian
radian = value * unit;
// Correct the hours or minutes
if (this.options.twelveHour) {
if (isHours) {
if (value === 0) value = 12;
} else {
if (roundBy5) value *= 5;
if (value === 60) value = 0;
}
} else {
if (isHours) {
if (value === 12) {
value = 0;
}
value = inner ? value === 0 ? 12 : value : value === 0 ? 0 : value + 12;
} else {
if (roundBy5) {
value *= 5;
}
if (value === 60) {
value = 0;
}
}
}
// Once hours or minutes changed, vibrate the device
if (this[this.currentView] !== value) {
if (this.vibrate && this.options.vibrate) {
// Do not vibrate too frequently
if (!this.vibrateTimer) {
navigator[this.vibrate](10);
this.vibrateTimer = setTimeout(function () {
_this37.vibrateTimer = null;
}, 100);
}
}
}
this[this.currentView] = value;
if (isHours) {
this['spanHours'].innerHTML = value;
} else {
this['spanMinutes'].innerHTML = Timepicker._addLeadingZero(value);
}
// Set clock hand and others' position
var cx1 = Math.sin(radian) * (radius - this.options.tickRadius),
cy1 = -Math.cos(radian) * (radius - this.options.tickRadius),
cx2 = Math.sin(radian) * radius,
cy2 = -Math.cos(radian) * radius;
this.hand.setAttribute('x2', cx1);
this.hand.setAttribute('y2', cy1);
this.bg.setAttribute('cx', cx2);
this.bg.setAttribute('cy', cy2);
}
}, {
key: "open",
value: function open() {
if (this.isOpen) {
return;
}
this.isOpen = true;
this._updateTimeFromInput();
this.showView('hours');
this.modal.open();
}
}, {
key: "close",
value: function close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
this.modal.close();
}
/**
* Finish timepicker selection.
*/
}, {
key: "done",
value: function done(e, clearValue) {
// Set input value
var last = this.el.value;
var value = clearValue ? '' : Timepicker._addLeadingZero(this.hours) + ':' + Timepicker._addLeadingZero(this.minutes);
this.time = value;
if (!clearValue && this.options.twelveHour) {
value = value + " " + this.amOrPm;
}
this.el.value = value;
// Trigger change event
if (value !== last) {
this.$el.trigger('change');
}
this.close();
this.el.focus();
}
}, {
key: "clear",
value: function clear() {
this.done(null, true);
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Timepicker.__proto__ || Object.getPrototypeOf(Timepicker), "init", this).call(this, this, els, options);
}
}, {
key: "_addLeadingZero",
value: function _addLeadingZero(num) {
return (num < 10 ? '0' : '') + num;
}
}, {
key: "_createSVGEl",
value: function _createSVGEl(name) {
var svgNS = 'http://www.w3.org/2000/svg';
return document.createElementNS(svgNS, name);
}
/**
* @typedef {Object} Point
* @property {number} x The X Coordinate
* @property {number} y The Y Coordinate
*/
/**
* Get x position of mouse or touch event
* @param {Event} e
* @return {Point} x and y location
*/
}, {
key: "_Pos",
value: function _Pos(e) {
if (e.targetTouches && e.targetTouches.length >= 1) {
return { x: e.targetTouches[0].clientX, y: e.targetTouches[0].clientY };
}
// mouse event
return { x: e.clientX, y: e.clientY };
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Timepicker;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Timepicker;
}(Component);
Timepicker._template = ['<div class= "modal timepicker-modal">', '<div class="modal-content timepicker-container">', '<div class="timepicker-digital-display">', '<div class="timepicker-text-container">', '<div class="timepicker-display-column">', '<span class="timepicker-span-hours text-primary"></span>', ':', '<span class="timepicker-span-minutes"></span>', '</div>', '<div class="timepicker-display-column timepicker-display-am-pm">', '<div class="timepicker-span-am-pm"></div>', '</div>', '</div>', '</div>', '<div class="timepicker-analog-display">', '<div class="timepicker-plate">', '<div class="timepicker-canvas"></div>', '<div class="timepicker-dial timepicker-hours"></div>', '<div class="timepicker-dial timepicker-minutes timepicker-dial-out"></div>', '</div>', '<div class="timepicker-footer"></div>', '</div>', '</div>', '</div>'].join('');
M.Timepicker = Timepicker;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Timepicker, 'timepicker', 'M_Timepicker');
}
})(cash);
(function ($, anim) {
'use strict';
var _defaults = {
exitDelay: 200,
enterDelay: 0,
html: null,
margin: 5,
inDuration: 250,
outDuration: 200,
position: 'bottom',
transitionMovement: 10
};
/**
* @class
*
*/
var Tooltip = function (_Component11) {
_inherits(Tooltip, _Component11);
/**
* Construct Tooltip instance
* @constructor
* @param {Element} el
* @param {Object} options
*/
function Tooltip(el, options) {
_classCallCheck(this, Tooltip);
var _this38 = _possibleConstructorReturn(this, (Tooltip.__proto__ || Object.getPrototypeOf(Tooltip)).call(this, Tooltip, el, options));
_this38.el.M_Tooltip = _this38;
_this38.options = $.extend({}, Tooltip.defaults, options);
_this38.isOpen = false;
_this38.isHovered = false;
_this38._appendTooltipEl();
_this38._setupEventHandlers();
return _this38;
}
_createClass(Tooltip, [{
key: "destroy",
/**
* Teardown component
*/
value: function destroy() {
$(this.tooltipEl).remove();
this._removeEventHandlers();
this.$el[0].M_Tooltip = undefined;
}
}, {
key: "_appendTooltipEl",
value: function _appendTooltipEl() {
var tooltipEl = document.createElement('div');
tooltipEl.classList.add('material-tooltip');
this.tooltipEl = tooltipEl;
var tooltipContentEl = document.createElement('div');
tooltipContentEl.classList.add('tooltip-content');
tooltipContentEl.innerHTML = this.options.html;
tooltipEl.appendChild(tooltipContentEl);
document.body.appendChild(tooltipEl);
}
}, {
key: "_updateTooltipContent",
value: function _updateTooltipContent() {
this.tooltipEl.querySelector('.tooltip-content').innerHTML = this.options.html;
}
}, {
key: "_setupEventHandlers",
value: function _setupEventHandlers() {
this.handleMouseEnterBound = this._handleMouseEnter.bind(this);
this.handleMouseLeaveBound = this._handleMouseLeave.bind(this);
this.$el[0].addEventListener('mouseenter', this.handleMouseEnterBound);
this.$el[0].addEventListener('mouseleave', this.handleMouseLeaveBound);
}
}, {
key: "_removeEventHandlers",
value: function _removeEventHandlers() {
this.$el[0].removeEventListener('mouseenter', this.handleMouseEnterBound);
this.$el[0].removeEventListener('mouseleave', this.handleMouseLeaveBound);
}
}, {
key: "open",
value: function open() {
if (this.isOpen) {
return;
}
this.isOpen = true;
// Update tooltip content with HTML attribute options
this.options = $.extend({}, this.options, this._getAttributeOptions());
this._updateTooltipContent();
this._setEnterDelayTimeout();
}
}, {
key: "close",
value: function close() {
if (!this.isOpen) {
return;
}
this.isOpen = false;
this._setExitDelayTimeout();
}
/**
* Create timeout which delays when the tooltip closes
*/
}, {
key: "_setExitDelayTimeout",
value: function _setExitDelayTimeout() {
var _this39 = this;
clearTimeout(this._exitDelayTimeout);
this._exitDelayTimeout = setTimeout(function () {
if (_this39.isHovered) {
return;
}
_this39._animateOut();
}, this.options.exitDelay);
}
/**
* Create timeout which delays when the toast closes
*/
}, {
key: "_setEnterDelayTimeout",
value: function _setEnterDelayTimeout() {
var _this40 = this;
clearTimeout(this._enterDelayTimeout);
this._enterDelayTimeout = setTimeout(function () {
if (!_this40.isHovered) {
return;
}
_this40._animateIn();
}, this.options.enterDelay);
}
}, {
key: "_positionTooltip",
value: function _positionTooltip() {
var origin = this.$el[0],
tooltip = this.tooltipEl,
originHeight = origin.offsetHeight,
originWidth = origin.offsetWidth,
tooltipHeight = tooltip.offsetHeight,
tooltipWidth = tooltip.offsetWidth,
newCoordinates = void 0,
margin = this.options.margin,
targetTop = void 0,
targetLeft = void 0;
this.xMovement = 0, this.yMovement = 0;
targetTop = origin.getBoundingClientRect().top + M.getDocumentScrollTop();
targetLeft = origin.getBoundingClientRect().left + M.getDocumentScrollLeft();
if (this.options.position === 'top') {
targetTop += -tooltipHeight - margin;
targetLeft += originWidth / 2 - tooltipWidth / 2;
this.yMovement = -this.options.transitionMovement;
} else if (this.options.position === 'right') {
targetTop += originHeight / 2 - tooltipHeight / 2;
targetLeft += originWidth + margin;
this.xMovement = this.options.transitionMovement;
} else if (this.options.position === 'left') {
targetTop += originHeight / 2 - tooltipHeight / 2;
targetLeft += -tooltipWidth - margin;
this.xMovement = -this.options.transitionMovement;
} else {
targetTop += originHeight + margin;
targetLeft += originWidth / 2 - tooltipWidth / 2;
this.yMovement = this.options.transitionMovement;
}
newCoordinates = this._repositionWithinScreen(targetLeft, targetTop, tooltipWidth, tooltipHeight);
$(tooltip).css({
top: newCoordinates.y + 'px',
left: newCoordinates.x + 'px'
});
}
}, {
key: "_repositionWithinScreen",
value: function _repositionWithinScreen(x, y, width, height) {
var scrollLeft = M.getDocumentScrollLeft();
var scrollTop = M.getDocumentScrollTop();
var newX = x - scrollLeft;
var newY = y - scrollTop;
var bounding = {
left: newX,
top: newY,
width: width,
height: height
};
var offset = this.options.margin + this.options.transitionMovement;
var edges = M.checkWithinContainer(document.body, bounding, offset);
if (edges.left) {
newX = offset;
} else if (edges.right) {
newX -= newX + width - window.innerWidth;
}
if (edges.top) {
newY = offset;
} else if (edges.bottom) {
newY -= newY + height - window.innerHeight;
}
return {
x: newX + scrollLeft,
y: newY + scrollTop
};
}
}, {
key: "_animateIn",
value: function _animateIn() {
this._positionTooltip();
this.tooltipEl.style.visibility = 'visible';
anim.remove(this.tooltipEl);
anim({
targets: this.tooltipEl,
opacity: 1,
translateX: this.xMovement,
translateY: this.yMovement,
duration: this.options.inDuration,
easing: 'easeOutCubic'
});
}
}, {
key: "_animateOut",
value: function _animateOut() {
anim.remove(this.tooltipEl);
anim({
targets: this.tooltipEl,
opacity: 0,
translateX: 0,
translateY: 0,
duration: this.options.outDuration,
easing: 'easeOutCubic'
});
}
}, {
key: "_handleMouseEnter",
value: function _handleMouseEnter() {
this.isHovered = true;
this.open();
}
}, {
key: "_handleMouseLeave",
value: function _handleMouseLeave() {
this.isHovered = false;
this.close();
}
}, {
key: "_getAttributeOptions",
value: function _getAttributeOptions() {
var attributeOptions = {};
var tooltipTextOption = this.$el[0].getAttribute('data-tooltip');
var positionOption = this.$el[0].getAttribute('data-position');
if (tooltipTextOption) {
attributeOptions.html = tooltipTextOption;
}
if (positionOption) {
attributeOptions.position = positionOption;
}
return attributeOptions;
}
}], [{
key: "init",
value: function init(els, options) {
return _get(Tooltip.__proto__ || Object.getPrototypeOf(Tooltip), "init", this).call(this, this, els, options);
}
/**
* Get Instance
*/
}, {
key: "getInstance",
value: function getInstance(el) {
var domElem = !!el.jquery ? el[0] : el;
return domElem.M_Tooltip;
}
}, {
key: "defaults",
get: function () {
return _defaults;
}
}]);
return Tooltip;
}(Component);
M.Tooltip = Tooltip;
if (M.jQueryLoaded) {
M.initializeJqueryWrapper(Tooltip, 'tooltip', 'M_Tooltip');
}
})(cash, M.anime);
/*!
* Bootstrap Colorpicker
* http://mjolnic.github.io/bootstrap-colorpicker/
*
* Originally written by (c) 2012 Stefan Petre
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* @todo Update DOCS
*/
(function (factory) {
"use strict";
if (typeof exports === 'object') {
module.exports = factory(window.jQuery);
} else if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (window.jQuery && !window.jQuery.fn.colorpicker) {
factory(window.jQuery);
}
})(function ($) {
'use strict';
// Color object
var Color = function (val, customColors) {
this.value = {
h: 0,
s: 0,
b: 0,
a: 1
};
this.origFormat = null; // original string format
if (customColors) {
$.extend(this.colors, customColors);
}
if (val) {
if (val.toLowerCase !== undefined) {
// cast to string
val = val + '';
this.setColor(val);
} else if (val.h !== undefined) {
this.value = val;
}
}
};
Color.prototype = {
constructor: Color,
// 140 predefined colors from the HTML Colors spec
colors: {
"aliceblue": "#f0f8ff",
"antiquewhite": "#faebd7",
"aqua": "#00ffff",
"aquamarine": "#7fffd4",
"azure": "#f0ffff",
"beige": "#f5f5dc",
"bisque": "#ffe4c4",
"black": "#000000",
"blanchedalmond": "#ffebcd",
"blue": "#0000ff",
"blueviolet": "#8a2be2",
"brown": "#a52a2a",
"burlywood": "#deb887",
"cadetblue": "#5f9ea0",
"chartreuse": "#7fff00",
"chocolate": "#d2691e",
"coral": "#ff7f50",
"cornflowerblue": "#6495ed",
"cornsilk": "#fff8dc",
"crimson": "#dc143c",
"cyan": "#00ffff",
"darkblue": "#00008b",
"darkcyan": "#008b8b",
"darkgoldenrod": "#b8860b",
"darkgray": "#a9a9a9",
"darkgreen": "#006400",
"darkkhaki": "#bdb76b",
"darkmagenta": "#8b008b",
"darkolivegreen": "#556b2f",
"darkorange": "#ff8c00",
"darkorchid": "#9932cc",
"darkred": "#8b0000",
"darksalmon": "#e9967a",
"darkseagreen": "#8fbc8f",
"darkslateblue": "#483d8b",
"darkslategray": "#2f4f4f",
"darkturquoise": "#00ced1",
"darkviolet": "#9400d3",
"deeppink": "#ff1493",
"deepskyblue": "#00bfff",
"dimgray": "#696969",
"dodgerblue": "#1e90ff",
"firebrick": "#b22222",
"floralwhite": "#fffaf0",
"forestgreen": "#228b22",
"fuchsia": "#ff00ff",
"gainsboro": "#dcdcdc",
"ghostwhite": "#f8f8ff",
"gold": "#ffd700",
"goldenrod": "#daa520",
"gray": "#808080",
"green": "#008000",
"greenyellow": "#adff2f",
"honeydew": "#f0fff0",
"hotpink": "#ff69b4",
"indianred": "#cd5c5c",
"indigo": "#4b0082",
"ivory": "#fffff0",
"khaki": "#f0e68c",
"lavender": "#e6e6fa",
"lavenderblush": "#fff0f5",
"lawngreen": "#7cfc00",
"lemonchiffon": "#fffacd",
"lightblue": "#add8e6",
"lightcoral": "#f08080",
"lightcyan": "#e0ffff",
"lightgoldenrodyellow": "#fafad2",
"lightgrey": "#d3d3d3",
"lightgreen": "#90ee90",
"lightpink": "#ffb6c1",
"lightsalmon": "#ffa07a",
"lightseagreen": "#20b2aa",
"lightskyblue": "#87cefa",
"lightslategray": "#778899",
"lightsteelblue": "#b0c4de",
"lightyellow": "#ffffe0",
"lime": "#00ff00",
"limegreen": "#32cd32",
"linen": "#faf0e6",
"magenta": "#ff00ff",
"maroon": "#800000",
"mediumaquamarine": "#66cdaa",
"mediumblue": "#0000cd",
"mediumorchid": "#ba55d3",
"mediumpurple": "#9370d8",
"mediumseagreen": "#3cb371",
"mediumslateblue": "#7b68ee",
"mediumspringgreen": "#00fa9a",
"mediumturquoise": "#48d1cc",
"mediumvioletred": "#c71585",
"midnightblue": "#191970",
"mintcream": "#f5fffa",
"mistyrose": "#ffe4e1",
"moccasin": "#ffe4b5",
"navajowhite": "#ffdead",
"navy": "#000080",
"oldlace": "#fdf5e6",
"olive": "#808000",
"olivedrab": "#6b8e23",
"orange": "#ffa500",
"orangered": "#ff4500",
"orchid": "#da70d6",
"palegoldenrod": "#eee8aa",
"palegreen": "#98fb98",
"paleturquoise": "#afeeee",
"palevioletred": "#d87093",
"papayawhip": "#ffefd5",
"peachpuff": "#ffdab9",
"peru": "#cd853f",
"pink": "#ffc0cb",
"plum": "#dda0dd",
"powderblue": "#b0e0e6",
"purple": "#800080",
"red": "#ff0000",
"rosybrown": "#bc8f8f",
"royalblue": "#4169e1",
"saddlebrown": "#8b4513",
"salmon": "#fa8072",
"sandybrown": "#f4a460",
"seagreen": "#2e8b57",
"seashell": "#fff5ee",
"sienna": "#a0522d",
"silver": "#c0c0c0",
"skyblue": "#87ceeb",
"slateblue": "#6a5acd",
"slategray": "#708090",
"snow": "#fffafa",
"springgreen": "#00ff7f",
"steelblue": "#4682b4",
"tan": "#d2b48c",
"teal": "#008080",
"thistle": "#d8bfd8",
"tomato": "#ff6347",
"turquoise": "#40e0d0",
"violet": "#ee82ee",
"wheat": "#f5deb3",
"white": "#ffffff",
"whitesmoke": "#f5f5f5",
"yellow": "#ffff00",
"yellowgreen": "#9acd32",
"transparent": "transparent"
},
_sanitizeNumber: function (val) {
if (typeof val === 'number') {
return val;
}
if (isNaN(val) || val === null || val === '' || val === undefined) {
return 1;
}
if (val.toLowerCase !== undefined) {
return parseFloat(val);
}
return 1;
},
isTransparent: function (strVal) {
if (!strVal) {
return false;
}
strVal = strVal.toLowerCase().trim();
return strVal === 'transparent' || strVal.match(/#?00000000/) || strVal.match(/(rgba|hsla)\(0,0,0,0?\.?0\)/);
},
rgbaIsTransparent: function (rgba) {
return rgba.r === 0 && rgba.g === 0 && rgba.b === 0 && rgba.a === 0;
},
//parse a string to HSB
setColor: function (strVal) {
strVal = strVal.toLowerCase().trim();
if (strVal) {
if (this.isTransparent(strVal)) {
this.value = {
h: 0,
s: 0,
b: 0,
a: 0
};
} else {
this.value = this.stringToHSB(strVal) || {
h: 0,
s: 0,
b: 0,
a: 1
}; // if parser fails, defaults to black
}
}
},
stringToHSB: function (strVal) {
strVal = strVal.toLowerCase();
var alias;
if (typeof this.colors[strVal] !== 'undefined') {
strVal = this.colors[strVal];
alias = 'alias';
}
var that = this,
result = false;
$.each(this.stringParsers, function (i, parser) {
var match = parser.re.exec(strVal),
values = match && parser.parse.apply(that, [match]),
format = alias || parser.format || 'rgba';
if (values) {
if (format.match(/hsla?/)) {
result = that.RGBtoHSB.apply(that, that.HSLtoRGB.apply(that, values));
} else {
result = that.RGBtoHSB.apply(that, values);
}
that.origFormat = format;
return false;
}
return true;
});
return result;
},
setHue: function (h) {
this.value.h = 1 - h;
},
setSaturation: function (s) {
this.value.s = s;
},
setBrightness: function (b) {
this.value.b = 1 - b;
},
setAlpha: function (a) {
this.value.a = parseInt((1 - a) * 100, 10) / 100;
},
toRGB: function (h, s, b, a) {
if (!h) {
h = this.value.h;
s = this.value.s;
b = this.value.b;
}
h *= 360;
var R, G, B, X, C;
h = h % 360 / 60;
C = b * s;
X = C * (1 - Math.abs(h % 2 - 1));
R = G = B = b - C;
h = ~~h;
R += [C, X, 0, 0, X, C][h];
G += [X, C, C, X, 0, 0][h];
B += [0, 0, X, C, C, X][h];
return {
r: Math.round(R * 255),
g: Math.round(G * 255),
b: Math.round(B * 255),
a: a || this.value.a
};
},
toHex: function (h, s, b, a) {
var rgb = this.toRGB(h, s, b, a);
if (this.rgbaIsTransparent(rgb)) {
return 'transparent';
}
return '#' + (1 << 24 | parseInt(rgb.r) << 16 | parseInt(rgb.g) << 8 | parseInt(rgb.b)).toString(16).substr(1);
},
toHSL: function (h, s, b, a) {
h = h || this.value.h;
s = s || this.value.s;
b = b || this.value.b;
a = a || this.value.a;
var H = h,
L = (2 - s) * b,
S = s * b;
if (L > 0 && L <= 1) {
S /= L;
} else {
S /= 2 - L;
}
L /= 2;
if (S > 1) {
S = 1;
}
return {
h: isNaN(H) ? 0 : H,
s: isNaN(S) ? 0 : S,
l: isNaN(L) ? 0 : L,
a: isNaN(a) ? 0 : a
};
},
toAlias: function (r, g, b, a) {
var rgb = this.toHex(r, g, b, a);
for (var alias in this.colors) {
if (this.colors[alias] === rgb) {
return alias;
}
}
return false;
},
RGBtoHSB: function (r, g, b, a) {
r /= 255;
g /= 255;
b /= 255;
var H, S, V, C;
V = Math.max(r, g, b);
C = V - Math.min(r, g, b);
H = C === 0 ? null : V === r ? (g - b) / C : V === g ? (b - r) / C + 2 : (r - g) / C + 4;
H = (H + 360) % 6 * 60 / 360;
S = C === 0 ? 0 : C / V;
return {
h: this._sanitizeNumber(H),
s: S,
b: V,
a: this._sanitizeNumber(a)
};
},
HueToRGB: function (p, q, h) {
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
if (h * 6 < 1) {
return p + (q - p) * h * 6;
} else if (h * 2 < 1) {
return q;
} else if (h * 3 < 2) {
return p + (q - p) * (2 / 3 - h) * 6;
} else {
return p;
}
},
HSLtoRGB: function (h, s, l, a) {
if (s < 0) {
s = 0;
}
var q;
if (l <= 0.5) {
q = l * (1 + s);
} else {
q = l + s - l * s;
}
var p = 2 * l - q;
var tr = h + 1 / 3;
var tg = h;
var tb = h - 1 / 3;
var r = Math.round(this.HueToRGB(p, q, tr) * 255);
var g = Math.round(this.HueToRGB(p, q, tg) * 255);
var b = Math.round(this.HueToRGB(p, q, tb) * 255);
return [r, g, b, this._sanitizeNumber(a)];
},
toString: function (format) {
format = format || 'rgba';
var c = false;
switch (format) {
case 'rgb':
{
c = this.toRGB();
if (this.rgbaIsTransparent(c)) {
return 'transparent';
}
return 'rgb(' + c.r + ',' + c.g + ',' + c.b + ')';
}
break;
case 'rgba':
{
c = this.toRGB();
return 'rgba(' + c.r + ',' + c.g + ',' + c.b + ',' + c.a + ')';
}
break;
case 'hsl':
{
c = this.toHSL();
return 'hsl(' + Math.round(c.h * 360) + ',' + Math.round(c.s * 100) + '%,' + Math.round(c.l * 100) + '%)';
}
break;
case 'hsla':
{
c = this.toHSL();
return 'hsla(' + Math.round(c.h * 360) + ',' + Math.round(c.s * 100) + '%,' + Math.round(c.l * 100) + '%,' + c.a + ')';
}
break;
case 'hex':
{
return this.toHex();
}
break;
case 'alias':
return this.toAlias() || this.toHex();
default:
{
return c;
}
break;
}
},
// a set of RE's that can match strings and generate color tuples.
// from John Resig color plugin
// https://github.com/jquery/jquery-color/
stringParsers: [{
re: /rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*?\)/,
format: 'rgb',
parse: function (execResult) {
return [execResult[1], execResult[2], execResult[3], 1];
}
}, {
re: /rgb\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*?\)/,
format: 'rgb',
parse: function (execResult) {
return [2.55 * execResult[1], 2.55 * execResult[2], 2.55 * execResult[3], 1];
}
}, {
re: /rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
format: 'rgba',
parse: function (execResult) {
return [execResult[1], execResult[2], execResult[3], execResult[4]];
}
}, {
re: /rgba\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
format: 'rgba',
parse: function (execResult) {
return [2.55 * execResult[1], 2.55 * execResult[2], 2.55 * execResult[3], execResult[4]];
}
}, {
re: /hsl\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*?\)/,
format: 'hsl',
parse: function (execResult) {
return [execResult[1] / 360, execResult[2] / 100, execResult[3] / 100, execResult[4]];
}
}, {
re: /hsla\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
format: 'hsla',
parse: function (execResult) {
return [execResult[1] / 360, execResult[2] / 100, execResult[3] / 100, execResult[4]];
}
}, {
re: /#?([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
format: 'hex',
parse: function (execResult) {
return [parseInt(execResult[1], 16), parseInt(execResult[2], 16), parseInt(execResult[3], 16), 1];
}
}, {
re: /#?([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/,
format: 'hex',
parse: function (execResult) {
return [parseInt(execResult[1] + execResult[1], 16), parseInt(execResult[2] + execResult[2], 16), parseInt(execResult[3] + execResult[3], 16), 1];
}
}],
colorNameToHex: function (name) {
if (typeof this.colors[name.toLowerCase()] !== 'undefined') {
return this.colors[name.toLowerCase()];
}
return false;
}
};
var defaults = {
horizontal: false, // horizontal mode layout ?
inline: false, //forces to show the colorpicker as an inline element
color: false, //forces a color
format: false, //forces a format
input: 'input', // children input selector
container: false, // container selector
component: '.add-on, .input-group-addon', // children component selector
sliders: {
saturation: {
maxLeft: 100,
maxTop: 100,
callLeft: 'setSaturation',
callTop: 'setBrightness'
},
hue: {
maxLeft: 0,
maxTop: 100,
callLeft: false,
callTop: 'setHue'
},
alpha: {
maxLeft: 0,
maxTop: 100,
callLeft: false,
callTop: 'setAlpha'
}
},
slidersHorz: {
saturation: {
maxLeft: 100,
maxTop: 100,
callLeft: 'setSaturation',
callTop: 'setBrightness'
},
hue: {
maxLeft: 100,
maxTop: 0,
callLeft: 'setHue',
callTop: false
},
alpha: {
maxLeft: 100,
maxTop: 0,
callLeft: 'setAlpha',
callTop: false
}
},
template: '<div class="colorpicker colorpicker-dropdown">' + '<div class="colorpicker-saturation"><i><b></b></i></div>' + '<div class="colorpicker-hue"><i></i></div>' + '<div class="colorpicker-alpha"><i></i></div>' + '<div class="colorpicker-color"><div /></div>' + '<div class="colorpicker-selectors"></div>' + '</div>',
align: 'right',
customClass: null,
colorSelectors: null
};
var Colorpicker = function (element, options) {
this.element = $(element).addClass('colorpicker-element');
this.options = $.extend(true, {}, defaults, this.element.data(), options);
this.component = this.options.component;
this.component = this.component !== false ? this.element.find(this.component) : false;
if (this.component && this.component.length === 0) {
this.component = false;
} else {
this.options.color = this.component.css('background-color');
}
this.container = this.options.container === true ? this.element : this.options.container;
this.container = this.container !== false ? $(this.container) : false;
// Is the element an input? Should we search inside for any input?
this.input = this.element.is('input') ? this.element : this.options.input ? this.element.find(this.options.input) : false;
if (this.input && this.input.length === 0) {
this.input = false;
}
// Set HSB color
this.color = new Color(this.options.color !== false ? this.options.color : this.getValue(), this.options.colorSelectors);
this.format = this.options.format !== false ? this.options.format : this.color.origFormat;
// Setup picker
this.picker = $(this.options.template);
if (this.options.customClass) {
this.picker.addClass(this.options.customClass);
}
if (this.options.inline) {
this.picker.addClass('colorpicker-inline colorpicker-visible');
} else {
this.picker.addClass('colorpicker-hidden');
}
if (this.options.horizontal) {
this.picker.addClass('colorpicker-horizontal');
}
if (this.format === 'rgba' || this.format === 'hsla' || this.options.format === false) {
this.picker.addClass('colorpicker-with-alpha');
}
if (this.options.align === 'right') {
this.picker.addClass('colorpicker-right');
}
if (this.options.inline === true) {
this.picker.addClass('colorpicker-no-arrow');
}
if (this.options.colorSelectors) {
var colorpicker = this;
$.each(this.options.colorSelectors, function (name, color) {
var $btn = $('<i />').css('background-color', color).data('class', name);
$btn.click(function () {
colorpicker.setValue($(this).css('background-color'));
});
colorpicker.picker.find('.colorpicker-selectors').append($btn);
});
this.picker.find('.colorpicker-selectors').show();
}
this.picker.on('mousedown.colorpicker touchstart.colorpicker', $.proxy(this.mousedown, this));
this.picker.appendTo(this.container ? this.container : $('body'));
// Bind events
if (this.input !== false) {
this.input.on({
'keyup.colorpicker': $.proxy(this.keyup, this)
});
this.input.on({
'change.colorpicker': $.proxy(this.change, this)
});
if (this.component === false) {
this.element.on({
'focus.colorpicker': $.proxy(this.show, this)
});
}
if (this.options.inline === false) {
this.element.on({
'focusout.colorpicker': $.proxy(this.hide, this)
});
}
}
if (this.component !== false) {
this.component.on({
'click.colorpicker': $.proxy(this.show, this)
});
}
if (this.input === false && this.component === false) {
this.element.on({
'click.colorpicker': $.proxy(this.show, this)
});
}
// for HTML5 input[type='color']
if (this.input !== false && this.component !== false && this.input.attr('type') === 'color') {
this.input.on({
'click.colorpicker': $.proxy(this.show, this),
'focus.colorpicker': $.proxy(this.show, this)
});
}
this.update(true);
$($.proxy(function () {
this.element.trigger('create');
}, this));
};
Colorpicker.Color = Color;
Colorpicker.prototype = {
constructor: Colorpicker,
destroy: function () {
this.picker.remove();
this.element.removeData('colorpicker').off('.colorpicker');
if (this.input !== false) {
this.input.off('.colorpicker');
}
if (this.component !== false) {
this.component.off('.colorpicker');
}
this.element.removeClass('colorpicker-element');
this.element.trigger({
type: 'destroy'
});
},
reposition: function () {
if (this.options.inline !== false || this.options.container) {
return false;
}
var type = this.container && this.container[0] !== document.body ? 'position' : 'offset';
var element = this.component || this.element;
var offset = element[type]();
if (this.options.align === 'right') {
offset.left -= this.picker.outerWidth() - element.outerWidth();
}
this.picker.css({
top: offset.top + element.outerHeight(),
left: offset.left
});
},
show: function (e) {
if (this.isDisabled()) {
return false;
}
this.picker.addClass('colorpicker-visible').removeClass('colorpicker-hidden');
this.reposition();
$(window).on('resize.colorpicker', $.proxy(this.reposition, this));
if (e && (!this.hasInput() || this.input.attr('type') === 'color')) {
if (e.stopPropagation && e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
}
if (this.options.inline === false) {
$(window.document).on({
'mousedown.colorpicker': $.proxy(this.hide, this)
});
}
this.element.trigger({
type: 'showPicker',
color: this.color
});
},
hide: function () {
this.picker.addClass('colorpicker-hidden').removeClass('colorpicker-visible');
$(window).off('resize.colorpicker', this.reposition);
$(document).off({
'mousedown.colorpicker': this.hide
});
this.update();
this.element.trigger({
type: 'hidePicker',
color: this.color
});
},
updateData: function (val) {
val = val || this.color.toString(this.format);
this.element.data('color', val);
return val;
},
updateInput: function (val) {
val = val || this.color.toString(this.format);
if (this.input !== false) {
if (this.options.colorSelectors) {
var color = new Color(val, this.options.colorSelectors);
var alias = color.toAlias();
if (typeof this.options.colorSelectors[alias] !== 'undefined') {
val = alias;
}
}
this.input.prop('value', val);
}
return val;
},
updatePicker: function (val) {
if (val !== undefined) {
this.color = new Color(val, this.options.colorSelectors);
}
var sl = this.options.horizontal === false ? this.options.sliders : this.options.slidersHorz;
var icns = this.picker.find('i');
if (icns.length === 0) {
return;
}
if (this.options.horizontal === false) {
sl = this.options.sliders;
icns.eq(1).css('top', sl.hue.maxTop * (1 - this.color.value.h)).end().eq(2).css('top', sl.alpha.maxTop * (1 - this.color.value.a));
} else {
sl = this.options.slidersHorz;
icns.eq(1).css('left', sl.hue.maxLeft * (1 - this.color.value.h)).end().eq(2).css('left', sl.alpha.maxLeft * (1 - this.color.value.a));
}
icns.eq(0).css({
'top': sl.saturation.maxTop - this.color.value.b * sl.saturation.maxTop,
'left': this.color.value.s * sl.saturation.maxLeft
});
this.picker.find('.colorpicker-saturation').css('backgroundColor', this.color.toHex(this.color.value.h, 1, 1, 1));
this.picker.find('.colorpicker-alpha').css('backgroundColor', this.color.toHex());
this.picker.find('.colorpicker-color, .colorpicker-color div').css('backgroundColor', this.color.toString(this.format));
return val;
},
updateComponent: function (val) {
val = val || this.color.toString(this.format);
if (this.component !== false) {
var icn = this.component.find('i').eq(0);
if (icn.length > 0) {
icn.css({
'backgroundColor': val
});
} else {
this.component.css({
'backgroundColor': val
});
}
}
return val;
},
update: function (force) {
var val;
if (this.getValue(false) !== false || force === true) {
// Update input/data only if the current value is not empty
val = this.updateComponent();
this.updateInput(val);
this.updateData(val);
this.updatePicker(); // only update picker if value is not empty
}
return val;
},
setValue: function (val) {
// set color manually
this.color = new Color(val, this.options.colorSelectors);
this.update(true);
this.element.trigger({
type: 'changeColor',
color: this.color,
value: val
});
},
getValue: function (defaultValue) {
defaultValue = defaultValue === undefined ? '#000000' : defaultValue;
var val;
if (this.hasInput()) {
val = this.input.val();
} else {
val = this.element.data('color');
}
if (val === undefined || val === '' || val === null) {
// if not defined or empty, return default
val = defaultValue;
}
return val;
},
hasInput: function () {
return this.input !== false;
},
isDisabled: function () {
if (this.hasInput()) {
return this.input.prop('disabled') === true;
}
return false;
},
disable: function () {
if (this.hasInput()) {
this.input.prop('disabled', true);
this.element.trigger({
type: 'disable',
color: this.color,
value: this.getValue()
});
return true;
}
return false;
},
enable: function () {
if (this.hasInput()) {
this.input.prop('disabled', false);
this.element.trigger({
type: 'enable',
color: this.color,
value: this.getValue()
});
return true;
}
return false;
},
currentSlider: null,
mousePointer: {
left: 0,
top: 0
},
mousedown: function (e) {
if (!e.pageX && !e.pageY && e.originalEvent) {
e.pageX = e.originalEvent.touches[0].pageX;
e.pageY = e.originalEvent.touches[0].pageY;
}
e.stopPropagation();
e.preventDefault();
var target = $(e.target);
//detect the slider and set the limits and callbacks
var zone = target.closest('div');
var sl = this.options.horizontal ? this.options.slidersHorz : this.options.sliders;
if (!zone.is('.colorpicker')) {
if (zone.is('.colorpicker-saturation')) {
this.currentSlider = $.extend({}, sl.saturation);
} else if (zone.is('.colorpicker-hue')) {
this.currentSlider = $.extend({}, sl.hue);
} else if (zone.is('.colorpicker-alpha')) {
this.currentSlider = $.extend({}, sl.alpha);
} else {
return false;
}
var offset = zone.offset();
//reference to guide's style
this.currentSlider.guide = zone.find('i')[0].style;
this.currentSlider.left = e.pageX - offset.left;
this.currentSlider.top = e.pageY - offset.top;
this.mousePointer = {
left: e.pageX,
top: e.pageY
};
//trigger mousemove to move the guide to the current position
$(document).on({
'mousemove.colorpicker': $.proxy(this.mousemove, this),
'touchmove.colorpicker': $.proxy(this.mousemove, this),
'mouseup.colorpicker': $.proxy(this.mouseup, this),
'touchend.colorpicker': $.proxy(this.mouseup, this)
}).trigger('mousemove');
}
return false;
},
mousemove: function (e) {
if (!e.pageX && !e.pageY && e.originalEvent) {
e.pageX = e.originalEvent.touches[0].pageX;
e.pageY = e.originalEvent.touches[0].pageY;
}
e.stopPropagation();
e.preventDefault();
var left = Math.max(0, Math.min(this.currentSlider.maxLeft, this.currentSlider.left + ((e.pageX || this.mousePointer.left) - this.mousePointer.left)));
var top = Math.max(0, Math.min(this.currentSlider.maxTop, this.currentSlider.top + ((e.pageY || this.mousePointer.top) - this.mousePointer.top)));
this.currentSlider.guide.left = left + 'px';
this.currentSlider.guide.top = top + 'px';
if (this.currentSlider.callLeft) {
this.color[this.currentSlider.callLeft].call(this.color, left / this.currentSlider.maxLeft);
}
if (this.currentSlider.callTop) {
this.color[this.currentSlider.callTop].call(this.color, top / this.currentSlider.maxTop);
}
// Change format dynamically
// Only occurs if user choose the dynamic format by
// setting option format to false
if (this.currentSlider.callTop === 'setAlpha' && this.options.format === false) {
// Converting from hex / rgb to rgba
if (this.color.value.a !== 1) {
this.format = 'rgba';
this.color.origFormat = 'rgba';
}
// Converting from rgba to hex
else {
this.format = 'hex';
this.color.origFormat = 'hex';
}
}
this.update(true);
this.element.trigger({
type: 'changeColor',
color: this.color
});
return false;
},
mouseup: function (e) {
e.stopPropagation();
e.preventDefault();
$(document).off({
'mousemove.colorpicker': this.mousemove,
'touchmove.colorpicker': this.mousemove,
'mouseup.colorpicker': this.mouseup,
'touchend.colorpicker': this.mouseup
});
return false;
},
change: function (e) {
this.keyup(e);
},
keyup: function (e) {
if (e.keyCode === 38) {
if (this.color.value.a < 1) {
this.color.value.a = Math.round((this.color.value.a + 0.01) * 100) / 100;
}
this.update(true);
} else if (e.keyCode === 40) {
if (this.color.value.a > 0) {
this.color.value.a = Math.round((this.color.value.a - 0.01) * 100) / 100;
}
this.update(true);
} else {
this.color = new Color(this.input.val(), this.options.colorSelectors);
// Change format dynamically
// Only occurs if user choose the dynamic format by
// setting option format to false
if (this.color.origFormat && this.options.format === false) {
this.format = this.color.origFormat;
}
if (this.getValue(false) !== false) {
this.updateData();
this.updateComponent();
this.updatePicker();
}
}
this.element.trigger({
type: 'changeColor',
color: this.color,
value: this.input.val()
});
}
};
$.colorpicker = Colorpicker;
$.fn.colorpicker = function (option) {
var pickerArgs = arguments,
rv;
var $returnValue = this.each(function () {
var $this = $(this),
inst = $this.data('colorpicker'),
options = typeof option === 'object' ? option : {};
if (!inst && typeof option !== 'string') {
$this.data('colorpicker', new Colorpicker(this, options));
} else {
if (typeof option === 'string') {
rv = inst[option].apply(inst, Array.prototype.slice.call(pickerArgs, 1));
}
}
});
if (option === 'getValue') {
return rv;
}
return $returnValue;
};
$.fn.colorpicker.constructor = Colorpicker;
});
//# sourceMappingURL=materialize.js.map