code
stringlengths
2
1.05M
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * Fetches the backup management usage summaries of the vault. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @param {string} [options.skipToken] skipToken Filter. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link BackupManagementUsageList} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _list(vaultName, resourceGroupName, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } let filter = (options && options.filter !== undefined) ? options.filter : undefined; let skipToken = (options && options.skipToken !== undefined) ? options.skipToken : undefined; let apiVersion = '2016-12-01'; // Validate try { if (vaultName === null || vaultName === undefined || typeof vaultName.valueOf() !== 'string') { throw new Error('vaultName cannot be null or undefined and it must be of type string.'); } if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') { throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.'); } if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') { throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.'); } if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') { throw new Error('filter must be of type string.'); } if (skipToken !== null && skipToken !== undefined && typeof skipToken.valueOf() !== 'string') { throw new Error('skipToken must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupUsageSummaries'; requestUrl = requestUrl.replace('{vaultName}', encodeURIComponent(vaultName)); requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName)); requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId)); let queryParameters = []; queryParameters.push('api-version=' + encodeURIComponent(apiVersion)); if (filter !== null && filter !== undefined) { queryParameters.push('$filter=' + encodeURIComponent(filter)); } if (skipToken !== null && skipToken !== undefined) { queryParameters.push('$skipToken=' + encodeURIComponent(skipToken)); } if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['BackupManagementUsageList']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** Class representing a BackupUsageSummaries. */ class BackupUsageSummaries { /** * Create a BackupUsageSummaries. * @param {RecoveryServicesBackupClient} client Reference to the service client. */ constructor(client) { this.client = client; this._list = _list; } /** * Fetches the backup management usage summaries of the vault. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @param {string} [options.skipToken] skipToken Filter. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BackupManagementUsageList>} - The deserialized result object. * * @reject {Error} - The error object. */ listWithHttpOperationResponse(vaultName, resourceGroupName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._list(vaultName, resourceGroupName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Fetches the backup management usage summaries of the vault. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] OData filter options. * * @param {string} [options.skipToken] skipToken Filter. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {BackupManagementUsageList} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link BackupManagementUsageList} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ list(vaultName, resourceGroupName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._list(vaultName, resourceGroupName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._list(vaultName, resourceGroupName, options, optionalCallback); } } } module.exports = BackupUsageSummaries;
module.exports = require('./as-library'); require('./');
module.exports = [{"isId":true,"priority":100000.0012,"key":"itemContainer","style":{backgroundColor:"#8A0808",borderRadius:"15",opacity:"1",font:{fontSize:"18",fontFamily:"Arial",},}}];
/** * @file name表 * @author mengke01(kekee000@gmail.com) */ define( function (require) { var table = require('./table'); var nameIdTbl = require('../enum/nameId'); var string = require('../util/string'); var platformTbl = require('../enum/platform'); var encodingTbl = require('../enum/encoding'); var name = table.create( 'name', [], { read: function (reader) { var offset = this.offset; reader.seek(offset); var nameTbl = {}; nameTbl.format = reader.readUint16(); nameTbl.count = reader.readUint16(); nameTbl.stringOffset = reader.readUint16(); var nameRecordTbl = []; var count = nameTbl.count; var i; var nameRecord; for (i = 0; i < count; ++i) { nameRecord = {}; nameRecord.platform = reader.readUint16(); nameRecord.encoding = reader.readUint16(); nameRecord.language = reader.readUint16(); nameRecord.nameId = reader.readUint16(); nameRecord.length = reader.readUint16(); nameRecord.offset = reader.readUint16(); nameRecordTbl.push(nameRecord); } offset = offset + nameTbl.stringOffset; // 读取字符名字 for (i = 0; i < count; ++i) { nameRecord = nameRecordTbl[i]; nameRecord.name = reader.readBytes(offset + nameRecord.offset, nameRecord.length); } var names = {}; // mac 下的english name var platform = platformTbl.Macintosh; var encoding = encodingTbl.mac.Default; var language = 0; // 如果有windows 下的 english,则用windows下的 name if (nameRecordTbl.some(function (record) { return record.platform === platformTbl.Microsoft && record.encoding === encodingTbl.win.UCS2 && record.language === 1033; })) { platform = platformTbl.Microsoft; encoding = encodingTbl.win.UCS2; language = 1033; } for (i = 0; i < count; ++i) { nameRecord = nameRecordTbl[i]; if (nameRecord.platform === platform && nameRecord.encoding === encoding && nameRecord.language === language && nameIdTbl[nameRecord.nameId]) { names[nameIdTbl[nameRecord.nameId]] = language === 0 ? string.getUTF8String(nameRecord.name) : string.getUCS2String(nameRecord.name); } } return names; }, write: function (writer, ttf) { var nameRecordTbl = ttf.support.name; writer.writeUint16(0); // format writer.writeUint16(nameRecordTbl.length); // count writer.writeUint16(6 + nameRecordTbl.length * 12); // string offset // write name tbl header var offset = 0; nameRecordTbl.forEach(function (nameRecord) { writer.writeUint16(nameRecord.platform); writer.writeUint16(nameRecord.encoding); writer.writeUint16(nameRecord.language); writer.writeUint16(nameRecord.nameId); writer.writeUint16(nameRecord.name.length); writer.writeUint16(offset); // offset offset += nameRecord.name.length; }); // write name tbl strings nameRecordTbl.forEach(function (nameRecord) { writer.writeBytes(nameRecord.name); }); return writer; }, size: function (ttf) { var names = ttf.name; var nameRecordTbl = []; // 写入name信息 // 这里为了简化书写,仅支持英文编码字符, // 中文编码字符将被转化成url encode var size = 6; Object.keys(names).forEach(function (name) { var id = nameIdTbl.names[name]; var utf8Bytes = string.toUTF8Bytes(names[name]); var usc2Bytes = string.toUCS2Bytes(names[name]); if (undefined !== id) { // mac nameRecordTbl.push({ nameId: id, platform: 1, encoding: 0, language: 0, name: utf8Bytes }); // windows nameRecordTbl.push({ nameId: id, platform: 3, encoding: 1, language: 1033, name: usc2Bytes }); // 子表大小 size += 12 * 2 + utf8Bytes.length + usc2Bytes.length; } }); var namingOrder = ['platform', 'encoding', 'language', 'nameId']; nameRecordTbl = nameRecordTbl.sort(function (a, b) { var l = 0; namingOrder.some(function (name) { var o = a[name] - b[name]; if (o) { l = o; return true; } }); return l; }); // 保存预处理信息 ttf.support.name = nameRecordTbl; return size; } } ); return name; } );
'use strict'; const validator = require('validator'); const Settings = require('../../settings'); module.exports = function(schema) { // Validations schema.path('email').required(true, Settings.Admin.errors.email.required); schema.path('email').validate(validator.isEmail, Settings.Admin.errors.email.invalid); };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /* Tabulator v4.4.2 (c) Oliver Folkerd */ var Edit = function Edit(table) { this.table = table; //hold Tabulator object this.currentCell = false; //hold currently editing cell this.mouseClick = false; //hold mousedown state to prevent click binding being overriden by editor opening this.recursionBlock = false; //prevent focus recursion this.invalidEdit = false; }; //initialize column editor Edit.prototype.initializeColumn = function (column) { var self = this, config = { editor: false, blocked: false, check: column.definition.editable, params: column.definition.editorParams || {} }; //set column editor switch (_typeof(column.definition.editor)) { case "string": if (column.definition.editor === "tick") { column.definition.editor = "tickCross"; console.warn("DEPRECATION WARNING - the tick editor has been deprecated, please use the tickCross editor"); } if (self.editors[column.definition.editor]) { config.editor = self.editors[column.definition.editor]; } else { console.warn("Editor Error - No such editor found: ", column.definition.editor); } break; case "function": config.editor = column.definition.editor; break; case "boolean": if (column.definition.editor === true) { if (typeof column.definition.formatter !== "function") { if (column.definition.formatter === "tick") { column.definition.formatter = "tickCross"; console.warn("DEPRECATION WARNING - the tick editor has been deprecated, please use the tickCross editor"); } if (self.editors[column.definition.formatter]) { config.editor = self.editors[column.definition.formatter]; } else { config.editor = self.editors["input"]; } } else { console.warn("Editor Error - Cannot auto lookup editor for a custom formatter: ", column.definition.formatter); } } break; } if (config.editor) { column.modules.edit = config; } }; Edit.prototype.getCurrentCell = function () { return this.currentCell ? this.currentCell.getComponent() : false; }; Edit.prototype.clearEditor = function () { var cell = this.currentCell, cellEl; this.invalidEdit = false; if (cell) { this.currentCell = false; cellEl = cell.getElement(); cellEl.classList.remove("tabulator-validation-fail"); cellEl.classList.remove("tabulator-editing"); while (cellEl.firstChild) { cellEl.removeChild(cellEl.firstChild); }cell.row.getElement().classList.remove("tabulator-row-editing"); } }; Edit.prototype.cancelEdit = function () { if (this.currentCell) { var cell = this.currentCell; var component = this.currentCell.getComponent(); this.clearEditor(); cell.setValueActual(cell.getValue()); if (cell.column.cellEvents.cellEditCancelled) { cell.column.cellEvents.cellEditCancelled.call(this.table, component); } this.table.options.cellEditCancelled.call(this.table, component); } }; //return a formatted value for a cell Edit.prototype.bindEditor = function (cell) { var self = this, element = cell.getElement(); element.setAttribute("tabindex", 0); element.addEventListener("click", function (e) { if (!element.classList.contains("tabulator-editing")) { element.focus(); } }); element.addEventListener("mousedown", function (e) { self.mouseClick = true; }); element.addEventListener("focus", function (e) { if (!self.recursionBlock) { self.edit(cell, e, false); } }); }; Edit.prototype.focusCellNoEvent = function (cell) { this.recursionBlock = true; if (this.table.browser !== "ie") { cell.getElement().focus(); } this.recursionBlock = false; }; Edit.prototype.editCell = function (cell, forceEdit) { this.focusCellNoEvent(cell); this.edit(cell, false, forceEdit); }; Edit.prototype.edit = function (cell, e, forceEdit) { var self = this, allowEdit = true, rendered = function rendered() {}, element = cell.getElement(), cellEditor, component, params; //prevent editing if another cell is refusing to leave focus (eg. validation fail) if (this.currentCell) { if (!this.invalidEdit) { this.cancelEdit(); } return; } //handle successfull value change function success(value) { if (self.currentCell === cell) { var valid = true; if (cell.column.modules.validate && self.table.modExists("validate")) { valid = self.table.modules.validate.validate(cell.column.modules.validate, cell.getComponent(), value); } if (valid === true) { self.clearEditor(); cell.setValue(value, true); if (self.table.options.dataTree && self.table.modExists("dataTree")) { self.table.modules.dataTree.checkForRestyle(cell); } } else { self.invalidEdit = true; element.classList.add("tabulator-validation-fail"); self.focusCellNoEvent(cell); rendered(); self.table.options.validationFailed.call(self.table, cell.getComponent(), value, valid); } } else { // console.warn("Edit Success Error - cannot call success on a cell that is no longer being edited"); } } //handle aborted edit function cancel() { if (self.currentCell === cell) { self.cancelEdit(); if (self.table.options.dataTree && self.table.modExists("dataTree")) { self.table.modules.dataTree.checkForRestyle(cell); } } else { // console.warn("Edit Success Error - cannot call cancel on a cell that is no longer being edited"); } } function onRendered(callback) { rendered = callback; } if (!cell.column.modules.edit.blocked) { if (e) { e.stopPropagation(); } switch (_typeof(cell.column.modules.edit.check)) { case "function": allowEdit = cell.column.modules.edit.check(cell.getComponent()); break; case "boolean": allowEdit = cell.column.modules.edit.check; break; } if (allowEdit || forceEdit) { self.cancelEdit(); self.currentCell = cell; component = cell.getComponent(); if (this.mouseClick) { this.mouseClick = false; if (cell.column.cellEvents.cellClick) { cell.column.cellEvents.cellClick.call(this.table, e, component); } } if (cell.column.cellEvents.cellEditing) { cell.column.cellEvents.cellEditing.call(this.table, component); } self.table.options.cellEditing.call(this.table, component); params = typeof cell.column.modules.edit.params === "function" ? cell.column.modules.edit.params(component) : cell.column.modules.edit.params; cellEditor = cell.column.modules.edit.editor.call(self, component, onRendered, success, cancel, params); //if editor returned, add to DOM, if false, abort edit if (cellEditor !== false) { if (cellEditor instanceof Node) { element.classList.add("tabulator-editing"); cell.row.getElement().classList.add("tabulator-row-editing"); while (element.firstChild) { element.removeChild(element.firstChild); }element.appendChild(cellEditor); //trigger onRendered Callback rendered(); //prevent editing from triggering rowClick event var children = element.children; for (var i = 0; i < children.length; i++) { children[i].addEventListener("click", function (e) { e.stopPropagation(); }); } } else { console.warn("Edit Error - Editor should return an instance of Node, the editor returned:", cellEditor); element.blur(); return false; } } else { element.blur(); return false; } return true; } else { this.mouseClick = false; element.blur(); return false; } } else { this.mouseClick = false; element.blur(); return false; } }; //default data editors Edit.prototype.editors = { //input element input: function input(cell, onRendered, success, cancel, editorParams) { //create and style input var cellValue = cell.getValue(), input = document.createElement("input"); input.setAttribute("type", editorParams.search ? "search" : "text"); input.style.padding = "4px"; input.style.width = "100%"; input.style.boxSizing = "border-box"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } input.value = typeof cellValue !== "undefined" ? cellValue : ""; onRendered(function () { input.focus(); input.style.height = "100%"; }); function onChange(e) { if ((cellValue === null || typeof cellValue === "undefined") && input.value !== "" || input.value != cellValue) { success(input.value); } else { cancel(); } } //submit new value on blur or change input.addEventListener("change", onChange); input.addEventListener("blur", onChange); //submit new value on enter input.addEventListener("keydown", function (e) { switch (e.keyCode) { case 13: success(input.value); break; case 27: cancel(); break; } }); return input; }, //resizable text area element textarea: function textarea(cell, onRendered, success, cancel, editorParams) { var self = this, cellValue = cell.getValue(), value = String(cellValue !== null && typeof cellValue !== "undefined" ? cellValue : ""), count = (value.match(/(?:\r\n|\r|\n)/g) || []).length + 1, input = document.createElement("textarea"), scrollHeight = 0; //create and style input input.style.display = "block"; input.style.padding = "2px"; input.style.height = "100%"; input.style.width = "100%"; input.style.boxSizing = "border-box"; input.style.whiteSpace = "pre-wrap"; input.style.resize = "none"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } input.value = value; onRendered(function () { input.focus(); input.style.height = "100%"; }); function onChange(e) { if ((cellValue === null || typeof cellValue === "undefined") && input.value !== "" || input.value != cellValue) { success(input.value); setTimeout(function () { cell.getRow().normalizeHeight(); }, 300); } else { cancel(); } } //submit new value on blur or change input.addEventListener("change", onChange); input.addEventListener("blur", onChange); input.addEventListener("keyup", function () { input.style.height = ""; var heightNow = input.scrollHeight; input.style.height = heightNow + "px"; if (heightNow != scrollHeight) { scrollHeight = heightNow; cell.getRow().normalizeHeight(); } }); input.addEventListener("keydown", function (e) { if (e.keyCode == 27) { cancel(); } }); return input; }, //input element with type of number number: function number(cell, onRendered, success, cancel, editorParams) { var cellValue = cell.getValue(), input = document.createElement("input"); input.setAttribute("type", "number"); if (typeof editorParams.max != "undefined") { input.setAttribute("max", editorParams.max); } if (typeof editorParams.min != "undefined") { input.setAttribute("min", editorParams.min); } if (typeof editorParams.step != "undefined") { input.setAttribute("step", editorParams.step); } //create and style input input.style.padding = "4px"; input.style.width = "100%"; input.style.boxSizing = "border-box"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } input.value = cellValue; var blurFunc = function blurFunc(e) { onChange(); }; onRendered(function () { //submit new value on blur input.removeEventListener("blur", blurFunc); input.focus(); input.style.height = "100%"; //submit new value on blur input.addEventListener("blur", blurFunc); }); function onChange() { var value = input.value; if (!isNaN(value) && value !== "") { value = Number(value); } if (value != cellValue) { success(value); } else { cancel(); } } //submit new value on enter input.addEventListener("keydown", function (e) { switch (e.keyCode) { case 13: // case 9: onChange(); break; case 27: cancel(); break; } }); return input; }, //input element with type of number range: function range(cell, onRendered, success, cancel, editorParams) { var cellValue = cell.getValue(), input = document.createElement("input"); input.setAttribute("type", "range"); if (typeof editorParams.max != "undefined") { input.setAttribute("max", editorParams.max); } if (typeof editorParams.min != "undefined") { input.setAttribute("min", editorParams.min); } if (typeof editorParams.step != "undefined") { input.setAttribute("step", editorParams.step); } //create and style input input.style.padding = "4px"; input.style.width = "100%"; input.style.boxSizing = "border-box"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } input.value = cellValue; onRendered(function () { input.focus(); input.style.height = "100%"; }); function onChange() { var value = input.value; if (!isNaN(value) && value !== "") { value = Number(value); } if (value != cellValue) { success(value); } else { cancel(); } } //submit new value on blur input.addEventListener("blur", function (e) { onChange(); }); //submit new value on enter input.addEventListener("keydown", function (e) { switch (e.keyCode) { case 13: case 9: onChange(); break; case 27: cancel(); break; } }); return input; }, //select select: function select(cell, onRendered, success, cancel, editorParams) { var self = this, cellEl = cell.getElement(), initialValue = cell.getValue(), initialDisplayValue = typeof initialValue !== "undefined" || initialValue === null ? initialValue : typeof editorParams.defaultValue !== "undefined" ? editorParams.defaultValue : "", input = document.createElement("input"), listEl = document.createElement("div"), dataItems = [], displayItems = [], currentItem = {}, blurable = true; this.table.rowManager.element.addEventListener("scroll", cancelItem); if (Array.isArray(editorParams) || !Array.isArray(editorParams) && (typeof editorParams === "undefined" ? "undefined" : _typeof(editorParams)) === "object" && !editorParams.values) { console.warn("DEPRECATION WANRING - values for the select editor must now be passed into the values property of the editorParams object, not as the editorParams object"); editorParams = { values: editorParams }; } function getUniqueColumnValues(field) { var output = {}, data = self.table.getData(), column; if (field) { column = self.table.columnManager.getColumnByField(field); } else { column = cell.getColumn()._getSelf(); } if (column) { data.forEach(function (row) { var val = column.getFieldValue(row); if (val !== null && typeof val !== "undefined" && val !== "") { output[val] = true; } }); if (editorParams.sortValuesList) { if (editorParams.sortValuesList == "asc") { output = Object.keys(output).sort(); } else { output = Object.keys(output).sort().reverse(); } } else { output = Object.keys(output); } } else { console.warn("unable to find matching column to create select lookup list:", field); } return output; } function parseItems(inputValues, curentValue) { var dataList = []; var displayList = []; function processComplexListItem(item) { var item = { label: editorParams.listItemFormatter ? editorParams.listItemFormatter(item.value, item.label) : item.label, value: item.value, element: false }; if (item.value === curentValue || !isNaN(parseFloat(item.value)) && !isNaN(parseFloat(item.value)) && parseFloat(item.value) === parseFloat(curentValue)) { setCurrentItem(item); } dataList.push(item); displayList.push(item); return item; } if (typeof inputValues == "function") { inputValues = inputValues(cell); } if (Array.isArray(inputValues)) { inputValues.forEach(function (value) { var item; if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object") { if (value.options) { item = { label: value.label, group: true, element: false }; displayList.push(item); value.options.forEach(function (item) { processComplexListItem(item); }); } else { processComplexListItem(value); } } else { item = { label: editorParams.listItemFormatter ? editorParams.listItemFormatter(value, value) : value, value: value, element: false }; if (item.value === curentValue || !isNaN(parseFloat(item.value)) && !isNaN(parseFloat(item.value)) && parseFloat(item.value) === parseFloat(curentValue)) { setCurrentItem(item); } dataList.push(item); displayList.push(item); } }); } else { for (var key in inputValues) { var item = { label: editorParams.listItemFormatter ? editorParams.listItemFormatter(key, inputValues[key]) : inputValues[key], value: key, element: false }; if (item.value === curentValue || !isNaN(parseFloat(item.value)) && !isNaN(parseFloat(item.value)) && parseFloat(item.value) === parseFloat(curentValue)) { setCurrentItem(item); } dataList.push(item); displayList.push(item); } } dataItems = dataList; displayItems = displayList; fillList(); } function fillList() { while (listEl.firstChild) { listEl.removeChild(listEl.firstChild); }displayItems.forEach(function (item) { var el = item.element; if (!el) { if (item.group) { el = document.createElement("div"); el.classList.add("tabulator-edit-select-list-group"); el.tabIndex = 0; el.innerHTML = item.label === "" ? "&nbsp;" : item.label; } else { el = document.createElement("div"); el.classList.add("tabulator-edit-select-list-item"); el.tabIndex = 0; el.innerHTML = item.label === "" ? "&nbsp;" : item.label; el.addEventListener("click", function () { setCurrentItem(item); chooseItem(); }); if (item === currentItem) { el.classList.add("active"); } } el.addEventListener("mousedown", function () { blurable = false; setTimeout(function () { blurable = true; }, 10); }); item.element = el; } listEl.appendChild(el); }); } function setCurrentItem(item) { if (currentItem && currentItem.element) { currentItem.element.classList.remove("active"); } currentItem = item; input.value = item.label === "&nbsp;" ? "" : item.label; if (item.element) { item.element.classList.add("active"); } } function chooseItem() { hideList(); if (initialValue !== currentItem.value) { initialValue = currentItem.value; success(currentItem.value); } else { cancel(); } } function cancelItem() { hideList(); cancel(); } function showList() { if (!listEl.parentNode) { if (editorParams.values === true) { parseItems(getUniqueColumnValues(), initialDisplayValue); } else if (typeof editorParams.values === "string") { parseItems(getUniqueColumnValues(editorParams.values), initialDisplayValue); } else { parseItems(editorParams.values || [], initialDisplayValue); } var offset = Tabulator.prototype.helpers.elOffset(cellEl); listEl.style.minWidth = cellEl.offsetWidth + "px"; listEl.style.top = offset.top + cellEl.offsetHeight + "px"; listEl.style.left = offset.left + "px"; document.body.appendChild(listEl); } } function hideList() { if (listEl.parentNode) { listEl.parentNode.removeChild(listEl); } removeScrollListener(); } function removeScrollListener() { self.table.rowManager.element.removeEventListener("scroll", cancelItem); } //style input input.setAttribute("type", "text"); input.style.padding = "4px"; input.style.width = "100%"; input.style.boxSizing = "border-box"; input.style.cursor = "default"; input.readOnly = this.currentCell != false; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } input.value = typeof initialValue !== "undefined" || initialValue === null ? initialValue : ""; if (editorParams.values === true) { parseItems(getUniqueColumnValues(), initialValue); } else if (typeof editorParams.values === "string") { parseItems(getUniqueColumnValues(editorParams.values), initialValue); } else { parseItems(editorParams.values || [], initialValue); } //allow key based navigation input.addEventListener("keydown", function (e) { var index; switch (e.keyCode) { case 38: //up arrow e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); index = dataItems.indexOf(currentItem); if (index > 0) { setCurrentItem(dataItems[index - 1]); } break; case 40: //down arrow e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); index = dataItems.indexOf(currentItem); if (index < dataItems.length - 1) { if (index == -1) { setCurrentItem(dataItems[0]); } else { setCurrentItem(dataItems[index + 1]); } } break; case 37: //left arrow case 39: //right arrow e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); break; case 13: //enter chooseItem(); break; case 27: //escape cancelItem(); break; } }); input.addEventListener("blur", function (e) { if (blurable) { cancelItem(); } }); input.addEventListener("focus", function (e) { showList(); }); //style list element listEl = document.createElement("div"); listEl.classList.add("tabulator-edit-select-list"); onRendered(function () { input.style.height = "100%"; input.focus(); }); return input; }, //autocomplete autocomplete: function autocomplete(cell, onRendered, success, cancel, editorParams) { var self = this, cellEl = cell.getElement(), initialValue = cell.getValue(), initialDisplayValue = typeof initialValue !== "undefined" || initialValue === null ? initialValue : typeof editorParams.defaultValue !== "undefined" ? editorParams.defaultValue : "", input = document.createElement("input"), listEl = document.createElement("div"), allItems = [], displayItems = [], values = [], currentItem = {}, blurable = true; this.table.rowManager.element.addEventListener("scroll", cancelItem); function getUniqueColumnValues(field) { var output = {}, data = self.table.getData(), column; if (field) { column = self.table.columnManager.getColumnByField(field); } else { column = cell.getColumn()._getSelf(); } if (column) { data.forEach(function (row) { var val = column.getFieldValue(row); if (val !== null && typeof val !== "undefined" && val !== "") { output[val] = true; } }); if (editorParams.sortValuesList) { if (editorParams.sortValuesList == "asc") { output = Object.keys(output).sort(); } else { output = Object.keys(output).sort().reverse(); } } else { output = Object.keys(output); } } else { console.warn("unable to find matching column to create autocomplete lookup list:", field); } return output; } function parseItems(inputValues, curentValue) { var itemList = []; if (Array.isArray(inputValues)) { inputValues.forEach(function (value) { var item = { title: editorParams.listItemFormatter ? editorParams.listItemFormatter(value, value) : value, value: value, element: false }; if (item.value === curentValue || !isNaN(parseFloat(item.value)) && !isNaN(parseFloat(item.value)) && parseFloat(item.value) === parseFloat(curentValue)) { setCurrentItem(item); } itemList.push(item); }); } else { for (var key in inputValues) { var item = { title: editorParams.listItemFormatter ? editorParams.listItemFormatter(key, inputValues[key]) : inputValues[key], value: key, element: false }; if (item.value === curentValue || !isNaN(parseFloat(item.value)) && !isNaN(parseFloat(item.value)) && parseFloat(item.value) === parseFloat(curentValue)) { setCurrentItem(item); } itemList.push(item); } } if (editorParams.searchFunc) { itemList.forEach(function (item) { item.search = { title: item.title, value: item.value }; }); } allItems = itemList; } function filterList(term, intialLoad) { var matches = [], searchObjs = [], searchResults = []; if (editorParams.searchFunc) { allItems.forEach(function (item) { searchObjs.push(item.search); }); searchResults = editorParams.searchFunc(term, searchObjs); searchResults.forEach(function (result) { var match = allItems.find(function (item) { return item.search === result; }); if (match) { matches.push(match); } }); } else { if (term === "") { if (editorParams.showListOnEmpty) { allItems.forEach(function (item) { matches.push(item); }); } } else { allItems.forEach(function (item) { if (item.value !== null || typeof item.value !== "undefined") { if (String(item.value).toLowerCase().indexOf(String(term).toLowerCase()) > -1 || String(item.title).toLowerCase().indexOf(String(term).toLowerCase()) > -1) { matches.push(item); } } }); } } displayItems = matches; fillList(intialLoad); } function fillList(intialLoad) { var current = false; while (listEl.firstChild) { listEl.removeChild(listEl.firstChild); }displayItems.forEach(function (item) { var el = item.element; if (!el) { el = document.createElement("div"); el.classList.add("tabulator-edit-select-list-item"); el.tabIndex = 0; el.innerHTML = item.title; el.addEventListener("click", function () { setCurrentItem(item); chooseItem(); }); el.addEventListener("mousedown", function () { blurable = false; setTimeout(function () { blurable = true; }, 10); }); item.element = el; if (intialLoad && item.value == initialValue) { input.value = item.title; item.element.classList.add("active"); current = true; } if (item === currentItem) { item.element.classList.add("active"); current = true; } } listEl.appendChild(el); }); if (!current) { setCurrentItem(false); } } function setCurrentItem(item, showInputValue) { if (currentItem && currentItem.element) { currentItem.element.classList.remove("active"); } currentItem = item; if (item && item.element) { item.element.classList.add("active"); } } function chooseItem() { hideList(); if (currentItem) { if (initialValue !== currentItem.value) { initialValue = currentItem.value; input.value = currentItem.title; success(currentItem.value); } else { cancel(); } } else { if (editorParams.freetext) { initialValue = input.value; success(input.value); } else { if (editorParams.allowEmpty && input.value === "") { initialValue = input.value; success(input.value); } else { cancel(); } } } } function cancelItem() { hideList(); cancel(); } function showList() { if (!listEl.parentNode) { while (listEl.firstChild) { listEl.removeChild(listEl.firstChild); }if (editorParams.values === true) { values = getUniqueColumnValues(); } else if (typeof editorParams.values === "string") { values = getUniqueColumnValues(editorParams.values); } else { values = editorParams.values || []; } parseItems(values, initialValue); var offset = Tabulator.prototype.helpers.elOffset(cellEl); listEl.style.minWidth = cellEl.offsetWidth + "px"; listEl.style.top = offset.top + cellEl.offsetHeight + "px"; listEl.style.left = offset.left + "px"; document.body.appendChild(listEl); } } function hideList() { if (listEl.parentNode) { listEl.parentNode.removeChild(listEl); } removeScrollListener(); } function removeScrollListener() { self.table.rowManager.element.removeEventListener("scroll", cancelItem); } //style input input.setAttribute("type", "search"); input.style.padding = "4px"; input.style.width = "100%"; input.style.boxSizing = "border-box"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } //allow key based navigation input.addEventListener("keydown", function (e) { var index; switch (e.keyCode) { case 38: //up arrow e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); index = displayItems.indexOf(currentItem); if (index > 0) { setCurrentItem(displayItems[index - 1]); } else { setCurrentItem(false); } break; case 40: //down arrow e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); index = displayItems.indexOf(currentItem); if (index < displayItems.length - 1) { if (index == -1) { setCurrentItem(displayItems[0]); } else { setCurrentItem(displayItems[index + 1]); } } break; case 37: //left arrow case 39: //right arrow e.stopImmediatePropagation(); e.stopPropagation(); e.preventDefault(); break; case 13: //enter chooseItem(); break; case 27: //escape cancelItem(); break; case 36: //home case 35: //end //prevent table navigation while using input element e.stopImmediatePropagation(); break; } }); input.addEventListener("keyup", function (e) { switch (e.keyCode) { case 38: //up arrow case 37: //left arrow case 39: //up arrow case 40: //right arrow case 13: //enter case 27: //escape break; default: filterList(input.value); } }); input.addEventListener("search", function (e) { filterList(input.value); }); input.addEventListener("blur", function (e) { if (blurable) { chooseItem(); } }); input.addEventListener("focus", function (e) { var value = initialDisplayValue; showList(); input.value = value; filterList(value, true); }); //style list element listEl = document.createElement("div"); listEl.classList.add("tabulator-edit-select-list"); onRendered(function () { input.style.height = "100%"; input.focus(); }); return input; }, //start rating star: function star(cell, onRendered, success, cancel, editorParams) { var self = this, element = cell.getElement(), value = cell.getValue(), maxStars = element.getElementsByTagName("svg").length || 5, size = element.getElementsByTagName("svg")[0] ? element.getElementsByTagName("svg")[0].getAttribute("width") : 14, stars = [], starsHolder = document.createElement("div"), star = document.createElementNS('http://www.w3.org/2000/svg', "svg"); //change star type function starChange(val) { stars.forEach(function (star, i) { if (i < val) { if (self.table.browser == "ie") { star.setAttribute("class", "tabulator-star-active"); } else { star.classList.replace("tabulator-star-inactive", "tabulator-star-active"); } star.innerHTML = '<polygon fill="#488CE9" stroke="#014AAE" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>'; } else { if (self.table.browser == "ie") { star.setAttribute("class", "tabulator-star-inactive"); } else { star.classList.replace("tabulator-star-active", "tabulator-star-inactive"); } star.innerHTML = '<polygon fill="#010155" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>'; } }); } //build stars function buildStar(i) { var starHolder = document.createElement("span"); var nextStar = star.cloneNode(true); stars.push(nextStar); starHolder.addEventListener("mouseenter", function (e) { e.stopPropagation(); e.stopImmediatePropagation(); starChange(i); }); starHolder.addEventListener("mousemove", function (e) { e.stopPropagation(); e.stopImmediatePropagation(); }); starHolder.addEventListener("click", function (e) { e.stopPropagation(); e.stopImmediatePropagation(); success(i); }); starHolder.appendChild(nextStar); starsHolder.appendChild(starHolder); } //handle keyboard navigation value change function changeValue(val) { value = val; starChange(val); } //style cell element.style.whiteSpace = "nowrap"; element.style.overflow = "hidden"; element.style.textOverflow = "ellipsis"; //style holding element starsHolder.style.verticalAlign = "middle"; starsHolder.style.display = "inline-block"; starsHolder.style.padding = "4px"; //style star star.setAttribute("width", size); star.setAttribute("height", size); star.setAttribute("viewBox", "0 0 512 512"); star.setAttribute("xml:space", "preserve"); star.style.padding = "0 1px"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); starsHolder.setAttribute(key, starsHolder.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { starsHolder.setAttribute(key, editorParams.elementAttributes[key]); } } } //create correct number of stars for (var i = 1; i <= maxStars; i++) { buildStar(i); } //ensure value does not exceed number of stars value = Math.min(parseInt(value), maxStars); // set initial styling of stars starChange(value); starsHolder.addEventListener("mousemove", function (e) { starChange(0); }); starsHolder.addEventListener("click", function (e) { success(0); }); element.addEventListener("blur", function (e) { cancel(); }); //allow key based navigation element.addEventListener("keydown", function (e) { switch (e.keyCode) { case 39: //right arrow changeValue(value + 1); break; case 37: //left arrow changeValue(value - 1); break; case 13: //enter success(value); break; case 27: //escape cancel(); break; } }); return starsHolder; }, //draggable progress bar progress: function progress(cell, onRendered, success, cancel, editorParams) { var element = cell.getElement(), max = typeof editorParams.max === "undefined" ? element.getElementsByTagName("div")[0].getAttribute("max") || 100 : editorParams.max, min = typeof editorParams.min === "undefined" ? element.getElementsByTagName("div")[0].getAttribute("min") || 0 : editorParams.min, percent = (max - min) / 100, value = cell.getValue() || 0, handle = document.createElement("div"), bar = document.createElement("div"), mouseDrag, mouseDragWidth; //set new value function updateValue() { var calcVal = percent * Math.round(bar.offsetWidth / (element.clientWidth / 100)) + min; success(calcVal); element.setAttribute("aria-valuenow", calcVal); element.setAttribute("aria-label", value); } //style handle handle.style.position = "absolute"; handle.style.right = "0"; handle.style.top = "0"; handle.style.bottom = "0"; handle.style.width = "5px"; handle.classList.add("tabulator-progress-handle"); //style bar bar.style.display = "inline-block"; bar.style.position = "relative"; // bar.style.top = "8px"; // bar.style.bottom = "8px"; // bar.style.left = "4px"; // bar.style.marginRight = "4px"; bar.style.height = "100%"; bar.style.backgroundColor = "#488CE9"; bar.style.maxWidth = "100%"; bar.style.minWidth = "0%"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); bar.setAttribute(key, bar.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { bar.setAttribute(key, editorParams.elementAttributes[key]); } } } //style cell element.style.padding = "4px 4px"; //make sure value is in range value = Math.min(parseFloat(value), max); value = Math.max(parseFloat(value), min); //workout percentage value = Math.round((value - min) / percent); // bar.style.right = value + "%"; bar.style.width = value + "%"; element.setAttribute("aria-valuemin", min); element.setAttribute("aria-valuemax", max); bar.appendChild(handle); handle.addEventListener("mousedown", function (e) { mouseDrag = e.screenX; mouseDragWidth = bar.offsetWidth; }); handle.addEventListener("mouseover", function () { handle.style.cursor = "ew-resize"; }); element.addEventListener("mousemove", function (e) { if (mouseDrag) { bar.style.width = mouseDragWidth + e.screenX - mouseDrag + "px"; } }); element.addEventListener("mouseup", function (e) { if (mouseDrag) { e.stopPropagation(); e.stopImmediatePropagation(); mouseDrag = false; mouseDragWidth = false; updateValue(); } }); //allow key based navigation element.addEventListener("keydown", function (e) { switch (e.keyCode) { case 39: //right arrow bar.style.width = bar.clientWidth + element.clientWidth / 100 + "px"; break; case 37: //left arrow bar.style.width = bar.clientWidth - element.clientWidth / 100 + "px"; break; case 13: //enter updateValue(); break; case 27: //escape cancel(); break; } }); element.addEventListener("blur", function () { cancel(); }); return bar; }, //checkbox tickCross: function tickCross(cell, onRendered, success, cancel, editorParams) { var value = cell.getValue(), input = document.createElement("input"), tristate = editorParams.tristate, indetermValue = typeof editorParams.indeterminateValue === "undefined" ? null : editorParams.indeterminateValue, indetermState = false; input.setAttribute("type", "checkbox"); input.style.marginTop = "5px"; input.style.boxSizing = "border-box"; if (editorParams.elementAttributes && _typeof(editorParams.elementAttributes) == "object") { for (var key in editorParams.elementAttributes) { if (key.charAt(0) == "+") { key = key.slice(1); input.setAttribute(key, input.getAttribute(key) + editorParams.elementAttributes["+" + key]); } else { input.setAttribute(key, editorParams.elementAttributes[key]); } } } input.value = value; if (tristate && (typeof value === "undefined" || value === indetermValue || value === "")) { indetermState = true; input.indeterminate = true; } if (this.table.browser != "firefox") { //prevent blur issue on mac firefox onRendered(function () { input.focus(); }); } input.checked = value === true || value === "true" || value === "True" || value === 1; function setValue(blur) { if (tristate) { if (!blur) { if (input.checked && !indetermState) { input.checked = false; input.indeterminate = true; indetermState = true; return indetermValue; } else { indetermState = false; return input.checked; } } else { if (indetermState) { return indetermValue; } else { return input.checked; } } } else { return input.checked; } } //submit new value on blur input.addEventListener("change", function (e) { success(setValue()); }); input.addEventListener("blur", function (e) { success(setValue(true)); }); //submit new value on enter input.addEventListener("keydown", function (e) { if (e.keyCode == 13) { success(setValue()); } if (e.keyCode == 27) { cancel(); } }); return input; } }; Tabulator.prototype.registerModule("edit", Edit);
expect(() => { function f(i) { if (i) f(i - 1); x; } f(3); let x; }).toThrow(ReferenceError);
var _ = require('../../../../../src/util') var def = require('../../../../../src/directives/public/text') describe('v-text', function () { it('element', function () { var dir = { el: document.createElement('div') } _.extend(dir, def) dir.bind() dir.update('hi') expect(dir.el.textContent).toBe('hi') dir.update(123) expect(dir.el.textContent).toBe('123') }) it('text node', function () { var dir = { el: document.createTextNode(' ') } _.extend(dir, def) dir.bind() dir.update('hi') expect(dir.el.nodeValue).toBe('hi') dir.update(123) expect(dir.el.nodeValue).toBe('123') }) })
'use strict'; const User = require('../models/User'), Paste = require('../models/Paste'), mongoose = require('mongoose'), hashing = require('../utils/hashing'); // the next 3 lines are mongoose configuration and should be extracted in a config file const CONNECTION_URL = 'mongodb://localhost:27017/demo-db'; mongoose.connect(CONNECTION_URL); mongoose.Promise = global.Promise; module.exports = { findById(id) { return User.findById(id); }, findByUsername(username) { return User.findOne({ username }); }, createUser(user) { // hash the password so it isn't stored in plain text const salt = hashing.generateSalt(), passHash = hashing.hashPassword(salt, user.password); const newUser = { username: user.username, roles: user.roles, salt, passHash }; return User.create(newUser); }, createPaste(paste, author) { const newPaste = { content: paste.content, lang: paste.lang }; if(author) { newPaste.author = { username: author.username } } return Paste.create(newPaste); }, getPagedPastes(pageNumber, pageSize, options) { const { widthDeleted, withDetails } = options; const query = Paste.find(withDeleted ? {} : { deletedAt: undefined }) .skip(pageNumber * pageSize) .limit(pageSize); return detailed ? query : query.select('content lang'); }, pasteById(id) { return Paste.findById(id); }, updatePasteById(id, updateOptions) { return Paste.findByIdAndUpdate(id, updateOptions); }, removePasteById(id) { return Paste.findByIdAndUpdate(id, { deletedAt: new Date() }); }, createCommentForPaste(pasteId, comment, author) { const newComment = { content: comment.content }; if(author) { newComment.author = { username: author.username }; } return Paste.findByIdAndUpdate(pasteId, { $push: { comments: newComment } }); } };
(function(document, window, $) { 'use strict'; var Site = window.Site; $(document).ready(function($) { Site.run(); }); window.getExampleTreeview = function() { return [{ text: 'Parent 1', href: '#parent1', tags: ['4'], nodes: [{ text: 'Child 1', href: '#child1', tags: ['2'], nodes: [{ text: 'Grandchild 1', href: '#grandchild1', tags: ['0'] }, { text: 'Grandchild 2', href: '#grandchild2', tags: ['0'] }] }, { text: 'Child 2', href: '#child2', tags: ['0'] }] }, { text: 'Parent 2', href: '#parent2', tags: ['0'] }, { text: 'Parent 3', href: '#parent3', tags: ['0'] }, { text: 'Parent 4', href: '#parent4', tags: ['0'] }, { text: 'Parent 5', href: '#parent5', tags: ['0'] }]; }; var defaults = $.components.getDefaults("treeview"); // Example TreeView Json Data // -------------------------- (function() { var json = '[' + '{' + '"text": "Parent 1",' + '"nodes": [' + '{' + '"text": "Child 1",' + '"nodes": [' + '{' + '"text": "Grandchild 1"' + '},' + '{' + '"text": "Grandchild 2"' + '}' + ']' + '},' + '{' + '"text": "Child 2"' + '}' + ']' + '},' + '{' + '"text": "Parent 2"' + '},' + '{' + '"text": "Parent 3"' + '},' + '{' + '"text": "Parent 4"' + '},' + '{' + '"text": "Parent 5"' + '}' + ']'; var json_options = $.extend({}, defaults, { data: json }); $('#exampleJsonData').treeview(json_options); })(); // Example TreeView Searchable // --------------------------- (function() { var options = $.extend({}, defaults, { data: getExampleTreeview() }); var $searchableTree = $('#exampleSearchableTree').treeview(options); $('#inputSearchable').on('keyup', function(e) { var pattern = $(e.target).val(); var results = $searchableTree.treeview('search', [pattern, { 'ignoreCase': true, 'exactMatch': false }]); }); })(); // Example TreeView Expandible // --------------------------- (function() { var options = $.extend({}, defaults, { data: getExampleTreeview() }); // Expandible var $expandibleTree = $('#exampleExpandibleTree').treeview(options); // Expand/collapse all $('#exampleExpandAll').on('click', function(e) { $expandibleTree.treeview('expandAll', { levels: '99' }); }); $('#exampleCollapseAll').on('click', function(e) { $expandibleTree.treeview('collapseAll'); }); })(); // Example TreeView Events // ----------------------- (function() { // Events var events_toastr = function(msg) { toastr.info(msg, '', { iconClass: 'toast-just-text toast-info', positionClass: 'toast-bottom-right', containertId: 'toast-bottom-right' }); }; var options = $.extend({}, defaults, { data: getExampleTreeview(), onNodeCollapsed: function(event, node) { events_toastr(node.text + ' was collapsed'); }, onNodeExpanded: function(event, node) { events_toastr(node.text + ' was expanded'); }, onNodeSelected: function(event, node) { events_toastr(node.text + ' was selected'); }, onNodeUnselected: function(event, node) { events_toastr(node.text + ' was unselected'); } }); $('#exampleEvents').treeview(options); })(); })(document, window, jQuery);
function Config() { const name = 'threejs-editor'; const storage = { 'language': 'en', 'autosave': true, 'project/title': '', 'project/editable': false, 'project/vr': false, 'project/renderer/antialias': true, 'project/renderer/shadows': true, 'project/renderer/shadowType': 1, // PCF 'project/renderer/physicallyCorrectLights': false, 'project/renderer/toneMapping': 0, // NoToneMapping 'project/renderer/toneMappingExposure': 1, 'settings/history': false, 'settings/shortcuts/translate': 'w', 'settings/shortcuts/rotate': 'e', 'settings/shortcuts/scale': 'r', 'settings/shortcuts/undo': 'z', 'settings/shortcuts/focus': 'f' }; if ( window.localStorage[ name ] === undefined ) { window.localStorage[ name ] = JSON.stringify( storage ); } else { const data = JSON.parse( window.localStorage[ name ] ); for ( const key in data ) { storage[ key ] = data[ key ]; } } return { getKey: function ( key ) { return storage[ key ]; }, setKey: function () { // key, value, key, value ... for ( let i = 0, l = arguments.length; i < l; i += 2 ) { storage[ arguments[ i ] ] = arguments[ i + 1 ]; } window.localStorage[ name ] = JSON.stringify( storage ); console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved config to LocalStorage.' ); }, clear: function () { delete window.localStorage[ name ]; } }; } export { Config };
'use strict'; module.exports = { type: 'error', error: { line: 2, column: 1, message: 'Unexpected end of file. The type at 1:7 should be followed by an alias name.', }, };
/*! * Table dialog plugin for Editor.md * * @file table-dialog.js * @author pandao * @version 1.2.0 * @updateTime 2015-03-08 * {@link https://github.com/pandao/editor.md} * @license MIT */ (function() { var factory = function (exports) { var $ = jQuery; var pluginName = "table-dialog"; var langs = { "zh-cn" : { toolbar : { table : "表格" }, dialog : { table : { title : "添加表格", cellsLabel : "单元格数", alignLabel : "对齐方式", rows : "行数", cols : "列数", aligns : ["默认", "左对齐", "居中对齐", "右对齐"] } } }, "zh-tw" : { toolbar : { table : "添加表格" }, dialog : { table : { title : "添加表格", cellsLabel : "單元格數", alignLabel : "對齊方式", rows : "行數", cols : "列數", aligns : ["默認", "左對齊", "居中對齊", "右對齊"] } } }, "en" : { toolbar : { table : "Tables" }, dialog : { table : { title : "Tables", cellsLabel : "Cells", alignLabel : "Align", rows : "Rows", cols : "Cols", aligns : ["Default", "Left align", "Center align", "Right align"] } } } }; exports.fn.tableDialog = function() { var _this = this; var cm = this.cm; var editor = this.editor; var settings = this.settings; var path = settings.path + "../plugins/" + pluginName +"/"; var classPrefix = this.classPrefix; var dialogName = classPrefix + pluginName, dialog; $.extend(true, this.lang, langs[this.lang.name]); this.setToolbar(); var lang = this.lang; var dialogLang = lang.dialog.table; var dialogContent = [ "<div class=\"editormd-form\" style=\"padding: 15px 0;\">", "<label>" + dialogLang.cellsLabel + "</label>", dialogLang.rows + " <input type=\"number\" value=\"3\" class=\"number-input\" style=\"width:40px;\" max=\"100\" min=\"2\" data-rows />&nbsp;&nbsp;", dialogLang.cols + " <input type=\"number\" value=\"2\" class=\"number-input\" style=\"width:40px;\" max=\"100\" min=\"1\" data-cols /><br/>", "<label>" + dialogLang.alignLabel + "</label>", "<div class=\"fa-btns\"></div>", "</div>" ].join("\n"); if (editor.find("." + dialogName).length > 0) { dialog = editor.find("." + dialogName); this.dialogShowMask(dialog); this.dialogLockScreen(); dialog.show(); } else { dialog = this.createDialog({ name : dialogName, title : dialogLang.title, width : 360, height : 226, mask : settings.dialogShowMask, drag : settings.dialogDraggable, content : dialogContent, lockScreen : settings.dialogLockScreen, maskStyle : { opacity : settings.dialogMaskOpacity, backgroundColor : settings.dialogMaskBgColor }, buttons : { enter : [lang.buttons.enter, function() { var rows = parseInt(this.find("[data-rows]").val()); var cols = parseInt(this.find("[data-cols]").val()); var align = this.find("[name=\"table-align\"]:checked").val(); var table = ""; var hrLine = "------------"; var alignSign = { _default : hrLine, left : ":" + hrLine, center : ":" + hrLine + ":", right : hrLine + ":" }; if ( rows > 1 && cols > 0) { for (var r = 0, len = rows; r < len; r++) { var row = []; var head = []; for (var c = 0, len2 = cols; c < len2; c++) { if (r === 1) { head.push(alignSign[align]); } row.push(" "); } if (r === 1) { table += "| " + head.join(" | ") + " |" + "\n"; } table += "| " + row.join( (cols === 1) ? "" : " | " ) + " |" + "\n"; } } cm.replaceSelection(table); this.hide().lockScreen(false).hideMask(); return false; }], cancel : [lang.buttons.cancel, function() { this.hide().lockScreen(false).hideMask(); return false; }] } }); } var faBtns = dialog.find(".fa-btns"); if (faBtns.html() === "") { var icons = ["align-justify", "align-left", "align-center", "align-right"]; var _lang = dialogLang.aligns; var values = ["_default", "left", "center", "right"]; for (var i = 0, len = icons.length; i < len; i++) { var checked = (i === 0) ? " checked=\"checked\"" : ""; var btn = "<a href=\"javascript:;\"><label for=\"editormd-table-dialog-radio"+i+"\" title=\"" + _lang[i] + "\">"; btn += "<input type=\"radio\" name=\"table-align\" id=\"editormd-table-dialog-radio"+i+"\" value=\"" + values[i] + "\"" +checked + " />&nbsp;"; btn += "<i class=\"fa fa-" + icons[i] + "\"></i>"; btn += "</label></a>"; faBtns.append(btn); } } }; }; // CommonJS/Node.js if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { module.exports = factory; } else if (typeof define === "function") // AMD/CMD/Sea.js { if (define.amd) { // for Require.js define(["editormd"], function(editormd) { factory(editormd); }); } else { // for Sea.js define(function(require) { var editormd = require("./../../editormd"); factory(editormd); }); } } else { factory(window.editormd); } })();
'use strict'; module.exports = function(grunt) { require('load-grunt-tasks')(grunt, { pattern: ['grunt-*', '!grunt-template-jasmine-requirejs'] }); require('time-grunt')(grunt); grunt.initConfig({ root: { app: 'app/assets', test: 'jstest' }, connect: { server: { options: { port : 8000 } } }, jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= root.app %>/javascripts/map/{,*/}{,*/}{,*/}*.js' ] }, jasmine: { test: { options: { specs: [ '<%= root.test %>/spec/*_spec.js', ], host: 'http://127.0.0.1:8000/', helpers: '<%= root.test %>/helpers/*.js', outfile: '<%= root.test %>/SpecRunner.html', keepRunner: true, template: require('grunt-template-jasmine-requirejs'), templateOptions: { requireConfigFile: '<%= root.test %>/config.js' }, vendor: [ '<%= root.test %>/lib/mock-ajax.js', 'http://maps.googleapis.com/maps/api/js?libraries=places,visualization,drawing&sensor=false&key=AIzaSyDJdVhfQhecwp0ngAGzN9zwqak8FaEkSTA' ] } } }, watch: { options: { spawn: false }, test: { files: '<%= jshint.all %>', tasks: ['jasmine'] }, scripts: { files: '<%= jshint.all %>', tasks: ['jshint'] } } }); grunt.registerTask('test', [ 'connect:server', 'jasmine', 'jshint' ]); grunt.registerTask('default', [ 'connect:server', 'jshint', 'jasmine', 'watch' ]); };
/*! * jQuery JavaScript Library v2.1.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:11Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // #11217 - WebKit loses check when the name is after the checked attribute // Support: Windows Web Apps (WWA) // `name` and `type` need .setAttribute for WWA input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
var selftest = require('../tool-testing/selftest.js'); var Sandbox = selftest.Sandbox; var files = require('../fs/files.js'); var utils = require('../utils/utils.js'); var archinfo = require('../utils/archinfo.js'); var _ = require('underscore'); selftest.define("wipe all packages", function () { var s = new Sandbox({ warehouse: { v1: { tool: "meteor-tool@33.0.1", recommended: true }, v2: { tool: "meteor-tool@33.0.2", recommended: true }, v3: { tool: "meteor-tool@33.0.3", recommended: true } } }); var meteorToolVersion = function (v) { return { _id: 'VID' + v.replace(/\./g, ''), packageName: 'meteor-tool', testName: null, version: v, publishedBy: null, description: 'The Meteor command-line tool', git: undefined, dependencies: { meteor: { constraint: null, references: [{ arch: 'os' }, { arch: 'web.browser' }, { arch: 'web.cordova' }] } }, source: null, lastUpdated: null, published: null, isTest: false, debugOnly: false, prodOnly: false, testOnly: false, containsPlugins: false }; }; var meteorToolBuild = function (v) { return { buildArchitectures: archinfo.host(), versionId: 'VID' + v.replace(/\./g, ''), _id: utils.randomToken() }; }; // insert the new tool versions into the catalog s.warehouseOfficialCatalog.insertData({ syncToken: {}, formatVersion: "1.0", collections: { packages: [], versions: [meteorToolVersion('33.0.1'), meteorToolVersion('33.0.2'), meteorToolVersion('33.0.3')], builds: [meteorToolBuild('33.0.1'), meteorToolBuild('33.0.2'), meteorToolBuild('33.0.3')], releaseTracks: [], releaseVersions: [] } }); // help warehouse faking by copying the meteor-tool 3 times and introducing 3 // fake versions (identical in code to the one we are running) var latestMeteorToolVersion = files.readLinkToMeteorScript(files.pathJoin(s.warehouse, 'meteor')).split('/'); latestMeteorToolVersion = latestMeteorToolVersion[latestMeteorToolVersion.length - 3]; var prefix = files.pathJoin(s.warehouse, 'packages', 'meteor-tool'); var copyTool = function (srcVersion, dstVersion) { if (process.platform === 'win32') { // just copy the files files.cp_r( files.pathJoin(prefix, srcVersion), files.pathJoin(prefix, dstVersion), { preserveSymlinks: true }); } else { // figure out what the symlink links to and copy the folder *and* the // symlink var srcFullVersion = files.readlink(files.pathJoin(prefix, srcVersion)); var dstFullVersion = srcFullVersion.replace(srcVersion, dstVersion); // copy the hidden folder files.cp_r( files.pathJoin(prefix, srcFullVersion), files.pathJoin(prefix, dstFullVersion), { preserveSymlinks: true }); // link to it files.symlink( dstFullVersion, files.pathJoin(prefix, dstVersion)); } var replaceVersionInFile = function (filename) { var filePath = files.pathJoin(prefix, dstVersion, filename); files.writeFile( filePath, files.readFile(filePath, 'utf8') .replace(new RegExp(srcVersion, 'g'), dstVersion)); }; // "fix" the isopack.json and unibuild.json files (they contain the versions) replaceVersionInFile('isopack.json'); replaceVersionInFile('unipackage.json'); }; copyTool(latestMeteorToolVersion, '33.0.3'); copyTool(latestMeteorToolVersion, '33.0.2'); copyTool(latestMeteorToolVersion, '33.0.1'); // since the warehouse faking system is weak and under-developed, add more // faking, such as making the v3 the latest version files.linkToMeteorScript( files.pathJoin('packages', 'meteor-tool', '33.0.3', 'mt-' + archinfo.host(), 'meteor'), files.pathJoin(s.warehouse, 'meteor')); var run; run = s.run('--release', 'v1', 'admin', 'wipe-all-packages'); run.waitSecs(15); run.expectExit(0); // OK, wiped all packages, now let's go and check that everything is removed // except for the tool we are running right now and the latest tool. i.e. v1 // and v3 var notHidden = function (f) { return f[0] !== '.'; }; var meteorToolDirs = _.filter(files.readdir(prefix), notHidden); selftest.expectTrue(meteorToolDirs.length === 2); _.each(meteorToolDirs, function (f) { var fPath = files.pathJoin(prefix, f); if (process.platform === 'win32') { // this is a dir selftest.expectTrue(files.lstat(fPath).isDirectory()); } else { // this is a symlink to a dir and this dir exists selftest.expectTrue(files.lstat(fPath).isSymbolicLink()); selftest.expectTrue(files.exists(files.pathJoin(prefix, files.readlink(fPath)))); } // check that the version is either the running one, or the latest one selftest.expectTrue(_.contains(['33.0.1', '33.0.3'], f)); }); // Check that all other packages are wiped _.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) { if (p[0] === '.') { return; } if (p === 'meteor-tool') { return; } var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p)); contents = _.filter(contents, notHidden); selftest.expectTrue(contents.length === 0); }); });
/*! iDevice.js v1.1.0 (c) Alexandre Dieulot dieulot.fr/idevice/license */ var iDevice = (function() { var canvasElement = document.createElement('canvas') try { var context = canvasElement.getContext('webgl') var extension = context.getExtension('WEBGL_debug_renderer_info') var gpu = context.getParameter(extension.UNMASKED_RENDERER_WEBGL) } catch (e) { return } var matches = gpu.match(/^Apple (.+) GPU$/) var cpu = matches && matches[1] var s = screen.width + 'x' + screen.height var dpr = devicePixelRatio if (!cpu) { if (gpu == 'PowerVR SGX 535' && s == '768x1024' && dpr == 1) { return 'iPad 2/mini 1' } if (gpu == 'PowerVR SGX 543' && dpr == 2) { if (s == '320x480') { return 'iPhone 4s' } if (s == '768x1024') { return 'iPad 3' } if (s == '320x568') { if (navigator.userAgent.indexOf('iPod') > -1) { return 'iPod Touch 5' } return 'iPhone 5/5c' } } if (gpu == 'PowerVR SGX 554' && s == '768x1024' && dpr == 2) { return 'iPad 4' } return } if (cpu == 'A7') { if (s == '320x568') { return 'iPhone 5s' } if (s == '768x1024') { return 'iPad Air/mini 2/mini 3' } } var models = ['6', '6s', '7', '8'] var cpuGeneration = parseInt(cpu.substr(1)) if (cpuGeneration >= 8 && cpuGeneration <= 11) { if (s == '375x667') { return 'iPhone ' + models[cpuGeneration - 8] } if (s == '414x736') { return 'iPhone ' + models[cpuGeneration - 8] + ' Plus' } } if (cpu == 'A8') { if (s == '320x568') { return 'iPod Touch 6' } if (s == '768x1024') { return 'iPad mini 4' } } if (cpu == 'A8X') { return 'iPad Air 2' } if (cpu == 'A9') { if (s == '320x568') { return 'iPhone SE' } if (s == '768x1024') { return 'iPad (2017)' } } if (cpu == 'A9X') { if (s == '768x1024') { return 'iPad Pro 9.7 (2016)' } if (s == '1024x1366') { return 'iPad Pro 12.9 (2015)' } } if (cpu == 'A10') { if (s == '768x1024') { return 'iPad (2018)' } } if (cpu == 'A10X') { if (s == '834x1112') { return 'iPad Pro 10.5 (2017)' } if (s == '1024x1366') { return 'iPad Pro 12.9 (2017)' } } if (cpu == 'A11') { if (s == '375x812') { return 'iPhone X' } } if (cpu == 'A12') { if (s == '375x812') { return 'iPhone XS' } if (s == '414x896') { if (dpr == 2) { return 'iPhone XR' } if (dpr == 3) { return 'iPhone XS Max' } } } if (cpu == 'A12X') { if (s == '834x1194') { return 'iPad Pro 11 (2018)' } if (s == '1024x1366') { return 'iPad Pro 12.9 (2018)' } } return 'Unidentified ' + cpu + ' ' + s + '@' + dpr })();
let OldValue = require('../old-value') let Value = require('../value') function regexp (name) { return new RegExp(`(^|[\\s,(])(${name}($|[\\s),]))`, 'gi') } class Intrinsic extends Value { regexp () { if (!this.regexpCache) this.regexpCache = regexp(this.name) return this.regexpCache } isStretch () { return ( this.name === 'stretch' || this.name === 'fill' || this.name === 'fill-available' ) } replace (string, prefix) { if (prefix === '-moz-' && this.isStretch()) { return string.replace(this.regexp(), '$1-moz-available$3') } if (prefix === '-webkit-' && this.isStretch()) { return string.replace(this.regexp(), '$1-webkit-fill-available$3') } return super.replace(string, prefix) } old (prefix) { let prefixed = prefix + this.name if (this.isStretch()) { if (prefix === '-moz-') { prefixed = '-moz-available' } else if (prefix === '-webkit-') { prefixed = '-webkit-fill-available' } } return new OldValue(this.name, prefixed, prefixed, regexp(prefixed)) } add (decl, prefix) { if (decl.prop.includes('grid') && prefix !== '-webkit-') { return undefined } return super.add(decl, prefix) } } Intrinsic.names = [ 'max-content', 'min-content', 'fit-content', 'fill', 'fill-available', 'stretch' ] module.exports = Intrinsic
"use strict"; var fs = require("fs"); var vm = require("vm"); var components = require("../../components"); var languagesCatalog = components.languages; module.exports = { /** * Creates a new Prism instance with the given language loaded * * @param {string|string[]} languages * @returns {Prism} */ createInstance: function (languages) { var context = { loadedLanguages: [], Prism: this.createEmptyPrism() }; context = this.loadLanguages(languages, context); return context.Prism; }, /** * Loads the given languages and appends the config to the given Prism object * * @private * @param {string|string[]} languages * @param {{loadedLanguages: string[], Prism: Prism}} context * @returns {{loadedLanguages: string[], Prism: Prism}} */ loadLanguages: function (languages, context) { if (typeof languages === 'string') { languages = [languages]; } var self = this; languages.forEach(function (language) { context = self.loadLanguage(language, context); }); return context; }, /** * Loads the given language (including recursively loading the dependencies) and * appends the config to the given Prism object * * @private * @param {string} language * @param {{loadedLanguages: string[], Prism: Prism}} context * @returns {{loadedLanguages: string[], Prism: Prism}} */ loadLanguage: function (language, context) { if (!languagesCatalog[language]) { throw new Error("Language '" + language + "' not found."); } // the given language was already loaded if (-1 < context.loadedLanguages.indexOf(language)) { return context; } // if the language has a dependency -> load it first if (languagesCatalog[language].require) { context = this.loadLanguages(languagesCatalog[language].require, context); } // load the language itself var languageSource = this.loadFileSource(language); context.Prism = this.runFileWithContext(languageSource, {Prism: context.Prism}).Prism; context.loadedLanguages.push(language); return context; }, /** * Creates a new empty prism instance * * @private * @returns {Prism} */ createEmptyPrism: function () { var coreSource = this.loadFileSource("core"); var context = this.runFileWithContext(coreSource); return context.Prism; }, /** * Cached file sources, to prevent massive HDD work * * @private * @type {Object.<string, string>} */ fileSourceCache: {}, /** * Loads the given file source as string * * @private * @param {string} name * @returns {string} */ loadFileSource: function (name) { return this.fileSourceCache[name] = this.fileSourceCache[name] || fs.readFileSync(__dirname + "/../../components/prism-" + name + ".js", "utf8"); }, /** * Runs a VM for a given file source with the given context * * @private * @param {string} fileSource * @param {*} [context] * * @returns {*} */ runFileWithContext: function (fileSource, context) { context = context || {}; vm.runInNewContext(fileSource, context); return context; } };
/** * Module that contains factories for element types used by Emmet * @param {Function} require * @param {Underscore} _ */ emmet.define('elements', function(require, _) { var factories = {}; var reAttrs = /([\w\-:]+)\s*=\s*(['"])(.*?)\2/g; var result = { /** * Create new element factory * @param {String} name Element identifier * @param {Function} factory Function that produces element of specified * type. The object generated by this factory is automatically * augmented with <code>type</code> property pointing to element * <code>name</code> * @memberOf elements */ add: function(name, factory) { var that = this; factories[name] = function() { var elem = factory.apply(that, arguments); if (elem) elem.type = name; return elem; }; }, /** * Returns factory for specified name * @param {String} name * @returns {Function} */ get: function(name) { return factories[name]; }, /** * Creates new element with specified type * @param {String} name * @returns {Object} */ create: function(name) { var args = [].slice.call(arguments, 1); var factory = this.get(name); return factory ? factory.apply(this, args) : null; }, /** * Check if passed element is of specified type * @param {Object} elem * @param {String} type * @returns {Boolean} */ is: function(elem, type) { return elem && elem.type === type; } }; // register resource references function commonFactory(value) { return {data: value}; } /** * Element factory * @param {String} elementName Name of output element * @param {String} attrs Attributes definition. You may also pass * <code>Array</code> where each contains object with <code>name</code> * and <code>value</code> properties, or <code>Object</code> * @param {Boolean} isEmpty Is expanded element should be empty */ result.add('element', function(elementName, attrs, isEmpty) { var ret = { /** @memberOf __emmetDataElement */ name: elementName, is_empty: !!isEmpty }; if (attrs) { ret.attributes = []; if (_.isArray(attrs)) { ret.attributes = attrs; } else if (_.isString(attrs)) { var m; while ((m = reAttrs.exec(attrs))) { ret.attributes.push({ name: m[1], value: m[3] }); } } else { _.each(attrs, function(value, name) { ret.attributes.push({ name: name, value: value }); }); } } return ret; }); result.add('snippet', commonFactory); result.add('reference', commonFactory); result.add('empty', function() { return {}; }); return result; });
import H from '../parts/Globals.js'; import '../parts/Utilities.js'; var fireEvent = H.fireEvent; /** * It provides methods for: * - adding and handling DOM events and a drag event, * - mapping a mouse move event to the distance between two following events. * The units of the distance are specific to a transformation, * e.g. for rotation they are radians, for scaling they are scale factors. * * @private * @mixin * @memberOf Annotation */ var eventEmitterMixin = { /** * Add emitter events. */ addEvents: function () { var emitter = this; H.addEvent( emitter.graphic.element, 'mousedown', function (e) { emitter.onMouseDown(e); } ); H.objectEach(emitter.options.events, function (event, type) { var eventHandler = function (e) { if (type !== 'click' || !emitter.cancelClick) { event.call( emitter, emitter.chart.pointer.normalize(e), emitter.target ); } }; if (H.inArray(type, emitter.nonDOMEvents || []) === -1) { emitter.graphic.on(type, eventHandler); } else { H.addEvent(emitter, type, eventHandler); } }); if (emitter.options.draggable) { H.addEvent(emitter, 'drag', emitter.onDrag); if (!emitter.graphic.renderer.styledMode) { emitter.graphic.css({ cursor: { x: 'ew-resize', y: 'ns-resize', xy: 'move' }[emitter.options.draggable] }); } } if (!emitter.isUpdating) { fireEvent(emitter, 'add'); } }, /** * Remove emitter document events. */ removeDocEvents: function () { if (this.removeDrag) { this.removeDrag = this.removeDrag(); } if (this.removeMouseUp) { this.removeMouseUp = this.removeMouseUp(); } }, /** * Mouse down handler. * * @param {Object} e event */ onMouseDown: function (e) { var emitter = this, pointer = emitter.chart.pointer, prevChartX, prevChartY; if (e.preventDefault) { e.preventDefault(); } // On right click, do nothing: if (e.button === 2) { return; } e.stopPropagation(); e = pointer.normalize(e); prevChartX = e.chartX; prevChartY = e.chartY; emitter.cancelClick = false; emitter.removeDrag = H.addEvent( H.doc, 'mousemove', function (e) { emitter.hasDragged = true; e = pointer.normalize(e); e.prevChartX = prevChartX; e.prevChartY = prevChartY; fireEvent(emitter, 'drag', e); prevChartX = e.chartX; prevChartY = e.chartY; } ); emitter.removeMouseUp = H.addEvent( H.doc, 'mouseup', function (e) { emitter.cancelClick = emitter.hasDragged; emitter.hasDragged = false; // ControlPoints vs Annotation: fireEvent(H.pick(emitter.target, emitter), 'afterUpdate'); emitter.onMouseUp(e); } ); }, /** * Mouse up handler. * * @param {Object} e event */ onMouseUp: function () { var chart = this.chart, annotation = this.target || this, annotationsOptions = chart.options.annotations, index = chart.annotations.indexOf(annotation); this.removeDocEvents(); annotationsOptions[index] = annotation.options; }, /** * Drag and drop event. All basic annotations should share this * capability as well as the extended ones. * * @param {Object} e event */ onDrag: function (e) { if ( this.chart.isInsidePlot( e.chartX - this.chart.plotLeft, e.chartY - this.chart.plotTop ) ) { var translation = this.mouseMoveToTranslation(e); if (this.options.draggable === 'x') { translation.y = 0; } if (this.options.draggable === 'y') { translation.x = 0; } if (this.points.length) { this.translate(translation.x, translation.y); } else { this.shapes.forEach(function (shape) { shape.translate(translation.x, translation.y); }); this.labels.forEach(function (label) { label.translate(translation.x, translation.y); }); } this.redraw(false); } }, /** * Map mouse move event to the radians. * * @param {Object} e event * @param {number} cx center x * @param {number} cy center y */ mouseMoveToRadians: function (e, cx, cy) { var prevDy = e.prevChartY - cy, prevDx = e.prevChartX - cx, dy = e.chartY - cy, dx = e.chartX - cx, temp; if (this.chart.inverted) { temp = prevDx; prevDx = prevDy; prevDy = temp; temp = dx; dx = dy; dy = temp; } return Math.atan2(dy, dx) - Math.atan2(prevDy, prevDx); }, /** * Map mouse move event to the distance between two following events. * * @param {Object} e event */ mouseMoveToTranslation: function (e) { var dx = e.chartX - e.prevChartX, dy = e.chartY - e.prevChartY, temp; if (this.chart.inverted) { temp = dy; dy = dx; dx = temp; } return { x: dx, y: dy }; }, /** * Map mouse move to the scale factors. * * @param {Object} e event * @param {number} cx center x * @param {number} cy center y **/ mouseMoveToScale: function (e, cx, cy) { var prevDx = e.prevChartX - cx, prevDy = e.prevChartY - cy, dx = e.chartX - cx, dy = e.chartY - cy, sx = (dx || 1) / (prevDx || 1), sy = (dy || 1) / (prevDy || 1), temp; if (this.chart.inverted) { temp = sy; sy = sx; sx = temp; } return { x: sx, y: sy }; }, /** * Destroy the event emitter. */ destroy: function () { this.removeDocEvents(); H.removeEvent(this); this.hcEvents = null; } }; export default eventEmitterMixin;
exports.translations = { commands: { /* * Tour Commands */ tourhelp: {'h': 'tour (formato), (segundos para iniciar u off), (minutos para el autodq u off), (máximo número de users u off), (elimination u roundrobin). Todos los argumentos son opcionales.'}, tourend: {'err': 'No hay ningún torneo en esta sala', 'err2': 'El torneo ya ha empezado'}, tournament: { 'e1': 'requiere rango de moderador (@) o superior para crear torneos', 'e2': 'Ya hay un torneo en esta sala', 'e31': 'El formato', 'e32': 'no es válido para torneos', 'e4': 'El tiempo para iniciar o es válido', 'e5': 'El AutoDq no es válido', 'e6': 'El máximo numero de users no es válido', 'e7': 'El tipo de torneo no es válido. Usa alguno de estos: elimination, roundrobin', 'notstarted': 'Error: El torneo no ha empezado, probablemente por un cambio en los permisos o en los comandos', 'param': 'Parámetro', 'paramhelp': 'no encontrado, Los parámetros correctos son' }, official: { 'not': 'La funcion Leaderboards no esta disponibe para la sala', 'notour': 'No hay ningún torneo en esta sala', 'already': 'El torneo ya era oficial', 'already-not': 'El torneo no es oficial', 'official': 'Este torneo es ahora oficial y contará para el Leaderboards', 'unofficial': 'Este torneo ha dejado de ser oficial' }, leaderboard: { 'usage': 'Uso correcto', 'invuser': 'Nombre de usuario no válido', 'rank': 'Ranking de', 'in': 'en', 'points': 'Puntos', 'w': 'Ganador', 'f': 'Finalista', 'sf': 'Semifinalista', 'times': 'veces', 'total': 'Total', 'tours': 'torneos jugados', 'bwon': 'batlalas ganadas', 'not': 'La funcion Leaderboards no esta disponibe para la sala', 'empty': 'No hay ningún torneo registrado aún para la sala', 'table': 'Tabla del leaderboards', 'err': 'Error subiendo la tabla del leaderboards a Hastebin', 'use': 'Usa', 'confirm': 'para confirmar el borrado de los datos de leaderboards en la sala', 'invhash': 'Código no válido', 'data': 'Datos del Leaderboars de la sala', 'del': 'borrados', 'wasset': 'La configuracion del sistema de Leaderboards ha sido establecida para la sala', 'wasdisabled': 'La funcion Leaderboards ha sido desactivada para la sala', 'alrdisabled': 'La funcion Leaderboards ya estaba desactivada en la sala', 'unknown': 'Opción desconocida' } } };
/** * @author mrdoob / http://mrdoob.com/ * @author zz85 / http://joshuakoo.com/ * @author yomboprime / https://yombo.org */ THREE.SVGLoader = function ( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; }; THREE.SVGLoader.prototype = { constructor: THREE.SVGLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new THREE.FileLoader( scope.manager ); loader.setPath( scope.path ); loader.load( url, function ( text ) { onLoad( scope.parse( text ) ); }, onProgress, onError ); }, setPath: function ( value ) { this.path = value; return this; }, parse: function ( text ) { function parseNode( node, style ) { if ( node.nodeType !== 1 ) return; var transform = getNodeTransform( node ); var path = null; switch ( node.nodeName ) { case 'svg': break; case 'g': style = parseStyle( node, style ); break; case 'path': style = parseStyle( node, style ); if ( node.hasAttribute( 'd' ) ) path = parsePathNode( node ); break; case 'rect': style = parseStyle( node, style ); path = parseRectNode( node ); break; case 'polygon': style = parseStyle( node, style ); path = parsePolygonNode( node ); break; case 'polyline': style = parseStyle( node, style ); path = parsePolylineNode( node ); break; case 'circle': style = parseStyle( node, style ); path = parseCircleNode( node ); break; case 'ellipse': style = parseStyle( node, style ); path = parseEllipseNode( node ); break; case 'line': style = parseStyle( node, style ); path = parseLineNode( node ); break; default: console.log( node ); } if ( path ) { if ( style.fill !== undefined && style.fill !== 'none' ) { path.color.setStyle( style.fill ); } transformPath( path, currentTransform ); paths.push( path ); path.userData = { node: node, style: style }; } var nodes = node.childNodes; for ( var i = 0; i < nodes.length; i ++ ) { parseNode( nodes[ i ], style ); } if ( transform ) { transformStack.pop(); if ( transformStack.length > 0 ) { currentTransform.copy( transformStack[ transformStack.length - 1 ] ); } else { currentTransform.identity(); } } } function parsePathNode( node ) { var path = new THREE.ShapePath(); var point = new THREE.Vector2(); var control = new THREE.Vector2(); var firstPoint = new THREE.Vector2(); var isFirstPoint = true; var doSetFirstPoint = false; var d = node.getAttribute( 'd' ); // console.log( d ); var commands = d.match( /[a-df-z][^a-df-z]*/ig ); for ( var i = 0, l = commands.length; i < l; i ++ ) { var command = commands[ i ]; var type = command.charAt( 0 ); var data = command.substr( 1 ).trim(); if ( isFirstPoint === true ) { doSetFirstPoint = true; isFirstPoint = false; } switch ( type ) { case 'M': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x = numbers[ j + 0 ]; point.y = numbers[ j + 1 ]; control.x = point.x; control.y = point.y; if ( j === 0 ) { path.moveTo( point.x, point.y ); } else { path.lineTo( point.x, point.y ); } if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'H': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.x = numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'V': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.y = numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'L': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x = numbers[ j + 0 ]; point.y = numbers[ j + 1 ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'C': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) { path.bezierCurveTo( numbers[ j + 0 ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], numbers[ j + 5 ] ); control.x = numbers[ j + 2 ]; control.y = numbers[ j + 3 ]; point.x = numbers[ j + 4 ]; point.y = numbers[ j + 5 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'S': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.bezierCurveTo( getReflection( point.x, control.x ), getReflection( point.y, control.y ), numbers[ j + 0 ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ] ); control.x = numbers[ j + 0 ]; control.y = numbers[ j + 1 ]; point.x = numbers[ j + 2 ]; point.y = numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'Q': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.quadraticCurveTo( numbers[ j + 0 ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ] ); control.x = numbers[ j + 0 ]; control.y = numbers[ j + 1 ]; point.x = numbers[ j + 2 ]; point.y = numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'T': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { var rx = getReflection( point.x, control.x ); var ry = getReflection( point.y, control.y ); path.quadraticCurveTo( rx, ry, numbers[ j + 0 ], numbers[ j + 1 ] ); control.x = rx; control.y = ry; point.x = numbers[ j + 0 ]; point.y = numbers[ j + 1 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'A': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) { var start = point.clone(); point.x = numbers[ j + 5 ]; point.y = numbers[ j + 6 ]; control.x = point.x; control.y = point.y; parseArcCommand( path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'm': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x += numbers[ j + 0 ]; point.y += numbers[ j + 1 ]; control.x = point.x; control.y = point.y; if ( j === 0 ) { path.moveTo( point.x, point.y ); } else { path.lineTo( point.x, point.y ); } if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'h': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.x += numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'v': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j ++ ) { point.y += numbers[ j ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'l': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { point.x += numbers[ j + 0 ]; point.y += numbers[ j + 1 ]; control.x = point.x; control.y = point.y; path.lineTo( point.x, point.y ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'c': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 6 ) { path.bezierCurveTo( point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ], point.x + numbers[ j + 2 ], point.y + numbers[ j + 3 ], point.x + numbers[ j + 4 ], point.y + numbers[ j + 5 ] ); control.x = point.x + numbers[ j + 2 ]; control.y = point.y + numbers[ j + 3 ]; point.x += numbers[ j + 4 ]; point.y += numbers[ j + 5 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 's': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.bezierCurveTo( getReflection( point.x, control.x ), getReflection( point.y, control.y ), point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ], point.x + numbers[ j + 2 ], point.y + numbers[ j + 3 ] ); control.x = point.x + numbers[ j + 0 ]; control.y = point.y + numbers[ j + 1 ]; point.x += numbers[ j + 2 ]; point.y += numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'q': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 4 ) { path.quadraticCurveTo( point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ], point.x + numbers[ j + 2 ], point.y + numbers[ j + 3 ] ); control.x = point.x + numbers[ j + 0 ]; control.y = point.y + numbers[ j + 1 ]; point.x += numbers[ j + 2 ]; point.y += numbers[ j + 3 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 't': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 2 ) { var rx = getReflection( point.x, control.x ); var ry = getReflection( point.y, control.y ); path.quadraticCurveTo( rx, ry, point.x + numbers[ j + 0 ], point.y + numbers[ j + 1 ] ); control.x = rx; control.y = ry; point.x = point.x + numbers[ j + 0 ]; point.y = point.y + numbers[ j + 1 ]; if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'a': var numbers = parseFloats( data ); for ( var j = 0, jl = numbers.length; j < jl; j += 7 ) { var start = point.clone(); point.x += numbers[ j + 5 ]; point.y += numbers[ j + 6 ]; control.x = point.x; control.y = point.y; parseArcCommand( path, numbers[ j ], numbers[ j + 1 ], numbers[ j + 2 ], numbers[ j + 3 ], numbers[ j + 4 ], start, point ); if ( j === 0 && doSetFirstPoint === true ) firstPoint.copy( point ); } break; case 'Z': case 'z': path.currentPath.autoClose = true; if ( path.currentPath.curves.length > 0 ) { // Reset point to beginning of Path point.copy( firstPoint ); path.currentPath.currentPoint.copy( point ); isFirstPoint = true; } break; default: console.warn( command ); } // console.log( type, parseFloats( data ), parseFloats( data ).length ) doSetFirstPoint = false; } return path; } /** * https://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes * https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ Appendix: Endpoint to center arc conversion * From * rx ry x-axis-rotation large-arc-flag sweep-flag x y * To * aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation */ function parseArcCommand( path, rx, ry, x_axis_rotation, large_arc_flag, sweep_flag, start, end ) { x_axis_rotation = x_axis_rotation * Math.PI / 180; // Ensure radii are positive rx = Math.abs( rx ); ry = Math.abs( ry ); // Compute (x1′, y1′) var dx2 = ( start.x - end.x ) / 2.0; var dy2 = ( start.y - end.y ) / 2.0; var x1p = Math.cos( x_axis_rotation ) * dx2 + Math.sin( x_axis_rotation ) * dy2; var y1p = - Math.sin( x_axis_rotation ) * dx2 + Math.cos( x_axis_rotation ) * dy2; // Compute (cx′, cy′) var rxs = rx * rx; var rys = ry * ry; var x1ps = x1p * x1p; var y1ps = y1p * y1p; // Ensure radii are large enough var cr = x1ps / rxs + y1ps / rys; if ( cr > 1 ) { // scale up rx,ry equally so cr == 1 var s = Math.sqrt( cr ); rx = s * rx; ry = s * ry; rxs = rx * rx; rys = ry * ry; } var dq = ( rxs * y1ps + rys * x1ps ); var pq = ( rxs * rys - dq ) / dq; var q = Math.sqrt( Math.max( 0, pq ) ); if ( large_arc_flag === sweep_flag ) q = - q; var cxp = q * rx * y1p / ry; var cyp = - q * ry * x1p / rx; // Step 3: Compute (cx, cy) from (cx′, cy′) var cx = Math.cos( x_axis_rotation ) * cxp - Math.sin( x_axis_rotation ) * cyp + ( start.x + end.x ) / 2; var cy = Math.sin( x_axis_rotation ) * cxp + Math.cos( x_axis_rotation ) * cyp + ( start.y + end.y ) / 2; // Step 4: Compute θ1 and Δθ var theta = svgAngle( 1, 0, ( x1p - cxp ) / rx, ( y1p - cyp ) / ry ); var delta = svgAngle( ( x1p - cxp ) / rx, ( y1p - cyp ) / ry, ( - x1p - cxp ) / rx, ( - y1p - cyp ) / ry ) % ( Math.PI * 2 ); path.currentPath.absellipse( cx, cy, rx, ry, theta, theta + delta, sweep_flag === 0, x_axis_rotation ); } function svgAngle( ux, uy, vx, vy ) { var dot = ux * vx + uy * vy; var len = Math.sqrt( ux * ux + uy * uy ) * Math.sqrt( vx * vx + vy * vy ); var ang = Math.acos( Math.max( - 1, Math.min( 1, dot / len ) ) ); // floating point precision, slightly over values appear if ( ( ux * vy - uy * vx ) < 0 ) ang = - ang; return ang; } /* * According to https://www.w3.org/TR/SVG/shapes.html#RectElementRXAttribute * rounded corner should be rendered to elliptical arc, but bezier curve does the job well enough */ function parseRectNode( node ) { var x = parseFloat( node.getAttribute( 'x' ) || 0 ); var y = parseFloat( node.getAttribute( 'y' ) || 0 ); var rx = parseFloat( node.getAttribute( 'rx' ) || 0 ); var ry = parseFloat( node.getAttribute( 'ry' ) || 0 ); var w = parseFloat( node.getAttribute( 'width' ) ); var h = parseFloat( node.getAttribute( 'height' ) ); var path = new THREE.ShapePath(); path.moveTo( x + 2 * rx, y ); path.lineTo( x + w - 2 * rx, y ); if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y, x + w, y, x + w, y + 2 * ry ); path.lineTo( x + w, y + h - 2 * ry ); if ( rx !== 0 || ry !== 0 ) path.bezierCurveTo( x + w, y + h, x + w, y + h, x + w - 2 * rx, y + h ); path.lineTo( x + 2 * rx, y + h ); if ( rx !== 0 || ry !== 0 ) { path.bezierCurveTo( x, y + h, x, y + h, x, y + h - 2 * ry ); } path.lineTo( x, y + 2 * ry ); if ( rx !== 0 || ry !== 0 ) { path.bezierCurveTo( x, y, x, y, x + 2 * rx, y ); } return path; } function parsePolygonNode( node ) { function iterator( match, a, b ) { var x = parseFloat( a ); var y = parseFloat( b ); if ( index === 0 ) { path.moveTo( x, y ); } else { path.lineTo( x, y ); } index ++; } var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g; var path = new THREE.ShapePath(); var index = 0; node.getAttribute( 'points' ).replace( regex, iterator ); path.currentPath.autoClose = true; return path; } function parsePolylineNode( node ) { function iterator( match, a, b ) { var x = parseFloat( a ); var y = parseFloat( b ); if ( index === 0 ) { path.moveTo( x, y ); } else { path.lineTo( x, y ); } index ++; } var regex = /(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g; var path = new THREE.ShapePath(); var index = 0; node.getAttribute( 'points' ).replace( regex, iterator ); path.currentPath.autoClose = false; return path; } function parseCircleNode( node ) { var x = parseFloat( node.getAttribute( 'cx' ) ); var y = parseFloat( node.getAttribute( 'cy' ) ); var r = parseFloat( node.getAttribute( 'r' ) ); var subpath = new THREE.Path(); subpath.absarc( x, y, r, 0, Math.PI * 2 ); var path = new THREE.ShapePath(); path.subPaths.push( subpath ); return path; } function parseEllipseNode( node ) { var x = parseFloat( node.getAttribute( 'cx' ) ); var y = parseFloat( node.getAttribute( 'cy' ) ); var rx = parseFloat( node.getAttribute( 'rx' ) ); var ry = parseFloat( node.getAttribute( 'ry' ) ); var subpath = new THREE.Path(); subpath.absellipse( x, y, rx, ry, 0, Math.PI * 2 ); var path = new THREE.ShapePath(); path.subPaths.push( subpath ); return path; } function parseLineNode( node ) { var x1 = parseFloat( node.getAttribute( 'x1' ) ); var y1 = parseFloat( node.getAttribute( 'y1' ) ); var x2 = parseFloat( node.getAttribute( 'x2' ) ); var y2 = parseFloat( node.getAttribute( 'y2' ) ); var path = new THREE.ShapePath(); path.moveTo( x1, y1 ); path.lineTo( x2, y2 ); path.currentPath.autoClose = false; return path; } // function parseStyle( node, style ) { style = Object.assign( {}, style ); // clone style function addStyle( svgName, jsName, adjustFunction ) { if ( adjustFunction === undefined ) adjustFunction = function copy( v ) { return v; }; if ( node.hasAttribute( svgName ) ) style[ jsName ] = adjustFunction( node.getAttribute( svgName ) ); if ( node.style[ svgName ] !== '' ) style[ jsName ] = adjustFunction( node.style[ svgName ] ); } function clamp( v ) { return Math.max( 0, Math.min( 1, v ) ); } function positive( v ) { return Math.max( 0, v ); } addStyle( 'fill', 'fill' ); addStyle( 'fill-opacity', 'fillOpacity', clamp ); addStyle( 'stroke', 'stroke' ); addStyle( 'stroke-opacity', 'strokeOpacity', clamp ); addStyle( 'stroke-width', 'strokeWidth', positive ); addStyle( 'stroke-linejoin', 'strokeLineJoin' ); addStyle( 'stroke-linecap', 'strokeLineCap' ); addStyle( 'stroke-miterlimit', 'strokeMiterLimit', positive ); return style; } // http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes function getReflection( a, b ) { return a - ( b - a ); } function parseFloats( string ) { var array = string.split( /[\s,]+|(?=\s?[+\-])/ ); for ( var i = 0; i < array.length; i ++ ) { var number = array[ i ]; // Handle values like 48.6037.7.8 // TODO Find a regex for this if ( number.indexOf( '.' ) !== number.lastIndexOf( '.' ) ) { var split = number.split( '.' ); for ( var s = 2; s < split.length; s ++ ) { array.splice( i + s - 1, 0, '0.' + split[ s ] ); } } array[ i ] = parseFloat( number ); } return array; } function getNodeTransform( node ) { if ( ! node.hasAttribute( 'transform' ) ) { return null; } var transform = parseNodeTransform( node ); if ( transform ) { if ( transformStack.length > 0 ) { transform.premultiply( transformStack[ transformStack.length - 1 ] ); } currentTransform.copy( transform ); transformStack.push( transform ); } return transform; } function parseNodeTransform( node ) { var transform = new THREE.Matrix3(); var currentTransform = tempTransform0; var transformsTexts = node.getAttribute( 'transform' ).split( ')' ); for ( var tIndex = transformsTexts.length - 1; tIndex >= 0; tIndex -- ) { var transformText = transformsTexts[ tIndex ].trim(); if ( transformText === '' ) continue; var openParPos = transformText.indexOf( '(' ); var closeParPos = transformText.length; if ( openParPos > 0 && openParPos < closeParPos ) { var transformType = transformText.substr( 0, openParPos ); var array = parseFloats( transformText.substr( openParPos + 1, closeParPos - openParPos - 1 ) ); currentTransform.identity(); switch ( transformType ) { case "translate": if ( array.length >= 1 ) { var tx = array[ 0 ]; var ty = tx; if ( array.length >= 2 ) { ty = array[ 1 ]; } currentTransform.translate( tx, ty ); } break; case "rotate": if ( array.length >= 1 ) { var angle = 0; var cx = 0; var cy = 0; // Angle angle = - array[ 0 ] * Math.PI / 180; if ( array.length >= 3 ) { // Center x, y cx = array[ 1 ]; cy = array[ 2 ]; } // Rotate around center (cx, cy) tempTransform1.identity().translate( - cx, - cy ); tempTransform2.identity().rotate( angle ); tempTransform3.multiplyMatrices( tempTransform2, tempTransform1 ); tempTransform1.identity().translate( cx, cy ); currentTransform.multiplyMatrices( tempTransform1, tempTransform3 ); } break; case "scale": if ( array.length >= 1 ) { var scaleX = array[ 0 ]; var scaleY = scaleX; if ( array.length >= 2 ) { scaleY = array[ 1 ]; } currentTransform.scale( scaleX, scaleY ); } break; case "skewX": if ( array.length === 1 ) { currentTransform.set( 1, Math.tan( array[ 0 ] * Math.PI / 180 ), 0, 0, 1, 0, 0, 0, 1 ); } break; case "skewY": if ( array.length === 1 ) { currentTransform.set( 1, 0, 0, Math.tan( array[ 0 ] * Math.PI / 180 ), 1, 0, 0, 0, 1 ); } break; case "matrix": if ( array.length === 6 ) { currentTransform.set( array[ 0 ], array[ 2 ], array[ 4 ], array[ 1 ], array[ 3 ], array[ 5 ], 0, 0, 1 ); } break; } } transform.premultiply( currentTransform ); } return transform; } function transformPath( path, m ) { function transfVec2( v2 ) { tempV3.set( v2.x, v2.y, 1 ).applyMatrix3( m ); v2.set( tempV3.x, tempV3.y ); } var isRotated = isTransformRotated( m ); var subPaths = path.subPaths; for ( var i = 0, n = subPaths.length; i < n; i ++ ) { var subPath = subPaths[ i ]; var curves = subPath.curves; for ( var j = 0; j < curves.length; j ++ ) { var curve = curves[ j ]; if ( curve.isLineCurve ) { transfVec2( curve.v1 ); transfVec2( curve.v2 ); } else if ( curve.isCubicBezierCurve ) { transfVec2( curve.v0 ); transfVec2( curve.v1 ); transfVec2( curve.v2 ); transfVec2( curve.v3 ); } else if ( curve.isQuadraticBezierCurve ) { transfVec2( curve.v0 ); transfVec2( curve.v1 ); transfVec2( curve.v2 ); } else if ( curve.isEllipseCurve ) { if ( isRotated ) { console.warn( "SVGLoader: Elliptic arc or ellipse rotation or skewing is not implemented." ); } tempV2.set( curve.aX, curve.aY ); transfVec2( tempV2 ); curve.aX = tempV2.x; curve.aY = tempV2.y; curve.xRadius *= getTransformScaleX( m ); curve.yRadius *= getTransformScaleY( m ); } } } } function isTransformRotated( m ) { return m.elements[ 1 ] !== 0 || m.elements[ 3 ] !== 0; } function getTransformScaleX( m ) { var te = m.elements; return Math.sqrt( te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] ); } function getTransformScaleY( m ) { var te = m.elements; return Math.sqrt( te[ 3 ] * te[ 3 ] + te[ 4 ] * te[ 4 ] ); } // console.log( 'THREE.SVGLoader' ); var paths = []; var transformStack = []; var tempTransform0 = new THREE.Matrix3(); var tempTransform1 = new THREE.Matrix3(); var tempTransform2 = new THREE.Matrix3(); var tempTransform3 = new THREE.Matrix3(); var tempV2 = new THREE.Vector2(); var tempV3 = new THREE.Vector3(); var currentTransform = new THREE.Matrix3(); console.time( 'THREE.SVGLoader: DOMParser' ); var xml = new DOMParser().parseFromString( text, 'image/svg+xml' ); // application/xml console.timeEnd( 'THREE.SVGLoader: DOMParser' ); console.time( 'THREE.SVGLoader: Parse' ); parseNode( xml.documentElement, { fill: '#000', fillOpacity: 1, strokeOpacity: 1, strokeWidth: 1, strokeLineJoin: 'miter', strokeLineCap: 'butt', strokeMiterLimit: 4 } ); var data = { paths: paths, xml: xml.documentElement }; // console.log( paths ); console.timeEnd( 'THREE.SVGLoader: Parse' ); return data; } }; THREE.SVGLoader.getStrokeStyle = function ( width, color, opacity, lineJoin, lineCap, miterLimit ) { // Param width: Stroke width // Param color: As returned by THREE.Color.getStyle() // Param opacity: 0 (transparent) to 1 (opaque) // Param lineJoin: One of "round", "bevel", "miter" or "miter-limit" // Param lineCap: One of "round", "square" or "butt" // Param miterLimit: Maximum join length, in multiples of the "width" parameter (join is truncated if it exceeds that distance) // Returns style object width = width !== undefined ? width : 1; color = color !== undefined ? color : '#000'; opacity = opacity !== undefined ? opacity : 1; lineJoin = lineJoin !== undefined ? lineJoin : 'miter'; lineCap = lineCap !== undefined ? lineCap : 'butt'; miterLimit = miterLimit !== undefined ? miterLimit : 4; return { strokeColor: color, strokeWidth: width, strokeLineJoin: lineJoin, strokeLineCap: lineCap, strokeMiterLimit: miterLimit }; }; THREE.SVGLoader.pointsToStroke = function ( points, style, arcDivisions, minDistance ) { // Generates a stroke with some witdh around the given path. // The path can be open or closed (last point equals to first point) // Param points: Array of Vector2D (the path). Minimum 2 points. // Param style: Object with SVG properties as returned by SVGLoader.getStrokeStyle(), or SVGLoader.parse() in the path.userData.style object // Params arcDivisions: Arc divisions for round joins and endcaps. (Optional) // Param minDistance: Points closer to this distance will be merged. (Optional) // Returns BufferGeometry with stroke triangles (In plane z = 0). UV coordinates are generated ('u' along path. 'v' across it, from left to right) var vertices = []; var normals = []; var uvs = []; if ( THREE.SVGLoader.pointsToStrokeWithBuffers( points, style, arcDivisions, minDistance, vertices, normals, uvs ) === 0 ) { return null; } var geometry = new THREE.BufferGeometry(); geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) ); geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) ); geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) ); return geometry; }; THREE.SVGLoader.pointsToStrokeWithBuffers = function () { var tempV2_1 = new THREE.Vector2(); var tempV2_2 = new THREE.Vector2(); var tempV2_3 = new THREE.Vector2(); var tempV2_4 = new THREE.Vector2(); var tempV2_5 = new THREE.Vector2(); var tempV2_6 = new THREE.Vector2(); var tempV2_7 = new THREE.Vector2(); var lastPointL = new THREE.Vector2(); var lastPointR = new THREE.Vector2(); var point0L = new THREE.Vector2(); var point0R = new THREE.Vector2(); var currentPointL = new THREE.Vector2(); var currentPointR = new THREE.Vector2(); var nextPointL = new THREE.Vector2(); var nextPointR = new THREE.Vector2(); var innerPoint = new THREE.Vector2(); var outerPoint = new THREE.Vector2(); return function ( points, style, arcDivisions, minDistance, vertices, normals, uvs, vertexOffset ) { // This function can be called to update existing arrays or buffers. // Accepts same parameters as pointsToStroke, plus the buffers and optional offset. // Param vertexOffset: Offset vertices to start writing in the buffers (3 elements/vertex for vertices and normals, and 2 elements/vertex for uvs) // Returns number of written vertices / normals / uvs pairs // if 'vertices' parameter is undefined no triangles will be generated, but the returned vertices count will still be valid (useful to preallocate the buffers) // 'normals' and 'uvs' buffers are optional arcDivisions = arcDivisions !== undefined ? arcDivisions : 12; minDistance = minDistance !== undefined ? minDistance : 0.001; vertexOffset = vertexOffset !== undefined ? vertexOffset : 0; // First ensure there are no duplicated points points = removeDuplicatedPoints( points ); var numPoints = points.length; if ( numPoints < 2 ) return 0; var isClosed = points[ 0 ].equals( points[ numPoints - 1 ] ); var currentPoint; var previousPoint = points[ 0 ]; var nextPoint; var strokeWidth2 = style.strokeWidth / 2; var deltaU = 1 / ( numPoints - 1 ); var u0 = 0; var innerSideModified; var joinIsOnLeftSide; var isMiter; var initialJoinIsOnLeftSide = false; var numVertices = 0; var currentCoordinate = vertexOffset * 3; var currentCoordinateUV = vertexOffset * 2; // Get initial left and right stroke points getNormal( points[ 0 ], points[ 1 ], tempV2_1 ).multiplyScalar( strokeWidth2 ); lastPointL.copy( points[ 0 ] ).sub( tempV2_1 ); lastPointR.copy( points[ 0 ] ).add( tempV2_1 ); point0L.copy( lastPointL ); point0R.copy( lastPointR ); for ( var iPoint = 1; iPoint < numPoints; iPoint ++ ) { currentPoint = points[ iPoint ]; // Get next point if ( iPoint === numPoints - 1 ) { if ( isClosed ) { // Skip duplicated initial point nextPoint = points[ 1 ]; } else nextPoint = undefined; } else { nextPoint = points[ iPoint + 1 ]; } // Normal of previous segment in tempV2_1 var normal1 = tempV2_1; getNormal( previousPoint, currentPoint, normal1 ); tempV2_3.copy( normal1 ).multiplyScalar( strokeWidth2 ); currentPointL.copy( currentPoint ).sub( tempV2_3 ); currentPointR.copy( currentPoint ).add( tempV2_3 ); var u1 = u0 + deltaU; innerSideModified = false; if ( nextPoint !== undefined ) { // Normal of next segment in tempV2_2 getNormal( currentPoint, nextPoint, tempV2_2 ); tempV2_3.copy( tempV2_2 ).multiplyScalar( strokeWidth2 ); nextPointL.copy( currentPoint ).sub( tempV2_3 ); nextPointR.copy( currentPoint ).add( tempV2_3 ); joinIsOnLeftSide = true; tempV2_3.subVectors( nextPoint, previousPoint ); if ( normal1.dot( tempV2_3 ) < 0 ) { joinIsOnLeftSide = false; } if ( iPoint === 1 ) initialJoinIsOnLeftSide = joinIsOnLeftSide; tempV2_3.subVectors( nextPoint, currentPoint ); tempV2_3.normalize(); var dot = Math.abs( normal1.dot( tempV2_3 ) ); // If path is straight, don't create join if ( dot !== 0 ) { // Compute inner and outer segment intersections var miterSide = strokeWidth2 / dot; tempV2_3.multiplyScalar( - miterSide ); tempV2_4.subVectors( currentPoint, previousPoint ); tempV2_5.copy( tempV2_4 ).setLength( miterSide ).add( tempV2_3 ); innerPoint.copy( tempV2_5 ).negate(); var miterLength2 = tempV2_5.length(); var segmentLengthPrev = tempV2_4.length(); tempV2_4.divideScalar( segmentLengthPrev ); tempV2_6.subVectors( nextPoint, currentPoint ); var segmentLengthNext = tempV2_6.length(); tempV2_6.divideScalar( segmentLengthNext ); // Check that previous and next segments doesn't overlap with the innerPoint of intersection if ( tempV2_4.dot( innerPoint ) < segmentLengthPrev && tempV2_6.dot( innerPoint ) < segmentLengthNext ) { innerSideModified = true; } outerPoint.copy( tempV2_5 ).add( currentPoint ); innerPoint.add( currentPoint ); isMiter = false; if ( innerSideModified ) { if ( joinIsOnLeftSide ) { nextPointR.copy( innerPoint ); currentPointR.copy( innerPoint ); } else { nextPointL.copy( innerPoint ); currentPointL.copy( innerPoint ); } } else { // The segment triangles are generated here if there was overlapping makeSegmentTriangles(); } switch ( style.strokeLineJoin ) { case 'bevel': makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 ); break; case 'round': // Segment triangles createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ); // Join triangles if ( joinIsOnLeftSide ) { makeCircularSector( currentPoint, currentPointL, nextPointL, u1, 0 ); } else { makeCircularSector( currentPoint, nextPointR, currentPointR, u1, 1 ); } break; case 'miter': case 'miter-clip': default: var miterFraction = ( strokeWidth2 * style.strokeMiterLimit ) / miterLength2; if ( miterFraction < 1 ) { // The join miter length exceeds the miter limit if ( style.strokeLineJoin !== 'miter-clip' ) { makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u1 ); break; } else { // Segment triangles createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ); // Miter-clip join triangles if ( joinIsOnLeftSide ) { tempV2_6.subVectors( outerPoint, currentPointL ).multiplyScalar( miterFraction ).add( currentPointL ); tempV2_7.subVectors( outerPoint, nextPointL ).multiplyScalar( miterFraction ).add( nextPointL ); addVertex( currentPointL, u1, 0 ); addVertex( tempV2_6, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_6, u1, 0 ); addVertex( tempV2_7, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_7, u1, 0 ); addVertex( nextPointL, u1, 0 ); } else { tempV2_6.subVectors( outerPoint, currentPointR ).multiplyScalar( miterFraction ).add( currentPointR ); tempV2_7.subVectors( outerPoint, nextPointR ).multiplyScalar( miterFraction ).add( nextPointR ); addVertex( currentPointR, u1, 1 ); addVertex( tempV2_6, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_6, u1, 1 ); addVertex( tempV2_7, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( tempV2_7, u1, 1 ); addVertex( nextPointR, u1, 1 ); } } } else { // Miter join segment triangles if ( innerSideModified ) { // Optimized segment + join triangles if ( joinIsOnLeftSide ) { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( outerPoint, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( outerPoint, u1, 0 ); addVertex( innerPoint, u1, 1 ); } else { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( outerPoint, u1, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( innerPoint, u1, 0 ); addVertex( outerPoint, u1, 1 ); } if ( joinIsOnLeftSide ) { nextPointL.copy( outerPoint ); } else { nextPointR.copy( outerPoint ); } } else { // Add extra miter join triangles if ( joinIsOnLeftSide ) { addVertex( currentPointL, u1, 0 ); addVertex( outerPoint, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( outerPoint, u1, 0 ); addVertex( nextPointL, u1, 0 ); } else { addVertex( currentPointR, u1, 1 ); addVertex( outerPoint, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( outerPoint, u1, 1 ); addVertex( nextPointR, u1, 1 ); } } isMiter = true; } break; } } else { // The segment triangles are generated here when two consecutive points are collinear makeSegmentTriangles(); } } else { // The segment triangles are generated here if it is the ending segment makeSegmentTriangles(); } if ( ! isClosed && iPoint === numPoints - 1 ) { // Start line endcap addCapGeometry( points[ 0 ], point0L, point0R, joinIsOnLeftSide, true, u0 ); } // Increment loop variables u0 = u1; previousPoint = currentPoint; lastPointL.copy( nextPointL ); lastPointR.copy( nextPointR ); } if ( ! isClosed ) { // Ending line endcap addCapGeometry( currentPoint, currentPointL, currentPointR, joinIsOnLeftSide, false, u1 ); } else if ( innerSideModified && vertices ) { // Modify path first segment vertices to adjust to the segments inner and outer intersections var lastOuter = outerPoint; var lastInner = innerPoint; if ( initialJoinIsOnLeftSide !== joinIsOnLeftSide ) { lastOuter = innerPoint; lastInner = outerPoint; } if ( joinIsOnLeftSide ) { lastInner.toArray( vertices, 0 * 3 ); lastInner.toArray( vertices, 3 * 3 ); if ( isMiter ) { lastOuter.toArray( vertices, 1 * 3 ); } } else { lastInner.toArray( vertices, 1 * 3 ); lastInner.toArray( vertices, 3 * 3 ); if ( isMiter ) { lastOuter.toArray( vertices, 0 * 3 ); } } } return numVertices; // -- End of algorithm // -- Functions function getNormal( p1, p2, result ) { result.subVectors( p2, p1 ); return result.set( - result.y, result.x ).normalize(); } function addVertex( position, u, v ) { if ( vertices ) { vertices[ currentCoordinate ] = position.x; vertices[ currentCoordinate + 1 ] = position.y; vertices[ currentCoordinate + 2 ] = 0; if ( normals ) { normals[ currentCoordinate ] = 0; normals[ currentCoordinate + 1 ] = 0; normals[ currentCoordinate + 2 ] = 1; } currentCoordinate += 3; if ( uvs ) { uvs[ currentCoordinateUV ] = u; uvs[ currentCoordinateUV + 1 ] = v; currentCoordinateUV += 2; } } numVertices += 3; } function makeCircularSector( center, p1, p2, u, v ) { // param p1, p2: Points in the circle arc. // p1 and p2 are in clockwise direction. tempV2_1.copy( p1 ).sub( center ).normalize(); tempV2_2.copy( p2 ).sub( center ).normalize(); var angle = Math.PI; var dot = tempV2_1.dot( tempV2_2 ); if ( Math.abs( dot ) < 1 ) angle = Math.abs( Math.acos( dot ) ); angle /= arcDivisions; tempV2_3.copy( p1 ); for ( var i = 0, il = arcDivisions - 1; i < il; i ++ ) { tempV2_4.copy( tempV2_3 ).rotateAround( center, angle ); addVertex( tempV2_3, u, v ); addVertex( tempV2_4, u, v ); addVertex( center, u, 0.5 ); tempV2_3.copy( tempV2_4 ); } addVertex( tempV2_4, u, v ); addVertex( p2, u, v ); addVertex( center, u, 0.5 ); } function makeSegmentTriangles() { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointL, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( currentPointL, u1, 1 ); addVertex( currentPointR, u1, 0 ); } function makeSegmentWithBevelJoin( joinIsOnLeftSide, innerSideModified, u ) { if ( innerSideModified ) { // Optimized segment + bevel triangles if ( joinIsOnLeftSide ) { // Path segments triangles addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointL, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( currentPointL, u1, 0 ); addVertex( innerPoint, u1, 1 ); // Bevel join triangle addVertex( currentPointL, u, 0 ); addVertex( nextPointL, u, 0 ); addVertex( innerPoint, u, 0.5 ); } else { // Path segments triangles addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointR, u1, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( innerPoint, u1, 0 ); addVertex( currentPointR, u1, 1 ); // Bevel join triangle addVertex( currentPointR, u, 1 ); addVertex( nextPointR, u, 0 ); addVertex( innerPoint, u, 0.5 ); } } else { // Bevel join triangle. The segment triangles are done in the main loop if ( joinIsOnLeftSide ) { addVertex( currentPointL, u, 0 ); addVertex( nextPointL, u, 0 ); addVertex( currentPoint, u, 0.5 ); } else { addVertex( currentPointR, u, 1 ); addVertex( nextPointR, u, 0 ); addVertex( currentPoint, u, 0.5 ); } } } function createSegmentTrianglesWithMiddleSection( joinIsOnLeftSide, innerSideModified ) { if ( innerSideModified ) { if ( joinIsOnLeftSide ) { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointL, u1, 0 ); addVertex( lastPointR, u0, 1 ); addVertex( currentPointL, u1, 0 ); addVertex( innerPoint, u1, 1 ); addVertex( currentPointL, u0, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( innerPoint, u1, 1 ); addVertex( currentPoint, u1, 0.5 ); addVertex( nextPointL, u0, 0 ); addVertex( innerPoint, u1, 1 ); } else { addVertex( lastPointR, u0, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( currentPointR, u1, 1 ); addVertex( lastPointL, u0, 0 ); addVertex( innerPoint, u1, 0 ); addVertex( currentPointR, u1, 1 ); addVertex( currentPointR, u0, 1 ); addVertex( innerPoint, u1, 0 ); addVertex( currentPoint, u1, 0.5 ); addVertex( currentPoint, u1, 0.5 ); addVertex( innerPoint, u1, 0 ); addVertex( nextPointR, u0, 1 ); } } } function addCapGeometry( center, p1, p2, joinIsOnLeftSide, start, u ) { // param center: End point of the path // param p1, p2: Left and right cap points switch ( style.strokeLineCap ) { case 'round': if ( start ) { makeCircularSector( center, p2, p1, u, 0.5 ); } else { makeCircularSector( center, p1, p2, u, 0.5 ); } break; case 'square': if ( start ) { tempV2_1.subVectors( p1, center ); tempV2_2.set( tempV2_1.y, - tempV2_1.x ); tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center ); tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center ); // Modify already existing vertices if ( joinIsOnLeftSide ) { tempV2_3.toArray( vertices, 1 * 3 ); tempV2_4.toArray( vertices, 0 * 3 ); tempV2_4.toArray( vertices, 3 * 3 ); } else { tempV2_3.toArray( vertices, 1 * 3 ); tempV2_3.toArray( vertices, 3 * 3 ); tempV2_4.toArray( vertices, 0 * 3 ); } } else { tempV2_1.subVectors( p2, center ); tempV2_2.set( tempV2_1.y, - tempV2_1.x ); tempV2_3.addVectors( tempV2_1, tempV2_2 ).add( center ); tempV2_4.subVectors( tempV2_2, tempV2_1 ).add( center ); var vl = vertices.length; // Modify already existing vertices if ( joinIsOnLeftSide ) { tempV2_3.toArray( vertices, vl - 1 * 3 ); tempV2_4.toArray( vertices, vl - 2 * 3 ); tempV2_4.toArray( vertices, vl - 4 * 3 ); } else { tempV2_3.toArray( vertices, vl - 2 * 3 ); tempV2_4.toArray( vertices, vl - 1 * 3 ); tempV2_4.toArray( vertices, vl - 4 * 3 ); } } break; case 'butt': default: // Nothing to do here break; } } function removeDuplicatedPoints( points ) { // Creates a new array if necessary with duplicated points removed. // This does not remove duplicated initial and ending points of a closed path. var dupPoints = false; for ( var i = 1, n = points.length - 1; i < n; i ++ ) { if ( points[ i ].distanceTo( points[ i + 1 ] ) < minDistance ) { dupPoints = true; break; } } if ( ! dupPoints ) return points; var newPoints = []; newPoints.push( points[ 0 ] ); for ( var i = 1, n = points.length - 1; i < n; i ++ ) { if ( points[ i ].distanceTo( points[ i + 1 ] ) >= minDistance ) { newPoints.push( points[ i ] ); } } newPoints.push( points[ points.length - 1 ] ); return newPoints; } }; }();
var express = require('express'); var http = require('http'); var routes = require('./modules/routes.js'); var importer = require('./modules/importer.js'); var app = express(); app.configure(function () { app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('CDqHZyw4v8NPxUWoecuA')); app.use(express.session()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function () { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function () { app.use(express.errorHandler()); }); // Gets app.get('/', routes.index); app.get('/projects', routes.hasToken, routes.getProjects); app.get('/iterations', routes.hasToken, routes.getIterations); app.get('/stories', routes.hasToken, routes.getStories); // Posts app.post('/addStory', routes.hasToken, routes.addStory); app.post('/moveStory', routes.hasToken, routes.moveStory); app.post('/updateStory', routes.hasToken, routes.updateStory); app.post('/addStoryComment', routes.hasToken, routes.addStoryComment); // JIRA Importer app.get('/getImportLog', importer.getImportLog); app.post('/getImportableProjects', importer.getImportableProjects); app.post('/importProject', importer.importProject); // Teamcity app.get('/getTeamcityBuildStatus', routes.hasToken, routes.getTeamcityBuildStatus); http.createServer(app).listen(app.get('port'), function () { console.log("Express server listening on port " + app.get('port')); });
var assert = require('assert') var debug = require('debug')('ref') exports = module.exports = require('bindings')('binding') /** * A `Buffer` that references the C NULL pointer. That is, its memory address * points to 0. Its `length` is 0 because accessing any data from this buffer * would cause a _segmentation fault_. * * ``` * console.log(ref.NULL); * <SlowBuffer@0x0 > * ``` * * @name NULL * @type Buffer */ /** * A string that represents the native endianness of the machine's processor. * The possible values are either `"LE"` or `"BE"`. * * ``` * console.log(ref.endianness); * 'LE' * ``` * * @name endianness * @type String */ /** * Accepts a `Buffer` instance and returns the memory address of the buffer * instance. * * ``` * console.log(ref.address(new Buffer(1))); * 4320233616 * * console.log(ref.address(ref.NULL))); * 0 * ``` * * @param {Buffer} buffer The buffer to get the memory address of. * @return {Number} The memory address the buffer instance. * @name address * @type method */ /** * Accepts a `Buffer` instance and returns _true_ if the buffer represents the * NULL pointer, _false_ otherwise. * * ``` * console.log(ref.isNull(new Buffer(1))); * false * * console.log(ref.isNull(ref.NULL)); * true * ``` * * @param {Buffer} buffer The buffer to check for NULL. * @return {Boolean} true or false. * @name isNull * @type method */ /** * Reads a JavaScript Object that has previously been written to the given * _buffer_ at the given _offset_. * * ``` * var obj = { foo: 'bar' }; * var buf = ref.alloc('Object', obj); * * var obj2 = ref.readObject(buf, 0); * console.log(obj === obj2); * true * ``` * * @param {Buffer} buffer The buffer to read an Object from. * @param {Number} offset The offset to begin reading from. * @return {Object} The Object that was read from _buffer_. * @name readObject * @type method */ /** * Reads a Buffer instance from the given _buffer_ at the given _offset_. * The _size_ parameter specifies the `length` of the returned Buffer instance, * which defaults to __0__. * * ``` * var buf = new Buffer('hello world'); * var pointer = ref.alloc('pointer'); * * var buf2 = ref.readPointer(pointer, 0, buf.length); * console.log(buf.toString()); * 'hello world' * ``` * * @param {Buffer} buffer The buffer to read a Buffer from. * @param {Number} offset The offset to begin reading from. * @param {Number} length (optional) The length of the returned Buffer. Defaults to 0. * @return {Buffer} The Buffer instance that was read from _buffer_. * @name readPointer * @type method */ /** * Returns a JavaScript String read from _buffer_ at the given _offset_. The * C String is read until the first NULL byte, which indicates the end of the * String. * * This function can read beyond the `length` of a Buffer. * * ``` * var buf = new Buffer('hello\0world\0'); * * var str = ref.readCString(buf, 0); * console.log(str); * 'hello' * ``` * * @param {Buffer} buffer The buffer to read a Buffer from. * @param {Number} offset The offset to begin reading from. * @return {String} The String that was read from _buffer_. * @name readCString * @type method */ /** * Returns a big-endian signed 64-bit int read from _buffer_ at the given * _offset_. * * If the returned value will fit inside a JavaScript Number without losing * precision, then a Number is returned, otherwise a String is returned. * * ``` * var buf = ref.alloc('int64'); * ref.writeInt64BE(buf, 0, '9223372036854775807'); * * var val = ref.readInt64BE(buf, 0) * console.log(val) * '9223372036854775807' * ``` * * @param {Buffer} buffer The buffer to read a Buffer from. * @param {Number} offset The offset to begin reading from. * @return {Number|String} The Number or String that was read from _buffer_. * @name readInt64BE * @type method */ /** * Returns a little-endian signed 64-bit int read from _buffer_ at the given * _offset_. * * If the returned value will fit inside a JavaScript Number without losing * precision, then a Number is returned, otherwise a String is returned. * * ``` * var buf = ref.alloc('int64'); * ref.writeInt64LE(buf, 0, '9223372036854775807'); * * var val = ref.readInt64LE(buf, 0) * console.log(val) * '9223372036854775807' * ``` * * @param {Buffer} buffer The buffer to read a Buffer from. * @param {Number} offset The offset to begin reading from. * @return {Number|String} The Number or String that was read from _buffer_. * @name readInt64LE * @type method */ /** * Returns a big-endian unsigned 64-bit int read from _buffer_ at the given * _offset_. * * If the returned value will fit inside a JavaScript Number without losing * precision, then a Number is returned, otherwise a String is returned. * * ``` * var buf = ref.alloc('uint64'); * ref.writeUInt64BE(buf, 0, '18446744073709551615'); * * var val = ref.readUInt64BE(buf, 0) * console.log(val) * '18446744073709551615' * ``` * * @param {Buffer} buffer The buffer to read a Buffer from. * @param {Number} offset The offset to begin reading from. * @return {Number|String} The Number or String that was read from _buffer_. * @name readUInt64BE * @type method */ /** * Returns a little-endian unsigned 64-bit int read from _buffer_ at the given * _offset_. * * If the returned value will fit inside a JavaScript Number without losing * precision, then a Number is returned, otherwise a String is returned. * * ``` * var buf = ref.alloc('uint64'); * ref.writeUInt64LE(buf, 0, '18446744073709551615'); * * var val = ref.readUInt64LE(buf, 0) * console.log(val) * '18446744073709551615' * ``` * * @param {Buffer} buffer The buffer to read a Buffer from. * @param {Number} offset The offset to begin reading from. * @return {Number|String} The Number or String that was read from _buffer_. * @name readUInt64LE * @type method */ /** * Writes the _input_ Number or String as a big-endian signed 64-bit int into * _buffer_ at the given _offset_. * * ``` * var buf = ref.alloc('int64'); * ref.writeInt64BE(buf, 0, '9223372036854775807'); * ``` * * @param {Buffer} buffer The buffer to write to. * @param {Number} offset The offset to begin writing from. * @param {Number|String} input This String or Number which gets written. * @name writeInt64BE * @type method */ /** * Writes the _input_ Number or String as a little-endian signed 64-bit int into * _buffer_ at the given _offset_. * * ``` * var buf = ref.alloc('int64'); * ref.writeInt64LE(buf, 0, '9223372036854775807'); * ``` * * @param {Buffer} buffer The buffer to write to. * @param {Number} offset The offset to begin writing from. * @param {Number|String} input This String or Number which gets written. * @name writeInt64LE * @type method */ /** * Writes the _input_ Number or String as a big-endian unsigned 64-bit int into * _buffer_ at the given _offset_. * * ``` * var buf = ref.alloc('uint64'); * ref.writeUInt64BE(buf, 0, '18446744073709551615'); * ``` * * @param {Buffer} buffer The buffer to write to. * @param {Number} offset The offset to begin writing from. * @param {Number|String} input This String or Number which gets written. * @name writeUInt64BE * @type method */ /** * Writes the _input_ Number or String as a little-endian unsigned 64-bit int * into _buffer_ at the given _offset_. * * ``` * var buf = ref.alloc('uint64'); * ref.writeUInt64LE(buf, 0, '18446744073709551615'); * ``` * * @param {Buffer} buffer The buffer to write to. * @param {Number} offset The offset to begin writing from. * @param {Number|String} input This String or Number which gets written. * @name writeUInt64LE * @type method */ /** * Returns a new clone of the given "type" object, with its * `indirection` level incremented by **1**. * * Say you wanted to create a type representing a `void *`: * * ``` * var voidPtrType = ref.refType(ref.types.void); * ``` * * @param {Object|String} type The "type" object to create a reference type from. Strings get coerced first. * @return {Object} The new "type" object with its `indirection` incremented by 1. */ exports.refType = function refType (type) { var _type = exports.coerceType(type) var rtn = Object.create(_type) rtn.indirection++ if (_type.name) { Object.defineProperty(rtn, 'name', { value: _type.name + '*', configurable: true, enumerable: true, writable: true }) } return rtn } /** * Returns a new clone of the given "type" object, with its * `indirection` level decremented by 1. * * @param {Object|String} type The "type" object to create a dereference type from. Strings get coerced first. * @return {Object} The new "type" object with its `indirection` decremented by 1. */ exports.derefType = function derefType (type) { var _type = exports.coerceType(type) if (_type.indirection === 1) { throw new Error('Cannot create deref\'d type for type with indirection 1') } var rtn = Object.getPrototypeOf(_type) if (rtn.indirection !== _type.indirection - 1) { // slow case rtn = Object.create(_type) rtn.indirection-- } return rtn } /** * Coerces a "type" object from a String or an actual "type" object. String values * are looked up from the `ref.types` Object. So: * * * `"int"` gets coerced into `ref.types.int`. * * `"int *"` gets translated into `ref.refType(ref.types.int)` * * `ref.types.int` gets translated into `ref.types.int` (returns itself) * * Throws an Error if no valid "type" object could be determined. Most `ref` * functions use this function under the hood, so anywhere a "type" object is * expected, a String may be passed as well, including simply setting the * `buffer.type` property. * * ``` * var type = ref.coerceType('int **'); * * console.log(type.indirection); * 3 * ``` * * @param {Object|String} type The "type" Object or String to coerce. * @return {Object} A "type" object */ exports.coerceType = function coerceType (type) { var rtn = type if (typeof rtn === 'string') { rtn = exports.types[type] if (rtn) return rtn // strip whitespace rtn = type.replace(/\s+/g, '').toLowerCase() if (rtn === 'pointer') { // legacy "pointer" being used :( rtn = exports.refType(exports.types.void) // void * } else if (rtn === 'string') { rtn = exports.types.CString // special char * type } else { var refCount = 0 rtn = rtn.replace(/\*/g, function () { refCount++ return '' }) // allow string names to be passed in rtn = exports.types[rtn] if (refCount > 0) { if (!(rtn && 'size' in rtn && 'indirection' in rtn)) { throw new TypeError('could not determine a proper "type" from: ' + JSON.stringify(type)) } for (var i = 0; i < refCount; i++) { rtn = exports.refType(rtn) } } } } if (!(rtn && 'size' in rtn && 'indirection' in rtn)) { throw new TypeError('could not determine a proper "type" from: ' + JSON.stringify(type)) } return rtn } /** * Returns the "type" property of the given Buffer. * Creates a default type for the buffer when none exists. * * @param {Buffer} buffer The Buffer instance to get the "type" object from. * @return {Object} The "type" object from the given Buffer. */ exports.getType = function getType (buffer) { if (!buffer.type) { debug('WARN: no "type" found on buffer, setting default "type"', buffer) buffer.type = {} buffer.type.size = buffer.length buffer.type.indirection = 1 buffer.type.get = function get () { throw new Error('unknown "type"; cannot get()') } buffer.type.set = function set () { throw new Error('unknown "type"; cannot set()') } } return exports.coerceType(buffer.type) } /** * Calls the `get()` function of the Buffer's current "type" (or the * passed in _type_ if present) at the given _offset_. * * This function handles checking the "indirection" level and returning a * proper "dereferenced" Bufffer instance when necessary. * * @param {Buffer} buffer The Buffer instance to read from. * @param {Number} offset (optional) The offset on the Buffer to start reading from. Defaults to 0. * @param {Object|String} type (optional) The "type" object to use when reading. Defaults to calling `getType()` on the buffer. * @return {?} Whatever value the "type" used when reading returns. */ exports.get = function get (buffer, offset, type) { if (!offset) { offset = 0 } if (type) { type = exports.coerceType(type) } else { type = exports.getType(buffer) } debug('get(): (offset: %d)', offset, buffer) assert(type.indirection > 0, '"indirection" level must be at least 1') if (type.indirection === 1) { // need to check "type" return type.get(buffer, offset) } else { // need to create a deref'd Buffer var size = type.indirection === 2 ? type.size : exports.sizeof.pointer var reference = exports.readPointer(buffer, offset, size) reference.type = exports.derefType(type) return reference } } /** * Calls the `set()` function of the Buffer's current "type" (or the * passed in _type_ if present) at the given _offset_. * * This function handles checking the "indirection" level writing a pointer rather * than calling the `set()` function if the indirection is greater than 1. * * @param {Buffer} buffer The Buffer instance to write to. * @param {Number} offset The offset on the Buffer to start writing to. * @param {?} value The value to write to the Buffer instance. * @param {Object|String} type (optional) The "type" object to use when reading. Defaults to calling `getType()` on the buffer. */ exports.set = function set (buffer, offset, value, type) { if (!offset) { offset = 0 } if (type) { type = exports.coerceType(type) } else { type = exports.getType(buffer) } debug('set(): (offset: %d)', offset, buffer, value) assert(type.indirection >= 1, '"indirection" level must be at least 1') if (type.indirection === 1) { type.set(buffer, offset, value) } else { exports.writePointer(buffer, offset, value) } } /** * Returns a new Buffer instance big enough to hold `type`, * with the given `value` written to it. * * ``` js * var intBuf = ref.alloc(ref.types.int) * var int_with_4 = ref.alloc(ref.types.int, 4) * ``` * * @param {Object|String} type The "type" object to allocate. Strings get coerced first. * @param {?} value (optional) The initial value set on the returned Buffer, using _type_'s `set()` function. * @return {Buffer} A new Buffer instance with it's `type` set to "type", and (optionally) "value" written to it. */ exports.alloc = function alloc (_type, value) { var type = exports.coerceType(_type) debug('allocating Buffer for type with "size"', type.size) var size if (type.indirection === 1) { size = type.size } else { size = exports.sizeof.pointer } var buffer = new Buffer(size) buffer.type = type if (arguments.length >= 2) { debug('setting value on allocated buffer', value) exports.set(buffer, 0, value, type) } return buffer } /** * Returns a new `Buffer` instance with the given String written to it with the * given encoding (defaults to __'utf8'__). The buffer is 1 byte longer than the * string itself, and is NUL terminated. * * ``` * var buf = ref.allocCString('hello world'); * * console.log(buf.toString()); * 'hello world\u0000' * ``` * * @param {String} string The JavaScript string to be converted to a C string. * @param {String} encoding (optional) The encoding to use for the C string. Defaults to __'utf8'__. * @return {Buffer} The new `Buffer` instance with the specified String wrtten to it, and a trailing NUL byte. */ exports.allocCString = function allocCString (string, encoding) { if (null == string || (Buffer.isBuffer(string) && exports.isNull(string))) { return exports.NULL } var size = Buffer.byteLength(string, encoding) + 1 var buffer = new Buffer(size) exports.writeCString(buffer, 0, string, encoding) buffer.type = charPtrType return buffer } /** * Writes the given string as a C String (NULL terminated) to the given buffer * at the given offset. "encoding" is optional and defaults to __'utf8'__. * * Unlike `readCString()`, this function requires the buffer to actually have the * proper length. * * @param {Buffer} buffer The Buffer instance to write to. * @param {Number} offset The offset of the buffer to begin writing at. * @param {String} string The JavaScript String to write that will be written to the buffer. * @param {String} encoding (optional) The encoding to read the C string as. Defaults to __'utf8'__. */ exports.writeCString = function writeCString (buffer, offset, string, encoding) { assert(Buffer.isBuffer(buffer), 'expected a Buffer as the first argument') assert.equal('string', typeof string, 'expected a "string" as the third argument') if (!offset) { offset = 0 } if (!encoding) { encoding = 'utf8' } var size = buffer.length - offset var len = buffer.write(string, offset, size, encoding) buffer.writeUInt8(0, offset + len) // NUL terminate } exports['readInt64' + exports.endianness] = exports.readInt64 exports['readUInt64' + exports.endianness] = exports.readUInt64 exports['writeInt64' + exports.endianness] = exports.writeInt64 exports['writeUInt64' + exports.endianness] = exports.writeUInt64 var opposite = exports.endianness == 'LE' ? 'BE' : 'LE' var int64temp = new Buffer(exports.sizeof.int64) var uint64temp = new Buffer(exports.sizeof.uint64) exports['readInt64' + opposite] = function (buffer, offset) { for (var i = 0; i < exports.sizeof.int64; i++) { int64temp[i] = buffer[offset + exports.sizeof.int64 - i - 1] } return exports.readInt64(int64temp, 0) } exports['readUInt64' + opposite] = function (buffer, offset) { for (var i = 0; i < exports.sizeof.uint64; i++) { uint64temp[i] = buffer[offset + exports.sizeof.uint64 - i - 1] } return exports.readUInt64(uint64temp, 0) } exports['writeInt64' + opposite] = function (buffer, offset, value) { exports.writeInt64(int64temp, 0, value) for (var i = 0; i < exports.sizeof.int64; i++) { buffer[offset + i] = int64temp[exports.sizeof.int64 - i - 1] } } exports['writeUInt64' + opposite] = function (buffer, offset, value) { exports.writeUInt64(uint64temp, 0, value) for (var i = 0; i < exports.sizeof.uint64; i++) { buffer[offset + i] = uint64temp[exports.sizeof.uint64 - i - 1] } } /** * `ref()` accepts a Buffer instance and returns a new Buffer * instance that is "pointer" sized and has its data pointing to the given * Buffer instance. Essentially the created Buffer is a "reference" to the * original pointer, equivalent to the following C code: * * ``` c * char *buf = buffer; * char **ref = &buf; * ``` * * @param {Buffer} buffer A Buffer instance to create a reference to. * @return {Buffer} A new Buffer instance pointing to _buffer_. */ exports.ref = function ref (buffer) { debug('creating a reference to buffer', buffer) var type = exports.refType(exports.getType(buffer)) return exports.alloc(type, buffer) } /** * Accepts a Buffer instance and attempts to "dereference" it. * That is, first it checks the `indirection` count of _buffer_'s "type", and if * it's greater than __1__ then it merely returns another Buffer, but with one * level less `indirection`. * * When _buffer_'s indirection is at __1__, then it checks for `buffer.type` * which should be an Object with its own `get()` function. * * ``` * var buf = ref.alloc('int', 6); * * var val = ref.deref(buf); * console.log(val); * 6 * ``` * * * @param {Buffer} buffer A Buffer instance to dereference. * @return {?} The returned value after dereferencing _buffer_. */ exports.deref = function deref (buffer) { debug('dereferencing buffer', buffer) return exports.get(buffer) } /** * Attaches _object_ to _buffer_ such that it prevents _object_ from being garbage * collected until _buffer_ does. * * @param {Buffer} buffer A Buffer instance to attach _object_ to. * @param {Object|Buffer} object An Object or Buffer to prevent from being garbage collected until _buffer_ does. * @api private */ exports._attach = function _attach (buf, obj) { if (!buf._refs) { buf._refs = [] } buf._refs.push(obj) } /** * Same as `ref.writeObject()`, except that this version does not _attach_ the * Object to the Buffer, which is potentially unsafe if the garbage collector * runs. * * @param {Buffer} buffer A Buffer instance to write _object_ to. * @param {Number} offset The offset on the Buffer to start writing at. * @param {Object} object The Object to be written into _buffer_. * @api private */ exports._writeObject = exports.writeObject /** * Writes a pointer to _object_ into _buffer_ at the specified _offset. * * This function "attaches" _object_ to _buffer_ to prevent it from being garbage * collected. * * ``` * var buf = ref.alloc('Object'); * ref.writeObject(buf, 0, { foo: 'bar' }); * * ``` * * @param {Buffer} buffer A Buffer instance to write _object_ to. * @param {Number} offset The offset on the Buffer to start writing at. * @param {Object} object The Object to be written into _buffer_. */ exports.writeObject = function writeObject (buf, offset, obj, persistent) { debug('writing Object to buffer', buf, offset, obj, persistent) exports._writeObject(buf, offset, obj, persistent) exports._attach(buf, obj) } /** * Same as `ref.writePointer()`, except that this version does not attach * _pointer_ to _buffer_, which is potentially unsafe if the garbage collector * runs. * * @param {Buffer} buffer A Buffer instance to write _pointer to. * @param {Number} offset The offset on the Buffer to start writing at. * @param {Buffer} pointer The Buffer instance whose memory address will be written to _buffer_. * @api private */ exports._writePointer = exports.writePointer /** * Writes the memory address of _pointer_ to _buffer_ at the specified _offset_. * * This function "attaches" _object_ to _buffer_ to prevent it from being garbage * collected. * * ``` * var someBuffer = new Buffer('whatever'); * var buf = ref.alloc('pointer'); * ref.writePointer(buf, 0, someBuffer); * ``` * * @param {Buffer} buffer A Buffer instance to write _pointer to. * @param {Number} offset The offset on the Buffer to start writing at. * @param {Buffer} pointer The Buffer instance whose memory address will be written to _buffer_. */ exports.writePointer = function writePointer (buf, offset, ptr) { debug('writing pointer to buffer', buf, offset, ptr) exports._writePointer(buf, offset, ptr) exports._attach(buf, ptr) } /** * Same as `ref.reinterpret()`, except that this version does not attach * _buffer_ to the returned Buffer, which is potentially unsafe if the * garbage collector runs. * * @param {Buffer} buffer A Buffer instance to base the returned Buffer off of. * @param {Number} size The `length` property of the returned Buffer. * @param {Number} offset The offset of the Buffer to begin from. * @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and the requested _size_. * @api private */ exports._reinterpret = exports.reinterpret /** * Returns a new Buffer instance with the specified _size_, with the same memory * address as _buffer_. * * This function "attaches" _buffer_ to the returned Buffer to prevent it from * being garbage collected. * * @param {Buffer} buffer A Buffer instance to base the returned Buffer off of. * @param {Number} size The `length` property of the returned Buffer. * @param {Number} offset The offset of the Buffer to begin from. * @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and the requested _size_. */ exports.reinterpret = function reinterpret (buffer, size, offset) { debug('reinterpreting buffer to "%d" bytes', size) var rtn = exports._reinterpret(buffer, size, offset || 0) exports._attach(rtn, buffer) return rtn } /** * Same as `ref.reinterpretUntilZeros()`, except that this version does not * attach _buffer_ to the returned Buffer, which is potentially unsafe if the * garbage collector runs. * * @param {Buffer} buffer A Buffer instance to base the returned Buffer off of. * @param {Number} size The number of sequential, aligned `NULL` bytes that are required to terminate the buffer. * @param {Number} offset The offset of the Buffer to begin from. * @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and a variable `length` that is terminated by _size_ NUL bytes. * @api private */ exports._reinterpretUntilZeros = exports.reinterpretUntilZeros /** * Accepts a `Buffer` instance and a number of `NULL` bytes to read from the * pointer. This function will scan past the boundary of the Buffer's `length` * until it finds `size` number of aligned `NULL` bytes. * * This is useful for finding the end of NUL-termintated array or C string. For * example, the `readCString()` function _could_ be implemented like: * * ``` * function readCString (buf) { * return ref.reinterpretUntilZeros(buf, 1).toString('utf8') * } * ``` * * This function "attaches" _buffer_ to the returned Buffer to prevent it from * being garbage collected. * * @param {Buffer} buffer A Buffer instance to base the returned Buffer off of. * @param {Number} size The number of sequential, aligned `NULL` bytes are required to terminate the buffer. * @param {Number} offset The offset of the Buffer to begin from. * @return {Buffer} A new Buffer instance with the same memory address as _buffer_, and a variable `length` that is terminated by _size_ NUL bytes. */ exports.reinterpretUntilZeros = function reinterpretUntilZeros (buffer, size, offset) { debug('reinterpreting buffer to until "%d" NULL (0) bytes are found', size) var rtn = exports._reinterpretUntilZeros(buffer, size, offset || 0) exports._attach(rtn, buffer) return rtn } // the built-in "types" var types = exports.types = {} /** * The `void` type. * * @section types */ types.void = { size: 0 , indirection: 1 , get: function get (buf, offset) { debug('getting `void` type (returns `null`)') return null } , set: function set (buf, offset, val) { debug('setting `void` type (no-op)') } } /** * The `int8` type. */ types.int8 = { size: exports.sizeof.int8 , indirection: 1 , get: function get (buf, offset) { return buf.readInt8(offset || 0) } , set: function set (buf, offset, val) { if (typeof val === 'string') { val = val.charCodeAt(0) } return buf.writeInt8(val, offset || 0) } } /** * The `uint8` type. */ types.uint8 = { size: exports.sizeof.uint8 , indirection: 1 , get: function get (buf, offset) { return buf.readUInt8(offset || 0) } , set: function set (buf, offset, val) { if (typeof val === 'string') { val = val.charCodeAt(0) } return buf.writeUInt8(val, offset || 0) } } /** * The `int16` type. */ types.int16 = { size: exports.sizeof.int16 , indirection: 1 , get: function get (buf, offset) { return buf['readInt16' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeInt16' + exports.endianness](val, offset || 0) } } /** * The `uint16` type. */ types.uint16 = { size: exports.sizeof.uint16 , indirection: 1 , get: function get (buf, offset) { return buf['readUInt16' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeUInt16' + exports.endianness](val, offset || 0) } } /** * The `int32` type. */ types.int32 = { size: exports.sizeof.int32 , indirection: 1 , get: function get (buf, offset) { return buf['readInt32' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeInt32' + exports.endianness](val, offset || 0) } } /** * The `uint32` type. */ types.uint32 = { size: exports.sizeof.uint32 , indirection: 1 , get: function get (buf, offset) { return buf['readUInt32' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeUInt32' + exports.endianness](val, offset || 0) } } /** * The `int64` type. */ types.int64 = { size: exports.sizeof.int64 , indirection: 1 , get: function get (buf, offset) { return buf['readInt64' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeInt64' + exports.endianness](val, offset || 0) } } /** * The `uint64` type. */ types.uint64 = { size: exports.sizeof.uint64 , indirection: 1 , get: function get (buf, offset) { return buf['readUInt64' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeUInt64' + exports.endianness](val, offset || 0) } } /** * The `float` type. */ types.float = { size: exports.sizeof.float , indirection: 1 , get: function get (buf, offset) { return buf['readFloat' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeFloat' + exports.endianness](val, offset || 0) } } /** * The `double` type. */ types.double = { size: exports.sizeof.double , indirection: 1 , get: function get (buf, offset) { return buf['readDouble' + exports.endianness](offset || 0) } , set: function set (buf, offset, val) { return buf['writeDouble' + exports.endianness](val, offset || 0) } } /** * The `Object` type. This can be used to read/write regular JS Objects * into raw memory. */ types.Object = { size: exports.sizeof.Object , indirection: 1 , get: function get (buf, offset) { return buf.readObject(offset || 0) } , set: function set (buf, offset, val) { return buf.writeObject(val, offset || 0) } } /** * The `CString` (a.k.a `"string"`) type. * * CStrings are a kind of weird thing. We say it's `sizeof(char *)`, and * `indirection` level of 1, which means that we have to return a Buffer that * is pointer sized, and points to a some utf8 string data, so we have to create * a 2nd "in-between" buffer. */ types.CString = { size: exports.sizeof.pointer , alignment: exports.alignof.pointer , indirection: 1 , get: function get (buf, offset) { var _buf = exports.readPointer(buf, offset) if (exports.isNull(_buf)) { return null } return exports.readCString(_buf, 0) } , set: function set (buf, offset, val) { var _buf if (Buffer.isBuffer(val)) { _buf = val } else { // assume string _buf = exports.allocCString(val) } return exports.writePointer(buf, offset, _buf) } } // alias Utf8String var utfstringwarned = false Object.defineProperty(types, 'Utf8String', { enumerable: false , configurable: true , get: function () { if (!utfstringwarned) { utfstringwarned = true console.error('"Utf8String" type is deprecated, use "CString" instead') } return types.CString } }) /** * The `bool` type. * * Wrapper type around `types.uint8` that accepts/returns `true` or * `false` Boolean JavaScript values. * * @name bool * */ /** * The `byte` type. * * @name byte */ /** * The `char` type. * * @name char */ /** * The `uchar` type. * * @name uchar */ /** * The `short` type. * * @name short */ /** * The `ushort` type. * * @name ushort */ /** * The `int` type. * * @name int */ /** * The `uint` type. * * @name uint */ /** * The `long` type. * * @name long */ /** * The `ulong` type. * * @name ulong */ /** * The `longlong` type. * * @name longlong */ /** * The `ulonglong` type. * * @name ulonglong */ /** * The `size_t` type. * * @name size_t */ // "typedef"s for the variable-sized types ;[ 'bool', 'byte', 'char', 'uchar', 'short', 'ushort', 'int', 'uint', 'long' , 'ulong', 'longlong', 'ulonglong', 'size_t' ].forEach(function (name) { var unsigned = name === 'bool' || name === 'byte' || name === 'size_t' || name[0] === 'u' var size = exports.sizeof[name] assert(size >= 1 && size <= 8) var typeName = 'int' + (size * 8) if (unsigned) { typeName = 'u' + typeName } var type = exports.types[typeName] assert(type) exports.types[name] = Object.create(type) }) // set the "alignment" property on the built-in types Object.keys(exports.alignof).forEach(function (name) { if (name === 'pointer') return exports.types[name].alignment = exports.alignof[name] assert(exports.types[name].alignment > 0) }) // make the `bool` type work with JS true/false values exports.types.bool.get = (function (_get) { return function get (buf, offset) { return _get(buf, offset) ? true : false } })(exports.types.bool.get) exports.types.bool.set = (function (_set) { return function set (buf, offset, val) { if (typeof val !== 'number') { val = val ? 1 : 0 } return _set(buf, offset, val) } })(exports.types.bool.set) /*! * Set the `name` property of the types. Used for debugging... */ Object.keys(exports.types).forEach(function (name) { exports.types[name].name = name }) /*! * This `char *` type is used by "allocCString()" above. */ var charPtrType = exports.refType(exports.types.char) /*! * Set the `type` property of the `NULL` pointer Buffer object. */ exports.NULL.type = exports.types.void /** * `NULL_POINTER` is a pointer-sized `Buffer` instance pointing to `NULL`. * Conceptually, it's equivalent to the following C code: * * ``` c * char *null_pointer; * null_pointer = NULL; * ``` * * @type Buffer */ exports.NULL_POINTER = exports.ref(exports.NULL) /** * All these '...' comment blocks below are for the documentation generator. * * @section buffer */ Buffer.prototype.address = function address () { return exports.address(this, 0) } /** * ... */ Buffer.prototype.hexAddress = function hexAddress () { return exports.hexAddress(this, 0) } /** * ... */ Buffer.prototype.isNull = function isNull () { return exports.isNull(this, 0) } /** * ... */ Buffer.prototype.ref = function ref () { return exports.ref(this) } /** * ... */ Buffer.prototype.deref = function deref () { return exports.deref(this) } /** * ... */ Buffer.prototype.readObject = function readObject (offset) { return exports.readObject(this, offset) } /** * ... */ Buffer.prototype.writeObject = function writeObject (obj, offset) { return exports.writeObject(this, offset, obj) } /** * ... */ Buffer.prototype.readPointer = function readPointer (offset, size) { return exports.readPointer(this, offset, size) } /** * ... */ Buffer.prototype.writePointer = function writePointer (ptr, offset) { return exports.writePointer(this, offset, ptr) } /** * ... */ Buffer.prototype.readCString = function readCString (offset) { return exports.readCString(this, offset) } /** * ... */ Buffer.prototype.writeCString = function writeCString (string, offset, encoding) { return exports.writeCString(this, offset, string, encoding) } /** * ... */ Buffer.prototype.readInt64BE = function readInt64BE (offset) { return exports.readInt64BE(this, offset) } /** * ... */ Buffer.prototype.writeInt64BE = function writeInt64BE (val, offset) { return exports.writeInt64BE(this, offset, val) } /** * ... */ Buffer.prototype.readUInt64BE = function readUInt64BE (offset) { return exports.readUInt64BE(this, offset) } /** * ... */ Buffer.prototype.writeUInt64BE = function writeUInt64BE (val, offset) { return exports.writeUInt64BE(this, offset, val) } /** * ... */ Buffer.prototype.readInt64LE = function readInt64LE (offset) { return exports.readInt64LE(this, offset) } /** * ... */ Buffer.prototype.writeInt64LE = function writeInt64LE (val, offset) { return exports.writeInt64LE(this, offset, val) } /** * ... */ Buffer.prototype.readUInt64LE = function readUInt64LE (offset) { return exports.readUInt64LE(this, offset) } /** * ... */ Buffer.prototype.writeUInt64LE = function writeUInt64LE (val, offset) { return exports.writeUInt64LE(this, offset, val) } /** * ... */ Buffer.prototype.reinterpret = function reinterpret (size, offset) { return exports.reinterpret(this, size, offset) } /** * ... */ Buffer.prototype.reinterpretUntilZeros = function reinterpretUntilZeros (size, offset) { return exports.reinterpretUntilZeros(this, size, offset) } /** * `ref` overwrites the default `Buffer#inspect()` function to include the * hex-encoded memory address of the Buffer instance when invoked. * * This is simply a nice-to-have. * * **Before**: * * ``` js * console.log(new Buffer('ref')); * <Buffer 72 65 66> * ``` * * **After**: * * ``` js * console.log(new Buffer('ref')); * <Buffer@0x103015490 72 65 66> * ``` */ Buffer.prototype.inspect = overwriteInspect(Buffer.prototype.inspect) // does SlowBuffer inherit from Buffer? (node >= v0.7.9) if (!(exports.NULL instanceof Buffer)) { debug('extending SlowBuffer\'s prototype since it doesn\'t inherit from Buffer.prototype') /*! * SlowBuffer convenience methods. */ var SlowBuffer = require('buffer').SlowBuffer SlowBuffer.prototype.address = Buffer.prototype.address SlowBuffer.prototype.hexAddress = Buffer.prototype.hexAddress SlowBuffer.prototype.isNull = Buffer.prototype.isNull SlowBuffer.prototype.ref = Buffer.prototype.ref SlowBuffer.prototype.deref = Buffer.prototype.deref SlowBuffer.prototype.readObject = Buffer.prototype.readObject SlowBuffer.prototype.writeObject = Buffer.prototype.writeObject SlowBuffer.prototype.readPointer = Buffer.prototype.readPointer SlowBuffer.prototype.writePointer = Buffer.prototype.writePointer SlowBuffer.prototype.readCString = Buffer.prototype.readCString SlowBuffer.prototype.writeCString = Buffer.prototype.writeCString SlowBuffer.prototype.reinterpret = Buffer.prototype.reinterpret SlowBuffer.prototype.reinterpretUntilZeros = Buffer.prototype.reinterpretUntilZeros SlowBuffer.prototype.readInt64BE = Buffer.prototype.readInt64BE SlowBuffer.prototype.writeInt64BE = Buffer.prototype.writeInt64BE SlowBuffer.prototype.readUInt64BE = Buffer.prototype.readUInt64BE SlowBuffer.prototype.writeUInt64BE = Buffer.prototype.writeUInt64BE SlowBuffer.prototype.readInt64LE = Buffer.prototype.readInt64LE SlowBuffer.prototype.writeInt64LE = Buffer.prototype.writeInt64LE SlowBuffer.prototype.readUInt64LE = Buffer.prototype.readUInt64LE SlowBuffer.prototype.writeUInt64LE = Buffer.prototype.writeUInt64LE SlowBuffer.prototype.inspect = overwriteInspect(SlowBuffer.prototype.inspect) } function overwriteInspect (inspect) { if (inspect.name === 'refinspect') { return inspect } else { return function refinspect () { var v = inspect.apply(this, arguments) return v.replace('Buffer', 'Buffer@0x' + this.hexAddress()) } } }
import EPUBComponent from './views/EpubRendererIndex'; import ContentRendererModule from 'content_renderer_module'; class DocumentEPUBModule extends ContentRendererModule { get rendererComponent() { EPUBComponent.contentModule = this; return EPUBComponent; } } const documentEPUBModule = new DocumentEPUBModule(); export { documentEPUBModule as default };
import dbg from 'debug'; const debug = dbg('slackin'); export default function log(slack, silent){ // keep track of elapsed time let last; out('fetching'); // attach events slack.on('ready', () => out('ready')); slack.on('retry', () => out('retrying')); slack.on('fetch', () => { last = new Date; out('fetching'); }); slack.on('data', online); // log online users function online(){ out('online %d, total %d %s', slack.users.active, slack.users.total, last ? `(+${new Date - last}ms)` : ''); } // print out errors and warnings if (!silent) { slack.on('error', (err) => { console.error('%s – ' + err.stack, new Date); }); slack.on('ready', () => { if (!slack.org.logo && !silent) { console.warn('\u001b[92mWARN: no logo configured\u001b[39m'); } }); } function out(...args){ if (args) { args[0] = `${new Date} – ${args[0]}`; } if (silent) return debug(...args); console.log(...args); } }
const { quotient } = require("../lib"); describe("quotient", () => { test("divides 1 / 2 to equal .5", () => { expect(quotient(1, 2)).toBe(.5); }); test("divides 12 / 4 to equal 3", () => { expect(quotient(12, 4)).toBe(3); }); });
/** * @license Highcharts JS v7.1.2 (2019-06-04) * * Tilemap module * * (c) 2010-2019 Highsoft AS * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/tilemap', ['highcharts', 'highcharts/modules/map'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'modules/tilemap.src.js', [_modules['parts/Globals.js']], function (H) { /* * * Tilemaps module * * (c) 2010-2017 Highsoft AS * Author: Øystein Moseng * * License: www.highcharts.com/license */ /** * @typedef {"circle"|"diamond"|"hexagon"|"square"} Highcharts.TilemapShapeValue */ var seriesType = H.seriesType, pick = H.pick, // Utility func to get the middle number of 3 between = function (x, a, b) { return Math.min(Math.max(a, x), b); }, // Utility func to get padding definition from tile size division tilePaddingFromTileSize = function (series, xDiv, yDiv) { var options = series.options; return { xPad: (options.colsize || 1) / -xDiv, yPad: (options.rowsize || 1) / -yDiv }; }; // Map of shape types. H.tileShapeTypes = { // Hexagon shape type. hexagon: { alignDataLabel: H.seriesTypes.scatter.prototype.alignDataLabel, getSeriesPadding: function (series) { return tilePaddingFromTileSize(series, 3, 2); }, haloPath: function (size) { if (!size) { return []; } var hexagon = this.tileEdges; return [ 'M', hexagon.x2 - size, hexagon.y1 + size, 'L', hexagon.x3 + size, hexagon.y1 + size, hexagon.x4 + size * 1.5, hexagon.y2, hexagon.x3 + size, hexagon.y3 - size, hexagon.x2 - size, hexagon.y3 - size, hexagon.x1 - size * 1.5, hexagon.y2, 'Z' ]; }, translate: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, xPad = (options.colsize || 1) / 3, yPad = (options.rowsize || 1) / 2, yShift; series.generatePoints(); series.points.forEach(function (point) { var x1 = between( Math.floor( xAxis.len - xAxis.translate(point.x - xPad * 2, 0, 1, 0, 1) ), -xAxis.len, 2 * xAxis.len ), x2 = between( Math.floor( xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1) ), -xAxis.len, 2 * xAxis.len ), x3 = between( Math.floor( xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1) ), -xAxis.len, 2 * xAxis.len ), x4 = between( Math.floor( xAxis.len - xAxis.translate(point.x + xPad * 2, 0, 1, 0, 1) ), -xAxis.len, 2 * xAxis.len ), y1 = between( Math.floor(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len ), y2 = between( Math.floor(yAxis.translate(point.y, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len ), y3 = between( Math.floor(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len ), pointPadding = pick(point.pointPadding, seriesPointPadding), // We calculate the point padding of the midpoints to // preserve the angles of the shape. midPointPadding = pointPadding * Math.abs(x2 - x1) / Math.abs(y3 - y2), xMidPadding = xAxis.reversed ? -midPointPadding : midPointPadding, xPointPadding = xAxis.reversed ? -pointPadding : pointPadding, yPointPadding = yAxis.reversed ? -pointPadding : pointPadding; // Shift y-values for every second grid column if (point.x % 2) { yShift = yShift || Math.round(Math.abs(y3 - y1) / 2) * // We have to reverse the shift for reversed y-axes (yAxis.reversed ? -1 : 1); y1 += yShift; y2 += yShift; y3 += yShift; } // Set plotX and plotY for use in K-D-Tree and more point.plotX = point.clientX = (x2 + x3) / 2; point.plotY = y2; // Apply point padding to translated coordinates x1 += xMidPadding + xPointPadding; x2 += xPointPadding; x3 -= xPointPadding; x4 -= xMidPadding + xPointPadding; y1 -= yPointPadding; y3 += yPointPadding; // Store points for halo creation point.tileEdges = { x1: x1, x2: x2, x3: x3, x4: x4, y1: y1, y2: y2, y3: y3 }; // Finally set the shape for this point point.shapeType = 'path'; point.shapeArgs = { d: [ 'M', x2, y1, 'L', x3, y1, x4, y2, x3, y3, x2, y3, x1, y2, 'Z' ] }; }); series.translateColors(); } }, // Diamond shape type. diamond: { alignDataLabel: H.seriesTypes.scatter.prototype.alignDataLabel, getSeriesPadding: function (series) { return tilePaddingFromTileSize(series, 2, 2); }, haloPath: function (size) { if (!size) { return []; } var diamond = this.tileEdges; return [ 'M', diamond.x2, diamond.y1 + size, 'L', diamond.x3 + size, diamond.y2, diamond.x2, diamond.y3 - size, diamond.x1 - size, diamond.y2, 'Z' ]; }, translate: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, xPad = (options.colsize || 1), yPad = (options.rowsize || 1) / 2, yShift; series.generatePoints(); series.points.forEach(function (point) { var x1 = between( Math.round( xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 0) ), -xAxis.len, 2 * xAxis.len ), x2 = between( Math.round( xAxis.len - xAxis.translate(point.x, 0, 1, 0, 0) ), -xAxis.len, 2 * xAxis.len ), x3 = between( Math.round( xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 0) ), -xAxis.len, 2 * xAxis.len ), y1 = between( Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len ), y2 = between( Math.round(yAxis.translate(point.y, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len ), y3 = between( Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len ), pointPadding = pick(point.pointPadding, seriesPointPadding), // We calculate the point padding of the midpoints to // preserve the angles of the shape. midPointPadding = pointPadding * Math.abs(x2 - x1) / Math.abs(y3 - y2), xPointPadding = xAxis.reversed ? -midPointPadding : midPointPadding, yPointPadding = yAxis.reversed ? -pointPadding : pointPadding; // Shift y-values for every second grid column // We have to reverse the shift for reversed y-axes if (point.x % 2) { yShift = Math.abs(y3 - y1) / 2 * (yAxis.reversed ? -1 : 1); y1 += yShift; y2 += yShift; y3 += yShift; } // Set plotX and plotY for use in K-D-Tree and more point.plotX = point.clientX = x2; point.plotY = y2; // Apply point padding to translated coordinates x1 += xPointPadding; x3 -= xPointPadding; y1 -= yPointPadding; y3 += yPointPadding; // Store points for halo creation point.tileEdges = { x1: x1, x2: x2, x3: x3, y1: y1, y2: y2, y3: y3 }; // Set this point's shape parameters point.shapeType = 'path'; point.shapeArgs = { d: [ 'M', x2, y1, 'L', x3, y2, x2, y3, x1, y2, 'Z' ] }; }); series.translateColors(); } }, // Circle shape type. circle: { alignDataLabel: H.seriesTypes.scatter.prototype.alignDataLabel, getSeriesPadding: function (series) { return tilePaddingFromTileSize(series, 2, 2); }, haloPath: function (size) { return H.seriesTypes.scatter.prototype.pointClass.prototype.haloPath .call( this, size + (size && this.radius) ); }, translate: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, seriesPointPadding = options.pointPadding || 0, yRadius = (options.rowsize || 1) / 2, colsize = (options.colsize || 1), colsizePx, yRadiusPx, xRadiusPx, radius, forceNextRadiusCompute = false; series.generatePoints(); series.points.forEach(function (point) { var x = between( Math.round( xAxis.len - xAxis.translate(point.x, 0, 1, 0, 0) ), -xAxis.len, 2 * xAxis.len ), y = between( Math.round(yAxis.translate(point.y, 0, 1, 0, 0)), -yAxis.len, 2 * yAxis.len ), pointPadding = seriesPointPadding, hasPerPointPadding = false; // If there is point padding defined on a single point, add it if (point.pointPadding !== undefined) { pointPadding = point.pointPadding; hasPerPointPadding = true; forceNextRadiusCompute = true; } // Find radius if not found already. // Use the smallest one (x vs y) to avoid overlap. // Note that the radius will be recomputed for each series. // Ideal (max) x radius is dependent on y radius: /* * (circle 2) * (circle 3) | yRadiusPx (circle 1) *-------| colsizePx The distance between circle 1 and 3 (and circle 2 and 3) is 2r, which is the hypotenuse of the triangle created by colsizePx and yRadiusPx. If the distance between circle 2 and circle 1 is less than 2r, we use half of that distance instead (yRadiusPx). */ if (!radius || forceNextRadiusCompute) { colsizePx = Math.abs( between( Math.floor( xAxis.len - xAxis.translate(point.x + colsize, 0, 1, 0, 0) ), -xAxis.len, 2 * xAxis.len ) - x ); yRadiusPx = Math.abs( between( Math.floor( yAxis.translate(point.y + yRadius, 0, 1, 0, 0) ), -yAxis.len, 2 * yAxis.len ) - y ); xRadiusPx = Math.floor( Math.sqrt( (colsizePx * colsizePx + yRadiusPx * yRadiusPx) ) / 2 ); radius = Math.min( colsizePx, xRadiusPx, yRadiusPx ) - pointPadding; // If we have per point padding we need to always compute // the radius for this point and the next. If we used to // have per point padding but don't anymore, don't force // compute next radius. if (forceNextRadiusCompute && !hasPerPointPadding) { forceNextRadiusCompute = false; } } // Shift y-values for every second grid column. // Note that we always use the optimal y axis radius for this. // Also note: We have to reverse the shift for reversed y-axes. if (point.x % 2) { y += yRadiusPx * (yAxis.reversed ? -1 : 1); } // Set plotX and plotY for use in K-D-Tree and more point.plotX = point.clientX = x; point.plotY = y; // Save radius for halo point.radius = radius; // Set this point's shape parameters point.shapeType = 'circle'; point.shapeArgs = { x: x, y: y, r: radius }; }); series.translateColors(); } }, // Square shape type. square: { alignDataLabel: H.seriesTypes.heatmap.prototype.alignDataLabel, translate: H.seriesTypes.heatmap.prototype.translate, getSeriesPadding: function () { }, haloPath: H.seriesTypes.heatmap.prototype.pointClass.prototype.haloPath } }; // Extension to add pixel padding for series. Uses getSeriesPixelPadding on each // series and adds the largest padding required. If no series has this function // defined, we add nothing. H.addEvent(H.Axis, 'afterSetAxisTranslation', function () { if (this.recomputingForTilemap) { return; } var axis = this, // Find which series' padding to use seriesPadding = axis.series .map(function (series) { return series.getSeriesPixelPadding && series.getSeriesPixelPadding(axis); }) .reduce(function (a, b) { return (a && a.padding) > (b && b.padding) ? a : b; }, undefined) || { padding: 0, axisLengthFactor: 1 }, lengthPadding = Math.round( seriesPadding.padding * seriesPadding.axisLengthFactor ); // Don't waste time on this if we're not adding extra padding if (seriesPadding.padding) { // Recompute translation with new axis length now (minus padding) axis.len -= lengthPadding; axis.recomputingForTilemap = true; axis.setAxisTranslation(); delete axis.recomputingForTilemap; axis.minPixelPadding += seriesPadding.padding; axis.len += lengthPadding; } }); /** * @private * @class * @name Highcharts.seriesTypes.tilemap * * @augments Highcharts.Series */ seriesType('tilemap', 'heatmap' /** * A tilemap series is a type of heatmap where the tile shapes are * configurable. * * @sample highcharts/demo/honeycomb-usa/ * Honeycomb tilemap, USA * @sample maps/plotoptions/honeycomb-brazil/ * Honeycomb tilemap, Brazil * @sample maps/plotoptions/honeycomb-china/ * Honeycomb tilemap, China * @sample maps/plotoptions/honeycomb-europe/ * Honeycomb tilemap, Europe * @sample maps/demo/circlemap-africa/ * Circlemap tilemap, Africa * @sample maps/demo/diamondmap * Diamondmap tilemap * * @extends plotOptions.heatmap * @since 6.0.0 * @excluding jitter, joinBy, shadow, allAreas, mapData, data * @product highcharts highmaps * @optionparent plotOptions.tilemap */ , { // Default options states: { hover: { halo: { enabled: true, size: 2, opacity: 0.5, attributes: { zIndex: 3 } } } }, /** * The padding between points in the tilemap. * * @sample maps/plotoptions/tilemap-pointpadding * Point padding on tiles */ pointPadding: 2, /** * The column size - how many X axis units each column in the tilemap * should span. Works as in [Heatmaps](#plotOptions.heatmap.colsize). * * @sample {highcharts} maps/demo/heatmap/ * One day * @sample {highmaps} maps/demo/heatmap/ * One day * * @type {number} * @default 1 * @product highcharts highmaps * @apioption plotOptions.tilemap.colsize */ /** * The row size - how many Y axis units each tilemap row should span. * Analogous to [colsize](#plotOptions.tilemap.colsize). * * @sample {highcharts} maps/demo/heatmap/ * 1 by default * @sample {highmaps} maps/demo/heatmap/ * 1 by default * * @type {number} * @default 1 * @product highcharts highmaps * @apioption plotOptions.tilemap.rowsize */ /** * The shape of the tiles in the tilemap. Possible values are `hexagon`, * `circle`, `diamond`, and `square`. * * @sample maps/demo/circlemap-africa * Circular tile shapes * @sample maps/demo/diamondmap * Diamond tile shapes * * @type {Highcharts.TilemapShapeValue} */ tileShape: 'hexagon' }, { // Prototype functions // Set tile shape object on series setOptions: function () { // Call original function var ret = H.seriesTypes.heatmap.prototype.setOptions.apply( this, Array.prototype.slice.call(arguments) ); this.tileShape = H.tileShapeTypes[ret.tileShape]; return ret; }, // Use the shape's defined data label alignment function alignDataLabel: function () { return this.tileShape.alignDataLabel.apply( this, Array.prototype.slice.call(arguments) ); }, // Get metrics for padding of axis for this series getSeriesPixelPadding: function (axis) { var isX = axis.isXAxis, padding = this.tileShape.getSeriesPadding(this), coord1, coord2; // If the shape type does not require padding, return no-op padding if (!padding) { return { padding: 0, axisLengthFactor: 1 }; } // Use translate to compute how far outside the points we // draw, and use this difference as padding. coord1 = Math.round( axis.translate( isX ? padding.xPad * 2 : padding.yPad, 0, 1, 0, 1 ) ); coord2 = Math.round( axis.translate( isX ? padding.xPad : 0, 0, 1, 0, 1 ) ); return { padding: Math.abs(coord1 - coord2) || 0, // Offset the yAxis length to compensate for shift. Setting the // length factor to 2 would add the same margin to max as min. // Now we only add a slight bit of the min margin to max, as we // don't actually draw outside the max bounds. For the xAxis we // draw outside on both sides so we add the same margin to min // and max. axisLengthFactor: isX ? 2 : 1.1 }; }, // Use translate from tileShape translate: function () { return this.tileShape.translate.apply( this, Array.prototype.slice.call(arguments) ); } }, H.extend({ /** * @private * @function Highcharts.Point#haloPath * * @return {Highcharts.SVGPathArray} */ haloPath: function () { return this.series.tileShape.haloPath.apply( this, Array.prototype.slice.call(arguments) ); } }, H.colorPointMixin)); /** * A `tilemap` series. If the [type](#series.tilemap.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.tilemap * @excluding allAreas, dataParser, dataURL, joinBy, mapData, marker, * pointRange, shadow, stack * @product highcharts highmaps * @apioption series.tilemap */ /** * An array of data points for the series. For the `tilemap` series * type, points can be given in the following ways: * * 1. An array of arrays with 3 or 2 values. In this case, the values correspond * to `x,y,value`. If the first value is a string, it is applied as the name * of the point, and the `x` value is inferred. The `x` value can also be * omitted, in which case the inner arrays should be of length 2\. Then the * `x` value is automatically calculated, either starting at 0 and * incremented by 1, or from `pointStart` and `pointInterval` given in the * series options. * ```js * data: [ * [0, 9, 7], * [1, 10, 4], * [2, 6, 3] * ] * ``` * * 2. An array of objects with named values. The objects are point configuration * objects as seen below. If the total number of data points exceeds the * series' [turboThreshold](#series.tilemap.turboThreshold), this option is * not available. * ```js * data: [{ * x: 1, * y: 3, * value: 10, * name: "Point2", * color: "#00FF00" * }, { * x: 1, * y: 7, * value: 10, * name: "Point1", * color: "#FF00FF" * }] * ``` * * Note that for some [tileShapes](#plotOptions.tilemap.tileShape) the grid * coordinates are offset. * * @sample maps/series/tilemap-gridoffset * Offset grid coordinates * @sample {highcharts} highcharts/series/data-array-of-arrays/ * Arrays of numeric x and y * @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/ * Arrays of datetime x and y * @sample {highcharts} highcharts/series/data-array-of-name-value/ * Arrays of point.name and y * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @type {Array<Array<(number|string),number>|Array<(number|string),number,number>|*>} * @extends series.heatmap.data * @excluding marker * @product highcharts highmaps * @apioption series.tilemap.data */ /** * The color of the point. In tilemaps the point color is rarely set * explicitly, as we use the color to denote the `value`. Options for * this are set in the [colorAxis](#colorAxis) configuration. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highcharts highmaps * @apioption series.tilemap.data.color */ /** * The x coordinate of the point. * * Note that for some [tileShapes](#plotOptions.tilemap.tileShape) the grid * coordinates are offset. * * @sample maps/series/tilemap-gridoffset * Offset grid coordinates * * @type {number} * @product highcharts highmaps * @apioption series.tilemap.data.x */ /** * The y coordinate of the point. * * Note that for some [tileShapes](#plotOptions.tilemap.tileShape) the grid * coordinates are offset. * * @sample maps/series/tilemap-gridoffset * Offset grid coordinates * * @type {number} * @product highcharts highmaps * @apioption series.tilemap.data.y */ }); _registerModule(_modules, 'masters/modules/tilemap.src.js', [], function () { }); }));
/* * Metro 4 Components Library v4.2.37 build 718 (https://metroui.org.ua) * Copyright 2019 Sergey Pimenov * Licensed under MIT */ (function( factory ) { if ( typeof define === 'function' && define.amd ) { define([ 'jquery' ], factory ); } else { factory( jQuery ); } }(function( jQuery ) { // Source: js/metro.js 'use strict'; var $ = jQuery; if (typeof jQuery === 'undefined') { throw new Error('Metro 4 requires jQuery!'); } if ('MutationObserver' in window === false) { throw new Error('Metro 4 requires MutationObserver!'); } var meta_init = $("meta[name='metro4:init']").attr("content"); var meta_locale = $("meta[name='metro4:locale']").attr("content"); var meta_week_start = $("meta[name='metro4:week_start']").attr("content"); var meta_date_format = $("meta[name='metro4:date_format']").attr("content"); var meta_date_format_input = $("meta[name='metro4:date_format_input']").attr("content"); var meta_animation_duration = $("meta[name='metro4:animation_duration']").attr("content"); var meta_callback_timeout = $("meta[name='metro4:callback_timeout']").attr("content"); var meta_timeout = $("meta[name='metro4:timeout']").attr("content"); var meta_scroll_multiple = $("meta[name='metro4:scroll_multiple']").attr("content"); var meta_cloak = $("meta[name='metro4:cloak']").attr("content"); //default or fade var meta_cloak_duration = $("meta[name='metro4:cloak_duration']").attr("content"); //100 if (window.METRO_INIT === undefined) { window.METRO_INIT = meta_init !== undefined ? JSON.parse(meta_init) : true; } if (window.METRO_DEBUG === undefined) {window.METRO_DEBUG = true;} if (window.METRO_WEEK_START === undefined) { window.METRO_WEEK_START = meta_week_start !== undefined ? parseInt(meta_week_start) : 0; } if (window.METRO_DATE_FORMAT === undefined) { window.METRO_DATE_FORMAT = meta_date_format !== undefined ? meta_date_format : "%Y-%m-%d"; } if (window.METRO_DATE_FORMAT_INPUT === undefined) { window.METRO_DATE_FORMAT_INPUT = meta_date_format_input !== undefined ? meta_date_format_input : "%Y-%m-%d"; } if (window.METRO_LOCALE === undefined) { window.METRO_LOCALE = meta_locale !== undefined ? meta_locale : 'en-US'; } if (window.METRO_ANIMATION_DURATION === undefined) { window.METRO_ANIMATION_DURATION = meta_animation_duration !== undefined ? parseInt(meta_animation_duration) : 300; } if (window.METRO_CALLBACK_TIMEOUT === undefined) { window.METRO_CALLBACK_TIMEOUT = meta_callback_timeout !== undefined ? parseInt(meta_callback_timeout) : 500; } if (window.METRO_TIMEOUT === undefined) { window.METRO_TIMEOUT = meta_timeout !== undefined ? parseInt(meta_timeout) : 2000; } if (window.METRO_SCROLL_MULTIPLE === undefined) { window.METRO_SCROLL_MULTIPLE = meta_scroll_multiple !== undefined ? parseInt(meta_scroll_multiple) : 20; } if (window.METRO_CLOAK_REMOVE === undefined) { window.METRO_CLOAK_REMOVE = meta_cloak !== undefined ? (""+meta_cloak).toLowerCase() : "fade"; } if (window.METRO_CLOAK_DURATION === undefined) { window.METRO_CLOAK_DURATION = meta_cloak_duration !== undefined ? parseInt(meta_cloak_duration) : 500; } if (window.METRO_HOTKEYS_FILTER_CONTENT_EDITABLE === undefined) {window.METRO_HOTKEYS_FILTER_CONTENT_EDITABLE = true;} if (window.METRO_HOTKEYS_FILTER_INPUT_ACCEPTING_ELEMENTS === undefined) {window.METRO_HOTKEYS_FILTER_INPUT_ACCEPTING_ELEMENTS = true;} if (window.METRO_HOTKEYS_FILTER_TEXT_INPUTS === undefined) {window.METRO_HOTKEYS_FILTER_TEXT_INPUTS = true;} if (window.METRO_HOTKEYS_BUBBLE_UP === undefined) {window.METRO_HOTKEYS_BUBBLE_UP = false;} if (window.METRO_THROWS === undefined) {window.METRO_THROWS = true;} window.METRO_MEDIA = []; if ( typeof Object.create !== 'function' ) { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } if (typeof Object.values !== 'function') { Object.values = function(obj) { return Object.keys(obj).map(function(e) { return obj[e] }); } } var isTouch = (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); var Metro = { version: "4.2.37", versionFull: "4.2.37.718 ", isTouchable: isTouch, fullScreenEnabled: document.fullscreenEnabled, sheet: null, controlsPosition: { INSIDE: "inside", OUTSIDE: "outside" }, groupMode: { ONE: "one", MULTI: "multi" }, aspectRatio: { HD: "hd", SD: "sd", CINEMA: "cinema" }, fullScreenMode: { WINDOW: "window", DESKTOP: "desktop" }, position: { TOP: "top", BOTTOM: "bottom", LEFT: "left", RIGHT: "right", TOP_RIGHT: "top-right", TOP_LEFT: "top-left", BOTTOM_LEFT: "bottom-left", BOTTOM_RIGHT: "bottom-right", LEFT_BOTTOM: "left-bottom", LEFT_TOP: "left-top", RIGHT_TOP: "right-top", RIGHT_BOTTOM: "right-bottom" }, popoverEvents: { CLICK: "click", HOVER: "hover", FOCUS: "focus" }, stepperView: { SQUARE: "square", CYCLE: "cycle", DIAMOND: "diamond" }, listView: { LIST: "list", CONTENT: "content", ICONS: "icons", ICONS_MEDIUM: "icons-medium", ICONS_LARGE: "icons-large", TILES: "tiles", TABLE: "table" }, events: { click: 'click.metro', start: isTouch ? 'touchstart.metro' : 'mousedown.metro', stop: isTouch ? 'touchend.metro' : 'mouseup.metro', move: isTouch ? 'touchmove.metro' : 'mousemove.metro', enter: isTouch ? 'touchstart.metro' : 'mouseenter.metro', leave: 'mouseleave.metro', focus: 'focus.metro', blur: 'blur.metro', resize: 'resize.metro', keyup: 'keyup.metro', keydown: 'keydown.metro', keypress: 'keypress.metro', dblclick: 'dblclick.metro', input: 'input.metro', change: 'change.metro', cut: 'cut.metro', paste: 'paste.metro', scroll: 'scroll.metro', scrollStart: 'scrollstart.metro', scrollStop: 'scrollstop.metro', mousewheel: 'mousewheel.metro', inputchange: "change.metro input.metro propertychange.metro cut.metro paste.metro copy.metro", dragstart: "dragstart.metro", dragend: "dragend.metro", dragenter: "dragenter.metro", dragover: "dragover.metro", dragleave: "dragleave.metro", drop: 'drop.metro', drag: 'drag.metro' }, keyCode: { BACKSPACE: 8, TAB: 9, ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, BREAK: 19, CAPS: 20, ESCAPE: 27, SPACE: 32, PAGEUP: 33, PAGEDOWN: 34, END: 35, HOME: 36, LEFT_ARROW: 37, UP_ARROW: 38, RIGHT_ARROW: 39, DOWN_ARROW: 40, COMMA: 188 }, media_queries: { FS: "(min-width: 0px)", XS: "(min-width: 360px)", SM: "(min-width: 576px)", MD: "(min-width: 768px)", LG: "(min-width: 992px)", XL: "(min-width: 1200px)", XXL: "(min-width: 1452px)" }, media_sizes: { FS: 0, XS: 360, SM: 576, LD: 640, MD: 768, LG: 992, XL: 1200, XXL: 1452 }, media_mode: { FS: "fs", XS: "xs", SM: "sm", MD: "md", LG: "lg", XL: "xl", XXL: "xxl" }, media_modes: ["fs","xs","sm","md","lg","xl","xxl"], actions: { REMOVE: 1, HIDE: 2 }, hotkeys: [], about: function(f){ console.log("Metro 4 - v" + (f === true ? this.versionFull : this.version)); }, aboutDlg: function(f){ alert("Metro 4 - v" + (f === true ? this.versionFull : this.version)); }, ver: function(f){ return (f === true ? this.versionFull : this.version); }, observe: function(){ 'use strict'; var observer, observerCallback; var observerConfig = { childList: true, attributes: true, subtree: true }; observerCallback = function(mutations){ mutations.map(function(mutation){ if (mutation.type === 'attributes' && mutation.attributeName !== "data-role") { var element = $(mutation.target); var mc = element.data('metroComponent'); if (mc !== undefined) { $.each(mc, function(){ 'use strict'; var plug = element.data(this); if (plug) plug.changeAttribute(mutation.attributeName); }); } } else if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { var i, obj, widgets = {}, plugins = {}; var nodes = mutation.addedNodes; for(i = 0; i < nodes.length; i++) { var node = mutation.addedNodes[i]; if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE') { continue ; } obj = $(mutation.addedNodes[i]); plugins = obj.find("[data-role]"); if (obj.data('role') !== undefined) { widgets = $.merge(plugins, obj); } else { widgets = plugins; } if (widgets.length) { Metro.initWidgets(widgets); } } } else { //console.log(mutation); } }); }; observer = new MutationObserver(observerCallback); observer.observe($("html")[0], observerConfig); }, init: function(){ var widgets = $("[data-role]"); var hotkeys = $("[data-hotkey]"); var html = $("html"); if (isTouch === true) { html.addClass("metro-touch-device"); } else { html.addClass("metro-no-touch-device"); } this.sheet = Utils.newCssSheet(); window.METRO_MEDIA = []; $.each(Metro.media_queries, function(key, query){ if (Utils.media(query)) { METRO_MEDIA.push(Metro.media_mode[key]); } }); this.observe(); this.initHotkeys(hotkeys); this.initWidgets(widgets); this.about(true); if (METRO_CLOAK_REMOVE !== "fade") { $(".m4-cloak").removeClass("m4-cloak"); } else { $(".m4-cloak").animate({ opacity: 1 }, METRO_CLOAK_REMOVE, function(){ $(".m4-cloak").removeClass("m4-cloak"); }) } return this; }, initHotkeys: function(hotkeys){ $.each(hotkeys, function(){ 'use strict'; var element = $(this); var hotkey = element.data('hotkey') ? element.data('hotkey').toLowerCase() : false; if (hotkey === false) { return; } if (element.data('hotKeyBonded') === true ) { return; } Metro.hotkeys.push(hotkey); $(document).on(Metro.events.keyup, null, hotkey, function(e){ if (element === undefined) return; if (element[0].tagName === 'A' && element.attr('href') !== undefined && element.attr('href').trim() !== '' && element.attr('href').trim() !== '#') { document.location.href = element.attr('href'); } else { element.click(); } return METRO_HOTKEYS_BUBBLE_UP; }); element.data('hotKeyBonded', true); }); }, initWidgets: function(widgets) { var that = this; $.each(widgets, function () { 'use strict'; var $this = $(this), w = this; var roles = $this.data('role').split(/\s*,\s*/); roles.map(function (func) { if ($.fn[func] !== undefined && $this.attr("data-role-"+func) === undefined) { $.fn[func].call($this); $this.attr("data-role-"+func, true); var mc = $this.data('metroComponent'); if (mc === undefined) { mc = [func]; } else { mc.push(func); } $this.data('metroComponent', mc); } }); }); }, plugin: function(name, object){ 'use strict'; $.fn[name] = function( options ) { return this.each(function() { $.data( this, name, Object.create(object).init(options, this )); }); }; }, destroyPlugin: function(element, name){ var p, mc; element = Utils.isJQueryObject(element) ? element[0] : element; p = $(element).data(name); if (!Utils.isValue(p)) { throw new Error("Component can not be destroyed: the element is not a Metro 4 component."); } if (!Utils.isFunc(p['destroy'])) { throw new Error("Component can not be destroyed: method destroy not found."); } p['destroy'](); mc = $(element).data("metroComponent"); Utils.arrayDelete(mc, name); $(element).data("metroComponent", mc); $.removeData(element, name); $(element).removeAttr("data-role-"+name); }, destroyPluginAll: function(element){ element = Utils.isJQueryObject(element) ? element[0] : element; var mc = $(element).data("metroComponent"); if (mc !== undefined && mc.length > 0) $.each(mc, function(){ 'use strict'; Metro.destroyPlugin(element, this); }); }, initPlugin: function(element, name){ element = $(element); try { if ($.fn[name] !== undefined && element.attr("data-role-"+name) === undefined) { $.fn[name].call(element); element.attr("data-role-"+name, true); var mc = element.data('metroComponent'); if (mc === undefined) { mc = [name]; } else { mc.push(name); } element.data('metroComponent', mc); } } catch (e) { console.log(e.message, e.stack); } }, reinitPlugin: function(element, name){ this.destroyPlugin(element, name); this.initPlugin(element, name); }, reinitPluginAll: function(element){ var mc = $(element).data("metroComponent"); if (mc !== undefined && mc.length > 0) $.each(mc, function(){ 'use strict'; Metro.reinitPlugin(element, this); }); }, noop: function(){}, noop_true: function(){return true;}, noop_false: function(){return false;}, stop: function(e){ e.stopPropagation(); e.preventDefault(); }, requestFullScreen: function(element){ if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullScreen) { element.webkitRequestFullScreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } else { element.requestFullscreen(); } }, exitFullScreen: function(){ if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else { document.exitFullscreen(); } }, inFullScreen: function(){ var fsm = (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement); return fsm !== undefined; } }; window['Metro'] = Metro; $(window).on(Metro.events.resize, function(){ window.METRO_MEDIA = []; $.each(Metro.media_queries, function(key, query){ if (Utils.media(query)) { METRO_MEDIA.push(Metro.media_mode[key]); } }); }); // Source: js/utils/animation.js var Animation = { duration: METRO_ANIMATION_DURATION, func: "swing", switch: function(current, next){ current.hide(); next.css({top: 0, left: 0}).show(); }, slideUp: function(current, next, duration, func){ var h = current.parent().outerHeight(true); if (duration === undefined) {duration = this.duration;} if (func === undefined) {func = this.func;} current.css("z-index", 1).animate({ top: -h, opacity: 0 }, duration, func); next.css({ top: h, left: 0, zIndex: 2 }).animate({ top: 0, opacity: 1 }, duration, func); }, slideDown: function(current, next, duration, func){ var h = current.parent().outerHeight(true); if (duration === undefined) {duration = this.duration;} if (func === undefined) {func = this.func;} current.css("z-index", 1).animate({ top: h, opacity: 0 }, duration, func); next.css({ left: 0, top: -h, zIndex: 2 }).animate({ top: 0, opacity: 1 }, duration, func); }, slideLeft: function(current, next, duration, func){ var w = current.parent().outerWidth(true); if (duration === undefined) {duration = this.duration;} if (func === undefined) {func = this.func;} current.css("z-index", 1).animate({ left: -w, opacity: 0 }, duration, func); next.css({ left: w, zIndex: 2 }).animate({ left: 0, opacity: 1 }, duration, func); }, slideRight: function(current, next, duration, func){ var w = current.parent().outerWidth(true); if (duration === undefined) {duration = this.duration;} if (func === undefined) {func = this.func;} current.css("z-index", 1).animate({ left: w, opacity: 0 }, duration, func); next.css({ left: -w, zIndex: 2 }).animate({ left: 0, opacity: 1 }, duration, func); }, fade: function(current, next, duration){ if (duration === undefined) {duration = this.duration;} current.animate({ opacity: 0 }, duration); next.css({ top: 0, left: 0 }).animate({ opacity: 1 }, duration); } }; Metro['animation'] = Animation; // Source: js/utils/colors.js function RGB(r, g, b){ this.r = r || 0; this.g = g || 0; this.g = b || 0; } function RGBA(r, g, b, a){ this.r = r || 0; this.g = g || 0; this.g = b || 0; this.a = a || 1; } function HSV(h, s, v){ this.h = h || 0; this.s = s || 0; this.v = v || 0; } function HSL(h, s, l){ this.h = h || 0; this.s = s || 0; this.l = l || 0; } function HSLA(h, s, l, a){ this.h = h || 0; this.s = s || 0; this.l = l || 0; this.a = a || 1; } function CMYK(c, m, y, k){ this.c = c || 0; this.m = m || 0; this.y = y || 0; this.k = k || 0; } var Colors = { TYPES: { HEX: "hex", RGB: "rgb", RGBA: "rgba", HSV: "hsv", HSL: "hsl", CMYK: "cmyk", UNKNOWN: "unknown" }, PALETTES: { ALL: "colorList", METRO: "colorListMetro", STANDARD: "colorListStandard" }, colorListMetro: { lime: '#a4c400', green: '#60a917', emerald: '#008a00', blue: '#00AFF0', teal: '#00aba9', cyan: '#1ba1e2', cobalt: '#0050ef', indigo: '#6a00ff', violet: '#aa00ff', pink: '#dc4fad', magenta: '#d80073', crimson: '#a20025', red: '#CE352C', orange: '#fa6800', amber: '#f0a30a', yellow: '#fff000', brown: '#825a2c', olive: '#6d8764', steel: '#647687', mauve: '#76608a', taupe: '#87794e' }, colorListStandard: { 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", lightGray: "#d3d3d3", lightGreen: "#90ee90", lightPink: "#ffb6c1", lightSalmon: "#ffa07a", lightSeaGreen: "#20b2aa", lightSkyBlue: "#87cefa", lightSlateGray: "#778899", lightSteelBlue: "#b0c4de", lightYellow: "#ffffe0", lime: "#00ff00", limeGreen: "#32dc32", linen: "#faf0e6", magenta: "#ff00ff", maroon: "#800000", mediumAquaMarine: "#66cdaa", mediumBlue: "#0000cd", mediumOrchid: "#ba55d3", mediumPurple: "#9370db", mediumSeaGreen: "#3cb371", mediumSlateBlue: "#7b68ee", mediumSpringGreen: "#00fa9a", mediumTurquoise: "#48d1cc", mediumVioletRed: "#c71585", midnightBlue: "#191970", mintCream: "#f5fffa", mistyRose: "#ffe4e1", moccasin: "#ffe4b5", navajoWhite: "#ffdead", navy: "#000080", oldLace: "#fdd5e6", olive: "#808000", oliveDrab: "#6b8e23", orange: "#ffa500", orangeRed: "#ff4500", orchid: "#da70d6", paleGoldenRod: "#eee8aa", paleGreen: "#98fb98", paleTurquoise: "#afeeee", paleVioletRed: "#db7093", papayaWhip: "#ffefd5", peachPuff: "#ffdab9", peru: "#cd853f", pink: "#ffc0cb", plum: "#dda0dd", powderBlue: "#b0e0e6", purple: "#800080", rebeccaPurple: "#663399", red: "#ff0000", rosyBrown: "#bc8f8f", royalBlue: "#4169e1", saddleBrown: "#8b4513", salmon: "#fa8072", sandyBrown: "#f4a460", seaGreen: "#2e8b57", seaShell: "#fff5ee", sienna: "#a0522d", silver: "#c0c0c0", slyBlue: "#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" }, colorList: {}, options: { angle: 30, algorithm: 1, step: .1, distance: 5, tint1: .8, tint2: .4, shade1: .6, shade2: .3, alpha: 1 }, init: function(){ this.colorList = $.extend( {}, this.colorListStandard, this.colorListMetro ); return this; }, setup: function(options){ this.options = $.extend( {}, this.options, options ); }, color: function(name, palette){ palette = palette || this.PALETTES.ALL; return this[palette][name] !== undefined ? this[palette][name] : false; }, palette: function(palette){ palette = palette || this.PALETTES.ALL; return Object.keys(this[palette]); }, colors: function(palette){ var c = []; palette = palette || this.PALETTES.ALL; $.each(this[palette], function(){ c.push(this); }); return c; }, hex2rgb: function(hex){ var regex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace( regex, function( m, r, g, b ) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec( hex ); return result ? { r: parseInt( result[1], 16 ), g: parseInt( result[2], 16 ), b: parseInt( result[3], 16 ) } : null; }, rgb2hex: function(rgb){ return "#" + (( 1 << 24 ) + ( rgb.r << 16 ) + ( rgb.g << 8 ) + rgb.b ) .toString( 16 ).slice( 1 ); }, rgb2hsv: function(rgb){ var hsv = new HSV(); var h, s, v; var r = rgb.r / 255, g = rgb.g / 255, b = rgb.b / 255; var max = Math.max(r, g, b); var min = Math.min(r, g, b); var delta = max - min; v = max; if (max === 0) { s = 0; } else { s = 1 - min / max; } if (max === min) { h = 0; } else if (max === r && g >= b) { h = 60 * ( (g - b) / delta ); } else if (max === r && g < b) { h = 60 * ( (g - b) / delta) + 360 } else if (max === g) { h = 60 * ( (b - r) / delta) + 120 } else if (max === b) { h = 60 * ( (r - g) / delta) + 240 } else { h = 0; } hsv.h = h; hsv.s = s; hsv.v = v; return hsv; }, hsv2rgb: function(hsv){ var r, g, b; var h = hsv.h, s = hsv.s * 100, v = hsv.v * 100; var Hi = Math.floor(h / 60); var Vmin = (100 - s) * v / 100; var alpha = (v - Vmin) * ( (h % 60) / 60 ); var Vinc = Vmin + alpha; var Vdec = v - alpha; switch (Hi) { case 0: r = v; g = Vinc; b = Vmin; break; case 1: r = Vdec; g = v; b = Vmin; break; case 2: r = Vmin; g = v; b = Vinc; break; case 3: r = Vmin; g = Vdec; b = v; break; case 4: r = Vinc; g = Vmin; b = v; break; case 5: r = v; g = Vmin; b = Vdec; break; } return { r: Math.round(r * 255 / 100), g: Math.round(g * 255 / 100), b: Math.round(b * 255 / 100) } }, hsv2hex: function(hsv){ return this.rgb2hex(this.hsv2rgb(hsv)); }, hex2hsv: function(hex){ return this.rgb2hsv(this.hex2rgb(hex)); }, rgb2cmyk: function(rgb){ var cmyk = new CMYK(); var r = rgb.r / 255; var g = rgb.g / 255; var b = rgb.b / 255; cmyk.k = Math.min( 1 - r, 1 - g, 1 - b ); cmyk.c = ( 1 - r - cmyk.k ) / ( 1 - cmyk.k ); cmyk.m = ( 1 - g - cmyk.k ) / ( 1 - cmyk.k ); cmyk.y = ( 1 - b - cmyk.k ) / ( 1 - cmyk.k ); cmyk.c = Math.round( cmyk.c * 100 ); cmyk.m = Math.round( cmyk.m * 100 ); cmyk.y = Math.round( cmyk.y * 100 ); cmyk.k = Math.round( cmyk.k * 100 ); return cmyk; }, cmyk2rgb: function(cmyk){ var rgb = new RGB(); var c = cmyk.c / 100; var m = cmyk.m / 100; var y = cmyk.y / 100; var k = cmyk.k / 100; rgb.r = 1 - Math.min( 1, c * ( 1 - k ) + k ); rgb.g = 1 - Math.min( 1, m * ( 1 - k ) + k ); rgb.b = 1 - Math.min( 1, y * ( 1 - k ) + k ); rgb.r = Math.round( rgb.r * 255 ); rgb.g = Math.round( rgb.g * 255 ); rgb.b = Math.round( rgb.b * 255 ); return rgb; }, hsv2hsl: function(hsv){ var h, s, l; h = hsv.h; l = (2 - hsv.s) * hsv.v; s = hsv.s * hsv.v; s /= (l <= 1) ? l : 2 - l; l /= 2; return {h: h, s: s, l: l} }, hsl2hsv: function(hsl){ var h, s, v, l; h = hsl.h; l = hsl.l * 2; s = hsl.s * (l <= 1 ? l : 2 - l); v = (l + s) / 2; s = (2 * s) / (l + s); return {h: h, s: s, l: v} }, rgb2websafe: function(rgb){ return { r: Math.round(rgb.r / 51) * 51, g: Math.round(rgb.g / 51) * 51, b: Math.round(rgb.b / 51) * 51 } }, rgba2websafe: function(rgba){ return { r: Math.round(rgba.r / 51) * 51, g: Math.round(rgba.g / 51) * 51, b: Math.round(rgba.b / 51) * 51, a: rgba.a } }, hex2websafe: function(hex){ return this.rgb2hex(this.rgb2websafe(this.toRGB(hex))); }, hsv2websafe: function(hsv){ return this.rgb2hsv(this.rgb2websafe(this.toRGB(hsv))); }, hsl2websafe: function(hsl){ return this.hsv2hsl(this.rgb2hsv(this.rgb2websafe(this.toRGB(hsl)))); }, cmyk2websafe: function(cmyk){ return this.rgb2cmyk(this.rgb2websafe(this.cmyk2rgb(cmyk))); }, websafe: function(color){ if (this.isHEX(color)) return this.hex2websafe(color); if (this.isRGB(color)) return this.rgb2websafe(color); if (this.isRGBA(color)) return this.rgba2websafe(color); if (this.isHSV(color)) return this.hsv2websafe(color); if (this.isHSL(color)) return this.hsl2websafe(color); if (this.isCMYK(color)) return this.cmyk2websafe(color); return color; }, is: function(color){ if (this.isHEX(color)) return this.TYPES.HEX; if (this.isRGB(color)) return this.TYPES.RGB; if (this.isRGBA(color)) return this.TYPES.RGBA; if (this.isHSV(color)) return this.TYPES.HSV; if (this.isHSL(color)) return this.TYPES.HSL; if (this.isCMYK(color)) return this.TYPES.CMYK; return this.TYPES.UNKNOWN; }, toRGB: function(color){ if (this.isHSV(color)) return this.hsv2rgb(color); if (this.isHSL(color)) return this.hsv2rgb(this.hsl2hsv(color)); if (this.isRGB(color)) return color; if (this.isHEX(color)) return this.hex2rgb(color); if (this.isCMYK(color)) return this.cmyk2rgb(color); throw new Error("Unknown color format!"); }, toRGBA: function(color, alpha){ var result = this.toRGB(color); result.a = alpha || 1; return result; }, toHSV: function(color){ return this.rgb2hsv(this.toRGB(color)); }, toHSL: function(color){ return this.hsv2hsl(this.rgb2hsv(this.toRGB(color))); }, toHSLA: function(color, alpha){ var hsla; hsla = this.hsv2hsl(this.rgb2hsv(this.toRGB(color))); hsla.a = alpha || this.options.alpha; return hsla; }, toHEX: function(color){ return this.rgb2hex(this.toRGB(color)); }, toCMYK: function(color){ return this.rgb2cmyk(this.toRGB(color)); }, toHexString: function(color){ return this.toHEX(color); }, toHsvString: function(color){ var hsv = this.toHSV(color); return "hsv("+[hsv.h, hsv.s, hsv.v].join(",")+")"; }, toHslString: function(color){ var hsl = this.toHSL(color); return "hsl("+[Math.round(hsl.h), Math.round(hsl.s * 100) + "%" , Math.round(hsl.l * 100) + "%"].join(",")+")"; }, toHslaString: function(color){ var hsl = this.toHSLA(color); return "hsl("+[Math.round(hsl.h), Math.round(hsl.s * 100) + "%" , Math.round(hsl.l * 100) + "%", hsl.a].join(",")+")"; }, toCmykString: function(color){ var cmyk = this.toCMYK(color); return "cmyk("+[cmyk.c, cmyk.m, cmyk.y, cmyk.k].join(",")+")"; }, toRgbString: function(color){ var rgb = this.toRGB(color); return "rgb("+[rgb.r, rgb.g, rgb.b].join(",")+")"; }, toRgbaString: function(color){ var rgb = this.toRGBA(color); return "rgba("+[rgb.r, rgb.g, rgb.b, rgb.a].join(",")+")"; }, toString: function(color){ if (this.isHEX(color)) return this.toHexString(color); if (this.isRGB(color)) return this.toRgbString(color); if (this.isRGBA(color)) return this.toRgbaString(color); if (this.isHSV(color)) return this.toHsvString(color); if (this.isHSL(color)) return this.toHslString(color); if (this.isHSLA(color)) return this.toHslaString(color); if (this.isCMYK(color)) return this.toCmykString(color); throw new Error("Unknown color format!"); }, grayscale: function(color, output){ output = output || "hex"; var rgb = this.toRGB(color); var gray = Math.round(rgb.r * .2125 + rgb.g * .7154 + rgb.b * .0721); var mono = { r: gray, g: gray, b: gray }; return this["rgb2"+output](mono); }, darken: function(color, amount){ if (amount === undefined) { amount = 10; } return this.lighten(color, -1 * Math.abs(amount)); }, lighten: function(color, amount){ var type, res, alpha = 1, ring = amount > 0; var calc = function(_color, _amount){ var col = _color.slice(1); var num = parseInt(col, 16); var r = (num >> 16) + _amount; if (r > 255) r = 255; else if (r < 0) r = 0; var b = ((num >> 8) & 0x00FF) + _amount; if (b > 255) b = 255; else if (b < 0) b = 0; var g = (num & 0x0000FF) + _amount; if (g > 255) g = 255; else if (g < 0) g = 0; res = "#" + (g | (b << 8) | (r << 16)).toString(16); return res; }; if (amount === undefined) { amount = 10; } type = this.is(color); if (type === this.TYPES.RGBA) { alpha = color.a; } do { res = calc(this.toHEX(color), amount); ring ? amount-- : amount++; } while (res.length < 7); switch (type) { case "rgb": return this.toRGB(res); case "rgba": return this.toRGBA(res, alpha); case "hsv": return this.toHSV(res); case "hsl": return this.toHSL(res); case "cmyk": return this.toCMYK(res); default: return res; } }, isDark: function(color){ var rgb = this.toRGB(color); var YIQ = ( ( rgb.r * 299 ) + ( rgb.g * 587 ) + ( rgb.b * 114 ) ) / 1000; return ( YIQ < 128 ) }, isLight: function(hex){ return !this.isDark(hex); }, isHSV: function(val){ return Utils.isObject(val) && "h" in val && "s" in val && "v" in val; }, isHSL: function(val){ return Utils.isObject(val) && "h" in val && "s" in val && "l" in val; }, isHSLA: function(val){ return Utils.isObject(val) && "h" in val && "s" in val && "l" in val && "a" in val; }, isRGB: function(val){ return Utils.isObject(val) && "r" in val && "g" in val && "b" in val; }, isRGBA: function(val){ return Utils.isObject(val) && "r" in val && "g" in val && "b" in val && "a" in val; }, isCMYK: function(val){ return Utils.isObject(val) && "c" in val && "m" in val && "y" in val && "k" in val; }, isHEX: function(val){ return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(val); }, isColor: function(color){ return this.isHEX(color) || this.isRGB(color) || this.isRGBA(color) || this.isHSV(color) || this.isHSL(color) || this.isCMYK(color); }, hueShift: function(h, s){ h+=s; while (h >= 360.0) h -= 360.0; while (h < 0.0) h += 360.0; return h; }, getScheme: function(color, name, format, options){ this.options = $.extend( {}, this.options, options ); var i; var scheme = []; var hsv; var that = this; hsv = this.toHSV(color); if (this.isHSV(hsv) === false) { console.log("The value is a not supported color format!"); return false; } function convert(source, format) { var result = []; var o = that.options; switch (format) { case "hex": result = source.map(function(v){return Colors.toHEX(v);}); break; case "rgb": result = source.map(function(v){return Colors.toRGB(v);}); break; case "rgba": result = source.map(function(v){return Colors.toRGBA(v, o.alpha);}); break; case "hsl": result = source.map(function(v){return Colors.toHSL(v);}); break; case "cmyk": result = source.map(function(v){return Colors.toCMYK(v);}); break; default: result = source; } return result; } function clamp( num, min, max ){ return Math.max( min, Math.min( num, max )); } function toRange(a, b, c){ return a < b ? b : ( a > c ? c : a); } var rgb, h = hsv.h, s = hsv.s, v = hsv.v; var o = this.options; switch (name) { case "monochromatic": case "mono": if (o.algorithm === 1) { rgb = this.hsv2rgb(hsv); rgb.r = toRange(Math.round(rgb.r + (255 - rgb.r) * o.tint1), 0, 255); rgb.g = toRange(Math.round(rgb.g + (255 - rgb.g) * o.tint1), 0, 255); rgb.b = toRange(Math.round(rgb.b + (255 - rgb.b) * o.tint1), 0, 255); scheme.push(this.rgb2hsv(rgb)); rgb = this.hsv2rgb(hsv); rgb.r = toRange(Math.round(rgb.r + (255 - rgb.r) * o.tint2), 0, 255); rgb.g = toRange(Math.round(rgb.g + (255 - rgb.g) * o.tint2), 0, 255); rgb.b = toRange(Math.round(rgb.b + (255 - rgb.b) * o.tint2), 0, 255); scheme.push(this.rgb2hsv(rgb)); scheme.push(hsv); rgb = this.hsv2rgb(hsv); rgb.r = toRange(Math.round(rgb.r * o.shade1), 0, 255); rgb.g = toRange(Math.round(rgb.g * o.shade1), 0, 255); rgb.b = toRange(Math.round(rgb.b * o.shade1), 0, 255); scheme.push(this.rgb2hsv(rgb)); rgb = this.hsv2rgb(hsv); rgb.r = toRange(Math.round(rgb.r * o.shade2), 0, 255); rgb.g = toRange(Math.round(rgb.g * o.shade2), 0, 255); rgb.b = toRange(Math.round(rgb.b * o.shade2), 0, 255); scheme.push(this.rgb2hsv(rgb)); } else if (o.algorithm === 2) { scheme.push(hsv); for(i = 1; i <= o.distance; i++) { v = clamp(v - o.step, 0, 1); s = clamp(s - o.step, 0, 1); scheme.push({h: h, s: s, v: v}); } } else if (o.algorithm === 3) { scheme.push(hsv); for(i = 1; i <= o.distance; i++) { v = clamp(v - o.step, 0, 1); scheme.push({h: h, s: s, v: v}); } } else { v = clamp(hsv.v + o.step * 2, 0, 1); scheme.push({h: h, s: s, v: v}); v = clamp(hsv.v + o.step, 0, 1); scheme.push({h: h, s: s, v: v}); scheme.push(hsv); s = hsv.s; v = hsv.v; v = clamp(hsv.v - o.step, 0, 1); scheme.push({h: h, s: s, v: v}); v = clamp(hsv.v - o.step * 2, 0, 1); scheme.push({h: h, s: s, v: v}); } break; case 'complementary': case 'complement': case 'comp': scheme.push(hsv); h = this.hueShift(hsv.h, 180.0); scheme.push({h: h, s: s, v: v}); break; case 'double-complementary': case 'double-complement': case 'double': scheme.push(hsv); console.log(h); h = this.hueShift(h, 180.0); scheme.push({h: h, s: s, v: v}); console.log(h); h = this.hueShift(h, o.angle); scheme.push({h: h, s: s, v: v}); console.log(h); h = this.hueShift(h, 180.0); scheme.push({h: h, s: s, v: v}); console.log(h); break; case 'analogous': case 'analog': h = this.hueShift(h, o.angle); scheme.push({h: h, s: s, v: v}); scheme.push(hsv); h = this.hueShift(hsv.h, 0.0 - o.angle); scheme.push({h: h, s: s, v: v}); break; case 'triadic': case 'triad': scheme.push(hsv); for ( i = 1; i < 3; i++ ) { h = this.hueShift(h, 120.0); scheme.push({h: h, s: s, v: v}); } break; case 'tetradic': case 'tetra': scheme.push(hsv); h = this.hueShift(hsv.h, 180.0); scheme.push({h: h, s: s, v: v}); h = this.hueShift(hsv.h, -1 * o.angle); scheme.push({h: h, s: s, v: v}); h = this.hueShift(h, 180.0); scheme.push({h: h, s: s, v: v}); break; case 'square': scheme.push(hsv); for ( i = 1; i < 4; i++ ) { h = this.hueShift(h, 90.0); scheme.push({h: h, s: s, v: v}); } break; case 'split-complementary': case 'split-complement': case 'split': h = this.hueShift(h, 180.0 - o.angle); scheme.push({h: h, s: s, v: v}); scheme.push(hsv); h = this.hueShift(hsv.h, 180.0 + o.angle); scheme.push({h: h, s: s, v: v}); break; default: console.log("Unknown scheme name"); } return convert(scheme, format); } }; Metro['colors'] = Colors.init(); // Source: js/utils/easing.js $.easing['jswing'] = $.easing['swing']; $.extend($.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert($.easing.default); return $.easing[$.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c * (t /= d) * t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c * (t /= d) * t * t + b; }, easeOutCubic: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c * (t /= d) * t * t * t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, easeOutQuint: function (x, t, b, c, d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t / d * (Math.PI / 2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t = t / d - 1) * t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b; return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(c / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; }, easeOutElastic: function (x, t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(c / a); return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5); if (a < Math.abs(c)) { a = c; s = p / 4; } else s = p / (2 * Math.PI) * Math.asin(c / a); if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - $.easing.easeOutBounce(x, d - t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if (t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; } else if (t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d / 2) return $.easing.easeInBounce(x, t * 2, 0, c, d) * .5 + b; return $.easing.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b; } }); // Source: js/utils/export.js var Export = { init: function(){ return this; }, options: { csvDelimiter: "\t", csvNewLine: "\r\n", includeHeader: true }, setup: function(options){ this.options = $.extend({}, this.options, options); return this; }, base64: function(data){ return window.btoa(unescape(encodeURIComponent(data))); }, b64toBlob: function (b64Data, contentType, sliceSize) { contentType = contentType || ''; sliceSize = sliceSize || 512; var byteCharacters = window.atob(b64Data); var byteArrays = []; var offset; for (offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); var i; for (i = 0; i < slice.length; i = i + 1) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new window.Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, { type: contentType }); }, tableToCSV: function(table, filename, options){ var that = this, o = this.options; var body, head, data = ""; var i, j, row, cell; o = $.extend({}, o, options); if (Utils.isJQueryObject(table)) { table = table[0]; } if (Utils.bool(o.includeHeader)) { head = table.querySelectorAll("thead")[0]; for(i = 0; i < head.rows.length; i++) { row = head.rows[i]; for(j = 0; j < row.cells.length; j++){ cell = row.cells[j]; data += (j ? o.csvDelimiter : '') + cell.textContent.trim(); } data += o.csvNewLine; } } body = table.querySelectorAll("tbody")[0]; for(i = 0; i < body.rows.length; i++) { row = body.rows[i]; for(j = 0; j < row.cells.length; j++){ cell = row.cells[j]; data += (j ? o.csvDelimiter : '') + cell.textContent.trim(); } data += o.csvNewLine; } if (Utils.isValue(filename)) { return this.createDownload(this.base64("\uFEFF" + data), 'application/csv', filename); } return data; }, createDownload: function (data, contentType, filename) { var blob, anchor, url; anchor = document.createElement('a'); anchor.style.display = "none"; document.body.appendChild(anchor); blob = this.b64toBlob(data, contentType); url = window.URL.createObjectURL(blob); anchor.href = url; anchor.download = filename || Utils.elementId("download"); anchor.click(); window.URL.revokeObjectURL(url); document.body.removeChild(anchor); return true; } }; Metro['export'] = Export.init(); // Source: js/utils/extensions.js $.fn.extend({ toggleAttr: function(a, v){ return this.each(function(){ var el = $(this); if (v !== undefined) { el.attr(a, v); } else { if (el.attr(a) !== undefined) { el.removeAttr(a); } else { el.attr(a, ""+a); } } }); }, clearClasses: function(){ return this.each(function(){ this.className = ""; }); } }); Array.prototype.shuffle = function () { var currentIndex = this.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = this[currentIndex]; this[currentIndex] = this[randomIndex]; this[randomIndex] = temporaryValue; } return this; }; Array.prototype.clone = function () { return this.slice(0); }; Array.prototype.unique = function () { var a = this.concat(); for (var i = 0; i < a.length; ++i) { for (var j = i + 1; j < a.length; ++j) { if (a[i] === a[j]) a.splice(j--, 1); } } return a; }; if (!Array.from) { Array.from = function(val) { var i, a = []; if (val.length === undefined && typeof val === "object") { return Object.values(val); } if (val.length !== undefined) { for(i = 0; i < val.length; i++) { a.push(val[i]); } return a; } throw new Error("Value can not be converted to array"); }; } if (typeof Array.contains !== "function") { Array.prototype.contains = function(val, from){ return this.indexOf(val, from) > -1; } } /** * Number.prototype.format(n, x, s, c) * * @param n: length of decimal * @param x: length of whole part * @param s: sections delimiter * @param c: decimal delimiter */ Number.prototype.format = function(n, x, s, c) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')', num = this.toFixed(Math.max(0, ~~n)); return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); }; String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); }; String.prototype.contains = function() { return !!~String.prototype.indexOf.apply(this, arguments); }; String.prototype.toDate = function(format, locale) { var result; var normalized, normalizedFormat, formatItems, dateItems, checkValue; var monthIndex, dayIndex, yearIndex, hourIndex, minutesIndex, secondsIndex; var year, month, day, hour, minute, second; var parsedMonth; locale = locale || "en-US"; var monthNameToNumber = function(month){ var d, months, index, i; month = month.substr(0, 3); if ( locale !== undefined && locale !== "en-US" && Locales !== undefined && Locales[locale] !== undefined && Locales[locale]['calendar'] !== undefined && Locales[locale]['calendar']['months'] !== undefined ) { months = Locales[locale]['calendar']['months']; for(i = 12; i < months.length; i++) { if (months[i].toLowerCase() === month.toLowerCase()) { index = i - 12; break; } } month = Locales["en-US"]['calendar']['months'][index]; } d = Date.parse(month + " 1, 1972"); if(!isNaN(d)){ return new Date(d).getMonth() + 1; } return -1; }; if (format === undefined || format === null || format === "") { return new Date(this); } // normalized = this.replace(/[^a-zA-Z0-9%]/g, '-'); normalized = this.replace(/[\/,.:\s]/g, '-'); normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9%]/g, '-'); formatItems = normalizedFormat.split('-'); dateItems = normalized.split('-'); checkValue = normalized.replace(/\-/g,""); if (checkValue.trim() === "") { return "Invalid Date"; } monthIndex = formatItems.indexOf("mm") > -1 ? formatItems.indexOf("mm") : formatItems.indexOf("%m"); dayIndex = formatItems.indexOf("dd") > -1 ? formatItems.indexOf("dd") : formatItems.indexOf("%d"); yearIndex = formatItems.indexOf("yyyy") > -1 ? formatItems.indexOf("yyyy") : formatItems.indexOf("yy") > -1 ? formatItems.indexOf("yy") : formatItems.indexOf("%y"); hourIndex = formatItems.indexOf("hh") > -1 ? formatItems.indexOf("hh") : formatItems.indexOf("%h"); minutesIndex = formatItems.indexOf("ii") > -1 ? formatItems.indexOf("ii") : formatItems.indexOf("mi") > -1 ? formatItems.indexOf("mi") : formatItems.indexOf("%i"); secondsIndex = formatItems.indexOf("ss") > -1 ? formatItems.indexOf("ss") : formatItems.indexOf("%s"); if (monthIndex > -1 && dateItems[monthIndex] !== "") { if (isNaN(parseInt(dateItems[monthIndex]))) { dateItems[monthIndex] = monthNameToNumber(dateItems[monthIndex]); if (dateItems[monthIndex] === -1) { return "Invalid Date"; } } else { parsedMonth = parseInt(dateItems[monthIndex]); if (parsedMonth < 1 || parsedMonth > 12) { return "Invalid Date"; } } } else { return "Invalid Date"; } year = yearIndex >-1 && dateItems[yearIndex] !== "" ? dateItems[yearIndex] : null; month = monthIndex >-1 && dateItems[monthIndex] !== "" ? dateItems[monthIndex] : null; day = dayIndex >-1 && dateItems[dayIndex] !== "" ? dateItems[dayIndex] : null; hour = hourIndex >-1 && dateItems[hourIndex] !== "" ? dateItems[hourIndex] : null; minute = minutesIndex>-1 && dateItems[minutesIndex] !== "" ? dateItems[minutesIndex] : null; second = secondsIndex>-1 && dateItems[secondsIndex] !== "" ? dateItems[secondsIndex] : null; result = new Date(year,month-1,day,hour,minute,second); return result; }; String.prototype.toArray = function(delimiter, type, format){ var str = this; var a; type = type || "string"; delimiter = delimiter || ","; format = format === undefined || format === null ? false : format; a = (""+str).split(delimiter); return a.map(function(s){ var result; switch (type) { case "int": case "integer": result = parseInt(s); break; case "number": case "float": result = parseFloat(s); break; case "date": result = !format ? new Date(s) : s.toDate(format); break; default: result = s.trim(); } return result; }); }; Date.prototype.getWeek = function (dowOffset) { var nYear, nday, newYear, day, daynum, weeknum; dowOffset = !Utils.isValue(dowOffset) ? METRO_WEEK_START : typeof dowOffset === 'number' ? parseInt(dowOffset) : 0; newYear = new Date(this.getFullYear(),0,1); day = newYear.getDay() - dowOffset; day = (day >= 0 ? day : day + 7); daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1; if(day < 4) { weeknum = Math.floor((daynum+day-1)/7) + 1; if(weeknum > 52) { nYear = new Date(this.getFullYear() + 1,0,1); nday = nYear.getDay() - dowOffset; nday = nday >= 0 ? nday : nday + 7; weeknum = nday < 4 ? 1 : 53; } } else { weeknum = Math.floor((daynum+day-1)/7); } return weeknum; }; Date.prototype.getYear = function(){ return this.getFullYear().toString().substr(-2); }; Date.prototype.format = function(format, locale){ if (locale === undefined) { locale = "en-US"; } var cal = (Metro.locales !== undefined && Metro.locales[locale] !== undefined ? Metro.locales[locale] : Metro.locales["en-US"])['calendar']; var date = this; var nDay = date.getDay(), nDate = date.getDate(), nMonth = date.getMonth(), nYear = date.getFullYear(), nHour = date.getHours(), aDays = cal['days'], aMonths = cal['months'], aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], isLeapYear = function() { return (nYear%4===0 && nYear%100!==0) || nYear%400===0; }, getThursday = function() { var target = new Date(date); target.setDate(nDate - ((nDay+6)%7) + 3); return target; }, zeroPad = function(nNum, nPad) { return ('' + (Math.pow(10, nPad) + nNum)).slice(1); }; return format.replace(/(%[a-z])/gi, function(sMatch) { return { '%a': aDays[nDay].slice(0,3), '%A': aDays[nDay], '%b': aMonths[nMonth].slice(0,3), '%B': aMonths[nMonth], '%c': date.toUTCString(), '%C': Math.floor(nYear/100), '%d': zeroPad(nDate, 2), 'dd': zeroPad(nDate, 2), '%e': nDate, '%F': date.toISOString().slice(0,10), '%G': getThursday().getFullYear(), '%g': ('' + getThursday().getFullYear()).slice(2), '%H': zeroPad(nHour, 2), // 'HH': zeroPad(nHour, 2), '%I': zeroPad((nHour+11)%12 + 1, 2), '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3), '%k': '' + nHour, '%l': (nHour+11)%12 + 1, '%m': zeroPad(nMonth + 1, 2), // 'mm': zeroPad(nMonth + 1, 2), '%M': zeroPad(date.getMinutes(), 2), // 'MM': zeroPad(date.getMinutes(), 2), '%p': (nHour<12) ? 'AM' : 'PM', '%P': (nHour<12) ? 'am' : 'pm', '%s': Math.round(date.getTime()/1000), // 'ss': Math.round(date.getTime()/1000), '%S': zeroPad(date.getSeconds(), 2), // 'SS': zeroPad(date.getSeconds(), 2), '%u': nDay || 7, '%V': (function() { var target = getThursday(), n1stThu = target.valueOf(); target.setMonth(0, 1); var nJan1 = target.getDay(); if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7); return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2); })(), '%w': '' + nDay, '%x': date.toLocaleDateString(), '%X': date.toLocaleTimeString(), '%y': ('' + nYear).slice(2), // 'yy': ('' + nYear).slice(2), '%Y': nYear, // 'YYYY': nYear, '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'), '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1') }[sMatch] || sMatch; }); }; Date.prototype.addHours = function(n) { this.setTime(this.getTime() + (n*60*60*1000)); return this; }; Date.prototype.addDays = function(n) { this.setDate(this.getDate() + (n)); return this; }; Date.prototype.addMonths = function(n) { this.setMonth(this.getMonth() + (n)); return this; }; Date.prototype.addYears = function(n) { this.setFullYear(this.getFullYear() + (n)); return this; }; // Source: js/utils/hotkeys.js var hotkeys = { specialKeys: { 8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'" }, shiftNums: { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" }, // excludes: button, checkbox, file, hidden, image, password, radio, reset, search, submit, url textAcceptingInputTypes: [ "text", "password", "number", "email", "url", "range", "date", "month", "week", "time", "datetime", "datetime-local", "search", "color", "tel"], // default input types not to bind to unless bound directly textInputTypes: /textarea|input|select/i, options: { filterInputAcceptingElements: METRO_HOTKEYS_FILTER_INPUT_ACCEPTING_ELEMENTS, filterTextInputs: METRO_HOTKEYS_FILTER_TEXT_INPUTS, filterContentEditable: METRO_HOTKEYS_FILTER_CONTENT_EDITABLE }, keyHandler: function(handleObj){ if (typeof handleObj.data === "string") { handleObj.data = { keys: handleObj.data }; } // Only care when a possible input has been specified if (!handleObj.data || !handleObj.data.keys || typeof handleObj.data.keys !== "string") { return; } var origHandler = handleObj.handler, keys = handleObj.data.keys.toLowerCase().split(" "); handleObj.handler = function(event) { // Don't fire in text-accepting inputs that we didn't directly bind to if (this !== event.target && (hotkeys.options.filterInputAcceptingElements && hotkeys.textInputTypes.test(event.target.nodeName) || (hotkeys.options.filterContentEditable && $(event.target).attr('contenteditable')) || (hotkeys.options.filterTextInputs && $.inArray(event.target.type, hotkeys.textAcceptingInputTypes) > -1)) ) { return; } var special = event.type !== "keypress" && hotkeys.specialKeys[event.which], character = String.fromCharCode(event.which).toLowerCase(), modif = "", possible = {}; $.each(["alt", "ctrl", "shift"], function(index, specialKey) { if (event[specialKey + 'Key'] && special !== specialKey) { modif += specialKey + '+'; } }); // metaKey is triggered off ctrlKey erronously if (event.metaKey && !event.ctrlKey && special !== "meta") { modif += "meta+"; } if (event.metaKey && special !== "meta" && modif.indexOf("alt+ctrl+shift+") > -1) { modif = modif.replace("alt+ctrl+shift+", "hyper+"); } if (special) { possible[modif + special] = true; } else { possible[modif + character] = true; possible[modif + hotkeys.shiftNums[character]] = true; // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" if (modif === "shift+") { possible[hotkeys.shiftNums[character]] = true; } } for (var i = 0, l = keys.length; i < l; i++) { if (possible[keys[i]]) { return origHandler.apply(this, arguments); } } }; } }; $.each(["keydown", "keyup", "keypress"], function() { $.event.special[this] = { add: hotkeys.keyHandler }; }); // Source: js/utils/i18n.js var Locales = { 'en-US': { "calendar": { "months": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "days": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Sun", "Mon", "Tus", "Wen", "Thu", "Fri", "Sat" ], "time": { "days": "DAYS", "hours": "HOURS", "minutes": "MINS", "seconds": "SECS", "month": "MON", "day": "DAY", "year": "YEAR" } }, "buttons": { "ok": "OK", "cancel": "Cancel", "done": "Done", "today": "Today", "now": "Now", "clear": "Clear", "help": "Help", "yes": "Yes", "no": "No", "random": "Random", "save": "Save", "reset": "Reset" } }, 'cn-ZH': { "calendar": { "months": [ "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], "days": [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "日", "一", "二", "三", "四", "五", "六", "周日", "周一", "周二", "周三", "周四", "周五", "周六" ], "time": { "days": "天", "hours": "时", "minutes": "分", "seconds": "秒", "month": "月", "day": "日", "year": "年" } }, "buttons": { "ok": "确认", "cancel": "取消", "done": "完成", "today": "今天", "now": "现在", "clear": "清除", "help": "帮助", "yes": "是", "no": "否", "random": "随机", "save": "保存", "reset": "重啟" } }, 'de-DE': { "calendar": { "months": [ "Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember", "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez" ], "days": [ "Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sn", "Mn", "Di", "Mi", "Do", "Fr", "Sa", "Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam" ], "time": { "days": "TAGE", "hours": "UHR", "minutes": "MIN", "seconds": "SEK" } }, "buttons": { "ok": "OK", "cancel": "Abbrechen", "done": "Fertig", "today": "Heute", "now": "Jetzt", "clear": "Reinigen", "help": "Hilfe", "yes": "Ja", "no": "Nein", "random": "Zufällig", "save": "Sparen", "reset": "Zurücksetzen" } }, 'hu-HU': { "calendar": { "months": [ 'Január', 'Február', 'Március', 'Április', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December', 'Jan', 'Feb', 'Már', 'Ápr', 'Máj', 'Jún', 'Júl', 'Aug', 'Szep', 'Okt', 'Nov', 'Dec' ], "days": [ 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat', 'V', 'H', 'K', 'Sz', 'Cs', 'P', 'Sz', 'Vas', 'Hét', 'Ke', 'Sze', 'Csü', 'Pén', 'Szom' ], "time": { "days": "NAP", "hours": "ÓRA", "minutes": "PERC", "seconds": "MP" } }, "buttons": { "ok": "OK", "cancel": "Mégse", "done": "Kész", "today": "Ma", "now": "Most", "clear": "Törlés", "help": "Segítség", "yes": "Igen", "no": "Nem", "random": "Véletlen", "save": "Mentés", "reset": "Visszaállítás" } }, 'ru-RU': { "calendar": { "months": [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь", "Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек" ], "days": [ "Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вос", "Пон", "Вто", "Сре", "Чет", "Пят", "Суб" ], "time": { "days": "ДНИ", "hours": "ЧАСЫ", "minutes": "МИН", "seconds": "СЕК" } }, "buttons": { "ok": "ОК", "cancel": "Отмена", "done": "Готово", "today": "Сегодня", "now": "Сейчас", "clear": "Очистить", "help": "Помощь", "yes": "Да", "no": "Нет", "random": "Случайно", "save": "Сохранить", "reset": "Сброс" } }, 'uk-UA': { "calendar": { "months": [ "Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень", "Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру" ], "days": [ "Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П’ятниця", "Субота", "Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нед", "Пон", "Вiв", "Сер", "Чет", "Пят", "Суб" ], "time": { "days": "ДНІ", "hours": "ГОД", "minutes": "ХВИЛ", "seconds": "СЕК" } }, "buttons": { "ok": "ОК", "cancel": "Відміна", "done": "Готово", "today": "Сьогодні", "now": "Зараз", "clear": "Очистити", "help": "Допомога", "yes": "Так", "no": "Ні", "random": "Випадково", "save": "Зберегти", "reset": "Скинути" } }, 'es-MX': { "calendar": { "months": [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre", "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" ], "days": [ "Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb" ], "time": { "days": "DÍAS", "hours": "HORAS", "minutes": "MINS", "seconds": "SEGS", "month": "MES", "day": "DÍA", "year": "AÑO" } }, "buttons": { "ok": "Aceptar", "cancel": "Cancelar", "done": "Hecho", "today": "Hoy", "now": "Ahora", "clear": "Limpiar", "help": "Ayuda", "yes": "Si", "no": "No", "random": "Aleatorio", "save": "Salvar", "reset": "Reiniciar" } }, 'fr-FR': { "calendar": { "months": [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre", "Janv", "Févr", "Mars", "Avr", "Mai", "Juin", "Juil", "Août", "Sept", "Oct", "Nov", "Déc" ], "days": [ "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "De", "Du", "Ma", "Me", "Je", "Ve", "Sa", "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam" ], "time": { "days": "JOURS", "hours": "HEURES", "minutes": "MINS", "seconds": "SECS", "month": "MOIS", "day": "JOUR", "year": "ANNEE" } }, "buttons": { "ok": "OK", "cancel": "Annulé", "done": "Fait", "today": "Aujourd'hui", "now": "Maintenant", "clear": "Effacé", "help": "Aide", "yes": "Oui", "no": "Non", "random": "Aléatoire", "save": "Sauvegarder", "reset": "Réinitialiser" } }, 'it-IT': { "calendar": { "months": [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre", "Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic" ], "days": [ "Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab" ], "time": { "days": "GIORNI", "hours": "ORE", "minutes": "MIN", "seconds": "SEC", "month": "MESE", "day": "GIORNO", "year": "ANNO" } }, "buttons": { "ok": "OK", "cancel": "Annulla", "done": "Fatto", "today": "Oggi", "now": "Adesso", "clear": "Cancella", "help": "Aiuto", "yes": "Sì", "no": "No", "random": "Random", "save": "Salvare", "reset": "Reset" } } }; Metro['locales'] = Locales; // Source: js/utils/md5.js var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ function hex_md5(s) { return rstr2hex(rstr_md5(str2rstr_utf8(s))); } function b64_md5(s) { return rstr2b64(rstr_md5(str2rstr_utf8(s))); } function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); } function hex_hmac_md5(k, d) { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); } function b64_hmac_md5(k, d) { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); } function any_hmac_md5(k, d, e) { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var bkey = rstr2binl(key); if (bkey.length > 16) bkey = binl_md5(bkey, key.length * 8); var ipad = new Array(16), opad = new Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; var output = ""; var x; for (var i = 0; i < input.length; i++) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Convert a raw string to a base-64 string */ function rstr2b64(input) { var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var output = ""; var len = input.length; for (var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > input.length * 8) output += b64pad; else output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F); } } return output; } /* * Convert a raw string to an arbitrary string encoding */ function rstr2any(input, encoding) { var divisor = encoding.length; var i, j, q, x, quotient; /* Convert to an array of 16-bit big-endian values, forming the dividend */ var dividend = new Array(Math.ceil(input.length / 2)); for (i = 0; i < dividend.length; i++) { dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); } /* * Repeatedly perform a long division. The binary array forms the dividend, * the length of the encoding is the divisor. Once computed, the quotient * forms the dividend for the next step. All remainders are stored for later * use. */ var full_length = Math.ceil(input.length * 8 / (Math.log(encoding.length) / Math.log(2))); var remainders = new Array(full_length); for (j = 0; j < full_length; j++) { quotient = []; x = 0; for (i = 0; i < dividend.length; i++) { x = (x << 16) + dividend[i]; q = Math.floor(x / divisor); x -= q * divisor; if (quotient.length > 0 || q > 0) quotient[quotient.length] = q; } remainders[j] = x; dividend = quotient; } /* Convert the remainders to the output string */ var output = ""; for (i = remainders.length - 1; i >= 0; i--) output += encoding.charAt(remainders[i]); return output; } /* * Encode a string as utf-8. * For efficiency, this assumes the input is valid utf-16. */ function str2rstr_utf8(input) { var output = ""; var i = -1; var x, y; while (++i < input.length) { /* Decode utf-16 surrogate pairs */ x = input.charCodeAt(i); y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF) { x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF); i++; } /* Encode output as utf-8 */ if (x <= 0x7F) output += String.fromCharCode(x); else if (x <= 0x7FF) output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F), 0x80 | ( x & 0x3F)); else if (x <= 0xFFFF) output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F), 0x80 | ((x >>> 6 ) & 0x3F), 0x80 | ( x & 0x3F)); else if (x <= 0x1FFFFF) output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3F), 0x80 | ((x >>> 6 ) & 0x3F), 0x80 | ( x & 0x3F)); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i; var output = new Array(input.length >> 2); for (i = 0; i < output.length; i++) output[i] = 0; for (i = 0; i < input.length * 8; i += 8) output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); return output; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var output = ""; for (var i = 0; i < input.length * 32; i += 8) output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); return output; } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } // window.md5 = { // hex: function(val){ // return hex_md5(val); // }, // // b64: function(val){ // return b64_md5(val); // }, // // any: function(s, e){ // return any_md5(s, e); // }, // // hex_hmac: function(k, d){ // return hex_hmac_md5(k, d); // }, // // b64_hmac: function(k, d){ // return b64_hmac_md5(k, d); // }, // // any_hmac: function(k, d, e){ // return any_hmac_md5(k, d, e); // } // }; //$.Metro['md5'] = hex_md5; // Source: js/utils/mousewheel.js var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { version: '3.1.12', setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], mousewheel_handler, false ); } } else { this.onmousewheel = mousewheel_handler; } // Store the line height and page height for this particular element $.data(this, 'mousewheel-line-height', $.event.special.mousewheel.getLineHeight(this)); $.data(this, 'mousewheel-page-height', $.event.special.mousewheel.getPageHeight(this)); }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], mousewheel_handler, false ); } } else { this.onmousewheel = null; } // Clean up the data we added to the element $.removeData(this, 'mousewheel-line-height'); $.removeData(this, 'mousewheel-page-height'); }, getLineHeight: function(elem) { var $elem = $(elem), $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent'](); if (!$parent.length) { $parent = $('body'); } return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16; }, getPageHeight: function(elem) { return $(elem).height(); }, settings: { adjustOldDeltas: true, // see shouldAdjustOldDeltas() below normalizeOffset: true // calls getBoundingClientRect for each event } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); }, unmousewheel: function(fn) { return this.unbind('mousewheel', fn); } }); function mousewheel_handler(event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, offsetX = 0, offsetY = 0; event = $.event.fix(orgEvent); event.type = 'mousewheel'; // Old school scrollwheel delta if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) if ( 'deltaY' in orgEvent ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( 'deltaX' in orgEvent ) { deltaX = orgEvent.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } // No change actually happened, no reason to go any further if ( deltaY === 0 && deltaX === 0 ) { return; } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages if ( orgEvent.deltaMode === 1 ) { var lineHeight = $.data(this, 'mousewheel-line-height'); delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; } else if ( orgEvent.deltaMode === 2 ) { var pageHeight = $.data(this, 'mousewheel-page-height'); delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { lowestDelta /= 40; } } // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { // Divide all the things by 40! delta /= 40; deltaX /= 40; deltaY /= 40; } // Get a whole, normalized value for the deltas delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); // Normalise offsetX and offsetY properties if ( $.event.special.mousewheel.settings.normalizeOffset && this.getBoundingClientRect ) { var boundingRect = this.getBoundingClientRect(); offsetX = event.clientX - boundingRect.left; offsetY = event.clientY - boundingRect.top; } // Add information to the event object event.deltaX = deltaX; event.deltaY = deltaY; event.deltaFactor = lowestDelta; event.offsetX = offsetX; event.offsetY = offsetY; // Go ahead and set deltaMode to 0 since we converted to pixels // Although this is a little odd since we overwrite the deltaX/Y // properties with normalized deltas. event.deltaMode = 0; // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); // Clearout lowestDelta after sometime to better // handle multiple device types that give different // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); return ($.event.dispatch || $.event.handle).apply(this, args); } function nullLowestDelta() { lowestDelta = null; } function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas // by 40 to try and get a more usable deltaFactor. // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. return $.event.special.mousewheel.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; } // Source: js/utils/scroll-events.js var dispatch = $.event.dispatch || $.event.handle; var special = jQuery.event.special, uid1 = 'D' + (+new Date()), uid2 = 'D' + (+new Date() + 1); special.scrollstart = { setup: function(data) { var _data = $.extend({ latency: special.scrollstop.latency }, data); var timer, handler = function(evt) { var _self = this; if (timer) { clearTimeout(timer); timer = null; } else { evt.type = 'scrollstart'; dispatch.apply(_self, arguments); } timer = setTimeout(function() { timer = null; }, _data.latency); }; $(this).on('scroll', handler).data(uid1, handler); }, teardown: function() { $(this).off('scroll', $(this).data(uid1)); } }; special.scrollstop = { latency: 250, setup: function(data) { var _data = $.extend({ latency: special.scrollstop.latency }, data); var timer, handler = function(evt) { var _self = this, _args = arguments; if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(function() { timer = null; evt.type = 'scrollstop'; dispatch.apply(_self, _args); }, _data.latency); }; $(this).on('scroll', handler).data(uid2, handler); }, teardown: function() { $(this).off('scroll', $(this).data(uid2)); } }; // Source: js/utils/storage.js var Storage = function(type){ return new Storage.init(type); }; Storage.prototype = { setKey: function(key){ this.key = key }, getKey: function(){ return this.key; }, setItem: function(key, value){ this.storage.setItem(this.key + ":" + key, JSON.stringify(value)); }, getItem: function(key, default_value, reviver){ var result, value; value = this.storage.getItem(this.key + ":" + key); try { result = JSON.parse(value, reviver); } catch (e) { result = null; } return Utils.nvl(result, default_value); }, getItemPart: function(key, sub_key, default_value, reviver){ var i; var val = this.getItem(key, default_value, reviver); sub_key = sub_key.split("->"); for(i = 0; i < sub_key.length; i++) { val = val[sub_key[i]]; } return val; }, delItem: function(key){ this.storage.removeItem(this.key + ":" + key) }, size: function(unit){ var divider; switch (unit) { case 'm': case 'M': { divider = 1024 * 1024; break; } case 'k': case 'K': { divider = 1024; break; } default: divider = 1; } return JSON.stringify(this.storage).length / divider; } }; Storage.init = function(type){ this.key = ""; this.storage = type ? type : window.localStorage; return this; }; Storage.init.prototype = Storage.prototype; Metro['storage'] = Storage(window.localStorage); Metro['session'] = Storage(window.sessionStorage); // Source: js/utils/tpl.js var TemplateEngine = function(html, options) { var re = /<%(.+?)%>/g, reExp = /(^( )?(var|if|for|else|switch|case|break|{|}|;))(.*)?/g, code = 'with(obj) { var r=[];\n', cursor = 0, result, match; var add = function(line, js) { js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') : (code += line !== '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : ''); return add; }; while(match = re.exec(html)) { add(html.slice(cursor, match.index))(match[1], true); cursor = match.index + match[0].length; } add(html.substr(cursor, html.length - cursor)); code = (code + 'return r.join(""); }').replace(/[\r\t\n]/g, ' '); try { result = new Function('obj', code).apply(options, [options]); } catch(err) { console.error("'" + err.message + "'", " in \n\nCode:\n", code, "\n"); } return result; }; Metro['template'] = TemplateEngine; // Source: js/utils/utilities.js var Utils = { isUrl: function (val) { return /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@\-\/]))?/.test(val); }, isTag: function(val){ return /^<\/?[\w\s="/.':;#-\/\?]+>/gi.test(val); }, isColor: function (val) { return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(val); }, isEmbedObject: function(val){ var embed = ["iframe", "object", "embed", "video"]; var result = false; $.each(embed, function(i, v){ 'use strict'; if (typeof val === "string" && val.toLowerCase() === v) { result = true; } else if (val.nodeType !== undefined && val.tagName.toLowerCase() === v) { result = true; } }); return result; }, isVideoUrl: function(val){ return /youtu\.be|youtube|vimeo/gi.test(val); }, isDate: function(val, format){ var result; if (typeof val === "object" && Utils.isFunc(val['getMonth'])) { return true; } if (Utils.isValue(format)) { result = String(val).toDate(format); } else { result = String(new Date(val)); } return result !== "Invalid Date"; }, isDateObject: function(v){ return typeof v === 'object' && v['getMonth'] !== undefined; }, isInt: function(n){ return Number(n) === n && n % 1 === 0; }, isFloat: function(n){ return Number(n) === n && n % 1 !== 0; }, isTouchDevice: function() { return (('ontouchstart' in window) || (navigator.MaxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); }, isFunc: function(f){ return Utils.isType(f, 'function'); }, isObject: function(o){ return Utils.isType(o, 'object') }, isArray: function(a){ return Array.isArray(a); }, isType: function(o, t){ if (o === undefined || o === null) { return false; } if (typeof o === t) { return o; } if (Utils.isTag(o) || Utils.isUrl(o)) { return false; } if (typeof window[o] === t) { return window[o]; } if (typeof o === 'string' && o.indexOf(".") === -1) { return false; } if (typeof o === 'string' && o.indexOf(" ") !== -1) { return false; } if (typeof o === 'string' && o.indexOf("(") !== -1) { return false; } if (typeof o === 'string' && o.indexOf("[") !== -1) { return false; } if (typeof o === "number" && t.toLowerCase() !== "number") { return false; } var ns = o.split("."); var i, context = window; for(i = 0; i < ns.length; i++) { context = context[ns[i]]; } return typeof context === t ? context : false; }, isMetroObject: function(el, type){ var $el = $(el), el_obj = $el.data(type); if ($el.length === 0) { console.log(type + ' ' + el + ' not found!'); return false; } if (el_obj === undefined) { console.log('Element not contain role '+ type +'! Please add attribute data-role="'+type+'" to element ' + el); return false; } return true; }, isJQueryObject: function(el){ return (typeof jQuery === "function" && el instanceof jQuery); }, embedObject: function(val){ if (typeof val !== "string" ) { val = Utils.isJQueryObject(val) ? val.html() : val.innerHTML; } return "<div class='embed-container'>" + val + "</div>"; }, embedUrl: function(val){ if (val.indexOf("youtu.be") !== -1) { val = "https://www.youtube.com/embed/" + val.split("/").pop(); } return "<div class='embed-container'><iframe src='"+val+"'></iframe></div>"; }, secondsToTime: function(secs) { var hours = Math.floor(secs / (60 * 60)); var divisor_for_minutes = secs % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); return { "h": hours, "m": minutes, "s": seconds }; }, hex2rgba: function(hex, alpha){ var c; alpha = isNaN(alpha) ? 1 : alpha; if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){ c= hex.substring(1).split(''); if(c.length=== 3){ c= [c[0], c[0], c[1], c[1], c[2], c[2]]; } c= '0x'+c.join(''); return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+','+alpha+')'; } throw new Error('Hex2rgba error. Bad Hex value'); }, random: function(from, to){ return Math.floor(Math.random()*(to-from+1)+from); }, uniqueId: function () { "use strict"; var d = new Date().getTime(); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); }, elementId: function(prefix){ return prefix+"-"+(new Date()).getTime()+Utils.random(1, 1000); }, secondsToFormattedString: function(time){ var sec_num = parseInt(time, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (hours < 10) {hours = "0"+hours;} if (minutes < 10) {minutes = "0"+minutes;} if (seconds < 10) {seconds = "0"+seconds;} return [hours, minutes, seconds].join(":"); }, callback: function(f, args, context){ return Utils.exec(f, args, context); }, func: function(f){ return new Function("a", f); }, exec: function(f, args, context){ var result; if (f === undefined || f === null) {return false;} var func = Utils.isFunc(f); if (func === false) { func = Utils.func(f); } try { result = func.apply(context, args); } catch (err) { result = null; if (METRO_THROWS === true) { throw err; } } return result; }, isOutsider: function(el) { el = Utils.isJQueryObject(el) ? el : $(el); var rect; var clone = el.clone(); clone.removeAttr("data-role").css({ visibility: "hidden", position: "absolute", display: "block" }); el.parent().append(clone); rect = clone[0].getBoundingClientRect(); clone.remove(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); }, inViewport: function(el){ var rect = Utils.rect(el); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); }, rect: function(el){ if (typeof jQuery === "function" && el instanceof jQuery) { el = el[0]; } return el.getBoundingClientRect(); }, getCursorPosition: function(el, e){ var a = Utils.rect(el); return { x: Utils.pageXY(e).x - a.left - window.pageXOffset, y: Utils.pageXY(e).y - a.top - window.pageYOffset }; }, getCursorPositionX: function(el, e){ return Utils.getCursorPosition(el, e).x; }, getCursorPositionY: function(el, e){ return Utils.getCursorPosition(el, e).y; }, objectLength: function(obj){ return Object.keys(obj).length; }, percent: function(total, part, round_value){ if (total === 0) { return 0; } var result = part * 100 / total; return round_value === true ? Math.round(result) : Math.round(result * 100) / 100; }, camelCase: function(str){ return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); }, dashedName: function(str){ return str.replace(/([A-Z])/g, function(u) { return "-" + u.toLowerCase(); }); }, objectShift: function(obj){ var min = 0; $.each(obj, function(i){ if (min === 0) { min = i; } else { if (min > i) { min = i; } } }); delete obj[min]; return obj; }, objectDelete: function(obj, key){ if (obj[key] !== undefined) delete obj[key]; }, arrayDeleteByMultipleKeys: function(arr, keys){ keys.forEach(function(ind){ delete arr[ind]; }); return arr.filter(function(item){ return item !== undefined; }) }, arrayDelete: function(arr, val){ arr.splice(arr.indexOf(val), 1); }, arrayDeleteByKey: function(arr, key){ arr.splice(key, 1); }, nvl: function(data, other){ return data === undefined || data === null ? other : data; }, objectClone: function(obj){ var copy = {}; for(var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = obj[key]; } } return copy; }, github: function(repo, callback){ var that = this; $.ajax({ url: 'https://api.github.com/repos/' + repo, dataType: 'jsonp' }) .done(function(data){ that.callback(callback, [data.data]); }); }, detectIE: function() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); if (msie > 0) { // IE 10 or older => return version number return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11 => return version number var rv = ua.indexOf('rv:'); return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); } var edge = ua.indexOf('Edge/'); if (edge > 0) { // Edge (IE 12+) => return version number return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10); } // other browser return false; }, detectChrome: function(){ return /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); }, md5: function(s){ return hex_md5(s); }, encodeURI: function(str){ return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }, pageHeight: function(){ var body = document.body, html = document.documentElement; return Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); }, cleanPreCode: function(selector){ var els = Array.prototype.slice.call(document.querySelectorAll(selector), 0); els.forEach(function(el){ var txt = el.textContent .replace(/^[\r\n]+/, "") // strip leading newline .replace(/\s+$/g, ""); if (/^\S/gm.test(txt)) { el.textContent = txt; return; } var mat, str, re = /^[\t ]+/gm, len, min = 1e3; while (mat = re.exec(txt)) { len = mat[0].length; if (len < min) { min = len; str = mat[0]; } } if (min === 1e3) return; el.textContent = txt.replace(new RegExp("^" + str, 'gm'), ""); }); }, coords: function(el){ if (Utils.isJQueryObject(el)) { el = el[0]; } var box = el.getBoundingClientRect(); return { top: box.top + window.pageYOffset, left: box.left + window.pageXOffset }; }, positionXY: function(e, t){ switch (t) { case 'client': return Utils.clientXY(e); case 'screen': return Utils.screenXY(e); case 'page': return Utils.pageXY(e); default: return {x: 0, y: 0} } }, clientXY: function(e){ return { x: e.changedTouches ? e.changedTouches[0].clientX : e.clientX, y: e.changedTouches ? e.changedTouches[0].clientY : e.clientY }; }, screenXY: function(e){ return { x: e.changedTouches ? e.changedTouches[0].screenX : e.screenX, y: e.changedTouches ? e.changedTouches[0].screenY : e.screenY }; }, pageXY: function(e){ return { x: e.changedTouches ? e.changedTouches[0].pageX : e.pageX, y: e.changedTouches ? e.changedTouches[0].pageY : e.pageY }; }, isRightMouse: function(e){ return "which" in e ? e.which === 3 : "button" in e ? e.button === 2 : undefined; }, hiddenElementSize: function(el, includeMargin){ var clone = $(el).clone(); clone.removeAttr("data-role").css({ visibility: "hidden", position: "absolute", display: "block" }); $("body").append(clone); if (includeMargin === undefined) { includeMargin = false; } var width = clone.outerWidth(includeMargin); var height = clone.outerHeight(includeMargin); clone.remove(); return { width: width, height: height } }, getStyle: function(el, pseudo){ if (Utils.isJQueryObject(el) === true) { el = el[0]; } return window.getComputedStyle(el, pseudo); }, getStyleOne: function(el, property){ return Utils.getStyle(el).getPropertyValue(property); }, getTransformMatrix: function(el, returnArray){ var computedMatrix = Utils.getStyleOne(el, "transform"); var a = computedMatrix .replace("matrix(", '') .slice(0, -1) .split(','); return returnArray !== true ? { a: a[0], b: a[1], c: a[2], d: a[3], tx: a[4], ty: a[5] } : a; }, computedRgbToHex: function(rgb){ var a = rgb.replace(/[^\d,]/g, '').split(','); var result = "#", i; for(i = 0; i < 3; i++) { var h = parseInt(a[i]).toString(16); result += h.length === 1 ? "0" + h : h; } return result; }, computedRgbToRgba: function(rgb, alpha){ var a = rgb.replace(/[^\d,]/g, '').split(','); if (alpha === undefined) { alpha = 1; } a.push(alpha); return "rgba("+a.join(",")+")"; }, computedRgbToArray: function(rgb){ return rgb.replace(/[^\d,]/g, '').split(','); }, hexColorToArray: function(hex){ var c; if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){ c= hex.substring(1).split(''); if(c.length === 3){ c= [c[0], c[0], c[1], c[1], c[2], c[2]]; } c= '0x'+c.join(''); return [(c>>16)&255, (c>>8)&255, c&255]; } return [0,0,0]; }, hexColorToRgbA: function(hex, alpha){ var c; if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){ c= hex.substring(1).split(''); if(c.length === 3){ c= [c[0], c[0], c[1], c[1], c[2], c[2]]; } c= '0x'+c.join(''); return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255, alpha ? alpha : 1].join(',')+')'; } return 'rgba(0,0,0,1)'; }, getInlineStyles: function(el){ var styles = {}; if (Utils.isJQueryObject(el)) { el = el[0]; } for (var i = 0, l = el.style.length; i < l; i++) { var s = el.style[i]; styles[s] = el.style[s]; } return styles; }, updateURIParameter: function(uri, key, value) { var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"); var separator = uri.indexOf('?') !== -1 ? "&" : "?"; if (uri.match(re)) { return uri.replace(re, '$1' + key + "=" + value + '$2'); } else { return uri + separator + key + "=" + value; } }, getURIParameter: function(url, name){ if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, " ")); }, getLocales: function(){ return Object.keys(Metro.locales); }, addLocale: function(locale){ Metro.locales = $.extend( {}, Metro.locales, locale ); }, strToArray: function(str, delimiter, type, format){ var a; if (!Utils.isValue(delimiter)) { delimiter = ","; } if (!Utils.isValue(type)) { type = "string"; } a = (""+str).split(delimiter); return a.map(function(s){ var result; switch (type) { case "int": case "integer": result = parseInt(s); break; case "number": case "float": result = parseFloat(s); break; case "date": result = !Utils.isValue(format) ? new Date(s) : s.toDate(format); break; default: result = s.trim(); } return result; }) }, aspectRatioH: function(width, a){ if (a === "16/9") return width * 9 / 16; if (a === "21/9") return width * 9 / 21; if (a === "4/3") return width * 3 / 4; }, aspectRatioW: function(height, a){ if (a === "16/9") return height * 16 / 9; if (a === "21/9") return height * 21 / 9; if (a === "4/3") return height * 4 / 3; }, valueInObject: function(obj, value){ return Object.values(obj).indexOf(value) > -1; }, keyInObject: function(obj, key){ return Object.keys(obj).indexOf(key) > -1; }, inObject: function(obj, key, val){ return obj[key] !== undefined && obj[key] === val; }, newCssSheet: function(media){ var style = document.createElement("style"); if (media !== undefined) { style.setAttribute("media", media); } style.appendChild(document.createTextNode("")); document.head.appendChild(style); return style.sheet; }, addCssRule: function(sheet, selector, rules, index){ if("insertRule" in sheet) { sheet.insertRule(selector + "{" + rules + "}", index); } else if("addRule" in sheet) { sheet.addRule(selector, rules, index); } }, media: function(query){ return window.matchMedia(query).matches }, mediaModes: function(){ return METRO_MEDIA; }, mediaExist: function(media){ return METRO_MEDIA.indexOf(media) > -1; }, inMedia: function(media){ return METRO_MEDIA.indexOf(media) > -1 && METRO_MEDIA.indexOf(media) === METRO_MEDIA.length - 1; }, isValue: function(val){ return val !== undefined && val !== null && val !== ""; }, isNull: function(val){ return val === undefined || val === null; }, isNegative: function(val){ return parseFloat(val) < 0; }, isPositive: function(val){ return parseFloat(val) > 0; }, isZero: function(val){ return (parseFloat(val.toFixed(2))) === 0.00; }, between: function(val, bottom, top, equals){ return equals === true ? val >= bottom && val <= top : val > bottom && val < top; }, parseMoney: function(val){ return Number(parseFloat(val.replace(/[^0-9-.]/g, ''))); }, parseCard: function(val){ return val.replace(/[^0-9]/g, ''); }, parsePhone: function(val){ return Utils.parseCard(val); }, isVisible: function(el){ if (Utils.isJQueryObject(el)) { el = el[0]; } return Utils.getStyleOne(el, "display") !== "none" && Utils.getStyleOne(el, "visibility") !== "hidden" && el.offsetParent !== null; }, parseNumber: function(val, thousand, decimal){ return val.replace(new RegExp('\\'+thousand, "g"), "").replace(new RegExp('\\'+decimal, 'g'), "."); }, nearest: function(val, precision, down){ val /= precision; val = Math[down === true ? 'floor' : 'ceil'](val) * precision; return val; }, bool: function(value){ switch(value){ case true: case "true": case 1: case "1": case "on": case "yes": return true; default: return false; } }, copy: function(el){ var body = document.body, range, sel; if (Utils.isJQueryObject(el)) { el = el[0]; } if (document.createRange && window.getSelection) { range = document.createRange(); sel = window.getSelection(); sel.removeAllRanges(); try { range.selectNodeContents(el); sel.addRange(range); } catch (e) { range.selectNode(el); sel.addRange(range); } } else if (body.createTextRange) { range = body.createTextRange(); range.moveToElementText(el); range.select(); } document.execCommand("Copy"); if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? document.selection.empty(); } }, isLocalhost: function(){ return (location.hostname === "localhost" || location.hostname === "127.0.0.1" || location.hostname === "") }, formData: function(form){ if (Utils.isNull(form)) { return ; } if (Utils.isJQueryObject(form)) { form = form[0]; } if (!form || form.nodeName !== "FORM") { return; } var i, j, q = {}; for (i = form.elements.length - 1; i >= 0; i = i - 1) { if (form.elements[i].name === "") { continue; } switch (form.elements[i].nodeName) { case 'INPUT': switch (form.elements[i].type) { case 'text': case 'hidden': case 'password': case 'button': case 'reset': case 'submit': q[form.elements[i].name] = form.elements[i].value; break; case 'checkbox': case 'radio': if (form.elements[i].checked) { q[form.elements[i].name] = form.elements[i].value; } break; } break; case 'file': break; case 'TEXTAREA': q[form.elements[i].name] = form.elements[i].value; break; case 'SELECT': switch (form.elements[i].type) { case 'select-one': q[form.elements[i].name] = form.elements[i].value; break; case 'select-multiple': q[form.elements[i].name] = []; for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) { if (form.elements[i].options[j].selected) { q[form.elements[i].name].push(form.elements[i].options[j].value); } } break; } break; case 'BUTTON': switch (form.elements[i].type) { case 'reset': case 'submit': case 'button': q[form.elements[i].name] = form.elements[i].value; break; } break; } } return q; } }; Metro['utils'] = Utils; // Source: js/plugins/accordion.js var Accordion = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onAccordionCreate, [this.element]); return this; }, options: { material: false, duration: METRO_ANIMATION_DURATION, oneFrame: true, showActive: true, activeFrameClass: "", activeHeadingClass: "", activeContentClass: "", onFrameOpen: Metro.noop, onFrameBeforeOpen: Metro.noop_true, onFrameClose: Metro.noop, onFrameBeforeClose: Metro.noop_true, onAccordionCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var frames = element.children(".frame"); var active = element.children(".frame.active"); var frame_to_open; element.addClass("accordion"); if (o.material === true) { element.addClass("material"); } if (active.length === 0) { frame_to_open = frames[0]; } else { frame_to_open = active[0]; } this._hideAll(); if (o.showActive === true || o.oneFrame === true) { this._openFrame(frame_to_open); } this._createEvents(); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var active = element.children(".frame.active"); element.on(Metro.events.click, ".heading", function(){ var heading = $(this); var frame = heading.parent(); if (heading.closest(".accordion")[0] !== element[0]) { return false; } if (frame.hasClass("active")) { if (active.length === 1 && o.oneFrame) { } else { that._closeFrame(frame); } } else { that._openFrame(frame); } element.trigger("open", {frame: frame}); }); }, _openFrame: function(f){ var that = this, element = this.element, o = this.options; var frames = element.children(".frame"); var frame = $(f); if (Utils.exec(o.onFrameBeforeOpen, [frame], element[0]) === false) { return false; } if (o.oneFrame === true) { this._closeAll(); } frame.addClass("active " + o.activeFrameClass); frame.children(".heading").addClass(o.activeHeadingClass); frame.children(".content").addClass(o.activeContentClass).slideDown(o.duration); Utils.exec(o.onFrameOpen, [frame], element[0]); }, _closeFrame: function(f){ var that = this, element = this.element, o = this.options; var frame = $(f); if (Utils.exec(o.onFrameBeforeClose, [frame], element[0]) === false) { return ; } frame.removeClass("active " + o.activeFrameClass); frame.children(".heading").removeClass(o.activeHeadingClass); frame.children(".content").removeClass(o.activeContentClass).slideUp(o.duration); Utils.callback(o.onFrameClose, [frame], element[0]); }, _closeAll: function(){ var that = this, element = this.element, o = this.options; var frames = element.children(".frame"); $.each(frames, function(){ that._closeFrame(this); }); }, _hideAll: function(){ var that = this, element = this.element, o = this.options; var frames = element.children(".frame"); $.each(frames, function(){ $(this).children(".content").hide(0); }); }, _openAll: function(){ var that = this, element = this.element, o = this.options; var frames = element.children(".frame"); $.each(frames, function(){ that._openFrame(this); }); }, changeAttribute: function(attributeName){ }, destroy: function(){ this.element.off(Metro.events.click, ".heading"); } }; Metro.plugin('accordion', Accordion); // Source: js/plugins/activity.js var Activity = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onActivityCreate, [this.element]); return this; }, options: { type: "ring", style: "light", size: 64, radius: 20, onActivityCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; var i, wrap; element .html('') .addClass(o.style + "-style") .addClass("activity-" + o.type); function _metro(){ for(i = 0; i < 5 ; i++) { $("<div/>").addClass('circle').appendTo(element); } } function _square(){ for(i = 0; i < 4 ; i++) { $("<div/>").addClass('square').appendTo(element); } } function _cycle(){ $("<div/>").addClass('cycle').appendTo(element); } function _ring(){ for(i = 0; i < 5 ; i++) { wrap = $("<div/>").addClass('wrap').appendTo(element); $("<div/>").addClass('circle').appendTo(wrap); } } function _simple(){ $('<svg class="circular"><circle class="path" cx="'+o.size/2+'" cy="'+o.size/2+'" r="'+o.radius+'" fill="none" stroke-width="2" stroke-miterlimit="10"/></svg>').appendTo(element); } switch (o.type) { case 'metro': _metro(); break; case 'square': _square(); break; case 'cycle': _cycle(); break; case 'simple': _simple(); break; default: _ring(); } }, changeAttribute: function(attributeName){ }, destroy: function(){ var element = this.element, o = this.options; element.html('') .removeClass(o.style + "-style") .removeClass("activity-" + o.type); } }; Metro.plugin('activity', Activity); Metro['activity'] = { open: function(options){ var activity = '<div data-role="activity" data-type="'+( options.type ? options.type : 'cycle' )+'" data-style="'+( options.style ? options.style : 'color' )+'"></div>'; var text = options.text ? '<div class="text-center">'+options.text+'</div>' : ''; return Metro.dialog.create({ content: activity + text, defaultAction: false, clsContent: "d-flex flex-column flex-justify-center flex-align-center bg-transparent no-shadow w-auto", clsDialog: "no-border no-shadow bg-transparent global-dialog", autoHide: options.autoHide ? options.autoHide : 0, overlayClickClose: options.overlayClickClose === true, overlayColor: options.overlayColor?options.overlayColor:'#000000', overlayAlpha: options.overlayAlpha?options.overlayAlpha:.5, clsOverlay: "global-overlay" }) }, close: function(a){ Metro.dialog.close(a); } }; // Source: js/plugins/app-bar.js var AppBar = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, options: { expand: false, expandPoint: null, duration: 100, onAppBarCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onAppBarCreate, [element]); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var id = Utils.elementId("app-bar"); var hamburger, menu; element.addClass("app-bar"); hamburger = element.find(".hamburger"); if (hamburger.length === 0) { hamburger = $("<button>").attr("type", "button").addClass("hamburger menu-down"); for(var i = 0; i < 3; i++) { $("<span>").addClass("line").appendTo(hamburger); } if (Colors.isLight(Utils.computedRgbToHex(Utils.getStyleOne(element, "background-color"))) === true) { hamburger.addClass("dark"); } } element.prepend(hamburger); menu = element.find(".app-bar-menu"); if (menu.length === 0) { hamburger.css("display", "none"); } else { Utils.addCssRule(Metro.sheet, ".app-bar-menu li", "list-style: none!important;"); // This special for IE11 and Edge } if( !!element.attr("id") === false ){ element.attr("id", id); } if (hamburger.css('display') === 'block') { menu.hide().addClass("collapsed"); hamburger.removeClass("hidden"); } else { hamburger.addClass("hidden"); } if (o.expand === true) { element.addClass("app-bar-expand"); hamburger.addClass("hidden"); } else { if (Utils.isValue(o.expandPoint) && Utils.mediaExist(o.expandPoint)) { element.addClass("app-bar-expand"); hamburger.addClass("hidden"); } } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var menu = element.find(".app-bar-menu"); var hamburger = element.find(".hamburger"); element.on(Metro.events.click, ".hamburger", function(){ if (menu.length === 0) return ; var collapsed = menu.hasClass("collapsed"); if (collapsed) { that.open(); } else { that.close(); } }); $(window).on(Metro.events.resize+"-"+element.attr("id"), function(){ if (o.expand !== true) { if (Utils.isValue(o.expandPoint) && Utils.mediaExist(o.expandPoint)) { element.addClass("app-bar-expand"); } else { element.removeClass("app-bar-expand"); } } if (menu.length === 0) return ; if (hamburger.css('display') !== 'block') { menu.show(); hamburger.addClass("hidden"); } else { hamburger.removeClass("hidden"); if (hamburger.hasClass("active")) { menu.show().removeClass("collapsed"); } else { menu.hide().addClass("collapsed"); } } }); }, close: function(){ var that = this, element = this.element, o = this.options; var menu = element.find(".app-bar-menu"); var hamburger = element.find(".hamburger"); menu.slideUp(o.duration, function(){ menu.addClass("collapsed"); hamburger.removeClass("active"); }); }, open: function(){ var that = this, element = this.element, o = this.options; var menu = element.find(".app-bar-menu"); var hamburger = element.find(".hamburger"); menu.slideDown(o.duration, function(){ menu.removeClass("collapsed"); hamburger.addClass("active"); }); }, changeAttribute: function(attributeName){ }, destroy: function(){ var element = this.element; element.off(Metro.events.click, ".hamburger"); $(window).off(Metro.events.resize+"-"+element.attr("id")); } }; Metro.plugin('appbar', AppBar); // Source: js/plugins/audio.js var Audio = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.preloader = null; this.player = null; this.audio = elem; this.stream = null; this.volume = null; this.volumeBackup = 0; this.muted = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { playlist: null, src: null, volume: .5, loop: false, autoplay: false, showLoop: true, showPlay: true, showStop: true, showMute: true, showFull: true, showStream: true, showVolume: true, showInfo: true, showPlaylist: true, showNext: true, showPrev: true, showFirst: true, showLast: true, showForward: true, showBackward: true, showShuffle: true, showRandom: true, loopIcon: "<span class='default-icon-loop'></span>", stopIcon: "<span class='default-icon-stop'></span>", playIcon: "<span class='default-icon-play'></span>", pauseIcon: "<span class='default-icon-pause'></span>", muteIcon: "<span class='default-icon-mute'></span>", volumeLowIcon: "<span class='default-icon-low-volume'></span>", volumeMediumIcon: "<span class='default-icon-medium-volume'></span>", volumeHighIcon: "<span class='default-icon-high-volume'></span>", playlistIcon: "<span class='default-icon-playlist'></span>", nextIcon: "<span class='default-icon-next'></span>", prevIcon: "<span class='default-icon-prev'></span>", firstIcon: "<span class='default-icon-first'></span>", lastIcon: "<span class='default-icon-last'></span>", forwardIcon: "<span class='default-icon-forward'></span>", backwardIcon: "<span class='default-icon-backward'></span>", shuffleIcon: "<span class='default-icon-shuffle'></span>", randomIcon: "<span class='default-icon-random'></span>", onPlay: Metro.noop, onPause: Metro.noop, onStop: Metro.noop, onEnd: Metro.noop, onMetadata: Metro.noop, onTime: Metro.noop, onAudioCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options, audio = this.audio; this._createPlayer(); this._createControls(); this._createEvents(); if (o.autoplay === true) { this.play(); } Utils.exec(o.onAudioCreate, [element, this.player], element[0]); }, _createPlayer: function(){ var that = this, element = this.element, o = this.options, audio = this.audio; var prev = element.prev(); var parent = element.parent(); var player = $("<div>").addClass("media-player audio-player " + element[0].className); if (prev.length === 0) { parent.prepend(player); } else { player.insertAfter(prev); } element.appendTo(player); $.each(['muted', 'autoplay', 'controls', 'height', 'width', 'loop', 'poster', 'preload'], function(){ element.removeAttr(this); }); element.attr("preload", "auto"); audio.volume = o.volume; if (o.src !== null) { this._setSource(o.src); } element[0].className = ""; this.player = player; }, _setSource: function(src){ var element = this.element; element.find("source").remove(); element.removeAttr("src"); if (Array.isArray(src)) { $.each(src, function(){ var item = this; if (item.src === undefined) return ; $("<source>").attr('src', item.src).attr('type', item.type !== undefined ? item.type : '').appendTo(element); }); } else { element.attr("src", src); } }, _createControls: function(){ var that = this, element = this.element, o = this.options, audio = this.elem, player = this.player; var controls = $("<div>").addClass("controls").addClass(o.clsControls).insertAfter(element); var stream = $("<div>").addClass("stream").appendTo(controls); var streamSlider = $("<input>").addClass("stream-slider ultra-thin cycle-marker").appendTo(stream); var preloader = $("<div>").addClass("load-audio").appendTo(stream); var volume = $("<div>").addClass("volume").appendTo(controls); var volumeSlider = $("<input>").addClass("volume-slider ultra-thin cycle-marker").appendTo(volume); var infoBox = $("<div>").addClass("info-box").appendTo(controls); if (o.showInfo !== true) { infoBox.hide(); } preloader.activity({ type: "metro", style: "color" }); preloader.hide(0); this.preloader = preloader; streamSlider.slider({ clsMarker: "bg-red", clsHint: "bg-cyan fg-white", clsComplete: "bg-cyan", hint: true, onStart: function(){ if (!audio.paused) audio.pause(); }, onStop: function(val){ if (audio.seekable.length > 0) { audio.currentTime = (that.duration * val / 100).toFixed(0); } if (audio.paused && audio.currentTime > 0) { audio.play(); } } }); this.stream = streamSlider; if (o.showStream !== true) { stream.hide(); } volumeSlider.slider({ clsMarker: "bg-red", clsHint: "bg-cyan fg-white", hint: true, value: o.volume * 100, onChangeValue: function(val){ audio.volume = val / 100; } }); this.volume = volumeSlider; if (o.showVolume !== true) { volume.hide(); } var loop, play, stop, mute, full; if (o.showLoop === true) loop = $("<button>").attr("type", "button").addClass("button square loop").html(o.loopIcon).appendTo(controls); if (o.showPlay === true) play = $("<button>").attr("type", "button").addClass("button square play").html(o.playIcon).appendTo(controls); if (o.showStop === true) stop = $("<button>").attr("type", "button").addClass("button square stop").html(o.stopIcon).appendTo(controls); if (o.showMute === true) mute = $("<button>").attr("type", "button").addClass("button square mute").html(o.muteIcon).appendTo(controls); if (o.loop === true) { loop.addClass("active"); element.attr("loop", "loop"); } this._setVolume(); if (o.muted) { that.volumeBackup = audio.volume; that.volume.data('slider').val(0); audio.volume = 0; } infoBox.html("00:00 / 00:00"); }, _createEvents: function(){ var that = this, element = this.element, o = this.options, audio = this.elem, player = this.player; element.on("loadstart", function(){ that.preloader.fadeIn(); }); element.on("loadedmetadata", function(){ that.duration = audio.duration.toFixed(0); that._setInfo(0, that.duration); Utils.exec(o.onMetadata, [audio, player], element[0]); }); element.on("canplay", function(){ that._setBuffer(); that.preloader.fadeOut(); }); element.on("progress", function(){ that._setBuffer(); }); element.on("timeupdate", function(){ var position = Math.round(audio.currentTime * 100 / that.duration); that._setInfo(audio.currentTime, that.duration); that.stream.data('slider').val(position); Utils.exec(o.onTime, [audio.currentTime, that.duration, audio, player], element[0]); }); element.on("waiting", function(){ that.preloader.fadeIn(); }); element.on("loadeddata", function(){ }); element.on("play", function(){ player.find(".play").html(o.pauseIcon); Utils.exec(o.onPlay, [audio, player], element[0]); }); element.on("pause", function(){ player.find(".play").html(o.playIcon); Utils.exec(o.onPause, [audio, player], element[0]); }); element.on("stop", function(){ that.stream.data('slider').val(0); Utils.exec(o.onStop, [audio, player], element[0]); }); element.on("ended", function(){ that.stream.data('slider').val(0); Utils.exec(o.onEnd, [audio, player], element[0]); }); element.on("volumechange", function(){ that._setVolume(); }); player.on(Metro.events.click, ".play", function(){ if (audio.paused) { that.play(); } else { that.pause(); } }); player.on(Metro.events.click, ".stop", function(){ that.stop(); }); player.on(Metro.events.click, ".mute", function(){ that._toggleMute(); }); player.on(Metro.events.click, ".loop", function(){ that._toggleLoop(); }); }, _toggleLoop: function(){ var loop = this.player.find(".loop"); if (loop.length === 0) return ; loop.toggleClass("active"); if (loop.hasClass("active")) { this.element.attr("loop", "loop"); } else { this.element.removeAttr("loop"); } }, _toggleMute: function(){ this.muted = !this.muted; if (this.muted === false) { this.audio.volume = this.volumeBackup; this.volume.data('slider').val(this.volumeBackup * 100); } else { this.volumeBackup = this.audio.volume; this.volume.data('slider').val(0); this.audio.volume = 0; } }, _setInfo: function(a, b){ this.player.find(".info-box").html(Utils.secondsToFormattedString(Math.round(a)) + " / " + Utils.secondsToFormattedString(Math.round(b))); }, _setBuffer: function(){ var buffer = this.audio.buffered.length ? Math.round(Math.floor(this.audio.buffered.end(0)) / Math.floor(this.audio.duration) * 100) : 0; this.stream.data('slider').buff(buffer); }, _setVolume: function(){ var audio = this.audio, player = this.player, o = this.options; var volumeButton = player.find(".mute"); var volume = audio.volume * 100; if (volume > 1 && volume < 30) { volumeButton.html(o.volumeLowIcon); } else if (volume >= 30 && volume < 60) { volumeButton.html(o.volumeMediumIcon); } else if (volume >= 60 && volume <= 100) { volumeButton.html(o.volumeHighIcon); } else { volumeButton.html(o.muteIcon); } }, play: function(src){ if (src !== undefined) { this._setSource(src); } if (this.element.attr("src") === undefined && this.element.find("source").length === 0) { return ; } this.audio.play(); }, pause: function(){ this.audio.pause(); }, resume: function(){ if (this.audio.paused) { this.play(); } }, stop: function(){ this.audio.pause(); this.audio.currentTime = 0; this.stream.data('slider').val(0); }, volume: function(v){ if (v === undefined) { return this.audio.volume; } if (v > 1) { v /= 100; } this.audio.volume = v; this.volume.data('slider').val(v*100); }, loop: function(){ this._toggleLoop(); }, mute: function(){ this._toggleMute(); }, changeSource: function(){ var src = JSON.parse(this.element.attr('data-src')); this.play(src); }, changeVolume: function(){ var volume = this.element.attr("data-volume"); this.volume(volume); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-src": this.changeSource(); break; case "data-volume": this.changeVolume(); break; } }, destroy: function(){ var element = this.element, player = this.player; element.off("loadstart"); element.off("loadedmetadata"); element.off("canplay"); element.off("progress"); element.off("timeupdate"); element.off("waiting"); element.off("loadeddata"); element.off("play"); element.off("pause"); element.off("stop"); element.off("ended"); element.off("volumechange"); player.off(Metro.events.click, ".play"); player.off(Metro.events.click, ".stop"); player.off(Metro.events.click, ".mute"); player.off(Metro.events.click, ".loop"); Metro.destroyPlugin(this.stream, "slider"); Metro.destroyPlugin(this.volume, "slider"); element.insertBefore(player); player.html("").remove(); } }; Metro.plugin('audio', Audio); // Source: js/plugins/bottom-sheet.js var BottomSheet = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.toggle = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { mode: "list", toggle: null, onOpen: Metro.noop, onClose: Metro.noop, onBottomSheetCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onBottomSheetCreate, [element], element[0]); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; element .addClass("bottom-sheet") .addClass(o.mode+"-list"); if (Utils.isValue(o.toggle) && $(o.toggle).length > 0) { this.toggle = $(o.toggle); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; if (Utils.isValue(this.toggle)) { this.toggle.on(Metro.events.click, function(){ that.toggleView(); }); } element.on(Metro.events.click, "li", function(){ that.close(); }); }, isOpen: function(){ return this.element.hasClass("opened"); }, open: function(mode){ var element = this.element, o = this.options; if (Utils.isValue(mode)) { element.removeClass("list-style grid-style").addClass(mode+"-style"); } this.element.addClass("opened"); Utils.exec(o.onOpen, [element], element[0]); }, close: function(){ var element = this.element, o = this.options; element.removeClass("opened"); Utils.exec(o.onClose, [element], element[0]); }, toggle: function(mode){ if (this.isOpen()) { this.close(); } else { this.open(mode); } }, changeAttribute: function(attributeName){ }, destroy: function(){} }; Metro.plugin('bottomsheet', BottomSheet); Metro['bottomsheet'] = { isBottomSheet: function(el){ return Utils.isMetroObject(el, "bottomsheet"); }, open: function(el, as){ if (!this.isBottomSheet(el)) { return false; } var sheet = $(el).data("bottomsheet"); sheet.open(as); }, close: function(el){ if (!this.isBottomSheet(el)) { return false; } var sheet = $(el).data("bottomsheet"); sheet.close(); }, toggle: function(el, as){ if (!this.isBottomSheet(el)) { return false; } if (this.isOpen(el)) { this.close(el); } else { this.open(el, as); } }, isOpen: function(el){ if (!this.isBottomSheet(el)) { return false; } var sheet = $(el).data("bottomsheet"); return sheet.isOpen(); } }; // Source: js/plugins/button-group.js var ButtonGroup = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.active = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { targets: "button", clsActive: "active", requiredButton: false, mode: Metro.groupMode.ONE, onButtonClick: Metro.noop, onButtonsGroupCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createGroup(); this._createEvents(); Utils.exec(o.onButtonsGroupCreate, [element]); }, _createGroup: function(){ var that = this, element = this.element, o = this.options; var cls, buttons, buttons_active, id = Utils.elementId("button-group"); if (element.attr("id") === undefined) { element.attr("id", id); } element.addClass("button-group"); buttons = element.find( o.targets ); buttons_active = element.find( "." + o.clsActive ); if (o.mode === Metro.groupMode.ONE && buttons_active.length === 0 && o.requiredButton === true) { $(buttons[0]).addClass(o.clsActive); } if (o.mode === Metro.groupMode.ONE && buttons_active.length > 1) { buttons.removeClass(o.clsActive); $(buttons[0]).addClass(o.clsActive); } element.find( "." + o.clsActive ).addClass("js-active"); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, o.targets, function(){ var el = $(this); Utils.exec(o.onButtonClick, [el], this); if (o.mode === Metro.groupMode.ONE && el.hasClass(o.clsActive)) { return ; } if (o.mode === Metro.groupMode.ONE) { element.find(o.targets).removeClass(o.clsActive).removeClass("js-active"); el.addClass(o.clsActive).addClass("js-active"); } else { el.toggleClass(o.clsActive).toggleClass("js-active"); } }); }, changeAttribute: function(attributeName){ }, destroy: function(){ var element = this.element, o = this.options; element.off(Metro.events.click, o.targets); element.find(o.targets).removeClass(o.clsActive).removeClass("js-active"); } }; Metro.plugin('buttongroup', ButtonGroup); // Source: js/plugins/calendar.js var Calendar = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.today = new Date(); this.today.setHours(0,0,0,0); this.show = new Date(); this.show.setHours(0,0,0,0); this.current = { year: this.show.getFullYear(), month: this.show.getMonth(), day: this.show.getDate() }; this.preset = []; this.selected = []; this.exclude = []; this.special = []; this.excludeDay = []; this.min = null; this.max = null; this.locale = null; this.minYear = this.current.year - this.options.yearsBefore; this.maxYear = this.current.year + this.options.yearsAfter; this.offset = (new Date()).getTimezoneOffset() / 60 + 1; this._setOptionsFromDOM(); this._create(); return this; }, options: { dayBorder: false, excludeDay: null, prevMonthIcon: "<span class='default-icon-chevron-left'></span>", nextMonthIcon: "<span class='default-icon-chevron-right'></span>", prevYearIcon: "<span class='default-icon-chevron-left'></span>", nextYearIcon: "<span class='default-icon-chevron-right'></span>", compact: false, wide: false, widePoint: null, pickerMode: false, show: null, locale: METRO_LOCALE, weekStart: METRO_WEEK_START, outside: true, buttons: 'cancel, today, clear, done', yearsBefore: 100, yearsAfter: 100, headerFormat: "%A, %b %e", showHeader: true, showFooter: true, showTimeField: true, showWeekNumber: false, clsCalendar: "", clsCalendarHeader: "", clsCalendarContent: "", clsCalendarFooter: "", clsCalendarMonths: "", clsCalendarYears: "", clsToday: "", clsSelected: "", clsExcluded: "", clsCancelButton: "", clsTodayButton: "", clsClearButton: "", clsDoneButton: "", isDialog: false, ripple: false, rippleColor: "#cccccc", exclude: null, preset: null, minDate: null, maxDate: null, weekDayClick: false, weekNumberClick: false, multiSelect: false, special: null, format: METRO_DATE_FORMAT, inputFormat: null, onCancel: Metro.noop, onToday: Metro.noop, onClear: Metro.noop, onDone: Metro.noop, onDayClick: Metro.noop, onDayDraw: Metro.noop, onWeekDayClick: Metro.noop, onWeekNumberClick: Metro.noop, onMonthChange: Metro.noop, onYearChange: Metro.noop, onCalendarCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; element.html("").addClass("calendar " + (o.compact === true ? "compact" : "")).addClass(o.clsCalendar); if (o.dayBorder === true) { element.addClass("day-border"); } if (Utils.isValue(o.excludeDay)) { this.excludeDay = (""+o.excludeDay).toArray(",", "int"); } if (Utils.isValue(o.preset)) { this._dates2array(o.preset, 'selected'); } if (Utils.isValue(o.exclude)) { this._dates2array(o.exclude, 'exclude'); } if (Utils.isValue(o.special)) { this._dates2array(o.special, 'special'); } if (o.buttons !== false) { if (Array.isArray(o.buttons) === false) { o.buttons = o.buttons.split(",").map(function(item){ return item.trim(); }); } } if (o.minDate !== null && Utils.isDate(o.minDate, o.inputFormat)) { this.min = Utils.isValue(o.inputFormat) ? o.minDate.toDate(o.inputFormat) : (new Date(o.minDate)); } if (o.maxDate !== null && Utils.isDate(o.maxDate, o.inputFormat)) { this.max = Utils.isValue(o.inputFormat) ? o.maxDate.toDate(o.inputFormat) : (new Date(o.maxDate)); } if (o.show !== null && Utils.isDate(o.show, o.inputFormat)) { this.show = Utils.isValue(o.inputFormat) ? o.show.toDate(o.inputFormat) : (new Date(o.show)); this.show.setHours(0,0,0,0); this.current = { year: this.show.getFullYear(), month: this.show.getMonth(), day: this.show.getDate() } } this.locale = Metro.locales[o.locale] !== undefined ? Metro.locales[o.locale] : Metro.locales["en-US"]; this._drawCalendar(); this._createEvents(); if (o.wide === true) { element.addClass("calendar-wide"); } else { if (!Utils.isNull(o.widePoint) && Utils.mediaExist(o.widePoint)) { element.addClass("calendar-wide"); } } if (o.ripple === true && Utils.isFunc(element.ripple) !== false) { element.ripple({ rippleTarget: ".button, .prev-month, .next-month, .prev-year, .next-year, .day", rippleColor: this.options.rippleColor }); } Utils.exec(this.options.onCalendarCreate, [this.element]); }, _dates2array: function(val, category){ var that = this, o = this.options; var dates; if (Utils.isNull(val)) { return ; } dates = typeof val === 'string' ? Utils.strToArray(val) : val; $.each(dates, function(){ var _d; if (!Utils.isDateObject(this)) { _d = Utils.isValue(o.inputFormat) ? this.toDate(o.inputFormat) : new Date(this); if (Utils.isDate(_d) === false) { return ; } _d.setHours(0,0,0,0); } else { _d = this; } that[category].push(_d.getTime()); }); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; $(window).on(Metro.events.resize, function(){ if (o.wide !== true) { if (!Utils.isNull(o.widePoint) && Utils.mediaExist(o.widePoint)) { element.addClass("calendar-wide"); } else { element.removeClass("calendar-wide"); } } }); element.on(Metro.events.click, ".prev-month, .next-month, .prev-year, .next-year", function(e){ var new_date, el = $(this); if (el.hasClass("prev-month")) { new_date = new Date(that.current.year, that.current.month - 1, 1); if (new_date.getFullYear() < that.minYear) { return ; } } if (el.hasClass("next-month")) { new_date = new Date(that.current.year, that.current.month + 1, 1); if (new_date.getFullYear() > that.maxYear) { return ; } } if (el.hasClass("prev-year")) { new_date = new Date(that.current.year - 1, that.current.month, 1); if (new_date.getFullYear() < that.minYear) { return ; } } if (el.hasClass("next-year")) { new_date = new Date(that.current.year + 1, that.current.month, 1); if (new_date.getFullYear() > that.maxYear) { return ; } } that.current = { year: new_date.getFullYear(), month: new_date.getMonth(), day: new_date.getDate() }; setTimeout(function(){ that._drawContent(); if (el.hasClass("prev-month") || el.hasClass("next-month")) { Utils.exec(o.onMonthChange, [that.current, element], element[0]); } if (el.hasClass("prev-year") || el.hasClass("next-year")) { Utils.exec(o.onYearChange, [that.current, element], element[0]); } }, o.ripple ? 300 : 1); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".button.today", function(e){ that.toDay(); Utils.exec(o.onToday, [that.today, element]); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".button.clear", function(e){ that.selected = []; that._drawContent(); Utils.exec(o.onClear, [element]); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".button.cancel", function(e){ that._drawContent(); Utils.exec(o.onCancel, [element]); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".button.done", function(e){ that._drawContent(); Utils.exec(o.onDone, [that.selected, element]); e.preventDefault(); e.stopPropagation(); }); if (o.weekDayClick === true) { element.on(Metro.events.click, ".week-days .day", function (e) { var day, index, days; day = $(this); index = day.index(); if (o.multiSelect === true) { days = o.outside === true ? element.find(".days-row .day:nth-child(" + (index + 1) + ")") : element.find(".days-row .day:not(.outside):nth-child(" + (index + 1) + ")"); $.each(days, function () { var d = $(this); var dd = d.data('day'); if (d.hasClass("disabled") || d.hasClass("excluded")) return; if (!that.selected.contains(dd)) that.selected.push(dd); d.addClass("selected").addClass(o.clsSelected); }); } Utils.exec(o.onWeekDayClick, [that.selected, day], element[0]); e.preventDefault(); e.stopPropagation(); }); } if (o.weekNumberClick) { element.on(Metro.events.click, ".days-row .week-number", function (e) { var weekNumElement, weekNumber, days; weekNumElement = $(this); weekNumber = weekNumElement.text(); if (o.multiSelect === true) { days = $(this).siblings(".day"); $.each(days, function () { var d = $(this); var dd = d.data('day'); if (d.hasClass("disabled") || d.hasClass("excluded")) return; if (!that.selected.contains(dd)) that.selected.push(dd); d.addClass("selected").addClass(o.clsSelected); }); } Utils.exec(o.onWeekNumberClick, [that.selected, weekNumber, weekNumElement], element[0]); e.preventDefault(); e.stopPropagation(); }); } element.on(Metro.events.click, ".days-row .day", function(e){ var day = $(this); var index, date; date = day.data('day'); index = that.selected.indexOf(date); if (day.hasClass("outside")) { date = new Date(date); that.current = { year: date.getFullYear(), month: date.getMonth(), day: date.getDate() }; that._drawContent(); return ; } if (!day.hasClass("disabled")) { if (o.pickerMode === true) { that.selected = [date]; that.today = new Date(date); that.current.year = that.today.getFullYear(); that.current.month = that.today.getMonth(); that.current.day = that.today.getDate(); that._drawHeader(); that._drawContent(); } else { if (index === -1) { if (o.multiSelect === false) { element.find(".days-row .day").removeClass("selected").removeClass(o.clsSelected); that.selected = []; } that.selected.push(date); day.addClass("selected").addClass(o.clsSelected); } else { day.removeClass("selected").removeClass(o.clsSelected); Utils.arrayDelete(that.selected, date); } } } Utils.exec(o.onDayClick, [that.selected, day, element]); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".curr-month", function(e){ var target; var list = element.find(".months-list"); list.find(".active").removeClass("active"); list.scrollTop(0); element.find(".calendar-months").addClass("open"); target = list.find(".js-month-"+that.current.month).addClass("active"); setTimeout(function(){ list.animate({ scrollTop: target.position().top - ( (list.height() - target.height() )/ 2) }, 200); }, 300); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".calendar-months li", function(e){ that.current.month = $(this).index(); that._drawContent(); Utils.exec(o.onMonthChange, [that.current, element], element[0]); element.find(".calendar-months").removeClass("open"); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".curr-year", function(e){ var target; var list = element.find(".years-list"); list.find(".active").removeClass("active"); list.scrollTop(0); element.find(".calendar-years").addClass("open"); target = list.find(".js-year-"+that.current.year).addClass("active"); setTimeout(function(){ list.animate({ scrollTop: target.position().top - ( (list.height() - target.height() )/ 2) }, 200); }, 300); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, ".calendar-years li", function(e){ that.current.year = $(this).text(); that._drawContent(); Utils.exec(o.onYearChange, [that.current, element], element[0]); element.find(".calendar-years").removeClass("open"); e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.click, function(e){ var months = element.find(".calendar-months"); var years = element.find(".calendar-years"); if (months.hasClass("open")) { months.removeClass("open"); } if (years.hasClass("open")) { years.removeClass("open"); } e.preventDefault(); e.stopPropagation(); }); }, _drawHeader: function(){ var element = this.element, o = this.options; var header = element.find(".calendar-header"); if (header.length === 0) { header = $("<div>").addClass("calendar-header").addClass(o.clsCalendarHeader).appendTo(element); } header.html(""); $("<div>").addClass("header-year").html(this.today.getFullYear()).appendTo(header); $("<div>").addClass("header-day").html(this.today.format(o.headerFormat, o.locale)).appendTo(header); if (o.showHeader === false) { header.hide(); } }, _drawFooter: function(){ var element = this.element, o = this.options; var buttons_locale = this.locale['buttons']; var footer = element.find(".calendar-footer"); if (o.buttons === false) { return ; } if (footer.length === 0) { footer = $("<div>").addClass("calendar-footer").addClass(o.clsCalendarFooter).appendTo(element); } footer.html(""); $.each(o.buttons, function(){ var button = $("<button>").attr("type", "button").addClass("button " + this + " " + o['cls'+this.capitalize()+'Button']).html(buttons_locale[this]).appendTo(footer); if (this === 'cancel' || this === 'done') { button.addClass("js-dialog-close"); } }); if (o.showFooter === false) { footer.hide(); } }, _drawMonths: function(){ var element = this.element, o = this.options; var months = $("<div>").addClass("calendar-months").addClass(o.clsCalendarMonths).appendTo(element); var list = $("<ul>").addClass("months-list").appendTo(months); var calendar_locale = this.locale['calendar']; var i; for(i = 0; i < 12; i++) { $("<li>").addClass("js-month-"+i).html(calendar_locale['months'][i]).appendTo(list); } }, _drawYears: function(){ var element = this.element, o = this.options; var years = $("<div>").addClass("calendar-years").addClass(o.clsCalendarYears).appendTo(element); var list = $("<ul>").addClass("years-list").appendTo(years); var i; for(i = this.minYear; i <= this.maxYear; i++) { $("<li>").addClass("js-year-"+i).html(i).appendTo(list); } }, _drawContent: function(){ var element = this.element, o = this.options; var content = element.find(".calendar-content"), toolbar; var calendar_locale = this.locale['calendar']; var i, j, d, s, counter = 0; var first = new Date(this.current.year, this.current.month, 1); var first_day; var prev_month_days = (new Date(this.current.year, this.current.month, 0)).getDate(); var year, month; if (content.length === 0) { content = $("<div>").addClass("calendar-content").addClass(o.clsCalendarContent).appendTo(element); } content.html(""); toolbar = $("<div>").addClass("calendar-toolbar").appendTo(content); /** * Calendar toolbar */ $("<span>").addClass("prev-month").html(o.prevMonthIcon).appendTo(toolbar); $("<span>").addClass("curr-month").html(calendar_locale['months'][this.current.month]).appendTo(toolbar); $("<span>").addClass("next-month").html(o.nextMonthIcon).appendTo(toolbar); $("<span>").addClass("prev-year").html(o.prevYearIcon).appendTo(toolbar); $("<span>").addClass("curr-year").html(this.current.year).appendTo(toolbar); $("<span>").addClass("next-year").html(o.nextYearIcon).appendTo(toolbar); /** * Week days */ var week_days = $("<div>").addClass("week-days").appendTo(content); var day_class = "day"; if (o.showWeekNumber === true) { $("<span>").addClass("week-number").html("#").appendTo(week_days); day_class += " and-week-number"; } for (i = 0; i < 7; i++) { if (o.weekStart === 0) { j = i; } else { j = i + 1; if (j === 7) j = 0; } $("<span>").addClass(day_class).html(calendar_locale["days"][j + 7]).appendTo(week_days); } /** * Calendar days */ var days = $("<div>").addClass("days").appendTo(content); var days_row = $("<div>").addClass("days-row").appendTo(days); first_day = o.weekStart === 0 ? first.getDay() : (first.getDay() === 0 ? 6 : first.getDay() - 1); if (this.current.month - 1 < 0) { month = 11; year = this.current.year - 1; } else { month = this.current.month - 1; year = this.current.year; } if (o.showWeekNumber === true) { $("<div>").addClass("week-number").html((new Date(year, month, prev_month_days - first_day + 1)).getWeek(o.weekStart)).appendTo(days_row); } for(i = 0; i < first_day; i++) { var v = prev_month_days - first_day + i + 1; d = $("<div>").addClass(day_class+" outside").appendTo(days_row); s = new Date(year, month, v); s.setHours(0,0,0,0); d.data('day', s.getTime()); if (o.outside === true) { d.html(v); if (this.excludeDay.length > 0) { if (this.excludeDay.indexOf(s.getDay()) > -1) { d.addClass("disabled excluded").addClass(o.clsExcluded); } } Utils.exec(o.onDayDraw, [s], d[0]); } counter++; } first.setHours(0,0,0,0); while(first.getMonth() === this.current.month) { d = $("<div>").addClass(day_class).html(first.getDate()).appendTo(days_row); d.data('day', first.getTime()); // console.log(this.show.getTime() === first.getTime()); if (this.show.getTime() === first.getTime()) { d.addClass("showed"); } // console.log(this.today.getTime() === first.getTime()); if (this.today.getTime() === first.getTime()) { d.addClass("today").addClass(o.clsToday); } if (this.special.length === 0) { if (this.selected.indexOf(first.getTime()) !== -1) { d.addClass("selected").addClass(o.clsSelected); } if (this.exclude.indexOf(first.getTime()) !== -1) { d.addClass("disabled excluded").addClass(o.clsExcluded); } if (this.min !== null && first.getTime() < this.min.getTime()) { d.addClass("disabled excluded").addClass(o.clsExcluded); } if (this.max !== null && first.getTime() > this.max.getTime()) { d.addClass("disabled excluded").addClass(o.clsExcluded); } if (this.excludeDay.length > 0) { if (this.excludeDay.indexOf(first.getDay()) > -1) { d.addClass("disabled excluded").addClass(o.clsExcluded); } } } else { if (this.special.indexOf(first.getTime()) === -1) { d.addClass("disabled excluded").addClass(o.clsExcluded); } } Utils.exec(o.onDayDraw, [first], d[0]); counter++; if (counter % 7 === 0) { days_row = $("<div>").addClass("days-row").appendTo(days); if (o.showWeekNumber === true) { $("<div>").addClass("week-number").html((new Date(first.getFullYear(), first.getMonth(), first.getDate() + 1)).getWeek(o.weekStart)).appendTo(days_row); } } first.setDate(first.getDate() + 1); first.setHours(0,0,0,0); } first_day = o.weekStart === 0 ? first.getDay() : (first.getDay() === 0 ? 6 : first.getDay() - 1); if (this.current.month + 1 > 11) { month = 0; year = this.current.year + 1; } else { month = this.current.month + 1; year = this.current.year; } if (first_day > 0) for(i = 0; i < 7 - first_day; i++) { d = $("<div>").addClass(day_class+" outside").appendTo(days_row); s = new Date(year, month, i + 1); s.setHours(0,0,0,0); d.data('day', s.getTime()); if (o.outside === true) { d.html(i + 1); if (this.excludeDay.length > 0) { if (this.excludeDay.indexOf(s.getDay()) > -1) { d.addClass("disabled excluded").addClass(o.clsExcluded); } } Utils.exec(o.onDayDraw, [s], d[0]); } } }, _drawCalendar: function(){ var that = this; setTimeout(function(){ that.element.html(""); that._drawHeader(); that._drawContent(); that._drawFooter(); that._drawMonths(); that._drawYears(); }, 0); }, getPreset: function(){ return this.preset; }, getSelected: function(){ return this.selected; }, getExcluded: function(){ return this.exclude; }, getToday: function(){ return this.today; }, getCurrent: function(){ return this.current; }, clearSelected: function(){ this.selected = []; this._drawContent(); }, toDay: function(){ this.today = new Date(); this.today.setHours(0,0,0,0); this.current = { year: this.today.getFullYear(), month: this.today.getMonth(), day: this.today.getDate() }; this._drawHeader(); this._drawContent(); }, setExclude: function(exclude){ var that = this, element = this.element, o = this.options; if (Utils.isNull(exclude) && Utils.isNull(element.attr("data-exclude"))) { return ; } o.exclude = !Utils.isNull(exclude) ? exclude : element.attr("data-exclude"); this._dates2array(o.exclude, 'exclude'); this._drawContent(); }, setPreset: function(preset){ var that = this, element = this.element, o = this.options; if (Utils.isNull(preset) && Utils.isNull(element.attr("data-preset"))) { return ; } o.preset = !Utils.isNull(preset) ? preset : element.attr("data-preset"); this._dates2array(o.preset, 'selected'); this._drawContent(); }, setSpecial: function(special){ var that = this, element = this.element, o = this.options; if (Utils.isNull(special) && Utils.isNull(element.attr("data-special"))) { return ; } o.special = !Utils.isNull(special) ? special : element.attr("data-special"); this._dates2array(o.exclude, 'special'); this._drawContent(); }, setShow: function(show){ var that = this, element = this.element, o = this.options; if (Utils.isNull(show) && Utils.isNull(element.attr("data-show"))) { return ; } o.show = !Utils.isNull(show) ? show : element.attr("data-show"); this.show = Utils.isDateObject(show) ? show : Utils.isValue(o.inputFormat) ? o.show.toDate(o.inputFormat) : new Date(o.show); this.show.setHours(0,0,0,0); this.current = { year: this.show.getFullYear(), month: this.show.getMonth(), day: this.show.getDate() }; this._drawContent(); }, setMinDate: function(date){ var that = this, element = this.element, o = this.options; o.minDate = date !== null ? date : element.attr("data-min-date"); this._drawContent(); }, setMaxDate: function(date){ var that = this, element = this.element, o = this.options; o.maxDate = date !== null ? date : element.attr("data-max-date"); this._drawContent(); }, setToday: function(val){ var that = this, element = this.element, o = this.options; if (!Utils.isValue(val)) { val = new Date(); } this.today = Utils.isDateObject(val) ? val : Utils.isValue(o.inputFormat) ? val.toDate(o.inputFormat) : new Date(val); this.today.setHours(0,0,0,0); this._drawHeader(); this._drawContent(); }, i18n: function(val){ var that = this, element = this.element, o = this.options; if (val === undefined) { return o.locale; } if (Metro.locales[val] === undefined) { return false; } o.locale = val; this.locale = Metro.locales[o.locale]; this._drawCalendar(); }, changeAttrLocale: function(){ var that = this, element = this.element, o = this.options; this.i18n(element.attr("data-locale")); }, changeAttribute: function(attributeName){ switch (attributeName) { case 'data-exclude': this.setExclude(); break; case 'data-preset': this.setPreset(); break; case 'data-special': this.setSpecial(); break; case 'data-show': this.setShow(); break; case 'data-min-date': this.setMinDate(); break; case 'data-max-date': this.setMaxDate(); break; case 'data-locale': this.changeAttrLocale(); break; } }, destroy: function(){ var element = this.element, o = this.options; element.off(Metro.events.click, ".prev-month, .next-month, .prev-year, .next-year"); element.off(Metro.events.click, ".button.today"); element.off(Metro.events.click, ".button.clear"); element.off(Metro.events.click, ".button.cancel"); element.off(Metro.events.click, ".button.done"); element.off(Metro.events.click, ".week-days .day"); element.off(Metro.events.click, ".days-row .day"); element.off(Metro.events.click, ".curr-month"); element.off(Metro.events.click, ".calendar-months li"); element.off(Metro.events.click, ".curr-year"); element.off(Metro.events.click, ".calendar-years li"); element.off(Metro.events.click); if (o.ripple === true) Metro.destroyPlugin(element, "ripple"); element.html(""); } }; $(document).on(Metro.events.click, function(e){ $('.calendar .calendar-years').each(function(){ $(this).removeClass("open"); }); $('.calendar .calendar-months').each(function(){ $(this).removeClass("open"); }); }); Metro.plugin('calendar', Calendar); // Source: js/plugins/calendarpicker.js var CalendarPicker = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.value = null; this.value_date = null; this.calendar = null; this.overlay = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onCalendarPickerCreate, [this.element], this.elem); return this; }, dependencies: ['calendar'], options: { nullValue: true, prepend: "", calendarWide: false, calendarWidePoint: null, dialogMode: false, dialogPoint: 360, dialogOverlay: true, overlayColor: '#000000', overlayAlpha: .5, locale: METRO_LOCALE, size: "100%", format: METRO_DATE_FORMAT, inputFormat: null, headerFormat: "%A, %b %e", clearButton: false, calendarButtonIcon: "<span class='default-icon-calendar'></span>", clearButtonIcon: "<span class='default-icon-cross'></span>", copyInlineStyles: false, clsPicker: "", clsInput: "", yearsBefore: 100, yearsAfter: 100, weekStart: METRO_WEEK_START, outside: true, ripple: false, rippleColor: "#cccccc", exclude: null, minDate: null, maxDate: null, special: null, showHeader: true, clsCalendar: "", clsCalendarHeader: "", clsCalendarContent: "", clsCalendarMonths: "", clsCalendarYears: "", clsToday: "", clsSelected: "", clsExcluded: "", onDayClick: Metro.noop, onCalendarPickerCreate: Metro.noop, onCalendarShow: Metro.noop, onCalendarHide: Metro.noop, onChange: Metro.noop, onMonthChange: Metro.noop, onYearChange: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createStructure(); this._createEvents(); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var container = $("<div>").addClass("input " + element[0].className + " calendar-picker"); var buttons = $("<div>").addClass("button-group"); var calendarButton, clearButton, cal = $("<div>").addClass("drop-shadow"); var curr = element.val().trim(); if (element.attr("type") === undefined) { element.attr("type", "text"); } if (!Utils.isValue(curr)) { //this.value = new Date(); } else { this.value = Utils.isValue(o.inputFormat) === false ? new Date(curr) : curr.toDate(o.inputFormat); } if (Utils.isValue(this.value)) this.value.setHours(0,0,0,0); element.val(!Utils.isValue(curr) && o.nullValue === true ? "" : this.value.format(o.format)); if (prev.length === 0) { parent.prepend(container); } else { container.insertAfter(prev); } element.appendTo(container); buttons.appendTo(container); cal.appendTo(container); cal.calendar({ wide: o.calendarWide, widePoint: o.calendarWidePoint, format: o.format, inputFormat: o.inputFormat, pickerMode: true, show: o.value, locale: o.locale, weekStart: o.weekStart, outside: o.outside, buttons: false, headerFormat: o.headerFormat, clsCalendar: o.clsCalendar, clsCalendarHeader: o.clsCalendarHeader, clsCalendarContent: o.clsCalendarContent, clsCalendarFooter: "d-none", clsCalendarMonths: o.clsCalendarMonths, clsCalendarYears: o.clsCalendarYears, clsToday: o.clsToday, clsSelected: o.clsSelected, clsExcluded: o.clsExcluded, ripple: o.ripple, rippleColor: o.rippleColor, exclude: o.exclude, minDate: o.minDate, maxDate: o.maxDate, yearsBefore: o.yearsBefore, yearsAfter: o.yearsAfter, special: o.special, showHeader: o.showHeader, showFooter: false, onDayClick: function(sel, day, el){ var date = new Date(sel[0]); date.setHours(0,0,0,0); that._removeOverlay(); that.value = date; element.val(date.format(o.format, o.locale)); element.trigger("change"); cal.removeClass("open open-up"); cal.hide(); Utils.exec(o.onChange, [that.value], element[0]); Utils.exec(o.onDayClick, [sel, day, el], element[0]); }, onMonthChange: o.onMonthChange, onYearChange: o.onYearChange }); this.calendar = cal; if (o.clearButton === true) { clearButton = $("<button>").addClass("button input-clear-button").attr("tabindex", -1).attr("type", "button").html(o.clearButtonIcon); clearButton.appendTo(buttons); } calendarButton = $("<button>").addClass("button").attr("tabindex", -1).attr("type", "button").html(o.calendarButtonIcon); calendarButton.appendTo(buttons); if (o.prepend !== "") { var prepend = $("<div>").html(o.prepend); prepend.addClass("prepend").addClass(o.clsPrepend).appendTo(container); } if (element.attr('dir') === 'rtl' ) { container.addClass("rtl"); } if (String(o.size).indexOf("%") > -1) { container.css({ width: o.size }); } else { container.css({ width: parseInt(o.size) + "px" }); } element[0].className = ''; element.attr("readonly", true); if (o.copyInlineStyles === true) { $.each(Utils.getInlineStyles(element), function(key, value){ container.css(key, value); }); } container.addClass(o.clsPicker); element.addClass(o.clsInput); if (o.dialogOverlay === true) { this.overlay = that._overlay(); } if (o.dialogMode === true) { container.addClass("dialog-mode"); } else { if (Utils.media("(max-width: "+o.dialogPoint+"px)")) { container.addClass("dialog-mode"); } } if (element.is(":disabled")) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var container = element.parent(); var clear = container.find(".input-clear-button"); var cal = this.calendar; var cal_plugin = cal.data('calendar'); $(window).on(Metro.events.resize, function(){ if (o.dialogMode !== true) { if (Utils.media("(max-width: " + o.dialogPoint + "px)")) { container.addClass("dialog-mode"); } else { container.removeClass("dialog-mode"); } } }); if (clear.length > 0) clear.on(Metro.events.click, function(e){ element.val("").trigger('change').blur(); that.value = null; e.preventDefault(); e.stopPropagation(); }); container.on(Metro.events.click, "button, input", function(e){ var value = Utils.isValue(that.value) ? that.value : new Date(); value.setHours(0,0,0,0); if (cal.hasClass("open") === false && cal.hasClass("open-up") === false) { $(".calendar-picker .calendar").removeClass("open open-up").hide(); cal_plugin.setPreset([value]); cal_plugin.setShow(value); cal_plugin.setToday(value); if (container.hasClass("dialog-mode")) { that.overlay.appendTo($('body')); } cal.addClass("open"); if (Utils.isOutsider(cal) === false) { cal.addClass("open-up"); } Utils.exec(o.onCalendarShow, [element, cal], cal); } else { that._removeOverlay(); cal.removeClass("open open-up"); Utils.exec(o.onCalendarHide, [element, cal], cal); } e.preventDefault(); e.stopPropagation(); }); element.on(Metro.events.blur, function(){container.removeClass("focused");}); element.on(Metro.events.focus, function(){container.addClass("focused");}); element.on(Metro.events.change, function(){ Utils.exec(o.onChange, [that.value], element[0]); }); }, _overlay: function(){ var o = this.options; var overlay = $("<div>"); overlay.addClass("overlay for-calendar-picker").addClass(o.clsOverlay); if (o.overlayColor === 'transparent') { overlay.addClass("transparent"); } else { overlay.css({ background: Utils.hex2rgba(o.overlayColor, o.overlayAlpha) }); } return overlay; }, _removeOverlay: function(){ $('body').find('.overlay.for-calendar-picker').remove(); }, val: function(v){ var element = this.element, o = this.options; if (Utils.isNull(v)) { return this.value; } if (Utils.isDate(v, o.inputFormat) === true) { this.calendar.data("calendar").clearSelected(); this.value = typeof v === 'string' ? v.toDate(o.inputFormat) : v; element.val(this.value.format(o.format)); element.trigger("change"); } }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, i18n: function(val){ var o = this.options; var hidden; var cal = this.calendar; if (val === undefined) { return o.locale; } if (Metro.locales[val] === undefined) { return false; } hidden = cal.is(':hidden'); if (hidden) { cal.css({ visibility: "hidden", display: "block" }); } cal.data('calendar').i18n(val); if (hidden) { cal.css({ visibility: "visible", display: "none" }); } }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var cal = this.calendar.data("calendar"); var changeAttrLocale = function(){ that.i18n(element.attr("data-locale")); }; var changeAttrSpecial = function(){ cal.setSpecial(element.attr("data-special")); }; var changeAttrExclude = function(){ cal.setExclude(element.attr("data-exclude")); }; var changeAttrMinDate = function(){ cal.setMinDate(element.attr("data-min-date")); }; var changeAttrMaxDate = function(){ cal.setMaxDate(element.attr("data-max-date")); }; var changeAttrValue = function(){ that.val(element.attr("value")); }; switch (attributeName) { case "value": changeAttrValue(); break; case 'disabled': this.toggleState(); break; case 'data-locale': changeAttrLocale(); break; case 'data-special': changeAttrSpecial(); break; case 'data-exclude': changeAttrExclude(); break; case 'data-min-date': changeAttrMinDate(); break; case 'data-max-date': changeAttrMaxDate(); break; } } }; Metro.plugin('calendarpicker', CalendarPicker); $(document).on(Metro.events.click, ".overlay.for-calendar-picker",function(){ $(this).remove(); }); $(document).on(Metro.events.click, function(){ $(".calendar-picker .calendar").removeClass("open open-up"); }); // Source: js/plugins/carousel.js var Carousel = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.height = 0; this.width = 0; this.slides = []; this.current = null; this.currentIndex = null; this.dir = this.options.direction; this.interval = null; this.isAnimate = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { autoStart: false, width: "100%", height: "16/9", // 3/4, 21/9 effect: "slide", // slide, fade, switch, slowdown, custom effectFunc: "linear", direction: "left", //left, right duration: METRO_ANIMATION_DURATION, period: 5000, stopOnMouse: true, controls: true, bullets: true, bulletsStyle: "square", // square, circle, rect, diamond bulletsSize: "default", // default, mini, small, large controlsOnMouse: false, controlsOutside: false, bulletsPosition: "default", // default, left, right controlPrev: '&#x23F4', controlNext: '&#x23F5', clsCarousel: "", clsSlides: "", clsSlide: "", clsControls: "", clsControlNext: "", clsControlPrev: "", clsBullets: "", clsBullet: "", clsBulletOn: "", clsThumbOn: "", onStop: Metro.noop, onStart: Metro.noop, onPlay: Metro.noop, onSlideClick: Metro.noop, onBulletClick: Metro.noop, onThumbClick: Metro.noop, onMouseEnter: Metro.noop, onMouseLeave: Metro.noop, onNextClick: Metro.noop, onPrevClick: Metro.noop, onSlideShow: Metro.noop, onSlideHide: Metro.noop, onCarouselCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; var slides = element.find(".slide"); var slides_container = element.find(".slides"); var maxHeight = 0; var id = Utils.elementId("carousel"); if (element.attr("id") === undefined) { element.attr("id", id); } element.addClass("carousel").addClass(o.clsCarousel); if (o.controlsOutside === true) { element.addClass("controls-outside"); } if (slides_container.length === 0) { slides_container = $("<div>").addClass("slides").appendTo(element); slides.appendTo(slides_container); } slides.addClass(o.clsSlides); if (slides.length === 0) { Utils.exec(this.options.onCarouselCreate, [this.element]); return ; } this._createSlides(); this._createControls(); this._createBullets(); this._createEvents(); this._resize(); if (o.controlsOnMouse === true) { element.find("[class*=carousel-switch]").hide(); element.find(".carousel-bullets").hide(); } if (o.autoStart === true) { this._start(); } else { Utils.exec(o.onSlideShow, [this.slides[this.currentIndex][0], undefined], this.slides[this.currentIndex][0]); } Utils.exec(this.options.onCarouselCreate, [this.element]); }, _start: function(){ var that = this, element = this.element, o = this.options; var period = o.period; var current = this.slides[this.currentIndex]; if (current.data("period") !== undefined) { period = current.data("period"); } if (this.slides.length <= 1) { return ; } this.interval = setTimeout(function run() { var t = o.direction === 'left' ? 'next' : 'prior'; that._slideTo(t, true); }, period); Utils.exec(o.onStart, [element], element[0]); }, _stop: function(){ clearInterval(this.interval); this.interval = false; }, _resize: function(){ var that = this, element = this.element, o = this.options; var width = element.outerWidth(); var height; var medias = []; if (["16/9", "21/9", "4/3"].indexOf(o.height) > -1) { height = Utils.aspectRatioH(width, o.height); } else { if (String(o.height).indexOf("@") > -1) { medias = Utils.strToArray(o.height.substr(1), "|"); $.each(medias, function(){ var media = Utils.strToArray(this, ","); if (window.matchMedia(media[0]).matches) { if (["16/9", "21/9", "4/3"].indexOf(media[1]) > -1) { height = Utils.aspectRatioH(width, media[1]); } else { height = parseInt(media[1]); } } }); } else { height = parseInt(o.height); } } element.css({ height: height }); }, _createSlides: function(){ var that = this, element = this.element, o = this.options; var slides = element.find(".slide"); $.each(slides, function(i){ var slide = $(this); if (slide.data("cover") !== undefined) { slide.css({ backgroundImage: "url("+slide.data('cover')+")", backgroundSize: "cover", backgroundRepeat: "no-repeat" }); } if (i !== 0) { switch (o.effect) { case "switch": case "slide": slide.css("left", "100%"); break; case "slide-v": slide.css("top", "100%"); break; case "fade": slide.css("opacity", "0"); break; } } slide.addClass(o.clsSlide); that.slides.push(slide); }); this.currentIndex = 0; this.current = this.slides[this.currentIndex]; }, _createControls: function(){ var element = this.element, o = this.options; var next, prev; if (o.controls === false) { return ; } next = $('<span/>').addClass('carousel-switch-next').addClass(o.clsControls).addClass(o.clsControlNext).html(">"); prev = $('<span/>').addClass('carousel-switch-prev').addClass(o.clsControls).addClass(o.clsControlPrev).html("<"); if (o.controlNext) { next.html(o.controlNext); } if (o.controlPrev) { prev.html(o.controlPrev); } next.appendTo(element); prev.appendTo(element); }, _createBullets: function(){ var element = this.element, o = this.options; var bullets, i; if (o.bullets === false) { return ; } bullets = $('<div>').addClass("carousel-bullets").addClass(o.bulletsSize+"-size").addClass("bullet-style-"+o.bulletsStyle).addClass(o.clsBullets); if (o.bulletsPosition === 'default' || o.bulletsPosition === 'center') { bullets.addClass("flex-justify-center"); } else if (o.bulletsPosition === 'left') { bullets.addClass("flex-justify-start"); } else { bullets.addClass("flex-justify-end"); } for (i = 0; i < this.slides.length; i++) { var bullet = $('<span>').addClass("carousel-bullet").addClass(o.clsBullet).data("slide", i); if (i === 0) { bullet.addClass('bullet-on').addClass(o.clsBulletOn); } bullet.appendTo(bullets); } bullets.appendTo(element); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".carousel-bullet", function(e){ var bullet = $(this); if (that.isAnimate === false) { that._slideToSlide(bullet.data('slide')); Utils.exec(o.onBulletClick, [bullet, element, e]) } }); element.on(Metro.events.click, ".carousel-switch-next", function(e){ if (that.isAnimate === false) { that._slideTo("next", false); Utils.exec(o.onNextClick, [element, e]) } }); element.on(Metro.events.click, ".carousel-switch-prev", function(e){ if (that.isAnimate === false) { that._slideTo("prev", false); Utils.exec(o.onPrevClick, [element, e]) } }); if (o.stopOnMouse === true && o.autoStart === true) { element.on(Metro.events.enter, function (e) { if (o.controlsOnMouse === true) { element.find("[class*=carousel-switch]").fadeIn(); element.find(".carousel-bullets").fadeIn(); } that._stop(); Utils.exec(o.onMouseEnter, [element, e]) }); element.on(Metro.events.leave, function (e) { if (o.controlsOnMouse === true) { element.find("[class*=carousel-switch]").fadeOut(); element.find(".carousel-bullets").fadeOut(); } that._start(); Utils.exec(o.onMouseLeave, [element, e]) }); } if (o.controlsOnMouse === true) { element.on(Metro.events.enter, function () { element.find("[class*=carousel-switch]").fadeIn(); element.find(".carousel-bullets").fadeIn(); }); element.on(Metro.events.leave, function () { element.find("[class*=carousel-switch]").fadeOut(); element.find(".carousel-bullets").fadeOut(); }); } element.on(Metro.events.click, ".slide", function(e){ var slide = $(this); Utils.exec(o.onSlideClick, [slide, element, e]) }); $(window).on(Metro.events.resize + "-" + element.attr("id"), function(){ that._resize(); }); }, _slideToSlide: function(index){ var element = this.element, o = this.options; var current, next, to; if (this.slides[index] === undefined) { return ; } if (this.currentIndex === index) { return ; } to = index > this.currentIndex ? "next" : "prev"; current = this.slides[this.currentIndex]; next = this.slides[index]; this.currentIndex = index; this._effect(current, next, o.effect, to); element.find(".carousel-bullet").removeClass("bullet-on").removeClass(o.clsBulletOn); element.find(".carousel-bullet:nth-child("+(this.currentIndex+1)+")").addClass("bullet-on").addClass(o.clsBulletOn); }, _slideTo: function(to, interval){ var that = this, element = this.element, o = this.options; var current, next; if (to === undefined) { to = "next"; } current = this.slides[this.currentIndex]; if (to === "next") { this.currentIndex++; if (this.currentIndex >= this.slides.length) { this.currentIndex = 0; } } else { this.currentIndex--; if (this.currentIndex < 0) { this.currentIndex = this.slides.length - 1; } } next = this.slides[this.currentIndex]; this._effect(current, next, o.effect, to, interval); element.find(".carousel-bullet").removeClass("bullet-on").removeClass(o.clsBulletOn); element.find(".carousel-bullet:nth-child("+(this.currentIndex+1)+")").addClass("bullet-on").addClass(o.clsBulletOn); }, _effect: function(current, next, effect, to, interval){ var that = this, element = this.element, o = this.options; var duration = o.duration; var func, effectFunc = o.effectFunc; var period = o.period; if (next.data('duration') !== undefined) { duration = next.data('duration'); } if (next.data('effectFunc') !== undefined) { effectFunc = next.data('effectFunc'); } if (effect === 'switch') { duration = 0; } current.stop(true, true); next.stop(true, true); this.isAnimate = true; setTimeout(function(){that.isAnimate = false;}, duration); if (effect === 'slide') { func = to === 'next' ? 'slideLeft': 'slideRight'; } if (effect === 'slide-v') { func = to === 'next' ? 'slideUp': 'slideDown'; } switch (effect) { case 'slide': Animation[func](current, next, duration, effectFunc); break; case 'slide-v': Animation[func](current, next, duration, effectFunc); break; case 'fade': Animation['fade'](current, next, duration, effectFunc); break; default: Animation['switch'](current, next); } setTimeout(function(){ Utils.exec(o.onSlideShow, [next[0], current[0]], next[0]); }, duration); setTimeout(function(){ Utils.exec(o.onSlideHide, [current[0], next[0]], current[0]); }, duration); if (interval === true) { if (next.data('period') !== undefined) { period = next.data('period'); } this.interval = setTimeout(function run() { var t = o.direction === 'left' ? 'next' : 'prior'; that._slideTo(t, true); }, period); } }, toSlide: function(index){ this._slideToSlide(index); }, next: function(){ this._slideTo("next"); }, prev: function(){ this._slideTo("prev"); }, stop: function () { clearInterval(this.interval); Utils.exec(this.options.onStop, [this.element]) }, play: function(){ this._start(); Utils.exec(this.options.onPlay, [this.element]) }, changeAttribute: function(attributeName){ }, destroy: function(){ var that = this, element = this.element, o = this.options; element.off(Metro.events.click, ".carousel-bullet"); element.off(Metro.events.click, ".carousel-switch-next"); element.off(Metro.events.click, ".carousel-switch-prev"); if (o.stopOnMouse === true && o.autoStart === true) { element.off(Metro.events.enter); element.off(Metro.events.leave); } if (o.controlsOnMouse === true) { element.off(Metro.events.enter); element.off(Metro.events.leave); } element.off(Metro.events.click, ".slide"); $(window).off(Metro.events.resize + "-" + element.attr("id")); element.removeClass("carousel").removeClass(o.clsCarousel); if (o.controlsOutside === true) { element.removeClass("controls-outside"); } } }; Metro.plugin('carousel', Carousel); // Source: js/plugins/charms.js var Charms = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.origin = { background: "" }; this._setOptionsFromDOM(); this._create(); return this; }, options: { position: "right", opacity: 1, clsCharms: "", onCharmCreate: Metro.noop, onOpen: Metro.noop, onClose: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onCharmCreate, [element]); }, _createStructure: function(){ var element = this.element, o = this.options; element .addClass("charms") .addClass(o.position + "-side") .addClass(o.clsCharms); this.origin.background = element.css("background-color"); element.css({ backgroundColor: Utils.computedRgbToRgba(Utils.getStyleOne(element, "background-color"), o.opacity) }); }, _createEvents: function(){ var element = this.element, o = this.options; element.on(Metro.events.click, function(e){ }); }, open: function(){ var element = this.element, o = this.options; element.addClass("open"); Utils.exec(o.onOpen, [element]); }, close: function(){ var element = this.element, o = this.options; element.removeClass("open"); Utils.exec(o.onClose, [element]); }, toggle: function(){ var element = this.element, o = this.options; element.toggleClass("open"); if (element.hasClass("open") === true) { Utils.exec(o.onOpen, [element]); } else { Utils.exec(o.onClose, [element]); } }, opacity: function(v){ var element = this.element, o = this.options; if (v === undefined) { return o.opacity; } var opacity = Math.abs(parseFloat(v)); if (opacity < 0 || opacity > 1) { return ; } o.opacity = opacity; element.css({ backgroundColor: Utils.computedRgbToRgba(Utils.getStyleOne(element, "background-color"), opacity) }); }, changeOpacity: function(){ var element = this.element; this.opacity(element.attr("data-opacity")); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-opacity": this.changeOpacity(); break; } }, destroy: function(){ var element = this.element, o = this.options; element.off(Metro.events.click); element .removeClass("charms") .removeClass(o.position + "-side") .removeClass(o.clsCharms); element.css("background-color", this.origin.background); } }; Metro.plugin('charms', Charms); Metro['charms'] = { check: function(el){ if (Utils.isMetroObject(el, "charms") === false) { console.log("Element is not a charms component"); return false; } return true; }, isOpen: function(el){ if (this.check(el) === false) return ; var charms = $(el).data("charms"); return charms.hasClass("open"); }, open: function(el){ if (this.check(el) === false) return ; var charms = $(el).data("charms"); charms.open(); }, close: function(el){ if (this.check(el) === false) return ; var charms = $(el).data("charms"); charms.close(); }, toggle: function(el){ if (this.check(el) === false) return ; var charms = $(el).data("charms"); charms.toggle(); }, closeAll: function(){ $('[data-role*=charms]').each(function() { $(this).data('charms').close(); }); }, opacity: function(el, opacity){ if (this.check(el) === false) return ; var charms = $(el).data("charms"); charms.opacity(opacity); } }; // Source: js/plugins/checkbox.js var Checkbox = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.origin = { className: "" }; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onCheckboxCreate, [this.element]); return this; }, options: { style: 1, caption: "", captionPosition: "right", indeterminate: false, clsCheckbox: "", clsCheck: "", clsCaption: "", onCheckboxCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; var checkbox = $("<label>").addClass("checkbox " + element[0].className).addClass(o.style === 2 ? "style2" : ""); var check = $("<span>").addClass("check"); var caption = $("<span>").addClass("caption").html(o.caption); if (element.attr('id') === undefined) { element.attr('id', Utils.elementId("checkbox")); } checkbox.attr('for', element.attr('id')); element.attr("type", "checkbox"); checkbox.insertBefore(element); element.appendTo(checkbox); check.appendTo(checkbox); caption.appendTo(checkbox); if (o.captionPosition === 'left') { checkbox.addClass("caption-left"); } this.origin.className = element[0].className; element[0].className = ''; checkbox.addClass(o.clsCheckbox); caption.addClass(o.clsCaption); check.addClass(o.clsCheck); if (o.indeterminate) { element[0].indeterminate = true; } if (element.is(':disabled')) { this.disable(); } else { this.enable(); } }, indeterminate: function(){ this.element[0].indeterminate = true; }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ var element = this.element, o = this.options; var parent = element.parent(); var changeStyle = function(){ var new_style = parseInt(element.attr("data-style")); if (!Utils.isInt(new_style)) return; o.style = new_style; parent.removeClass("style1 style2").addClass("style"+new_style); }; var indeterminateState = function(){ element[0].indeterminate = JSON.parse(element.attr("data-indeterminate")) === true; }; switch (attributeName) { case 'disabled': this.toggleState(); break; case 'data-indeterminate': indeterminateState(); break; case 'data-style': changeStyle(); break; } }, destroy: function(){ var element = this.element; var parent = element.parent(); element[0].className = this.origin.className; element.insertBefore(parent); parent.remove(); } }; Metro.plugin('checkbox', Checkbox); // Source: js/plugins/clock.js var Clock = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._clockInterval = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onClockCreate, [this.element]); return this; }, options: { showTime: true, showDate: true, timeFormat: '24', dateFormat: 'american', divider: "&nbsp;&nbsp;", onClockCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this; this._tick(); this._clockInterval = setInterval(function(){ that._tick(); }, 500); }, _addLeadingZero: function(i){ if (i<10){i="0" + i;} return i; }, _tick: function(){ var that = this, element = this.element, o = this.options; var timestamp = new Date(); var time = timestamp.getTime(); var result = ""; var h = timestamp.getHours(), i = timestamp.getMinutes(), s = timestamp.getSeconds(), d = timestamp.getDate(), m = timestamp.getMonth() + 1, y = timestamp.getFullYear(), a = ''; if (o.timeFormat === '12') { a = " AM"; if (h > 11) { a = " PM"; } if (h > 12) { h = h - 12; } if (h === 0) { h = 12; } } h = this._addLeadingZero(h); i = this._addLeadingZero(i); s = this._addLeadingZero(s); m = this._addLeadingZero(m); d = this._addLeadingZero(d); if (o.showDate) { if (o.dateFormat === 'american') { result += "<span class='date-month'>" + m + "</span>"; result += "<span class='date-divider'>-</span>"; result += "<span class='date-day'>" + d + "</span>"; result += "<span class='date-divider'>-</span>"; result += "<span class='date-year'>" + y + "</span>"; } else { result += "<span class='date-day'>" + d + "</span>"; result += "<span class='date-divider'>-</span>"; result += "<span class='date-month'>" + m + "</span>"; result += "<span class='date-divider'>-</span>"; result += "<span class='date-year'>" + y + "</span>"; } result += o.divider; } if (o.showTime) { result += "<span class='clock-hour'>" + h + "</span>"; result += "<span class='clock-divider'>:</span>"; result += "<span class='clock-minute'>" + i + "</span>"; result += "<span class='clock-divider'>:</span>"; result += "<span class='clock-second'>" + s + "</span>"; } element.html(result); }, changeAttribute: function(attributeName){ }, destroy: function(){ clearInterval(this._clockInterval); this._clockInterval = null; this.element.html(""); } }; Metro.plugin('clock', Clock); // Source: js/plugins/collapse.js var Collapse = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.toggle = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onCollapseCreate, [this.element]); return this; }, options: { collapsed: false, toggleElement: false, duration: METRO_ANIMATION_DURATION, onExpand: Metro.noop, onCollapse: Metro.noop, onCollapseCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var toggle; toggle = o.toggleElement !== false ? $(o.toggleElement) : element.siblings('.collapse-toggle').length > 0 ? element.siblings('.collapse-toggle') : element.siblings('a:nth-child(1)'); if (o.collapsed === true || element.attr("collapsed") === true) { element.hide(0); } toggle.on(Metro.events.click, function(e){ console.log("ku"); if (element.css('display') === 'block' && !element.hasClass('keep-open')) { that._close(element); } else { that._open(element); } if (["INPUT"].indexOf(e.target.tagName) === -1) { e.preventDefault(); } e.stopPropagation(); }); this.toggle = toggle; }, _close: function(el){ if (Utils.isJQueryObject(el) === false) { el = $(el); } var dropdown = el.data("collapse"); var options = dropdown.options; this.toggle.removeClass("active-toggle"); el.slideUp(options.duration, function(){ el.trigger("onCollapse", null, el); el.data("collapsed", true); el.addClass("collapsed"); Utils.exec(options.onCollapse, [el]); }); }, _open: function(el){ if (Utils.isJQueryObject(el) === false) { el = $(el); } var dropdown = el.data("collapse"); var options = dropdown.options; this.toggle.addClass("active-toggle"); el.slideDown(options.duration, function(){ el.trigger("onExpand", null, el); el.data("collapsed", false); el.removeClass("collapsed"); Utils.exec(options.onExpand, [el]); }); }, collapse: function(){ this._close(this.element); }, expand: function(){ this._open(this.element); }, isCollapsed: function(){ return this.element.data("collapsed"); }, toggleState: function(){ var element = this.element; if (element.attr("collapsed") === true || element.data("collapsed") === true) { this.collapse(); } else { this.expand(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case "collapsed": case "data-collapsed": this.toggleState(); break; } }, destroy: function(){ this.toggle.off(Metro.events.click); this.element.show(); } }; Metro.plugin('collapse', Collapse); // Source: js/plugins/countdown.js var Countdown = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.breakpoint = (new Date()).getTime(); this.blinkInterval = null; this.tickInterval = null; this.zeroDaysFired = false; this.zeroHoursFired = false; this.zeroMinutesFired = false; this.zeroSecondsFired = false; this.current = { d: 0, h: 0, m: 0, s: 0 }; this.locale = null; this.inactiveTab = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { stopOnBlur: true, animate: "none", animationFunc: "swing", inputFormat: null, locale: METRO_LOCALE, days: 0, hours: 0, minutes: 0, seconds: 0, date: null, start: true, clsCountdown: "", clsPart: "", clsZero: "", clsAlarm: "", clsDays: "", clsHours: "", clsMinutes: "", clsSeconds: "", onAlarm: Metro.noop, onTick: Metro.noop, onZero: Metro.noop, onBlink: Metro.noop, onCountdownCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var o = this.options; this.locale = Metro.locales[o.locale] !== undefined ? Metro.locales[o.locale] : Metro.locales["en-US"]; this._build(); this._createEvents(); }, _setBreakpoint: function(){ var o = this.options; var dm = 86400000, hm = 3600000, mm = 60000, sm = 1000; this.breakpoint = (new Date()).getTime(); if (Utils.isValue(o.date) && Utils.isDate(o.date, o.inputFormat)) { this.breakpoint = Utils.isValue(o.inputFormat) ? (o.date.toDate(o.inputFormat)).getTime() : (new Date(o.date)).getTime(); } if (parseInt(o.days) > 0) { this.breakpoint += parseInt(o.days) * dm; } if (parseInt(o.hours) > 0) { this.breakpoint += parseInt(o.hours) * hm; } if (parseInt(o.minutes) > 0) { this.breakpoint += parseInt(o.minutes) * mm; } if (parseInt(o.seconds) > 0) { this.breakpoint += parseInt(o.seconds) * sm; } }, _build: function(){ var that = this, element = this.element, o = this.options; var parts = ["days", "hours", "minutes", "seconds"]; var dm = 24*60*60*1000; var delta_days; var now = (new Date()).getTime(); var digit; if (!Utils.isValue(element.attr("id"))) { element.attr("id", Utils.elementId("countdown")); } element.addClass("countdown").addClass(o.clsCountdown); this._setBreakpoint(); delta_days = Math.round((that.breakpoint - now) / dm); $.each(parts, function(){ var part = $("<div>").addClass("part " + this).addClass(o.clsPart).attr("data-label", that.locale["calendar"]["time"][this]).appendTo(element); if (this === "days") {part.addClass(o.clsDays);} if (this === "hours") {part.addClass(o.clsHours);} if (this === "minutes") {part.addClass(o.clsMinutes);} if (this === "seconds") {part.addClass(o.clsSeconds);} $("<div>").addClass("digit").appendTo(part); $("<div>").addClass("digit").appendTo(part); if (this === "days" && delta_days >= 100) { for(var i = 0; i < String(Math.round(delta_days/100)).length; i++) { $("<div>").addClass("digit").appendTo(part); } } }); digit = element.find(".digit"); digit.append($("<span class='digit-placeholder'>").html("0")); digit.append($("<span class='digit-value'>").html("0")); Utils.exec(o.onCountdownCreate, [element], element[0]); if (o.start === true) { this.start(); } else { this.tick(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; // if (o.stopOnBlur === true) { $(window).on(Metro.events.blur+"-"+element.attr("id"), function(){ // that.pause(); that.inactiveTab = true; }); $(window).on(Metro.events.focus+"-"+element.attr("id"), function(){ // that.resume(); that.inactiveTab = false; }); // } }, blink: function(){ var element = this.element, o = this.options; element.toggleClass("blink"); Utils.exec(o.onBlink, [this.current], element[0]); }, tick: function(){ var element = this.element, o = this.options; var dm = 24*60*60, hm = 60*60, mm = 60, sm = 1; var left, now = (new Date()).getTime(); var d, h, m, s; var days = element.find(".days"), hours = element.find(".hours"), minutes = element.find(".minutes"), seconds = element.find(".seconds"); left = Math.floor((this.breakpoint - now)/1000); if (left <= -1) { this.stop(); element.addClass(o.clsAlarm); Utils.exec(o.onAlarm, [now], element[0]); return ; } d = Math.floor(left / dm); left -= d * dm; if (this.current.d !== d) { this.current.d = d; this.draw("days", d); } if (d === 0) { if (this.zeroDaysFired === false) { this.zeroDaysFired = true; days.addClass(o.clsZero); Utils.exec(o.onZero, ["days", days], element[0]); } } h = Math.floor(left / hm); left -= h*hm; if (this.current.h !== h) { this.current.h = h; this.draw("hours", h); } if (d === 0 && h === 0) { if (this.zeroHoursFired === false) { this.zeroHoursFired = true; hours.addClass(o.clsZero); Utils.exec(o.onZero, ["hours", hours], element[0]); } } m = Math.floor(left / mm); left -= m*mm; if (this.current.m !== m) { this.current.m = m; this.draw("minutes", m); } if (d === 0 && h === 0 && m === 0) { if (this.zeroMinutesFired === false) { this.zeroMinutesFired = true; minutes.addClass(o.clsZero); Utils.exec(o.onZero, ["minutes", minutes], element[0]); } } s = Math.floor(left / sm); if (this.current.s !== s) { this.current.s = s; this.draw("seconds", s); } if (d === 0 && h === 0 && m === 0 && s === 0) { if (this.zeroSecondsFired === false) { this.zeroSecondsFired = true; seconds.addClass(o.clsZero); Utils.exec(o.onZero, ["seconds", seconds], element[0]); } } Utils.exec(o.onTick, [{days:d, hours:h, minutes:m, seconds:s}], element[0]); }, draw: function(part, value){ var that = this, element = this.element, o = this.options; var digits, digits_length, digit_value, digit_current, digit, digit_copy; var len, i, duration = 900, height; var removeOldDigit = function(_digit){ if (!document.hidden) { setTimeout(function(){ _digit.remove(); }, 500); } else { _digit.remove(); } }; var slideDigit = function(digit){ var digit_copy, height = digit.height(); digit_copy = digit.clone().appendTo(digit.parent()); digit_copy.css({ top: -1 * height, opacity: .5 }); digit.addClass("-old-digit").animate({ top: height, opacity: 0 }, duration, o.animationFunc, removeOldDigit(digit)); digit_copy.html(digit_value).animate({ top: 0, opacity: 1 }, duration, o.animationFunc); }; var fadeDigit = function(digit){ var digit_copy; digit_copy = digit.clone().appendTo(digit.parent()); digit_copy.css({ opacity: 0 }); digit.addClass("-old-digit").animate({ opacity: 0 }, duration, o.animationFunc, removeOldDigit(digit)); digit_copy.html(digit_value).animate({ opacity: 1 }, duration, o.animationFunc); }; var zoomDigit = function(digit){ var digit_copy, height = digit.height(), width = digit.width(), fs = parseInt(Utils.getStyleOne(digit, "font-size")); digit_copy = digit.clone().appendTo(digit.parent()); digit_copy.css({ opacity: 0, fontSize: 0, top: height/2, left: width/2 }); digit.addClass("-old-digit").animate({ opacity: 0, fontSize: 0, top: height, left: width/2 }, duration, o.animationFunc, removeOldDigit(digit)); digit_copy.html(digit_value).animate({ opacity: 1, fontSize: fs, top: 0, left: 0 }, duration, o.animationFunc); }; value = String(value); if (value.length === 1) { value = '0'+value; } len = value.length; digits = element.find("."+part+" .digit"); digits_length = digits.length; for(i = 0; i < len; i++){ digit = element.find("." + part + " .digit:eq("+ (digits_length - 1) +") .digit-value"); digit_value = Math.floor( value / Math.pow(10, i) ) % 10; digit_current = parseInt(digit.text()); if (digit_current === digit_value) { continue; } switch (String(o.animate).toLowerCase()) { case "slide": slideDigit(digit); break; case "fade": fadeDigit(digit); break; case "zoom": zoomDigit(digit); break; default: digit.html(digit_value); } digits_length--; } }, start: function(){ var that = this, element = this.element; if (element.data("paused") === false) { return; } clearInterval(this.blinkInterval); clearInterval(this.tickInterval); element.data("paused", false); this._setBreakpoint(); this.tick(); this.blinkInterval = setInterval(function(){that.blink();}, 500); this.tickInterval = setInterval(function(){that.tick();}, 1000); }, stop: function(){ var element = this.element; clearInterval(this.blinkInterval); clearInterval(this.tickInterval); element.data("paused", true); element.find(".digit").html("0"); this.current = { d: 0, h:0, m: 0, s:0 }; }, pause: function(){ clearInterval(this.blinkInterval); clearInterval(this.tickInterval); this.element.data("paused", true); }, resume: function(){ var that = this; this.element.data("paused", false); this.blinkInterval = setInterval(function(){that.blink();}, 500); this.tickInterval = setInterval(function(){that.tick();}, 1000); }, reset: function(){ var that = this, element = this.element, o = this.options; clearInterval(this.blinkInterval); clearInterval(this.tickInterval); element.find(".part").removeClass(o.clsZero); element.find(".digit").html("0"); this._setBreakpoint(); element.data("paused", false); this.tick(); this.blinkInterval = setInterval(function(){that.blink();}, 500); this.tickInterval = setInterval(function(){that.tick();}, 1000); }, togglePlay: function(){ if (this.element.attr("data-pause") === true) { this.pause(); } else { this.start(); } }, isPaused: function(){ return this.element.data("paused"); }, getBreakpoint: function(asDate){ return asDate === true ? new Date(this.breakpoint) : this.breakpoint; }, getLeft: function(){ var dm = 24*60*60*1000, hm = 60*60*1000, mm = 60*1000, sm = 1000; var now = (new Date()).getTime(); var left_seconds = Math.floor(this.breakpoint - now); return { days: Math.round(left_seconds / dm), hours: Math.round(left_seconds / hm), minutes: Math.round(left_seconds / mm), seconds: Math.round(left_seconds / sm) }; }, i18n: function(val){ var that = this, element = this.element, o = this.options; var parts = ["days", "hours", "minutes", "seconds"]; if (val === undefined) { return o.locale; } if (Metro.locales[val] === undefined) { return false; } o.locale = val; this.locale = Metro.locales[o.locale]; $.each(parts, function(){ var cls = ".part." + this; var part = element.find(cls); part.attr("data-label", that.locale["calendar"]["time"][this]); }); }, changeAttrLocale: function(){ var element = this.element; var locale = element.attr('data-locale'); this.i18n(locale); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-pause": this.togglePlay(); break; case "data-locale": this.changeAttrLocale(); break; } }, destroy: function(){ clearInterval(this.blinkInterval); clearInterval(this.tickInterval); this.element.html(""); this.element.removeClass("countdown").removeClass(this.options.clsCountdown); } }; Metro.plugin('countdown', Countdown); // Source: js/plugins/counter.js var Counter = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.numbers = []; this.html = this.element.html(); this._setOptionsFromDOM(); this._create(); return this; }, options: { delay: 10, step: 1, value: 0, timeout: null, delimiter: ",", onStart: Metro.noop, onStop: Metro.noop, onTick: Metro.noop, onCounterCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._calcArray(); Utils.exec(o.onCounterCreate, [element], this.elem); if (o.timeout !== null && Utils.isInt(o.timeout)) { setTimeout(function () { that.start(); }, o.timeout); } }, _calcArray: function(){ var o = this.options; var i; for (i = 0; i <= o.value; i += o.step ) { this.numbers.push(i); } if (this.numbers[this.numbers.length - 1] !== o.value) { this.numbers.push(o.value); } }, start: function(){ var that = this, element = this.element, o = this.options; var tick = function(){ if (that.numbers.length === 0) { Utils.exec(o.onStop, [element], element[0]); return ; } var n = that.numbers.shift(); Utils.exec(o.onTick, [n, element], element[0]); element.html(Number(n).format(0, 0, o.delimiter)); if (that.numbers.length > 0) { setTimeout(tick, o.delay); } else { Utils.exec(o.onStop, [element], element[0]); } }; Utils.exec(o.onStart, [element], element[0]); setTimeout(tick, o.delay); }, reset: function(){ this._calcArray(); this.element.html(this.html); }, setValueAttribute: function(){ this.options.value = this.element.attr("data-value"); this._calcArray(); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-value": this.setValueAttribute(); break; } }, destroy: function(){} }; Metro.plugin('counter', Counter); // Source: js/plugins/cube.js var Cube = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.id = null; this.rules = null; this.interval = false; this.ruleInterval = false; this.running = false; this.intervals = []; this._setOptionsFromDOM(); this._create(); return this; }, default_rules: [ { on: {'top': [16], 'left': [4], 'right': [1]}, off: {'top': [13, 4], 'left': [1, 16], 'right': [13, 4]} }, { on: {'top': [12, 15], 'left': [3, 8], 'right': [2, 5]}, off: {'top': [9, 6, 3], 'left': [5, 10, 15], 'right': [14, 11, 8]} }, { on: {'top': [11], 'left': [7], 'right': [6]}, off: {'top': [1, 2, 5], 'left': [9, 13, 14], 'right': [15, 12, 16]} }, { on: {'top': [8, 14], 'left': [2, 12], 'right': [9, 3]}, off: {'top': [16], 'left': [4], 'right': [1]} }, { on: {'top': [10, 7], 'left': [6, 11], 'right': [10, 7]}, off: {'top': [12, 15], 'left': [3, 8], 'right': [2, 5]} }, { on: {'top': [13, 4], 'left': [1, 16], 'right': [13, 4]}, off: {'top': [11], 'left': [7], 'right': [6]} }, { on: {'top': [9, 6, 3], 'left': [5, 10, 15], 'right': [14, 11, 8]}, off: {'top': [8, 14], 'left': [2, 12], 'right': [9, 3]} }, { on: {'top': [1, 2, 5], 'left': [9, 13, 14], 'right': [15, 12, 16]}, off: {'top': [10, 7], 'left': [6, 11], 'right': [10, 7]} } ], options: { rules: null, color: null, flashColor: null, flashInterval: 1000, numbers: false, offBefore: true, attenuation: .3, stopOnBlur: false, cells: 4, margin: 8, showAxis: false, axisStyle: "arrow", //line cellClick: false, autoRestart: 5000, clsCube: "", clsCell: "", clsSide: "", clsSideLeft: "", clsSideRight: "", clsSideTop: "", clsSideLeftCell: "", clsSideRightCell: "", clsSideTopCell: "", clsAxis: "", clsAxisX: "", clsAxisY: "", clsAxisZ: "", custom: Metro.noop, onTick: Metro.noop, onCubeCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; if (o.rules === null) { this.rules = this.default_rules; } else { this._parseRules(o.rules); } this._createCube(); this._createEvents(); Utils.exec(o.onCubeCreate, [element]); }, _parseRules: function(rules){ if (rules === undefined || rules === null) { return false; } if (Utils.isObject(rules)) { this.rules = Utils.isObject(rules); return true; } else { try { this.rules = JSON.parse(rules); return true; } catch (err) { console.log("Unknown or empty rules for cell flashing!"); return false; } } }, _createCube: function(){ var that = this, element = this.element, o = this.options; var sides = ['left', 'right', 'top']; var id = Utils.elementId("cube"); var cells_count = Math.pow(o.cells, 2); element.addClass("cube").addClass(o.clsCube); if (element.attr('id') === undefined) { element.attr('id', id); } this.id = element.attr('id'); this._createCssForFlashColor(); this._createCssForCellSize(); $.each(sides, function(){ var side, cell, i; side = $("<div>").addClass("side " + this+"-side").addClass(o.clsSide).appendTo(element); if (this === 'left') {side.addClass(o.clsSideLeft);} if (this === 'right') {side.addClass(o.clsSideRight);} if (this === 'top') {side.addClass(o.clsSideTop);} for(i = 0; i < cells_count; i++) { cell = $("<div>").addClass("cube-cell").addClass("cell-id-"+(i+1)).addClass(o.clsCell); cell.data("id", i + 1).data("side", this); cell.appendTo(side); if (o.numbers === true) { cell.html(i + 1); } } }); var cells = element.find(".cube-cell"); if (o.color !== null) { if (Utils.isColor(o.color)) { cells.css({ backgroundColor: o.color, borderColor: o.color }) } else { cells.addClass(o.color); } } var axis = ['x', 'y', 'z']; $.each(axis, function(){ var axis_name = this; var ax = $("<div>").addClass("axis " + o.axisStyle).addClass("axis-"+axis_name).addClass(o.clsAxis); if (axis_name === "x") ax.addClass(o.clsAxisX); if (axis_name === "y") ax.addClass(o.clsAxisY); if (axis_name === "z") ax.addClass(o.clsAxisZ); ax.appendTo(element); }); if (o.showAxis === false) { element.find(".axis").hide(); } this._run(); }, _run: function(){ var that = this, element = this.element, o = this.options; var interval = 0; clearInterval(this.interval); element.find(".cube-cell").removeClass("light"); if (o.custom !== Metro.noop) { Utils.exec(o.custom, [element]); } else { element.find(".cube-cell").removeClass("light"); that._start(); interval = Utils.isObject(this.rules) ? Utils.objectLength(this.rules) : 0; this.interval = setInterval(function(){ that._start(); }, interval * o.flashInterval); } }, _createCssForCellSize: function(){ var that = this, element = this.element, o = this.options; var sheet = Metro.sheet; var width; var cell_size; if (o.margin === 8 && o.cells === 4) { return ; } width = parseInt(Utils.getStyleOne(element, 'width')); cell_size = Math.ceil((width / 2 - o.margin * o.cells * 2) / o.cells); Utils.addCssRule(sheet, "#"+element.attr('id')+" .side .cube-cell", "width: "+cell_size+"px!important; height: "+cell_size+"px!important; margin: " + o.margin + "px!important;"); }, _createCssForFlashColor: function(){ var that = this, element = this.element, o = this.options; var sheet = Metro.sheet; var rule1; var rule2; var rules1 = []; var rules2 = []; var i; if (o.flashColor === null) { return ; } rule1 = "0 0 10px " + Utils.hexColorToRgbA(o.flashColor, 1); rule2 = "0 0 10px " + Utils.hexColorToRgbA(o.flashColor, o.attenuation); for(i = 0; i < 3; i++) { rules1.push(rule1); rules2.push(rule2); } Utils.addCssRule(sheet, "@keyframes pulsar-cell-"+element.attr('id'), "0%, 100% { " + "box-shadow: " + rules1.join(",") + "} 50% { " + "box-shadow: " + rules2.join(",") + " }"); Utils.addCssRule(sheet, "#"+element.attr('id')+" .side .cube-cell.light", "animation: pulsar-cell-" + element.attr('id') + " 2.5s 0s ease-out infinite; " + "background-color: " + o.flashColor + "!important; border-color: " + o.flashColor+"!important;"); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; $(window).on(Metro.events.blur + "-" + element.attr("id"), function(){ if (o.stopOnBlur === true && that.running === true) { that._stop(); } }); $(window).on(Metro.events.focus + "-" + element.attr("id"), function(){ if (o.stopOnBlur === true && that.running === false) { that._start(); } }); element.on(Metro.events.click, ".cube-cell", function(){ if (o.cellClick === true) { var cell = $(this); cell.toggleClass("light"); } }); }, _start: function(){ var that = this, element = this.element, o = this.options; var sides = ['left', 'right', 'top']; element.find(".cube-cell").removeClass("light"); this.running = true; $.each(this.rules, function(index, rule){ that._execRule(index, rule); }); }, _stop: function(){ this.running = false; clearInterval(this.interval); $.each(this.intervals, function(){ clearInterval(this); }) }, _tick: function(index, speed){ var that = this, element = this.element, o = this.options; if (speed === undefined) { speed = o.flashInterval * index; } var interval = setTimeout(function(){ Utils.exec(o.onTick, [index], element[0]); clearInterval(interval); Utils.arrayDelete(that.intervals, interval); }, speed); this.intervals.push(interval); }, _toggle: function(cell, func, time, speed){ var that = this; if (speed === undefined) { speed = this.options.flashInterval * time; } var interval = setTimeout(function(){ cell[func === 'on' ? 'addClass' : 'removeClass']("light"); clearInterval(interval); Utils.arrayDelete(that.intervals, interval); }, speed); this.intervals.push(interval); }, start: function(){ this._start(); }, stop: function(){ this._stop(); }, toRule: function(index, speed){ var that = this, element = this.element, o = this.options; var rules = this.rules; if (rules === null || rules === undefined || rules[index] === undefined) { return ; } clearInterval(this.ruleInterval); this.ruleInterval = false; this.stop(); element.find(".cube-cell").removeClass("light"); for (var i = 0; i <= index; i++) { this._execRule(i, rules[i], speed); } if (Utils.isInt(o.autoRestart) && o.autoRestart > 0) { this.ruleInterval = setTimeout(function(){ that._run(); }, o.autoRestart); } }, _execRule: function(index, rule, speed){ var that = this, element = this.element, o = this.options; var sides = ['left', 'right', 'top']; this._tick(index, speed); $.each(sides, function(){ var side_class = "."+this+"-side"; var side_name = this; var cells_on = rule["on"] !== undefined && rule["on"][side_name] !== undefined ? rule["on"][side_name] : false; var cells_off = rule["off"] !== undefined && rule["off"][side_name] !== undefined ? rule["off"][side_name] : false; if (cells_on !== false) $.each(cells_on, function(){ var cell_index = this; var cell = element.find(side_class + " .cell-id-"+cell_index); that._toggle(cell, 'on', index, speed); }); if (cells_off !== false) $.each(cells_off, function(){ var cell_index = this; var cell = element.find(side_class + " .cell-id-"+cell_index); that._toggle(cell, 'off', index, speed); }); }); }, rule: function(r){ if (r === undefined) { return this.rules; } if (this._parseRules(r) !== true) { return ; } this.options.rules = r; this.stop(); this.element.find(".cube-cell").removeClass("light"); this._run(); }, axis: function(show){ var func = show === true ? "show" : "hide"; this.element.find(".axis")[func](); }, changeRules: function(){ var that = this, element = this.element, o = this.options; var rules = element.attr("data-rules"); if (this._parseRules(rules) !== true) { return ; } this.stop(); element.find(".cube-cell").removeClass("light"); o.rules = rules; this._run(); }, changeAxisVisibility: function(){ var that = this, element = this.element, o = this.options; var visibility = JSON.parse(element.attr("data-show-axis")) === true; var func = visibility ? "show" : "hide"; element.find(".axis")[func](); }, changeAxisStyle: function(){ var that = this, element = this.element, o = this.options; var style = element.attr("data-axis-style"); element.find(".axis").removeClass("arrow line no-style").addClass(style); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-rules": this.changeRules(); break; case "data-show-axis": this.changeAxisVisibility(); break; case "data-axis-style": this.changeAxisStyle(); break; } }, destroy: function(){ var that = this, element = this.element, o = this.options; clearInterval(this.interval); this.interval = null; $(window).off(Metro.events.blur + "-" + element.attr("id")); $(window).off(Metro.events.focus + "-" + element.attr("id")); element.off(Metro.events.click, ".cube-cell"); element.html(""); element.removeClass("cube").removeClass(o.clsCube); } }; Metro.plugin('cube', Cube); // Source: js/plugins/datepicker.js var DatePicker = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.picker = null; this.isOpen = false; this.value = new Date(); this.locale = Metro.locales[METRO_LOCALE]['calendar']; this.offset = (new Date()).getTimezoneOffset() / 60 + 1; this._setOptionsFromDOM(); this._create(); return this; }, options: { gmt: 0, format: "%Y-%m-%d", locale: METRO_LOCALE, value: null, distance: 3, month: true, day: true, year: true, minYear: null, maxYear: null, scrollSpeed: 5, copyInlineStyles: true, clsPicker: "", clsPart: "", clsMonth: "", clsDay: "", clsYear: "", okButtonIcon: "<span class='default-icon-check'></span>", cancelButtonIcon: "<span class='default-icon-cross'></span>", onSet: Metro.noop, onOpen: Metro.noop, onClose: Metro.noop, onScroll: Metro.noop, onDatePickerCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; if (o.distance < 1) { o.distance = 1; } if (o.value !== null && Utils.isDate(o.value)) { this.value = (new Date(o.value)).addHours(this.offset); } if (Metro.locales[o.locale] === undefined) { o.locale = METRO_LOCALE; } this.locale = Metro.locales[o.locale]['calendar']; if (o.minYear === null) { o.minYear = (new Date()).getFullYear() - 100; } if (o.maxYear === null) { o.maxYear = (new Date()).getFullYear() + 100; } this._createStructure(); this._createEvents(); this._set(); Utils.exec(o.onDatePickerCreate, [element]); }, _createStructure: function(){ var element = this.element, o = this.options; var picker, month, day, year, i, j; var dateWrapper, selectWrapper, selectBlock, actionBlock; var prev = element.prev(); var parent = element.parent(); var id = Utils.elementId("date-picker"); picker = $("<div>").attr("id", id).addClass("wheel-picker date-picker " + element[0].className).addClass(o.clsPicker); if (prev.length === 0) { parent.prepend(picker); } else { picker.insertAfter(prev); } element.appendTo(picker); dateWrapper = $("<div>").addClass("date-wrapper").appendTo(picker); if (o.month === true) { month = $("<div>").addClass("month").addClass(o.clsPart).addClass(o.clsMonth).appendTo(dateWrapper); } if (o.day === true) { day = $("<div>").addClass("day").addClass(o.clsPart).addClass(o.clsDay).appendTo(dateWrapper); } if (o.year === true) { year = $("<div>").addClass("year").addClass(o.clsPart).addClass(o.clsYear).appendTo(dateWrapper); } selectWrapper = $("<div>").addClass("select-wrapper").appendTo(picker); selectBlock = $("<div>").addClass("select-block").appendTo(selectWrapper); if (o.month === true) { month = $("<ul>").addClass("sel-month").appendTo(selectBlock); for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(month); for (i = 0; i < 12; i++) { $("<li>").addClass("js-month-"+i+" js-month-real-"+this.locale['months'][i].toLowerCase()).html(this.locale['months'][i]).data("value", i).appendTo(month); } for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(month); } if (o.day === true) { day = $("<ul>").addClass("sel-day").appendTo(selectBlock); for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(day); for (i = 0; i < 31; i++) { $("<li>").addClass("js-day-"+i+" js-day-real-"+(i+1)).html(i + 1).data("value", i + 1).appendTo(day); } for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(day); } if (o.year === true) { year = $("<ul>").addClass("sel-year").appendTo(selectBlock); for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(year); for (i = o.minYear, j = 0; i <= o.maxYear; i++, j++) { $("<li>").addClass("js-year-"+ j + " js-year-real-" + i).html(i).data("value", i).appendTo(year); } for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(year); } selectBlock.height((o.distance * 2 + 1) * 40); actionBlock = $("<div>").addClass("action-block").appendTo(selectWrapper); $("<button>").attr("type", "button").addClass("button action-ok").html(o.okButtonIcon).appendTo(actionBlock); $("<button>").attr("type", "button").addClass("button action-cancel").html(o.cancelButtonIcon).appendTo(actionBlock); element[0].className = ''; if (o.copyInlineStyles === true) { for (i = 0; i < element[0].style.length; i++) { picker.css(element[0].style[i], element.css(element[0].style[i])); } } this.picker = picker; }, _createEvents: function(){ var that = this, o = this.options; var picker = this.picker; picker.on(Metro.events.start, ".select-block ul", function(e){ if (e.changedTouches) { return ; } var target = this; var pageY = Utils.pageXY(e).y; $(document).on(Metro.events.move + "-picker", function(e){ target.scrollTop -= o.scrollSpeed * (pageY > Utils.pageXY(e).y ? -1 : 1); pageY = Utils.pageXY(e).y; }); $(document).on(Metro.events.stop + "-picker", function(){ $(document).off(Metro.events.move + "-picker"); $(document).off(Metro.events.stop + "-picker"); }); }); picker.on(Metro.events.click, function(e){ if (that.isOpen === false) that.open(); e.stopPropagation(); }); picker.on(Metro.events.click, ".action-ok", function(e){ var m, d, y; var sm = picker.find(".sel-month li.active"), sd = picker.find(".sel-day li.active"), sy = picker.find(".sel-year li.active"); m = sm.length === 0 ? that.value.getMonth() : sm.data("value"); d = sd.length === 0 ? that.value.getDate() : sd.data("value"); y = sy.length === 0 ? that.value.getFullYear() : sy.data("value"); that.value = new Date(y, m, d); that._correct(); that._set(); that.close(); e.stopPropagation(); }); picker.on(Metro.events.click, ".action-cancel", function(e){ that.close(); e.stopPropagation(); }); this._addScrollEvents(); }, _addScrollEvents: function(){ var picker = this.picker, o = this.options; var lists = ['month', 'day', 'year']; $.each(lists, function(){ var list_name = this; var list = picker.find(".sel-" + list_name); if (list.length === 0) return ; list.on(Metro.events.scrollStart, function(){ list.find(".active").removeClass("active"); }); list.on(Metro.events.scrollStop, {latency: 50}, function(){ var target = Math.round((Math.ceil(list.scrollTop()) / 40)); var target_element = list.find(".js-"+list_name+"-"+target); var scroll_to = target_element.position().top - (o.distance * 40) + list.scrollTop() - 1; list.animate({ scrollTop: scroll_to }, 100, function(){ target_element.addClass("active"); Utils.exec(o.onScroll, [target_element, list, picker], list[0]); }); }); }); }, _removeScrollEvents: function(){ var picker = this.picker; var lists = ['month', 'day', 'year']; $.each(lists, function(){ picker.find(".sel-" + this).off("scrollstart scrollstop"); }); }, _correct: function(){ var m = this.value.getMonth(), d = this.value.getDate(), y = this.value.getFullYear(); this.value = new Date(y, m, d); }, _set: function(){ var element = this.element, o = this.options; var picker = this.picker; var m = this.locale['months'][this.value.getMonth()], d = this.value.getDate(), y = this.value.getFullYear(); if (o.month === true) { picker.find(".month").html(m); } if (o.day === true) { picker.find(".day").html(d); } if (o.year === true) { picker.find(".year").html(y); } element.val(this.value.format(o.format, o.locale)).trigger("change"); Utils.exec(o.onSet, [this.value, element.val(), element, picker], element[0]); }, open: function(){ var element = this.element, o = this.options; var picker = this.picker; var m = this.value.getMonth(), d = this.value.getDate() - 1, y = this.value.getFullYear(); var m_list, d_list, y_list; var select_wrapper = picker.find(".select-wrapper"); var select_wrapper_in_viewport, select_wrapper_rect; select_wrapper.parent().removeClass("for-top for-bottom"); select_wrapper.show(); picker.find("li").removeClass("active"); select_wrapper_in_viewport = Utils.inViewport(select_wrapper); select_wrapper_rect = Utils.rect(select_wrapper); if (!select_wrapper_in_viewport && select_wrapper_rect.top > 0) { select_wrapper.parent().addClass("for-bottom"); } if (!select_wrapper_in_viewport && select_wrapper_rect.top < 0) { select_wrapper.parent().addClass("for-top"); } if (o.month === true) { m_list = picker.find(".sel-month"); m_list.scrollTop(0).animate({ scrollTop: m_list.find("li.js-month-" + m).addClass("active").position().top - (40 * o.distance) }, 100); } if (o.day === true) { d_list = picker.find(".sel-day"); d_list.scrollTop(0).animate({ scrollTop: d_list.find("li.js-day-" + d).addClass("active").position().top - (40 * o.distance) }, 100); } if (o.year === true) { y_list = picker.find(".sel-year"); y_list.scrollTop(0).animate({ scrollTop: y_list.find("li.js-year-real-" + y).addClass("active").position().top - (40 * o.distance) }, 100); } this.isOpen = true; Utils.exec(o.onOpen, [this.value, element, picker], element[0]); }, close: function(){ var picker = this.picker, o = this.options, element = this.element; picker.find(".select-wrapper").hide(); this.isOpen = false; Utils.exec(o.onClose, [this.value, element, picker], element[0]); }, val: function(t){ if (t === undefined) { return this.element.val(); } if (Utils.isDate(t) === false) { return false; } this.value = (new Date(t)).addHours(this.offset); this._set(); }, date: function(t){ if (t === undefined) { return this.value; } try { this.value = new Date(t.format("%Y-%m-%d")); this._set(); } catch (e) { return false; } }, changeValueAttribute: function(){ this.val(this.element.attr("data-value")); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-value": this.changeValueAttribute(); break; } }, destroy: function(){ var element = this.element; var picker = this.picker; var parent = element.parent(); this._removeScrollEvents(); picker.off(Metro.events.start, ".select-block ul"); picker.off(Metro.events.click); picker.off(Metro.events.click, ".action-ok"); picker.off(Metro.events.click, ".action-cancel"); element.insertBefore(parent); parent.remove(); } }; Metro.plugin('datepicker', DatePicker); $(document).on(Metro.events.click, function(){ $.each($(".date-picker"), function(){ $(this).find("input").data("datepicker").close(); }); }); // Source: js/plugins/dialog.js var Dialog = { _counter: 0, init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.interval = null; this.overlay = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { leaveOverlayOnClose: false, toTop: false, toBottom: false, locale: METRO_LOCALE, title: "", content: "", actions: {}, actionsAlign: "right", defaultAction: true, overlay: true, overlayColor: '#000000', overlayAlpha: .5, overlayClickClose: false, width: '480', height: 'auto', shadow: true, closeAction: true, clsDialog: "", clsTitle: "", clsContent: "", clsAction: "", clsDefaultAction: "", clsOverlay: "", autoHide: 0, removeOnClose: false, show: false, onShow: Metro.noop, onHide: Metro.noop, onOpen: Metro.noop, onClose: Metro.noop, onDialogCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var o = this.options; this.locale = Metro.locales[o.locale] !== undefined ? Metro.locales[o.locale] : Metro.locales["en-US"]; this._build(); }, _build: function(){ var that = this, element = this.element, o = this.options; var body = $("body"); var overlay; element.addClass("dialog"); if (o.shadow === true) { element.addClass("shadow-on"); } if (element.attr("id") === undefined) { element.attr("id", Utils.elementId("dialog")); } if (o.title !== "") { this.setTitle(o.title); } if (o.content !== "") { this.setContent(o.content); } if (o.defaultAction === true || (o.actions !== false && typeof o.actions === 'object' && Utils.objectLength(o.actions) > 0)) { var buttons = element.find(".dialog-actions"); var button; if (buttons.length === 0) { buttons = $("<div>").addClass("dialog-actions").addClass("text-"+o.actionsAlign).appendTo(element); } if (o.defaultAction === true && (Utils.objectLength(o.actions) === 0 && element.find(".dialog-actions > *").length === 0)) { button = $("<button>").addClass("button js-dialog-close").addClass(o.clsDefaultAction).html(this.locale["buttons"]["ok"]); button.appendTo(buttons); } $.each(o.actions, function(){ var item = this; button = $("<button>").addClass("button").addClass(item.cls).html(item.caption); if (item.onclick !== undefined) button.on(Metro.events.click, function(){ Utils.exec(item.onclick, [element]); }); button.appendTo(buttons); }); } if (o.overlay === true) { overlay = this._overlay(); this.overlay = overlay; } if (o.closeAction === true) { element.on(Metro.events.click, ".js-dialog-close", function(){ that.close(); }); } element.css({ width: o.width, height: o.height, visibility: "hidden", top: '100%', left: ( $(window).width() - element.outerWidth() ) / 2 }); element.addClass(o.clsDialog); element.find(".dialog-title").addClass(o.clsTitle); element.find(".dialog-content").addClass(o.clsContent); element.find(".dialog-actions").addClass(o.clsAction); element.appendTo(body); if (o.show) { this.open(); } $(window).on(Metro.events.resize + "_" + element.attr("id"), function(){ that.setPosition(); }); Utils.exec(this.options.onDialogCreate, [this.element]); }, _overlay: function(){ var that = this, element = this.element, o = this.options; var overlay = $("<div>"); overlay.addClass("overlay").addClass(o.clsOverlay); if (o.overlayColor === 'transparent') { overlay.addClass("transparent"); } else { overlay.css({ background: Utils.hex2rgba(o.overlayColor, o.overlayAlpha) }); } return overlay; }, hide: function(callback){ var that = this, element = this.element, o = this.options; var timeout = 0; if (o.onHide !== Metro.noop) { timeout = 300; } setTimeout(function(){ element.css({ visibility: "hidden", top: "100%" }); Utils.exec(o.onHide, [that], element[0]); Utils.callback(callback); }, timeout); }, show: function(callback){ var that = this, element = this.element, o = this.options; this.setPosition(); element.css({ visibility: "visible" }); Utils.exec(o.onShow, [that], element[0]); Utils.callback(callback); }, setPosition: function(){ var element = this.element, o = this.options; var top, bottom; if (o.toTop !== true && o.toBottom !== true) { top = ( $(window).height() - element.outerHeight() ) / 2; if (top < 0) { top = 0; } bottom = "auto"; } else { if (o.toTop === true) { top = 0; bottom = "auto"; } if (o.toTop !== true && o.toBottom === true) { bottom = 0; top = "auto"; } } element.css({ top: top, bottom: bottom, left: ( $(window).width() - element.outerWidth() ) / 2 }); }, setContent: function(c){ var that = this, element = this.element, o = this.options; var content = element.find(".dialog-content"); if (content.length === 0) { content = $("<div>").addClass("dialog-content"); content.appendTo(element); } if (!Utils.isJQueryObject(c) && Utils.isFunc(c)) { c = Utils.exec(c); } if (Utils.isJQueryObject(c)) { c.appendTo(content); } else { content.html(c); } }, setTitle: function(t){ var that = this, element = this.element, o = this.options; var title = element.find(".dialog-title"); if (title.length === 0) { title = $("<div>").addClass("dialog-title"); title.appendTo(element); } title.html(t); }, close: function(){ var that = this, element = this.element, o = this.options; if (!Utils.bool(o.leaveOverlayOnClose)) { $('body').find('.overlay').remove(); } this.hide(function(){ element.data("open", false); Utils.exec(o.onClose, [element], element[0]); if (o.removeOnClose === true) { element.remove(); } }); }, open: function(){ var that = this, element = this.element, o = this.options; if (o.overlay === true && $(".overlay").length === 0) { this.overlay.appendTo($("body")); if (o.overlayClickClose === true) { this.overlay.on(Metro.events.click, function(){ that.close(); }); } } this.show(function(){ Utils.exec(o.onOpen, [element], element[0]); element.data("open", true); if (parseInt(o.autoHide) > 0) { setTimeout(function(){ that.close(); }, parseInt(o.autoHide)); } }); }, toggle: function(){ var element = this.element; if (element.data('open')) { this.close(); } else { this.open(); } }, isOpen: function(){ return this.element.data('open') === true; }, changeAttribute: function(attributeName){ } }; Metro.plugin('dialog', Dialog); Metro['dialog'] = { isDialog: function(el){ return Utils.isMetroObject(el, "dialog"); }, open: function(el, content, title){ if (!this.isDialog(el)) { return false; } var dialog = $(el).data("dialog"); if (title !== undefined) { dialog.setTitle(title); } if (content !== undefined) { dialog.setContent(content); } dialog.open(); }, close: function(el){ if (!this.isDialog(el)) { return false; } var dialog = $(el).data("dialog"); dialog.close(); }, toggle: function(el){ if (!this.isDialog(el)) { return false; } var dialog = $(el).data("dialog"); dialog.toggle(); }, isOpen: function(el){ if (!this.isDialog(el)) { return false; } var dialog = $(el).data("dialog"); return dialog.isOpen(); }, remove: function(el){ if (!this.isDialog(el)) { return false; } var dialog = $(el).data("dialog"); dialog.options.removeOnClose = true; dialog.close(); }, create: function(options){ var dlg; dlg = $("<div>").appendTo($("body")); var dlg_options = $.extend({}, { show: true, closeAction: true, removeOnClose: true }, (options !== undefined ? options : {})); return dlg.dialog(dlg_options); } }; // Source: js/plugins/donut.js var Donut = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.value = 0; this.animation_change_interval = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onDonutCreate, [this.element]); return this; }, options: { size: 100, radius: 50, hole: .8, value: 0, background: "#ffffff", color: "", stroke: "#d1d8e7", fill: "#49649f", fontSize: 24, total: 100, cap: "%", showText: true, showValue: false, animate: 0, onChange: Metro.noop, onDonutCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var html = ""; var r = o.radius * (1 - (1 - o.hole) / 2); var width = o.radius * (1 - o.hole); var circumference = 2 * Math.PI * r; var strokeDasharray = ((o.value * circumference) / o.total) + ' ' + circumference; var transform = 'rotate(-90 ' + o.radius + ',' + o.radius + ')'; var fontSize = r * o.hole * 0.6; element.addClass("donut"); element.css({ width: o.size, height: o.size, background: o.background }); html += "<svg>"; html += " <circle class='donut-back' r='"+(r)+"px' cx='"+(o.radius)+"px' cy='"+(o.radius)+"px' transform='"+(transform)+"' fill='none' stroke='"+(o.stroke)+"' stroke-width='"+(width)+"'/>"; html += " <circle class='donut-fill' r='"+(r)+"px' cx='"+(o.radius)+"px' cy='"+(o.radius)+"px' transform='"+(transform)+"' fill='none' stroke='"+(o.fill)+"' stroke-width='"+(width)+"'/>"; if (o.showText === true) html += " <text class='donut-title' x='"+(o.radius)+"px' y='"+(o.radius)+"px' dy='"+(fontSize/3)+"px' text-anchor='middle' fill='"+(o.color !== "" ? o.color: o.fill)+"' font-size='"+(fontSize)+"px'>0"+(o.cap)+"</text>"; html += "</svg>"; element.html(html); this.val(o.value); }, _setValue: function(v){ var that = this, element = this.element, o = this.options; var fill = element.find(".donut-fill"); var title = element.find(".donut-title"); var r = o.radius * (1 - (1 - o.hole) / 2); var circumference = 2 * Math.PI * r; // var title_value = (o.showValue ? o.value : Math.round(((v * 1000 / o.total) / 10)))+(o.cap); var title_value = (o.showValue ? v : Utils.percent(o.total, v, true)) + (o.cap); var fill_value = ((v * circumference) / o.total) + ' ' + circumference; fill.attr("stroke-dasharray", fill_value); title.html(title_value); }, val: function(v){ var that = this, element = this.element, o = this.options; if (v === undefined) { return this.value } if (parseInt(v) < 0 || parseInt(v) > o.total) { return false; } if (o.animate > 0 && !document.hidden) { var inc = v > that.value; var i = that.value + (inc ? -1 : 1); clearInterval(that.animation_change_interval); this.animation_change_interval = setInterval(function(){ if (inc) { that._setValue(++i); if (i >= v) { clearInterval(that.animation_change_interval); } } else { that._setValue(--i); if (i <= v) { clearInterval(that.animation_change_interval); } } }, o.animate); } else { clearInterval(that.animation_change_interval); this._setValue(v); } this.value = v; //element.attr("data-value", v); Utils.exec(o.onChange, [this.value, element]); }, changeValue: function(){ this.val(this.element.attr("data-value")); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-value": this.changeValue(); break; } }, destroy: function(){ this.element.removeClass("donut").html(""); } }; Metro.plugin('donut', Donut); // Source: js/plugins/draggable.js var Draggable = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.drag = false; this.move = false; this.backup = { cursor: 'default', zIndex: '0' }; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onDraggableCreate, [this.element]); return this; }, options: { dragElement: 'self', dragArea: "parent", onCanDrag: Metro.noop_true, onDragStart: Metro.noop, onDragStop: Metro.noop, onDragMove: Metro.noop, onDraggableCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, elem = this.elem, o = this.options; var dragArea; var position = { x: 0, y: 0 }; var dragElement = o.dragElement !== 'self' ? element.find(o.dragElement) : element; dragElement[0].ondragstart = function(){return false;}; dragElement.on(Metro.events.start, function(e){ if (o.dragArea === 'document' || o.dragArea === 'window') { o.dragArea = "body"; } dragArea = o.dragArea === 'parent' ? element.parent() : $(o.dragArea); var coord = o.dragArea === "body" ? element.offset() : element.position(), shiftX = Utils.pageXY(e).x - coord.left, shiftY = Utils.pageXY(e).y - coord.top; var moveElement = function(e){ var top = Utils.pageXY(e).y - shiftY; var left = Utils.pageXY(e).x - shiftX; if (top < 0) top = 0; if (left < 0) left = 0; if (top > dragArea.outerHeight() - element.outerHeight()) top = dragArea.outerHeight() - element.outerHeight(); if (left > dragArea.outerWidth() - element.outerWidth()) left = dragArea.outerWidth() - element.outerWidth(); position.y = top; position.x = left; element.css({ left: left, top: top }); }; if (element.data("canDrag") === false || Utils.exec(o.onCanDrag, [element]) !== true) { return ; } if (isTouch === false && e.which !== 1) { return ; } that.drag = true; that.backup.cursor = element.css("cursor"); that.backup.zIndex = element.css("z-index"); element.css("position", "absolute").addClass("draggable"); element.appendTo(dragArea); moveElement(e); Utils.exec(o.onDragStart, [position, element]); $(document).on(Metro.events.move+".draggable", function(e){ moveElement(e); Utils.exec(o.onDragMove, [position], elem); e.preventDefault(); }); $(document).on(Metro.events.stop+".draggable", function(e){ element.css({ cursor: that.backup.cursor, zIndex: that.backup.zIndex }).removeClass("draggable"); if (that.drag) { $(document).off(Metro.events.move+".draggable"); $(document).off(Metro.events.stop+".draggable"); } that.drag = false; that.move = false; Utils.exec(o.onDragStop, [position], elem); }); }); }, off: function(){ this.element.data("canDrag", false); }, on: function(){ this.element.data("canDrag", true); }, changeAttribute: function(attributeName){ } }; Metro.plugin('draggable', Draggable); // Source: js/plugins/dropdown.js var Dropdown = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._toggle = null; this.displayOrigin = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onDropdownCreate, [this.element]); return this; }, options: { effect: 'slide', toggleElement: null, noClose: false, duration: 100, onDrop: Metro.noop, onUp: Metro.noop, onDropdownCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var toggle, parent = element.parent(); var element_roles = Utils.isValue(element.attr("data-role")) ? Utils.strToArray(element.attr("data-role")) : []; toggle = o.toggleElement !== null ? $(o.toggleElement) : element.siblings('.dropdown-toggle').length > 0 ? element.siblings('.dropdown-toggle') : element.prev(); this.displayOrigin = element.css("display"); if (element.hasClass("v-menu")) { element.addClass("for-dropdown"); } element.css("display", "none"); if (element_roles.length === 0 || element_roles.indexOf("dropdown") === -1) { element_roles.push("dropdown"); element.attr("data-role", element_roles.join(", ")); } toggle.on(Metro.events.click, function(e){ parent.siblings(parent[0].tagName).removeClass("active-container"); $(".active-container").removeClass("active-container"); if (element.css('display') !== 'none' && !element.hasClass('keep-open')) { that._close(element); } else { $('[data-role=dropdown]').each(function(i, el){ if (!element.parents('[data-role=dropdown]').is(el) && !$(el).hasClass('keep-open') && $(el).css('display') !== 'none') { that._close(el); } }); if (element.hasClass('horizontal')) { element.css({ 'visibility': 'hidden', 'display': 'block' }); var children_width = 0; $.each(element.children('li'), function(){ children_width += $(this).outerWidth(true); }); element.css({ 'visibility': 'visible', 'display': 'none' }); element.css('width', children_width); } that._open(element); parent.addClass("active-container"); } e.preventDefault(); e.stopPropagation(); }); this._toggle = toggle; if (o.noClose === true) { element.addClass("keep-open").on(Metro.events.click, function (e) { //e.preventDefault(); e.stopPropagation(); }); } $(element).find('li.disabled a').on(Metro.events.click, function(e){ e.preventDefault(); }); }, _close: function(el){ if (Utils.isJQueryObject(el) === false) { el = $(el); } var dropdown = el.data("dropdown"); var toggle = dropdown._toggle; var options = dropdown.options; var func = options.effect === "slide" ? "slideUp" : "fadeOut"; toggle.removeClass('active-toggle').removeClass("active-control"); dropdown.element.parent().removeClass("active-container"); el[func](options.duration, function(){ el.trigger("onClose", null, el); }); Utils.exec(options.onUp, [el]); }, _open: function(el){ if (Utils.isJQueryObject(el) === false) { el = $(el); } var dropdown = el.data("dropdown"); var toggle = dropdown._toggle; var options = dropdown.options; var func = options.effect === "slide" ? "slideDown" : "fadeIn"; toggle.addClass('active-toggle').addClass("active-control"); el[func](options.duration, function(){ el.trigger("onOpen", null, el); }); Utils.exec(options.onDrop, [el]); }, close: function(){ this._close(this.element); }, open: function(){ this._open(this.element); }, changeAttribute: function(attributeName){ }, destroy: function(){ this._toggle.off(Metro.events.click); } }; $(document).on(Metro.events.click, function(e){ $('[data-role*=dropdown]').each(function(){ var el = $(this); if (el.css('display')==='block' && el.hasClass('keep-open') === false) { var dropdown = el.data('dropdown'); dropdown.close(); } }); }); Metro.plugin('dropdown', Dropdown); // Source: js/plugins/file.js var File = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onFileCreate, [this.element], elem); return this; }, options: { mode: "input", buttonTitle: "Choose file(s)", filesTitle: "file(s) selected", dropTitle: "<strong>Choose a file</strong> or drop it here", dropIcon: "<span class='default-icon-upload'></span>", prepend: "", clsComponent: "", clsPrepend: "", clsButton: "", clsCaption: "", copyInlineStyles: true, onSelect: Metro.noop, onFileCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createStructure(); this._createEvents(); }, _createStructure: function(){ var element = this.element, o = this.options; var container = $("<label>").addClass((o.mode === "input" ? " file " : " drop-zone ") + element[0].className).addClass(o.clsComponent); var caption = $("<span>").addClass("caption").addClass(o.clsCaption); var files = $("<span>").addClass("files").addClass(o.clsCaption); var icon, button; container.insertBefore(element); element.appendTo(container); if (o.mode === "input") { caption.insertBefore(element); button = $("<button>").addClass("button").attr("tabindex", -1).attr("type", "button").html(o.buttonTitle); button.appendTo(container); button.addClass(o.clsButton); if (element.attr('dir') === 'rtl' ) { container.addClass("rtl"); } if (o.prepend !== "") { var prepend = $("<div>").html(o.prepend); prepend.addClass("prepend").addClass(o.clsPrepend).appendTo(container); } } else { icon = $(o.dropIcon).addClass("icon").appendTo(container); caption.html(o.dropTitle).insertAfter(icon); files.html("0" + " " + o.filesTitle).insertAfter(caption); } element[0].className = ''; if (o.copyInlineStyles === true) { for (var i = 0, l = element[0].style.length; i < l; i++) { container.css(element[0].style[i], element.css(element[0].style[i])); } } if (element.is(":disabled")) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var element = this.element, o = this.options; var container = element.closest("label"); var caption = container.find(".caption"); var files = container.find(".files"); container.on(Metro.events.click, "button", function(){ element.trigger("click"); }); element.on(Metro.events.change, function(){ var fi = this; var file_names = []; var entry; if (fi.files.length === 0) { return ; } Array.from(fi.files).forEach(function(file){ file_names.push(file.name); }); if (o.mode === "input") { entry = file_names.join(", "); caption.html(entry); caption.attr('title', entry); } else { files.html(element[0].files.length + " " +o.filesTitle); } Utils.exec(o.onSelect, [fi.files, element], element[0]); }); element.on(Metro.events.focus, function(){container.addClass("focused");}); element.on(Metro.events.blur, function(){container.removeClass("focused");}); if (o.mode !== "input") { container.on('drag dragstart dragend dragover dragenter dragleave drop', function(e){ e.preventDefault(); }); container.on('dragenter dragover', function(){ container.addClass("drop-on"); }); container.on('dragleave', function(){ container.removeClass("drop-on"); }); container.on('drop', function(e){ element[0].files = e.originalEvent.dataTransfer.files; files.html(element[0].files.length + " " +o.filesTitle); container.removeClass("drop-on"); if (!Utils.detectChrome()) Utils.exec(o.onSelect, [element[0].files, element], element[0]); }); } }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, toggleDir: function(){ if (this.element.attr("dir") === 'rtl') { this.element.parent().addClass("rtl"); } else { this.element.parent().removeClass("rtl"); } }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; case 'dir': this.toggleDir(); break; } }, destroy: function(){ var element = this.element; var parent = element.parent(); element.off(Metro.events.change); parent.off(Metro.events.click, "button"); element.insertBefore(parent); parent.remove(); } }; Metro.plugin('file', File); // Source: js/plugins/gravatar.js var Gravatar = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onGravatarCreate, [this.element]); return this; }, options: { email: "", size: 80, default: "404", onGravatarCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this.get(); }, getImage: function(email, size, def, is_jquery_object){ var image = $("<img>"); image.attr("src", this.getImageSrc(email, size)); return is_jquery_object === true ? image : image[0]; }, getImageSrc: function(email, size, def){ if (email === undefined || email.trim() === '') { return ""; } size = size || 80; def = Utils.encodeURI(def) || '404'; return "//www.gravatar.com/avatar/" + Utils.md5((email.toLowerCase()).trim()) + '?size=' + size + '&d=' + def; }, get: function(){ var that = this, element = this.element, o = this.options; var img = element[0].tagName === 'IMG' ? element : element.find("img"); if (img.length === 0) { return; } img.attr("src", this.getImageSrc(o.email, o.size, o.default)); return this; }, resize: function(new_size){ this.options.size = new_size !== undefined ? new_size : this.element.attr("data-size"); this.get(); }, email: function(new_email){ this.options.email = new_email !== undefined ? new_email : this.element.attr("data-email"); this.get(); }, changeAttribute: function(attributeName){ switch (attributeName) { case 'data-size': this.resize(); break; case 'data-email': this.email(); break; } }, destroy: function(){ var element = this.element; if (element[0].tagName.toLowerCase() !== "img") { element.html(""); } } }; Metro.plugin('gravatar', Gravatar); // Source: js/plugins/hint.js var Hint = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.hint = null; this.hint_size = { width: 0, height: 0 }; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onHintCreate, [this.element]); return this; }, options: { hintHide: 5000, clsHint: "", hintText: "", hintPosition: Metro.position.TOP, hintOffset: 4, onHintCreate: Metro.noop, onHintShow: Metro.noop, onHintHide: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.enter + "-hint", function(){ that.createHint(); if (o.hintHide > 0) { setTimeout(function(){ that.removeHint(); }, o.hintHide); } }); element.on(Metro.events.leave + "-hint", function(){ that.removeHint(); }); $(window).on(Metro.events.scroll + "-hint", function(){ if (that.hint !== null) that.setPosition(); }); }, createHint: function(){ var that = this, elem = this.elem, element = this.element, o = this.options; var hint = $("<div>").addClass("hint").addClass(o.clsHint).html(o.hintText); this.hint = hint; this.hint_size = Utils.hiddenElementSize(hint); $(".hint:not(.permanent-hint)").remove(); if (elem.tagName === 'TD' || elem.tagName === 'TH') { var wrp = $("<div/>").css("display", "inline-block").html(element.html()); element.html(wrp); element = wrp; } this.setPosition(); hint.appendTo($('body')); Utils.exec(o.onHintShow, [hint, element]); }, setPosition: function(){ var hint = this.hint, hint_size = this.hint_size, o = this.options, element = this.element; if (o.hintPosition === Metro.position.BOTTOM) { hint.addClass('bottom'); hint.css({ top: element.offset().top - $(window).scrollTop() + element.outerHeight() + o.hintOffset, left: element.offset().left + element.outerWidth()/2 - hint_size.width/2 - $(window).scrollLeft() }); } else if (o.hintPosition === Metro.position.RIGHT) { hint.addClass('right'); hint.css({ top: element.offset().top + element.outerHeight()/2 - hint_size.height/2 - $(window).scrollTop(), left: element.offset().left + element.outerWidth() - $(window).scrollLeft() + o.hintOffset }); } else if (o.hintPosition === Metro.position.LEFT) { hint.addClass('left'); hint.css({ top: element.offset().top + element.outerHeight()/2 - hint_size.height/2 - $(window).scrollTop(), left: element.offset().left - hint_size.width - $(window).scrollLeft() - o.hintOffset }); } else { hint.addClass('top'); hint.css({ top: element.offset().top - $(window).scrollTop() - hint_size.height - o.hintOffset, left: element.offset().left + element.outerWidth()/2 - hint_size.width/2 - $(window).scrollLeft() }); } }, removeHint: function(){ var that = this; var hint = this.hint; var element = this.element; var options = this.options; var timeout = options.onHintHide === Metro.noop ? 0 : 300; if (hint !== null) { Utils.exec(options.onHintHide, [hint, element]); setTimeout(function(){ hint.hide(0, function(){ hint.remove(); that.hint = null; }); }, timeout); } }, changeText: function(){ this.options.hintText = this.element.attr("data-hint-text"); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-hint-text": this.changeText(); break; } }, destroy: function(){ var that = this, elem = this.elem, element = this.element, o = this.options; this.removeHint(); element.off(Metro.events.enter + "-hint"); element.off(Metro.events.leave + "-hint"); $(window).off(Metro.events.scroll + "-hint"); } }; Metro.plugin('hint', Hint); // Source: js/plugins/html-container.js // TODO source as array, mode as array var HtmlContainer = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, options: { htmlSource: null, insertMode: "replace", // replace, append, prepend onLoad: Metro.noop, onFail: Metro.noop, onDone: Metro.noop, onHtmlContainerCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; if (Utils.isValue(o.htmlSource)) { this._load(); } Utils.exec(o.onHtmlContainerCreate, [element], element[0]); }, _load: function(){ var element = this.element, elem = this.elem, o = this.options; var xhttp, html; html = o.htmlSource; xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4) { if (this.status === 404) { elem.innerHTML = "Page not found."; Utils.exec(o.onFail, [this], elem); } if (this.status === 200) { switch (o.insertMode.toLowerCase()) { case "prepend": element.prepend(this.responseText); break; case "append": element.append(this.responseText); break; default: { element.html(this.responseText); } } Utils.exec(o.onLoad, [this.responseText], elem); } Utils.exec(o.onDone, [this], elem); } }; xhttp.open("GET", html, true); xhttp.send(); }, changeAttribute: function(attributeName){ var element = this.element, o = this.options; var changeHTMLSource = function(){ var html = element.attr("data-html-source"); if (Utils.isNull(html)) { return ; } if (html.trim() === "") { element.html(""); } o.htmlSource = html; this._load(); }; var changeInsertMode = function(){ var attr = element.attr("data-insert-mode"); if (Utils.isValue(attr)) { o.insertMode = attr; } }; switch (attributeName) { case "data-html-source": changeHTMLSource(); break; case "data-insert-mode": changeInsertMode(); break; } }, destroy: function(){} }; Metro.plugin('htmlcontainer', HtmlContainer); // Source: js/plugins/image-comparer.js var ImageCompare = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, options: { width: "100%", height: "auto", onResize: Metro.noop, onSliderMove: Metro.noop, onImageCompareCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onImageCompareCreate, [element], element[0]); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var container, container_overlay, slider; var images, element_width, element_height; if (!Utils.isValue(element.attr("id"))) { element.attr("id", Utils.elementId("image-compare")); } element.addClass("image-compare").css({ width: o.width }); element_width = element.width(); switch (o.height) { case "16/9": element_height = Utils.aspectRatioH(element_width, o.height); break; case "21/9": element_height = Utils.aspectRatioH(element_width, o.height); break; case "4/3": element_height = Utils.aspectRatioH(element_width, o.height); break; case "auto": element_height = Utils.aspectRatioH(element_width, "16/9"); break; default: element_height = o.height; } element.css({ height: element_height }); container = $("<div>").addClass("image-container").appendTo(element); container_overlay = $("<div>").addClass("image-container-overlay").appendTo(element).css({ width: element_width / 2 }); slider = $("<div>").addClass("image-slider").appendTo(element); slider.css({ top: element_height / 2 - slider.height() / 2, left: element_width / 2 - slider.width() / 2 }); images = element.find("img"); $.each(images, function(i, v){ var img = $("<div>").addClass("image-wrapper"); img.css({ width: element_width, height: element_height, backgroundImage: "url("+this.src+")" }); img.appendTo(i === 0 ? container : container_overlay); }); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var overlay = element.find(".image-container-overlay"); var slider = element.find(".image-slider"); slider.on(Metro.events.start, function(e){ var w = element.width(); $(document).on(Metro.events.move + "-" + element.attr("id"), function(e){ var x = Utils.getCursorPositionX(element, e), left_pos; if (x < 0) x = 0; if (x > w) x = w; overlay.css({ width: x }); left_pos = x - slider.width() / 2; slider.css({ left: left_pos }); Utils.exec(o.onSliderMove, [x, left_pos, slider[0]], element[0]); }); $(document).on(Metro.events.stop + "-" + element.attr("id"), function(){ $(document).off(Metro.events.move + "-" + element.attr("id")); $(document).off(Metro.events.stop + "-" + element.attr("id")); }) }); $(window).on(Metro.events.resize+"-"+element.attr("id"), function(){ var element_width = element.width(), element_height; if (o.width !== "100%") { return ; } switch (o.height) { case "16/9": element_height = Utils.aspectRatioH(element_width, o.height); break; case "21/9": element_height = Utils.aspectRatioH(element_width, o.height); break; case "4/3": element_height = Utils.aspectRatioH(element_width, o.height); break; case "auto": element_height = Utils.aspectRatioH(element_width, "16/9"); break; default: element_height = o.height; } element.css({ height: element_height }); $.each(element.find(".image-wrapper"), function(){ $(this).css({ width: element_width, height: element_height }) }); element.find(".image-container-overlay").css({ width: element_width / 2 }); slider.css({ top: element_height / 2 - slider.height() / 2, left: element_width / 2 - slider.width() / 2 }); Utils.exec(o.onResize, [element_width, element_height], element[0]); }); }, changeAttribute: function(attributeName){ }, destroy: function(){ var element = this.element; element.off(Metro.events.start); $(window).off(Metro.events.resize+"-"+element.attr("id")); } }; Metro.plugin('imagecompare', ImageCompare); // Source: js/plugins/image-magnifier.js var ImageMagnifier = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.zoomElement = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { width: "100%", height: "auto", lensSize: 100, lensType: "square", // square, circle magnifierZoom: 2, magnifierMode: "glass", // glass, zoom magnifierZoomElement: null, clsMagnifier: "", clsLens: "", clsZoom: "", onMagnifierMove: Metro.noop, onImageMagnifierCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onCreate, [element]); }, _createStructure: function(){ var element = this.element, o = this.options; var magnifier, element_width, element_height; var image = element.find("img"); if (image.length === 0) { throw new Error("Image not defined"); } if (!Utils.isValue(element.attr("id"))) { element.attr("id", Utils.elementId("image-magnifier")); } element.addClass("image-magnifier").css({ width: o.width }).addClass(o.clsMagnifier); element_width = element.width(); switch (o.height) { case "16/9": element_height = Utils.aspectRatioH(element_width, o.height); break; case "21/9": element_height = Utils.aspectRatioH(element_width, o.height); break; case "4/3": element_height = Utils.aspectRatioH(element_width, o.height); break; case "auto": element_height = Utils.aspectRatioH(element_width, "16/9"); break; default: element_height = o.height; } element.css({ height: element_height }); var x = element_width / 2 - o.lensSize / 2; var y = element_height / 2 - o.lensSize / 2; if (o.magnifierMode === "glass") { magnifier = $("<div>").addClass("image-magnifier-glass").appendTo(element); magnifier.css({ width: o.lensSize, height: o.lensSize, borderRadius: o.lensType !== "circle" ? 0 : "50%", top: y, left: x, backgroundImage: "url(" + image[0].src + ")", backgroundRepeat: "no-repeat", backgroundPosition: "-" + ((x * o.magnifierZoom) - o.lensSize / 4 + 4) + "px -" + ((y * o.magnifierZoom) - o.lensSize / 4 + 4) + "px", backgroundSize: (image[0].width * o.magnifierZoom) + "px " + (image[0].height * o.magnifierZoom) + "px" }).addClass(o.clsLens); } else { magnifier = $("<div>").addClass("image-magnifier-glass").appendTo(element); magnifier.css({ width: o.lensSize, height: o.lensSize, borderRadius: 0, borderWidth: 1, top: y, left: x }).addClass(o.clsLens); if (!Utils.isValue(o.magnifierZoomElement) || $(o.magnifierZoomElement).length === 0) { this.zoomElement = $("<div>").insertAfter(element); } else { this.zoomElement = $(o.magnifierZoomElement); } var zoom_element_width = magnifier[0].offsetWidth * o.magnifierZoom; var zoom_element_height = magnifier[0].offsetHeight * o.magnifierZoom; var cx = zoom_element_width / o.lensSize; var cy = zoom_element_height / o.lensSize; this.zoomElement.css({ width: zoom_element_width, height: zoom_element_height, backgroundImage: "url(" + image[0].src + ")", backgroundRepeat: "no-repeat", backgroundPosition: "-" + (x * cx) + "px -" + (y * cy) + "px", backgroundSize: (image[0].width * cx) + "px " + (image[0].height * cy) + "px" }).addClass(o.clsZoom); } }, _createEvents: function(){ var element = this.element, o = this.options; var glass = element.find(".image-magnifier-glass"); var glass_size = glass[0].offsetWidth / 2; var image = element.find("img")[0]; var zoomElement = this.zoomElement; var cx, cy; if (o.magnifierMode !== "glass") { cx = zoomElement[0].offsetWidth / glass_size / 2; cy = zoomElement[0].offsetHeight / glass_size / 2; zoomElement.css({ backgroundSize: (image.width * cx) + "px " + (image.height * cy) + "px" }); } var lens_move = function(pos){ var x, y; var magic = 4, zoom = parseInt(o.magnifierZoom); if (o.magnifierMode === "glass") { x = pos.x; y = pos.y; if (x > image.width - (glass_size / zoom)) { x = image.width - (glass_size / zoom); } if (x < glass_size / zoom) { x = glass_size / zoom; } if (y > image.height - (glass_size / zoom)) { y = image.height - (glass_size / zoom); } if (y < glass_size / zoom) { y = glass_size / zoom; } glass.css({ top: y - glass_size, left: x - glass_size, backgroundPosition: "-" + ((x * zoom) - glass_size + magic) + "px -" + ((y * zoom) - glass_size + magic) + "px" }); } else { x = pos.x - (glass_size); y = pos.y - (glass_size); if (x > image.width - glass_size * 2) {x = image.width - glass_size * 2;} if (x < 0) {x = 0;} if (y > image.height - glass_size * 2) {y = image.height - glass_size * 2;} if (y < 0) {y = 0;} glass.css({ top: y, left: x }); zoomElement.css({ backgroundPosition: "-" + (x * cx) + "px -" + (y * cy) + "px" }); } }; element.on(Metro.events.move, function(e){ var pos = Utils.getCursorPosition(image, e); lens_move(pos); Utils.exec(o.onMagnifierMove, [pos, glass, zoomElement], element[0]); e.preventDefault(); }); element.on(Metro.events.leave, function(){ var x = element.width() / 2 - o.lensSize / 2; var y = element.height() / 2 - o.lensSize / 2; glass.animate({ top: y, left: x }); lens_move({ x: x + o.lensSize / 2, y: y + o.lensSize / 2 }); }); }, changeAttribute: function(attributeName){ }, destroy: function(){} }; Metro.plugin('imagemagnifier', ImageMagnifier); // Source: js/plugins/info-box.js var InfoBox = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.overlay = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { type: "", width: 480, height: "auto", overlay: true, overlayColor: '#000000', overlayAlpha: .5, autoHide: 0, removeOnClose: false, closeButton: true, clsBox: "", clsBoxContent: "", clsOverlay: "", onOpen: Metro.noop, onClose: Metro.noop, onInfoBoxCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onInfoBoxCreate, [element], element[0]); }, _overlay: function(){ var that = this, element = this.element, o = this.options; var overlay = $("<div>"); overlay.addClass("overlay").addClass(o.clsOverlay); if (o.overlayColor === 'transparent') { overlay.addClass("transparent"); } else { overlay.css({ background: Utils.hex2rgba(o.overlayColor, o.overlayAlpha) }); } return overlay; }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var closer, content; if (o.overlay === true) { this.overlay = this._overlay(); } if (element.attr("id") === undefined) { element.attr("id", Utils.elementId("infobox")); } element.addClass("info-box").addClass(o.type).addClass(o.clsBox); closer = element.find("closer"); if (closer.length === 0) { closer = $("<span>").addClass("button square closer"); closer.appendTo(element); } if (o.closeButton !== true) { closer.hide(); } content = element.find(".info-box-content"); if (content.length > 0) { content.addClass(o.clsBoxContent); } element.css({ width: o.width, height: o.height, visibility: "hidden", top: '100%', left: ( $(window).width() - element.outerWidth() ) / 2 }); element.appendTo($('body')); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".closer", function(){ that.close(); }); element.on(Metro.events.click, ".js-dialog-close", function(){ that.close(); }); $(window).on(Metro.events.resize + "_" + element.attr("id"), function(){ that.reposition(); }); }, _setPosition: function(){ var element = this.element; element.css({ top: ( $(window).height() - element.outerHeight() ) / 2, left: ( $(window).width() - element.outerWidth() ) / 2 }); }, reposition: function(){ this._setPosition(); }, setContent: function(c){ var that = this, element = this.element, o = this.options; var content = element.find(".info-box-content"); if (content.length === 0) { return ; } content.html(c); this.reposition(); }, setType: function(t){ var that = this, element = this.element, o = this.options; element.removeClass("success info alert warning").addClass(t); }, open: function(){ var that = this, element = this.element, o = this.options; if (o.overlay === true) { this.overlay.appendTo($("body")); } this._setPosition(); element.css({ visibility: "visible" }); Utils.exec(o.onOpen, [element], element[0]); element.data("open", true); if (parseInt(o.autoHide) > 0) { setTimeout(function(){ that.close(); }, parseInt(o.autoHide)); } }, close: function(){ var that = this, element = this.element, o = this.options; if (o.overlay === true) { $('body').find('.overlay').remove(); } element.css({ visibility: "hidden", top: "100%" }); Utils.exec(o.onClose, [element], element[0]); element.data("open", false); if (o.removeOnClose === true) { this.destroy(); element.remove(); } }, isOpen: function(){ return this.element.data("open") === true; }, changeAttribute: function(attributeName){ }, destroy: function(){ var that = this, element = this.element, o = this.options; element.off(Metro.events.click, ".closer"); element.off(Metro.events.click, ".js-dialog-close"); $(window).off(Metro.events.resize + "_" + element.attr("id")); } }; Metro.plugin('infobox', InfoBox); Metro['infobox'] = { isInfoBox: function(el){ return Utils.isMetroObject(el, "dialog"); }, open: function(el, c, t){ if (!this.isInfoBox(el)) { return false; } var ib = $(el).data("infobox"); if (c !== undefined) { ib.setContent(c); } if (t !== undefined) { ib.setType(t); } ib.open(); }, close: function(el){ if (!this.isInfoBox(el)) { return false; } var ib = $(el).data("infobox"); ib.close(); }, setContent: function(el, c){ if (!this.isInfoBox(el)) { return false; } if (c === undefined) { c = ""; } var ib = $(el).data("infobox"); ib.setContent(c); ib.reposition(); }, setType: function(el, t){ if (!this.isInfoBox(el)) { return false; } var ib = $(el).data("infobox"); ib.setType(t); ib.reposition(); }, isOpen: function(el){ if (!this.isInfoBox(el)) { return false; } var ib = $(el).data("infobox"); return ib.isOpen(); }, create: function(c, t, o, open){ var el, ib, box_type, con; box_type = t !== undefined ? t : ""; el = $("<div>").appendTo($("body")); $("<div>").addClass("info-box-content").appendTo(el); var ib_options = $.extend({}, { removeOnClose: true, type: box_type }, (o !== undefined ? o : {})); el.infobox(ib_options); ib = el.data('infobox'); ib.setContent(c); if (open !== false) { ib.open(); } return el; } }; // Source: js/plugins/input-material.js var MaterialInput = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.history = []; this.historyIndex = -1; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onInputCreate, [this.element], this.elem); return this; }, options: { label: "", informer: "", icon: "", permanentLabel: false, clsComponent: "", clsInput: "", clsLabel: "", clsInformer: "", clsIcon: "", clsLine: "", onInputCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createStructure(); this._createEvents(); }, _createStructure: function(){ var element = this.element, o = this.options; var container = $("<div>").addClass("input-material " + element[0].className); element[0].className = ""; element.attr("autocomplete", "nope"); if (element.attr("type") === undefined) { element.attr("type", "text"); } container.insertBefore(element); element.appendTo(container); if (Utils.isValue(o.label)) { $("<span>").html(o.label).addClass("label").addClass(o.clsLabel).insertAfter(element); } if (Utils.isValue(o.informer)) { $("<span>").html(o.informer).addClass("informer").addClass(o.clsInformer).insertAfter(element); } if (Utils.isValue(o.icon)) { container.addClass("with-icon"); $("<span>").html(o.icon).addClass("icon").addClass(o.clsIcon).insertAfter(element); } container.append($("<hr>").addClass(o.clsLine)); if (o.permanentLabel === true) { container.addClass("permanent-label"); } container.addClass(o.clsComponent); element.addClass(o.clsInput); if (element.is(":disabled")) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ }, clear: function(){ this.element.val(''); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; } }, destroy: function(){ var element = this.element; var parent = element.parent(); element.insertBefore(parent); parent.remove(); } }; Metro.plugin('materialinput', MaterialInput); // Source: js/plugins/input.js var Input = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.history = []; this.historyIndex = -1; this.autocomplete = []; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onInputCreate, [this.element], this.elem); return this; }, options: { autocomplete: null, autocompleteDivider: ",", autocompleteListHeight: 200, history: false, historyPreset: "", historyDivider: "|", preventSubmit: false, defaultValue: "", size: "default", prepend: "", append: "", copyInlineStyles: true, searchButton: false, clearButton: true, revealButton: true, clearButtonIcon: "<span class='default-icon-cross'></span>", revealButtonIcon: "<span class='default-icon-eye'></span>", searchButtonIcon: "<span class='default-icon-search'></span>", customButtons: [], searchButtonClick: 'submit', clsComponent: "", clsInput: "", clsPrepend: "", clsAppend: "", clsClearButton: "", clsRevealButton: "", clsCustomButton: "", clsSearchButton: "", onHistoryChange: Metro.noop, onHistoryUp: Metro.noop, onHistoryDown: Metro.noop, onClearClick: Metro.noop, onRevealClick: Metro.noop, onSearchButtonClick: Metro.noop, onEnterClick: Metro.noop, onInputCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createStructure(); this._createEvents(); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var container = $("<div>").addClass("input " + element[0].className); var buttons = $("<div>").addClass("button-group"); var clearButton, revealButton, searchButton; if (Utils.isValue(o.historyPreset)) { $.each(Utils.strToArray(o.historyPreset, o.historyDivider), function(){ that.history.push(this); }); that.historyIndex = that.history.length - 1; } if (element.attr("type") === undefined) { element.attr("type", "text"); } if (prev.length === 0) { parent.prepend(container); } else { container.insertAfter(prev); } element.appendTo(container); buttons.appendTo(container); if (!Utils.isValue(element.val().trim())) { element.val(o.defaultValue); } if (o.clearButton === true) { clearButton = $("<button>").addClass("button input-clear-button").addClass(o.clsClearButton).attr("tabindex", -1).attr("type", "button").html(o.clearButtonIcon); clearButton.appendTo(buttons); } if (element.attr('type') === 'password' && o.revealButton === true) { revealButton = $("<button>").addClass("button input-reveal-button").addClass(o.clsRevealButton).attr("tabindex", -1).attr("type", "button").html(o.revealButtonIcon); revealButton.appendTo(buttons); } if (o.searchButton === true) { searchButton = $("<button>").addClass("button input-search-button").addClass(o.clsSearchButton).attr("tabindex", -1).attr("type", o.searchButtonClick === 'submit' ? "submit" : "button").html(o.searchButtonIcon); searchButton.appendTo(buttons); } if (o.prepend !== "") { var prepend = $("<div>").html(o.prepend); prepend.addClass("prepend").addClass(o.clsPrepend).appendTo(container); } if (o.append !== "") { var append = $("<div>").html(o.append); append.addClass("append").addClass(o.clsAppend).appendTo(container); } if (typeof o.customButtons === "string") { o.customButtons = Utils.isObject(o.customButtons); } if (typeof o.customButtons === "object" && Utils.objectLength(o.customButtons) > 0) { $.each(o.customButtons, function(){ var item = this; var customButton = $("<button>"); customButton .addClass("button input-custom-button") .addClass(o.clsCustomButton) .addClass(item.cls) .attr("tabindex", -1) .attr("type", "button") .html(item.html); customButton.data("action", item.onclick); customButton.appendTo(buttons); }); } if (element.attr('dir') === 'rtl' ) { container.addClass("rtl").attr("dir", "rtl"); } element[0].className = ''; if (o.copyInlineStyles === true) { for (var i = 0, l = element[0].style.length; i < l; i++) { container.css(element[0].style[i], element.css(element[0].style[i])); } } container.addClass(o.clsComponent); element.addClass(o.clsInput); if (o.size !== "default") { container.css({ width: o.size }); } if (!Utils.isNull(o.autocomplete)) { var autocomplete_obj = Utils.isObject(o.autocomplete); if (autocomplete_obj !== false) { that.autocomplete = autocomplete_obj; } else { this.autocomplete = Utils.strToArray(o.autocomplete, o.autocompleteDivider); } $("<div>").addClass("autocomplete-list").css({ maxHeight: o.autocompleteListHeight, display: "none" }).appendTo(container); } if (element.is(":disabled")) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var container = element.closest(".input"); var autocompleteList = container.find(".autocomplete-list"); container.on(Metro.events.click, ".input-clear-button", function(){ var curr = element.val(); element.val(Utils.isValue(o.defaultValue) ? o.defaultValue : "").trigger('change').trigger('keyup').focus(); if (autocompleteList.length > 0) { autocompleteList.css({ display: "none" }) } Utils.exec(o.onClearClick, [curr, element.val()], element[0]); }); container.on(Metro.events.start, ".input-reveal-button", function(){ element.attr('type', 'text'); Utils.exec(o.onRevealClick, [element.val()], element[0]); }); container.on(Metro.events.start, ".input-search-button", function(){ if (o.searchButtonClick !== 'submit') { Utils.exec(o.onSearchButtonClick, [element.val(), $(this)], element[0]); } else { this.form.submit(); } }); container.on(Metro.events.stop, ".input-reveal-button", function(){ element.attr('type', 'password').focus(); }); container.on(Metro.events.stop, ".input-custom-button", function(){ var button = $(this); var action = button.data("action"); Utils.exec(action, [element.val(), button], this); }); element.on(Metro.events.keyup, function(e){ var val = element.val().trim(); if (o.history && e.keyCode === Metro.keyCode.ENTER && val !== "") { element.val(""); that.history.push(val); that.historyIndex = that.history.length - 1; Utils.exec(o.onHistoryChange, [val, that.history, that.historyIndex], element[0]); if (o.preventSubmit === true) { e.preventDefault(); } } if (o.history && e.keyCode === Metro.keyCode.UP_ARROW) { that.historyIndex--; if (that.historyIndex >= 0) { element.val(""); element.val(that.history[that.historyIndex]); Utils.exec(o.onHistoryDown, [element.val(), that.history, that.historyIndex], element[0]); } else { that.historyIndex = 0; } e.preventDefault(); } if (o.history && e.keyCode === Metro.keyCode.DOWN_ARROW) { that.historyIndex++; if (that.historyIndex < that.history.length) { element.val(""); element.val(that.history[that.historyIndex]); Utils.exec(o.onHistoryUp, [element.val(), that.history, that.historyIndex], element[0]); } else { that.historyIndex = that.history.length - 1; } e.preventDefault(); } }); element.on(Metro.events.keydown, function(e){ if (e.keyCode === Metro.keyCode.ENTER) { Utils.exec(o.onEnterClick, [element.val()], element[0]); } }); element.on(Metro.events.blur, function(){ container.removeClass("focused"); }); element.on(Metro.events.focus, function(){ container.addClass("focused"); }); element.on(Metro.events.input, function(){ var val = this.value.toLowerCase(); var items; if (autocompleteList.length === 0) { return; } autocompleteList.html(""); items = that.autocomplete.filter(function(item){ return item.toLowerCase().indexOf(val) > -1; }); autocompleteList.css({ display: items.length > 0 ? "block" : "none" }); $.each(items, function(i, v){ var index = v.toLowerCase().indexOf(val); var item = $("<div>").addClass("item").attr("data-autocomplete-value", v); var html; if (index === 0) { html = "<strong>"+v.substr(0, val.length)+"</strong>"+v.substr(val.length); } else { html = v.substr(0, index) + "<strong>"+v.substr(index, val.length)+"</strong>"+v.substr(index + val.length); } item.html(html).appendTo(autocompleteList); }) }); container.on(Metro.events.click, ".autocomplete-list .item", function(){ element.val($(this).attr("data-autocomplete-value")); autocompleteList.css({ display: "none" }); element.trigger("change"); }); }, getHistory: function(){ return this.history; }, getHistoryIndex: function(){ return this.historyIndex; }, setHistoryIndex: function(val){ this.historyIndex = val >= this.history.length ? this.history.length - 1 : val; }, setHistory: function(history, append) { var that = this, o = this.options; if (Utils.isNull(history)) return; if (!Array.isArray(history)) { history = Utils.strToArray(history, o.historyDivider); } if (append === true) { $.each(history, function () { that.history.push(this); }) } else{ this.history = history; } this.historyIndex = this.history.length - 1; }, clear: function(){ this.element.val(''); }, toDefault: function(){ this.element.val(Utils.isValue(this.options.defaultValue) ? this.options.defaultValue : ""); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; } }, destroy: function(){ var element = this.element; var parent = element.parent(); var clearBtn = parent.find(".input-clear-button"); var revealBtn = parent.find(".input-reveal-button"); var customBtn = parent.find(".input-custom-button"); if (clearBtn.length > 0) { clearBtn.off(Metro.events.click); } if (revealBtn.length > 0) { revealBtn.off(Metro.events.start); revealBtn.off(Metro.events.stop); } if (customBtn.length > 0) { clearBtn.off(Metro.events.click); } element.off(Metro.events.blur); element.off(Metro.events.focus); element.insertBefore(parent); parent.remove(); } }; Metro.plugin('input', Input); $(document).on(Metro.events.click, function(e){ $('.input .autocomplete-list').hide(); }); // Source: js/plugins/keypad.js var Keypad = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.value = ""; this.positions = ["top-left", "top", "top-right", "right", "bottom-right", "bottom", "bottom-left", "left"]; this.keypad = null; this._setOptionsFromDOM(); this.keys = Utils.strToArray(this.options.keys, ","); this.keys_to_work = this.keys; this._create(); return this; }, options: { keySize: 32, keys: "1, 2, 3, 4, 5, 6, 7, 8, 9, 0", copyInlineStyles: false, target: null, length: 0, shuffle: false, shuffleCount: 3, position: Metro.position.BOTTOM_LEFT, //top-left, top, top-right, right, bottom-right, bottom, bottom-left, left dynamicPosition: false, serviceButtons: true, showValue: true, open: false, sizeAsKeys: false, clsKeypad: "", clsInput: "", clsKeys: "", clsKey: "", clsServiceKey: "", clsBackspace: "", clsClear: "", onChange: Metro.noop, onClear: Metro.noop, onBackspace: Metro.noop, onShuffle: Metro.noop, onKey: Metro.noop, onKeypadCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createKeypad(); if (this.options.shuffle === true) { this.shuffle(); } this._createKeys(); this._createEvents(); Utils.exec(this.options.onKeypadCreate, [this.element]); }, _createKeypad: function(){ var element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var keypad, keys; if (parent.hasClass("input")) { keypad = parent; } else { keypad = $("<div>").addClass("input").addClass(element[0].className); } keypad.addClass("keypad"); if (keypad.css("position") === "static" || keypad.css("position") === "") { keypad.css({ position: "relative" }); } if (element.attr("type") === undefined) { element.attr("type", "text"); } if (prev.length === 0) { parent.prepend(keypad); } else { keypad.insertAfter(prev); } element.attr("readonly", true); element.appendTo(keypad); keys = $("<div>").addClass("keys").addClass(o.clsKeys); keys.appendTo(keypad); this._setKeysPosition(); if (o.open === true) { keys.addClass("open keep-open"); } element[0].className = ''; if (o.copyInlineStyles === true) { for (var i = 0, l = element[0].style.length; i < l; i++) { keypad.css(element[0].style[i], element.css(element[0].style[i])); } } element.addClass(o.clsInput); keypad.addClass(o.clsKeypad); element.on(Metro.events.blur, function(){keypad.removeClass("focused");}); element.on(Metro.events.focus, function(){keypad.addClass("focused");}); if (o.disabled === true || element.is(":disabled")) { this.disable(); } else { this.enable(); } this.keypad = keypad; }, _setKeysPosition: function(){ var element = this.element, o = this.options; var keypad = element.parent(); var keys = keypad.find(".keys"); keys.removeClass(this.positions.join(" ")).addClass(o.position) }, _createKeys: function(){ var element = this.element, o = this.options; var keypad = element.parent(); var factor = Math.round(Math.sqrt(this.keys.length + 2)); var key_size = o.keySize; var width = factor * key_size + factor * 4; var key, keys = keypad.find(".keys"); keys.html(""); $.each(this.keys_to_work, function(){ key = $("<span>").addClass("key").addClass(o.clsKey).html(this); key.data("key", this); key.css({ width: o.keySize, height: o.keySize, lineHeight: o.keySize - 4 + "px" }).appendTo(keys); }); if (o.serviceButtons === true) { var service_keys = ['&larr;', '&times;']; $.each(service_keys, function () { key = $("<span>").addClass("key service-key").addClass(o.clsKey).addClass(o.clsServiceKey).html(this); if (this === '&larr;') { key.addClass(o.clsBackspace); } if (this === '&times;') { key.addClass(o.clsClear); } key.data("key", this); key.css({ width: o.keySize, height: o.keySize, lineHeight: o.keySize - 4 + "px" }).appendTo(keys); }); } keys.width(width); if (o.sizeAsKeys === true && ['top-left', 'top', 'top-right', 'bottom-left', 'bottom', 'bottom-right'].indexOf(o.position) !== -1) { keypad.outerWidth(keys.outerWidth()); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var keypad = element.parent(); var keys = keypad.find(".keys"); keypad.on(Metro.events.click, ".keys", function(e){ e.preventDefault(); e.stopPropagation(); }); keypad.on(Metro.events.click, function(e){ if (o.open === true) { return ; } if (keys.hasClass("open") === true) { keys.removeClass("open"); } else { keys.addClass("open"); } e.preventDefault(); e.stopPropagation(); }); keypad.on(Metro.events.click, ".key", function(e){ var key = $(this); if (key.data('key') !== '&larr;' && key.data('key') !== '&times;') { if (o.length > 0 && (String(that.value).length === o.length)) { return false; } that.value = that.value + "" + key.data('key'); if (o.shuffle === true) { that.shuffle(); that._createKeys(); } if (o.dynamicPosition === true) { o.position = that.positions[Utils.random(0, that.positions.length - 1)]; that._setKeysPosition(); } Utils.exec(o.onKey, [key.data('key'), that.value, element]); } else { if (key.data('key') === '&times;') { that.value = ""; Utils.exec(o.onClear, [element]); } if (key.data('key') === '&larr;') { that.value = (that.value.substring(0, that.value.length - 1)); Utils.exec(o.onBackspace, [that.value, element]); } } if (o.showValue === true) { if (element[0].tagName === "INPUT") { element.val(that.value); } else { element.text(that.value); } } element.trigger('change'); Utils.exec(o.onChange, [that.value, element]); e.preventDefault(); e.stopPropagation(); }); if (o.target !== null) { element.on(Metro.events.change, function(){ var t = $(o.target); if (t.length === 0) { return ; } if (t[0].tagName === "INPUT") { t.val(that.value); } else { t.text(that.value); } }); } }, shuffle: function(){ for (var i = 0; i < this.options.shuffleCount; i++) { this.keys_to_work = this.keys_to_work.shuffle(); } Utils.exec(this.options.onShuffle, [this.keys_to_work, this.keys, this.element]); }, shuffleKeys: function(count){ if (count === undefined) { count = this.options.shuffleCount; } for (var i = 0; i < count; i++) { this.keys_to_work = this.keys_to_work.shuffle(); } this._createKeys(); }, val: function(v){ if (v !== undefined) { this.value = v; this.element[0].tagName === "INPUT" ? this.element.val(v) : this.element.text(v); } else { return this.value; } }, open: function(){ var element = this.element; var keypad = element.parent(); var keys = keypad.find(".keys"); keys.addClass("open"); }, close: function(){ var element = this.element; var keypad = element.parent(); var keys = keypad.find(".keys"); keys.removeClass("open"); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, setPosition: function(pos){ var new_position = pos !== undefined ? pos : this.element.attr("data-position"); if (this.positions.indexOf(new_position) === -1) { return ; } this.options.position = new_position; this._setKeysPosition(); }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; case 'data-position': this.setPosition(); break; } }, destroy: function(){ var element = this.element, keypad = this.keypad; keypad.off(Metro.events.click, ".keys"); keypad.off(Metro.events.click); keypad.off(Metro.events.click, ".key"); element.off(Metro.events.change); element.insertBefore(keypad); keypad.remove(); } }; Metro.plugin('keypad', Keypad); $(document).on(Metro.events.click, function(){ var keypads = $(".keypad .keys"); $.each(keypads, function(){ if (!$(this).hasClass("keep-open")) { $(this).removeClass("open"); } }); }); // Source: js/plugins/list.js var List = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.currentPage = 1; this.pagesCount = 1; this.filterString = ""; this.data = null; this.activity = null; this.busy = false; this.filters = []; this.wrapperInfo = null; this.wrapperSearch = null; this.wrapperRows = null; this.wrapperPagination = null; this.filterIndex = null; this.filtersIndexes = []; this.sort = { dir: "asc", colIndex: 0 }; this.header = null; this.items = []; this._setOptionsFromDOM(); this._create(); return this; }, options: { thousandSeparator: ",", decimalSeparator: ",", sortTarget: "li", sortClass: null, sortDir: "asc", sortInitial: false, filterClass: null, filter: null, filterString: "", filters: null, source: null, showItemsSteps: false, showSearch: false, showListInfo: false, showPagination: false, showAllPages: false, showActivity: true, muteList: true, items: -1, itemsSteps: "all, 10,25,50,100", itemsAllTitle: "Show all", listItemsCountTitle: "Show entries:", listSearchTitle: "Search:", listInfoTitle: "Showing $1 to $2 of $3 entries", paginationPrevTitle: "Prev", paginationNextTitle: "Next", activityType: "cycle", activityStyle: "color", activityTimeout: 100, searchWrapper: null, rowsWrapper: null, infoWrapper: null, paginationWrapper: null, clsComponent: "", clsList: "", clsListItem: "", clsListTop: "", clsItemsCount: "", clsSearch: "", clsListBottom: "", clsListInfo: "", clsListPagination: "", clsPagination: "", onDraw: Metro.noop, onDrawItem: Metro.noop, onSortStart: Metro.noop, onSortStop: Metro.noop, onSortItemSwitch: Metro.noop, onSearch: Metro.noop, onRowsCountChange: Metro.noop, onDataLoad: Metro.noop, onDataLoaded: Metro.noop, onFilterItemAccepted: Metro.noop, onFilterItemDeclined: Metro.noop, onListCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; if (o.source !== null) { Utils.exec(o.onDataLoad, [o.source], element[0]); $.get(o.source, function(data){ that._build(data); Utils.exec(o.onDataLoaded, [o.source, data], element[0]); }).fail(function( jqXHR, textStatus, errorThrown) { console.log(textStatus); console.log(jqXHR); console.log(errorThrown); }); } else { that._build(); } }, _build: function(data){ var element = this.element, o = this.options; if (Utils.isValue(data)) { this._createItemsFromJSON(data); } else { this._createItemsFromHTML() } this._createStructure(); this._createEvents(); Utils.exec(o.onListCreate, [element], element[0]); }, _createItemsFromHTML: function(){ var that = this, element = this.element, o = this.options; this.items = []; $.each(element.children(o.sortTarget), function(){ that.items.push(this); }); }, _createItemsFromJSON: function(source){ var that = this; this.items = []; if (Utils.isValue(source.header)) { that.header = source.header; } if (Utils.isValue(source.data)) { $.each(source.data, function(){ var row = this; var li = document.createElement("li"); var inner = Utils.isValue(that.header.template) ? that.header.template : ""; $.each(row, function(k, v){ inner = inner.replace("$"+k, v); }); li.innerHTML = inner; that.items.push(li); }); } }, _createTopBlock: function (){ var that = this, element = this.element, o = this.options; var top_block = $("<div>").addClass("list-top").addClass(o.clsListTop).insertBefore(element); var search_block, search_input, rows_block, rows_select; search_block = Utils.isValue(this.wrapperSearch) ? this.wrapperSearch : $("<div>").addClass("list-search-block").addClass(o.clsSearch).appendTo(top_block); search_input = $("<input>").attr("type", "text").appendTo(search_block); search_input.input({ prepend: o.listSearchTitle }); if (o.showSearch !== true) { search_block.hide(); } rows_block = Utils.isValue(this.wrapperRows) ? this.wrapperRows : $("<div>").addClass("list-rows-block").addClass(o.clsItemsCount).appendTo(top_block); rows_select = $("<select>").appendTo(rows_block); $.each(Utils.strToArray(o.itemsSteps), function () { var option = $("<option>").attr("value", this === "all" ? -1 : this).text(this === "all" ? o.itemsAllTitle : this).appendTo(rows_select); if (parseInt(this) === parseInt(o.items)) { option.attr("selected", "selected"); } }); rows_select.select({ filter: false, prepend: o.listItemsCountTitle, onChange: function (val) { if (parseInt(val) === parseInt(o.items)) { return; } o.items = parseInt(val); that.currentPage = 1; that._draw(); Utils.exec(o.onRowsCountChange, [val], element[0]) } }); if (o.showItemsSteps !== true) { rows_block.hide(); } return top_block; }, _createBottomBlock: function (){ var element = this.element, o = this.options; var bottom_block = $("<div>").addClass("list-bottom").addClass(o.clsListBottom).insertAfter(element); var info, pagination; info = $("<div>").addClass("list-info").addClass(o.clsListInfo).appendTo(bottom_block); if (o.showListInfo !== true) { info.hide(); } pagination = $("<div>").addClass("list-pagination").addClass(o.clsListPagination).appendTo(bottom_block); if (o.showPagination !== true) { pagination.hide(); } return bottom_block; }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var list_component; var w_search = $(o.searchWrapper), w_info = $(o.infoWrapper), w_rows = $(o.rowsWrapper), w_paging = $(o.paginationWrapper); if (w_search.length > 0) {this.wrapperSearch = w_search;} if (w_info.length > 0) {this.wrapperInfo = w_info;} if (w_rows.length > 0) {this.wrapperRows = w_rows;} if (w_paging.length > 0) {this.wrapperPagination = w_paging;} if (!element.parent().hasClass("list-component")) { list_component = $("<div>").addClass("list-component").insertBefore(element); element.appendTo(list_component); } else { list_component = element.parent(); } list_component.addClass(o.clsComponent); this.activity = $("<div>").addClass("list-progress").appendTo(list_component); $("<div>").activity({ type: o.activityType, style: o.activityStyle }).appendTo(this.activity); if (o.showActivity !== true) { this.activity.css({ visibility: "hidden" }) } // element.html("").addClass(o.clsList); element.addClass(o.clsList); this._createTopBlock(); this._createBottomBlock(); if (Utils.isValue(o.filterString)) { this.filterString = o.filterString; } var filter_func; if (Utils.isValue(o.filter)) { filter_func = Utils.isFunc(o.filter); if (filter_func === false) { filter_func = Utils.func(o.filter); } that.filterIndex = that.addFilter(filter_func); } if (Utils.isValue(o.filters)) { $.each(Utils.strToArray(o.filters), function(){ filter_func = Utils.isFunc(this); if (filter_func !== false) { that.filtersIndexes.push(that.addFilter(filter_func)); } }); } this.currentPage = 1; this.sorting(o.sortClass, o.sortDir, true); }, _createEvents: function(){ var that = this, element = this.element; var component = element.parent(); var search = component.find(".list-search-block input"); var customSearch; search.on(Metro.events.inputchange, function(){ that.filterString = this.value.trim().toLowerCase(); if (that.filterString[that.filterString.length - 1] === ":") { return ; } that.currentPage = 1; that._draw(); }); if (Utils.isValue(this.wrapperSearch)) { customSearch = this.wrapperSearch.find("input"); if (customSearch.length > 0) { customSearch.on(Metro.events.inputchange, function(){ that.filterString = this.value.trim().toLowerCase(); if (that.filterString[that.filterString.length - 1] === ":") { return ; } that.currentPage = 1; that._draw(); }); } } function pageLinkClick(l){ var link = $(l); var item = link.parent(); if (item.hasClass("active")) { return ; } if (item.hasClass("service")) { if (link.data("page") === "prev") { that.currentPage--; if (that.currentPage === 0) { that.currentPage = 1; } } else { that.currentPage++; if (that.currentPage > that.pagesCount) { that.currentPage = that.pagesCount; } } } else { that.currentPage = link.data("page"); } that._draw(); } component.on(Metro.events.click, ".pagination .page-link", function(){ pageLinkClick(this) }); if (Utils.isValue(this.wrapperPagination)) { this.wrapperPagination.on(Metro.events.click, ".pagination .page-link", function(){ pageLinkClick(this) }); } }, _info: function(start, stop, length){ var element = this.element, o = this.options; var component = element.parent(); var info = Utils.isValue(this.wrapperInfo) ? this.wrapperInfo : component.find(".list-info"); var text; if (info.length === 0) { return ; } if (stop > length) { stop = length; } if (this.items.length === 0) { start = stop = length = 0; } text = o.listInfoTitle; text = text.replace("$1", start); text = text.replace("$2", stop); text = text.replace("$3", length); info.html(text); }, _paging: function(length){ var that = this, element = this.element, o = this.options; var component = element.parent(); var pagination_wrapper = Utils.isValue(this.wrapperPagination) ? this.wrapperPagination : component.find(".list-pagination"); var i, prev, next; var shortDistance = 5; var pagination; pagination_wrapper.html(""); pagination = $("<ul>").addClass("pagination").addClass(o.clsPagination).appendTo(pagination_wrapper); if (this.items.length === 0) { return ; } this.pagesCount = Math.ceil(length / o.items); var add_item = function(item_title, item_type, data){ var li, a; li = $("<li>").addClass("page-item").addClass(item_type); a = $("<a>").addClass("page-link").html(item_title); a.data("page", data); a.appendTo(li); return li; }; prev = add_item(o.paginationPrevTitle, "service prev-page", "prev"); pagination.append(prev); pagination.append(add_item(1, that.currentPage === 1 ? "active" : "", 1)); if (o.showAllPages === true || this.pagesCount <= 7) { for (i = 2; i < this.pagesCount; i++) { pagination.append(add_item(i, i === that.currentPage ? "active" : "", i)); } } else { if (that.currentPage < shortDistance) { for (i = 2; i <= shortDistance; i++) { pagination.append(add_item(i, i === that.currentPage ? "active" : "", i)); } if (this.pagesCount > shortDistance) { pagination.append(add_item("...", "no-link", null)); } } else if (that.currentPage <= that.pagesCount && that.currentPage > that.pagesCount - shortDistance + 1) { if (this.pagesCount > shortDistance) { pagination.append(add_item("...", "no-link", null)); } for (i = that.pagesCount - shortDistance + 1; i < that.pagesCount; i++) { pagination.append(add_item(i, i === that.currentPage ? "active" : "", i)); } } else { pagination.append(add_item("...", "no-link", null)); pagination.append(add_item(that.currentPage - 1, "", that.currentPage - 1)); pagination.append(add_item(that.currentPage, "active", that.currentPage)); pagination.append(add_item(that.currentPage + 1, "", that.currentPage + 1)); pagination.append(add_item("...", "no-link", null)); } } if (that.pagesCount > 1 || that.currentPage < that.pagesCount) pagination.append(add_item(that.pagesCount, that.currentPage === that.pagesCount ? "active" : "", that.pagesCount)); next = add_item(o.paginationNextTitle, "service next-page", "next"); pagination.append(next); if (this.currentPage === 1) { prev.addClass("disabled"); } if (this.currentPage === this.pagesCount) { next.addClass("disabled"); } }, _filter: function(){ var that = this, element = this.element, o = this.options, items, i, data, inset, c1, result; if (Utils.isValue(this.filterString) || this.filters.length > 0) { items = this.items.filter(function(item){ data = ""; if (Utils.isValue(o.filterClass)) { inset = item.getElementsByClassName(o.filterClass); if (inset.length > 0) for (i = 0; i < inset.length; i++) { data += inset[i].textContent; } } else { data = item.textContent; } c1 = data.replace(/[\n\r]+|[\s]{2,}/g, ' ').trim().toLowerCase(); result = Utils.isValue(that.filterString) ? c1.indexOf(that.filterString) > -1 : true; if (result === true && that.filters.length > 0) { for (i = 0; i < that.filters.length; i++) { if (Utils.exec(that.filters[i], [item]) !== true) { result = false; break; } } } if (result) { Utils.exec(o.onFilterItemAccepted, [item], element[0]); } else { Utils.exec(o.onFilterItemDeclined, [item], element[0]); } return result; }); Utils.exec(o.onSearch, [that.filterString, items], element[0]) } else { items = this.items; } return items; }, _draw: function(cb){ var element = this.element, o = this.options; var i; var start = o.items === -1 ? 0 : o.items * (this.currentPage - 1), stop = o.items === -1 ? this.items.length - 1 : start + o.items - 1; var items; items = this._filter(); element.children(o.sortTarget).remove(); for (i = start; i <= stop; i++) { if (Utils.isValue(items[i])) { $(items[i]).addClass(o.clsListItem).appendTo(element); } Utils.exec(o.onDrawItem, [items[i]], element[0]); } this._info(start + 1, stop + 1, items.length); this._paging(items.length); this.activity.hide(); Utils.exec(o.onDraw, [element], element[0]); if (cb !== undefined) { Utils.exec(cb, [element], element[0]) } }, _getItemContent: function(item){ var o = this.options, $item = $(item); var i, inset, data; var format, formatMask = Utils.isValue($item.data("formatMask")) ? $item.data("formatMask") : null; if (Utils.isValue(o.sortClass)) { data = ""; inset = $(item).find("."+o.sortClass); if (inset.length > 0) for (i = 0; i < inset.length; i++) { data += inset[i].textContent; } format = inset.length > 0 ? inset[0].getAttribute("data-format") : ""; } else { data = item.textContent; format = item.getAttribute("data-format"); } data = (""+data).toLowerCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim(); if (Utils.isValue(format)) { if (['number', 'int', 'integer', 'float', 'money'].indexOf(format) !== -1 && (o.thousandSeparator !== "," || o.decimalSeparator !== "." )) { data = Utils.parseNumber(data, o.thousandSeparator, o.decimalSeparator); } switch (format) { case "date": data = Utils.isValue(formatMask) ? data.toDate(formatMask) : new Date(data); break; case "number": data = Number(data); break; case "int": case "integer": data = parseInt(data); break; case "float": data = parseFloat(data); break; case "money": data = Utils.parseMoney(data); break; case "card": data = Utils.parseCard(data); break; case "phone": data = Utils.parsePhone(data); break; } } return data; }, deleteItem: function(value){ var i, deleteIndexes = [], item; var is_func = Utils.isFunc(value); for (i = 0; i < this.items.length; i++) { item = this.items[i]; if (is_func) { if (Utils.exec(value, [item])) { deleteIndexes.push(i); } } else { if (item.textContent.contains(value)) { deleteIndexes.push(i); } } } this.items = Utils.arrayDeleteByMultipleKeys(this.items, deleteIndexes); return this; }, draw: function(){ return this._draw(); }, sorting: function(source, dir, redraw){ var that = this, element = this.element, o = this.options; if (Utils.isValue(source)) { o.sortClass = source; } if (Utils.isValue(dir) && ["asc", "desc"].indexOf(dir) > -1) { o.sortDir= dir; } Utils.exec(o.onSortStart, [this.items], element[0]); this.items.sort(function(a, b){ var c1 = that._getItemContent(a); var c2 = that._getItemContent(b); var result = 0; if (c1 < c2) { result = o.sortDir === "asc" ? -1 : 1; } if (c1 > c2) { result = o.sortDir === "asc" ? 1 : -1; } if (result !== 0) { Utils.exec(o.onSortItemSwitch, [a, b, result], element[0]); } return result; }); Utils.exec(o.onSortStop, [this.items], element[0]); if (redraw === true) { this._draw(); } return this; }, filter: function(val){ this.filterString = val.trim().toLowerCase(); this.currentPage = 1; this._draw(); }, loadData: function(source){ var that = this, element = this.element, o = this.options; if (Utils.isValue(source) !== true) { return ; } o.source = source; Utils.exec(o.onDataLoad, [o.source], element[0]); $.get(o.source, function(data){ Utils.exec(o.onDataLoaded, [o.source, data], element[0]); that._createItemsFromJSON(data); element.html(""); if (Utils.isValue(o.filterString)) { that.filterString = o.filterString; } var filter_func; if (Utils.isValue(o.filter)) { filter_func = Utils.isFunc(o.filter); if (filter_func === false) { filter_func = Utils.func(o.filter); } that.filterIndex = that.addFilter(filter_func); } if (Utils.isValue(o.filters)) { $.each(Utils.strToArray(o.filters), function(){ filter_func = Utils.isFunc(this); if (filter_func !== false) { that.filtersIndexes.push(that.addFilter(filter_func)); } }); } that.currentPage = 1; that.sorting(o.sortClass, o.sortDir, true); }).fail(function( jqXHR, textStatus, errorThrown) { console.log(textStatus); console.log(jqXHR); console.log(errorThrown); }); }, next: function(){ if (this.items.length === 0) return ; this.currentPage++; if (this.currentPage > this.pagesCount) { this.currentPage = this.pagesCount; return ; } this._draw(); }, prev: function(){ if (this.items.length === 0) return ; this.currentPage--; if (this.currentPage === 0) { this.currentPage = 1; return ; } this._draw(); }, first: function(){ if (this.items.length === 0) return ; this.currentPage = 1; this._draw(); }, last: function(){ if (this.items.length === 0) return ; this.currentPage = this.pagesCount; this._draw(); }, page: function(num){ if (num <= 0) { num = 1; } if (num > this.pagesCount) { num = this.pagesCount; } this.currentPage = num; this._draw(); }, addFilter: function(f, redraw){ var func = Utils.isFunc(f); if (func === false) { return ; } this.filters.push(func); if (redraw === true) { this.currentPage = 1; this.draw(); } return this.filters.length - 1; }, removeFilter: function(key, redraw){ Utils.arrayDeleteByKey(this.filters, key); if (redraw === true) { this.currentPage = 1; this.draw(); } return this; }, removeFilters: function(redraw){ this.filters = []; if (redraw === true) { this.currentPage = 1; this.draw(); } }, getFilters: function(){ return this.filters; }, getFilterIndex: function(){ return this.filterIndex; }, getFiltersIndexes: function(){ return this.filtersIndexes; }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var changeSortDir = function(){ var dir = element.attr("data-sort-dir"); if (!Utils.isValue(dir)) { return ; } o.sortDir = dir; that.sorting(o.sortClass, o.sortDir, true); }; var changeSortClass = function(){ var target = element.attr("data-sort-source"); if (!Utils.isValue(target)) { return ; } o.sortClass = target; that.sorting(o.sortClass, o.sortDir, true); }; var changeFilterString = function(){ var filter = element.attr("data-filter-string"); if (!Utils.isValue(target)) { return ; } o.filterString = filter; that.filter(o.filterString); }; switch (attributeName) { case "data-sort-dir": changeSortDir(); break; case "data-sort-source": changeSortClass(); break; case "data-filter-string": changeFilterString(); break; } }, destroy: function(){} }; Metro.plugin('list', List); // Source: js/plugins/listview.js var Listview = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, options: { selectable: false, checkStyle: 1, effect: "slide", duration: 100, view: Metro.listView.LIST, selectCurrent: true, structure: {}, onNodeInsert: Metro.noop, onNodeDelete: Metro.noop, onNodeClean: Metro.noop, onCollapseNode: Metro.noop, onExpandNode: Metro.noop, onGroupNodeClick: Metro.noop, onNodeClick: Metro.noop, onListviewCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createView(); this._createEvents(); Utils.exec(o.onListviewCreate, [element]); }, _createIcon: function(data){ var icon, src; src = Utils.isTag(data) ? $(data) : $("<img>").attr("src", data); icon = $("<span>").addClass("icon"); icon.html(src); return icon; }, _createCaption: function(data){ return $("<div>").addClass("caption").html(data); }, _createContent: function(data){ return $("<div>").addClass("content").html(data); }, _createToggle: function(){ return $("<span>").addClass("node-toggle"); }, _createNode: function(data){ var that = this, o = this.options; var node; node = $("<li>"); if (data.caption !== undefined || data.content !== undefined ) { var d = $("<div>").addClass("data"); node.prepend(d); if (data.caption !== undefined) d.append(that._createCaption(data.caption)); if (data.content !== undefined) d.append(that._createContent(data.content)); } if (data.icon !== undefined) { node.prepend(this._createIcon(data.icon)); } if (Utils.objectLength(o.structure) > 0) $.each(o.structure, function(key, val){ if (data[key] !== undefined) { $("<div>").addClass("node-data item-data-"+key).addClass(data[val]).html(data[key]).appendTo(node); } }); return node; }, _createView: function(){ var that = this, element = this.element, o = this.options; var nodes = element.find("li"); var struct_length = Utils.objectLength(o.structure); element.addClass("listview"); element.find("ul").addClass("listview"); $.each(nodes, function(){ var node = $(this); if (node.data("caption") !== undefined || node.data("content") !== undefined) { var data = $("<div>").addClass("data"); node.prepend(data); if (node.data("caption") !== undefined) data.append(that._createCaption(node.data("caption"))); if (node.data("content") !== undefined) data.append(that._createContent(node.data("content"))); } if (node.data('icon') !== undefined) { node.prepend(that._createIcon(node.data('icon'))); } if (node.children("ul").length > 0) { node.addClass("node-group"); node.append(that._createToggle()); if (node.data("collapsed") !== true) node.addClass("expanded"); } else { node.addClass("node"); } if (node.hasClass("node")) { var cb = $("<input type='checkbox' data-role='checkbox' data-style='"+o.checkStyle+"'>"); cb.data("node", node); node.prepend(cb); } if (struct_length > 0) $.each(o.structure, function(key){ if (node.data(key) !== undefined) { $("<div>").addClass("node-data item-data-"+key).addClass(node.data(key)).html(node.data(key)).appendTo(node); } }); }); this.toggleSelectable(); this.view(o.view); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".node", function(){ var node = $(this); element.find(".node").removeClass("current"); node.toggleClass("current"); if (o.selectCurrent === true) { element.find(".node").removeClass("current-select"); node.toggleClass("current-select"); } Utils.exec(o.onNodeClick, [node, element]) }); element.on(Metro.events.click, ".node-toggle", function(){ var node = $(this).closest("li"); that.toggleNode(node); }); element.on(Metro.events.click, ".node-group > .data > .caption", function(){ var node = $(this).closest("li"); element.find(".node-group").removeClass("current-group"); node.addClass("current-group"); Utils.exec(o.onGroupNodeClick, [node, element]) }); element.on(Metro.events.dblclick, ".node-group > .data > .caption", function(){ var node = $(this).closest("li"); that.toggleNode(node); }); }, view: function(v){ var element = this.element, o = this.options; if (v === undefined) { return o.view; } o.view = v; $.each(Metro.listView, function(i, v){ element.removeClass("view-"+v); element.find("ul").removeClass("view-"+v); }); element.addClass("view-" + o.view); element.find("ul").addClass("view-" + o.view); }, toggleNode: function(node){ var element = this.element, o = this.options; var func; if (!node.hasClass("node-group")) { return ; } node.toggleClass("expanded"); if (o.effect === "slide") { func = node.hasClass("expanded") !== true ? "slideUp" : "slideDown"; Utils.exec(o.onCollapseNode, [node, element]); } else { func = node.hasClass("expanded") !== true ? "fadeOut" : "fadeIn"; Utils.exec(o.onExpandNode, [node, element]); } node.children("ul")[func](o.duration); }, toggleSelectable: function(){ var element = this.element, o = this.options; var func = o.selectable === true ? "addClass" : "removeClass"; element[func]("selectable"); element.find("ul")[func]("selectable"); }, add: function(node, data){ var element = this.element, o = this.options; var target; var new_node; var toggle; if (node === null) { target = element; } else { if (!node.hasClass("node-group")) { return ; } target = node.children("ul"); if (target.length === 0) { target = $("<ul>").addClass("listview").addClass("view-"+o.view).appendTo(node); toggle = this._createToggle(); toggle.appendTo(node); node.addClass("expanded"); } } new_node = this._createNode(data); new_node.addClass("node").appendTo(target); var cb = $("<input type='checkbox'>"); cb.data("node", new_node); new_node.prepend(cb); cb.checkbox(); Utils.exec(o.onNodeInsert, [new_node, element]); return new_node; }, addGroup: function(data){ var element = this.element, o = this.options; var node; delete data['icon']; node = this._createNode(data); node.addClass("node-group").appendTo(element); node.append(this._createToggle()); node.addClass("expanded"); node.append($("<ul>").addClass("listview").addClass("view-"+o.view)); Utils.exec(o.onNodeInsert, [node, element]); return node; }, insertBefore: function(node, data){ var element = this.element, o = this.options; if (!node.length) {return;} var new_node = this._createNode(data); new_node.addClass("node").insertBefore(node); Utils.exec(o.onNodeInsert, [new_node, element]); return new_node; }, insertAfter: function(node, data){ var element = this.element, o = this.options; if (!node.length) {return;} var new_node = this._createNode(data); new_node.addClass("node").insertAfter(node); Utils.exec(o.onNodeInsert, [new_node, element]); return new_node; }, del: function(node){ var element = this.element, o = this.options; if (!node.length) {return;} var parent_list = node.closest("ul"); var parent_node = parent_list.closest("li"); node.remove(); if (parent_list.children().length === 0 && !parent_list.is(element)) { parent_list.remove(); parent_node.removeClass("expanded"); parent_node.children(".node-toggle").remove(); } Utils.exec(o.onNodeDelete, [node, element]); }, clean: function(node){ var element = this.element, o = this.options; if (!node.length) {return;} node.children("ul").remove(); node.removeClass("expanded"); node.children(".node-toggle").remove(); Utils.exec(o.onNodeClean, [node, element]); }, getSelected: function(){ var element = this.element; var nodes = []; $.each(element.find(":checked"), function(){ var check = $(this); nodes.push(check.closest(".node")[0]) }); return nodes; }, clearSelected: function(){ this.element.find(":checked").prop("checked", false); this.element.trigger('change'); }, selectAll: function(mode){ this.element.find(".node > .checkbox input").prop("checked", mode !== false); this.element.trigger('change'); }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var changeView = function(){ var new_view = "view-"+element.attr("data-view"); that.view(new_view); }; var changeSelectable = function(){ o.selectable = JSON.parse(element.attr("data-selectable")) === true; that.toggleSelectable(); }; switch (attributeName) { case "data-view": changeView(); break; case "data-selectable": changeSelectable(); break; } } }; Metro.plugin('listview', Listview); // Source: js/plugins/master.js var Master = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.pages = []; this.currentIndex = 0; this.isAnimate = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { effect: "slide", // slide, fade, switch, slowdown, custom effectFunc: "linear", duration: METRO_ANIMATION_DURATION, controlPrev: "<span class='default-icon-left-arrow'></span>", controlNext: "<span class='default-icon-right-arrow'></span>", controlTitle: "Master, page $1 of $2", backgroundImage: "", clsMaster: "", clsControls: "", clsControlPrev: "", clsControlNext: "", clsControlTitle: "", clsPages: "", clsPage: "", onBeforePage: Metro.noop_true, onBeforeNext: Metro.noop_true, onBeforePrev: Metro.noop_true, onMasterCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; element.addClass("master").addClass(o.clsMaster); element.css({ backgroundImage: "url("+o.backgroundImage+")" }); this._createControls(); this._createPages(); this._createEvents(); Utils.exec(this.options.onMasterCreate, [this.element]); }, _createControls: function(){ var that = this, element = this.element, o = this.options; var controls_position = ['top', 'bottom']; var i, controls, title, pages = element.find(".page"); title = String(o.controlTitle).replace("$1", "1"); title = String(title).replace("$2", pages.length); $.each(controls_position, function(){ controls = $("<div>").addClass("controls controls-"+this).addClass(o.clsControls).appendTo(element); $("<span>").addClass("prev").addClass(o.clsControlPrev).html(o.controlPrev).appendTo(controls); $("<span>").addClass("next").addClass(o.clsControlNext).html(o.controlNext).appendTo(controls); $("<span>").addClass("title").addClass(o.clsControlTitle).html(title).appendTo(controls); }); this._enableControl("prev", false); }, _enableControl: function(type, state){ var control = this.element.find(".controls ." + type); if (state === true) { control.removeClass("disabled"); } else { control.addClass("disabled"); } }, _setTitle: function(){ var title = this.element.find(".controls .title"); var title_str = this.options.controlTitle.replace("$1", this.currentIndex + 1); title_str = title_str.replace("$2", String(this.pages.length)); title.html(title_str); }, _createPages: function(){ var that = this, element = this.element, o = this.options; var pages = element.find(".pages"); var page = element.find(".page"); if (pages.length === 0) { pages = $("<div>").addClass("pages").appendTo(element); } pages.addClass(o.clsPages); $.each(page, function(){ var p = $(this); if (p.data("cover") !== undefined) { element.css({ backgroundImage: "url("+p.data('cover')+")" }); } else { element.css({ backgroundImage: "url("+o.backgroundImage+")" }); } p.css({ left: "100%" }); p.addClass(o.clsPage).hide(0); that.pages.push(p); }); page.appendTo(pages); this.currentIndex = 0; if (this.pages[this.currentIndex] !== undefined) { if (this.pages[this.currentIndex].data("cover") !== undefined ) { element.css({ backgroundImage: "url("+this.pages[this.currentIndex].data('cover')+")" }); } this.pages[this.currentIndex].css("left", "0").show(0); setTimeout(function(){ pages.css({ height: that.pages[0].outerHeight(true) + 2 }); }, 0); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".controls .prev", function(){ if (that.isAnimate === true) { return ; } if ( Utils.exec(o.onBeforePrev, [that.currentIndex, that.pages[that.currentIndex], element]) === true && Utils.exec(o.onBeforePage, ["prev", that.currentIndex, that.pages[that.currentIndex], element]) === true ) { that.prev(); } }); element.on(Metro.events.click, ".controls .next", function(){ if (that.isAnimate === true) { return ; } if ( Utils.exec(o.onBeforeNext, [that.currentIndex, that.pages[that.currentIndex], element]) === true && Utils.exec(o.onBeforePage, ["next", that.currentIndex, that.pages[that.currentIndex], element]) === true ) { that.next(); } }); $(window).on(Metro.events.resize + "-master" + element.attr("id"), function(){ element.find(".pages").height(that.pages[that.currentIndex].outerHeight(true) + 2); }); }, _slideToPage: function(index){ var current, next, to; if (this.pages[index] === undefined) { return ; } if (this.currentIndex === index) { return ; } to = index > this.currentIndex ? "next" : "prev"; current = this.pages[this.currentIndex]; next = this.pages[index]; this.currentIndex = index; this._effect(current, next, to); }, _slideTo: function(to){ var current, next; if (to === undefined) { return ; } current = this.pages[this.currentIndex]; if (to === "next") { if (this.currentIndex + 1 >= this.pages.length) { return ; } this.currentIndex++; } else { if (this.currentIndex - 1 < 0) { return ; } this.currentIndex--; } next = this.pages[this.currentIndex]; this._effect(current, next, to); }, _effect: function(current, next, to){ var that = this, element = this.element, o = this.options; var out = element.width(); var pages = element.find(".pages"); this._setTitle(); if (this.currentIndex === this.pages.length - 1) { this._enableControl("next", false); } else { this._enableControl("next", true); } if (this.currentIndex === 0) { this._enableControl("prev", false); } else { this._enableControl("prev", true); } this.isAnimate = true; setTimeout(function(){ pages.animate({ height: next.outerHeight(true) + 2 }); },0); pages.css("overflow", "hidden"); function finish(){ if (next.data("cover") !== undefined) { element.css({ backgroundImage: "url("+next.data('cover')+")" }); } else { element.css({ backgroundImage: "url("+o.backgroundImage+")" }); } pages.css("overflow", "initial"); that.isAnimate = false; } function _slide(){ current.stop(true, true).animate({ left: to === "next" ? -out : out }, o.duration, o.effectFunc, function(){ current.hide(0); }); next.stop(true, true).css({ left: to === "next" ? out : -out }).show(0).animate({ left: 0 }, o.duration, o.effectFunc, function(){ finish(); }); } function _switch(){ current.hide(0); next.hide(0).css("left", 0).show(0, function(){ finish(); }); } function _fade(){ current.fadeOut(o.duration); next.hide(0).css("left", 0).fadeIn(o.duration, function(){ finish(); }); } switch (o.effect) { case "fade": _fade(); break; case "switch": _switch(); break; default: _slide(); } }, toPage: function(index){ this._slideToPage(index); }, next: function(){ this._slideTo("next"); }, prev: function(){ this._slideTo("prev"); }, changeEffect: function(){ this.options.effect = this.element.attr("data-effect"); }, changeEffectFunc: function(){ this.options.effectFunc = this.element.attr("data-effect-func"); }, changeEffectDuration: function(){ this.options.duration = this.element.attr("data-duration"); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-effect": this.changeEffect(); break; case "data-effect-func": this.changeEffectFunc(); break; case "data-duration": this.changeEffectDuration(); break; } } }; Metro.plugin('master', Master); // Source: js/plugins/navview.js var NavigationView = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.pane = null; this.content = null; this.paneToggle = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { compact: "md", expanded: "lg", toggle: null, onNavigationViewCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createView(); this._createEvents(); Utils.exec(o.onNavigationViewCreate, [element]); }, _createView: function(){ var that = this, element = this.element, o = this.options; var pane, content, toggle, menu; element .addClass("navview") .addClass(o.compact !== false ? "compact-"+o.compact : "") .addClass(o.expanded !== false ? "expanded-"+o.expanded : ""); pane = element.children(".navview-pane"); content = element.children(".navview-content"); toggle = $(o.toggle); menu = pane.find(".navview-menu"); if (menu.length > 0) { var elements_height = 0; $.each(menu.prevAll(), function(){ elements_height += $(this).outerHeight(true); }); $.each(menu.nextAll(), function(){ elements_height += $(this).outerHeight(true); }); menu.css({ height: "calc(100% - "+(elements_height + 20)+"px)" }); } this.pane = pane.length > 0 ? pane : null; this.content = content.length > 0 ? content : null; this.paneToggle = toggle.length > 0 ? toggle : null; }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var pane = this.pane, content = this.content; element.on(Metro.events.click, ".pull-button, .holder", function(e){ var pane_compact = pane.width() < 280; var target = $(this); var input; if (target.hasClass("holder")) { input = target.parent().find("input"); setTimeout(function(){ input.focus(); }, 200); } if (that.pane.hasClass("open")) { that.close(); return ; } if ((pane_compact || element.hasClass("expand")) && !element.hasClass("compacted")) { element.toggleClass("expand"); return ; } if (element.hasClass("compacted") || !pane_compact) { element.toggleClass("compacted"); return ; } return true; }); if (this.paneToggle !== null) { this.paneToggle.on(Metro.events.click, function(){ that.pane.toggleClass("open"); }) } $(window).on(Metro.events.resize, function(){ element.removeClass("expand"); that.pane.removeClass("open"); if ($(this).width() <= Metro.media_sizes[String(o.compact).toUpperCase()]) { element.removeClass("compacted"); } }) }, open: function(){ this.pane.addClass("open"); }, close: function(){ this.pane.removeClass("open"); }, changeAttribute: function(attributeName){ } }; Metro.plugin('navview', NavigationView); // Source: js/plugins/notify.js var Notify = { options: { container: null, width: 220, timeout: METRO_TIMEOUT, duration: METRO_ANIMATION_DURATION, distance: "100vh", animation: "swing", onClick: Metro.noop, onClose: Metro.noop, onShow: Metro.noop, onAppend: Metro.noop, onNotifyCreate: Metro.noop }, notifies: [], setup: function(options){ var body = $("body"), container; this.options = $.extend({}, this.options, options); if (this.options.container === null) { container = $("<div>").addClass("notify-container"); body.prepend(container); this.options.container = container; } return this; }, reset: function(){ var reset_options = { width: 220, timeout: METRO_TIMEOUT, duration: METRO_ANIMATION_DURATION, distance: "100vh", animation: "swing" }; this.options = $.extend({}, this.options, reset_options); }, create: function(message, title, options){ var notify, that = this, o = this.options; var m, t; if (Utils.isNull(options)) { options = {}; } if (!Utils.isValue(message)) { return false; } notify = $("<div>").addClass("notify"); notify.css({ width: o.width }); if (title) { t = $("<div>").addClass("notify-title").html(title); notify.prepend(t); } m = $("<div>").addClass("notify-message").html(message); m.appendTo(notify); // Set options /* * keepOpen, cls, width, callback * */ if (options !== undefined) { if (options.cls !== undefined) { notify.addClass(options.cls); } if (options.width !== undefined) { notify.css({ width: options.width }); } } notify.on(Metro.events.click, function(){ Utils.exec(Utils.isValue(options.onClick) ? options.onClick : o.onClick, null, this); that.kill($(this), Utils.isValue(options.onClose) ? options.onClose : o.onClose); }); // Show notify.hide(function(){ notify.appendTo(o.container); Utils.exec(Utils.isValue(options.onAppend) ? options.onAppend : o.onAppend, null, notify[0]); notify.css({ marginTop: Utils.isValue(options.distance) ? options.distance : o.distance }).fadeIn(100, function(){ var duration = Utils.isValue(options.duration) ? options.duration : o.duration; var animation = Utils.isValue(options.animation) ? options.animation : o.animation; notify.animate({ marginTop: ".25rem" }, duration, animation, function(){ Utils.exec(o.onNotifyCreate, null, this); if (options !== undefined && options.keepOpen === true) { } else { setTimeout(function(){ that.kill(notify, Utils.isValue(options.onClose) ? options.onClose : o.onClose); }, o.timeout); } Utils.exec(Utils.isValue(options.onShow) ? options.onShow : o.onShow, null, notify[0]); }); }); }); }, kill: function(notify, callback){ notify.off(Metro.events.click); notify.fadeOut('slow', function(){ Utils.exec(Utils.isValue(callback) ? callback : this.options.onClose, null, notify[0]); notify.remove(); }); }, killAll: function(){ var that = this; var notifies = $(".notify"); $.each(notifies, function(){ that.kill($(this)); }); } }; Metro['notify'] = Notify.setup(); // Source: js/plugins/panel.js var Panel = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, dependencies: ['draggable', 'collapse'], options: { titleCaption: "", titleIcon: "", collapsible: false, collapsed: false, collapseDuration: METRO_ANIMATION_DURATION, width: "auto", height: "auto", draggable: false, clsPanel: "", clsTitle: "", clsTitleCaption: "", clsTitleIcon: "", clsContent: "", clsCollapseToggle: "", onCollapse: Metro.noop, onExpand: Metro.noop, onDragStart: Metro.noop, onDragStop: Metro.noop, onDragMove: Metro.noop, onPanelCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var panel = $("<div>").addClass("panel").addClass(o.clsPanel); var id = Utils.uniqueId(); var original_classes = element[0].className; if (prev.length === 0) { parent.prepend(panel); } else { panel.insertAfter(prev); } panel.attr("id", id).addClass(original_classes); element[0].className = ''; element.addClass("panel-content").addClass(o.clsContent).appendTo(panel); if (o.titleCaption !== "" || o.titleIcon !== "" || o.collapsible === true) { var title = $("<div>").addClass("panel-title").addClass(o.clsTitle); if (o.titleCaption !== "") { $("<span>").addClass("caption").addClass(o.clsTitleCaption).html(o.titleCaption).appendTo(title) } if (o.titleIcon !== "") { $(o.titleIcon).addClass("icon").addClass(o.clsTitleIcon).appendTo(title) } if (o.collapsible === true) { var collapseToggle = $("<span>").addClass("dropdown-toggle marker-center active-toggle").addClass(o.clsCollapseToggle).appendTo(title); element.collapse({ toggleElement: collapseToggle, duration: o.collapseDuration, onCollapse: o.onCollapse, onExpand: o.onExpand }); if (o.collapsed === true) { this.collapse(); } } title.appendTo(panel); } if (o.draggable === true) { panel.draggable({ dragElement: title || panel, onDragStart: o.onDragStart, onDragStop: o.onDragStop, onDragMove: o.onDragMove }); } if (o.width !== "auto" && parseInt(o.width) >= 0) { panel.outerWidth(parseInt(o.width)); } if (o.height !== "auto" && parseInt(o.height) >= 0) { panel.outerHeight(parseInt(o.height)); element.css({overflow: "auto"}); } this.panel = panel; Utils.exec(o.onPanelCreate, [this.element]); }, collapse: function(){ var element = this.element, o = this.options; if (Utils.isMetroObject(element, 'collapse') === false) { return ; } element.data('collapse').collapse(); }, expand: function(){ var element = this.element, o = this.options; if (Utils.isMetroObject(element, 'collapse') === false) { return ; } element.data('collapse').expand(); }, changeAttribute: function(attributeName){ switch (attributeName) { } } }; Metro.plugin('panel', Panel); // Source: js/plugins/popovers.js var Popover = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.popover = null; this.popovered = false; this.size = { width: 0, height: 0 }; this._setOptionsFromDOM(); this._create(); return this; }, options: { popoverText: "", popoverHide: 3000, popoverTimeout: 10, popoverOffset: 10, popoverTrigger: Metro.popoverEvents.HOVER, popoverPosition: Metro.position.TOP, hideOnLeave: false, closeButton: true, clsPopover: "", clsPopoverContent: "", onPopoverShow: Metro.noop, onPopoverHide: Metro.noop, onPopoverCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createEvents(); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var event; switch (o.popoverTrigger) { case Metro.popoverEvents.CLICK: event = Metro.events.click; break; case Metro.popoverEvents.FOCUS: event = Metro.events.focus; break; default: event = Metro.events.enter; } element.on(event, function(){ if (that.popover !== null || that.popovered === true) { return ; } setTimeout(function(){ that.createPopover(); Utils.exec(o.onPopoverShow, [that.popover], element[0]); if (o.popoverHide > 0) { setTimeout(function(){ that.removePopover(); }, o.popoverHide); } }, o.popoverTimeout); }); if (o.hideOnLeave === true) { element.on(Metro.events.leave, function(){ that.removePopover(); }); } $(window).on(Metro.events.scroll, function(){ if (that.popover !== null) that.setPosition(); }); }, setPosition: function(){ var popover = this.popover, size = this.size, o = this.options, element = this.element; if (o.popoverPosition === Metro.position.BOTTOM) { popover.addClass('bottom'); popover.css({ top: element.offset().top - $(window).scrollTop() + element.outerHeight() + o.popoverOffset, left: element.offset().left + element.outerWidth()/2 - size.width/2 - $(window).scrollLeft() }); } else if (o.popoverPosition === Metro.position.RIGHT) { popover.addClass('right'); popover.css({ top: element.offset().top + element.outerHeight()/2 - size.height/2 - $(window).scrollTop(), left: element.offset().left + element.outerWidth() - $(window).scrollLeft() + o.popoverOffset }); } else if (o.popoverPosition === Metro.position.LEFT) { popover.addClass('left'); popover.css({ top: element.offset().top + element.outerHeight()/2 - size.height/2 - $(window).scrollTop(), left: element.offset().left - size.width - $(window).scrollLeft() - o.popoverOffset }); } else { popover.addClass('top'); popover.css({ top: element.offset().top - $(window).scrollTop() - size.height - o.popoverOffset, left: element.offset().left + element.outerWidth()/2 - size.width/2 - $(window).scrollLeft() }); } }, createPopover: function(){ var that = this, elem = this.elem, element = this.element, o = this.options; var popover; var neb_pos; var id = Utils.elementId("popover"); var closeButton; if (this.popovered) { return ; } popover = $("<div>").addClass("popover neb").addClass(o.clsPopover); popover.attr("id", id); $("<div>").addClass("popover-content").addClass(o.clsPopoverContent).html(o.popoverText).appendTo(popover); if (o.popoverHide === 0 && o.closeButton === true) { closeButton = $("<button>").addClass("button square small popover-close-button bg-white").html("&times;").appendTo(popover); closeButton.on(Metro.events.click, function(){ that.removePopover(); }); } switch (o.popoverPosition) { case Metro.position.TOP: neb_pos = "neb-s"; break; case Metro.position.BOTTOM: neb_pos = "neb-n"; break; case Metro.position.RIGHT: neb_pos = "neb-w"; break; case Metro.position.LEFT: neb_pos = "neb-e"; break; } popover.addClass(neb_pos); if (o.closeButton !== true) { popover.on(Metro.events.click, function(){ that.removePopover(); }); } this.popover = popover; this.size = Utils.hiddenElementSize(popover); if (elem.tagName === 'TD' || elem.tagName === 'TH') { var wrp = $("<div/>").css("display", "inline-block").html(element.html()); element.html(wrp); element = wrp; } this.setPosition(); popover.appendTo($('body')); this.popovered = true; Utils.exec(o.onPopoverCreate, [popover], element[0]); }, removePopover: function(){ var that = this; var timeout = this.options.onPopoverHide === Metro.noop ? 0 : 300; var popover = this.popover; if (!this.popovered) { return ; } Utils.exec(this.options.onPopoverHide, [popover], this.elem); setTimeout(function(){ popover.hide(0, function(){ popover.remove(); that.popover = null; that.popovered = false; }); }, timeout); }, show: function(){ var that = this, element = this.element, o = this.options; if (this.popovered === true) { return ; } setTimeout(function(){ that.createPopover(); Utils.exec(o.onPopoverShow, [that.popover], element[0]); if (o.popoverHide > 0) { setTimeout(function(){ that.removePopover(); }, o.popoverHide); } }, o.popoverTimeout); }, hide: function(){ this.removePopover(); }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var changeText = function(){ o.popoverText = element.attr("data-popover-text"); if (that.popover) { that.popover.find(".popover-content").html(o.popoverText); that.setPosition(); } }; var changePosition = function(){ o.popoverPosition = element.attr("data-popover-position"); that.setPosition(); }; switch (attributeName) { case "data-popover-text": changeText(); break; case "data-popover-position": changePosition(); break; } } }; Metro.plugin('popover', Popover); // Source: js/plugins/progress.js var Progress = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.value = 0; this.buffer = 0; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onProgressCreate, [this.element]); return this; }, options: { value: 0, buffer: 0, type: "bar", small: false, clsBack: "", clsBar: "", clsBuffer: "", onValueChange: Metro.noop, onBufferChange: Metro.noop, onComplete: Metro.noop, onBuffered: Metro.noop, onProgressCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; element .html("") .addClass("progress"); function _progress(){ $("<div>").addClass("bar").appendTo(element); } function _buffer(){ $("<div>").addClass("bar").appendTo(element); $("<div>").addClass("buffer").appendTo(element); } function _load(){ element.addClass("with-load"); $("<div>").addClass("bar").appendTo(element); $("<div>").addClass("buffer").appendTo(element); $("<div>").addClass("load").appendTo(element); } function _line(){ element.addClass("line"); } switch (o.type) { case "buffer": _buffer(); break; case "load": _load(); break; case "line": _line(); break; default: _progress(); } if (o.small === true) { element.addClass("small"); } element.addClass(o.clsBack); element.find(".bar").addClass(o.clsBar); element.find(".buffer").addClass(o.clsBuffer); this.val(o.value); this.buff(o.buffer); }, val: function(v){ var that = this, element = this.element, o = this.options; if (v === undefined) { return that.value; } var bar = element.find(".bar"); if (bar.length === 0) { return false; } this.value = parseInt(v, 10); bar.css("width", this.value + "%"); element.trigger("valuechange", [this.value]); Utils.exec(o.onValueChange, [this.value, element]); if (this.value === 100) { Utils.exec(o.onComplete, [this.value, element]); } }, buff: function(v){ var that = this, element = this.element, o = this.options; if (v === undefined) { return that.buffer; } var bar = element.find(".buffer"); if (bar.length === 0) { return false; } this.buffer = parseInt(v, 10); bar.css("width", this.buffer + "%"); element.trigger("bufferchange", [this.buffer]); Utils.exec(o.onBufferChange, [this.buffer, element]); if (this.buffer === 100) { Utils.exec(o.onBuffered, [this.buffer, element]); } }, changeValue: function(){ this.val(this.element.attr('data-value')); }, changeBuffer: function(){ this.buff(this.element.attr('data-buffer')); }, changeAttribute: function(attributeName){ switch (attributeName) { case 'data-value': this.changeValue(); break; case 'data-buffer': this.changeBuffer(); break; } } }; Metro.plugin('progress', Progress); // Source: js/plugins/radio.js var Radio = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.origin = { className: "" }; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onRadioCreate, [this.element]); return this; }, options: { style: 1, caption: "", captionPosition: "right", clsRadio: "", clsCheck: "", clsCaption: "", onRadioCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; var radio = $("<label>").addClass("radio " + element[0].className).addClass(o.style === 2 ? "style2" : ""); var check = $("<span>").addClass("check"); var caption = $("<span>").addClass("caption").html(o.caption); element.attr("type", "radio"); radio.insertBefore(element); element.appendTo(radio); check.appendTo(radio); caption.appendTo(radio); if (o.captionPosition === 'left') { radio.addClass("caption-left"); } this.origin.className = element[0].className; element[0].className = ''; radio.addClass(o.clsRadio); caption.addClass(o.clsCaption); check.addClass(o.clsCheck); if (element.is(':disabled')) { this.disable(); } else { this.enable(); } }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ var element = this.element, o = this.options; var parent = element.parent(); var changeStyle = function(){ var new_style = parseInt(element.attr("data-style")); if (!Utils.isInt(new_style)) return; o.style = new_style; parent.removeClass("style1 style2").addClass("style"+new_style); }; switch (attributeName) { case 'disabled': this.toggleState(); break; case 'data-style': changeStyle(); break; } }, destroy: function(){ var element = this.element; var parent = element.parent(); element[0].className = this.origin.className; element.insertBefore(parent); parent.remove(); } }; Metro.plugin('radio', Radio); // Source: js/plugins/rating.js var Rating = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.value = 0; this.values = []; this.rate = 0; this.rating = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { static: false, title: null, value: 0, values: null, message: "", stars: 5, starColor: null, staredColor: null, roundFunc: "round", // ceil, floor, round clsRating: "", clsTitle: "", clsStars: "", clsResult: "", onStarClick: Metro.noop, onRatingCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; var i; if (o.values !== null) { if (Array.isArray(o.values)) { this.values = o.values; } else if (typeof o.values === "string") { this.values = Utils.strToArray(o.values) } } else { for(i = 1; i <= o.stars; i++) { this.values.push(i); } } this.value = o.value > 0 ? Math[o.roundFunc](o.value) : 0; if (o.starColor !== null) { if (!Utils.isColor(o.starColor)) { o.starColor = Colors.color(o.starColor); } } if (o.staredColor !== null) { if (!Utils.isColor(o.staredColor)) { o.staredColor = Colors.color(o.staredColor); } } this._createRating(); this._createEvents(); Utils.exec(o.onRatingCreate, [element]); }, _createRating: function(){ var element = this.element, o = this.options; var id = Utils.elementId("rating"); var rating = $("<div>").addClass("rating " + String(element[0].className).replace("d-block", "d-flex")).addClass(o.clsRating); var i, stars, result, li; var sheet = Metro.sheet; element.val(this.value); rating.attr("id", id); rating.insertBefore(element); element.appendTo(rating); stars = $("<ul>").addClass("stars").addClass(o.clsStars).appendTo(rating); for(i = 1; i <= o.stars; i++) { li = $("<li>").data("value", this.values[i-1]).appendTo(stars); if (i <= this.value) { li.addClass("on"); } } result = $("<span>").addClass("result").addClass(o.clsResult).appendTo(rating); result.html(o.message); if (o.starColor !== null) { Utils.addCssRule(sheet, "#" + id + " .stars:hover li", "color: " + o.starColor + ";"); } if (o.staredColor !== null) { Utils.addCssRule(sheet, "#"+id+" .stars li.on", "color: "+o.staredColor+";"); } if (o.title !== null) { var title = $("<span>").addClass("title").addClass(o.clsTitle).html(o.title); rating.prepend(title); } if (o.static === true) { rating.addClass("static"); } element[0].className = ''; if (o.copyInlineStyles === true) { for (i = 0; i < element[0].style.length; i++) { rating.css(element[0].style[i], element.css(element[0].style[i])); } } if (element.is(":disabled")) { this.disable(); } else { this.enable(); } this.rating = rating; }, _createEvents: function(){ var element = this.element, o = this.options; var rating = this.rating; rating.on(Metro.events.click, ".stars li", function(){ if (o.static === true) { return ; } var star = $(this); var value = star.data("value"); star.addClass("scale"); setTimeout(function(){ star.removeClass("scale"); }, 300); element.val(value).trigger("change"); star.addClass("on"); star.prevAll().addClass("on"); star.nextAll().removeClass("on"); Utils.exec(o.onStarClick, [value, star, element]); }); }, val: function(v){ var that = this, element = this.element, o = this.options; var rating = this.rating; if (v === undefined) { return this.value; } this.value = v > 0 ? Math[o.roundFunc](v) : 0; element.val(this.value).trigger("change"); var stars = rating.find(".stars li").removeClass("on"); $.each(stars, function(){ var star = $(this); if (star.data("value") <= that.value) { star.addClass("on"); } }); return this; }, msg: function(m){ var rating = this.rating; if (m === undefined) { return ; } rating.find(".result").html(m); return this; }, static: function (mode) { var o = this.options; var rating = this.rating; o.static = mode; if (mode === true) { rating.addClass("static"); } else { rating.removeClass("static"); } }, changeAttributeValue: function(a){ var element = this.element; var value = a === "value" ? element.val() : element.attr("data-value"); this.val(value); }, changeAttributeMessage: function(){ var element = this.element; var message = element.attr("data-message"); this.msg(message); }, changeAttributeStatic: function(){ var element = this.element; var isStatic = JSON.parse(element.attr("data-static")) === true; this.static(isStatic); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case "value": case "data-value": this.changeAttributeValue(attributeName); break; case "disabled": this.toggleState(); break; case "data-message": this.changeAttributeMessage(); break; case "data-static": this.changeAttributeStatic(); break; } } }; Metro.plugin('rating', Rating); // Source: js/plugins/resizable.js var Resizable = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.resizer = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onResizableCreate, [this.element]); return this; }, options: { canResize: true, resizeElement: ".resize-element", minWidth: 0, minHeight: 0, maxWidth: 0, maxHeight: 0, preserveRatio: false, onResizeStart: Metro.noop, onResizeStop: Metro.noop, onResize: Metro.noop, onResizableCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createStructure(); this._createEvents(); }, _createStructure: function(){ var element = this.element, o = this.options; if (Utils.isValue(o.resizeElement) && element.find(o.resizeElement).length > 0) { this.resizer = element.find(o.resizeElement); } else { this.resizer = $("<span>").addClass("resize-element").appendTo(element); } }, _createEvents: function(){ var element = this.element, o = this.options; this.resizer.on(Metro.events.start + "-resize-element", function(e){ if (o.canResize === false) { return ; } var startXY = Utils.pageXY(e); var startWidth = parseInt(element.outerWidth()); var startHeight = parseInt(element.outerHeight()); var size = {width: startWidth, height: startHeight}; Utils.exec(o.onResizeStart, [element, size]); $(document).on(Metro.events.move + "-resize-element", function(e){ var moveXY = Utils.pageXY(e); var size = { width: startWidth + moveXY.x - startXY.x, height: startHeight + moveXY.y - startXY.y }; if (o.maxWidth > 0 && size.width > o.maxWidth) {return true;} if (o.minWidth > 0 && size.width < o.minWidth) {return true;} if (o.maxHeight > 0 && size.height > o.maxHeight) {return true;} if (o.minHeight > 0 && size.height < o.minHeight) {return true;} element.css(size); Utils.exec(o.onResize, [element, size]); }); $(document).on(Metro.events.stop + "-resize-element", function(){ $(document).off(Metro.events.move + "-resize-element"); $(document).off(Metro.events.stop + "-resize-element"); var size = { width: parseInt(element.outerWidth()), height: parseInt(element.outerHeight()) }; Utils.exec(o.onResizeStop, [element, size]); }); e.preventDefault(); e.stopPropagation(); }); }, off: function(){ this.element.data("canResize", false); }, on: function(){ this.element.data("canResize", true); }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var canResize = function(){ o.canResize = JSON.parse(element.attr('data-can-resize')) === true; }; switch (attributeName) { case "data-can-resize": canResize(); break; } } }; Metro.plugin('resizable', Resizable); // Source: js/plugins/ribbon-menu.js var RibbonMenu = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, dependencies: ['buttongroup'], options: { onStatic: Metro.noop, onBeforeTab: Metro.noop_true, onTab: Metro.noop, onRibbonMenuCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onRibbonMenuCreate, [element]); }, _createStructure: function(){ var element = this.element; element.addClass("ribbon-menu"); var tabs = element.find(".tabs-holder li:not(.static)"); var active_tab = element.find(".tabs-holder li.active"); if (active_tab.length > 0) { this.open($(active_tab[0])); } else { if (tabs.length > 0) { this.open($(tabs[0])); } } var fluentGroups = element.find(".ribbon-toggle-group"); $.each(fluentGroups, function(){ var g = $(this); g.buttongroup({ clsActive: "active" }); var gw = 0; var btns = g.find(".ribbon-icon-button"); $.each(btns, function(){ var b = $(this); var w = b.outerWidth(true); if (w > gw) gw = w; }); g.css("width", gw * Math.ceil(btns.length / 3) + 4); }); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".tabs-holder li a", function(e){ var link = $(this); var tab = $(this).parent("li"); if (tab.hasClass("static")) { if (o.onStatic === Metro.noop && link.attr("href") !== undefined) { document.location.href = link.attr("href"); } else { Utils.exec(o.onStatic, [tab, element]); } } else { if (Utils.exec(o.onBeforeTab, [tab, element]) === true) { that.open(tab); } } e.preventDefault(); }) }, open: function(tab){ var element = this.element, o = this.options; var tabs = element.find(".tabs-holder li"); var sections = element.find(".content-holder .section"); var target = tab.children("a").attr("href"); var target_section = target !== "#" ? element.find(target) : null; tabs.removeClass("active"); tab.addClass("active"); sections.removeClass("active"); if (target_section) target_section.addClass("active"); Utils.exec(o.onTab, [tab, element]); }, changeAttribute: function(attributeName){ } }; Metro.plugin('ribbonmenu', RibbonMenu); // Source: js/plugins/ripple.js var Ripple = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onRippleCreate, [this.element]); return this; }, options: { rippleColor: "#fff", rippleAlpha: .4, rippleTarget: "default", onRippleCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var target = o.rippleTarget === 'default' ? null : o.rippleTarget; element.on(Metro.events.click, target, function(e){ var el = $(this); var timer = null; if (el.css('position') === 'static') { el.css('position', 'relative'); } el.css({ overflow: 'hidden' }); $(".ripple").remove(); var size = Math.max(el.outerWidth(), el.outerHeight()); // Add the element var ripple = $("<span class='ripple'></span>").css({ width: size, height: size }); el.prepend(ripple); // Get the center of the element var x = e.pageX - el.offset().left - ripple.width()/2; var y = e.pageY - el.offset().top - ripple.height()/2; // Add the ripples CSS and start the animation ripple.css({ background: Utils.hex2rgba(o.rippleColor, o.rippleAlpha), width: size, height: size, top: y + 'px', left: x + 'px' }).addClass("rippleEffect"); timer = setTimeout(function(){ timer = null; $(".ripple").remove(); }, 400); }); }, changeAttribute: function(attributeName){ } }; Metro.plugin('ripple', Ripple); // Source: js/plugins/select.js var Select = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.list = null; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onSelectCreate, [this.element]); return this; }, options: { duration: 100, prepend: "", append: "", placeholder: "", filterPlaceholder: "", filter: true, copyInlineStyles: true, dropHeight: 200, clsSelect: "", clsSelectInput: "", clsPrepend: "", clsAppend: "", clsOption: "", clsOptionActive: "", clsOptionGroup: "", clsDropList: "", clsSelectedItem: "", clsSelectedItemRemover: "", onChange: Metro.noop, onUp: Metro.noop, onDrop: Metro.noop, onItemSelect: Metro.noop, onItemDeselect: Metro.noop, onSelectCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createSelect(); this._createEvents(); }, _addOption: function(item, parent){ var option = $(item); var l, a; var element = this.element, o = this.options; var multiple = element[0].multiple; var input = element.siblings(".select-input"); var html = Utils.isValue(option.attr('data-template')) ? option.attr('data-template').replace("$1", item.text):item.text; var tag; l = $("<li>").addClass(o.clsOption).data("option", item).attr("data-text", item.text).attr('data-value', Utils.isValue(item.value) ? item.value : "").appendTo(parent); a = $("<a>").html(html).appendTo(l).addClass(item.className); if (option.is(":selected")) { if (multiple) { l.addClass("d-none"); tag = $("<div>").addClass("selected-item").addClass(o.clsSelectedItem).html("<span class='title'>"+html+"</span>").appendTo(input); tag.data("option", l); $("<span>").addClass("remover").addClass(o.clsSelectedItemRemover).html("&times;").appendTo(tag); } else { element.val(item.value); input.html(html); element.trigger("change"); l.addClass("active"); } } a.appendTo(l); l.appendTo(parent); }, _addOptionGroup: function(item, parent){ var that = this; var group = $(item); $("<li>").html(item.label).addClass("group-title").appendTo(parent); $.each(group.children(), function(){ that._addOption(this, parent); }) }, _createOptions: function(){ var that = this, element = this.element, select = element.parent(); var list = select.find("ul").html(""); $.each(element.children(), function(){ if (this.tagName === "OPTION") { that._addOption(this, list); } else if (this.tagName === "OPTGROUP") { that._addOptionGroup(this, list); } }); }, _createSelect: function(){ var that = this, element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var container = $("<label>").addClass("select " + element[0].className).addClass(o.clsSelect); var multiple = element[0].multiple; var select_id = Utils.elementId("select"); var buttons = $("<div>").addClass("button-group"); var input, drop_container, list, filter_input; container.attr("id", select_id).addClass("dropdown-toggle"); if (multiple) { container.addClass("multiple"); } if (prev.length === 0) { parent.prepend(container); } else { container.insertAfter(prev); } element.appendTo(container); buttons.appendTo(container); input = $("<div>").addClass("select-input").addClass(o.clsSelectInput).attr("name", "__" + select_id + "__"); drop_container = $("<div>").addClass("drop-container"); list = $("<ul>").addClass("d-menu").addClass(o.clsDropList).css({ "max-height": o.dropHeight }); filter_input = $("<input type='text' data-role='input'>").attr("placeholder", o.filterPlaceholder); container.append(input); container.append(drop_container); drop_container.append(filter_input); if (o.filter !== true) { filter_input.hide(); } drop_container.append(list); this._createOptions(); drop_container.dropdown({ duration: o.duration, toggleElement: "#"+select_id, onDrop: function(){ var dropped, target; dropped = $(".select .drop-container"); $.each(dropped, function(){ var drop = $(this); if (drop.is(drop_container)) { return ; } drop.data('dropdown').close(); }); filter_input.val("").trigger(Metro.events.keyup).focus(); target = list.find("li.active").length > 0 ? $(list.find("li.active")[0]) : undefined; if (target !== undefined) { list.scrollTop(0); setTimeout(function(){ list.animate({ scrollTop: target.position().top - ( (list.height() - target.height() )/ 2) }, 100); }, 200); } Utils.exec(o.onDrop, [list, element], list[0]); }, onUp: function(){ Utils.exec(o.onUp, [list, element], list[0]); } }); this.list = list; if (o.prepend !== "") { var prepend = $("<div>").html(o.prepend); prepend.addClass("prepend").addClass(o.clsPrepend).appendTo(container); } if (o.append !== "") { var append = $("<div>").html(o.append); append.addClass("append").addClass(o.clsAppend).appendTo(container); } if (o.copyInlineStyles === true) { for (var i = 0, l = element[0].style.length; i < l; i++) { container.css(element[0].style[i], element.css(element[0].style[i])); } } if (element.attr('dir') === 'rtl' ) { container.addClass("rtl").attr("dir", "rtl"); } if (element.is(':disabled')) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var container = element.closest(".select"); var drop_container = container.find(".drop-container"); var input = element.siblings(".select-input"); var filter_input = drop_container.find("input"); var list = drop_container.find("ul"); container.on(Metro.events.click, function(e){ $(".focused").removeClass("focused"); container.addClass("focused"); e.preventDefault(); e.stopPropagation(); }); input.on(Metro.events.click, function(e){ $(".focused").removeClass("focused"); container.addClass("focused"); e.preventDefault(); e.stopPropagation(); }); // filter_input.on(Metro.events.blur, function(){container.removeClass("focused");}); // filter_input.on(Metro.events.focus, function(){container.addClass("focused");}); list.on(Metro.events.click, "li", function(e){ if ($(this).hasClass("group-title")) { e.preventDefault(); e.stopPropagation(); return ; } var leaf = $(this); var val = leaf.data('value'); var txt = leaf.data('text'); var html = leaf.children('a').html(); var selected_item; var option = leaf.data("option"); var options = element.find("option"); if (element[0].multiple) { leaf.addClass("d-none"); selected_item = $("<div>").addClass("selected-item").addClass(o.clsSelectedItem).html("<span class='title'>"+html+"</span>").appendTo(input); selected_item.data("option", leaf); $("<span>").addClass("remover").addClass(o.clsSelectedItemRemover).html("&times;").appendTo(selected_item); } else { list.find("li.active").removeClass("active").removeClass(o.clsOptionActive); leaf.addClass("active").addClass(o.clsOptionActive); input.html(html); drop_container.data("dropdown").close(); } $.each(options, function(){ if (this === option) { this.selected = true; } }); element.trigger("change"); Utils.exec(o.onItemSelect, [val, option, leaf], element[0]); Utils.exec(o.onChange, [that.getSelected()], element[0]); }); input.on("click", ".selected-item .remover", function(e){ var item = $(this).closest(".selected-item"); var leaf = item.data("option"); var option = leaf.data('option'); leaf.removeClass("d-none"); $.each(element.find("option"), function(){ if (this === option) { this.selected = false; } }); item.remove(); element.trigger("change"); Utils.exec(o.onItemDeselect, [option], element[0]); Utils.exec(o.onChange, [that.getSelected()], element[0]); e.preventDefault(); e.stopPropagation(); }); filter_input.on(Metro.events.keyup, function(){ var filter = this.value.toUpperCase(); var li = list.find("li"); var i, a; for (i = 0; i < li.length; i++) { if ($(li[i]).hasClass("group-title")) continue; a = li[i].getElementsByTagName("a")[0]; if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].style.display = "none"; } } }); drop_container.on(Metro.events.click, function(e){ e.preventDefault(); e.stopPropagation(); }); }, disable: function(){ this.element.data("disabled", true); this.element.closest(".select").addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.closest(".select").removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, reset: function(to_default){ var element = this.element, o = this.options; var options = element.find("option"); var select = element.closest('.select'); $.each(options, function(){ this.selected = !Utils.isNull(to_default) ? this.defaultSelected : false; }); this.list.find("li").remove(); select.find(".select-input").html(''); this._createOptions(); element.trigger('change'); Utils.exec(o.onChange, [this.getSelected()], element[0]); }, getSelected: function(){ var element = this.element; var result = []; element.find("option:selected").each(function(){ result.push(this.value); }); return result; }, val: function(val){ var that = this, element = this.element, o = this.options; var input = element.siblings(".select-input"); var options = element.find("option"); var list_items = this.list.find("li"); var result = []; var multiple = element.attr("multiple") !== undefined; var option; var i, html, list_item, option_value, tag; if (Utils.isNull(val)) { $.each(options, function(){ if (this.selected) result.push(this.value); }); return multiple ? result : result[0]; } $.each(options, function(){ this.selected = false; }); list_items.removeClass("active"); input.html(''); if (Array.isArray(val) === false) { val = [val]; } $.each(val, function(){ for (i = 0; i < options.length; i++) { option = options[i]; html = Utils.isValue(option.getAttribute('data-template')) ? option.getAttribute('data-template').replace("$1", option.text) : option.text; if (""+option.value === ""+this) { option.selected = true; break; } } for(i = 0; i < list_items.length; i++) { list_item = $(list_items[i]); option_value = list_item.attr("data-value"); if (""+option_value === ""+this) { if (multiple) { list_item.addClass("d-none"); tag = $("<div>").addClass("selected-item").addClass(o.clsSelectedItem).html("<span class='title'>"+html+"</span>").appendTo(input); tag.data("option", list_item); $("<span>").addClass("remover").addClass(o.clsSelectedItemRemover).html("&times;").appendTo(tag); } else { list_item.addClass("active"); input.html(html); } break; } } }); element.trigger('change'); Utils.exec(o.onChange, [this.getSelected()], element[0]); }, data: function(op){ var element = this.element; var option_group; element.html(""); if (typeof op === 'string') { element.html(op); } else if (Utils.isObject(op)) { $.each(op, function(key, val){ if (Utils.isObject(val)) { option_group = $("<optgroup>").attr("label", key).appendTo(element); $.each(val, function(key2, val2){ $("<option>").attr("value", key2).text(val2).appendTo(option_group); }); } else { $("<option>").attr("value", key).text(val).appendTo(element); } }); } this._createOptions(); }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; } }, destroy: function(){ var element = this.element; var container = element.closest(".select"); var drop_container = container.find(".drop-container"); var input = element.siblings(".select-input"); var filter_input = drop_container.find("input"); var list = drop_container.find("ul"); container.off(Metro.events.click); container.off(Metro.events.click, ".input-clear-button"); input.off(Metro.events.click); filter_input.off(Metro.events.blur); filter_input.off(Metro.events.focus); list.off(Metro.events.click, "li"); filter_input.off(Metro.events.keyup); drop_container.off(Metro.events.click); Metro.destroyPlugin(drop_container, "dropdown"); element.insertBefore(container); container.remove(); } }; $(document).on(Metro.events.click, function(){ var selects = $(".select .drop-container"); $.each(selects, function(){ $(this).data('dropdown').close(); }); $(".select").removeClass("focused"); }); Metro.plugin('select', Select); // Source: js/plugins/sidebar.js var Sidebar = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.toggle_element = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { shadow: true, position: "left", size: 290, shift: null, staticShift: null, toggle: null, duration: METRO_ANIMATION_DURATION, static: null, menuItemClick: true, onOpen: Metro.noop, onClose: Metro.noop, onToggle: Metro.noop, onStaticSet: Metro.noop, onStaticLoss: Metro.noop, onSidebarCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); $(window).resize(); this._checkStatic(); Utils.exec(o.onSidebarCreate, [element], element[0]); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var header = element.find(".sidebar-header"); var sheet = Metro.sheet; element.addClass("sidebar").addClass("on-"+o.position); if (o.size !== 290) { Utils.addCssRule(sheet, ".sidebar", "width: " + o.size + "px;"); if (o.position === "left") { Utils.addCssRule(sheet, ".sidebar.on-left", "left: " + -o.size + "px;"); } else { Utils.addCssRule(sheet, ".sidebar.on-right", "right: " + -o.size + "px;"); } } if (o.shadow === true) { element.addClass("sidebar-shadow"); } if (element.attr("id") === undefined) { element.attr("id", Utils.elementId("sidebar")); } if (o.toggle !== null && $(o.toggle).length > 0) { this.toggle_element = $(o.toggle); } if (header.length > 0) { if (header.data("image") !== undefined) { header.css({ backgroundImage: "url("+header.data("image")+")" }); } } if (o.static !== null) { if (o.staticShift !== null) { if (o.position === 'left') { Utils.addCssRule(sheet, "@media screen and " + Metro.media_queries[o.static.toUpperCase()], o.staticShift + "{margin-left: " + o.size + "px; width: calc(100% - " + o.size + "px);}"); } else { Utils.addCssRule(sheet, "@media screen and " + Metro.media_queries[o.static.toUpperCase()], o.staticShift + "{margin-right: " + o.size + "px; width: calc(100% - " + o.size + "px);}"); } } } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var toggle = this.toggle_element; if (toggle !== null) { toggle.on(Metro.events.click, function(e){ that.toggle(); }); } if (o.static !== null && ["fs", "sm", "md", "lg", "xl", "xxl"].indexOf(o.static) > -1) { $(window).on(Metro.events.resize + "_" + element.attr("id"), function(){ that._checkStatic(); }); } if (o.menuItemClick === true) { element.on(Metro.events.click, ".sidebar-menu li > a", function(){ that.close(); }); } element.on(Metro.events.click, ".sidebar-menu .js-sidebar-close", function(){ that.close(); }); }, _checkStatic: function(){ var element = this.element, o = this.options; if (Utils.mediaExist(o.static) && !element.hasClass("static")) { element.addClass("static"); element.data("opened", false).removeClass('open'); if (o.shift !== null) { $.each(o.shift.split(","), function(){ $(this).css({left: 0}, o.duration); }); } Utils.exec(o.onStaticSet, [element], element[0]); } if (!Utils.mediaExist(o.static)) { element.removeClass("static"); Utils.exec(o.onStaticLoss, [element], element[0]); } }, isOpen: function(){ return this.element.data("opened") === true; }, open: function(){ var that = this, element = this.element, o = this.options; if (element.hasClass("static")) { return ; } element.data("opened", true).addClass('open'); if (o.shift !== null) { $(o.shift).animate({ left: element.outerWidth() }, o.duration); } Utils.exec(o.onOpen, [element], element[0]); }, close: function(){ var that = this, element = this.element, o = this.options; if (element.hasClass("static")) { return ; } element.data("opened", false).removeClass('open'); if (o.shift !== null) { $(o.shift).animate({ left: 0 }, o.duration); } Utils.exec(o.onClose, [element], element[0]); }, toggle: function(){ if (this.isOpen()) { this.close(); } else { this.open(); } Utils.exec(this.options.onToggle, [this.element], this.element[0]); }, changeAttribute: function(attributeName){ }, destroy: function(){} }; Metro.plugin('sidebar', Sidebar); Metro['sidebar'] = { isSidebar: function(el){ return Utils.isMetroObject(el, "sidebar"); }, open: function(el){ if (!this.isSidebar(el)) { return ; } $(el).data("sidebar").open(); }, close: function(el){ if (!this.isSidebar(el)) { return ; } $(el).data("sidebar").close(); }, toggle: function(el){ if (!this.isSidebar(el)) { return ; } $(el).data("sidebar").toggle(); }, isOpen: function(el){ if (!this.isSidebar(el)) { return ; } return $(el).data("sidebar").isOpen(); } }; // Source: js/plugins/slider.js var Slider = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.slider = null; this.value = 0; this.percent = 0; this.pixel = 0; this.buffer = 0; this.keyInterval = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { min: 0, max: 100, accuracy: 0, showMinMax: false, minMaxPosition: Metro.position.TOP, value: 0, buffer: 0, hint: false, hintAlways: false, hintPosition: Metro.position.TOP, hintMask: "$1", vertical: false, target: null, returnType: "value", // value or percent size: 0, clsSlider: "", clsBackside: "", clsComplete: "", clsBuffer: "", clsMarker: "", clsHint: "", clsMinMax: "", clsMin: "", clsMax: "", onStart: Metro.noop, onStop: Metro.noop, onMove: Metro.noop, onClick: Metro.noop, onChange: Metro.noop, onChangeValue: Metro.noop, onChangeBuffer: Metro.noop, onFocus: Metro.noop, onBlur: Metro.noop, onSliderCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createSlider(); this._createEvents(); this.buff(o.buffer); this.val(o.value); Utils.exec(o.onSliderCreate, [element]); }, _createSlider: function(){ var element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var slider = $("<div>").addClass("slider " + element[0].className).addClass(o.clsSlider); var backside = $("<div>").addClass("backside").addClass(o.clsBackside); var complete = $("<div>").addClass("complete").addClass(o.clsComplete); var buffer = $("<div>").addClass("buffer").addClass(o.clsBuffer); var marker = $("<button>").attr("type", "button").addClass("marker").addClass(o.clsMarker); var hint = $("<div>").addClass("hint").addClass(o.hintPosition + "-side").addClass(o.clsHint); var id = Utils.uniqueId(); var i; slider.attr("id", id); if (o.size > 0) { if (o.vertical === true) { slider.outerHeight(o.size); } else { slider.outerWidth(o.size); } } if (o.vertical === true) { slider.addClass("vertical-slider"); } if (prev.length === 0) { parent.prepend(slider); } else { slider.insertAfter(prev); } if (o.hintAlways === true) { hint.css({ display: "block" }).addClass("permanent-hint"); } element.appendTo(slider); backside.appendTo(slider); complete.appendTo(slider); buffer.appendTo(slider); marker.appendTo(slider); hint.appendTo(marker); if (o.showMinMax === true) { var min_max_wrapper = $("<div>").addClass("slider-min-max clear").addClass(o.clsMinMax); $("<span>").addClass("place-left").addClass(o.clsMin).html(o.min).appendTo(min_max_wrapper); $("<span>").addClass("place-right").addClass(o.clsMax).html(o.max).appendTo(min_max_wrapper); if (o.minMaxPosition === Metro.position.TOP) { min_max_wrapper.insertBefore(slider); } else { min_max_wrapper.insertAfter(slider); } } element[0].className = ''; if (o.copyInlineStyles === true) { for (i = 0; i < element[0].style.length; i++) { slider.css(element[0].style[i], element.css(element[0].style[i])); } } if (element.is(":disabled")) { this.disable(); } else { this.enable(); } this.slider = slider; }, _createEvents: function(){ var that = this, slider = this.slider, o = this.options; var marker = slider.find(".marker"); var hint = slider.find(".hint"); marker.on(Metro.events.start, function(){ $(document).on(Metro.events.move, function(e){ if (o.hint === true && o.hintAlways !== true) { hint.fadeIn(); } that._move(e); Utils.exec(o.onMove, [that.value, that.percent, slider]); }); $(document).on(Metro.events.stop, function(){ $(document).off(Metro.events.move); $(document).off(Metro.events.stop); if (o.hintAlways !== true) { hint.fadeOut(); } Utils.exec(o.onStop, [that.value, that.percent, slider]); }); Utils.exec(o.onStart, [that.value, that.percent, slider]); }); marker.on(Metro.events.focus, function(){ Utils.exec(o.onFocus, [that.value, that.percent, slider]); }); marker.on(Metro.events.blur, function(){ Utils.exec(o.onBlur, [that.value, that.percent, slider]); }); marker.on(Metro.events.keydown, function(e){ var key = e.keyCode ? e.keyCode : e.which; if ([37,38,39,40].indexOf(key) === -1) { return; } var step = o.accuracy === 0 ? 1 : o.accuracy; if (that.keyInterval) { return ; } that.keyInterval = setInterval(function(){ var val = that.value; if (e.keyCode === 37 || e.keyCode === 40) { // left, down if (val - step < o.min) { val = o.min; } else { val -= step; } } if (e.keyCode === 38 || e.keyCode === 39) { // right, up if (val + step > o.max) { val = o.max; } else { val += step; } } that.value = that._correct(val); that.percent = that._convert(that.value, 'val2prc'); that.pixel = that._convert(that.percent, 'prc2pix'); that._redraw(); }, 100); e.preventDefault(); }); marker.on(Metro.events.keyup, function(){ clearInterval(that.keyInterval); that.keyInterval = false; }); slider.on(Metro.events.click, function(e){ that._move(e); Utils.exec(o.onClick, [that.value, that.percent, slider]); Utils.exec(o.onStop, [that.value, that.percent, slider]); }); $(window).resize(function(){ that.val(that.value); that.buff(that.buffer); }); }, _convert: function(v, how){ var slider = this.slider, o = this.options; var length = (o.vertical === true ? slider.outerHeight() : slider.outerWidth()) - slider.find(".marker").outerWidth(); switch (how) { case "pix2prc": return Math.round( v * 100 / length ); case "pix2val": return Math.round( this._convert(v, 'pix2prc') * ((o.max - o.min) / 100) + o.min ); case "val2prc": return Math.round( (v - o.min)/( (o.max - o.min) / 100 ) ); case "prc2pix": return Math.round( v / ( 100 / length )); case "val2pix": return Math.round( this._convert(this._convert(v, 'val2prc'), 'prc2pix') ); } return 0; }, _correct: function(value){ var accuracy = this.options.accuracy; var min = this.options.min, max = this.options.max; if (accuracy === 0 || isNaN(accuracy)) { return value; } value = Math.floor(value / accuracy) * accuracy + Math.round(value % accuracy / accuracy) * accuracy; if (value < min) { value = min; } if (value > max) { value = max; } return value; }, _move: function(e){ var slider = this.slider, o = this.options; var offset = slider.offset(), marker_size = slider.find(".marker").outerWidth(), length = o.vertical === true ? slider.outerHeight() : slider.outerWidth(), cPos, cPix, cStart = 0, cStop = length - marker_size; cPos = o.vertical === true ? Utils.pageXY(e).y - offset.top : Utils.pageXY(e).x - offset.left; cPix = o.vertical === true ? length - cPos - marker_size / 2 : cPos - marker_size / 2; if (cPix < cStart || cPix > cStop) { return ; } this.value = this._correct(this._convert(cPix, 'pix2val')); this.percent = this._convert(this.value, 'val2prc'); this.pixel = this._convert(this.percent, 'prc2pix'); this._redraw(); }, _hint: function(){ var o = this.options, slider = this.slider, hint = slider.find(".hint"); var value; value = o.hintMask.replace("$1", this.value).replace("$2", this.percent); hint.text(value); }, _value: function(){ var element = this.element, o = this.options, slider = this.slider; var value = o.returnType === 'value' ? this.value : this.percent; if (element[0].tagName === "INPUT") { element.val(value); } element.trigger("change"); if (o.target !== null) { var target = $(o.target); if (target.length !== 0) { $.each(target, function(){ var t = $(this); if (this.tagName === "INPUT") { t.val(value); } else { t.text(value); } }); } } Utils.exec(o.onChangeValue, [value, this.percent, slider], element[0]); Utils.exec(o.onChange, [value, this.percent, this.buffer], element[0]); }, _marker: function(){ var slider = this.slider, o = this.options; var marker = slider.find(".marker"), complete = slider.find(".complete"); var length = o.vertical === true ? slider.outerHeight() : slider.outerWidth(); var marker_size = parseInt(Utils.getStyleOne(marker, "width")); var slider_visible = Utils.isVisible(slider); if (slider_visible) { marker.css({ 'margin-top': 0, 'margin-left': 0 }); } if (o.vertical === true) { if (slider_visible) { marker.css('top', length - this.pixel); } else { marker.css('top', this.percent + "%"); marker.css('margin-top', this.percent === 0 ? 0 : -1 * marker_size / 2); } complete.css('height', this.percent+"%"); } else { if (slider_visible) { marker.css('left', this.pixel); } else { marker.css('left', this.percent + "%"); marker.css('margin-left', this.percent === 0 ? 0 : -1 * marker_size / 2); } complete.css('width', this.percent+"%"); } }, _redraw: function(){ this._marker(); this._value(); this._hint(); }, _buffer: function(){ var element = this.element, o = this.options; var buffer = this.slider.find(".buffer"); if (o.vertical === true) { buffer.css("height", this.buffer + "%"); } else { buffer.css("width", this.buffer + "%"); } Utils.exec(o.onChangeBuffer, [this.buffer, this.slider], element[0]); Utils.exec(o.onChange, [element.val(), this.percent, this.buffer], element[0]); }, val: function(v){ var o = this.options; if (v === undefined || isNaN(v)) { return this.value; } if (v < o.min) { v = o.min; } if (v > o.max) { v = o.max; } this.value = this._correct(v); this.percent = this._convert(this.value, 'val2prc'); this.pixel = this._convert(this.percent, 'prc2pix'); this._redraw(); }, buff: function(v){ var slider = this.slider; var buffer = slider.find(".buffer"); if (v === undefined || isNaN(v)) { return this.buffer; } if (buffer.length === 0) { return false; } v = parseInt(v); if (v > 100) { v = 100; } if (v < 0) { v = 0; } this.buffer = v; this._buffer(); }, changeValue: function(){ var element = this.element, o = this.options; var val = element.attr("data-value"); if (val < o.min) { val = o.min } if (val > o.max) { val = o.max } this.val(val); }, changeBuffer: function(){ var element = this.element; var val = parseInt(element.attr("data-buffer")); if (val < 0) { val = 0 } if (val > 100) { val = 100 } this.buff(val); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-value": this.changeValue(); break; case "data-buffer": this.changeBuffer(); break; case 'disabled': this.toggleState(); break; } } }; Metro.plugin('slider', Slider); // Source: js/plugins/sorter.js var Sorter = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.initial = []; this._setOptionsFromDOM(); this._create(); return this; }, options: { thousandSeparator: ",", decimalSeparator: ",", sortTarget: null, sortSource: null, sortDir: "asc", sortStart: true, saveInitial: true, onSortStart: Metro.noop, onSortStop: Metro.noop, onSortItemSwitch: Metro.noop, onSorterCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createStructure(); Utils.exec(o.onSorterCreate, [element]); }, _createStructure: function(){ var element = this.element, o = this.options; if (o.sortTarget === null) { o.sortTarget = element.children()[0].tagName; } this.initial = element.find(o.sortTarget).get(); if (o.sortStart === true) { this.sort(o.sortDir); } }, _getItemContent: function(item){ var o = this.options; var data, inset, i, format; if (Utils.isValue(o.sortSource)) { data = ""; inset = item.getElementsByClassName(o.sortSource); if (inset.length > 0) for (i = 0; i < inset.length; i++) { data += inset[i].textContent; } format = inset[0].dataset.format; } else { data = item.textContent; format = item.dataset.format; } data = (""+data).toLowerCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim(); if (Utils.isValue(format)) { if (['number', 'int', 'float', 'money'].indexOf(format) !== -1 && (o.thousandSeparator !== "," || o.decimalSeparator !== "." )) { data = Utils.parseNumber(data, o.thousandSeparator, o.decimalSeparator); } switch (format) { case "date": data = Utils.isDate(data) ? new Date(data) : ""; break; case "number": data = Number(data); break; case "int": data = parseInt(data); break; case "float": data = parseFloat(data); break; case "money": data = Utils.parseMoney(data); break; case "card": data = Utils.parseCard(data); break; case "phone": data = Utils.parsePhone(data); break; } } return data; }, sort: function(dir){ var that = this, element = this.element, o = this.options; var items; var id = Utils.uniqueId(); var prev; if (dir !== undefined) { o.sortDir = dir; } items = element.find(o.sortTarget).get(); if (items.length === 0) { return ; } prev = $("<div>").attr("id", id).insertBefore($(element.find(o.sortTarget)[0])); Utils.exec(o.onSortStart, [element], element[0]); items.sort(function(a, b){ var c1 = that._getItemContent(a); var c2 = that._getItemContent(b); var result = 0; if (c1 < c2 ) { return result = -1; } if (c1 > c2 ) { return result = 1; } if (result !== 0) { Utils.exec(o.onSortItemSwitch, [a, b], element[0]); } return result; }); if (o.sortDir === "desc") { items.reverse(); } element.find(o.sortTarget).remove(); $.each(items, function(){ var $this = $(this); $this.insertAfter(prev); prev = $this; }); $("#"+id).remove(); Utils.exec(o.onSortStop, [element], element[0]); }, reset: function(){ var that = this, element = this.element, o = this.options; var items; var id = Utils.uniqueId(); var prev; items = this.initial; if (items.length === 0) { return ; } prev = $("<div>").attr("id", id).insertBefore($(element.find(o.sortTarget)[0])); element.find(o.sortTarget).remove(); $.each(items, function(){ var $this = $(this); $this.insertAfter(prev); prev = $this; }); $("#"+id).remove(); }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var changeSortDir = function() { var dir = element.attr("data-sort-dir").trim(); if (dir === "") return; o.sortDir = dir; that.sort(); }; var changeSortContent = function(){ var content = element.attr("data-sort-content").trim(); if (content === "") return ; o.sortContent = content; that.sort(); }; switch (attributeName) { case "data-sort-dir": changeSortDir(); break; case "data-sort-content": changeSortContent(); break; } }, destroy: function(){} }; Metro.plugin('sorter', Sorter); Metro['sorter'] = { create: function(el, op){ return $(el).sorter(op); }, isSorter: function(el){ return Utils.isMetroObject(el, "sorter"); }, sort: function(el, dir){ if (!this.isSorter(el)) { return false; } var sorter = $(el).data("sorter"); if (dir === undefined) { dir = "asc"; } sorter.sort(dir); }, reset: function(el){ if (!this.isSorter(el)) { return false; } var sorter = $(el).data("sorter"); sorter.reset(); } }; // Source: js/plugins/spinner.js var Spinner = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.repeat_timer = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { step: 1, plusIcon: "<span class='default-icon-plus'></span>", minusIcon: "<span class='default-icon-minus'></span>", buttonsPosition: "default", defaultValue: 0, minValue: null, maxValue: null, fixed: 0, repeatThreshold: 500, hideCursor: false, clsSpinner: "", clsSpinnerInput: "", clsSpinnerButton: "", clsSpinnerButtonPlus: "", clsSpinnerButtonMinus: "", onBeforeChange: Metro.noop_true, onChange: Metro.noop, onPlusClick: Metro.noop, onMinusClick: Metro.noop, onArrowUp: Metro.noop, onArrowDown: Metro.noop, onButtonClick: Metro.noop, onArrowClick: Metro.noop, onSpinnerCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onCreate, [element]); }, _createStructure: function(){ var element = this.element, o = this.options; var spinner = $("<div>").addClass("spinner").addClass("buttons-"+o.buttonsPosition).addClass(element[0].className).addClass(o.clsSpinner); var button_plus = $("<button>").attr("type", "button").addClass("button spinner-button spinner-button-plus").addClass(o.clsSpinnerButton + " " + o.clsSpinnerButtonPlus).html(o.plusIcon); var button_minus = $("<button>").attr("type", "button").addClass("button spinner-button spinner-button-minus").addClass(o.clsSpinnerButton + " " + o.clsSpinnerButtonMinus).html(o.minusIcon); var init_value = element.val().trim(); if (!Utils.isValue(init_value)) { element.val(0); } element[0].className = ''; spinner.insertBefore(element); element.appendTo(spinner).addClass(o.clsSpinnerInput); element.addClass("original-input"); button_plus.appendTo(spinner); button_minus.appendTo(spinner); if (o.hideCursor === true) { spinner.addClass("hide-cursor"); } if (o.disabled === true || element.is(":disabled")) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var spinner = element.closest(".spinner"); var spinner_buttons = spinner.find(".spinner-button"); var spinnerButtonClick = function(plus, threshold){ var curr = element.val(); var val = Number(element.val()); var step = Number(o.step); if (plus) { val += step; } else { val -= step; } that._setValue(val.toFixed(o.fixed), true); Utils.exec(plus ? o.onPlusClick : o.onMinusClick, [curr, val, element.val()], element[0]); Utils.exec(plus ? o.onArrowUp : o.onArrowDown, [curr, val, element.val()], element[0]); Utils.exec(o.onButtonClick, [curr, val, element.val(), plus ? 'plus' : 'minus'], element[0]); Utils.exec(o.onArrowClick, [curr, val, element.val(), plus ? 'plus' : 'minus'], element[0]); setTimeout(function(){ if (that.repeat_timer) { spinnerButtonClick(plus, 100); } }, threshold); }; spinner.on(Metro.events.click, function(e){ $(".focused").removeClass("focused"); spinner.addClass("focused"); e.preventDefault(); e.stopPropagation(); }); spinner_buttons.on(Metro.events.start, function(e){ e.preventDefault(); that.repeat_timer = true; spinnerButtonClick($(this).hasClass("spinner-button-plus"), o.repeatThreshold); }); spinner_buttons.on(Metro.events.stop, function(){ that.repeat_timer = false; }); element.on(Metro.events.keydown, function(e){ if (e.keyCode === Metro.keyCode.UP_ARROW || e.keyCode === Metro.keyCode.DOWN_ARROW) { that.repeat_timer = true; spinnerButtonClick(e.keyCode === Metro.keyCode.UP_ARROW, o.repeatThreshold); } }); spinner.on(Metro.events.keyup, function(){ that.repeat_timer = false; }); }, _setValue: function(val, trigger_change){ var element = this.element, o = this.options; if (Utils.exec(o.onBeforeChange, [val], element[0]) !== true) { return ; } if (Utils.isValue(o.maxValue) && val > Number(o.maxValue)) { val = Number(o.maxValue); } if (Utils.isValue(o.minValue) && val < Number(o.minValue)) { val = Number(o.minValue); } element.val(val); Utils.exec(o.onChange, [val], element[0]); if (trigger_change === true) { element.trigger("change"); } }, val: function(val){ var that = this, element = this.element, o = this.options; if (!Utils.isValue(val)) { return element.val(); } that._setValue(val.toFixed(o.fixed), true); }, toDefault: function(){ var element = this.element, o = this.options; var val = Utils.isValue(o.defaultValue) ? Number(o.defaultValue) : 0; this._setValue(val.toFixed(o.fixed), true); Utils.exec(o.onChange, [val], element[0]); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ var that = this, element = this.element; var changeValue = function(){ var val = element.attr('value').trim(); if (Utils.isValue(val)) { that._setValue(Number(val), false); } }; switch (attributeName) { case 'disabled': this.toggleState(); break; case 'value': changeValue(); break; } }, destroy: function(){ var element = this.element; var spinner = element.closest(".spinner"); spinner.off(Metro.events.click, ".spinner-button"); element.insertBefore(spinner); spinner.remove(); } }; Metro.plugin('spinner', Spinner); $(document).on(Metro.events.click, function(){ $(".spinner").removeClass("focused"); }); // Source: js/plugins/splitter.js var Splitter = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.storage = Utils.isValue(Metro.storage) ? Metro.storage : null; this.storageKey = "SPLITTER:"; this._setOptionsFromDOM(); this._create(); return this; }, options: { splitMode: "horizontal", // horizontal or vertical splitSizes: null, gutterSize: 4, minSizes: null, children: "*", gutterClick: "expand", // TODO expand or collapse saveState: false, onResizeStart: Metro.noop, onResizeStop: Metro.noop, onResizeSplit: Metro.noop, onSplitterCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onCreate, [element]); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var children = element.children(o.children).addClass("split-block"); var i, children_sizes = []; var gutters, resizeProp = o.splitMode === "horizontal" ? "width" : "height"; if (!Utils.isValue(element.attr("id"))) { element.attr("id", Utils.elementId("splitter")); } element.addClass("splitter"); if (o.splitMode.toLowerCase() === "vertical") { element.addClass("vertical"); } for (i = 0; i < children.length - 1; i++) { $("<div>").addClass("gutter").css(resizeProp, o.gutterSize).insertAfter($(children[i])); } gutters = element.children(".gutter"); if (!Utils.isValue(o.splitSizes)) { children.css({ flexBasis: "calc("+(100/children.length)+"% - "+(gutters.length * o.gutterSize)+"px)" }) } else { children_sizes = Utils.strToArray(o.splitSizes); for(i = 0; i < children_sizes.length; i++) { $(children[i]).css({ flexBasis: "calc("+children_sizes[i]+"% - "+(gutters.length * o.gutterSize)+"px)" }); } } if (Utils.isValue(o.minSizes)) { if (String(o.minSizes).contains(",")) { children_sizes = Utils.strToArray(o.minSizes); for (i = 0; i < children_sizes.length; i++) { $(children[i]).data("min-size", children_sizes[i]); children[i].style.setProperty('min-'+resizeProp, String(children_sizes[i]).contains("%") ? children_sizes[i] : String(children_sizes[i]).replace("px", "")+"px", 'important'); } } else { $.each(children, function(){ this.style.setProperty('min-'+resizeProp, String(o.minSizes).contains("%") ? o.minSizes : String(o.minSizes).replace("px", "")+"px", 'important'); }); } } if (o.saveState && this.storage !== null) { this._getSize(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var gutters = element.children(".gutter"); gutters.on(Metro.events.start, function(e){ var w = o.splitMode === "horizontal" ? element.width() : element.height(); var gutter = $(this); var prev_block = gutter.prev(".split-block"); var next_block = gutter.next(".split-block"); var prev_block_size = 100 * (o.splitMode === "horizontal" ? prev_block.outerWidth(true) : prev_block.outerHeight(true)) / w; var next_block_size = 100 * (o.splitMode === "horizontal" ? next_block.outerWidth(true) : next_block.outerHeight(true)) / w; var start_pos = Utils.getCursorPosition(element, e); gutter.addClass("active"); prev_block.addClass("stop-select stop-pointer"); next_block.addClass("stop-select stop-pointer"); Utils.exec(o.onResizeStart, [start_pos, gutter, prev_block, next_block], element); $(window).on(Metro.events.move + "-" + element.attr("id"), function(e){ var pos = Utils.getCursorPosition(element, e); var new_pos; if (o.splitMode === "horizontal") { new_pos = (pos.x * 100 / w) - (start_pos.x * 100 / w); } else { new_pos = (pos.y * 100 / w) - (start_pos.y * 100 / w); } prev_block.css("flex-basis", "calc(" + (prev_block_size + new_pos) + "% - "+(gutters.length * o.gutterSize)+"px)"); next_block.css("flex-basis", "calc(" + (next_block_size - new_pos) + "% - "+(gutters.length * o.gutterSize)+"px)"); Utils.exec(o.onResizeSplit, [pos, gutter, prev_block, next_block], element); }); $(window).on(Metro.events.stop + "-" + element.attr("id"), function(e){ prev_block.removeClass("stop-select stop-pointer"); next_block.removeClass("stop-select stop-pointer"); that._saveSize(); gutter.removeClass("active"); $(window).off(Metro.events.move + "-" + element.attr("id")); $(window).off(Metro.events.stop + "-" + element.attr("id")); Utils.exec(o.onResizeStop, [Utils.getCursorPosition(element, e), gutter, prev_block, next_block], element); }) }); }, _saveSize: function(){ var that = this, element = this.element, o = this.options; var storage = this.storage, itemsSize = []; if (o.saveState === true && storage !== null) { $.each(element.children(".split-block"), function(){ var item = $(this); itemsSize.push(item.css("flex-basis")); }); storage.setItem(this.storageKey + element.attr("id"), itemsSize); } }, _getSize: function(){ var that = this, element = this.element, o = this.options; var storage = this.storage, itemsSize = []; if (o.saveState === true && storage !== null) { itemsSize = storage.getItem(this.storageKey + element.attr("id")); $.each(element.children(".split-block"), function(i, v){ var item = $(v); if (Utils.isValue(itemsSize) && Utils.isValue(itemsSize[i])) item.css("flex-basis", itemsSize[i]); }); } }, changeAttribute: function(attributeName){ }, destroy: function(){} }; Metro.plugin('splitter', Splitter); // Source: js/plugins/stepper.js var Stepper = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.current = 0; this._setOptionsFromDOM(); this._create(); return this; }, options: { view: Metro.stepperView.SQUARE, // square, cycle, diamond steps: 3, step: 1, stepClick: false, clsStepper: "", clsStep: "", clsComplete: "", clsCurrent: "", onStep: Metro.noop, onStepClick: Metro.noop, onStepperCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; if (o.step <= 0) { o.step = 1; } this._createStepper(); this._createEvents(); Utils.exec(o.onStepperCreate, [element]); }, _createStepper: function(){ var that = this, element = this.element, o = this.options; var i; element.addClass("stepper").addClass(o.view).addClass(o.clsStepper); for(i = 1; i <= o.steps; i++) { var step = $("<span>").addClass("step").addClass(o.clsStep).data("step", i).html("<span>"+i+"</span>").appendTo(element); } this.current = 1; this.toStep(o.step); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".step", function(){ var step = $(this).data("step"); if (o.stepClick === true) { that.toStep(step); Utils.exec(o.onStepClick, [step, element]); } }); }, next: function(){ var that = this, element = this.element, o = this.options; var steps = element.find(".step"); if (this.current + 1 > steps.length) { return ; } this.current++; this.toStep(this.current); }, prev: function(){ var that = this, element = this.element, o = this.options; if (this.current - 1 === 0) { return ; } this.current--; this.toStep(this.current); }, last: function(){ var that = this, element = this.element, o = this.options; this.toStep(element.find(".step").length); }, first: function(){ this.toStep(1); }, toStep: function(step){ var that = this, element = this.element, o = this.options; var target = $(element.find(".step").get(step - 1)); if (target.length === 0) { return ; } this.current = step; element.find(".step") .removeClass("complete current") .removeClass(o.clsCurrent) .removeClass(o.clsComplete); target.addClass("current").addClass(o.clsCurrent); target.prevAll().addClass("complete").addClass(o.clsComplete); Utils.exec(o.onStep, [this.current, element]); }, changeAttribute: function(attributeName){ } }; Metro.plugin('stepper', Stepper); // Source: js/plugins/streamer.js var Streamer = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.data = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { duration: METRO_ANIMATION_DURATION, defaultClosedIcon: "", defaultOpenIcon: "", changeUri: true, encodeLink: true, closed: false, chromeNotice: false, startFrom: null, slideToStart: true, startSlideSleep: 1000, source: null, data: null, eventClick: "select", selectGlobal: true, streamSelect: false, excludeSelectElement: null, excludeClickElement: null, excludeElement: null, excludeSelectClass: "", excludeClickClass: "", excludeClass: "", onStreamClick: Metro.noop, onStreamSelect: Metro.noop, onEventClick: Metro.noop, onEventSelect: Metro.noop, onStreamerCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; element.addClass("streamer"); if (element.attr("id") === undefined) { element.attr("id", Utils.elementId("streamer")); } if (o.source === null && o.data === null) { return false; } $("<div>").addClass("streams").appendTo(element); $("<div>").addClass("events-area").appendTo(element); if (o.source !== null) { $.get(o.source, function(data){ that.data = data; that.build(); }); } else { this.data = o.data; this.build(); } this._createEvents(); if (o.chromeNotice === true && Utils.detectChrome() === true && Utils.isTouchDevice() === false) { $("<p>").addClass("text-small text-muted").html("*) In Chrome browser please press and hold Shift and turn the mouse wheel.").insertAfter(element); } }, build: function(){ var that = this, element = this.element, o = this.options, data = this.data; var streams = element.find(".streams").html(""); var events_area = element.find(".events-area").html(""); var timeline = $("<ul>").addClass("streamer-timeline").html("").appendTo(events_area); var streamer_events = $("<div>").addClass("streamer-events").appendTo(events_area); var event_group_main = $("<div>").addClass("event-group").appendTo(streamer_events); var StreamerIDS = Utils.getURIParameter(null, "StreamerIDS"); if (StreamerIDS !== null && o.encodeLink === true) { StreamerIDS = atob(StreamerIDS); } var StreamerIDS_i = StreamerIDS ? StreamerIDS.split("|")[0] : null; var StreamerIDS_a = StreamerIDS ? StreamerIDS.split("|")[1].split(",") : []; if (data.actions !== undefined) { var actions = $("<div>").addClass("streamer-actions").appendTo(streams); $.each(data.actions, function(){ var item = this; var button = $("<button>").addClass("streamer-action").addClass(item.cls).html(item.html); if (item.onclick !== undefined) button.on(Metro.events.click, function(){ Utils.exec(item.onclick, [element]); }); button.appendTo(actions); }); } // Create timeline timeline.html(""); if (data.timeline === undefined) { data.timeline = { start: "09:00", stop: "18:00", step: 20 } } var start = new Date(), stop = new Date(); var start_time_array = data.timeline.start ? data.timeline.start.split(":") : [9,0]; var stop_time_array = data.timeline.stop ? data.timeline.stop.split(":") : [18,0]; var step = data.timeline.step ? parseInt(data.timeline.step) * 60 : 1200; start.setHours(start_time_array[0]); start.setMinutes(start_time_array[1]); start.setSeconds(0); stop.setHours(stop_time_array[0]); stop.setMinutes(stop_time_array[1]); stop.setSeconds(0); for (var i = start.getTime()/1000; i <= stop.getTime()/1000; i += step) { var t = new Date(i * 1000); var h = t.getHours(), m = t.getMinutes(); var v = (h < 10 ? "0"+h : h) + ":" + (m < 10 ? "0"+m : m); var li = $("<li>").data("time", v).addClass("js-time-point-" + v.replace(":", "-")).html("<em>"+v+"</em>").appendTo(timeline); } // -- End timeline creator if (data.streams !== undefined) { $.each(data.streams, function(stream_index){ var stream_item = this; var stream = $("<div>").addClass("stream").addClass(this.cls).appendTo(streams); stream .addClass(stream_item.cls) .data("one", false) .data("data", stream_item.data); $("<div>").addClass("stream-title").html(stream_item.title).appendTo(stream); $("<div>").addClass("stream-secondary").html(stream_item.secondary).appendTo(stream); $(stream_item.icon).addClass("stream-icon").appendTo(stream); var bg = Utils.computedRgbToHex(Utils.getStyleOne(stream, "background-color")); var fg = Utils.computedRgbToHex(Utils.getStyleOne(stream, "color")); var stream_events = $("<div>").addClass("stream-events") .data("background-color", bg) .data("text-color", fg) .appendTo(event_group_main); if (stream_item.events !== undefined) { $.each(stream_item.events, function(event_index){ var event_item = this; var _icon; var sid = stream_index+":"+event_index; var custom_html = event_item.custom !== undefined ? event_item.custom : ""; var custom_html_open = event_item.custom_open !== undefined ? event_item.custom_open : ""; var custom_html_close = event_item.custom_close !== undefined ? event_item.custom_close : ""; var event = $("<div>") .data("origin", event_item) .data("sid", sid) .data("data", event_item.data) .data("time", event_item.time) .data("target", event_item.target) .addClass("stream-event") .addClass("size-"+event_item.size+"x") .addClass(event_item.cls) .appendTo(stream_events); var left = timeline.find(".js-time-point-"+this.time.replace(":", "-"))[0].offsetLeft - stream.outerWidth(); event.css({ position: "absolute", left: left }); var slide = $("<div>").addClass("stream-event-slide").appendTo(event); var slide_logo = $("<div>").addClass("slide-logo").appendTo(slide); var slide_data = $("<div>").addClass("slide-data").appendTo(slide); if (event_item.icon !== undefined) { if (Utils.isTag(event_item.icon)) { $(event_item.icon).addClass("icon").appendTo(slide_logo); } else { $("<img>").addClass("icon").attr("src", event_item.icon).appendTo(slide_logo); } } $("<span>").addClass("time").css({ backgroundColor: bg, color: fg }).html(event_item.time).appendTo(slide_logo); $("<div>").addClass("title").html(event_item.title).appendTo(slide_data); $("<div>").addClass("subtitle").html(event_item.subtitle).appendTo(slide_data); $("<div>").addClass("desc").html(event_item.desc).appendTo(slide_data); if (o.closed === false && (element.attr("id") === StreamerIDS_i && StreamerIDS_a.indexOf(sid) !== -1) || event_item.selected === true || parseInt(event_item.selected) === 1) { event.addClass("selected"); } if (o.closed === true || event_item.closed === true || parseInt(event_item.closed) === 1) { _icon = event_item.closedIcon !== undefined ? Utils.isTag(event_item.closedIcon) ? event_item.closedIcon : "<span>"+event_item.closedIcon+"</span>" : Utils.isTag(o.defaultClosedIcon) ? o.defaultClosedIcon : "<span>"+o.defaultClosedIcon+"</span>"; $(_icon).addClass("state-icon").addClass(event_item.clsClosedIcon).appendTo(slide); event .data("closed", true) .data("target", event_item.target); event.append(custom_html_open); } else { _icon = event_item.openIcon !== undefined ? Utils.isTag(event_item.openIcon) ? event_item.openIcon : "<span>"+event_item.openIcon+"</span>" : Utils.isTag(o.defaultOpenIcon) ? o.defaultOpenIcon : "<span>"+o.defaultOpenIcon+"</span>"; $(_icon).addClass("state-icon").addClass(event_item.clsOpenIcon).appendTo(slide); event .data("closed", false); event.append(custom_html_close); } event.append(custom_html); }); var last_child = stream_events.find(".stream-event:last-child"); if (last_child.length > 0) stream_events.outerWidth(last_child[0].offsetLeft + last_child.outerWidth()); } }); } if (data.global !== undefined) { $.each(['before', 'after'], function(){ var global_item = this; if (data.global[global_item] !== undefined) { $.each(data.global[global_item], function(){ var event_item = this; var group = $("<div>").addClass("event-group").addClass("size-"+event_item.size+"x"); var events = $("<div>").addClass("stream-events global-stream").appendTo(group); var event = $("<div>").addClass("stream-event").appendTo(events); event .addClass("global-event") .addClass(event_item.cls) .data("time", event_item.time) .data("origin", event_item) .data("data", event_item.data); $("<div>").addClass("event-title").html(event_item.title).appendTo(event); $("<div>").addClass("event-subtitle").html(event_item.subtitle).appendTo(event); $("<div>").addClass("event-html").html(event_item.html).appendTo(event); var left, t = timeline.find(".js-time-point-"+this.time.replace(":", "-")); if (t.length > 0) left = t[0].offsetLeft - streams.find(".stream").outerWidth(); group.css({ position: "absolute", left: left, height: "100%" }).appendTo(streamer_events); }); } }); } element.data("stream", -1); if (o.startFrom !== null && o.slideToStart === true) { setTimeout(function(){ that.slideTo(o.startFrom); }, o.startSlideSleep); } Utils.exec(o.onStreamerCreate, [element]); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".stream-event", function(e){ var event = $(this); if (o.excludeClass !== "" && event.hasClass(o.excludeClass)) { return ; } if (o.excludeElement !== null && $(e.target).is(o.excludeElement)) { return ; } if (o.closed === false && event.data("closed") !== true && o.eventClick === 'select') { if (o.excludeSelectClass !== "" && event.hasClass(o.excludeSelectClass)) { } else { if (o.excludeSelectElement !== null && $(e.target).is(o.excludeSelectElement)) { } else { if (event.hasClass("global-event")) { if (o.selectGlobal === true) { event.toggleClass("selected"); } } else { event.toggleClass("selected"); } if (o.changeUri === true) { that._changeURI(); } Utils.exec(o.onEventSelect, [event, event.hasClass("selected")]); } } } else { if (o.excludeClickClass !== "" && event.hasClass(o.excludeClickClass)) { } else { if (o.excludeClickElement !== null && $(e.target).is(o.excludeClickElement)) { } else { Utils.exec(o.onEventClick, [event]); if (o.closed === true || event.data("closed") === true) { var target = event.data("target"); if (target) { window.location.href = target; } } } } } }); element.on(Metro.events.click, ".stream", function(e){ var stream = $(this); var index = stream.index(); if (o.streamSelect === false) { return; } console.log(index, element.data("stream")); if (element.data("stream") === index) { element.find(".stream-event").removeClass("disabled"); element.data("stream", -1); } else { element.data("stream", index); element.find(".stream-event").addClass("disabled"); that.enableStream(stream); Utils.exec(o.onStreamSelect, [stream]); } Utils.exec(o.onStreamClick, [stream]); }); if (Utils.isTouchDevice() !== true) { element.on(Metro.events.mousewheel, ".events-area", function(e) { var acrollable = $(this); if (e.deltaY === undefined || e.deltaFactor === undefined) { return ; } if (e.deltaFactor > 1) { var scroll = acrollable.scrollLeft() - ( e.deltaY * 30 ); acrollable.scrollLeft(scroll); e.preventDefault(); } }); } if (Utils.isTouchDevice() === true) { element.on(Metro.events.click, ".stream", function(){ var stream = $(this); stream.toggleClass("focused"); $.each(element.find(".stream"), function () { if ($(this).is(stream)) return ; $(this).removeClass("focused"); }) }) } }, _changeURI: function(){ var that = this, element = this.element, o = this.options, data = this.data; var link = this.getLink(); history.pushState({}, document.title, link); }, slideTo: function(time){ var that = this, element = this.element, o = this.options, data = this.data; var target; if (time === undefined) { target = $(element.find(".streamer-timeline li")[0]); } else { target = $(element.find(".streamer-timeline .js-time-point-" + time.replace(":", "-"))[0]); } element.find(".events-area").animate({ scrollLeft: target[0].offsetLeft - element.find(".streams .stream").outerWidth() }, o.duration); }, enableStream: function(stream){ var that = this, element = this.element, o = this.options, data = this.data; var index = stream.index()-1; stream.removeClass("disabled").data("streamDisabled", false); element.find(".stream-events").eq(index).find(".stream-event").removeClass("disabled"); }, disableStream: function(stream){ var that = this, element = this.element, o = this.options, data = this.data; var index = stream.index()-1; stream.addClass("disabled").data("streamDisabled", true); element.find(".stream-events").eq(index).find(".stream-event").addClass("disabled"); }, toggleStream: function(stream){ if (stream.data("streamDisabled") === true) { this.enableStream(stream); } else { this.disableStream(stream); } }, getLink: function(){ var that = this, element = this.element, o = this.options, data = this.data; var events = element.find(".stream-event"); var a = []; var link; var origin = window.location.href; $.each(events, function(){ var event = $(this); if (event.data("sid") === undefined || !event.hasClass("selected")) { return; } a.push(event.data("sid")); }); link = element.attr("id") + "|" + a.join(","); if (o.encodeLink === true) { link = btoa(link); } return Utils.updateURIParameter(origin, "StreamerIDS", link); }, getTimes: function(){ var that = this, element = this.element, o = this.options, data = this.data; var times = element.find(".streamer-timeline > li"); var result = []; $.each(times, function(){ result.push($(this).data("time")); }); return result; }, getEvents: function(event_type, include_global){ var that = this, element = this.element, o = this.options, data = this.data; var items, events = []; switch (event_type) { case "selected": items = element.find(".stream-event.selected"); break; case "non-selected": items = element.find(".stream-event:not(.selected)"); break; default: items = element.find(".stream-event"); } $.each(items, function(){ var item = $(this); var origin; if (include_global !== true && item.parent().hasClass("global-stream")) return ; origin = item.data("origin"); events.push(origin); }); return events; }, source: function(s){ if (s === undefined) { return this.options.source; } this.options.source = s; this.changeSource(); }, data: function(s){ if (s === undefined) { return this.options.source; } this.options.data = s; this.changeData(); }, getStreamerData: function(){ return this.data; }, toggleEvent: function(event){ var that = this, element = this.element, o = this.options, data = this.data; event = $(event); if (event.hasClass("global-event") && o.selectGlobal !== true) { return ; } if (event.hasClass("selected")) { this.selectEvent(event, false); } else { this.selectEvent(event, true); } }, selectEvent: function(event, state){ var that = this, element = this.element, o = this.options, data = this.data; if (state === undefined) { state = true; } event = $(event); if (event.hasClass("global-event") && o.selectGlobal !== true) { return ; } if (state === true) event.addClass("selected"); else event.removeClass("selected"); if (o.changeUri === true) { that._changeURI(); } Utils.exec(o.onEventSelect, [event, state]); }, changeSource: function(){ var that = this, element = this.element, o = this.options, data = this.data; var new_source = element.attr("data-source"); if (String(new_source).trim() === "") { return ; } o.source = new_source; $.get(o.source, function(data){ that.data = data; that.build(); }); element.trigger("sourcechanged"); }, changeData: function(){ var that = this, element = this.element, o = this.options, data = this.data; var new_data = element.attr("data-data"); if (String(new_data).trim() === "") { return ; } o.data = new_data; this.data = JSON.parse(o.data); this.build(); element.trigger("datachanged"); }, changeStreamSelectOption: function(){ var that = this, element = this.element, o = this.options, data = this.data; o.streamSelect = element.attr("data-stream-select").toLowerCase() === "true"; }, changeAttribute: function(attributeName){ switch (attributeName) { case 'data-source': this.changeSource(); break; case 'data-data': this.changeData(); break; case 'data-stream-select': this.changeStreamSelectOption(); break; } } }; Metro.plugin('streamer', Streamer); // Source: js/plugins/switch.js var Switch = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onSwitchCreate, [this.element]); return this; }, options: { material: false, caption: "", captionPosition: "right", clsSwitch: "", clsCheck: "", clsCaption: "", onSwitchCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; var container = $("<label>").addClass((o.material === true ? " switch-material " : " switch ") + element[0].className); var check = $("<span>").addClass("check"); var caption = $("<span>").addClass("caption").html(o.caption); element.attr("type", "checkbox"); container.insertBefore(element); element.appendTo(container); check.appendTo(container); caption.appendTo(container); if (o.captionPosition === 'left') { container.addClass("caption-left"); } element[0].className = ''; container.addClass(o.clsSwitch); caption.addClass(o.clsCaption); check.addClass(o.clsCheck); if (element.is(':disabled')) { this.disable(); } else { this.enable(); } }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; } } }; Metro.plugin('switch', Switch); // Source: js/plugins/table.js var Table = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.currentPage = 1; this.pagesCount = 1; this.searchString = ""; this.data = null; this.activity = null; this.busy = false; this.filters = []; this.wrapperInfo = null; this.wrapperSearch = null; this.wrapperRows = null; this.wrapperPagination = null; this.filterIndex = null; this.filtersIndexes = []; this.component = null; this.inspector = null; this.view = {}; this.viewDefault = {}; this.locale = Metro.locales["en-US"]; this.input_interval = null; this.searchFields = []; this.sort = { dir: "asc", colIndex: 0 }; this.service = []; this.heads = []; this.items = []; this.foots = []; this.filteredItems = []; this._setOptionsFromDOM(); this._create(); return this; }, options: { locale: METRO_LOCALE, horizontalScroll: false, horizontalScrollStop: null, check: false, checkType: "checkbox", checkStyle: 1, checkColIndex: 0, checkName: null, checkStoreKey: "TABLE:$1:KEYS", rownum: false, rownumTitle: "#", filters: null, filtersOperator: "and", source: null, searchMinLength: 1, searchThreshold: 500, searchFields: null, showRowsSteps: true, showSearch: true, showTableInfo: true, showPagination: true, paginationShortMode: true, showActivity: true, muteTable: true, rows: 10, rowsSteps: "10,25,50,100", staticView: false, viewSaveMode: "client", viewSavePath: "TABLE:$1:OPTIONS", sortDir: "asc", decimalSeparator: ".", thousandSeparator: ",", tableRowsCountTitle: "Show entries:", tableSearchTitle: "Search:", tableInfoTitle: "Showing $1 to $2 of $3 entries", paginationPrevTitle: "Prev", paginationNextTitle: "Next", allRecordsTitle: "All", inspectorTitle: "Inspector", activityType: "cycle", activityStyle: "color", activityTimeout: 100, searchWrapper: null, rowsWrapper: null, infoWrapper: null, paginationWrapper: null, cellWrapper: true, clsComponent: "", clsTableContainer: "", clsTable: "", clsHead: "", clsHeadRow: "", clsHeadCell: "", clsBody: "", clsBodyRow: "", clsBodyCell: "", clsCellWrapper: "", clsFooter: "", clsFooterRow: "", clsFooterCell: "", clsTableTop: "", clsRowsCount: "", clsSearch: "", clsTableBottom: "", clsTableInfo: "", clsTablePagination: "", clsPagination: "", clsEvenRow: "", clsOddRow: "", clsRow: "", onDraw: Metro.noop, onDrawRow: Metro.noop, onDrawCell: Metro.noop, onAppendRow: Metro.noop, onAppendCell: Metro.noop, onSortStart: Metro.noop, onSortStop: Metro.noop, onSortItemSwitch: Metro.noop, onSearch: Metro.noop, onRowsCountChange: Metro.noop, onDataLoad: Metro.noop, onDataLoadError: Metro.noop, onDataLoaded: Metro.noop, onFilterRowAccepted: Metro.noop, onFilterRowDeclined: Metro.noop, onCheckClick: Metro.noop, onCheckClickAll: Metro.noop, onCheckDraw: Metro.noop, onViewSave: Metro.noop, onViewGet: Metro.noop, onViewCreated: Metro.noop, onTableCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var id = Utils.elementId("table"); if (!Utils.isValue(element.attr("id"))) { element.attr("id", id); } if (Utils.isValue(Metro.locales[o.locale])) { this.locale = Metro.locales[o.locale]; } if (Utils.isValue(o.searchFields)) { this.searchFields = Utils.strToArray(o.searchFields); } if (o.source !== null) { Utils.exec(o.onDataLoad, [o.source], element[0]); $.get(o.source, function(data){ if (typeof data !== "object") { throw new Error("Data for table is not a object"); } that._build(data); Utils.exec(o.onDataLoaded, [o.source, data], element[0]); }).fail(function( jqXHR, textStatus, errorThrown) { Utils.exec(o.onDataLoadError, [o.source, jqXHR, textStatus, errorThrown], element[0]); console.log(textStatus); console.log(jqXHR); console.log(errorThrown); }); } else { that._build(); } }, _build: function(data){ var that = this, element = this.element, o = this.options; var view, id = element.attr("id"); o.rows = parseInt(o.rows); this.items = []; this.heads = []; this.foots = []; if (Utils.isValue(data)) { this._createItemsFromJSON(data); } else { this._createItemsFromHTML() } this.view = this._createView(); this.viewDefault = Utils.objectClone(this.view); if (o.viewSaveMode.toLowerCase() === "client") { view = Metro.storage.getItem(o.viewSavePath.replace("$1", id)); if (Utils.isValue(view) && Utils.objectLength(view) === Utils.objectLength(this.view)) { this.view = view; Utils.exec(o.onViewGet, [view], element[0]); } this._final(); } else { $.get( o.viewSavePath, { id: id }, function(view){ if (Utils.isValue(view) && Utils.objectLength(view) === Utils.objectLength(that.view)) { that.view = view; Utils.exec(o.onViewGet, [view], element[0]); } that._final(); } ).fail(function(jqXHR, textStatus) { that._final(); console.log("Warning! View " + textStatus + " for table " + element.attr('id') + " "); }); } }, _final: function(){ var element = this.element, o = this.options; var id = element.attr("id"); Metro.storage.delItem(o.checkStoreKey.replace("$1", id)); this._service(); this._createStructure(); this._createInspector(); this._createEvents(); Utils.exec(o.onTableCreate, [element], element[0]); }, _service: function(){ var o = this.options; this.service = [ { // Rownum title: o.rownumTitle, format: undefined, name: undefined, sortable: false, sortDir: undefined, clsColumn: "rownum-cell " + (o.rownum !== true ? "d-none" : ""), cls: "rownum-cell " + (o.rownum !== true ? "d-none" : ""), colspan: undefined, type: "rownum" }, { // Check title: o.checkType === "checkbox" ? "<input type='checkbox' data-role='checkbox' class='table-service-check-all' data-style='"+o.checkStyle+"'>" : "", format: undefined, name: undefined, sortable: false, sortDir: undefined, clsColumn: "check-cell " + (o.check !== true ? "d-none" : ""), cls: "check-cell "+(o.check !== true ? "d-none" : ""), colspan: undefined, type: "rowcheck" } ]; }, _createView: function(){ var view, o = this.options; view = {}; $.each(this.heads, function(i){ if (Utils.isValue(this.cls)) {this.cls = this.cls.replace("hidden", "");} if (Utils.isValue(this.clsColumn)) {this.clsColumn = this.clsColumn.replace("hidden", "");} view[i] = { "index": i, "index-view": i, "show": !Utils.isValue(this.show) ? true : this.show, "size": Utils.isValue(this.size) ? this.size : "" } }); Utils.exec(o.onViewCreated, [view], view); return view; }, _createInspectorItems: function(table){ var that = this, o = this.options; var j, tds = [], row; var cells = this.heads; table.html(""); for (j = 0; j < cells.length; j++){ tds[j] = null; } $.each(cells, function(i){ row = $("<tr>"); row.data('index', i); row.data('index-view', i); $("<td>").html("<input type='checkbox' data-style='"+o.checkStyle+"' data-role='checkbox' name='column_show_check[]' value='"+i+"' "+(Utils.bool(that.view[i]['show']) ? "checked" : "")+">").appendTo(row); $("<td>").html(this.title).appendTo(row); $("<td>").html("<input type='number' data-role='spinner' name='column_size' value='"+that.view[i]['size']+"' data-index='"+i+"'>").appendTo(row); $("<td>").html("" + "<button class='button square js-table-inspector-field-up' type='button'><span class='mif-arrow-up'></span></button>" + "<button class='button square js-table-inspector-field-down' type='button'><span class='mif-arrow-down'></span></button>" + "").appendTo(row); tds[that.view[i]['index-view']] = row; }); // for (j = 0; j < cells.length; j++){ tds[j].appendTo(table); } }, _createInspector: function(){ var o = this.options; var inspector, table_wrap, table, tbody, actions; inspector = $("<div data-role='draggable' data-drag-element='.table-inspector-header' data-drag-area='body'>").addClass("table-inspector"); inspector.attr("for", this.element.attr("id")); $("<div class='table-inspector-header'>"+o.inspectorTitle+"</div>").appendTo(inspector); table_wrap = $("<div>").addClass("table-wrap").appendTo(inspector); table = $("<table>").addClass("table subcompact"); tbody = $("<tbody>").appendTo(table); table.appendTo(table_wrap); this._createInspectorItems(tbody); actions = $("<div class='table-inspector-actions'>").appendTo(inspector); $("<button class='button primary js-table-inspector-save' type='button'>").html(this.locale.buttons.save).appendTo(actions); $("<button class='button secondary js-table-inspector-reset ml-2 mr-2' type='button'>").html(this.locale.buttons.reset).appendTo(actions); $("<button class='button link js-table-inspector-cancel place-right' type='button'>").html(this.locale.buttons.cancel).appendTo(actions); inspector.data("open", false); this.inspector = inspector; $("body").append(inspector); this._createInspectorEvents(); }, _resetInspector: function(){ var inspector = this.inspector; var table = inspector.find("table tbody"); this._createInspectorItems(table); this._createInspectorEvents(); }, _createHeadsFormHTML: function(){ var that = this, element = this.element; var head = element.find("thead"); if (head.length > 0) $.each(head.find("tr > *"), function(){ var item = $(this); var dir, head_item, item_class; if (Utils.isValue(item.data('sort-dir'))) { dir = item.data('sort-dir'); } else { if (item.hasClass("sort-asc")) { dir = "asc"; } else if (item.hasClass("sort-desc")) { dir = "desc" } else { dir = undefined; } } item_class = item[0].className.replace("sortable-column", ""); item_class = item_class.replace("sort-asc", ""); item_class = item_class.replace("sort-desc", ""); item_class = item_class.replace("hidden", ""); head_item = { type: "data", title: item.html(), name: Utils.isValue(item.data("name")) ? item.data("name") : item.text().replace(" ", "_"), sortable: item.hasClass("sortable-column") || (Utils.isValue(item.data('sortable')) && JSON.parse(item.data('sortable') === true)), sortDir: dir, format: Utils.isValue(item.data("format")) ? item.data("format") : "string", clsColumn: Utils.isValue(item.data("cls-column")) ? item.data("cls-column") : "", cls: item_class, colspan: item.attr("colspan"), size: Utils.isValue(item.data("size")) ? item.data("size") : "", show: !(item.hasClass("hidden") || (Utils.isValue(item.data('show')) && JSON.parse(item.data('show')) === false)), required: Utils.isValue(item.data("required")) ? JSON.parse(item.data("required")) === true : false, field: Utils.isValue(item.data("field")) ? item.data("field") : "input", fieldType: Utils.isValue(item.data("field-type")) ? item.data("field-type") : "text", validator: Utils.isValue(item.data("validator")) ? item.data("validator") : null }; that.heads.push(head_item); }); }, _createFootsFromHTML: function(){ var that = this, element = this.element; var foot = element.find("tfoot"); if (foot.length > 0) $.each(foot.find("tr > *"), function(){ var item = $(this); var foot_item; foot_item = { title: item.html(), name: Utils.isValue(item.data("name")) ? item.data("name") : false, cls: item[0].className, colspan: item.attr("colspan") }; that.foots.push(foot_item); }); }, _createItemsFromHTML: function(){ var that = this, element = this.element; var body = element.find("tbody"); if (body.length > 0) $.each(body.find("tr"), function(){ var row = $(this); var tr = []; $.each(row.children("td"), function(){ var td = $(this); tr.push(td.html()); }); that.items.push(tr); }); this._createHeadsFormHTML(); this._createFootsFromHTML(); }, _createItemsFromJSON: function(source){ var that = this; if (typeof source === "string") { source = JSON.parse(source); } if (source.header !== undefined) { that.heads = source.header; } else { this._createHeadsFormHTML(); } if (source.data !== undefined) { $.each(source.data, function(){ var row = this; var tr = []; $.each(row, function(){ var td = this; tr.push(td); }); that.items.push(tr); }); } if (source.footer !== undefined) { this.foots = source.footer; } else { this._createFootsFromHTML(); } }, _createTableHeader: function(){ var element = this.element, o = this.options; var head = $("<thead>").html(''); var tr, th, tds = [], j, cells; var view = o.staticView ? this._createView() : this.view; element.find("thead").remove(); head.addClass(o.clsHead); if (this.heads.length === 0) { return head; } tr = $("<tr>").addClass(o.clsHeadRow).appendTo(head); $.each(this.service, function(){ var item = this, classes = []; th = $("<th>").appendTo(tr); if (Utils.isValue(item.title)) {th.html(item.title);} if (Utils.isValue(item.size)) {th.css({width: item.size});} if (Utils.isValue(item.cls)) {classes.push(item.cls);} classes.push(o.clsHeadCell); th.addClass(classes.join(" ")); }); cells = this.heads; for (j = 0; j < cells.length; j++){ tds[j] = null; } $.each(cells, function(cell_index){ var item = this; var classes = []; th = $("<th>"); th.data("index", cell_index); if (Utils.isValue(item.title)) {th.html(item.title);} if (Utils.isValue(item.format)) {th.attr("data-format", item.format);} if (Utils.isValue(item.name)) {th.attr("data-name", item.name);} if (Utils.isValue(item.colspan)) {th.attr("colspan", item.colspan);} if (Utils.isValue(view[cell_index]['size'])) {th.css({width: view[cell_index]['size']});} if (item.sortable === true) { classes.push("sortable-column"); if (Utils.isValue(item.sortDir)) { classes.push("sort-" + item.sortDir); } } if (Utils.isValue(item.cls)) {classes.push(item.cls);} if (Utils.bool(view[cell_index]['show']) === false) { classes.push("hidden"); } classes.push(o.clsHeadCell); if (Utils.bool(view[cell_index]['show'])) { Utils.arrayDelete(classes, "hidden"); } th.addClass(classes.join(" ")); tds[view[cell_index]['index-view']] = th; }); for (j = 0; j < cells.length; j++){ tds[j].appendTo(tr); } element.prepend(head); }, _createTableBody: function(){ var body, head, element = this.element; head = element.find("thead"); element.find("tbody").remove(); body = $("<tbody>").addClass(this.options.clsBody); body.insertAfter(head); }, _createTableFooter: function(){ var element = this.element, o = this.options; var foot = $("<tfoot>").addClass(o.clsFooter); var tr, th; element.find("tfoot").remove(); if (this.foots.length === 0) { element.append(foot); return; } tr = $("<tr>").addClass(o.clsHeadRow).appendTo(foot); $.each(this.foots, function(){ var item = this; th = $("<th>").appendTo(tr); if (item.title !== undefined) { th.html(item.title); } if (item.name !== undefined) { th.addClass("foot-column-name-" + item.name); } if (item.cls !== undefined) { th.addClass(item.cls); } if (Utils.isValue(item.colspan)) { th.attr("colspan", item.colspan); } th.appendTo(tr); }); element.append(foot); }, _createTopBlock: function (){ var that = this, element = this.element, o = this.options; var top_block = $("<div>").addClass("table-top").addClass(o.clsTableTop).insertBefore(element.parent()); var search_block, search_input, rows_block, rows_select; search_block = Utils.isValue(this.wrapperSearch) ? this.wrapperSearch : $("<div>").addClass("table-search-block").addClass(o.clsSearch).appendTo(top_block); search_input = $("<input>").attr("type", "text").appendTo(search_block); search_input.input({ prepend: o.tableSearchTitle }); if (o.showSearch !== true) { search_block.hide(); } rows_block = Utils.isValue(this.wrapperRows) ? this.wrapperRows : $("<div>").addClass("table-rows-block").addClass(o.clsRowsCount).appendTo(top_block); rows_select = $("<select>").appendTo(rows_block); $.each(Utils.strToArray(o.rowsSteps), function () { var val = parseInt(this); var option = $("<option>").attr("value", val).text(val === -1 ? o.allRecordsTitle : val).appendTo(rows_select); if (val === parseInt(o.rows)) { option.attr("selected", "selected"); } }); rows_select.select({ filter: false, prepend: o.tableRowsCountTitle, onChange: function (val) { val = parseInt(val); if (val === parseInt(o.rows)) { return; } o.rows = val; that.currentPage = 1; that._draw(); Utils.exec(o.onRowsCountChange, [val], element[0]) } }); if (o.showRowsSteps !== true) { rows_block.hide(); } return top_block; }, _createBottomBlock: function (){ var element = this.element, o = this.options; var bottom_block = $("<div>").addClass("table-bottom").addClass(o.clsTableBottom).insertAfter(element.parent()); var info, pagination; info = Utils.isValue(this.wrapperInfo) ? this.wrapperInfo : $("<div>").addClass("table-info").addClass(o.clsTableInfo).appendTo(bottom_block); if (o.showTableInfo !== true) { info.hide(); } pagination = Utils.isValue(this.wrapperPagination) ? this.wrapperPagination : $("<div>").addClass("table-pagination").addClass(o.clsTablePagination).appendTo(bottom_block); if (o.showPagination !== true) { pagination.hide(); } return bottom_block; }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var table_container, table_component, columns; var w_search = $(o.searchWrapper), w_info = $(o.infoWrapper), w_rows = $(o.rowsWrapper), w_paging = $(o.paginationWrapper); if (w_search.length > 0) {this.wrapperSearch = w_search;} if (w_info.length > 0) {this.wrapperInfo = w_info;} if (w_rows.length > 0) {this.wrapperRows = w_rows;} if (w_paging.length > 0) {this.wrapperPagination = w_paging;} table_component = $("<div>").addClass("table-component"); table_component.insertBefore(element); table_container = $("<div>").addClass("table-container").addClass(o.clsTableContainer).appendTo(table_component); element.appendTo(table_container); if (o.horizontalScroll === true) { table_container.addClass("horizontal-scroll"); } if (!Utils.isNull(o.horizontalScrollStop) && Utils.mediaExist(o.horizontalScrollStop)) { table_container.removeClass("horizontal-scroll"); } table_component.addClass(o.clsComponent); this.activity = $("<div>").addClass("table-progress").appendTo(table_component); $("<div>").activity({ type: o.activityType, style: o.activityStyle }).appendTo(this.activity); if (o.showActivity !== true) { this.activity.css({ visibility: "hidden" }) } element.html("").addClass(o.clsTable); this._createTableHeader(); this._createTableBody(); this._createTableFooter(); this._createTopBlock(); this._createBottomBlock(); var need_sort = false; if (this.heads.length > 0) $.each(this.heads, function(i){ var item = this; if (!need_sort && ["asc", "desc"].indexOf(item.sortDir) > -1) { need_sort = true; that.sort.colIndex = i; that.sort.dir = item.sortDir; } }); if (need_sort) { columns = element.find("thead th"); this._resetSortClass(columns); $(columns.get(this.sort.colIndex + that.service.length)).addClass("sort-"+this.sort.dir); this.sorting(); } var filter_func; if (Utils.isValue(o.filters)) { $.each(Utils.strToArray(o.filters), function(){ filter_func = Utils.isFunc(this); if (filter_func !== false) { that.filtersIndexes.push(that.addFilter(filter_func)); } }); } this.currentPage = 1; this.component = table_component; this._draw(); }, _resetSortClass: function(el){ $(el).removeClass("sort-asc sort-desc"); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var component = element.closest(".table-component"); var table_container = component.find(".table-container"); var search = component.find(".table-search-block input"); var customSearch; var id = element.attr("id"); $(window).on(Metro.events.resize+"-"+id, function(){ if (o.horizontalScroll === true) { if (!Utils.isNull(o.horizontalScrollStop) && Utils.mediaExist(o.horizontalScrollStop)) { table_container.removeClass("horizontal-scroll"); } else { table_container.addClass("horizontal-scroll"); } } }); element.on(Metro.events.click, ".sortable-column", function(){ if (o.muteTable === true) element.addClass("disabled"); if (that.busy) { return false; } that.busy = true; var col = $(this); that.activity.show(o.activityTimeout, function(){ that.currentPage = 1; that.sort.colIndex = col.data("index"); if (!col.hasClass("sort-asc") && !col.hasClass("sort-desc")) { that.sort.dir = o.sortDir; } else { if (col.hasClass("sort-asc")) { that.sort.dir = "desc"; } else { that.sort.dir = "asc"; } } that._resetSortClass(element.find(".sortable-column")); col.addClass("sort-"+that.sort.dir); that.sorting(); that._draw(function(){ that.busy = false; if (o.muteTable === true) element.removeClass("disabled"); }); }); }); element.on(Metro.events.click, ".table-service-check input", function(){ var check = $(this); var status = check.is(":checked"); var val = ""+check.val(); var store_key = o.checkStoreKey.replace("$1", id); var storage = Metro.storage; var data = storage.getItem(store_key); if (status) { if (!Utils.isValue(data)) { data = [val]; } else { if (Array(data).indexOf(val) === -1) { data.push(val); } } } else { if (Utils.isValue(data)) { Utils.arrayDelete(data, val); } else { data = []; } } storage.setItem(store_key, data); Utils.exec(o.onCheckClick, [status], this); }); element.on(Metro.events.click, ".table-service-check-all input", function(){ var status = $(this).is(":checked"); var store_key = o.checkStoreKey.replace("$1", id); var data = []; if (status) { $.each(that.filteredItems, function(){ if (data.indexOf(this[o.checkColIndex]) !== -1) return ; data.push(""+this[o.checkColIndex]); }); } else { data = []; } Metro.storage.setItem(store_key, data); that._draw(); Utils.exec(o.onCheckClickAll, [status], this); }); var _search = function(){ that.searchString = this.value.trim().toLowerCase(); clearInterval(that.input_interval); that.input_interval = false; if (!that.input_interval) that.input_interval = setTimeout(function(){ that.currentPage = 1; that._draw(); clearInterval(that.input_interval); that.input_interval = false; }, o.searchThreshold); }; search.on(Metro.events.inputchange, _search); if (Utils.isValue(this.wrapperSearch)) { customSearch = this.wrapperSearch.find("input"); if (customSearch.length > 0) { customSearch.on(Metro.events.inputchange, _search); } } function pageLinkClick(l){ var link = $(l); var item = link.parent(); if (that.filteredItems.length === 0) { return ; } if (item.hasClass("active")) { return ; } if (item.hasClass("service")) { if (link.data("page") === "prev") { that.currentPage--; if (that.currentPage === 0) { that.currentPage = 1; } } else { that.currentPage++; if (that.currentPage > that.pagesCount) { that.currentPage = that.pagesCount; } } } else { that.currentPage = link.data("page"); } that._draw(); } component.on(Metro.events.click, ".pagination .page-link", function(){ pageLinkClick(this) }); if (Utils.isValue(this.wrapperPagination)) { this.wrapperPagination.on(Metro.events.click, ".pagination .page-link", function(){ pageLinkClick(this) }); } this._createInspectorEvents(); element.on(Metro.events.click, ".js-table-crud-button", function(){ }); }, _createInspectorEvents: function(){ var that = this, inspector = this.inspector; // Inspector event this._removeInspectorEvents(); inspector.on(Metro.events.click, ".js-table-inspector-field-up", function(){ var button = $(this), tr = button.closest("tr"); var tr_prev = tr.prev("tr"); var index = tr.data("index"); var index_view; if (tr_prev.length === 0) { return ; } tr.insertBefore(tr_prev); tr.addClass("flash"); setTimeout(function(){ tr.removeClass("flash"); }, 1000); index_view = tr.index(); tr.data("index-view", index_view); that.view[index]['index-view'] = index_view; $.each(tr.nextAll(), function(){ var t = $(this); index_view++; t.data("index-view", index_view); that.view[t.data("index")]['index-view'] = index_view; }); that._createTableHeader(); that._draw(); }); inspector.on(Metro.events.click, ".js-table-inspector-field-down", function(){ var button = $(this), tr = button.closest("tr"); var tr_next = tr.next("tr"); var index = tr.data("index"); var index_view; if (tr_next.length === 0) { return ; } tr.insertAfter(tr_next); tr.addClass("flash"); setTimeout(function(){ tr.removeClass("flash"); }, 1000); index_view = tr.index(); tr.data("index-view", index_view); that.view[index]['index-view'] = index_view; $.each(tr.prevAll(), function(){ var t = $(this); index_view--; t.data("index-view", index_view); that.view[t.data("index")]['index-view'] = index_view; }); that._createTableHeader(); that._draw(); }); inspector.on(Metro.events.click, "input[type=checkbox]", function(){ var check = $(this); var status = check.is(":checked"); var index = check.val(); var op = ['cls', 'clsColumn']; if (status) { $.each(op, function(){ var a; a = Utils.isValue(that.heads[index][this]) ? Utils.strToArray(that.heads[index][this]) : []; Utils.arrayDelete(a, "hidden"); that.heads[index][this] = a.join(" "); that.view[index]['show'] = true; }); } else { $.each(op, function(){ var a; a = Utils.isValue(that.heads[index][this]) ? Utils.strToArray(that.heads[index][this]) : []; if (a.indexOf("hidden") === -1) { a.push("hidden"); } that.heads[index][this] = a.join(" "); that.view[index]['show'] = false; }); } that._createTableHeader(); that._draw(); }); inspector.find("input[type=number]").on(Metro.events.inputchange, function(){ var input = $(this); var index = input.attr("data-index"); var val = parseInt(input.val()); that.view[index]['size'] = val === 0 ? "" : val; that._createTableHeader(); }); inspector.on(Metro.events.click, ".js-table-inspector-save", function(){ that._saveTableView(); that.openInspector(false); }); inspector.on(Metro.events.click, ".js-table-inspector-cancel", function(){ that.openInspector(false); }); inspector.on(Metro.events.click, ".js-table-inspector-reset", function(){ that.resetView(); }); }, _removeInspectorEvents: function(){ var inspector = this.inspector; inspector.off(Metro.events.click, ".js-table-inspector-field-up"); inspector.off(Metro.events.click, ".js-table-inspector-field-down"); inspector.off(Metro.events.click, "input[type=checkbox]"); inspector.off(Metro.events.click, ".js-table-inspector-save"); inspector.off(Metro.events.click, ".js-table-inspector-cancel"); inspector.off(Metro.events.click, ".js-table-inspector-reset"); inspector.find("input[type=number]").off(Metro.events.inputchange); }, _saveTableView: function(){ var element = this.element, o = this.options; var view = this.view; var id = element.attr("id"); if (o.viewSaveMode.toLowerCase() === "client") { Metro.storage.setItem(o.viewSavePath.replace("$1", id), view); Utils.exec(o.onViewSave, [o.viewSavePath, view], element[0]); } else { $.post( o.viewSavePath, { id : element.attr("id"), view : view }, function(data, status, xhr){ Utils.exec(o.onViewSave, [o.viewSavePath, view, data, status, xhr], element[0]); } ); } }, _info: function(start, stop, length){ var element = this.element, o = this.options; var component = element.closest(".table-component"); var info = Utils.isValue(this.wrapperInfo) ? this.wrapperInfo : component.find(".table-info"); var text; if (info.length === 0) { return ; } if (stop > length) { stop = length; } if (this.items.length === 0) { start = stop = length = 0; } text = o.tableInfoTitle; text = text.replace("$1", start); text = text.replace("$2", stop); text = text.replace("$3", length); info.html(text); }, _paging: function(length){ var that = this, element = this.element, o = this.options; var component = element.closest(".table-component"); var pagination_wrapper = Utils.isValue(this.wrapperPagination) ? this.wrapperPagination : component.find(".table-pagination"); var i, prev, next; var shortDistance = 5; var pagination; pagination_wrapper.html(""); pagination = $("<ul>").addClass("pagination").addClass(o.clsPagination).appendTo(pagination_wrapper); if (this.items.length === 0) { return ; } if (o.rows === -1) { return ; } this.pagesCount = Math.ceil(length / o.rows); var add_item = function(item_title, item_type, data){ var li, a; li = $("<li>").addClass("page-item").addClass(item_type); a = $("<a>").addClass("page-link").html(item_title); a.data("page", data); a.appendTo(li); return li; }; prev = add_item(o.paginationPrevTitle, "service prev-page", "prev"); pagination.append(prev); pagination.append(add_item(1, that.currentPage === 1 ? "active" : "", 1)); if (o.paginationShortMode !== true || this.pagesCount <= 7) { for (i = 2; i < this.pagesCount; i++) { pagination.append(add_item(i, i === that.currentPage ? "active" : "", i)); } } else { if (that.currentPage < shortDistance) { for (i = 2; i <= shortDistance; i++) { pagination.append(add_item(i, i === that.currentPage ? "active" : "", i)); } if (this.pagesCount > shortDistance) { pagination.append(add_item("...", "no-link", null)); } } else if (that.currentPage <= that.pagesCount && that.currentPage > that.pagesCount - shortDistance + 1) { if (this.pagesCount > shortDistance) { pagination.append(add_item("...", "no-link", null)); } for (i = that.pagesCount - shortDistance + 1; i < that.pagesCount; i++) { pagination.append(add_item(i, i === that.currentPage ? "active" : "", i)); } } else { pagination.append(add_item("...", "no-link", null)); pagination.append(add_item(that.currentPage - 1, "", that.currentPage - 1)); pagination.append(add_item(that.currentPage, "active", that.currentPage)); pagination.append(add_item(that.currentPage + 1, "", that.currentPage + 1)); pagination.append(add_item("...", "no-link", null)); } } if (that.pagesCount > 1 || that.currentPage < that.pagesCount) pagination.append(add_item(that.pagesCount, that.currentPage === that.pagesCount ? "active" : "", that.pagesCount)); next = add_item(o.paginationNextTitle, "service next-page", "next"); pagination.append(next); if (this.currentPage === 1) { prev.addClass("disabled"); } if (this.currentPage === this.pagesCount) { next.addClass("disabled"); } if (this.filteredItems.length === 0) { pagination.addClass("disabled"); pagination.children().addClass("disabled"); } }, _filter: function(){ var that = this, o = this.options, element = this.element; var items; if ((Utils.isValue(this.searchString) && that.searchString.length >= o.searchMinLength) || this.filters.length > 0) { items = this.items.filter(function(row){ var row_data = "", result, search_result, i, j = 0; if (that.filters.length > 0) { result = o.filtersOperator.toLowerCase() === "and"; for (i = 0; i < that.filters.length; i++) { if (Utils.isNull(that.filters[i])) continue; j++; result = o.filtersOperator.toLowerCase() === "and" ? result && Utils.exec(that.filters[i], [row, that.heads]) : result || Utils.exec(that.filters[i], [row, that.heads]) ; } if (j === 0) result = true; } else { result = true; } if (that.searchFields.length > 0) { $.each(that.heads, function(i, v){ if (that.searchFields.indexOf(v.name) > -1) { row_data += "•"+row[i]; } }) } else { row_data = row.join("•"); } row_data = row_data.replace(/[\n\r]+|[\s]{2,}/g, ' ').trim().toLowerCase(); search_result = Utils.isValue(that.searchString) && that.searchString.length >= o.searchMinLength ? ~row_data.indexOf(that.searchString) : true; result = result && search_result; if (result) { Utils.exec(o.onFilterRowAccepted, [row], element[0]); } else { Utils.exec(o.onFilterRowDeclined, [row], element[0]); } return result; }); } else { items = this.items; } Utils.exec(o.onSearch, [that.searchString, items], element[0]); this.filteredItems = items; return items; }, _draw: function(cb){ var that = this, element = this.element, o = this.options; var body = element.find("tbody"); var i; var start = parseInt(o.rows) === -1 ? 0 : o.rows * (this.currentPage - 1), stop = parseInt(o.rows) === -1 ? this.items.length - 1 : start + o.rows - 1; var items; var stored_keys = Metro.storage.getItem(o.checkStoreKey.replace("$1", element.attr('id'))); var view = o.staticView ? this.viewDefault : this.view; body.html(""); items = this._filter(); for (i = start; i <= stop; i++) { var j, tr, td, check, cells = [], tds = [], is_even_row; if (Utils.isValue(items[i])) { tr = $("<tr>").addClass(o.clsBodyRow); // Rownum is_even_row = i % 2 === 0; td = $("<td>").html(i + 1); if (that.service[0].clsColumn !== undefined) { td.addClass(that.service[0].clsColumn); } td.appendTo(tr); // Checkbox td = $("<td>"); if (o.checkType === "checkbox") { check = $("<input type='checkbox' data-style='"+o.checkStyle+"' data-role='checkbox' name='" + (Utils.isValue(o.checkName) ? o.checkName : 'table_row_check') + "[]' value='" + items[i][o.checkColIndex] + "'>"); } else { check = $("<input type='radio' data-style='"+o.checkStyle+"' data-role='radio' name='" + (Utils.isValue(o.checkName) ? o.checkName : 'table_row_check') + "' value='" + items[i][o.checkColIndex] + "'>"); } if (Utils.isValue(stored_keys) && Array.isArray(stored_keys) && stored_keys.indexOf(""+items[i][o.checkColIndex]) > -1) { check.prop("checked", true); } check.addClass("table-service-check"); Utils.exec(o.onCheckDraw, [check], check[0]); check.appendTo(td); if (that.service[1].clsColumn !== undefined) { td.addClass(that.service[1].clsColumn); } td.appendTo(tr); cells = items[i]; for (j = 0; j < cells.length; j++){ tds[j] = null; } $.each(cells, function(cell_index){ if (o.cellWrapper === true) { td = $("<td>"); $("<div>").addClass("cell-wrapper").addClass(o.clsCellWrapper).html(this).appendTo(td); } else { td = $("<td>").html(this); } td.addClass(o.clsBodyCell); if (Utils.isValue(that.heads[cell_index].clsColumn)) { td.addClass(that.heads[cell_index].clsColumn); } if (Utils.bool(view[cell_index].show) === false) { td.addClass("hidden"); } if (Utils.bool(view[cell_index].show)) { td.removeClass("hidden"); } tds[view[cell_index]['index-view']] = td; Utils.exec(o.onDrawCell, [td, this, cell_index, that.heads[cell_index]], td[0]); }); for (j = 0; j < cells.length; j++){ tds[j].appendTo(tr); Utils.exec(o.onAppendCell, [tds[j], tr, j, element], tds[j][0]) } Utils.exec(o.onDrawRow, [tr, that.view, that.heads, element], tr[0]); tr.addClass(o.clsRow).addClass(is_even_row ? o.clsEvenRow : o.clsOddRow).appendTo(body); Utils.exec(o.onAppendRow, [tr, element], tr[0]); } } this._info(start + 1, stop + 1, items.length); this._paging(items.length); if (this.activity) this.activity.hide(); Utils.exec(o.onDraw, [element], element[0]); if (cb !== undefined) { Utils.exec(cb, [element], element[0]) } }, _getItemContent: function(row){ var result, col = row[this.sort.colIndex]; var format = this.heads[this.sort.colIndex].format; var formatMask = !Utils.isNull(this.heads) && !Utils.isNull(this.heads[this.sort.colIndex]) && Utils.isValue(this.heads[this.sort.colIndex]['formatMask']) ? this.heads[this.sort.colIndex]['formatMask'] : "%Y-%m-%d"; var o = this.options; result = (""+col).toLowerCase().replace(/[\n\r]+|[\s]{2,}/g, ' ').trim(); if (Utils.isValue(format)) { if (['number', 'int', 'float', 'money'].indexOf(format) !== -1 && (o.thousandSeparator !== "," || o.decimalSeparator !== "." )) { result = Utils.parseNumber(result, o.thousandSeparator, o.decimalSeparator); } switch (format) { case "date": result = Utils.isValue(formatMask) ? result.toDate(formatMask) : new Date(result); break; case "number": result = Number(result); break; case "int": result = parseInt(result); break; case "float": result = parseFloat(result); break; case "money": result = Utils.parseMoney(result); break; case "card": result = Utils.parseCard(result); break; case "phone": result = Utils.parsePhone(result); break; } } return result; }, deleteItem: function(fieldIndex, value){ var i, deleteIndexes = []; var is_func = Utils.isFunc(value); for(i = 0; i < this.items.length; i++) { if (is_func) { if (Utils.exec(value, [this.items[i][fieldIndex]])) { deleteIndexes.push(i); } } else { if (this.items[i][fieldIndex] === value) { deleteIndexes.push(i); } } } this.items = Utils.arrayDeleteByMultipleKeys(this.items, deleteIndexes); return this; }, deleteItemByName: function(fieldName, value){ var i, fieldIndex, deleteIndexes = []; var is_func = Utils.isFunc(value); for(i = 0; i < this.heads.length; i++) { if (this.heads[i]['name'] === fieldName) { fieldIndex = i; break; } } for(i = 0; i < this.items.length; i++) { if (is_func) { if (Utils.exec(value, [this.items[i][fieldIndex]])) { deleteIndexes.push(i); } } else { if (this.items[i][fieldIndex] === value) { deleteIndexes.push(i); } } } this.items = Utils.arrayDeleteByMultipleKeys(this.items, deleteIndexes); return this; }, draw: function(){ this._draw(); return this; }, sorting: function(dir){ var that = this, element = this.element, o = this.options; if (Utils.isValue(dir)) { this.sort.dir = dir; } Utils.exec(o.onSortStart, [this.items], element[0]); this.items.sort(function(a, b){ var c1 = that._getItemContent(a); var c2 = that._getItemContent(b); var result = 0; if (c1 < c2) { result = that.sort.dir === "asc" ? -1 : 1; } if (c1 > c2) { result = that.sort.dir === "asc" ? 1 : -1; } if (result !== 0) { Utils.exec(o.onSortItemSwitch, [a, b, result], element[0]); } return result; }); Utils.exec(o.onSortStop, [this.items], element[0]); return this; }, search: function(val){ this.searchString = val.trim().toLowerCase(); this.currentPage = 1; this._draw(); return this; }, _rebuild: function(review){ var that = this, element = this.element; var need_sort = false, sortable_columns; if (review === true) { this.view = this._createView(); } this._createTableHeader(); this._createTableBody(); this._createTableFooter(); if (this.heads.length > 0) $.each(this.heads, function(i){ var item = this; if (!need_sort && ["asc", "desc"].indexOf(item.sortDir) > -1) { need_sort = true; that.sort.colIndex = i; that.sort.dir = item.sortDir; } }); if (need_sort) { sortable_columns = element.find(".sortable-column"); this._resetSortClass(sortable_columns); $(sortable_columns.get(that.sort.colIndex)).addClass("sort-"+that.sort.dir); this.sorting(); } that.currentPage = 1; that._draw(); }, setHeads: function(data){ this.heads = data; return this; }, setHeadItem: function(name, data){ var i, index; for(i = 0; i < this.heads.length; i++) { if (item.name === name) { index = i; break; } } this.heads[index] = data; return this; }, setItems: function(data){ this.items = data; return this; }, setData: function(/*obj*/ data){ this.items = []; this.heads = []; this.foots = []; this._createItemsFromJSON(data); this._rebuild(true); return this; }, loadData: function(source, review){ var that = this, element = this.element, o = this.options; if (!Utils.isValue(review)) { review = true; } element.html(""); if (!Utils.isValue(source)) { this._rebuild(review); } else { o.source = source; Utils.exec(o.onDataLoad, [o.source], element[0]); $.get(o.source, function(data){ that.items = []; that.heads = []; that.foots = []; that._createItemsFromJSON(data); that._rebuild(review); Utils.exec(o.onDataLoaded, [o.source, data], element[0]); }).fail(function( jqXHR, textStatus, errorThrown) { Utils.exec(o.onDataLoadError, [o.source, jqXHR, textStatus, errorThrown], element[0]); console.log(textStatus); console.log(jqXHR); console.log(errorThrown); }); } }, reload: function(review){ this.loadData(this.options.source, review); }, next: function(){ if (this.items.length === 0) return ; this.currentPage++; if (this.currentPage > this.pagesCount) { this.currentPage = this.pagesCount; return ; } this._draw(); return this; }, prev: function(){ if (this.items.length === 0) return ; this.currentPage--; if (this.currentPage === 0) { this.currentPage = 1; return ; } this._draw(); return this; }, first: function(){ if (this.items.length === 0) return ; this.currentPage = 1; this._draw(); return this; }, last: function(){ if (this.items.length === 0) return ; this.currentPage = this.pagesCount; this._draw(); return this; }, page: function(num){ if (num <= 0) { num = 1; } if (num > this.pagesCount) { num = this.pagesCount; } this.currentPage = num; this._draw(); return this; }, addFilter: function(f, redraw){ var filterIndex = null, i, func = Utils.isFunc(f); if (func === false) { return ; } for(i = 0; i < this.filters.length; i++) { if (Utils.isNull(this.filters[i])) { filterIndex = i; this.filters[i] = func; break; } } if (Utils.isNull(filterIndex)) { this.filters.push(func); filterIndex = this.filters.length - 1; } if (redraw === true) { this.currentPage = 1; this.draw(); } return filterIndex }, removeFilter: function(key, redraw){ this.filters[key] = null; if (redraw === true) { this.currentPage = 1; this.draw(); } return this; }, removeFilters: function(redraw){ this.filters = []; if (redraw === true) { this.currentPage = 1; this.draw(); } return this; }, getItems: function(){ return this.items; }, getHeads: function(){ return this.heads; }, getView: function(){ return this.view; }, getFilteredItems: function(){ return this.filteredItems.length > 0 ? this.filteredItems : this.items; }, getSelectedItems: function(){ var element = this.element, o = this.options; var stored_keys = Metro.storage.getItem(o.checkStoreKey.replace("$1", element.attr("id"))); var selected = []; if (!Utils.isValue(stored_keys)) { return []; } $.each(this.items, function(){ if (stored_keys.indexOf(""+this[o.checkColIndex]) !== -1) { selected.push(this); } }); return selected; }, getStoredKeys: function(){ var element = this.element, o = this.options; return Metro.storage.getItem(o.checkStoreKey.replace("$1", element.attr("id")), []); }, clearSelected: function(redraw){ var element = this.element, o = this.options; Metro.storage.setItem(o.checkStoreKey.replace("$1", element.attr("id")), []); element.find("table-service-check-all input").prop("checked", false); if (redraw === true) this._draw(); }, getFilters: function(){ return this.filters; }, getFiltersIndexes: function(){ return this.filtersIndexes; }, openInspector: function(mode){ var ins = this.inspector; if (mode) { ins.show(0, function(){ ins.css({ top: ($(window).height() - ins.outerHeight(true)) / 2 + pageYOffset, left: ($(window).width() - ins.outerWidth(true)) / 2 + pageXOffset }).data("open", true); }); } else { ins.hide().data("open", false); } }, closeInspector: function(){ this.openInspector(false); }, toggleInspector: function(){ this.openInspector(!this.inspector.data("open")); }, resetView: function(){ this.view = this._createView(); this._createTableHeader(); this._createTableFooter(); this._draw(); this._resetInspector(); this._saveTableView(); }, export: function(to, mode, filename, options){ var that = this, o = this.options; var table = document.createElement("table"); var head = $("<thead>").appendTo(table); var body = $("<tbody>").appendTo(table); var i, j, cells, tds = [], items, tr, td; var start, stop; if (typeof Export.tableToCSV !== 'function') { return ; } mode = Utils.isValue(mode) ? mode.toLowerCase() : "all-filtered"; filename = Utils.isValue(filename) ? filename : Utils.elementId("table")+"-export.csv"; // Create table header tr = $("<tr>"); cells = this.heads; for (j = 0; j < cells.length; j++){ tds[j] = null; } $.each(cells, function(cell_index){ var item = this; if (Utils.bool(that.view[cell_index]['show']) === false) { return ; } td = $("<th>"); if (Utils.isValue(item.title)) { td.html(item.title); } tds[that.view[cell_index]['index-view']] = td; }); for (j = 0; j < cells.length; j++){ if (Utils.isValue(tds[j])) tds[j].appendTo(tr); } tr.appendTo(head); // Create table data if (mode === "checked") { items = this.getSelectedItems(); start = 0; stop = items.length - 1; } else if (mode === "view") { items = this._filter(); start = parseInt(o.rows) === -1 ? 0 : o.rows * (this.currentPage - 1); stop = parseInt(o.rows) === -1 ? items.length - 1 : start + o.rows - 1; } else if (mode === "all") { items = this.items; start = 0; stop = items.length - 1; } else { items = this._filter(); start = 0; stop = items.length - 1; } for (i = start; i <= stop; i++) { if (Utils.isValue(items[i])) { tr = $("<tr>"); cells = items[i]; for (j = 0; j < cells.length; j++){ tds[j] = null; } $.each(cells, function(cell_index){ if (Utils.bool(that.view[cell_index].show) === false) { return ; } td = $("<td>").html(this); tds[that.view[cell_index]['index-view']] = td; }); for (j = 0; j < cells.length; j++){ if (Utils.isValue(tds[j])) tds[j].appendTo(tr); } tr.appendTo(body); } } switch (to) { default: Export.tableToCSV(table, filename, options); } table.remove(); }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; function dataCheck(){ o.check = Utils.bool(element.attr("data-check")); that._service(); that._createTableHeader(); that._draw(); } function dataRownum(){ o.rownum = Utils.bool(element.attr("data-rownum")); that._service(); that._createTableHeader(); that._draw(); } switch (attributeName) { case "data-check": dataCheck(); break; case "data-rownum": dataRownum(); break; } } }; Metro.plugin('table', Table); // Source: js/plugins/tabs-material.js var MaterialTabs = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.marker = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { deep: false, fixedTabs: false, clsComponent: "", clsTab: "", clsTabActive: "", clsMarker: "", onBeforeTabOpen: Metro.noop_true, onTabOpen: Metro.noop, onTabsCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onTabsCreate, [element]); }, _applyColor: function(to, color, option){ if (!Utils.isJQueryObject(to)) { to = $(to); } if (Utils.isValue(color)) { if (Utils.isColor(color)) { to.css(option, color); } else { to.addClass(color); } } }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var tabs = element.find("li"), active_tab = element.find("li.active"); element.addClass("tabs-material").addClass(o.clsComponent); tabs.addClass(o.clsTab); if (o.deep === true) { element.addClass("deep"); } if (o.fixedTabs === true) { element.addClass("fixed-tabs"); } this.marker = element.find(".tab-marker"); if (this.marker.length === 0) { this.marker = $("<span>").addClass("tab-marker").addClass(o.clsMarker).appendTo(element); } this.openTab(active_tab.length === 0 ? tabs[0] : active_tab[0]); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var tabs = element.find("li"); element.on(Metro.events.click, "li", function(e){ var tab = $(this); var active_tab = element.find("li.active"); var tab_next = tabs.index(tab) > tabs.index(active_tab); var target = tab.children("a").attr("href"); if (Utils.isValue(target) && target[0] === "#") { if (tab.hasClass("active")) return; if (tab.hasClass("disabled")) return; if (Utils.exec(o.onBeforeTabOpen, [tab, target, tab_next], this) === false) return; if (!Utils.isValue(target)) return; that.openTab(tab, tab_next); e.preventDefault(); } }); var addMouseWheel = function (){ $(element).mousewheel(function(event, delta, deltaX, deltaY){ var scroll_value = delta * METRO_SCROLL_MULTIPLE; element.scrollLeft(element.scrollLeft() - scroll_value); return false; }); }; if (!$('html').hasClass("metro-touch-device")) { addMouseWheel(); } }, openTab: function(tab, tab_next){ var that = this, element = this.element, o = this.options; var tabs = element.find("li"), element_scroll = element.scrollLeft(); var magic = 32, shift, width = element.width(), tab_width, target, tab_left; if (!Utils.isJQueryObject(tab)) { tab = $(tab); } $.each(tabs, function(){ var target = $(this).find("a").attr("href"); if (!Utils.isValue(target)) return; if (target.trim() !== "#" && $(target).length > 0) $(target).hide(); }); tab_left = tab.position().left; tab_width = tab.width(); shift = tab.position().left + tab.width(); tabs.removeClass("active").removeClass(o.clsTabActive); tab.addClass("active").addClass(o.clsTabActive); if (shift + magic > width) { element.animate({ scrollLeft: element_scroll + (shift - width) + (tab_width / 2) }); } if (tab_left - magic < 0) { element.animate({ scrollLeft: tab_left + element_scroll - (tab_width / 2) }); } this.marker.animate({ left: tab_left + element_scroll, width: tab.width() }); target = tab.find("a").attr("href"); if (Utils.isValue(target)) { if (target.trim() !== "#" && $(target).length > 0) $(target).show(); } Utils.exec(o.onTabOpen, [tab, target, tab_next], tab[0]); }, changeAttribute: function(attributeName){ }, destroy: function(){} }; Metro.plugin('materialtabs', MaterialTabs); // Source: js/plugins/tabs.js var Tabs = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._targets = []; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onTabsCreate, [this.element], this.elem); return this; }, options: { expand: false, expandPoint: null, tabsPosition: "top", tabsType: "default", clsTabs: "", clsTabsList: "", clsTabsListItem: "", clsTabsListItemActive: "", onTab: Metro.noop, onBeforeTab: Metro.noop_true, onTabsCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element; var tab = element.find(".active").length > 0 ? $(element.find(".active")[0]) : undefined; this._createStructure(); this._createEvents(); this._open(tab); }, _createStructure: function(){ var element = this.element, o = this.options; var parent = element.parent(); var right_parent = parent.hasClass("tabs"); var container = right_parent ? parent : $("<div>").addClass("tabs tabs-wrapper"); var expandTitle, hamburger; if (!Utils.isValue(element.attr("id"))) { element.attr("id", Utils.elementId("tabs")); } container.addClass(o.tabsPosition.replace(["-", "_", "+"], " ")); element.addClass("tabs-list"); if (o.tabsType !== "default") { element.addClass("tabs-"+o.tabsType); } if (!right_parent) { container.insertBefore(element); element.appendTo(container); } element.data('expanded', false); expandTitle = $("<div>").addClass("expand-title"); container.prepend(expandTitle); hamburger = container.find(".hamburger"); if (hamburger.length === 0) { hamburger = $("<button>").attr("type", "button").addClass("hamburger menu-down").appendTo(container); for(var i = 0; i < 3; i++) { $("<span>").addClass("line").appendTo(hamburger); } if (Colors.isLight(Utils.computedRgbToHex(Utils.getStyleOne(container, "background-color"))) === true) { hamburger.addClass("dark"); } } container.addClass(o.clsTabs); element.addClass(o.clsTabsList); element.children("li").addClass(o.clsTabsListItem); if (o.expand === true && !o.tabsPosition.contains("vertical")) { container.addClass("tabs-expand"); } else { if (Utils.isValue(o.expandPoint) && Utils.mediaExist(o.expandPoint) && !o.tabsPosition.contains("vertical")) { container.addClass("tabs-expand"); } } if (o.tabsPosition.contains("vertical")) { container.addClass("tabs-expand"); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var container = element.parent(); $(window).on(Metro.events.resize+"-"+element.attr("id"), function(){ if (o.tabsPosition.contains("vertical")) { return ; } if (o.expand === true && !o.tabsPosition.contains("vertical")) { container.addClass("tabs-expand"); } else { if (Utils.isValue(o.expandPoint) && Utils.mediaExist(o.expandPoint) && !o.tabsPosition.contains("vertical")) { if (!container.hasClass("tabs-expand")) container.addClass("tabs-expand"); } else { if (container.hasClass("tabs-expand")) container.removeClass("tabs-expand"); } } }); container.on(Metro.events.click, ".hamburger, .expand-title", function(){ if (element.data('expanded') === false) { element.addClass("expand"); element.data('expanded', true); container.find(".hamburger").addClass("active"); } else { element.removeClass("expand"); element.data('expanded', false); container.find(".hamburger").removeClass("active"); } }); element.on(Metro.events.click, "a", function(e){ var link = $(this); var href = link.attr("href").trim(); var tab = link.parent("li"); if (tab.hasClass("active")) { e.preventDefault(); } if (element.data('expanded') === true) { element.removeClass("expand"); element.data('expanded', false); container.find(".hamburger").removeClass("active"); } if (Utils.exec(o.onBeforeTab, [tab, element], tab[0]) !== true) { return false; } if (Utils.isValue(href) && href[0] === "#") { that._open(tab); e.preventDefault(); } }); }, _collectTargets: function(){ var that = this, element = this.element; var tabs = element.find("li"); this._targets = []; $.each(tabs, function(){ var target = $(this).find("a").attr("href").trim(); if (target.length > 1 && target[0] === "#") { that._targets.push(target); } }); }, _open: function(tab){ var element = this.element, o = this.options; var tabs = element.find("li"); var expandTitle = element.siblings(".expand-title"); if (tabs.length === 0) { return; } this._collectTargets(); if (tab === undefined) { tab = $(tabs[0]); } var target = tab.find("a").attr("href"); if (target === undefined) { return; } tabs.removeClass("active"); if (tab.parent().hasClass("d-menu")) { tab.parent().parent().addClass("active"); } else { tab.addClass("active"); } $.each(this._targets, function(){ var t = $(this); if (t.length > 0) t.hide(); }); if (target !== "#" && target[0] === "#") { $(target).show(); } expandTitle.html(tab.find("a").html()); tab.addClass(o.clsTabsListItemActive); Utils.exec(o.onTab, [tab, element], tab[0]); }, next: function(){ var element = this.element; var next, active_tab = element.find("li.active"); next = active_tab.next("li"); if (next.length > 0) { this._open(next); } }, prev: function(){ var element = this.element; var next, active_tab = element.find("li.active"); next = active_tab.prev("li"); if (next.length > 0) { this._open(next); } }, open: function(tab){ var element = this.element; var tabs = element.find("li"); if (!Utils.isValue(tab)) { tab = 1; } if (Utils.isInt(tab)) { if (Utils.isValue(tabs[tab-1])) this._open($(tabs[tab-1])); } else { this._open($(tab)); } }, changeAttribute: function(attributeName){ } }; Metro.plugin('tabs', Tabs); // Source: js/plugins/tag-input.js var TagInput = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.values = []; this._setOptionsFromDOM(); this._create(); return this; }, options: { randomColor: false, maxTags: 0, tagSeparator: ",", tagTrigger: "13,188", clsTag: "", clsTagTitle: "", clsTagRemover: "", onBeforeTagAdd: Metro.noop_true, onTagAdd: Metro.noop, onBeforeTagRemove: Metro.noop_true, onTagRemove: Metro.noop, onTag: Metro.noop, onTagInputCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var element = this.element, o = this.options; this._createStructure(); this._createEvents(); Utils.exec(o.onTagInputCreate, [element], element[0]); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var container, input; var values = element.val().trim(); container = $("<div>").addClass("tag-input " + element[0].className).insertBefore(element); element.appendTo(container); element[0].className = ""; element.addClass("original-input"); input = $("<input type='text'>").addClass("input-wrapper").attr("size", 1); input.appendTo(container); if (Utils.isValue(values)) { $.each(Utils.strToArray(values, o.tagSeparator), function(){ that._addTag(this); }) } if (element.is(":disabled")) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var container = element.closest(".tag-input"); var input = container.find(".input-wrapper"); input.on(Metro.events.focus, function(){ container.addClass("focused"); }); input.on(Metro.events.blur, function(){ container.removeClass("focused"); }); input.on(Metro.events.inputchange, function(){ input.attr("size", Math.ceil(input.val().length / 2) + 2); }); input.on(Metro.events.keyup, function(e){ var val = input.val().trim(); if (val === "") {return ;} if (Utils.strToArray(o.tagTrigger, ",", "integer").indexOf(e.keyCode) === -1) { return ; } input.val(""); that._addTag(val.replace(",", "")); input.attr("size", 1); if (e.keyCode === Metro.keyCode.ENTER) { e.preventDefault(); } }); container.on(Metro.events.click, ".tag .remover", function(){ var tag = $(this).closest(".tag"); that._delTag(tag); }); container.on(Metro.events.click, function(){ input.focus(); }); }, _addTag: function(val){ var element = this.element, o = this.options; var container = element.closest(".tag-input"); var input = container.find(".input-wrapper"); var tag, title, remover; if (o.maxTags > 0 && this.values.length === o.maxTags) { return ; } if (!Utils.exec(o.onBeforeTagAdd, [val, this.values], element[0])) { return ; } tag = $("<span>").addClass("tag").addClass(o.clsTag).insertBefore(input); tag.data("value", val); title = $("<span>").addClass("title").addClass(o.clsTagTitle).html(val); remover = $("<span>").addClass("remover").addClass(o.clsTagRemover).html("&times;"); title.appendTo(tag); remover.appendTo(tag); if (o.randomColor === true) { var colors = Colors.colors(Colors.PALETTES.ALL), bg, fg, bg_r; bg = colors[Utils.random(0, colors.length - 1)]; bg_r = Colors.darken(bg, 15); fg = Colors.isDark(bg) ? "#ffffff" : "#000000"; tag.css({ backgroundColor: bg, color: fg }); remover.css({ backgroundColor: bg_r, color: fg }); } this.values.push(val); element.val(this.values.join(o.tagSeparator)); Utils.exec(o.onTagAdd, [tag, val, this.values], element[0]); Utils.exec(o.onTag, [tag, val, this.values], element[0]); }, _delTag: function(tag) { var element = this.element, o = this.options; var val = tag.data("value"); if (!Utils.exec(o.onBeforeTagRemove, [tag, val, this.values], element[0])) { return ; } Utils.arrayDelete(this.values, val); element.val(this.values.join(o.tagSeparator)); Utils.exec(o.onTagRemove, [tag, val, this.values], element[0]); Utils.exec(o.onTag, [tag, val, this.values], element[0]); tag.remove(); }, tags: function(){ return this.values; }, val: function(v){ var that = this, o = this.options; if (!Utils.isValue(v)) { return this.tags(); } this.values = []; if (Utils.isValue(v)) { $.each(Utils.strToArray(v, o.tagSeparator), function(){ that._addTag(this); }) } }, clear: function(){ var element = this.element; var container = element.closest(".tag-input"); this.values = []; element.val(""); container.find(".tag").remove(); }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ var that = this, element = this.element, o = this.options; var changeValue = function(){ var val = element.attr("value").trim(); that.clear(); if (!Utils.isValue(val)) { return ; } that.val(Utils.strToArray(val, ",")); }; switch (attributeName) { case "value": changeValue(); break; case "disabled": this.toggleState(); break; } }, destroy: function(){ var element = this.element; var container = element.closest(".tag-input"); var input = container.find(".input-wrapper"); input.off(Metro.events.focus); input.off(Metro.events.blur); input.off(Metro.events.keydown); container.off(Metro.events.click, ".tag .remover"); container.off(Metro.events.click); element.insertBefore(container); container.remove(); } }; Metro.plugin('taginput', TagInput); // Source: js/plugins/textarea.js var Textarea = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onTextareaCreate, [this.element]); return this; }, options: { charsCounter: null, charsCounterTemplate: "$1", defaultValue: "", prepend: "", append: "", copyInlineStyles: true, clearButton: true, clearButtonIcon: "<span class='default-icon-cross'></span>", autoSize: true, clsPrepend: "", clsAppend: "", clsComponent: "", clsTextarea: "", onChange: Metro.noop, onTextareaCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ this._createStructure(); this._createEvents(); }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var prev = element.prev(); var parent = element.parent(); var container = $("<div>").addClass("textarea " + element[0].className); var clearButton; var timer = null; if (prev.length === 0) { parent.prepend(container); } else { container.insertAfter(prev); } if (o.clearButton !== false) { clearButton = $("<button>").addClass("button input-clear-button").attr("tabindex", -1).attr("type", "button").html(o.clearButtonIcon); clearButton.appendTo(container); } element.appendTo(container); if (o.autoSize) { container.addClass("autosize"); timer = setTimeout(function(){ timer = null; that.resize(); }, 0); } if (element.attr('dir') === 'rtl' ) { container.addClass("rtl").attr("dir", "rtl"); } if (o.prepend !== "") { var prepend = $("<div>").html(o.prepend); prepend.addClass("prepend").addClass(o.clsPrepend).appendTo(container); } if (o.append !== "") { var append = $("<div>").html(o.append); append.addClass("append").addClass(o.clsAppend).appendTo(container); clearButton.css({ right: append.outerWidth() + 4 }); } element[0].className = ''; if (o.copyInlineStyles === true) { for (var i = 0, l = element[0].style.length; i < l; i++) { container.css(element[0].style[i], element.css(element[0].style[i])); } } if (Utils.isValue(o.defaultValue) && element.val().trim() === "") { element.val(o.defaultValue); } container.addClass(o.clsComponent); element.addClass(o.clsTextarea); if (element.is(':disabled')) { this.disable(); } else { this.enable(); } }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var textarea = element.closest(".textarea"); var chars_counter = $(o.charsCounter); textarea.on(Metro.events.click, ".input-clear-button", function(){ element.val(Utils.isValue(o.defaultValue) ? o.defaultValue : "").trigger('change').trigger('keyup').focus(); }); if (o.autoSize) { element.on(Metro.events.keyup, $.proxy(this.resize, that)); element.on(Metro.events.keydown, $.proxy(this.resize, that)); element.on(Metro.events.change, $.proxy(this.resize, that)); element.on(Metro.events.focus, $.proxy(this.resize, that)); element.on(Metro.events.cut, $.proxy(this.resize, that)); element.on(Metro.events.paste, $.proxy(this.resize, that)); element.on(Metro.events.drop, $.proxy(this.resize, that)); } element.on(Metro.events.blur, function(){textarea.removeClass("focused");}); element.on(Metro.events.focus, function(){textarea.addClass("focused");}); element.on(Metro.events.keyup, function(){ if (Utils.isValue(o.charsCounter) && chars_counter.length > 0) { if (chars_counter[0].tagName === "INPUT") { chars_counter.val(that.length()); } else { chars_counter.html(o.charsCounterTemplate.replace("$1", that.length())); } } Utils.exec(o.onChange, [element.val(), that.length()], element[0]); }) }, resize: function(){ var element = this.element; element[0].style.cssText = 'height:auto;'; element[0].style.cssText = 'height:' + element[0].scrollHeight + 'px'; }, clear: function(){ this.element.val("").trigger('change').trigger('keyup').focus(); }, toDefault: function(){ this.element.val(Utils.isValue(this.options.defaultValue) ? this.options.defaultValue : "").trigger('change').trigger('keyup').focus(); }, length: function(){ var characters = this.elem.value.split(''); return characters.length; }, disable: function(){ this.element.data("disabled", true); this.element.parent().addClass("disabled"); }, enable: function(){ this.element.data("disabled", false); this.element.parent().removeClass("disabled"); }, toggleState: function(){ if (this.elem.disabled) { this.disable(); } else { this.enable(); } }, changeAttribute: function(attributeName){ switch (attributeName) { case 'disabled': this.toggleState(); break; } } }; Metro.plugin('textarea', Textarea); // Source: js/plugins/tiles.js var Tile = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.effectInterval = false; this.images = []; this.slides = []; this.currentSlide = -1; this.unload = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { size: "medium", cover: "", effect: "", effectInterval: 3000, effectDuration: 500, target: null, canTransform: true, onClick: Metro.noop, onTileCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createTile(); this._createEvents(); Utils.exec(o.onTileCreate, [element]); }, _createTile: function(){ function switchImage(el, img_src){ setTimeout(function(){ el.fadeOut(500, function(){ el.css("background-image", "url(" + img_src + ")"); el.fadeIn(); }); }, Utils.random(0,1000)); } var that = this, element = this.element, o = this.options; var slides = element.find(".slide"); var slides2 = element.find(".slide-front, .slide-back"); element.addClass("tile-" + o.size); if (o.effect.indexOf("hover-") > -1) { element.addClass("effect-" + o.effect); $.each(slides2, function(){ var slide = $(this); if (slide.data("cover") !== undefined) { that._setCover(slide, slide.data("cover")); } }) } if (o.effect.indexOf("animate-") > -1 && slides.length > 1) { $.each(slides, function(i){ var slide = $(this); that.slides.push(this); if (slide.data("cover") !== undefined) { that._setCover(slide, slide.data("cover")); } if (i > 0) { if (["animate-slide-up", "animate-slide-down"].indexOf(o.effect) > -1) slide.css("top", "100%"); if (["animate-slide-left", "animate-slide-right"].indexOf(o.effect) > -1) slide.css("left", "100%"); if (["animate-fade"].indexOf(o.effect) > -1) slide.css("opacity", 0); } }); this.currentSlide = 0; this._runEffects(); } if (o.cover !== "") { this._setCover(element, o.cover); } if (o.effect === "image-set") { element.addClass("image-set"); $.each(element.children("img"), function(){ var img = $(this); var src = this.src; var div = $("<div>").addClass("img"); if (img.hasClass("icon")) { return ; } that.images.push(this); div.css("background-image", "url("+src+")"); element.prepend(div); img.remove(); }); setInterval(function(){ var temp = that.images.slice(); for(var i = 0; i < element.find(".img").length; i++) { var rnd_index = Utils.random(0, temp.length - 1); var div = $(element.find(".img").get(i)); switchImage(div, temp[rnd_index].src); temp.splice(rnd_index, 1); } }, 3000); } }, _runEffects: function(){ var that = this, o = this.options; if (this.effectInterval === false) this.effectInterval = setInterval(function(){ var current, next; current = $(that.slides[that.currentSlide]); that.currentSlide++; if (that.currentSlide === that.slides.length) { that.currentSlide = 0; } next = that.slides[that.currentSlide]; if (o.effect === "animate-slide-up") Animation.slideUp($(current), $(next), o.effectDuration); if (o.effect === "animate-slide-down") Animation.slideDown($(current), $(next), o.effectDuration); if (o.effect === "animate-slide-left") Animation.slideLeft($(current), $(next), o.effectDuration); if (o.effect === "animate-slide-right") Animation.slideRight($(current), $(next), o.effectDuration); if (o.effect === "animate-fade") Animation.fade($(current), $(next), o.effectDuration); }, o.effectInterval); }, _stopEffects: function(){ clearInterval(this.effectInterval); this.effectInterval = false; }, _setCover: function(to, src){ to.css({ backgroundImage: "url("+src+")", backgroundSize: "cover", backgroundRepeat: "no-repeat" }); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.start, function(e){ var tile = $(this); var dim = {w: element.width(), h: element.height()}; var X = Utils.pageXY(e).x - tile.offset().left, Y = Utils.pageXY(e).y - tile.offset().top; var side; if (Utils.isRightMouse(e) === false) { if (X < dim.w * 1 / 3 && (Y < dim.h * 1 / 2 || Y > dim.h * 1 / 2)) { side = 'left'; } else if (X > dim.w * 2 / 3 && (Y < dim.h * 1 / 2 || Y > dim.h * 1 / 2)) { side = 'right'; } else if (X > dim.w * 1 / 3 && X < dim.w * 2 / 3 && Y > dim.h / 2) { side = 'bottom'; } else { side = "top"; } if (o.canTransform === true) tile.addClass("transform-" + side); if (o.target !== null) { setTimeout(function(){ document.location.href = o.target; }, 100); } Utils.exec(o.onClick, [tile]); } }); element.on([Metro.events.stop, Metro.events.leave].join(" "), function(e){ $(this) .removeClass("transform-left") .removeClass("transform-right") .removeClass("transform-top") .removeClass("transform-bottom"); }); $(window).on(Metro.events.blur, function(){ that._stopEffects(); }); $(window).on(Metro.events.focus, function(){ that._runEffects(); }); }, changeAttribute: function(attributeName){ } }; Metro.plugin('tile', Tile); // Source: js/plugins/timepicker.js var TimePicker = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.picker = null; this.isOpen = false; this.value = []; this.locale = Metro.locales[METRO_LOCALE]['calendar']; this._setOptionsFromDOM(); this._create(); return this; }, options: { hoursStep: 1, minutesStep: 1, secondsStep: 1, value: null, locale: METRO_LOCALE, distance: 3, hours: true, minutes: true, seconds: true, showLabels: true, scrollSpeed: 5, copyInlineStyles: true, clsPicker: "", clsPart: "", clsHours: "", clsMinutes: "", clsSeconds: "", okButtonIcon: "<span class='default-icon-check'></span>", cancelButtonIcon: "<span class='default-icon-cross'></span>", onSet: Metro.noop, onOpen: Metro.noop, onClose: Metro.noop, onScroll: Metro.noop, onTimePickerCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var picker = this.picker; var i; if (o.distance < 1) { o.distance = 1; } if (o.hoursStep < 1) {o.hoursStep = 1;} if (o.hoursStep > 23) {o.hoursStep = 23;} if (o.minutesStep < 1) {o.minutesStep = 1;} if (o.minutesStep > 59) {o.minutesStep = 59;} if (o.secondsStep < 1) {o.secondsStep = 1;} if (o.secondsStep > 59) {o.secondsStep = 59;} if (element.val() === "" && (!Utils.isValue(o.value))) { o.value = (new Date()).format("%H:%M:%S"); } this.value = Utils.strToArray(element.val() !== "" ? element.val() : String(o.value), ":"); for(i = 0; i < 3; i++) { if (this.value[i] === undefined || this.value[i] === null) { this.value[i] = 0; } else { this.value[i] = parseInt(this.value[i]); } } this._normalizeValue(); if (Metro.locales[o.locale] === undefined) { o.locale = METRO_LOCALE; } this.locale = Metro.locales[o.locale]['calendar']; this._createStructure(); this._createEvents(); this._set(); Utils.exec(o.onTimePickerCreate, [element, picker]); }, _normalizeValue: function(){ var o = this.options; if (o.hoursStep > 1) { this.value[0] = Utils.nearest(this.value[0], o.hoursStep, true); } if (o.minutesStep > 1) { this.value[1] = Utils.nearest(this.value[1], o.minutesStep, true); } if (o.minutesStep > 1) { this.value[2] = Utils.nearest(this.value[2], o.secondsStep, true); } }, _createStructure: function(){ var that = this, element = this.element, o = this.options; var picker, hours, minutes, seconds, ampm, select, i; var timeWrapper, selectWrapper, selectBlock, actionBlock; var prev = element.prev(); var parent = element.parent(); var id = Utils.elementId("time-picker"); picker = $("<div>").attr("id", id).addClass("wheel-picker time-picker " + element[0].className).addClass(o.clsPicker); if (prev.length === 0) { parent.prepend(picker); } else { picker.insertAfter(prev); } element.attr("readonly", true).appendTo(picker); timeWrapper = $("<div>").addClass("time-wrapper").appendTo(picker); if (o.hours === true) { hours = $("<div>").attr("data-title", this.locale['time']['hours']).addClass("hours").addClass(o.clsPart).addClass(o.clsHours).appendTo(timeWrapper); } if (o.minutes === true) { minutes = $("<div>").attr("data-title", this.locale['time']['minutes']).addClass("minutes").addClass(o.clsPart).addClass(o.clsMinutes).appendTo(timeWrapper); } if (o.seconds === true) { seconds = $("<div>").attr("data-title", this.locale['time']['seconds']).addClass("seconds").addClass(o.clsPart).addClass(o.clsSeconds).appendTo(timeWrapper); } selectWrapper = $("<div>").addClass("select-wrapper").appendTo(picker); selectBlock = $("<div>").addClass("select-block").appendTo(selectWrapper); if (o.hours === true) { hours = $("<ul>").addClass("sel-hours").appendTo(selectBlock); for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(hours); for (i = 0; i < 24; i = i + o.hoursStep) { $("<li>").addClass("js-hours-"+i).html(i < 10 ? "0"+i : i).data("value", i).appendTo(hours); } for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(hours); } if (o.minutes === true) { minutes = $("<ul>").addClass("sel-minutes").appendTo(selectBlock); for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(minutes); for (i = 0; i < 60; i = i + o.minutesStep) { $("<li>").addClass("js-minutes-"+i).html(i < 10 ? "0"+i : i).data("value", i).appendTo(minutes); } for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(minutes); } if (o.seconds === true) { seconds = $("<ul>").addClass("sel-seconds").appendTo(selectBlock); for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(seconds); for (i = 0; i < 60; i = i + o.secondsStep) { $("<li>").addClass("js-seconds-"+i).html(i < 10 ? "0"+i : i).data("value", i).appendTo(seconds); } for (i = 0; i < o.distance; i++) $("<li>").html("&nbsp;").data("value", -1).appendTo(seconds); } selectBlock.height((o.distance * 2 + 1) * 40); actionBlock = $("<div>").addClass("action-block").appendTo(selectWrapper); $("<button>").attr("type", "button").addClass("button action-ok").html(o.okButtonIcon).appendTo(actionBlock); $("<button>").attr("type", "button").addClass("button action-cancel").html(o.cancelButtonIcon).appendTo(actionBlock); element[0].className = ''; if (o.copyInlineStyles === true) { for (i = 0; i < element[0].style.length; i++) { picker.css(element[0].style[i], element.css(element[0].style[i])); } } if (o.showLabels === true) { picker.addClass("show-labels"); } this.picker = picker; }, _createEvents: function(){ var that = this, element = this.element, o = this.options; var picker = this.picker; picker.on(Metro.events.start, ".select-block ul", function(e){ if (e.changedTouches) { return ; } var target = this; var pageY = Utils.pageXY(e).y; $(document).on(Metro.events.move + "-picker", function(e){ target.scrollTop -= o.scrollSpeed * (pageY > Utils.pageXY(e).y ? -1 : 1); pageY = Utils.pageXY(e).y; }); $(document).on(Metro.events.stop + "-picker", function(e){ $(document).off(Metro.events.move + "-picker"); $(document).off(Metro.events.stop + "-picker"); }); }); picker.on(Metro.events.click, function(e){ if (that.isOpen === false) that.open(); e.stopPropagation(); }); picker.on(Metro.events.click, ".action-ok", function(e){ var h, m, s, a; var sh = picker.find(".sel-hours li.active"), sm = picker.find(".sel-minutes li.active"), ss = picker.find(".sel-seconds li.active"); h = sh.length === 0 ? 0 : sh.data("value"); m = sm.length === 0 ? 0 : sm.data("value"); s = ss.length === 0 ? 0 : ss.data("value"); that.value = [h, m, s]; that._normalizeValue(); that._set(); that.close(); e.stopPropagation(); }); picker.on(Metro.events.click, ".action-cancel", function(e){ that.close(); e.stopPropagation(); }); this._addScrollEvents(); }, _addScrollEvents: function(){ var picker = this.picker, o = this.options; var lists = ['hours', 'minutes', 'seconds']; $.each(lists, function(){ var list_name = this; var list = picker.find(".sel-" + list_name); if (list.length === 0) return ; list.on(Metro.events.scrollStart, function(){ list.find(".active").removeClass("active"); }); list.on(Metro.events.scrollStop, {latency: 50}, function(){ var target = Math.round((Math.ceil(list.scrollTop() + 40) / 40)) ; var target_element = list.find("li").eq(target + o.distance - 1); var scroll_to = target_element.position().top - (o.distance * 40) + list.scrollTop(); list.animate({ scrollTop: scroll_to }, 100, function(){ target_element.addClass("active"); Utils.exec(o.onScroll, [target_element, list, picker]); }); }); }); }, _removeScrollEvents: function(){ var picker = this.picker; var lists = ['hours', 'minutes', 'seconds']; $.each(lists, function(){ picker.find(".sel-" + this).off("scrollstart scrollstop"); }); }, _set: function(){ var that = this, element = this.element, o = this.options; var picker = this.picker; var h = "00", m = "00", s = "00"; if (o.hours === true) { h = parseInt(this.value[0]); if (h < 10) { h = "0"+h; } picker.find(".hours").html(h); } if (o.minutes === true) { m = parseInt(this.value[1]); if (m < 10) { m = "0"+m; } picker.find(".minutes").html(m); } if (o.seconds === true) { s = parseInt(this.value[2]); if (s < 10) { s = "0"+s; } picker.find(".seconds").html(s); } element.val([h, m, s].join(":")).trigger("change"); Utils.exec(o.onSet, [this.value, element.val(), element, picker]); }, open: function(){ var that = this, element = this.element, o = this.options; var picker = this.picker; var h, m, s; var h_list, m_list, s_list; var items = picker.find("li"); var select_wrapper = picker.find(".select-wrapper"); var select_wrapper_in_viewport, select_wrapper_rect; var h_item, m_item, s_item; select_wrapper.parent().removeClass("for-top for-bottom"); select_wrapper.show(); items.removeClass("active"); select_wrapper_in_viewport = Utils.inViewport(select_wrapper); select_wrapper_rect = Utils.rect(select_wrapper); if (!select_wrapper_in_viewport && select_wrapper_rect.top > 0) { select_wrapper.parent().addClass("for-bottom"); } if (!select_wrapper_in_viewport && select_wrapper_rect.top < 0) { select_wrapper.parent().addClass("for-top"); } var animateList = function(list, item){ list.scrollTop(0).animate({ scrollTop: item.position().top - (o.distance * 40) + list.scrollTop() }, 100); }; if (o.hours === true) { h = parseInt(this.value[0]); h_list = picker.find(".sel-hours"); h_item = h_list.find("li.js-hours-" + h).addClass("active"); animateList(h_list, h_item); } if (o.minutes === true) { m = parseInt(this.value[1]); m_list = picker.find(".sel-minutes"); m_item = m_list.find("li.js-minutes-" + m).addClass("active"); animateList(m_list, m_item); } if (o.seconds === true) { s = parseInt(this.value[2]); s_list = picker.find(".sel-seconds"); s_item = s_list.find("li.js-seconds-" + s).addClass("active"); animateList(s_list, s_item); } this.isOpen = true; Utils.exec(o.onOpen, [this.value, element, picker]); }, close: function(){ var picker = this.picker, o = this.options, element = this.element; picker.find(".select-wrapper").hide(); this.isOpen = false; Utils.exec(o.onClose, [this.value, element, picker]); }, _convert: function(t){ var result; if (Array.isArray(t)) { result = t; } else if (typeof t.getMonth === 'function') { result = [t.getHours(), t.getMinutes(), t.getSeconds()]; } else if (Utils.isObject(t)) { result = [t.h, t.m, t.s]; } else { result = Utils.strToArray(t, ":"); } return result; }, val: function(t){ if (t === undefined) { return this.element.val(); } this.value = this._convert(t); this._normalizeValue(); this._set(); }, time: function(t){ if (t === undefined) { return { h: this.value[0], m: this.value[1], s: this.value[2] } } this.value = this._convert(t); this._normalizeValue(); this._set(); }, date: function(t){ if (t === undefined || typeof t.getMonth !== 'function') { var ret = new Date(); ret.setHours(this.value[0]); ret.setMinutes(this.value[1]); ret.setSeconds(this.value[2]); ret.setMilliseconds(0); return ret; } this.value = this._convert(t); this._normalizeValue(); this._set(); }, changeAttribute: function(attributeName){ var that = this, element = this.element; var changeValueAttribute = function(){ that.val(element.attr("data-value")); }; switch (attributeName) { case "data-value": changeValueAttribute(); break; } } }; Metro.plugin('timepicker', TimePicker); $(document).on(Metro.events.click, function(e){ $.each($(".time-picker"), function(){ $(this).find("input").data("timepicker").close(); }); }); // Source: js/plugins/toast.js var Toast = { options: { callback: Metro.noop, timeout: METRO_TIMEOUT, distance: 20, showTop: false, clsToast: "" }, create: function(message, callback, timeout, cls, options){ var o = options || Toast.options; var toast = $("<div>").addClass("toast").html(message).appendTo($("body")).hide(); var width = toast.outerWidth(); var timer = null; timeout = timeout || o.timeout; callback = callback || o.callback; cls = cls || o.clsToast; if (o.showTop === true) { toast.addClass("show-top").css({ top: o.distance }); } else { toast.css({ bottom: o.distance }) } toast.css({ 'left': '50%', 'margin-left': -(width / 2) }).addClass(o.clsToast).addClass(cls).fadeIn(METRO_ANIMATION_DURATION); timer = setTimeout(function(){ timer = null; toast.fadeOut(METRO_ANIMATION_DURATION, function(){ toast.remove(); Utils.callback(callback); }); }, timeout); } }; Metro['toast'] = Toast; // Source: js/plugins/touch.js var TouchConst = { LEFT : "left", RIGHT : "right", UP : "up", DOWN : "down", IN : "in", OUT : "out", NONE : "none", AUTO : "auto", SWIPE : "swipe", PINCH : "pinch", TAP : "tap", DOUBLE_TAP : "doubletap", LONG_TAP : "longtap", HOLD : "hold", HORIZONTAL : "horizontal", VERTICAL : "vertical", ALL_FINGERS : "all", DOUBLE_TAP_THRESHOLD : 10, PHASE_START : "start", PHASE_MOVE : "move", PHASE_END : "end", PHASE_CANCEL : "cancel", SUPPORTS_TOUCH : 'ontouchstart' in window, SUPPORTS_POINTER_IE10 : window.navigator.msPointerEnabled && !window.navigator.pointerEnabled && !('ontouchstart' in window), SUPPORTS_POINTER : (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) && !('ontouchstart' in window), IN_TOUCH: "intouch" }; var Touch = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.useTouchEvents = (TouchConst.SUPPORTS_TOUCH || TouchConst.SUPPORTS_POINTER || !this.options.fallbackToMouseEvents); this.START_EV = this.useTouchEvents ? (TouchConst.SUPPORTS_POINTER ? (TouchConst.SUPPORTS_POINTER_IE10 ? 'MSPointerDown' : 'pointerdown') : 'touchstart') : 'mousedown'; this.MOVE_EV = this.useTouchEvents ? (TouchConst.SUPPORTS_POINTER ? (TouchConst.SUPPORTS_POINTER_IE10 ? 'MSPointerMove' : 'pointermove') : 'touchmove') : 'mousemove'; this.END_EV = this.useTouchEvents ? (TouchConst.SUPPORTS_POINTER ? (TouchConst.SUPPORTS_POINTER_IE10 ? 'MSPointerUp' : 'pointerup') : 'touchend') : 'mouseup'; this.LEAVE_EV = this.useTouchEvents ? (TouchConst.SUPPORTS_POINTER ? 'mouseleave' : null) : 'mouseleave'; //we manually detect leave on touch devices, so null event here this.CANCEL_EV = (TouchConst.SUPPORTS_POINTER ? (TouchConst.SUPPORTS_POINTER_IE10 ? 'MSPointerCancel' : 'pointercancel') : 'touchcancel'); //touch properties this.distance = 0; this.direction = null; this.currentDirection = null; this.duration = 0; this.startTouchesDistance = 0; this.endTouchesDistance = 0; this.pinchZoom = 1; this.pinchDistance = 0; this.pinchDirection = 0; this.maximumsMap = null; //Current phase of th touch cycle this.phase = "start"; // the current number of fingers being used. this.fingerCount = 0; //track mouse points / delta this.fingerData = {}; //track times this.startTime = 0; this.endTime = 0; this.previousTouchEndTime = 0; this.fingerCountAtRelease = 0; this.doubleTapStartTime = 0; //Timeouts this.singleTapTimeout = null; this.holdTimeout = null; this._setOptionsFromDOM(); this._create(); return this; }, options: { fingers: 1, threshold: 75, cancelThreshold: null, pinchThreshold: 20, maxTimeThreshold: null, fingerReleaseThreshold: 250, longTapThreshold: 500, doubleTapThreshold: 200, triggerOnTouchEnd: true, triggerOnTouchLeave: false, allowPageScroll: "auto", fallbackToMouseEvents: true, excludedElements: ".no-swipe", preventDefaultEvents: true, onSwipe: Metro.noop, onSwipeLeft: Metro.noop, onSwipeRight: Metro.noop, onSwipeUp: Metro.noop, onSwipeDown: Metro.noop, onSwipeStatus: Metro.noop_true, // params: phase, direction, distance, duration, fingerCount, fingerData, currentDirection onPinchIn: Metro.noop, onPinchOut: Metro.noop, onPinchStatus: Metro.noop_true, onTap: Metro.noop, onDoubleTap: Metro.noop, onLongTap: Metro.noop, onHold: Metro.noop, onSwipeCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; if (o.allowPageScroll === undefined && (o.onSwipe !== Metro.noop || o.onSwipeStatus !== Metro.noop)) { o.allowPageScroll = TouchConst.NONE; } try { element.bind(this.START_EV, $.proxy(this.touchStart, that)); element.bind(this.CANCEL_EV, $.proxy(this.touchCancel, that)); } catch (e) { $.error('Events not supported ' + this.START_EV + ',' + this.CANCEL_EV + ' on Swipe'); } Utils.exec(o.onSwipeCreate, [element]); }, touchStart: function(e) { var element = this.element, options = this.options; //If we already in a touch event (a finger already in use) then ignore subsequent ones.. if (this.getTouchInProgress()) { return; } //Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe if ($(e.target).closest(options.excludedElements, element).length > 0) { return; } //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = e.originalEvent ? e.originalEvent : e; var ret, touches = event.touches, evt = touches ? touches[0] : event; this.phase = TouchConst.PHASE_START; //If we support touches, get the finger count if (touches) { // get the total number of fingers touching the screen this.fingerCount = touches.length; } //Else this is the desktop, so stop the browser from dragging content else if (options.preventDefaultEvents !== false) { e.preventDefault(); //call this on jq event so we are cross browser } //clear vars.. this.distance = 0; this.direction = null; this.currentDirection=null; this.pinchDirection = null; this.duration = 0; this.startTouchesDistance = 0; this.endTouchesDistance = 0; this.pinchZoom = 1; this.pinchDistance = 0; this.maximumsMap = this.createMaximumsData(); this.cancelMultiFingerRelease(); //Create the default finger data this.createFingerData(0, evt); // check the number of fingers is what we are looking for, or we are capturing pinches if (!touches || (this.fingerCount === options.fingers || options.fingers === TouchConst.ALL_FINGERS) || this.hasPinches()) { // get the coordinates of the touch this.startTime = this.getTimeStamp(); if (this.fingerCount === 2) { //Keep track of the initial pinch distance, so we can calculate the diff later //Store second finger data as start this.createFingerData(1, touches[1]); this.startTouchesDistance = this.endTouchesDistance = this.calculateTouchesDistance(this.fingerData[0].start, this.fingerData[1].start); } if (options.onSwipeStatus !== Metro.noop || options.onPinchStatus !== Metro.noop) { ret = this.triggerHandler(event, this.phase); } } else { //A touch with more or less than the fingers we are looking for, so cancel ret = false; } //If we have a return value from the users handler, then return and cancel if (ret === false) { this.phase = TouchConst.PHASE_CANCEL; this.triggerHandler(event, this.phase); return ret; } else { if (options.onHold !== Metro.noop) { this.holdTimeout = setTimeout($.proxy(function() { //Trigger the event element.trigger('hold', [event.target]); //Fire the callback if (options.onHold !== Metro.noop) { // TODO Remove this if ret = Utils.exec(options.onHold, [event, event.target], element[0]); } }, this), options.longTapThreshold); } this.setTouchInProgress(true); } return null; }, touchMove: function(e) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = e.originalEvent ? e.originalEvent : e; //If we are ending, cancelling, or within the threshold of 2 fingers being released, don't track anything.. if (this.phase === TouchConst.PHASE_END || this.phase === TouchConst.PHASE_CANCEL || this.inMultiFingerRelease()) return; var ret, touches = event.touches, evt = touches ? touches[0] : event; //Update the finger data var currentFinger = this.updateFingerData(evt); this.endTime = this.getTimeStamp(); if (touches) { this.fingerCount = touches.length; } if (this.options.onHold !== Metro.noop) { clearTimeout(this.holdTimeout); } this.phase = TouchConst.PHASE_MOVE; //If we have 2 fingers get Touches distance as well if (this.fingerCount === 2) { //Keep track of the initial pinch distance, so we can calculate the diff later //We do this here as well as the start event, in case they start with 1 finger, and the press 2 fingers if (this.startTouchesDistance === 0) { //Create second finger if this is the first time... this.createFingerData(1, touches[1]); this.startTouchesDistance = this.endTouchesDistance = this.calculateTouchesDistance(this.fingerData[0].start, this.fingerData[1].start); } else { //Else just update the second finger this.updateFingerData(touches[1]); this.endTouchesDistance = this.calculateTouchesDistance(this.fingerData[0].end, this.fingerData[1].end); this.pinchDirection = this.calculatePinchDirection(this.fingerData[0].end, this.fingerData[1].end); } this.pinchZoom = this.calculatePinchZoom(this.startTouchesDistance, this.endTouchesDistance); this.pinchDistance = Math.abs(this.startTouchesDistance - this.endTouchesDistance); } if ((this.fingerCount === this.options.fingers || this.options.fingers === TouchConst.ALL_FINGERS) || !touches || this.hasPinches()) { //The overall direction of the swipe. From start to now. this.direction = this.calculateDirection(currentFinger.start, currentFinger.end); //The immediate direction of the swipe, direction between the last movement and this one. this.currentDirection = this.calculateDirection(currentFinger.last, currentFinger.end); //Check if we need to prevent default event (page scroll / pinch zoom) or not this.validateDefaultEvent(e, this.currentDirection); //Distance and duration are all off the main finger this.distance = this.calculateDistance(currentFinger.start, currentFinger.end); this.duration = this.calculateDuration(); //Cache the maximum distance we made in this direction this.setMaxDistance(this.direction, this.distance); //Trigger status handler ret = this.triggerHandler(event, this.phase); //If we trigger end events when threshold are met, or trigger events when touch leaves element if (!this.options.triggerOnTouchEnd || this.options.triggerOnTouchLeave) { var inBounds = true; //If checking if we leave the element, run the bounds check (we can use touchleave as its not supported on webkit) if (this.options.triggerOnTouchLeave) { var bounds = this.getBounds(this); inBounds = this.isInBounds(currentFinger.end, bounds); } //Trigger end handles as we swipe if thresholds met or if we have left the element if the user has asked to check these.. if (!this.options.triggerOnTouchEnd && inBounds) { this.phase = this.getNextPhase(TouchConst.PHASE_MOVE); } //We end if out of bounds here, so set current phase to END, and check if its modified else if (this.options.triggerOnTouchLeave && !inBounds) { this.phase = this.getNextPhase(TouchConst.PHASE_END); } if (this.phase === TouchConst.PHASE_CANCEL || this.phase === TouchConst.PHASE_END) { this.triggerHandler(event, this.phase); } } } else { this.phase = TouchConst.PHASE_CANCEL; this.triggerHandler(event, this.phase); } if (ret === false) { this.phase = TouchConst.PHASE_CANCEL; this.triggerHandler(event, this.phase); } }, touchEnd: function(e) { //As we use Jquery bind for events, we need to target the original event object //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = e.originalEvent ? e.originalEvent : e, touches = event.touches; //If we are still in a touch with the device wait a fraction and see if the other finger comes up //if it does within the threshold, then we treat it as a multi release, not a single release and end the touch / swipe if (touches) { if (touches.length && !this.inMultiFingerRelease()) { this.startMultiFingerRelease(event); return true; } else if (touches.length && this.inMultiFingerRelease()) { return true; } } //If a previous finger has been released, check how long ago, if within the threshold, then assume it was a multifinger release. //This is used to allow 2 fingers to release fractionally after each other, whilst maintaining the event as containing 2 fingers, not 1 if (this.inMultiFingerRelease()) { this.fingerCount = this.fingerCountAtRelease; } //Set end of swipe this.endTime = this.getTimeStamp(); //Get duration incase move was never fired this.duration = this.calculateDuration(); //If we trigger handlers at end of swipe OR, we trigger during, but they didnt trigger and we are still in the move phase if (this.didSwipeBackToCancel() || !this.validateSwipeDistance()) { this.phase = TouchConst.PHASE_CANCEL; this.triggerHandler(event, this.phase); } else if (this.options.triggerOnTouchEnd || (this.options.triggerOnTouchEnd === false && this.phase === TouchConst.PHASE_MOVE)) { //call this on jq event so we are cross browser if (this.options.preventDefaultEvents !== false) { e.preventDefault(); } this.phase = TouchConst.PHASE_END; this.triggerHandler(event, this.phase); } //Special cases - A tap should always fire on touch end regardless, //So here we manually trigger the tap end handler by itself //We dont run trigger handler as it will re-trigger events that may have fired already else if (!this.options.triggerOnTouchEnd && this.hasTap()) { //Trigger the pinch events... this.phase = TouchConst.PHASE_END; this.triggerHandlerForGesture(event, this.phase, TouchConst.TAP); } else if (this.phase === TouchConst.PHASE_MOVE) { this.phase = TouchConst.PHASE_CANCEL; this.triggerHandler(event, this.phase); } this.setTouchInProgress(false); return null; }, touchCancel: function() { // reset the variables back to default values this.fingerCount = 0; this.endTime = 0; this.startTime = 0; this.startTouchesDistance = 0; this.endTouchesDistance = 0; this.pinchZoom = 1; //If we were in progress of tracking a possible multi touch end, then re set it. this.cancelMultiFingerRelease(); this.setTouchInProgress(false); }, touchLeave: function(e) { //If these events are being programmatically triggered, we don't have an original event object, so use the Jq one. var event = e.originalEvent ? e.originalEvent : e; //If we have the trigger on leave property set.... if (this.options.triggerOnTouchLeave) { this.phase = this.getNextPhase(TouchConst.PHASE_END); this.triggerHandler(event, this.phase); } }, getNextPhase: function(currentPhase) { var options = this.options; var nextPhase = currentPhase; // Ensure we have valid swipe (under time and over distance and check if we are out of bound...) var validTime = this.validateSwipeTime(); var validDistance = this.validateSwipeDistance(); var didCancel = this.didSwipeBackToCancel(); //If we have exceeded our time, then cancel if (!validTime || didCancel) { nextPhase = TouchConst.PHASE_CANCEL; } //Else if we are moving, and have reached distance then end else if (validDistance && currentPhase === TouchConst.PHASE_MOVE && (!options.triggerOnTouchEnd || options.triggerOnTouchLeave)) { nextPhase = TouchConst.PHASE_END; } //Else if we have ended by leaving and didn't reach distance, then cancel else if (!validDistance && currentPhase === TouchConst.PHASE_END && options.triggerOnTouchLeave) { nextPhase = TouchConst.PHASE_CANCEL; } return nextPhase; }, triggerHandler: function(event, phase) { var ret, touches = event.touches; // SWIPE GESTURES if (this.didSwipe() || this.hasSwipes()) { ret = this.triggerHandlerForGesture(event, phase, TouchConst.SWIPE); } // PINCH GESTURES (if the above didn't cancel) if ((this.didPinch() || this.hasPinches()) && ret !== false) { ret = this.triggerHandlerForGesture(event, phase, TouchConst.PINCH); } // CLICK / TAP (if the above didn't cancel) if (this.didDoubleTap() && ret !== false) { //Trigger the tap events... ret = this.triggerHandlerForGesture(event, phase, TouchConst.DOUBLE_TAP); } // CLICK / TAP (if the above didn't cancel) else if (this.didLongTap() && ret !== false) { //Trigger the tap events... ret = this.triggerHandlerForGesture(event, phase, TouchConst.LONG_TAP); } // CLICK / TAP (if the above didn't cancel) else if (this.didTap() && ret !== false) { //Trigger the tap event.. ret = this.triggerHandlerForGesture(event, phase, TouchConst.TAP); } // If we are cancelling the gesture, then manually trigger the reset handler if (phase === TouchConst.PHASE_CANCEL) { this.touchCancel(event); } // If we are ending the gesture, then manually trigger the reset handler IF all fingers are off if (phase === TouchConst.PHASE_END) { //If we support touch, then check that all fingers are off before we cancel if (touches) { if (!touches.length) { this.touchCancel(event); } } else { this.touchCancel(event); } } return ret; }, triggerHandlerForGesture: function(event, phase, gesture) { var ret, element = this.element, options = this.options; //SWIPES.... if (gesture === TouchConst.SWIPE) { //Trigger status every time.. element.trigger('swipeStatus', [phase, this.direction || null, this.distance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.currentDirection]); ret = Utils.exec(options.onSwipeStatus, [event, phase, this.direction || null, this.distance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.currentDirection], element[0]); if (ret === false) return false; if (phase === TouchConst.PHASE_END && this.validateSwipe()) { //Cancel any taps that were in progress... clearTimeout(this.singleTapTimeout); clearTimeout(this.holdTimeout); element.trigger('swipe', [this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection]); ret = Utils.exec(options.onSwipe, [event, this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection], element[0]); if (ret === false) return false; //trigger direction specific event handlers switch (this.direction) { case TouchConst.LEFT: element.trigger('swipeLeft', [this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection]); ret = Utils.exec(options.onSwipeLeft, [event, this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection], element[0]); break; case TouchConst.RIGHT: element.trigger('swipeRight', [this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection]); ret = Utils.exec(options.onSwipeRight, [event, this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection], element[0]); break; case TouchConst.UP: element.trigger('swipeUp', [this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection]); ret = Utils.exec(options.onSwipeUp, [event, this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection], element[0]); break; case TouchConst.DOWN: element.trigger('swipeDown', [this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection]); ret = Utils.exec(options.onSwipeDown, [event, this.direction, this.distance, this.duration, this.fingerCount, this.fingerData, this.currentDirection], element[0]); break; } } } //PINCHES.... if (gesture === TouchConst.PINCH) { element.trigger('pinchStatus', [phase, this.pinchDirection || null, this.pinchDistance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.pinchZoom]); ret = Utils.exec(options.onPinchStatus, [event, phase, this.pinchDirection || null, this.pinchDistance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.pinchZoom], element[0]); if (ret === false) return false; if (phase === TouchConst.PHASE_END && this.validatePinch()) { switch (this.pinchDirection) { case TouchConst.IN: element.trigger('pinchIn', [this.pinchDirection || null, this.pinchDistance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.pinchZoom]); ret = Utils.exec(options.onPinchIn, [event, this.pinchDirection || null, this.pinchDistance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.pinchZoom], element[0]); break; case TouchConst.OUT: element.trigger('pinchOut', [this.pinchDirection || null, this.pinchDistance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.pinchZoom]); ret = Utils.exec(options.onPinchOut, [event, this.pinchDirection || null, this.pinchDistance || 0, this.duration || 0, this.fingerCount, this.fingerData, this.pinchZoom], element[0]); break; } } } if (gesture === TouchConst.TAP) { if (phase === TouchConst.PHASE_CANCEL || phase === TouchConst.PHASE_END) { clearTimeout(this.singleTapTimeout); clearTimeout(this.holdTimeout); //If we are also looking for doubelTaps, wait incase this is one... if (this.hasDoubleTap() && !this.inDoubleTap()) { this.doubleTapStartTime = this.getTimeStamp(); //Now wait for the double tap timeout, and trigger this single tap //if its not cancelled by a double tap this.singleTapTimeout = setTimeout($.proxy(function() { this.doubleTapStartTime = null; element.trigger('tap', [event.target]); ret = Utils.exec(options.onTap, [event, event.target], element[0]); }, this), options.doubleTapThreshold); } else { this.doubleTapStartTime = null; element.trigger('tap', [event.target]); ret = Utils.exec(options.onTap, [event, event.target], element[0]); } } } else if (gesture === TouchConst.DOUBLE_TAP) { if (phase === TouchConst.PHASE_CANCEL || phase === TouchConst.PHASE_END) { clearTimeout(this.singleTapTimeout); clearTimeout(this.holdTimeout); this.doubleTapStartTime = null; element.trigger('doubletap', [event.target]); ret = Utils.exec(options.onDoubleTap, [event, event.target], element[0]); } } else if (gesture === TouchConst.LONG_TAP) { if (phase === TouchConst.PHASE_CANCEL || phase === TouchConst.PHASE_END) { clearTimeout(this.singleTapTimeout); this.doubleTapStartTime = null; element.trigger('longtap', [event.target]); ret = Utils.exec(options.onLongTap, [event, event.target], element[0]); } } return ret; }, validateSwipeDistance: function() { var valid = true; //If we made it past the min swipe distance.. if (this.options.threshold !== null) { valid = this.distance >= this.options.threshold; } return valid; }, didSwipeBackToCancel: function() { var options = this.options; var cancelled = false; if (options.cancelThreshold !== null && this.direction !== null) { cancelled = (this.getMaxDistance(this.direction) - this.distance) >= options.cancelThreshold; } return cancelled; }, validatePinchDistance: function() { if (this.options.pinchThreshold !== null) { return this.pinchDistance >= this.options.pinchThreshold; } return true; }, validateSwipeTime: function() { var result, options = this.options; if (options.maxTimeThreshold) { result = duration < options.maxTimeThreshold; } else { result = true; } return result; }, validateDefaultEvent: function(e, direction) { var options = this.options; //If the option is set, allways allow the event to bubble up (let user handle weirdness) if (options.preventDefaultEvents === false) { return; } if (options.allowPageScroll === TouchConst.NONE) { e.preventDefault(); } else { var auto = options.allowPageScroll === TouchConst.AUTO; switch (direction) { case TouchConst.LEFT: if ((options.onSwipeLeft !== Metro.noop && auto) || (!auto && options.allowPageScroll.toLowerCase() !== TouchConst.HORIZONTAL)) { e.preventDefault(); } break; case TouchConst.RIGHT: if ((options.onSwipeRight !== Metro.noop && auto) || (!auto && options.allowPageScroll.toLowerCase() !== TouchConst.HORIZONTAL)) { e.preventDefault(); } break; case TouchConst.UP: if ((options.onSwipeUp !== Metro.noop && auto) || (!auto && options.allowPageScroll.toLowerCase() !== TouchConst.VERTICAL)) { e.preventDefault(); } break; case TouchConst.DOWN: if ((options.onSwipeDown !== Metro.noop && auto) || (!auto && options.allowPageScroll.toLowerCase() !== TouchConst.VERTICAL)) { e.preventDefault(); } break; case TouchConst.NONE: break; } } }, validatePinch: function() { var hasCorrectFingerCount = this.validateFingers(); var hasEndPoint = this.validateEndPoint(); var hasCorrectDistance = this.validatePinchDistance(); return hasCorrectFingerCount && hasEndPoint && hasCorrectDistance; }, hasPinches: function() { //Enure we dont return 0 or null for false values return !!(this.options.onPinchStatus || this.options.onPinchIn || this.options.onPinchOut); }, didPinch: function() { //Enure we dont return 0 or null for false values return !!(this.validatePinch() && this.hasPinches()); }, validateSwipe: function() { //Check validity of swipe var hasValidTime = this.validateSwipeTime(); var hasValidDistance = this.validateSwipeDistance(); var hasCorrectFingerCount = this.validateFingers(); var hasEndPoint = this.validateEndPoint(); var didCancel = this.didSwipeBackToCancel(); // if the user swiped more than the minimum length, perform the appropriate action // hasValidDistance is null when no distance is set return !didCancel && hasEndPoint && hasCorrectFingerCount && hasValidDistance && hasValidTime; }, hasSwipes: function() { //Enure we dont return 0 or null for false values return !!( this.options.onSwipe !== Metro.noop || this.options.onSwipeStatus !== Metro.noop || this.options.onSwipeLeft !== Metro.noop || this.options.onSwipeRight !== Metro.noop || this.options.onSwipeUp !== Metro.noop || this.options.onSwipeDown !== Metro.noop ); }, didSwipe: function() { //Enure we dont return 0 or null for false values return !!(this.validateSwipe() && this.hasSwipes()); }, validateFingers: function() { //The number of fingers we want were matched, or on desktop we ignore return ((this.fingerCount === this.options.fingers || this.options.fingers === TouchConst.ALL_FINGERS) || !TouchConst.SUPPORTS_TOUCH); }, validateEndPoint: function() { //We have an end value for the finger return this.fingerData[0].end.x !== 0; }, hasTap: function() { //Enure we dont return 0 or null for false values return this.options.onTap !== Metro.noop; }, hasDoubleTap: function() { //Enure we dont return 0 or null for false values return this.options.onDoubleTap !== Metro.noop; }, hasLongTap: function() { //Enure we dont return 0 or null for false values return this.options.onLongTap !== Metro.noop; }, validateDoubleTap: function() { if (this.doubleTapStartTime == null) { return false; } var now = this.getTimeStamp(); return (this.hasDoubleTap() && ((now - this.doubleTapStartTime) <= this.options.doubleTapThreshold)); }, inDoubleTap: function() { return this.validateDoubleTap(); }, validateTap: function() { return ((this.fingerCount === 1 || !TouchConst.SUPPORTS_TOUCH) && (isNaN(this.distance) || this.distance < this.options.threshold)); }, validateLongTap: function() { var options = this.options; //slight threshold on moving finger return ((this.duration > options.longTapThreshold) && (this.distance < TouchConst.DOUBLE_TAP_THRESHOLD)); // check double_tab_threshold where from }, didTap: function() { //Enure we dont return 0 or null for false values return !!(this.validateTap() && this.hasTap()); }, didDoubleTap: function() { //Enure we dont return 0 or null for false values return !!(this.validateDoubleTap() && this.hasDoubleTap()); }, didLongTap: function() { //Enure we dont return 0 or null for false values return !!(this.validateLongTap() && this.hasLongTap()); }, startMultiFingerRelease: function(event) { this.previousTouchEndTime = this.getTimeStamp(); this.fingerCountAtRelease = event.touches.length + 1; }, cancelMultiFingerRelease: function() { this.previousTouchEndTime = 0; this.fingerCountAtRelease = 0; }, inMultiFingerRelease: function() { var withinThreshold = false; if (this.previousTouchEndTime) { var diff = this.getTimeStamp() - this.previousTouchEndTime; if (diff <= this.options.fingerReleaseThreshold) { withinThreshold = true; } } return withinThreshold; }, getTouchInProgress: function() { var element = this.element; //strict equality to ensure only true and false are returned return (element.data('intouch') === true); }, setTouchInProgress: function(val) { var element = this.element; //If destroy is called in an event handler, we have no el, and we have already cleaned up, so return. if(!element) { return; } //Add or remove event listeners depending on touch status if (val === true) { element.bind(this.MOVE_EV, $.proxy(this.touchMove, this)); element.bind(this.END_EV, $.proxy(this.touchEnd, this)); //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit if (this.LEAVE_EV) { element.bind(this.LEAVE_EV, $.proxy(this.touchLeave, this)); } } else { element.unbind(this.MOVE_EV, this.touchMove, false); element.unbind(this.END_EV, this.touchEnd, false); //we only have leave events on desktop, we manually calcuate leave on touch as its not supported in webkit if (this.LEAVE_EV) { element.unbind(this.LEAVE_EV, this.touchLeave, false); } } //strict equality to ensure only true and false can update the value element.data('intouch', val === true); }, createFingerData: function(id, evt) { var f = { start: { x: 0, y: 0 }, last: { x: 0, y: 0 }, end: { x: 0, y: 0 } }; f.start.x = f.last.x = f.end.x = evt.pageX || evt.clientX; f.start.y = f.last.y = f.end.y = evt.pageY || evt.clientY; this.fingerData[id] = f; return f; }, updateFingerData: function(evt) { var id = evt.identifier !== undefined ? evt.identifier : 0; var f = this.getFingerData(id); if (f === null) { f = this.createFingerData(id, evt); } f.last.x = f.end.x; f.last.y = f.end.y; f.end.x = evt.pageX || evt.clientX; f.end.y = evt.pageY || evt.clientY; return f; }, getFingerData: function(id) { return this.fingerData[id] || null; }, setMaxDistance: function(direction, distance) { if (direction === TouchConst.NONE) return; distance = Math.max(distance, this.getMaxDistance(direction)); this.maximumsMap[direction].distance = distance; }, getMaxDistance: function(direction) { return (this.maximumsMap[direction]) ? this.maximumsMap[direction].distance : undefined; }, createMaximumsData: function() { var maxData = {}; maxData[TouchConst.LEFT] = this.createMaximumVO(TouchConst.LEFT); maxData[TouchConst.RIGHT] = this.createMaximumVO(TouchConst.RIGHT); maxData[TouchConst.UP] = this.createMaximumVO(TouchConst.UP); maxData[TouchConst.DOWN] = this.createMaximumVO(TouchConst.DOWN); return maxData; }, createMaximumVO: function(dir) { return { direction: dir, distance: 0 } }, calculateDuration: function(){ return this.endTime - this.startTime; }, calculateTouchesDistance: function(startPoint, endPoint){ var diffX = Math.abs(startPoint.x - endPoint.x); var diffY = Math.abs(startPoint.y - endPoint.y); return Math.round(Math.sqrt(diffX * diffX + diffY * diffY)); }, calculatePinchZoom: function(startDistance, endDistance){ var percent = (endDistance / startDistance) * 100; // 1 ? 100 return percent.toFixed(2); }, calculatePinchDirection: function(){ if (this.pinchZoom < 1) { return TouchConst.OUT; } else { return TouchConst.IN; } }, calculateDistance: function(startPoint, endPoint){ return Math.round(Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2))); }, calculateAngle: function(startPoint, endPoint){ var x = startPoint.x - endPoint.x; var y = endPoint.y - startPoint.y; var r = Math.atan2(y, x); //radians var angle = Math.round(r * 180 / Math.PI); //degrees //ensure value is positive if (angle < 0) { angle = 360 - Math.abs(angle); } return angle; }, calculateDirection: function(startPoint, endPoint){ if( this.comparePoints(startPoint, endPoint) ) { return TouchConst.NONE; } var angle = this.calculateAngle(startPoint, endPoint); if ((angle <= 45) && (angle >= 0)) { return TouchConst.LEFT; } else if ((angle <= 360) && (angle >= 315)) { return TouchConst.LEFT; } else if ((angle >= 135) && (angle <= 225)) { return TouchConst.RIGHT; } else if ((angle > 45) && (angle < 135)) { return TouchConst.DOWN; } else { return TouchConst.UP; } }, getTimeStamp: function(){ return (new Date()).getTime(); }, getBounds: function (el) { el = $(el); var offset = el.offset(); return { left: offset.left, right: offset.left + el.outerWidth(), top: offset.top, bottom: offset.top + el.outerHeight() }; }, isInBounds: function(point, bounds){ return (point.x > bounds.left && point.x < bounds.right && point.y > bounds.top && point.y < bounds.bottom); }, comparePoints: function(pointA, pointB) { return (pointA.x === pointB.x && pointA.y === pointB.y); }, removeListeners: function() { var element = this.element; element.unbind(this.START_EV, this.touchStart, this); element.unbind(this.CANCEL_EV, this.touchCancel, this); element.unbind(this.MOVE_EV, this.touchMove, this); element.unbind(this.END_EV, this.touchEnd, this); //we only have leave events on desktop, we manually calculate leave on touch as its not supported in webkit if (this.LEAVE_EV) { element.unbind(this.LEAVE_EV, this.touchLeave, this); } this.setTouchInProgress(false); }, enable: function(){ this.disable(); this.element.bind(this.START_EV, this.touchStart); this.element.bind(this.CANCEL_EV, this.touchCancel); return this.element; }, disable: function(){ this.removeListeners(); return this.element; }, changeAttribute: function(attributeName){ }, destroy: function(){ this.removeListeners(); } }; Metro['touch'] = TouchConst; Metro.plugin('touch', Touch); // Source: js/plugins/treeview.js var Treeview = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, options: { effect: "slide", duration: 100, onNodeClick: Metro.noop, onNodeDblClick: Metro.noop, onNodeDelete: Metro.noop, onNodeInsert: Metro.noop, onNodeClean: Metro.noop, onCheckClick: Metro.noop, onRadioClick: Metro.noop, onExpandNode: Metro.noop, onCollapseNode: Metro.noop, onTreeviewCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createTree(); this._createEvents(); $.each(element.find("input"), function(){ if (!$(this).is(":checked")) return; that._recheck(this); }); Utils.exec(o.onTreeviewCreate, [element], element[0]); }, _createIcon: function(data){ var icon, src; src = Utils.isTag(data) ? $(data) : $("<img>").attr("src", data); icon = $("<span>").addClass("icon"); icon.html(src); return icon; }, _createCaption: function(data){ return $("<span>").addClass("caption").html(data); }, _createToggle: function(){ return $("<span>").addClass("node-toggle"); }, _createNode: function(data){ var node; node = $("<li>"); if (data.caption !== undefined) { node.prepend(this._createCaption(data.caption)); } if (data.icon !== undefined) { node.prepend(this._createIcon(data.icon)); } if (data.html !== undefined) { node.append(data.html); } return node; }, _createTree: function(){ var that = this, element = this.element, o = this.options; var nodes = element.find("li"); element.addClass("treeview"); $.each(nodes, function(){ var node = $(this); if (node.data("caption") !== undefined) { node.prepend(that._createCaption(node.data("caption"))); } if (node.data("icon") !== undefined) { node.prepend(that._createIcon(node.data("icon"))); } if (node.children("ul").length > 0) { node.append(that._createToggle()); if (node.data("collapsed") !== true) { node.addClass("expanded"); } else { node.children("ul").hide(); } } }); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".node-toggle", function(e){ var toggle = $(this); var node = toggle.parent(); that.toggleNode(node); e.preventDefault(); }); element.on(Metro.events.click, "li > .caption", function(e){ var node = $(this).parent(); that.current(node); Utils.exec(o.onNodeClick, [node, element], node[0]); e.preventDefault(); }); element.on(Metro.events.dblclick, "li > .caption", function(e){ var node = $(this).closest("li"); var toggle = node.children(".node-toggle"); var subtree = node.children("ul"); if (toggle.length > 0 || subtree.length > 0) { that.toggleNode(node); } Utils.exec(o.onNodeDblClick, [node, element], node[0]); e.preventDefault(); }); element.on(Metro.events.click, "input[type=radio]", function(e){ var check = $(this); var checked = check.is(":checked"); var node = check.closest("li"); that.current(node); Utils.exec(o.onRadioClick, [checked, check, node, element], this); }); element.on(Metro.events.click, "input[type=checkbox]", function(e){ var check = $(this); var checked = check.is(":checked"); var node = check.closest("li"); that._recheck(check); Utils.exec(o.onCheckClick, [checked, check, node, element], this); }); }, _recheck: function(check){ var element = this.element; var checked, node, checks; if (!Utils.isJQueryObject(check)) { check = $(check); } checked = check.is(":checked"); node = check.closest("li"); this.current(node); // down checks = check.closest("li").find("ul input[type=checkbox]"); checks.attr("data-indeterminate", false); checks.prop("checked", checked); checks = []; $.each(element.find(":checkbox"), function(){ checks.push(this); }); $.each(checks.reverse(), function(){ var ch = $(this); var children = ch.closest("li").children("ul").find(":checkbox").length; var children_checked = ch.closest("li").children("ul").find(":checkbox:checked").length; if (children > 0 && children_checked === 0) { ch.attr("data-indeterminate", false); ch.prop("checked", false); } if (children_checked === 0) { ch.attr("data-indeterminate", false); } else { if (children_checked > 0 && children > children_checked) { ch.attr("data-indeterminate", true); } else if (children === children_checked) { ch.attr("data-indeterminate", false); ch.prop("checked", true); } } }); }, current: function(node){ var element = this.element, o = this.options; if (node === undefined) { return element.find("li.current") } element.find("li").removeClass("current"); node.addClass("current"); }, toggleNode: function(node){ var element = this.element, o = this.options; var func; var toBeExpanded = !node.hasClass("expanded"); node.toggleClass("expanded"); if (o.effect === "slide") { func = toBeExpanded === true ? "slideUp" : "slideDown"; } else { func = toBeExpanded === true ? "fadeOut" : "fadeIn"; } if (toBeExpanded) { Utils.exec(o.onExpandNode, [node, element]); } else { Utils.exec(o.onCollapseNode, [node, element]); } node.children("ul")[func](o.duration); }, addTo: function(node, data){ var that = this, element = this.element, o = this.options; var target; var new_node; var toggle; if (node === null) { target = element; } else { target = node.children("ul"); if (target.length === 0) { target = $("<ul>").appendTo(node); toggle = this._createToggle(); toggle.appendTo(node); node.addClass("expanded"); } } new_node = this._createNode(data); new_node.appendTo(target); Utils.exec(o.onNodeInsert, [new_node, element], new_node[0]); return new_node; }, insertBefore: function(node, data){ var element = this.element, o = this.options; var new_node = this._createNode(data); new_node.insertBefore(node); Utils.exec(o.onNodeInsert, [new_node, element], new_node[0]); return new_node; }, insertAfter: function(node, data){ var element = this.element, o = this.options; var new_node = this._createNode(data); new_node.insertAfter(node); Utils.exec(o.onNodeInsert, [new_node, element], new_node[0]); return new_node; }, del: function(node){ var element = this.element, o = this.options; var parent_list = node.closest("ul"); var parent_node = parent_list.closest("li"); node.remove(); if (parent_list.children().length === 0 && !parent_list.is(element)) { parent_list.remove(); parent_node.removeClass("expanded"); parent_node.children(".node-toggle").remove(); } Utils.exec(o.onNodeDelete, [element], element[0]); }, clean: function(node){ var element = this.element, o = this.options; node.children("ul").remove(); node.removeClass("expanded"); node.children(".node-toggle").remove(); Utils.exec(o.onNodeClean, [node, element], node[0]); }, changeAttribute: function(attributeName){ switch (attributeName) { default: ; } } }; Metro.plugin('treeview', Treeview); // Source: js/plugins/validator.js var ValidatorFuncs = { required: function(val){ return Utils.isValue(val) ? val.trim() : false; }, length: function(val, len){ if (!Utils.isValue(len) || isNaN(len) || len <= 0) { return false; } return val.trim().length === parseInt(len); }, minlength: function(val, len){ if (!Utils.isValue(len) || isNaN(len) || len <= 0) { return false; } return val.trim().length >= parseInt(len); }, maxlength: function(val, len){ if (!Utils.isValue(len) || isNaN(len) || len <= 0) { return false; } return val.trim().length <= parseInt(len); }, min: function(val, min_value){ if (!Utils.isValue(min_value) || isNaN(min_value)) { return false; } if (!this.number(val)) { return false; } if (isNaN(val)) { return false; } return Number(val) >= Number(min_value); }, max: function(val, max_value){ if (!Utils.isValue(max_value) || isNaN(max_value)) { return false; } if (!this.number(val)) { return false; } if (isNaN(val)) { return false; } return Number(val) <= Number(max_value); }, email: function(val){ return /^[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i.test(val); }, domain: function(val){ return /^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/.test(val); }, url: function(val){ return /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(val); }, date: function(val, format, locale){ if (Utils.isNull(format)) { return String(new Date(val)).toLowerCase() !== "invalid date"; } else { return String(val.toDate(format, locale)).toLowerCase() !== "invalid date"; } }, number: function(val){ return !isNaN(val); }, integer: function(val){ return Utils.isInt(val); }, float: function(val){ return Utils.isFloat(val); }, digits: function(val){ return /^\d+$/.test(val); }, hexcolor: function(val){ return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(val); }, color: function(val){ if (!Utils.isValue(val)) return false; return Colors.color(val, Colors.PALETTES.STANDARD) !== false; }, pattern: function(val, pat){ if (!Utils.isValue(val)) return false; if (!Utils.isValue(pat)) return false; var reg = new RegExp(pat); return reg.test(val); }, compare: function(val, val2){ return val === val2; }, not: function(val, not_this){ return val !== not_this; }, notequals: function(val, val2){ if (Utils.isNull(val)) return false; if (Utils.isNull(val2)) return false; return val.trim() !== val2.trim(); }, equals: function(val, val2){ if (Utils.isNull(val)) return false; if (Utils.isNull(val2)) return false; return val.trim() === val2.trim(); }, custom: function(val, func){ if (Utils.isFunc(func) === false) { return false; } return Utils.exec(func, [val]); }, is_control: function(el){ return el.parent().hasClass("input") || el.parent().hasClass("select") || el.parent().hasClass("textarea") || el.parent().hasClass("checkbox") || el.parent().hasClass("switch") || el.parent().hasClass("radio") || el.parent().hasClass("spinner") ; }, reset_state: function(el){ var input = Utils.isJQueryObject(el) === false ? $(el) : el ; var is_control = ValidatorFuncs.is_control(input); if (is_control) { input.parent().removeClass("invalid valid"); } else { input.removeClass("invalid valid"); } }, set_valid_state: function(input){ if (Utils.isJQueryObject(input) === false) { input = $(input); } var is_control = ValidatorFuncs.is_control(input); if (is_control) { input.parent().addClass("valid"); } else { input.addClass("valid"); } }, set_invalid_state: function(input){ if (Utils.isJQueryObject(input) === false) { input = $(input); } var is_control = ValidatorFuncs.is_control(input); if (is_control) { input.parent().addClass("invalid"); } else { input.addClass("invalid"); } }, reset: function(form){ var that = this; $.each($(form).find("[data-validate]"), function(){ that.reset_state(this); }); return this; }, validate: function(el, result, cb_ok, cb_error, required_mode){ var this_result = true; var input = $(el); var funcs = input.data('validate') !== undefined ? String(input.data('validate')).split(" ").map(function(s){return s.trim();}) : []; var errors = []; if (funcs.length === 0) { return true; } this.reset_state(input); if (input.attr('type') && input.attr('type').toLowerCase() === "checkbox") { if (funcs.indexOf('required') === -1) { this_result = true; } else { this_result = input.is(":checked"); } if (this_result === false) { errors.push('required'); } if (result !== undefined) { result.val += this_result ? 0 : 1; } } else if (input.attr('type') && input.attr('type').toLowerCase() === "radio") { if (input.attr('name') === undefined) { this_result = true; } var radio_selector = 'input[name=' + input.attr('name') + ']:checked'; this_result = $(radio_selector).length > 0; if (result !== undefined) { result.val += this_result ? 0 : 1; } } else { $.each(funcs, function(){ if (this_result === false) return; var rule = this.split("="); var f, a, b; f = rule[0]; rule.shift(); a = rule.join("="); if (['compare', 'equals', 'notequals'].indexOf(f) > -1) { a = input[0].form.elements[a].value; } if (f === 'date') { a = input.attr("data-value-format"); b = input.attr("data-value-locale"); } if (Utils.isFunc(ValidatorFuncs[f]) === false) { this_result = true; } else { if (required_mode === true || f === "required") { this_result = ValidatorFuncs[f](input.val(), a, b); } else { if (input.val().trim() !== "") { this_result = ValidatorFuncs[f](input.val(), a, b); } else { this_result = true; } } } if (this_result === false) { errors.push(f); } if (result !== undefined) { result.val += this_result ? 0 : 1; } }); } if (this_result === false) { this.set_invalid_state(input); if (result !== undefined) { result.log.push({ input: input[0], name: input.attr("name"), value: input.val(), funcs: funcs, errors: errors }); } if (cb_error !== undefined) Utils.exec(cb_error, [input, input.val()], input[0]); } else { this.set_valid_state(input); if (cb_ok !== undefined) Utils.exec(cb_ok, [input, input.val()], input[0]); } return this_result; } }; Metro['validator'] = ValidatorFuncs; var Validator = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._onsubmit = null; this._onreset = null; this.result = []; this._setOptionsFromDOM(); this._create(); return this; }, dependencies: ['utils', 'colors'], options: { submitTimeout: 200, interactiveCheck: false, clearInvalid: 0, requiredMode: true, useRequiredClass: true, onBeforeSubmit: Metro.noop_true, onSubmit: Metro.noop, onError: Metro.noop, onValidate: Metro.noop, onErrorForm: Metro.noop, onValidateForm: Metro.noop, onValidatorCreate: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var inputs = element.find("[data-validate]"); element .attr("novalidate", 'novalidate'); //.attr("action", "javascript:"); $.each(inputs, function(){ var input = $(this); var funcs = input.data("validate"); var required = funcs.indexOf("required") > -1; if (required && o.useRequiredClass === true) { if (ValidatorFuncs.is_control(input)) { input.parent().addClass("required"); } else { input.addClass("required"); } } if (o.interactiveCheck === true) { input.on(Metro.events.inputchange, function () { ValidatorFuncs.validate(this, undefined, undefined, undefined, o.requiredMode); }); } }); this._onsubmit = null; this._onreset = null; if (element[0].onsubmit !== null) { this._onsubmit = element[0].onsubmit; element[0].onsubmit = null; } if (element[0].onreset !== null) { this._onreset = element[0].onreset; element[0].onreset = null; } element[0].onsubmit = function(){ return that._submit(); }; element[0].onreset = function(){ return that._reset(); }; Utils.exec(this.options.onValidatorCreate, [element], this.elem); }, _reset: function(){ ValidatorFuncs.reset(this.element); if (this._onsubmit !== null) Utils.exec(this._onsubmit, null, this.element[0]); }, _submit: function(){ var that = this, element = this.element, o = this.options; var form = this.elem; var inputs = element.find("[data-validate]"); var submit = element.find(":submit").attr('disabled', 'disabled').addClass('disabled'); var result = { val: 0, log: [] }; var formData = Utils.formData(element); $.each(inputs, function(){ ValidatorFuncs.validate(this, result, o.onValidate, o.onError, o.requiredMode); }); submit.removeAttr("disabled").removeClass("disabled"); result.val += Utils.exec(o.onBeforeSubmit, [element, formData], this.elem) === false ? 1 : 0; if (result.val === 0) { Utils.exec(o.onValidateForm, [element, formData], form); setTimeout(function(){ Utils.exec(o.onSubmit, [element, formData], form); if (that._onsubmit !== null) Utils.exec(that._onsubmit, null, form); }, o.submitTimeout); } else { Utils.exec(o.onErrorForm, [result.log, element, formData], form); if (o.clearInvalid > 0) { setTimeout(function(){ $.each(inputs, function(){ var inp = $(this); if (ValidatorFuncs.is_control(inp)) { inp.parent().removeClass("invalid"); } else { inp.removeClass("invalid"); } }) }, o.clearInvalid); } } return result.val === 0; }, changeAttribute: function(attributeName){ switch (attributeName) { } } }; Metro.plugin('validator', Validator); // Source: js/plugins/video.js var Video = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.fullscreen = false; this.preloader = null; this.player = null; this.video = elem; this.stream = null; this.volume = null; this.volumeBackup = 0; this.muted = false; this.fullScreenInterval = false; this._setOptionsFromDOM(); this._create(); return this; }, options: { src: null, poster: "", logo: "", logoHeight: 32, logoWidth: "auto", logoTarget: "", volume: .5, loop: false, autoplay: false, fullScreenMode: Metro.fullScreenMode.DESKTOP, aspectRatio: Metro.aspectRatio.HD, controlsHide: 3000, showLoop: true, showPlay: true, showStop: true, showMute: true, showFull: true, showStream: true, showVolume: true, showInfo: true, loopIcon: "<span class='default-icon-loop'></span>", stopIcon: "<span class='default-icon-stop'></span>", playIcon: "<span class='default-icon-play'></span>", pauseIcon: "<span class='default-icon-pause'></span>", muteIcon: "<span class='default-icon-mute'></span>", volumeLowIcon: "<span class='default-icon-low-volume'></span>", volumeMediumIcon: "<span class='default-icon-medium-volume'></span>", volumeHighIcon: "<span class='default-icon-high-volume'></span>", screenMoreIcon: "<span class='default-icon-enlarge'></span>", screenLessIcon: "<span class='default-icon-shrink'></span>", onPlay: Metro.noop, onPause: Metro.noop, onStop: Metro.noop, onEnd: Metro.noop, onMetadata: Metro.noop, onTime: Metro.noop, onVideoCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options, video = this.video; if (Metro.fullScreenEnabled === false) { o.fullScreenMode = Metro.fullScreenMode.WINDOW; } this._createPlayer(); this._createControls(); this._createEvents(); this._setAspectRatio(); if (o.autoplay === true) { this.play(); } Utils.exec(o.onVideoCreate, [element, this.player], element[0]); }, _createPlayer: function(){ var that = this, element = this.element, o = this.options, video = this.video; var prev = element.prev(); var parent = element.parent(); var player = $("<div>").addClass("media-player video-player " + element[0].className); var preloader = $("<div>").addClass("preloader").appendTo(player); var logo = $("<a>").attr("href", o.logoTarget).addClass("logo").appendTo(player); if (prev.length === 0) { parent.prepend(player); } else { player.insertAfter(prev); } element.appendTo(player); $.each(['muted', 'autoplay', 'controls', 'height', 'width', 'loop', 'poster', 'preload'], function(){ element.removeAttr(this); }); element.attr("preload", "auto"); if (o.poster !== "") { element.attr("poster", o.poster); } video.volume = o.volume; preloader.activity({ type: "cycle", style: "color" }); preloader.hide(0); this.preloader = preloader; if (o.logo !== "") { $("<img>") .css({ height: o.logoHeight, width: o.logoWidth }) .attr("src", o.logo).appendTo(logo); } if (o.src !== null) { this._setSource(o.src); } element[0].className = ""; this.player = player; }, _setSource: function(src){ var element = this.element; element.find("source").remove(); element.removeAttr("src"); if (Array.isArray(src)) { $.each(src, function(){ var item = this; if (item.src === undefined) return ; $("<source>").attr('src', item.src).attr('type', item.type !== undefined ? item.type : '').appendTo(element); }); } else { element.attr("src", src); } }, _createControls: function(){ var that = this, element = this.element, o = this.options, video = this.elem, player = this.player; var controls = $("<div>").addClass("controls").addClass(o.clsControls).insertAfter(element); var stream = $("<div>").addClass("stream").appendTo(controls); var streamSlider = $("<input>").addClass("stream-slider ultra-thin cycle-marker").appendTo(stream); var volume = $("<div>").addClass("volume").appendTo(controls); var volumeSlider = $("<input>").addClass("volume-slider ultra-thin cycle-marker").appendTo(volume); var infoBox = $("<div>").addClass("info-box").appendTo(controls); if (o.showInfo !== true) { infoBox.hide(); } streamSlider.slider({ clsMarker: "bg-red", clsHint: "bg-cyan fg-white", clsComplete: "bg-cyan", hint: true, onStart: function(){ if (!video.paused) video.pause(); }, onStop: function(val){ if (video.seekable.length > 0) { video.currentTime = (that.duration * val / 100).toFixed(0); } if (video.paused && video.currentTime > 0) { video.play(); } } }); this.stream = streamSlider; if (o.showStream !== true) { stream.hide(); } volumeSlider.slider({ clsMarker: "bg-red", clsHint: "bg-cyan fg-white", hint: true, value: o.volume * 100, onChangeValue: function(val){ video.volume = val / 100; } }); this.volume = volumeSlider; if (o.showVolume !== true) { volume.hide(); } var loop, play, stop, mute, full; if (o.showLoop === true) loop = $("<button>").attr("type", "button").addClass("button square loop").html(o.loopIcon).appendTo(controls); if (o.showPlay === true) play = $("<button>").attr("type", "button").addClass("button square play").html(o.playIcon).appendTo(controls); if (o.showStop === true) stop = $("<button>").attr("type", "button").addClass("button square stop").html(o.stopIcon).appendTo(controls); if (o.showMute === true) mute = $("<button>").attr("type", "button").addClass("button square mute").html(o.muteIcon).appendTo(controls); if (o.showFull === true) full = $("<button>").attr("type", "button").addClass("button square full").html(o.screenMoreIcon).appendTo(controls); if (o.loop === true) { loop.addClass("active"); element.attr("loop", "loop"); } this._setVolume(); if (o.muted) { that.volumeBackup = video.volume; that.volume.data('slider').val(0); video.volume = 0; } infoBox.html("00:00 / 00:00"); }, _createEvents: function(){ var that = this, element = this.element, o = this.options, video = this.elem, player = this.player; element.on("loadstart", function(){ that.preloader.fadeIn(); }); element.on("loadedmetadata", function(){ that.duration = video.duration.toFixed(0); that._setInfo(0, that.duration); Utils.exec(o.onMetadata, [video, player], element[0]); }); element.on("canplay", function(){ that._setBuffer(); that.preloader.fadeOut(); }); element.on("progress", function(){ that._setBuffer(); }); element.on("timeupdate", function(){ var position = Math.round(video.currentTime * 100 / that.duration); that._setInfo(video.currentTime, that.duration); that.stream.data('slider').val(position); Utils.exec(o.onTime, [video.currentTime, that.duration, video, player], element[0]); }); element.on("waiting", function(){ that.preloader.fadeIn(); }); element.on("loadeddata", function(){ }); element.on("play", function(){ player.find(".play").html(o.pauseIcon); Utils.exec(o.onPlay, [video, player], element[0]); that._onMouse(); }); element.on("pause", function(){ player.find(".play").html(o.playIcon); Utils.exec(o.onPause, [video, player], element[0]); that._offMouse(); }); element.on("stop", function(){ that.stream.data('slider').val(0); Utils.exec(o.onStop, [video, player], element[0]); that._offMouse(); }); element.on("ended", function(){ that.stream.data('slider').val(0); Utils.exec(o.onEnd, [video, player], element[0]); that._offMouse(); }); element.on("volumechange", function(){ that._setVolume(); }); player.on(Metro.events.click, ".play", function(e){ if (video.paused) { that.play(); } else { that.pause(); } }); player.on(Metro.events.click, ".stop", function(e){ that.stop(); }); player.on(Metro.events.click, ".mute", function(e){ that._toggleMute(); }); player.on(Metro.events.click, ".loop", function(){ that._toggleLoop(); }); player.on(Metro.events.click, ".full", function(e){ that.fullscreen = !that.fullscreen; player.find(".full").html(that.fullscreen === true ? o.screenLessIcon : o.screenMoreIcon); if (o.fullScreenMode === Metro.fullScreenMode.WINDOW) { if (that.fullscreen === true) { player.addClass("full-screen"); } else { player.removeClass("full-screen"); } } else { if (that.fullscreen === true) { Metro.requestFullScreen(video); if (that.fullScreenInterval === false) that.fullScreenInterval = setInterval(function(){ if (Metro.inFullScreen() === false) { that.fullscreen = false; clearInterval(that.fullScreenInterval); that.fullScreenInterval = false; player.find(".full").html(o.screenMoreIcon); } }, 1000); } else { Metro.exitFullScreen(); } } if (that.fullscreen === true) { $(document).on(Metro.events.keyup + "_video", function(e){ if (e.keyCode === 27) { player.find(".full").click(); } }); } else { $(document).off(Metro.events.keyup + "_video"); } }); $(window).resize(function(){ that._setAspectRatio(); }); }, _onMouse: function(){ var player = this.player, o = this.options; if (o.controlsHide > 0) { player.on(Metro.events.enter, function(){ player.find(".controls").fadeIn(); }); player.on(Metro.events.leave, function(){ setTimeout(function(){ player.find(".controls").fadeOut(); }, o.controlsHide); }); } }, _offMouse: function(){ this.player.off(Metro.events.enter); this.player.off(Metro.events.leave); this.player.find(".controls").fadeIn(); }, _toggleLoop: function(){ var loop = this.player.find(".loop"); if (loop.length === 0) return ; loop.toggleClass("active"); if (loop.hasClass("active")) { this.element.attr("loop", "loop"); } else { this.element.removeAttr("loop"); } }, _toggleMute: function(){ this.muted = !this.muted; if (this.muted === false) { this.video.volume = this.volumeBackup; this.volume.data('slider').val(this.volumeBackup * 100); } else { this.volumeBackup = this.video.volume; this.volume.data('slider').val(0); this.video.volume = 0; } }, _setInfo: function(a, b){ this.player.find(".info-box").html(Utils.secondsToFormattedString(Math.round(a)) + " / " + Utils.secondsToFormattedString(Math.round(b))); }, _setBuffer: function(){ var buffer = this.video.buffered.length ? Math.round(Math.floor(this.video.buffered.end(0)) / Math.floor(this.video.duration) * 100) : 0; this.stream.data('slider').buff(buffer); }, _setVolume: function(){ var video = this.video, player = this.player, o = this.options; var volumeButton = player.find(".mute"); var volume = video.volume * 100; if (volume > 1 && volume < 30) { volumeButton.html(o.volumeLowIcon); } else if (volume >= 30 && volume < 60) { volumeButton.html(o.volumeMediumIcon); } else if (volume >= 60 && volume <= 100) { volumeButton.html(o.volumeHighIcon); } else { volumeButton.html(o.muteIcon); } }, _setAspectRatio: function(){ var player = this.player, o = this.options; var width = player.outerWidth(); var height; switch (o.aspectRatio) { case Metro.aspectRatio.SD: height = Utils.aspectRatioH(width, "4/3"); break; case Metro.aspectRatio.CINEMA: height = Utils.aspectRatioH(width, "21/9"); break; default: height = Utils.aspectRatioH(width, "16/9"); } player.outerHeight(height); }, aspectRatio: function(ratio){ this.options.aspectRatio = ratio; this._setAspectRatio(); }, play: function(src){ if (src !== undefined) { this._setSource(src); } if (this.element.attr("src") === undefined && this.element.find("source").length === 0) { return ; } this.video.play(); }, pause: function(){ this.video.pause(); }, resume: function(){ if (this.video.paused) { this.play(); } }, stop: function(){ this.video.pause(); this.video.currentTime = 0; this.stream.data('slider').val(0); this._offMouse(); }, volume: function(v){ if (v === undefined) { return this.video.volume; } if (v > 1) { v /= 100; } this.video.volume = v; this.volume.data('slider').val(v*100); }, loop: function(){ this._toggleLoop(); }, mute: function(){ this._toggleMute(); }, changeAspectRatio: function(){ this.options.aspectRatio = this.element.attr("data-aspect-ratio"); this._setAspectRatio(); }, changeSource: function(){ var src = JSON.parse(this.element.attr('data-src')); this.play(src); }, changeVolume: function(){ var volume = this.element.attr("data-volume"); this.volume(volume); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-aspect-ratio": this.changeAspectRatio(); break; case "data-src": this.changeSource(); break; case "data-volume": this.changeVolume(); break; } } }; Metro.plugin('video', Video); // Source: js/plugins/window.js var Window = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this.win = null; this.overlay = null; this.position = { top: 0, left: 0 }; this.hidden = false; this._setOptionsFromDOM(); this._create(); Utils.exec(this.options.onWindowCreate, [this.win, this.element]); return this; }, dependencies: ['draggable', 'resizeable'], options: { hidden: false, width: "auto", height: "auto", btnClose: true, btnMin: true, btnMax: true, clsCaption: "", clsContent: "", clsWindow: "", draggable: true, dragElement: ".window-caption .icon, .window-caption .title", dragArea: "parent", shadow: false, icon: "", title: "Window", content: "default", resizable: true, overlay: false, overlayColor: 'transparent', overlayAlpha: .5, modal: false, position: "absolute", checkEmbed: true, top: "auto", left: "auto", place: "auto", closeAction: Metro.actions.REMOVE, customButtons: null, clsCustomButton: "", minWidth: 0, minHeight: 0, maxWidth: 0, maxHeight: 0, onDragStart: Metro.noop, onDragStop: Metro.noop, onDragMove: Metro.noop, onCaptionDblClick: Metro.noop, onCloseClick: Metro.noop, onMaxClick: Metro.noop, onMinClick: Metro.noop, onResizeStart: Metro.noop, onResizeStop: Metro.noop, onResize: Metro.noop, onWindowCreate: Metro.noop, onShow: Metro.noop, onWindowDestroy: Metro.noop, onCanClose: Metro.noop_true, onClose: Metro.noop }, _setOptionsFromDOM: function(){ var element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; var win, overlay; var parent = o.dragArea === "parent" ? element.parent() : $(o.dragArea); if (o.modal === true) { o.btnMax = false; o.btnMin = false; o.resizable = false; } if (o.content === "default") { o.content = element; } win = this._window(o); win.addClass("no-visible"); parent.append(win); if (o.overlay === true) { overlay = this._overlay(); overlay.appendTo(win.parent()); this.overlay = overlay; } this.win = win; setTimeout(function(){ that._setPosition(); if (o.hidden !== true) { that.win.removeClass("no-visible"); } Utils.exec(o.onShow, [win], win[0]); }, 100); }, _setPosition: function(){ var o = this.options; var win = this.win; var parent = o.dragArea === "parent" ? win.parent() : $(o.dragArea); var top_center = parent.height() / 2 - win[0].offsetHeight / 2; var left_center = parent.width() / 2 - win[0].offsetWidth / 2; var top, left, right, bottom; if (o.place !== 'auto') { switch (o.place.toLowerCase()) { case "top-left": top = 0; left = 0; right = "auto"; bottom = "auto"; break; case "top-center": top = 0; left = left_center; right = "auto"; bottom = "auto"; break; case "top-right": top = 0; right = 0; left = "auto"; bottom = "auto"; break; case "right-center": top = top_center; right = 0; left = "auto"; bottom = "auto"; break; case "bottom-right": bottom = 0; right = 0; left = "auto"; top = "auto"; break; case "bottom-center": bottom = 0; left = left_center; right = "auto"; top = "auto"; break; case "bottom-left": bottom = 0; left = 0; right = "auto"; top = "auto"; break; case "left-center": top = top_center; left = 0; right = "auto"; bottom = "auto"; break; default: top = top_center; left = left_center; bottom = "auto"; right = "auto"; } win.css({ top: top, left: left, bottom: bottom, right: right }); } }, _window: function(o){ var that = this; var win, caption, content, icon, title, buttons, btnClose, btnMin, btnMax, resizer, status; var width = o.width, height = o.height; win = $("<div>").addClass("window"); if (o.modal === true) { win.addClass("modal"); } caption = $("<div>").addClass("window-caption"); content = $("<div>").addClass("window-content"); win.append(caption); win.append(content); if (o.status === true) { status = $("<div>").addClass("window-status"); win.append(status); } if (o.shadow === true) { win.addClass("win-shadow"); } if (Utils.isValue(o.icon)) { icon = $("<span>").addClass("icon").html(o.icon); icon.appendTo(caption); } title = $("<span>").addClass("title").html(Utils.isValue(o.title) ? o.title : "&nbsp;"); title.appendTo(caption); if (o.content !== undefined && o.content !== 'original') { if (Utils.isUrl(o.content) && Utils.isVideoUrl(o.content)) { o.content = Utils.embedUrl(o.content); } if (!Utils.isJQueryObject(o.content) && Utils.isFunc(o.content)) { o.content = Utils.exec(o.content); } if (Utils.isJQueryObject(o.content)) { o.content.appendTo(content); } else { content.html(o.content); } } buttons = $("<div>").addClass("buttons"); buttons.appendTo(caption); if (o.btnMax === true) { btnMax = $("<span>").addClass("button btn-max sys-button"); btnMax.appendTo(buttons); } if (o.btnMin === true) { btnMin = $("<span>").addClass("button btn-min sys-button"); btnMin.appendTo(buttons); } if (o.btnClose === true) { btnClose = $("<span>").addClass("button btn-close sys-button"); btnClose.appendTo(buttons); } if (Utils.isValue(o.customButtons)) { var customButtons = []; if (Utils.isObject(o.customButtons) !== false) { o.customButtons = Utils.isObject(o.customButtons); } if (typeof o.customButtons === "string" && o.customButtons.indexOf("{") > -1) { customButtons = JSON.parse(o.customButtons); } else if (typeof o.customButtons === "object" && Utils.objectLength(o.customButtons) > 0) { customButtons = o.customButtons; } else { console.log("Unknown format for custom buttons"); } $.each(customButtons, function(){ var item = this; var customButton = $("<span>"); customButton .addClass("button btn-custom") .addClass(o.clsCustomButton) .addClass(item.cls) .attr("tabindex", -1) .html(item.html); customButton.data("action", item.onclick); buttons.prepend(customButton); }); } caption.on(Metro.events.stop, ".btn-custom", function(e){ if (Utils.isRightMouse(e)) return; var button = $(this); var action = button.data("action"); Utils.exec(action, [button], this); }); win.attr("id", o.id === undefined ? Utils.elementId("window") : o.id); win.on(Metro.events.dblclick, ".window-caption", function(e){ that.maximized(e); }); caption.on(Metro.events.click, ".btn-max, .btn-min, .btn-close", function(e){ if (Utils.isRightMouse(e)) return; var target = $(e.target); if (target.hasClass("btn-max")) that.maximized(e); if (target.hasClass("btn-min")) that.minimized(e); if (target.hasClass("btn-close")) that.close(e); }); if (o.draggable === true) { win.draggable({ dragElement: o.dragElement, dragArea: o.dragArea, onDragStart: o.onDragStart, onDragStop: o.onDragStop, onDragMove: o.onDragMove }) } win.addClass(o.clsWindow); caption.addClass(o.clsCaption); content.addClass(o.clsContent); if (o.minWidth === 0) { o.minWidth = 34; $.each(buttons.children(".btn-custom"), function(){ o.minWidth += Utils.hiddenElementSize(this).width; }); if (o.btnMax) o.minWidth += 34; if (o.btnMin) o.minWidth += 34; if (o.btnClose) o.minWidth += 34; } if (o.minWidth > 0 && !isNaN(o.width) && o.width < o.minWidth) { width = o.minWidth; } if (o.minHeight > 0 && !isNaN(o.height) && o.height > o.minHeight) { height = o.minHeight; } if (o.resizable === true) { resizer = $("<span>").addClass("resize-element"); resizer.appendTo(win); win.addClass("resizable"); win.resizable({ minWidth: o.minWidth, minHeight: o.minHeight, maxWidth: o.maxWidth, maxHeight: o.maxHeight, resizeElement: ".resize-element", onResizeStart: o.onResizeStart, onResizeStop: o.onResizeStop, onResize: o.onResize }); } win.css({ width: width, height: height, position: o.position, top: o.top, left: o.left }); return win; }, _overlay: function(){ var o = this.options; var overlay = $("<div>"); overlay.addClass("overlay"); if (o.overlayColor === 'transparent') { overlay.addClass("transparent"); } else { overlay.css({ background: Utils.hex2rgba(o.overlayColor, o.overlayAlpha) }); } return overlay; }, maximized: function(e){ var win = this.win, o = this.options; var target = $(e.currentTarget); win.toggleClass("maximized"); if (target.hasClass("window-caption")) { Utils.exec(o.onCaptionDblClick, [win]); } else { Utils.exec(o.onMaxClick, [win]); } }, minimized: function(){ var win = this.win, element = this.element, o = this.options; win.toggleClass("minimized"); Utils.exec(o.onMinClick, [win], element[0]); }, close: function(){ var that = this, win = this.win, element = this.element, o = this.options; var timer = null; if (Utils.exec(o.onCanClose, [win]) === false) { return false; } var timeout = 0; if (o.onClose !== Metro.noop) { timeout = 500; } Utils.exec(o.onClose, [win], element[0]); timer = setTimeout(function(){ timer = null; if (o.modal === true) { win.siblings(".overlay").remove(); } Utils.exec(o.onCloseClick, [win], element[0]); Utils.exec(o.onWindowDestroy, [win], element[0]); if (o.closeAction === Metro.actions.REMOVE) { win.remove(); } else { that.hide(); } }, timeout); }, hide: function(){ this.win.css({ display: "none" }); }, show: function(){ this.win.removeClass("no-visible"); this.win.css({ display: "flex" }); }, toggle: function(){ if (this.win.css("display") === "none" || this.win.hasClass("no-visible")) { this.show(); } else { this.hide(); } }, isOpen: function(){ return this.win.hasClass("no-visible"); }, min: function(a){ a ? this.win.addClass("minimized") : this.win.removeClass("minimized"); }, max: function(a){ a ? this.win.addClass("maximized") : this.win.removeClass("maximized"); }, toggleButtons: function(a) { var win = this.win; var btnClose = win.find(".btn-close"); var btnMin = win.find(".btn-min"); var btnMax = win.find(".btn-max"); if (a === "data-btn-close") { btnClose.toggle(); } if (a === "data-btn-min") { btnMin.toggle(); } if (a === "data-btn-max") { btnMax.toggle(); } }, changeSize: function(a){ var element = this.element, win = this.win; if (a === "data-width") { win.css("width", element.data("width")); } if (a === "data-height") { win.css("height", element.data("height")); } }, changeClass: function(a){ var element = this.element, win = this.win, o = this.options; if (a === "data-cls-window") { win[0].className = "window " + (o.resizable ? " resizeable " : " ") + element.attr("data-cls-window"); } if (a === "data-cls-caption") { win.find(".window-caption")[0].className = "window-caption " + element.attr("data-cls-caption"); } if (a === "data-cls-content") { win.find(".window-content")[0].className = "window-content " + element.attr("data-cls-content"); } }, toggleShadow: function(){ var element = this.element, win = this.win; var flag = JSON.parse(element.attr("data-shadow")); if (flag === true) { win.addClass("win-shadow"); } else { win.removeClass("win-shadow"); } }, setContent: function(){ var element = this.element, win = this.win; var content = element.attr("data-content"); var result; if (!Utils.isJQueryObject(content) && Utils.isFunc(content)) { result = Utils.exec(content); } else if (Utils.isJQueryObject(content)) { result = content.html(); } else { result = content; } win.find(".window-content").html(result); }, setTitle: function(){ var element = this.element, win = this.win; var title = element.attr("data-title"); win.find(".window-caption .title").html(title); }, setIcon: function(){ var element = this.element, win = this.win; var icon = element.attr("data-icon"); win.find(".window-caption .icon").html(icon); }, getIcon: function(){ return this.win.find(".window-caption .icon").html(); }, getTitle: function(){ return this.win.find(".window-caption .title").html(); }, toggleDraggable: function(){ var element = this.element, win = this.win; var flag = JSON.parse(element.attr("data-draggable")); var drag = win.data("draggable"); if (flag === true) { drag.on(); } else { drag.off(); } }, toggleResizable: function(){ var element = this.element, win = this.win; var flag = JSON.parse(element.attr("data-resizable")); var resize = win.data("resizable"); if (flag === true) { resize.on(); win.find(".resize-element").removeClass("resize-element-disabled"); } else { resize.off(); win.find(".resize-element").addClass("resize-element-disabled"); } }, changeTopLeft: function(a){ var element = this.element, win = this.win; var pos; if (a === "data-top") { pos = parseInt(element.attr("data-top")); if (!isNaN(pos)) { return ; } win.css("top", pos); } if (a === "data-left") { pos = parseInt(element.attr("data-left")); if (!isNaN(pos)) { return ; } win.css("left", pos); } }, changePlace: function () { var element = this.element, win = this.win; var place = element.attr("data-place"); win.addClass(place); }, changeAttribute: function(attributeName){ switch (attributeName) { case "data-btn-close": case "data-btn-min": case "data-btn-max": this.toggleButtons(attributeName); break; case "data-width": case "data-height": this.changeSize(attributeName); break; case "data-cls-window": case "data-cls-caption": case "data-cls-content": this.changeClass(attributeName); break; case "data-shadow": this.toggleShadow(); break; case "data-icon": this.setIcon(); break; case "data-title": this.setTitle(); break; case "data-content": this.setContent(); break; case "data-draggable": this.toggleDraggable(); break; case "data-resizable": this.toggleResizable(); break; case "data-top": case "data-left": this.changeTopLeft(attributeName); break; case "data-place": this.changePlace(); break; } } }; Metro.plugin('window', Window); Metro['window'] = { isWindow: function(el){ return Utils.isMetroObject(el, "window"); }, min: function(el, a){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); win.min(a); }, max: function(el, a){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); win.max(a); }, show: function(el){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); win.show(); }, hide: function(el){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); win.hide(); }, toggle: function(el){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); win.toggle(); }, isOpen: function(el){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); return win.isOpen(); }, close: function(el){ if (!this.isWindow(el)) { return false; } var win = $(el).data("window"); win.close(); }, create: function(options){ var w; w = $("<div>").appendTo($("body")); var w_options = $.extend({}, { }, (options !== undefined ? options : {})); return w.window(w_options); } }; // Source: js/plugins/wizard.js var Wizard = { init: function( options, elem ) { this.options = $.extend( {}, this.options, options ); this.elem = elem; this.element = $(elem); this._setOptionsFromDOM(); this._create(); return this; }, options: { start: 1, finish: 0, iconHelp: "<span class='default-icon-help'></span>", iconPrev: "<span class='default-icon-left-arrow'></span>", iconNext: "<span class='default-icon-right-arrow'></span>", iconFinish: "<span class='default-icon-check'></span>", buttonMode: "cycle", // default, cycle, square buttonOutline: true, clsWizard: "", clsActions: "", clsHelp: "", clsPrev: "", clsNext: "", clsFinish: "", onPage: Metro.noop, onHelpClick: Metro.noop, onPrevClick: Metro.noop, onNextClick: Metro.noop, onFinishClick: Metro.noop, onBeforePrev: Metro.noop_true, onBeforeNext: Metro.noop_true, onWizardCreate: Metro.noop }, _setOptionsFromDOM: function(){ var that = this, element = this.element, o = this.options; $.each(element.data(), function(key, value){ if (key in o) { try { o[key] = JSON.parse(value); } catch (e) { o[key] = value; } } }); }, _create: function(){ var that = this, element = this.element, o = this.options; this._createWizard(); this._createEvents(); Utils.exec(o.onWizardCreate, [element]); }, _createWizard: function(){ var that = this, element = this.element, o = this.options; var bar; element.addClass("wizard").addClass(o.view).addClass(o.clsWizard); bar = $("<div>").addClass("action-bar").addClass(o.clsActions).appendTo(element); var buttonMode = o.buttonMode === "button" ? "" : o.buttonMode; if (o.buttonOutline === true) { buttonMode += " outline"; } if (o.iconHelp !== false) $("<button>").attr("type", "button").addClass("button wizard-btn-help").addClass(buttonMode).addClass(o.clsHelp).html(Utils.isTag(o.iconHelp) ? o.iconHelp : $("<img>").attr('src', o.iconHelp)).appendTo(bar); if (o.iconPrev !== false) $("<button>").attr("type", "button").addClass("button wizard-btn-prev").addClass(buttonMode).addClass(o.clsPrev).html(Utils.isTag(o.iconPrev) ? o.iconPrev : $("<img>").attr('src', o.iconPrev)).appendTo(bar); if (o.iconNext !== false) $("<button>").attr("type", "button").addClass("button wizard-btn-next").addClass(buttonMode).addClass(o.clsNext).html(Utils.isTag(o.iconNext) ? o.iconNext : $("<img>").attr('src', o.iconNext)).appendTo(bar); if (o.iconFinish !== false) $("<button>").attr("type", "button").addClass("button wizard-btn-finish").addClass(buttonMode).addClass(o.clsFinish).html(Utils.isTag(o.iconFinish) ? o.iconFinish : $("<img>").attr('src', o.iconFinish)).appendTo(bar); this.toPage(o.start); this._setHeight(); }, _setHeight: function(){ var that = this, element = this.element, o = this.options; var pages = element.children("section"); var max_height = 0; pages.children(".page-content").css("max-height", "none"); $.each(pages, function(){ var h = $(this).height(); if (max_height < parseInt(h)) { max_height = h; } }); element.height(max_height); }, _createEvents: function(){ var that = this, element = this.element, o = this.options; element.on(Metro.events.click, ".wizard-btn-help", function(){ var pages = element.children("section"); var page = pages.get(that.current - 1); Utils.exec(o.onHelpClick, [that.current, page, element]) }); element.on(Metro.events.click, ".wizard-btn-prev", function(){ that.prev(); Utils.exec(o.onPrevClick, [that.current, element]) }); element.on(Metro.events.click, ".wizard-btn-next", function(){ that.next(); Utils.exec(o.onNextClick, [that.current, element]) }); element.on(Metro.events.click, ".wizard-btn-finish", function(){ Utils.exec(o.onFinishClick, [that.current, element]) }); element.on(Metro.events.click, ".complete", function(){ var index = $(this).index() + 1; that.toPage(index); }); $(window).on(Metro.events.resize, function(){ that._setHeight(); }); }, next: function(){ var that = this, element = this.element, o = this.options; var pages = element.children("section"); var page = $(element.children("section").get(this.current - 1)); if (this.current + 1 > pages.length || Utils.exec(o.onBeforeNext, [this.current, page, element]) === false) { return ; } this.current++; this.toPage(this.current); }, prev: function(){ var that = this, element = this.element, o = this.options; var page = $(element.children("section").get(this.current - 1)); if (this.current - 1 === 0 || Utils.exec(o.onBeforePrev, [this.current, page, element]) === false) { return ; } this.current--; this.toPage(this.current); }, last: function(){ var that = this, element = this.element, o = this.options; this.toPage(element.children("section").length); }, first: function(){ this.toPage(1); }, toPage: function(page){ var that = this, element = this.element, o = this.options; var target = $(element.children("section").get(page - 1)); var sections = element.children("section"); var actions = element.find(".action-bar"); if (target.length === 0) { return ; } var finish = element.find(".wizard-btn-finish").addClass("disabled"); var next = element.find(".wizard-btn-next").addClass("disabled"); var prev = element.find(".wizard-btn-prev").addClass("disabled"); this.current = page; element.children("section") .removeClass("complete current") .removeClass(o.clsCurrent) .removeClass(o.clsComplete); target.addClass("current").addClass(o.clsCurrent); target.prevAll().addClass("complete").addClass(o.clsComplete); var border_size = element.children("section.complete").length === 0 ? 0 : parseInt(Utils.getStyleOne(element.children("section.complete")[0], "border-left-width")); actions.animate({ left: element.children("section.complete").length * border_size + 41 }); if ( (this.current === sections.length) || (o.finish > 0 && this.current >= o.finish) ) { finish.removeClass("disabled"); } if (this.current < sections.length) { next.removeClass("disabled"); } if (this.current > 1) { prev.removeClass("disabled"); } element.trigger("onpage", [this.current, target, element]); Utils.exec(o.onPage, [this.current, target, element]); }, changeAttribute: function(attributeName){ } }; Metro.plugin('wizard', Wizard); return METRO_INIT === true ? Metro.init() : Metro; }));
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./app.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./app.ts": /*!****************!*\ !*** ./app.ts ***! \****************/ /*! no static exports found */ /***/ (function(module, exports) { eval("var message = \"HELLO FROM US!\";\nconsole.log(message);\n\n\n//# sourceURL=webpack:///./app.ts?"); /***/ }) /******/ });
/*! * jQuery JavaScript Library v2.0.3 -effects,-offset,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:08Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3 -effects,-offset,-dimensions", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var curCSS, iframe, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
/** * @fileoverview Tests for strict rule. * @author Nicholas C. Zakas * @copyright 2013-2014 Nicholas C. Zakas. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), ESLintTester = require("../../../lib/testers/eslint-tester"); var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/strict", { valid: [ // "never" mode { code: "foo();", options: ["never"] }, { code: "function foo() { return; }", options: ["never"] }, { code: "var foo = function() { return; };", options: ["never"] }, { code: "foo(); 'use strict';", options: ["never"] }, { code: "function foo() { bar(); 'use strict'; return; }", options: ["never"] }, { code: "var foo = function() { { 'use strict'; } return; };", options: ["never"] }, { code: "(function() { bar('use strict'); return; }());", options: ["never"] }, { code: "var fn = x => 1;", ecmaFeatures: { arrowFunctions: true }, options: ["never"] }, { code: "var fn = x => { return; };", ecmaFeatures: { arrowFunctions: true }, options: ["never"] }, { code: "foo();", ecmaFeatures: { modules: true }, options: ["never"] }, // "global" mode { code: "// Intentionally empty", options: ["global"] }, { code: "\"use strict\"; foo();", options: ["global"] }, { code: "foo();", ecmaFeatures: { modules: true }, options: ["global"] }, { code: "'use strict'; function foo() { return; }", options: ["global"] }, { code: "'use strict'; var foo = function() { return; };", options: ["global"] }, { code: "'use strict'; function foo() { bar(); 'use strict'; return; }", options: ["global"] }, { code: "'use strict'; var foo = function() { bar(); 'use strict'; return; };", options: ["global"] }, { code: "'use strict'; function foo() { return function() { bar(); 'use strict'; return; }; }", options: ["global"] }, { code: "'use strict'; var foo = () => { return () => { bar(); 'use strict'; return; }; }", ecmaFeatures: { arrowFunctions: true }, options: ["global"] }, // "function" mode { code: "function foo() { 'use strict'; return; }", options: ["function"] }, { code: "function foo() { return; }", ecmaFeatures: { modules: true }, options: ["function"] }, { code: "var foo = function() { return; }", ecmaFeatures: { modules: true }, options: ["function"] }, { code: "var foo = function() { 'use strict'; return; }", options: ["function"] }, { code: "function foo() { 'use strict'; return; } var bar = function() { 'use strict'; bar(); };", options: ["function"] }, { code: "var foo = function() { 'use strict'; function bar() { return; } bar(); };", options: ["function"] }, { code: "var foo = () => { 'use strict'; var bar = () => 1; bar(); };", ecmaFeatures: { arrowFunctions: true }, options: ["function"] }, { code: "var foo = () => { var bar = () => 1; bar(); };", ecmaFeatures: { arrowFunctions: true, modules: true }, options: ["function"] }, { code: "class A { constructor() { } }", ecmaFeatures: { classes: true }, options: ["function"] }, { code: "class A { foo() { } }", ecmaFeatures: { classes: true }, options: ["function"] }, { code: "class A { foo() { function bar() { } } }", ecmaFeatures: { classes: true }, options: ["function"] }, // defaults to "function" mode { code: "function foo() { 'use strict'; return; }" } ], invalid: [ // "never" mode { code: "\"use strict\"; foo();", options: ["never"], errors: [ { message: "Strict mode is not permitted.", type: "ExpressionStatement" } ] }, { code: "function foo() { 'use strict'; return; }", options: ["never"], errors: [ { message: "Strict mode is not permitted.", type: "ExpressionStatement" } ] }, { code: "var foo = function() { 'use strict'; return; };", options: ["never"], errors: [ { message: "Strict mode is not permitted.", type: "ExpressionStatement" } ] }, { code: "function foo() { return function() { 'use strict'; return; }; }", options: ["never"], errors: [ { message: "Strict mode is not permitted.", type: "ExpressionStatement" } ] }, { code: "'use strict'; function foo() { \"use strict\"; return; }", options: ["never"], errors: [ { message: "Strict mode is not permitted.", type: "ExpressionStatement" }, { message: "Strict mode is not permitted.", type: "ExpressionStatement" } ] }, // "global" mode { code: "foo();", options: ["global"], errors: [ { message: "Use the global form of \"use strict\".", type: "Program" } ] }, { code: "function foo() { 'use strict'; return; }", options: ["global"], errors: [ { message: "Use the global form of \"use strict\".", type: "Program" }, { message: "Use the global form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "var foo = function() { 'use strict'; return; }", options: ["global"], errors: [ { message: "Use the global form of \"use strict\".", type: "Program" }, { message: "Use the global form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "var foo = () => { 'use strict'; return () => 1; }", options: ["global"], ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "Use the global form of \"use strict\".", type: "Program" }, { message: "Use the global form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "'use strict'; function foo() { 'use strict'; return; }", options: ["global"], errors: [ { message: "Use the global form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "'use strict'; var foo = function() { 'use strict'; return; };", options: ["global"], errors: [ { message: "Use the global form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "'use strict'; 'use strict'; foo();", options: ["global"], errors: [ { message: "Multiple \"use strict\" directives.", type: "ExpressionStatement" } ] }, { code: "'use strict'; foo();", options: ["global"], ecmaFeatures: { modules: true }, errors: [ { message: "\"use strict\" is unnecessary inside of modules.", type: "ExpressionStatement" } ] }, // "function" mode { code: "'use strict'; foo();", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "'use strict'; (function() { 'use strict'; return true; }());", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "ExpressionStatement" } ] }, { code: "(function() { 'use strict'; function f() { 'use strict'; return } return true; }());", options: ["function"], errors: [ { message: "Unnecessary \"use strict\" directive.", type: "ExpressionStatement" } ] }, { code: "(function() { return true; }());", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "FunctionExpression" } ] }, { code: "(() => { return true; })();", options: ["function"], ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "Use the function form of \"use strict\".", type: "ArrowFunctionExpression" } ] }, { code: "(() => true)();", options: ["function"], ecmaFeatures: { arrowFunctions: true }, errors: [ { message: "Use the function form of \"use strict\".", type: "ArrowFunctionExpression" } ] }, { code: "var foo = function() { foo(); 'use strict'; return; }; function bar() { foo(); 'use strict'; }", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "FunctionExpression" }, { message: "Use the function form of \"use strict\".", type: "FunctionDeclaration" } ] }, { code: "function foo() { 'use strict'; 'use strict'; return; }", options: ["function"], errors: [ { message: "Multiple \"use strict\" directives.", type: "ExpressionStatement" } ] }, { code: "var foo = function() { 'use strict'; 'use strict'; return; }", options: ["function"], errors: [ { message: "Multiple \"use strict\" directives.", type: "ExpressionStatement" } ] }, { code: "var foo = function() { 'use strict'; return; }", options: ["function"], ecmaFeatures: { modules: true }, errors: [ { message: "\"use strict\" is unnecessary inside of modules.", type: "ExpressionStatement" } ] }, { code: "function foo() { return function() { 'use strict'; return; }; }", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "FunctionDeclaration" } ] }, { code: "var foo = function() { function bar() { 'use strict'; return; } return; }", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "FunctionExpression" } ] }, { code: "function foo() { 'use strict'; return; } var bar = function() { return; };", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "FunctionExpression" } ] }, { code: "var foo = function() { 'use strict'; return; }; function bar() { return; };", options: ["function"], errors: [ { message: "Use the function form of \"use strict\".", type: "FunctionDeclaration" } ] }, { code: "function foo() { 'use strict'; return function() { 'use strict'; 'use strict'; return; }; }", options: ["function"], errors: [ { message: "Unnecessary \"use strict\" directive.", type: "ExpressionStatement" }, { message: "Multiple \"use strict\" directives.", type: "ExpressionStatement" } ] }, { code: "var foo = function() { 'use strict'; function bar() { 'use strict'; 'use strict'; return; } }", options: ["function"], errors: [ { message: "Unnecessary \"use strict\" directive.", type: "ExpressionStatement" }, { message: "Multiple \"use strict\" directives.", type: "ExpressionStatement" } ] }, { code: "var foo = () => { return; };", ecmaFeatures: { arrowFunctions: true }, options: ["function"], errors: [{ message: "Use the function form of \"use strict\".", type: "ArrowFunctionExpression"}] }, // Classes { code: "class A { constructor() { \"use strict\"; } }", ecmaFeatures: { classes: true }, options: ["function"], errors: [{ message: "\"use strict\" is unnecessary inside of classes.", type: "ExpressionStatement"}] }, { code: "class A { foo() { \"use strict\"; } }", ecmaFeatures: { classes: true }, options: ["function"], errors: [{ message: "\"use strict\" is unnecessary inside of classes.", type: "ExpressionStatement"}] }, { code: "class A { foo() { function bar() { \"use strict\"; } } }", ecmaFeatures: { classes: true }, options: ["function"], errors: [{ message: "\"use strict\" is unnecessary inside of classes.", type: "ExpressionStatement"}] }, // Default to "function" mode { code: "'use strict'; function foo() { return; }", errors: [ { message: "Use the function form of \"use strict\".", type: "ExpressionStatement" }, { message: "Use the function form of \"use strict\".", type: "FunctionDeclaration" } ] }, { code: "function foo() { return; }", errors: [{ message: "Use the function form of \"use strict\".", type: "FunctionDeclaration" }] } ] });
'use strict'; var Message = require('../message'); var inherits = require('util').inherits; var bitcore = require('bitcore-lib'); var $ = bitcore.util.preconditions; var _ = bitcore.deps._; /** * @param {Block=} arg - An instance of a Block * @param {Object} options * @param {Function} options.Block - A block constructor * @extends Message * @constructor */ function BlockMessage(arg, options) { Message.call(this, options); this.Block = options.Block; this.command = 'block'; $.checkArgument( _.isUndefined(arg) || arg instanceof this.Block, 'An instance of Block or undefined is expected' ); this.block = arg; } inherits(BlockMessage, Message); BlockMessage.prototype.setPayload = function(payload) { if (this.Block.prototype.fromRaw) { this.block = this.Block.fromRaw(payload); } else { this.block = this.Block.fromBuffer(payload); } }; BlockMessage.prototype.getPayload = function() { if (this.Block.prototype.toRaw) { return this.block.toRaw(); } return this.block.toBuffer(); }; module.exports = BlockMessage;
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.0.14 (2019-08-19) */ !function(o){"use strict";var i=tinymce.util.Tools.resolve("tinymce.PluginManager");!function n(){i.add("textcolor",function(){o.console.warn("Text color plugin is now built in to the core editor, please remove it from your editor configuration")})}()}(window);
// Generated by CoffeeScript 1.8.0 module.exports = function(tasks, callback) { var next, result; tasks = tasks.slice(0); next = function(cb) { var task; if (tasks.length === 0) { return cb(); } task = tasks.shift(); return task(function() { return next(cb); }); }; result = function(cb) { return next(cb); }; if (callback != null) { result(callback); } return result; };
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import * as React from 'react'; import { isFragment } from 'react-is'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export const styles = { /* Styles applied to the root element. */ root: {}, /* Styles applied to the root element if `orientation="horizontal"`. */ horizontal: { paddingLeft: 8, paddingRight: 8 }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: {}, /* Styles applied to the root element if `alternativeLabel={true}`. */ alternativeLabel: { flex: 1, position: 'relative' }, /* Pseudo-class applied to the root element if `completed={true}`. */ completed: {} }; const Step = React.forwardRef(function Step(props, ref) { const { active = false, // eslint-disable-next-line react/prop-types alternativeLabel, children, classes, className, completed = false, // eslint-disable-next-line react/prop-types connector, disabled = false, expanded = false, // eslint-disable-next-line react/prop-types index, // eslint-disable-next-line react/prop-types last, // eslint-disable-next-line react/prop-types orientation } = props, other = _objectWithoutPropertiesLoose(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "connector", "disabled", "expanded", "index", "last", "orientation"]); return /*#__PURE__*/React.createElement("div", _extends({ className: clsx(classes.root, classes[orientation], className, alternativeLabel && classes.alternativeLabel, completed && classes.completed), ref: ref }, other), connector && alternativeLabel && index !== 0 && React.cloneElement(connector, { orientation, alternativeLabel, index, active, completed, disabled }), React.Children.map(children, child => { if (!React.isValidElement(child)) { return null; } if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: The Step component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } return React.cloneElement(child, _extends({ active, alternativeLabel, completed, disabled, expanded, last, icon: index + 1, orientation }, child.props)); })); }); process.env.NODE_ENV !== "production" ? Step.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * Sets the step as active. Is passed to child components. */ active: PropTypes.bool, /** * Should be `Step` sub-components such as `StepLabel`, `StepContent`. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * Mark the step as completed. Is passed to child components. */ completed: PropTypes.bool, /** * Mark the step as disabled, will also disable the button if * `StepButton` is a child of `Step`. Is passed to child components. */ disabled: PropTypes.bool, /** * Expand the step. */ expanded: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiStep' })(Step);
/* * Copyright (c) 2011, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ AsyncTestCase("BusListenerTest", { _setUp: ondeviceready(function(callback) { bus = new org.alljoyn.bus.BusAttachment(); bus.create(false, callback); }), tearDown: function() { bus.destroy(); }, testRegisteredUnregistered: function(queue) { queue.call(function(callbacks) { var registerBusListener = function(err) { assertFalsy(err); var busListener = { onRegistered: callbacks.add(function(busAttachment) { bus.unregisterBusListener(busListener, callbacks.add(function(err) { assertFalsy(err); })); }), onUnregistered: callbacks.add(function() { }) }; bus.registerBusListener(busListener, callbacks.add(done)); }; var done = function(err) { assertFalsy(err); }; this._setUp(callbacks.add(registerBusListener)); }); }, testStoppingDisconnected: function(queue) { queue.call(function(callbacks) { var registerBusListener = function(err) { assertFalsy(err); var busListener = { onStopping: callbacks.add(function() { }), onDisconnected: callbacks.add(function() { }) }; bus.registerBusListener(busListener, callbacks.add(connect)); }; var connect = function(err) { assertFalsy(err); bus.connect(callbacks.add(disconnect)); }; var disconnect = function(err) { assertFalsy(err); bus.disconnect(callbacks.add(done)); }; var done = function(err) { assertFalsy(err); }; this._setUp(callbacks.add(registerBusListener)); }); }, testFoundLostAdvertisedName: function(queue) { queue.call(function(callbacks) { var registerBusListener = function(err) { assertFalsy(err); var busListener = { onFoundAdvertisedName: callbacks.add(function(name, transport, namePrefix) { assertEquals("org.alljoyn.testName", name); assertEquals(1, transport); assertEquals("org.alljoyn.testName", namePrefix); bus.cancelAdvertiseName("org.alljoyn.testName", 0xffff, callbacks.add(function(err) { assertFalsy(err); })); }), onLostAdvertisedName: callbacks.add(function(name, transport, namePrefix) { assertEquals("org.alljoyn.testName", name); assertEquals(1, transport); assertEquals("org.alljoyn.testName", namePrefix); bus.releaseName("org.alljoyn.testName", callbacks.add(function(err) { assertFalsy(err); })); }) }; bus.registerBusListener(busListener, callbacks.add(connect)); }; var connect = function(err) { assertFalsy(err); bus.connect(callbacks.add(requestName)); }; var requestName = function(err) { assertFalsy(err); bus.requestName("org.alljoyn.testName", 0, callbacks.add(advertiseName)); }; var advertiseName = function(err) { assertFalsy(err); bus.advertiseName("org.alljoyn.testName", 0xffff, callbacks.add(findAdvertisedName)); }; var findAdvertisedName = function(err) { assertFalsy(err); bus.findAdvertisedName("org.alljoyn.testName", callbacks.add(done)); }; var done = function(err) { assertFalsy(err); }; this._setUp(callbacks.add(registerBusListener)); }); }, testNameOwnerChanged: function(queue) { queue.call(function(callbacks) { var registerBusListener = function(err) { assertFalsy(err); var busListener = { onNameOwnerChanged: callbacks.add(function(busName, previousOwner, newOwner) { assertEquals("org.alljoyn.bus.BusListenerTest", busName); }), }; bus.registerBusListener(busListener, callbacks.add(connect)); }; var connect = function(err) { assertFalsy(err); bus.connect(callbacks.add(getProxyObj)); }; var getProxyObj = function(err) { assertFalsy(err); bus.getProxyBusObject("org.freedesktop.DBus/org/freedesktop/DBus", callbacks.add(requestName)); }; var requestName = function(err, dbus) { assertFalsy(err); /* Trigger the onNameOwnerChanged callback by requesting a well-known name. */ dbus.methodCall("org.freedesktop.DBus", "RequestName", "org.alljoyn.bus.BusListenerTest", 0, callbacks.add(onRequestName)); }; var onRequestName = function(err, context, result) { assertFalsy(err); assertEquals(1, result); }; this._setUp(callbacks.add(registerBusListener)); }); }, });
var fs = require('q-io/fs'); /** * @dgService writeFile * @description * Write the given contents to a file, ensuring the path to the file exists */ module.exports = function writeFile() { return function(file, content) { return fs.makeTree(fs.directory(file)).then(function() { return fs.write(file, content, 'wb'); }); }; };
import {h, Component} from 'preact/preact'; import ContentTimeline from 'com/content-timeline/timeline'; export default class PageRootFeedNews extends Component { render( props ) { let {node, user, path, extra} = props; return ( <ContentTimeline class="content-timeline-news" types={['post']} subtypes={['news']} methods={['all']} node={node} user={user} path={path} extra={extra} /> ); } }
var assert = require('assert'); var path = require('path'); var levelup = require('levelup'); var memdown = require('memdown'); var PeerRegistry = require('../lib/peer_registry'); var Query = require('calypso').Query; var dbPath = path.join(__dirname, './.peers'); describe('Peer Registry', function() { var db, opts; beforeEach(function(done) { db = levelup(dbPath, { db: memdown }); opts = { db: db, collection: 'peers' }; done(); }); afterEach(function(done) { if (db) { db.close(done); } }); it('should save a peer', function(done) { var reg = new PeerRegistry(opts); reg.save({ id: 0 }, function(err) { assert.ifError(err); done(); }); }); it('should remove error property on peer save when status is not failed', function(done) { var reg = new PeerRegistry(opts); reg.save({ id: 0, error: new Error() }, function() { reg.get(0, function(err, result) { assert.equal(result.error, undefined); done(); }); }); }) it('should find multiple peers', function(done) { var reg = new PeerRegistry(opts); reg.save({ id: 0 }, function() { reg.save({ id: 1 }, function() { var query = Query.of('peers'); reg.find(query, function(err, results) { assert.equal(results.length, 2); done(); }); }); }); }); it('should get peers by id', function(done) { var reg = new PeerRegistry(opts); reg.save({ id: 012345 }, function() { reg.get(012345, function(err, peer) { assert(peer); done(); }); }); }); it('should delete peers', function(done) { var reg = new PeerRegistry(opts); var peer = { id: 0123456 }; reg.save(peer, function() { reg.remove(peer, function(err, peer) { assert.ifError(err); done(); }); }); }); it('should close', function(done) { var reg = new PeerRegistry(opts); reg.close(function(err) { assert.ifError(err); done(); }); }); describe('#add', function() { it('should save new peers', function(done) { var reg = new PeerRegistry(opts); var peer = {id: 'someid'}; reg.add(peer, function(err, result) { assert.ok(result); done(); }); }); it('should generate an ID for new peers', function(done) { var reg = new PeerRegistry(opts); var peer = {id: 'someid'}; reg.add(peer, function(err, result) { assert.ok(result.id); done(); }); }); it('should update existing peers', function(done) { var reg = new PeerRegistry(opts); var peer = { id: 012345 }; reg.save(peer, function() { reg.add(peer, function(err, result) { assert.equal(result.id, peer.id); done(); }); }); }); it('propagates errors from #find', function(done) { var reg = new PeerRegistry(opts); var peer = {id: 'someid'}; reg.find = function(key, cb) { cb(new Error()); }; reg.add(peer, function(err, result) { assert.ok(err); done(); }); }); it('propagates errors from #save', function(done) { var reg = new PeerRegistry(opts); var peer = {}; reg.save = function(key, cb) { cb(new Error()); }; reg.add(peer, function(err, result) { assert.ok(err); done(); }); }); it('it should not match entries when both .url are undefined or null', function(done) { var reg = new PeerRegistry(opts); var peer1 = { id: 'some-peer-1'}; var peer2 = { id: 'some-peer-2'}; reg.add(peer1, function(err, result1) { assert.ok(result1.id); reg.add(peer2, function(err, result2) { assert.ok(result2.id); assert.ok(result1.id !== result2.id, 'should create two unique peers') done(); }); }); }); }); });
'use strict'; // Refs: https://github.com/nodejs/node/issues/5832 require('../common'); const url = require('url'); const assert = require('assert'); const fixtures = require('../common/fixtures'); const tests = require( fixtures.path('wpt', 'url', 'resources', 'urltestdata.json') ); let failed = 0; let attempted = 0; tests.forEach((test) => { attempted++; // Skip comments if (typeof test === 'string') return; let parsed; try { // Attempt to parse parsed = url.parse(url.resolve(test.base, test.input)); if (test.failure) { // If the test was supposed to fail and we didn't get an // error, treat it as a failure. failed++; } else { // Test was not supposed to fail, so we're good so far. Now // check the results of the parse. let username, password; try { assert.strictEqual(test.href, parsed.href); assert.strictEqual(test.protocol, parsed.protocol); username = parsed.auth ? parsed.auth.split(':', 2)[0] : ''; password = parsed.auth ? parsed.auth.split(':', 2)[1] : ''; assert.strictEqual(test.username, username); assert.strictEqual(test.password, password); assert.strictEqual(test.host, parsed.host); assert.strictEqual(test.hostname, parsed.hostname); assert.strictEqual(+test.port, +parsed.port); assert.strictEqual(test.pathname, parsed.pathname || '/'); assert.strictEqual(test.search, parsed.search || ''); assert.strictEqual(test.hash, parsed.hash || ''); } catch { // For now, we're just interested in the number of failures. failed++; } } } catch { // If Parse failed and it wasn't supposed to, treat it as a failure. if (!test.failure) failed++; } }); assert.ok(failed === 0, `${failed} failed tests (out of ${attempted})`);
/* * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com> * * This file is licensed under the Affero General Public License version 3 * or later. * * See the COPYING-README file. * */ describe('OCA.Sharing.Util tests', function() { var oldFileListPrototype; var fileList; var testFiles; function getImageUrl($el) { // might be slightly different cross-browser var url = $el.css('background-image'); var r = url.match(/url\(['"]?([^'")]*)['"]?\)/); if (!r) { return url; } return r[1]; } beforeEach(function() { // back up prototype, as it will be extended by // the sharing code oldFileListPrototype = _.extend({}, OCA.Files.FileList.prototype); var $content = $('<div id="content"></div>'); $('#testArea').append($content); // dummy file list var $div = $( '<div>' + '<table id="filestable">' + '<thead></thead>' + '<tbody id="fileList"></tbody>' + '</table>' + '</div>'); $('#content').append($div); var fileActions = new OCA.Files.FileActions(); OCA.Sharing.Util.initialize(fileActions); fileList = new OCA.Files.FileList( $div, { fileActions : fileActions } ); testFiles = [{ id: 1, type: 'file', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc', shareOwner: 'User One', isShareMountPoint: false }]; OCA.Sharing.sharesLoaded = true; OC.Share.statuses = { 1: {link: false, path: '/subdir'} }; }); afterEach(function() { OCA.Files.FileList.prototype = oldFileListPrototype; delete OCA.Sharing.sharesLoaded; delete OC.Share.droppedDown; fileList.destroy(); fileList = null; OC.Share.statuses = {}; OC.Share.currentShares = {}; }); describe('Sharing data in table row', function() { // TODO: test data-permissions, data-share-owner, etc }); describe('Share action icon', function() { beforeEach(function() { OC.Share.statuses = {1: {link: false, path: '/subdir'}}; OCA.Sharing.sharesLoaded = true; }); afterEach(function() { OC.Share.statuses = {}; OCA.Sharing.sharesLoaded = false; }); it('do not shows share text when not shared', function() { var $action, $tr; OC.Share.statuses = {}; fileList.setFiles([{ id: 1, type: 'dir', name: 'One', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc' }]); $tr = fileList.$el.find('tbody tr:first'); $action = $tr.find('.action-share'); expect($action.hasClass('permanent')).toEqual(false); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); expect(OC.basename(getImageUrl($tr.find('.filename')))).toEqual('folder.svg'); expect($action.find('img').length).toEqual(1); }); it('shows simple share text with share icon', function() { var $action, $tr; fileList.setFiles([{ id: 1, type: 'dir', name: 'One', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc' }]); $tr = fileList.$el.find('tbody tr:first'); $action = $tr.find('.action-share'); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('Shared'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); expect(OC.basename(getImageUrl($tr.find('.filename')))).toEqual('folder-shared.svg'); expect($action.find('img').length).toEqual(1); }); it('shows simple share text with public icon when shared with link', function() { var $action, $tr; OC.Share.statuses = {1: {link: true, path: '/subdir'}}; fileList.setFiles([{ id: 1, type: 'dir', name: 'One', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc' }]); $tr = fileList.$el.find('tbody tr:first'); $action = $tr.find('.action-share'); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('Shared'); expect(OC.basename($action.find('img').attr('src'))).toEqual('public.svg'); expect(OC.basename(getImageUrl($tr.find('.filename')))).toEqual('folder-public.svg'); expect($action.find('img').length).toEqual(1); }); it('shows owner name when owner is available', function() { var $action, $tr; fileList.setFiles([{ id: 1, type: 'dir', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, shareOwner: 'User One', etag: 'abc' }]); $tr = fileList.$el.find('tbody tr:first'); $action = $tr.find('.action-share'); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('User One'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); expect(OC.basename(getImageUrl($tr.find('.filename')))).toEqual('folder-shared.svg'); }); it('shows recipients when recipients are available', function() { var $action, $tr; fileList.setFiles([{ id: 1, type: 'dir', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, recipientsDisplayName: 'User One, User Two', etag: 'abc' }]); $tr = fileList.$el.find('tbody tr:first'); $action = $tr.find('.action-share'); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('Shared with User One, User Two'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); expect(OC.basename(getImageUrl($tr.find('.filename')))).toEqual('folder-shared.svg'); expect($action.find('img').length).toEqual(1); }); it('shows static share text when file shared with user that has no share permission', function() { var $action, $tr; fileList.setFiles([{ id: 1, type: 'dir', name: 'One', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_CREATE, etag: 'abc', shareOwner: 'User One' }]); $tr = fileList.$el.find('tbody tr:first'); expect($tr.find('.action-share').length).toEqual(0); $action = $tr.find('.action-share-notification'); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text().trim()).toEqual('User One'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); expect(OC.basename(getImageUrl($tr.find('.filename')))).toEqual('folder-shared.svg'); expect($action.find('img').length).toEqual(1); }); }); describe('Share action', function() { var showDropDownStub; function makeDummyShareItem(displayName) { return { share_with_displayname: displayName }; } beforeEach(function() { showDropDownStub = sinon.stub(OC.Share, 'showDropDown', function() { $('#testArea').append($('<div id="dropdown"></div>')); }); }); afterEach(function() { showDropDownStub.restore(); }); it('adds share icon after sharing a non-shared file', function() { var $action, $tr; OC.Share.statuses = {}; fileList.setFiles([{ id: 1, type: 'file', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc' }]); $action = fileList.$el.find('tbody tr:first .action-share'); $tr = fileList.$el.find('tr:first'); expect($action.hasClass('permanent')).toEqual(false); $tr.find('.action-share').click(); expect(showDropDownStub.calledOnce).toEqual(true); // simulate what the dropdown does var shares = {}; OC.Share.itemShares[OC.Share.SHARE_TYPE_USER] = ['user1', 'user2']; OC.Share.itemShares[OC.Share.SHARE_TYPE_GROUP] = ['group1', 'group2']; shares[OC.Share.SHARE_TYPE_USER] = _.map(['User One', 'User Two'], makeDummyShareItem); shares[OC.Share.SHARE_TYPE_GROUP] = _.map(['Group One', 'Group Two'], makeDummyShareItem); $('#dropdown').trigger(new $.Event('sharesChanged', {shares: shares})); expect($tr.attr('data-share-recipients')).toEqual('Group One, Group Two, User One, User Two'); OC.Share.updateIcon('file', 1); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('Shared with Group One, Group Two, User One, User Two'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); }); it('updates share icon after updating shares of a file', function() { var $action, $tr; OC.Share.statuses = {1: {link: false, path: '/subdir'}}; fileList.setFiles([{ id: 1, type: 'file', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc' }]); $action = fileList.$el.find('tbody tr:first .action-share'); $tr = fileList.$el.find('tr:first'); expect($action.hasClass('permanent')).toEqual(true); $tr.find('.action-share').click(); expect(showDropDownStub.calledOnce).toEqual(true); // simulate what the dropdown does var shares = {}; OC.Share.itemShares[OC.Share.SHARE_TYPE_USER] = ['user1', 'user2', 'user3']; shares[OC.Share.SHARE_TYPE_USER] = _.map(['User One', 'User Two', 'User Three'], makeDummyShareItem); $('#dropdown').trigger(new $.Event('sharesChanged', {shares: shares})); expect($tr.attr('data-share-recipients')).toEqual('User One, User Three, User Two'); OC.Share.updateIcon('file', 1); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('Shared with User One, User Three, User Two'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); }); it('removes share icon after removing all shares from a file', function() { var $action, $tr; OC.Share.statuses = {1: {link: false, path: '/subdir'}}; fileList.setFiles([{ id: 1, type: 'file', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc', recipients: 'User One, User Two' }]); $action = fileList.$el.find('tbody tr:first .action-share'); $tr = fileList.$el.find('tr:first'); expect($action.hasClass('permanent')).toEqual(true); $tr.find('.action-share').click(); expect(showDropDownStub.calledOnce).toEqual(true); // simulate what the dropdown does OC.Share.itemShares = {}; $('#dropdown').trigger(new $.Event('sharesChanged', {shares: {}})); expect($tr.attr('data-share-recipients')).not.toBeDefined(); OC.Share.updateIcon('file', 1); expect($action.hasClass('permanent')).toEqual(false); }); it('keep share text after updating reshare', function() { var $action, $tr; OC.Share.statuses = {1: {link: false, path: '/subdir'}}; fileList.setFiles([{ id: 1, type: 'file', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc', shareOwner: 'User One' }]); $action = fileList.$el.find('tbody tr:first .action-share'); $tr = fileList.$el.find('tr:first'); expect($action.hasClass('permanent')).toEqual(true); $tr.find('.action-share').click(); expect(showDropDownStub.calledOnce).toEqual(true); // simulate what the dropdown does var shares = {}; OC.Share.itemShares[OC.Share.SHARE_TYPE_USER] = ['user2']; shares[OC.Share.SHARE_TYPE_USER] = _.map(['User Two'], makeDummyShareItem); $('#dropdown').trigger(new $.Event('sharesChanged', {shares: shares})); expect($tr.attr('data-share-recipients')).toEqual('User Two'); OC.Share.updateIcon('file', 1); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('User One'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); }); it('keep share text after unsharing reshare', function() { var $action, $tr; OC.Share.statuses = {1: {link: false, path: '/subdir'}}; fileList.setFiles([{ id: 1, type: 'file', name: 'One.txt', path: '/subdir', mimetype: 'text/plain', size: 12, permissions: OC.PERMISSION_ALL, etag: 'abc', shareOwner: 'User One', recipients: 'User Two' }]); $action = fileList.$el.find('tbody tr:first .action-share'); $tr = fileList.$el.find('tr:first'); expect($action.hasClass('permanent')).toEqual(true); $tr.find('.action-share').click(); expect(showDropDownStub.calledOnce).toEqual(true); // simulate what the dropdown does OC.Share.itemShares = {}; $('#dropdown').trigger(new $.Event('sharesChanged', {shares: {}})); expect($tr.attr('data-share-recipients')).not.toBeDefined(); OC.Share.updateIcon('file', 1); expect($action.hasClass('permanent')).toEqual(true); expect($action.find('>span').text()).toEqual('User One'); expect(OC.basename($action.find('img').attr('src'))).toEqual('share.svg'); }); }); describe('formatRecipients', function() { it('returns a single recipient when one passed', function() { expect(OCA.Sharing.Util.formatRecipients(['User one'])) .toEqual('User one'); }); it('returns two recipients when two passed', function() { expect(OCA.Sharing.Util.formatRecipients(['User one', 'User two'])) .toEqual('User one, User two'); }); it('returns four recipients with plus when five passed', function() { var recipients = [ 'User one', 'User two', 'User three', 'User four', 'User five' ]; expect(OCA.Sharing.Util.formatRecipients(recipients)) .toEqual('User four, User one, User three, User two, +1'); }); it('returns four recipients with plus when ten passed', function() { var recipients = [ 'User one', 'User two', 'User three', 'User four', 'User five', 'User six', 'User seven', 'User eight', 'User nine', 'User ten' ]; expect(OCA.Sharing.Util.formatRecipients(recipients)) .toEqual('User four, User one, User three, User two, +6'); }); it('returns four recipients with plus when four passed with counter', function() { var recipients = [ 'User one', 'User two', 'User three', 'User four' ]; expect(OCA.Sharing.Util.formatRecipients(recipients, 10)) .toEqual('User four, User one, User three, User two, +6'); }); }); });
this.Triggers = (function() { var triggers = []; var initiated = false; var requests = []; var fire = function(actions) { if (Meteor.userId()) { console.log('already logged user - does nothing'); return; } actions.forEach(function(action) { if (action.name === 'send-message') { var roomId = visitor.getRoom(); if (!roomId) { roomId = Random.id(); visitor.setRoom(roomId); } Session.set('triggered', true); ChatMessage.insert({ msg: action.params.msg, rid: roomId, u: { username: action.params.name } }); parentCall('openWidget'); } }); }; var processRequest = function(request) { if (!initiated) { return requests.push(request); } triggers.forEach(function(trigger) { trigger.conditions.forEach(function(condition) { switch (condition.name) { case 'page-url': if (request.location.href.match(new RegExp(condition.value))) { fire(trigger.actions); } break; case 'time-on-site': if (trigger.timeout) { clearTimeout(trigger.timeout); } trigger.timeout = setTimeout(function() { fire(trigger.actions); }, parseInt(condition.value) * 1000); break; } }); }); }; var init = function() { initiated = true; Tracker.autorun(function() { triggers = Trigger.find().fetch(); if (requests.length > 0 && triggers.length > 0) { requests.forEach(function(request) { processRequest(request); }); requests = []; } }); }; return { init: init, processRequest: processRequest }; }());
var fs = require('fs') var test = require('tape') var postcss = require('postcss') var plugin = require('..') function filename(name) { return 'test/' + name + '.css' } function read(name) { return fs.readFileSync(name, 'utf8') } function compareFixtures(t, name, msg, opts, postcssOpts) { postcssOpts = postcssOpts || {} postcssOpts.from = filename('fixtures/' + name) opts = opts || {} var actual = postcss().use(plugin).process(read(postcssOpts.from), postcssOpts).css var expected = read(filename('fixtures/' + name + '-out')) fs.writeFile(filename('fixtures/' + name + '-real'), actual) t.equal(actual.trim(), expected.trim(), msg) } test('remove display', function(t) { compareFixtures(t, 'remove-display', 'Should be remove display property') t.end() }) test('remove colons', function(t) { compareFixtures(t, 'remove-colons', 'Should be remove colons') t.end() }) test('position center mixin', function(t) { compareFixtures(t, 'position-center', 'Should be transform') t.end() }) test('ellipsis mixin', function(t) { compareFixtures(t, 'ellipsis', 'Should be transform') t.end() }) test('resize mixin', function(t) { compareFixtures(t, 'resize', 'Should be transform') t.end() }) test('clearfix mixin', function(t) { compareFixtures(t, 'clearfix', 'Should be transform') t.end() }) test('IE opacity hack', function(t) { compareFixtures(t, 'ie-opacity', 'Should be added filter') t.end() }) test('IE rgba hack', function(t) { compareFixtures(t, 'bg-rgba', 'Should be added filter and :root selector') t.end() }) test('inline-block hack', function(t) { compareFixtures(t, 'inline-block', 'Should be added *display: inline and *zoom: 1') t.end() }) test('image set mixin', function(t) { compareFixtures(t, 'image-set', 'Should be transform') t.end() }) test('image size', function(t) { compareFixtures(t, 'image-size', 'Should be transform') t.end() }) test('comment', function(t) { compareFixtures(t, 'comment', 'Should be keep the comments on the current line') t.end() }) test('image-size-multiple', function(t) { compareFixtures(t, 'image-size-multiple', 'Should be transform') t.end() }) test('base64-image-size', function (t) { compareFixtures(t, 'base64-image-size', 'Should be transform') t.end(); }); test('hash', function (t) { compareFixtures(t, 'hash', 'Should be remove hash') t.end(); })
/* eslint-disable max-len */ /* eslint-disable prefer-destructuring */ /* eslint-disable camelcase */ /* eslint-disable no-undef */ const rollCombatDistance = ['pSDistance', 'mEDistance', 'repeating_armeDist:armedistance', 'repeating_armeDistVehicule:armedistance']; rollCombatDistance.forEach((button) => { on(`clicked:${button}`, async (info) => { const roll = info.htmlAttributes.value; let firstExec = []; let exec = []; firstExec.push(roll); let hasArmure = true; let listAttrs = [ 'espoir', 'energiePJ', 'force', 'discretion', `${ODValue.discretion}`, 'dexterite', `${ODValue.dexterite}`, 'tir', `${ODValue.tir}`, 'devasterAnatheme', 'bourreauTenebres', 'equilibreBalance', ]; listAttrs = listAttrs.concat(listArmure, listArmureLegende, listStyle, listBase); let prefix = ''; let id = ''; let name = ''; let portee = ''; let dEffets = []; let dEffetsValue = []; let AA = []; let AAValue = []; let special = []; let specialValue = []; let baseDegats = 0; let baseViolence = 0; let diceDegats = 0; let diceViolence = 0; let bDegats = []; const bViolence = []; switch (button) { case 'pSDistance': name = i18n_pistoletService; prefix = 'pS'; dEffets = wpnEffects.map((a) => `${prefix}${a}`); dEffetsValue = wpnEffectsValue.map((a) => `${prefix}${a}`); AA = wpnAmeliorationA.map((a) => `${prefix}${a}`); AAValue = wpnAmeliorationAValue.map((a) => `${prefix}${a}`); special = wpnSpecial.map((a) => `${prefix}${a}`); specialValue = wpnSpecialValue.map((a) => `${prefix}${a}`); listAttrs.push('pScaracteristique1Equipement'); listAttrs.push('pScaracteristique2Equipement'); listAttrs.push('pScaracteristique3Equipement'); listAttrs.push('pScaracteristique4Equipement'); listAttrs.push('pSpilonnage'); listAttrs.push('pSpilonnageType'); baseDegats = 2; baseViolence = 1; diceDegats = 2; bDegats.push(6); diceViolence = 1; bViolence.push(0); listAttrs = listAttrs.concat(dEffets, dEffetsValue, AA, AAValue, special, specialValue); break; case 'mEDistance': name = i18n_marteauEpieuD; prefix = 'mE'; dEffets = wpnEffects.map((a) => `${prefix}${a}`); dEffetsValue = wpnEffectsValue.map((a) => `${prefix}${a}`); AA = wpnAmeliorationA.map((a) => `${prefix}${a}`); AAValue = wpnAmeliorationAValue.map((a) => `${prefix}${a}`); special = wpnSpecial.map((a) => `${prefix}${a}`); specialValue = wpnSpecialValue.map((a) => `${prefix}${a}`); listAttrs.push('mEcaracteristique1Equipement'); listAttrs.push('mEcaracteristique2Equipement'); listAttrs.push('mEcaracteristique3Equipement'); listAttrs.push('mEcaracteristique4Equipement'); listAttrs.push('mEpilonnage'); listAttrs.push('mEpilonnageType'); baseDegats = 3; baseViolence = 3; diceDegats = 3; bDegats.push(12); diceViolence = 3; bViolence.push(12); listAttrs = listAttrs.concat(dEffets, dEffetsValue, AA, AAValue, special, specialValue); break; case 'repeating_armeDist:armedistance': id = info.triggerName.split('_')[2]; prefix = `repeating_armeDist_${id}_`; dEffets = wpnEffects.map((a) => `${prefix}${a}`); dEffetsValue = wpnEffectsValue.map((a) => `${prefix}${a}`); AA = wpnAmeliorationA.map((a) => `${prefix}${a}`); AAValue = wpnAmeliorationAValue.map((a) => `${prefix}${a}`); special = wpnSpecial.map((a) => `${prefix}${a}`); specialValue = wpnSpecialValue.map((a) => `${prefix}${a}`); listAttrs.push(`${prefix}caracteristique1Equipement`); listAttrs.push(`${prefix}caracteristique2Equipement`); listAttrs.push(`${prefix}caracteristique3Equipement`); listAttrs.push(`${prefix}caracteristique4Equipement`); listAttrs.push(`${prefix}pilonnage`); listAttrs.push(`${prefix}pilonnageType`); listAttrs.push(`${prefix}ArmeDist`); listAttrs.push(`${prefix}armeDistPortee`); listAttrs.push(`${prefix}armeDistDegat`); listAttrs.push(`${prefix}armeDistViolence`); listAttrs.push(`${prefix}armeDistBDegat`); listAttrs.push(`${prefix}armeDistBViolence`); listAttrs = listAttrs.concat(dEffets, dEffetsValue, AA, AAValue, special, specialValue); break; case 'repeating_armeDistVehicule:armedistance': id = info.triggerName.split('_')[2]; prefix = `repeating_armeDistVehicule_${id}_`; dEffets = wpnEffects.map((a) => `${prefix}${a}`); dEffetsValue = wpnEffectsValue.map((a) => `${prefix}${a}`); AA = wpnAmeliorationA.map((a) => `${prefix}${a}`); AAValue = wpnAmeliorationAValue.map((a) => `${prefix}${a}`); special = wpnSpecial.map((a) => `${prefix}${a}`); specialValue = wpnSpecialValue.map((a) => `${prefix}${a}`); listAttrs.push(`${prefix}caracteristique1Equipement`); listAttrs.push(`${prefix}caracteristique2Equipement`); listAttrs.push(`${prefix}caracteristique3Equipement`); listAttrs.push(`${prefix}caracteristique4Equipement`); listAttrs.push(`${prefix}pilonnage`); listAttrs.push(`${prefix}pilonnageType`); listAttrs.push(`${prefix}ArmeDist`); listAttrs.push(`${prefix}armeDistPortee`); listAttrs.push(`${prefix}armeDistDegat`); listAttrs.push(`${prefix}armeDistViolence`); listAttrs.push(`${prefix}armeDistBDegat`); listAttrs.push(`${prefix}armeDistBViolence`); listAttrs = listAttrs.concat(dEffets, dEffetsValue, AA, AAValue, special, specialValue); break; default: name = ''; prefix = ''; dEffets = []; dEffetsValue = []; AA = []; AAValue = []; special = []; specialValue = []; baseDegats = 0; baseViolence = 0; diceDegats = 0; bDegats.push(0); diceViolence = 0; bViolence.push(0); listAttrs = listAttrs.concat(dEffets, dEffetsValue, AA, AAValue, special, specialValue); break; } const attrs = await getAttrsAsync(listAttrs); const armure = attrs.armure; const armureL = attrs.armureLegende; if (button === 'repeating_armeDist:armedistance' || button === 'repeating_armeDistVehicule:armedistance') { name = attrs[`${prefix}ArmeDist`] || ''; portee = attrs[`${prefix}armeDistPortee`] || '^{portee-contact}'; exec.push(`{{special1=${name}}}`); exec.push(`{{portee=^{portee} ${portee}}}`); baseDegats = Number(attrs[`${prefix}armeDistDegat`]) || 0; baseViolence = Number(attrs[`${prefix}armeDistViolence`]) || 0; diceDegats = Number(attrs[`${prefix}armeDistDegat`]) || 0; bDegats.push(Number(attrs[`${prefix}armeDistBDegat`]) || 0); diceViolence = Number(attrs[`${prefix}armeDistViolence`]) || 0; bViolence.push(Number(attrs[`${prefix}armeDistBViolence`]) || 0); } const C1 = attrs[`${prefix}caracteristique1Equipement`] || '0'; const C2 = attrs[`${prefix}caracteristique2Equipement`] || '0'; const C3 = attrs[`${prefix}caracteristique3Equipement`] || '0'; const C4 = attrs[`${prefix}caracteristique4Equipement`] || '0'; const vPilonnage = attrs[`${prefix}pilonnage`] || 0; const vPilonnageType = attrs[`${prefix}pilonnageType`] || 0; if (armure === 'sans' || armure === 'guardian') { hasArmure = false; } let isConditionnelA = false; let isConditionnelD = false; let isConditionnelV = false; const cBase = []; const cBonus = []; let cRoll = []; let bonus = []; let OD = 0; const mod = +attrs.jetModifDes; const hasBonus = attrs.bonusCarac; let degats = []; let violence = []; const attrsCarac = await getCarac(hasBonus, C1, C2, C3, C4); let ODBarbarian = []; let ODMALBarbarian = []; let ODShaman = []; let ODMALShaman = []; const ODWarrior = []; const ODMALWarrior = []; const vForce = +attrs.force; const vDiscretion = +attrs.discretion; const oDiscretion = +attrs[`${ODValue.discretion}`]; const vDexterite = +attrs.dexterite; const oDexterite = +attrs[`${ODValue.dexterite}`]; const vTir = +attrs.tir; const oTir = +attrs[`${ODValue.tir}`]; let attaquesSurprises = []; let attaquesSurprisesValue = []; let attaquesSurprisesCondition = ''; let eASAssassin = ''; let eASAssassinValue = 0; let isSurprise = false; let isAssistantAttaque = false; let isAntiAnatheme = false; let isCadence = false; let sCadence = 0; let vCadence = 0; let isDeuxMains = false; let isDestructeur = false; let vDestructeur = 0; let isFureur = false; let isMeurtrier = false; let vMeurtrier = 0; let nowSilencieux = false; let isObliteration = false; let isTenebricide = false; let isTirRafale = false; let isUltraviolence = false; let isChambreDouble = false; let isELumiere = false; let lumiereValue = 0; let isEAkimbo = false; let isEAmbidextrie = false; let pasEnergie = false; let sEnergieText = ''; const energie = attrs.energiePJ; const espoir = attrs.espoir; const devaste = +attrs.devasterAnatheme; const bourreau = +attrs.bourreauTenebres; const equilibre = +attrs.equilibreBalance; let autresEffets = []; let autresAmeliorationsA = []; const autresSpecial = []; if (hasArmure) { exec.push('{{OD=true}}'); } let C1Nom = ''; let C2Nom = ''; let C3Nom = ''; let C4Nom = ''; if (attrsCarac.C1) { C1Nom = attrsCarac.C1Brut; const C1Value = attrsCarac.C1Base; const C1OD = attrsCarac.C1OD; cBase.push(attrsCarac.C1Nom); cRoll.push(C1Value); if (hasArmure) { OD += C1OD; } } if (attrsCarac.C2) { C2Nom = attrsCarac.C2Brut; const C2Value = attrsCarac.C2Base; const C2OD = attrsCarac.C2OD; cBase.push(attrsCarac.C2Nom); cRoll.push(C2Value); if (hasArmure) { OD += C2OD; } } if (attrsCarac.C3) { C3Nom = attrsCarac.C3Brut; const C3Value = attrsCarac.C3Base; const C3OD = attrsCarac.C3OD; cBonus.push(attrsCarac.C3Nom); cRoll.push(C3Value); if (hasArmure) { OD += C3OD; } } if (attrsCarac.C4) { C4Nom = attrsCarac.C4Brut; const C4Value = attrsCarac.C4Base; const C4OD = attrsCarac.C4OD; cBonus.push(attrsCarac.C4Nom); cRoll.push(C4Value); if (hasArmure) { OD += C4OD; } } if (mod !== 0) { cRoll.push(mod); exec.push(`{{mod=${mod}}}`); } // GESTION DES BONUS DES OD if (oDiscretion >= 2 && hasArmure) { let bODDiscretion = vDiscretion; attaquesSurprises.push(i18n_odDiscretion); if (oDiscretion >= 5) { bODDiscretion += vDiscretion + oDiscretion; } attaquesSurprisesValue.push(bODDiscretion); attaquesSurprisesCondition = `{{attaqueSurpriseCondition=${i18n_attaqueSurpriseCondition}}}`; } // FIN DE GESTION DES BONUS DES OD // GESTION DES EFFETS const effets = getWeaponsEffects(prefix, attrs, hasArmure, armure, vForce, vDexterite, oDexterite, vDiscretion, oDiscretion, vTir, oTir); bDegats = bDegats.concat(effets.bDegats); eASAssassin = effets.eASAssassin; eASAssassinValue = effets.eASAssassinValue; if (attaquesSurprisesCondition === '' && effets.attaquesSurprisesCondition !== '') { attaquesSurprisesCondition = effets.attaquesSurprisesCondition; } attaquesSurprises = attaquesSurprises.concat(effets.attaquesSurprises); attaquesSurprisesValue = attaquesSurprisesValue.concat(effets.attaquesSurprisesValue); autresEffets = autresEffets.concat(effets.autresEffets); isAntiAnatheme = effets.isAntiAnatheme; isAssassin = effets.isAssassin; isAssistantAttaque = effets.isAssistantAttaque; isCadence = effets.isCadence; sCadence = effets.sCadence; vCadence = effets.vCadence; isDestructeur = effets.isDestructeur; vDestructeur = effets.vDestructeur; isDeuxMains = effets.isDeuxMains; isLourd = effets.isLourd; isMeurtrier = effets.isMeurtrier; vMeurtrier = effets.vMeurtrier; nowSilencieux = effets.nowSilencieux; isTenebricide = effets.isTenebricide; isFureur = effets.isFureur; isUltraviolence = effets.isUltraviolence; isObliteration = effets.isObliteration; isTirRafale = effets.isTirRafale; isELumiere = effets.isELumiere; lumiereValue = Number(effets.eLumiereValue); isEAkimbo = effets.isAkimbo; isEAmbidextrie = effets.isAmbidextrie; if (effets.isConditionnelA) { isConditionnelA = true; } if (effets.isConditionnelD) { isConditionnelD = true; } if (effets.isConditionnelV) { isConditionnelV = true; } // FIN GESTION DES EFFETS // GESTION DES AMELIORATIONS D'ARMES const ameliorationsA = getWeaponsDistanceAA(prefix, attrs, vDiscretion, oDiscretion, isAssistantAttaque, eASAssassinValue, isCadence, vCadence, nowSilencieux, isTirRafale, isObliteration, isAntiAnatheme); exec = exec.concat(ameliorationsA.exec); bonus = bonus.concat(ameliorationsA.bonus); baseDegats += ameliorationsA.diceDegats; baseViolence += ameliorationsA.diceViolence; diceDegats += ameliorationsA.diceDegats; diceViolence += ameliorationsA.diceViolence; bDegats = bDegats.concat(ameliorationsA.bDegats); attaquesSurprises = attaquesSurprises.concat(ameliorationsA.attaquesSurprises); attaquesSurprisesValue = attaquesSurprisesValue.concat(ameliorationsA.attaquesSurprisesValue); if (attaquesSurprisesCondition === '') { attaquesSurprisesCondition = ameliorationsA.attaquesSurprisesCondition; } if (ameliorationsA.isChambreDouble) { isCadence = false; isChambreDouble = ameliorationsA.isChambreDouble; sCadence = ameliorationsA.rChambreDouble; } if (ameliorationsA.isJAkimbo) { isEAkimbo = ameliorationsA.isJAkimbo; } if (ameliorationsA.isJAmbidextre) { isEAmbidextrie = ameliorationsA.isJAmbidextre; } autresEffets = autresEffets.concat(ameliorationsA.autresEffets); autresAmeliorationsA = autresAmeliorationsA.concat(ameliorationsA.autresAmeliorations); if (ameliorationsA.aASAssassin !== '') { eASAssassin = ameliorationsA.aASAssassin; eASAssassinValue = ameliorationsA.aASAssassinValue; } if (ameliorationsA.isConditionnelA) { isConditionnelA = true; } if (ameliorationsA.isConditionnelD) { isConditionnelD = true; } if (ameliorationsA.isConditionnelV) { isConditionnelV = true; } // FIN GESTION DES AMELIORATIONS D'ARMES // GESTION DU STYLE const getStyle = getStyleDistanceMod(attrs, baseDegats, baseViolence, vPilonnage, vPilonnageType, hasArmure, oTir, isEAkimbo, isEAmbidextrie, isDeuxMains, isLourd); exec = exec.concat(getStyle.exec); cRoll = cRoll.concat(getStyle.cRoll); diceDegats += getStyle.diceDegats; diceViolence += getStyle.diceViolence; // FIN GESTION DU STYLE // GESTION DES BONUS SPECIAUX const sBonusDegats = isApplied(attrs[`${prefix}BDDiversTotal`]); const sBonusDegatsD6 = attrs[`${prefix}BDDiversD6`]; const sBonusDegatsFixe = attrs[`${prefix}BDDiversFixe`]; const sBonusViolence = isApplied(attrs[`${prefix}BVDiversTotal`]); const sBonusViolenceD6 = attrs[`${prefix}BVDiversD6`]; const sBonusViolenceFixe = attrs[`${prefix}BVDiversFixe`]; const sEnergie = isApplied(attrs[`${prefix}energie`]); const sEnergieValue = attrs[`${prefix}energieValue`]; let newEnergie = 0; if (sBonusDegats) { exec.push(`{{vMSpecialD=+${sBonusDegatsD6}D6+${sBonusDegatsFixe}}}`); diceDegats += Number(sBonusDegatsD6); bDegats.push(sBonusDegatsFixe); } if (sBonusViolence) { exec.push(`{{vMSpecialV=+${sBonusViolenceD6}D6+${sBonusViolenceFixe}}}`); diceViolence += Number(sBonusViolenceD6); bViolence.push(sBonusViolenceFixe); } if (sEnergie) { if (armure === 'berserk') { let sEspoirValue = Math.floor((Number(sEnergieValue) / 2) - 1); if (sEspoirValue < 1) { sEspoirValue = 1; } autresSpecial.push(`${i18n_espoirRetire} (${sEspoirValue})`); newEnergie = Number(espoir) - Number(sEspoirValue); if (newEnergie === 0) { sEnergieText = i18n_plusEspoir; } else if (newEnergie < 0) { newEnergie = 0; sEnergieText = i18n_pasEspoir; pasEnergie = true; } } else { autresSpecial.push(`${i18n_energieRetiree} (${sEnergieValue})`); newEnergie = Number(energie) - Number(sEnergieValue); if (newEnergie === 0) { sEnergieText = i18n_plusEnergie; } else if (newEnergie < 0) { newEnergie = 0; sEnergieText = i18n_pasEnergie; pasEnergie = true; } } exec.push(`{{energieR=${newEnergie}}}`); } // FIN DE GESTION DES BONUS SPECIAUX // GESTION DES BONUS D'ARMURE const armorBonus = getArmorBonus(attrs, armure, isELumiere, false, vDiscretion, oDiscretion, hasBonus, C1Nom, C2Nom, C3Nom, C4Nom); exec = exec.concat(armorBonus.exec); cRoll = cRoll.concat(armorBonus.cRoll); if (isConditionnelA === false) { isConditionnelA = armorBonus.isConditionnelA; } if (isConditionnelD === false) { isConditionnelD = armorBonus.isConditionnelD; } attaquesSurprises = armorBonus.attaquesSurprises.concat(attaquesSurprises); attaquesSurprisesValue = armorBonus.attaquesSurprisesValue.concat(attaquesSurprisesValue); if (attaquesSurprisesCondition === '') { attaquesSurprisesCondition = armorBonus.attaquesSurprisesCondition.concat(attaquesSurprisesCondition); } diceDegats += Number(armorBonus.diceDegats); diceViolence += Number(armorBonus.diceViolence); ODBarbarian = ODBarbarian.concat(armorBonus.ODBarbarian); ODShaman = ODShaman.concat(armorBonus.ODShaman); ODWarrior.push(armorBonus.ODWarrior); const MALBonus = getMALBonus(attrs, armureL, isELumiere, false, vDiscretion, oDiscretion, hasBonus, C1Nom, C2Nom, C3Nom, C4Nom); exec = exec.concat(MALBonus.exec); cRoll = cRoll.concat(MALBonus.cRoll); if (isConditionnelA === false) { isConditionnelA = MALBonus.isConditionnelA; } if (isConditionnelD === false) { isConditionnelD = MALBonus.isConditionnelD; } attaquesSurprises = MALBonus.attaquesSurprises.concat(attaquesSurprises); attaquesSurprisesValue = MALBonus.attaquesSurprisesValue.concat(attaquesSurprisesValue); if (attaquesSurprisesCondition === '') { attaquesSurprisesCondition = MALBonus.attaquesSurprisesCondition.concat(attaquesSurprisesCondition); } diceDegats += Number(MALBonus.diceDegats); diceViolence += Number(MALBonus.diceViolence); ODMALBarbarian = ODMALBarbarian.concat(MALBonus.ODMALBarbarian); ODMALShaman = ODMALShaman.concat(MALBonus.ODMALShaman); ODMALWarrior.push(MALBonus.ODMALWarrior); // FIN GESTION DES BONUS D'ARMURE OD -= armorBonus.ODWarrior; OD -= MALBonus.ODMALWarrior; exec.push(`{{vOD=${OD}}}`); if (cRoll.length === 0) { cRoll.push(0); } if (bonus.length === 0) { bonus.push(0); } bonus = bonus.concat(OD); bonus = bonus.concat(ODBarbarian); bonus = bonus.concat(ODMALBarbarian); bonus = bonus.concat(ODShaman); bonus = bonus.concat(ODMALShaman); bonus = bonus.concat(ODWarrior); bonus = bonus.concat(ODMALWarrior); if (diceDegats < 0) { diceDegats = 0; } if (diceViolence < 0) { diceViolence = 0; } degats.push(`${diceDegats}D6`); degats = degats.concat(bDegats); violence.push(`${diceViolence}D6`); violence = violence.concat(bViolence); if (cBase.length !== 0) { exec.push(`{{cBase=${cBase.join(' - ')}}}`); } if (cBonus.length !== 0) { exec.push(`{{cBonus=${cBonus.join(' - ')}}}`); } const jet = `{{jet=[[ {{[[{${cRoll.join('+')}-${sCadence}, 0}kh1]]d6cs2cs4cs6cf1cf3cf5s%2}=0}]]}}`; firstExec.push(jet); exec.push(`{{Exploit=[[${cRoll.join('+')}]]}}`); exec.push(`{{bonus=[[${bonus.join('+')}]]}}`); exec.push(`{{degats=[[${degats.join('+')}]]}}`); exec.push(`{{violence=[[${violence.join('+')}]]}}`); if (isObliteration) { let ASObliteration = []; let ASValueObliteration = []; diceDegatsObliteration = diceDegats * 6; degatsFObliteration = _.reduce(bDegats, (n1, n2) => Number(n1) + Number(n2)); const vObliteration = diceDegatsObliteration + degatsFObliteration; exec.push(`{{obliterationValue=${vObliteration}}}`); if (isMeurtrier) { exec.push(`{{obliterationMeurtrierValue=${vMeurtrier * 6}}}`); } if (isDestructeur) { exec.push(`{{obliterationDestructeurValue=${vDestructeur * 6}}}`); } if (eASAssassinValue > 0) { eAssassinTenebricideValue = eASAssassinValue * 6; ASObliteration.unshift(eASAssassin); ASValueObliteration.unshift(eAssassinTenebricideValue); if (attaquesSurprises.length > 0) { ASObliteration = ASObliteration.concat(attaquesSurprises); ASValueObliteration = ASValueObliteration.concat(attaquesSurprisesValue); } exec.push(`{{obliterationAS=${ASObliteration.join('\n+')}}}`); exec.push(`{{obliterationASValue=${_.reduce(ASValueObliteration, (n1, n2) => n1 + n2, 0)}}}`); } else if (attaquesSurprises.length > 0) { ASObliteration = ASObliteration.concat(attaquesSurprises); ASValueObliteration = ASValueObliteration.concat(attaquesSurprisesValue); exec.push(`{{obliterationAS=${ASTenebricide.join('\n+')}}}`); exec.push(`{{obliterationASValue=${_.reduce(ASValueObliteration, (n1, n2) => n1 + n2, 0)}}}`); } } if (isCadence) { exec.push(`{{rCadence=${i18n_cadence} ${vCadence} ${i18n_inclus}}}`); exec.push(`{{vCadence=${sCadence}D}}`); } if (isChambreDouble) { exec.push(`{{rCadence=${i18n_chambreDouble} (${i18n_cadence} 2) ${i18n_inclus}}}`); exec.push(`{{vCadence=${sCadence}D}}`); } if (eASAssassinValue > 0) { attaquesSurprises.unshift(eASAssassin); attaquesSurprisesValue.unshift(`${eASAssassinValue}D6`); } if (attaquesSurprises.length > 0) { exec.push(`{{attaqueSurprise=${attaquesSurprises.join('\n+')}}}`); exec.push(`{{attaqueSurpriseValue=[[${attaquesSurprisesValue.join('+')}]]}}`); exec.push(attaquesSurprisesCondition); isSurprise = true; } if (isTenebricide) { exec.push(`{{tenebricide=${i18n_tenebricide}}} {{tenebricideConditionD=${i18n_tenebricideConditionD}}} {{tenebricideConditionV=${i18n_tenebricideConditionV}}}`); exec.push('{{tenebricideValueD=[[0]]}}'); exec.push('{{tenebricideValueV=[[0]]}}'); if (attaquesSurprises.length > 0) { exec.push(`{{tenebricideAS=${attaquesSurprises.join('\n+')}}}`); exec.push('{{tenebricideASValue=[[0]]}}'); } if (isMeurtrier) { firstExec.push('{{tMeurtrierValue=[[0]]}}'); } if (isDestructeur) { firstExec.push('{{tDestructeurValue=[[0]]}}'); } if (isFureur) { firstExec.push('{{tFureurValue=[[0]]}}'); } if (isUltraviolence) { firstExec.push('{{tUltraviolenceValue=[[0]]}}'); } } if (isELumiere) { autresEffets.push(`${i18n_lumiere} ${lumiereValue}`); } if (devaste || bourreau || equilibre) { const herauts = []; if (devaste) { herauts.push(i18n_devasterAnatheme); } if (bourreau) { herauts.push(i18n_bourreauTenebres); } if (equilibre) { herauts.push(i18n_equilibrerBalance); } exec.push(`{{herauts=${herauts.join(' / ')}}}`); } if (autresEffets.length > 0) { autresEffets.sort(); exec.push(`{{effets=${autresEffets.join(' / ')}}}`); } if (autresAmeliorationsA.length > 0) { autresAmeliorationsA.sort(); exec.push(`{{ameliorations=${autresAmeliorationsA.join(' / ')}}}`); } if (autresSpecial.length > 0) { autresSpecial.sort(); exec.push(`{{special=${autresSpecial.join(' / ')}}}`); } if (isConditionnelA) { exec.push('{{succesConditionnel=true}}'); } if (isConditionnelD) { exec.push('{{degatsConditionnel=true}}'); } if (isConditionnelV) { exec.push('{{violenceConditionnel=true}}'); } if (effets.exec) { exec = exec.concat(effets.exec); } if (effets.firstExec) { firstExec = firstExec.concat(effets.firstExec); } exec = firstExec.concat(exec); // ROLL let finalRoll; if (pasEnergie === false) { finalRoll = await startRoll(exec.join(' ')); const tJet = finalRoll.results.jet.result; const tBonus = finalRoll.results.bonus.result; const tExploit = finalRoll.results.Exploit.result; const rDegats = finalRoll.results.degats.dice; const rViolence = finalRoll.results.violence.dice; const tDegats = finalRoll.results.degats.result; const tViolence = finalRoll.results.violence.result; const conditions = { bourreau, devaste, equilibre, isTenebricide, isSurprise, isDestructeur, isFureur, isMeurtrier, isUltraviolence, }; const computed = updateRoll(finalRoll, tDegats, rDegats, bDegats, tViolence, rViolence, bViolence, conditions); const finalComputed = { jet: tJet + tBonus, }; Object.assign(finalComputed, computed); finishRoll(finalRoll.rollId, finalComputed); if (tJet !== 0 && tJet === tExploit) { const exploitRoll = await startRoll(`${roll}@{jetGM} &{template:simple} {{Nom=@{name}}} {{special1=${i18n_exploit}}}${jet}`); const tRExploit = exploitRoll.results.jet.result; const exploitComputed = { jet: tRExploit, }; finishRoll(exploitRoll.rollId, exploitComputed); } if (sEnergie !== false) { if (armure === 'berserk') { setAttrs({ espoir: newEnergie, }); } else { setAttrs({ energiePJ: newEnergie, }); } if (newEnergie === 0) { const noEnergieRoll = await startRoll(`@{jetGM} &{template:simple} {{Nom=@{name}}} {{special1=${name}}} {{text=${sEnergieText}}}`); finishRoll(noEnergieRoll.rollId, {}); } } } else if (button === 'repeating_armeCaC:armecontact') { finalRoll = await startRoll(`@{jetGM} &{template:simple} {{Nom=@{name}}} {{special1=${name}}} {{text=${sEnergieText}}}`); finishRoll(finalRoll.rollId, {}); } else { finalRoll = await startRoll(`@{jetGM} &{template:simple} {{Nom=@{name}}} {{special1=${name}}} {{text=${sEnergieText}}}`); finishRoll(finalRoll.rollId, {}); } }); });
var Blueprint = require('../../lib/models/blueprint'); var Promise = require('../../lib/ext/promise'); var merge = require('lodash-node/compat/objects/merge'); var inflection = require('inflection'); module.exports = { description: 'Generates a model and route.', install: function(options) { return this._process('install', options); }, uninstall: function(options) { return this._process('uninstall', options); }, _processBlueprint: function(type, name, options) { var mainBlueprint = Blueprint.lookup(name, { ui: this.ui, analytics: this.analytics, project: this.project }); return Promise.resolve() .then(function() { return mainBlueprint[type](options); }) .then(function() { var testBlueprint = mainBlueprint.lookupBlueprint(name + '-test', { ui: this.ui, analytics: this.analytics, project: this.project, ignoreMissing: true }); if (!testBlueprint) { return; } if (testBlueprint.locals === Blueprint.prototype.locals) { testBlueprint.locals = function(options) { return mainBlueprint.locals(options); }; } return testBlueprint[type](options); }); }, _process: function(type, options) { var modelOptions = merge({}, options, { entity: { name: inflection.singularize(options.entity.name) } }); var routeOptions = merge({}, options, { type: 'resource' }); var self = this; return this._processBlueprint(type, 'model', modelOptions) .then(function() { return self._processBlueprint(type, 'route', routeOptions); }); } };
/** * Copyright 2014 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["sk-SK"] = { name: "sk-SK", numberFormat: { pattern: ["-n"], decimals: 2, ",": " ", ".": ",", groupSize: [3], percent: { pattern: ["-n%","n%"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-n $","n $"], decimals: 2, ",": " ", ".": ",", groupSize: [3], symbol: "€" } }, calendars: { standard: { days: { names: ["nedeľa","pondelok","utorok","streda","štvrtok","piatok","sobota"], namesAbbr: ["ne","po","ut","st","št","pi","so"], namesShort: ["ne","po","ut","st","št","pi","so"] }, months: { names: ["január","február","marec","apríl","máj","jún","júl","august","september","október","november","december",""], namesAbbr: ["1","2","3","4","5","6","7","8","9","10","11","12",""] }, AM: [""], PM: [""], patterns: { d: "d. M. yyyy", D: "d. MMMM yyyy", F: "d. MMMM yyyy H:mm:ss", g: "d. M. yyyy H:mm", G: "d. M. yyyy H:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "H:mm", T: "H:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ". ", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
import { EventEmitter } from 'events'; import _ from 'underscore'; import s from 'underscore.string'; export const LoggerManager = new class extends EventEmitter { constructor() { super(); this.enabled = false; this.loggers = {}; this.queue = []; this.showPackage = false; this.showFileAndLine = false; this.logLevel = 0; } register(logger) { // eslint-disable-next-line no-use-before-define if (!(logger instanceof Logger)) { return; } this.loggers[logger.name] = logger; this.emit('register', logger); } addToQueue(logger, args) { this.queue.push({ logger, args, }); } dispatchQueue() { _.each(this.queue, (item) => item.logger._log.apply(item.logger, item.args)); this.clearQueue(); } clearQueue() { this.queue = []; } disable() { this.enabled = false; } enable(dispatchQueue = false) { this.enabled = true; return dispatchQueue === true ? this.dispatchQueue() : this.clearQueue(); } }(); const defaultTypes = { debug: { name: 'debug', color: 'blue', level: 2, }, log: { name: 'info', color: 'blue', level: 1, }, info: { name: 'info', color: 'blue', level: 1, }, success: { name: 'info', color: 'green', level: 1, }, warn: { name: 'warn', color: 'magenta', level: 1, }, error: { name: 'error', color: 'red', level: 0, }, deprecation: { name: 'warn', color: 'magenta', level: 0, }, }; export class Logger { constructor(name, config = {}) { const self = this; this.name = name; this.config = Object.assign({}, config); if (LoggerManager.loggers && LoggerManager.loggers[this.name] != null) { LoggerManager.loggers[this.name].warn('Duplicated instance'); return LoggerManager.loggers[this.name]; } _.each(defaultTypes, (typeConfig, type) => { this[type] = function(...args) { return self._log.call(self, { section: this.__section, type, level: typeConfig.level, method: typeConfig.name, arguments: args, }); }; self[`${ type }_box`] = function(...args) { return self._log.call(self, { section: this.__section, type, box: true, level: typeConfig.level, method: typeConfig.name, arguments: args, }); }; }); if (this.config.methods) { _.each(this.config.methods, (typeConfig, method) => { if (this[method] != null) { self.warn(`Method ${ method } already exists`); } if (defaultTypes[typeConfig.type] == null) { self.warn(`Method type ${ typeConfig.type } does not exist`); } this[method] = function(...args) { return self._log.call(self, { section: this.__section, type: typeConfig.type, level: typeConfig.level != null ? typeConfig.level : defaultTypes[typeConfig.type] && defaultTypes[typeConfig.type].level, method, arguments: args, }); }; this[`${ method }_box`] = function(...args) { return self._log.call(self, { section: this.__section, type: typeConfig.type, box: true, level: typeConfig.level != null ? typeConfig.level : defaultTypes[typeConfig.type] && defaultTypes[typeConfig.type].level, method, arguments: args, }); }; }); } if (this.config.sections) { _.each(this.config.sections, (name, section) => { this[section] = {}; _.each(defaultTypes, (typeConfig, type) => { self[section][type] = (...args) => this[type].apply({ __section: name }, args); self[section][`${ type }_box`] = (...args) => this[`${ type }_box`].apply({ __section: name }, args); }); _.each(this.config.methods, (typeConfig, method) => { self[section][method] = (...args) => self[method].apply({ __section: name }, args); self[section][`${ method }_box`] = (...args) => self[`${ method }_box`].apply({ __section: name }, args); }); }); } LoggerManager.register(this); } getPrefix(options) { let prefix = `${ this.name } ➔ ${ options.method }`; if (options.section) { prefix = `${ this.name } ➔ ${ options.section }.${ options.method }`; } const details = this._getCallerDetails(); const detailParts = []; if (details.package && (LoggerManager.showPackage === true || options.type === 'error')) { detailParts.push(details.package); } if (LoggerManager.showFileAndLine === true || options.type === 'error') { if ((details.file != null) && (details.line != null)) { detailParts.push(`${ details.file }:${ details.line }`); } else { if (details.file != null) { detailParts.push(details.file); } if (details.line != null) { detailParts.push(details.line); } } } if (defaultTypes[options.type]) { // format the message to a colored message prefix = prefix[defaultTypes[options.type].color]; } if (detailParts.length > 0) { prefix = `${ detailParts.join(' ') } ${ prefix }`; } return prefix; } _getCallerDetails() { const getStack = () => { // We do NOT use Error.prepareStackTrace here (a V8 extension that gets us a // core-parsed stack) since it's impossible to compose it with the use of // Error.prepareStackTrace used on the server for source maps. const { stack } = new Error(); return stack; }; const stack = getStack(); if (!stack) { return {}; } const lines = stack.split('\n').splice(1); // looking for the first line outside the logging package (or an // eval if we find that first) let line = lines[0]; for (let index = 0, len = lines.length; index < len; index++, line = lines[index]) { if (line.match(/^\s*at eval \(eval/)) { return { file: 'eval' }; } if (!line.match(/packages\/rocketchat_logger(?:\/|\.js)/)) { break; } } const details = {}; // The format for FF is 'functionName@filePath:lineNumber' // The format for V8 is 'functionName (packages/logging/logging.js:81)' or // 'packages/logging/logging.js:81' const match = /(?:[@(]| at )([^(]+?):([0-9:]+)(?:\)|$)/.exec(line); if (!match) { return details; } details.line = match[2].split(':')[0]; // Possible format: https://foo.bar.com/scripts/file.js?random=foobar // XXX: if you can write the following in better way, please do it // XXX: what about evals? details.file = match[1].split('/').slice(-1)[0].split('?')[0]; const packageMatch = match[1].match(/packages\/([^\.\/]+)(?:\/|\.)/); if (packageMatch) { details.package = packageMatch[1]; } return details; } makeABox(message, title) { if (!_.isArray(message)) { message = message.split('\n'); } let len = 0; len = Math.max.apply(null, message.map((line) => line.length)); const topLine = `+--${ s.pad('', len, '-') }--+`; const separator = `| ${ s.pad('', len, '') } |`; let lines = []; lines.push(topLine); if (title) { lines.push(`| ${ s.lrpad(title, len) } |`); lines.push(topLine); } lines.push(separator); lines = [...lines, ...message.map((line) => `| ${ s.rpad(line, len) } |`)]; lines.push(separator); lines.push(topLine); return lines; } _log(options, ...args) { if (LoggerManager.enabled === false) { LoggerManager.addToQueue(this, [options, ...args]); return; } if (options.level == null) { options.level = 1; } if (LoggerManager.logLevel < options.level) { return; } // Deferred logging if (typeof options.arguments[0] === 'function') { options.arguments[0] = options.arguments[0](); } const prefix = this.getPrefix(options); if (options.box === true && _.isString(options.arguments[0])) { let color = undefined; if (defaultTypes[options.type]) { color = defaultTypes[options.type].color; } const box = this.makeABox(options.arguments[0], options.arguments[1]); let subPrefix = '➔'; if (color) { subPrefix = subPrefix[color]; } console.log(subPrefix, prefix); box.forEach((line) => { console.log(subPrefix, color ? line[color] : line); }); } else { options.arguments.unshift(prefix); console.log.apply(console, options.arguments); } } } export const SystemLogger = new Logger('System', { methods: { startup: { type: 'success', level: 0, }, }, });
for (let i = 0;;) { var i; }
\u2163\u2161 = []
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.5.2.1_A1_T1; * @section: 15.5.2.1; * @assertion: When "String" is called as part of a new expression, it is a constructor: it initialises the newly created object and * The [[Value]] property of the newly constructed object is set to ToString(value), or to the empty string if value is not supplied; * @description: Creating string object with expression "new String"; */ __str = new String; ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (typeof __str !== "object") { $ERROR('#1: __str = new String; typeof __str === "object". Actual: typeof __str ==='+typeof __str ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#1.5 if (__str.constructor !== String) { $ERROR('#1.5: __str = new String; __str.constructor === String. Actual: __str.constructor ==='+__str.constructor ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__str != "") { $ERROR('#2: __str = new String; __str == "". Actual: __str =='+__str); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if ( __str === "") { $ERROR('#3: __str = new String; __str !== ""'); } // //////////////////////////////////////////////////////////////////////////////
/* global wc_stripe_params */ Stripe.setPublishableKey( wc_stripe_params.key ); jQuery( function( $ ) { 'use strict'; /* Open and close for legacy class */ $( 'form.checkout, form#order_review' ).on( 'change', 'input[name="wc-stripe-payment-token"]', function() { if ( 'new' === $( '.stripe-legacy-payment-fields input[name="wc-stripe-payment-token"]:checked' ).val() ) { $( '.stripe-legacy-payment-fields #stripe-payment-data' ).slideDown( 200 ); } else { $( '.stripe-legacy-payment-fields #stripe-payment-data' ).slideUp( 200 ); } } ); /** * Object to handle Stripe payment forms. */ var wc_stripe_form = { /** * Initialize event handlers and UI state. */ init: function() { // checkout page if ( $( 'form.woocommerce-checkout' ).length ) { this.form = $( 'form.woocommerce-checkout' ); } $( 'form.woocommerce-checkout' ) .on( 'checkout_place_order_stripe', this.onSubmit ); // pay order page if ( $( 'form#order_review' ).length ) { this.form = $( 'form#order_review' ); } $( 'form#order_review' ) .on( 'submit', this.onSubmit ); // add payment method page if ( $( 'form#add_payment_method' ).length ) { this.form = $( 'form#add_payment_method' ); } $( 'form#add_payment_method' ) .on( 'submit', this.onSubmit ); $( document ) .on( 'change', '#wc-stripe-cc-form :input', this.onCCFormChange ) .on( 'stripeError', this.onError ) .on( 'checkout_error', this.clearToken ); }, isStripeChosen: function() { return $( '#payment_method_stripe' ).is( ':checked' ) && ( ! $( 'input[name="wc-stripe-payment-token"]:checked' ).length || 'new' === $( 'input[name="wc-stripe-payment-token"]:checked' ).val() ); }, hasToken: function() { return 0 < $( 'input.stripe_token' ).length; }, block: function() { wc_stripe_form.form.block({ message: null, overlayCSS: { background: '#fff', opacity: 0.6 } }); }, unblock: function() { wc_stripe_form.form.unblock(); }, onError: function( e, responseObject ) { var message = responseObject.response.error.message; // Customers do not need to know the specifics of the below type of errors // therefore return a generic localizable error message. if ( 'invalid_request_error' === responseObject.response.error.type || 'api_connection_error' === responseObject.response.error.type || 'api_error' === responseObject.response.error.type || 'authentication_error' === responseObject.response.error.type || 'rate_limit_error' === responseObject.response.error.type ) { message = wc_stripe_params.invalid_request_error; } if ( 'card_error' === responseObject.response.error.type && wc_stripe_params.hasOwnProperty( responseObject.response.error.code ) ) { message = wc_stripe_params[ responseObject.response.error.code ]; } $( '.wc-stripe-error, .stripe_token' ).remove(); $( '#stripe-card-number' ).closest( 'p' ).before( '<ul class="woocommerce_error woocommerce-error wc-stripe-error"><li>' + message + '</li></ul>' ); wc_stripe_form.unblock(); }, onSubmit: function( e ) { if ( wc_stripe_form.isStripeChosen() && ! wc_stripe_form.hasToken() ) { e.preventDefault(); wc_stripe_form.block(); var card = $( '#stripe-card-number' ).val(), cvc = $( '#stripe-card-cvc' ).val(), expires = $( '#stripe-card-expiry' ).payment( 'cardExpiryVal' ), first_name = $( '#billing_first_name' ).length ? $( '#billing_first_name' ).val() : wc_stripe_params.billing_first_name, last_name = $( '#billing_last_name' ).length ? $( '#billing_last_name' ).val() : wc_stripe_params.billing_last_name, data = { number : card, cvc : cvc, exp_month: parseInt( expires.month, 10 ) || 0, exp_year : parseInt( expires.year, 10 ) || 0 }; if ( first_name && last_name ) { data.name = first_name + ' ' + last_name; } if ( $( '#billing_address_1' ).length > 0 ) { data.address_line1 = $( '#billing_address_1' ).val(); data.address_line2 = $( '#billing_address_2' ).val(); data.address_state = $( '#billing_state' ).val(); data.address_city = $( '#billing_city' ).val(); data.address_zip = $( '#billing_postcode' ).val(); data.address_country = $( '#billing_country' ).val(); } else if ( wc_stripe_params.billing_address_1 ) { data.address_line1 = wc_stripe_params.billing_address_1; data.address_line2 = wc_stripe_params.billing_address_2; data.address_state = wc_stripe_params.billing_state; data.address_city = wc_stripe_params.billing_city; data.address_zip = wc_stripe_params.billing_postcode; data.address_country = wc_stripe_params.billing_country; } Stripe.createToken( data, wc_stripe_form.onStripeResponse ); // Prevent form submitting return false; } }, onCCFormChange: function() { $( '.wc-stripe-error, .stripe_token' ).remove(); }, onStripeResponse: function( status, response ) { if ( response.error ) { $( document ).trigger( 'stripeError', { response: response } ); } else { // check if we allow prepaid cards if ( 'no' === wc_stripe_params.allow_prepaid_card && 'prepaid' === response.card.funding ) { response.error = { message: wc_stripe_params.no_prepaid_card_msg }; $( document ).trigger( 'stripeError', { response: response } ); return false; } // token contains id, last4, and card type var token = response.id; // insert the token into the form so it gets submitted to the server wc_stripe_form.form.append( "<input type='hidden' class='stripe_token' name='stripe_token' value='" + token + "'/>" ); wc_stripe_form.form.submit(); } }, clearToken: function() { $( '.stripe_token' ).remove(); } }; wc_stripe_form.init(); } );
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; require('../common'); const assert = require('assert'); const http = require('http'); let requests_sent = 0; let requests_done = 0; const options = { method: 'GET', port: undefined, host: '127.0.0.1', }; const server = http.createServer((req, res) => { const m = /\/(.*)/.exec(req.url); const reqid = parseInt(m[1], 10); if (reqid % 2) { // Do not reply the request } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write(reqid.toString()); res.end(); } }); server.listen(0, options.host, function() { options.port = this.address().port; for (requests_sent = 0; requests_sent < 30; requests_sent += 1) { options.path = `/${requests_sent}`; const req = http.request(options); req.id = requests_sent; req.on('response', (res) => { res.on('data', function(data) { console.log(`res#${this.req.id} data:${data}`); }); res.on('end', function(data) { console.log(`res#${this.req.id} end`); requests_done += 1; req.destroy(); }); }); req.on('close', function() { console.log(`req#${this.id} close`); }); req.on('error', function() { console.log(`req#${this.id} error`); this.destroy(); }); req.setTimeout(50, function() { console.log(`req#${this.id} timeout`); this.abort(); requests_done += 1; }); req.end(); } setTimeout(function maybeDone() { if (requests_done >= requests_sent) { setTimeout(() => { server.close(); }, 100); } else { setTimeout(maybeDone, 100); } }, 100); }); process.on('exit', () => { console.error(`done=${requests_done} sent=${requests_sent}`); // Check that timeout on http request was not called too much assert.strictEqual(requests_done, requests_sent); });
const Server = require('template-ui/server') const webpackConfig = require('./webpack.config') const appsConfig = require('./apps.config') Server({ webpackConfig, appsConfig, dirname: __dirname })
description("Tests Geolocation error callback using the mock service."); var mockMessage = "debug"; if (window.testRunner) { testRunner.setGeolocationPermission(true); testRunner.setMockGeolocationPositionUnavailableError(mockMessage); } else debug('This test can not be run without the testRunner'); var error; navigator.geolocation.getCurrentPosition(function(p) { testFailed('Success callback invoked unexpectedly'); finishJSTest(); }, function(e) { error = e; shouldBe('error.code', 'error.POSITION_UNAVAILABLE'); shouldBe('error.message', 'mockMessage'); shouldBe('error.UNKNOWN_ERROR', 'undefined'); shouldBe('error.PERMISSION_DENIED', '1'); shouldBe('error.POSITION_UNAVAILABLE', '2'); shouldBe('error.TIMEOUT', '3'); finishJSTest(); }); window.jsTestIsAsync = true;
import { test } from '../qunit'; import { localeModule } from '../qunit-locale'; import moment from '../../moment'; localeModule('en-in'); test('parse', function (assert) { var tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split( '_' ), i; function equalTest(input, mmm, i) { assert.equal( moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) ); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ [ 'dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm', ], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '8 8th 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LTS', '3:25:50 PM'], ['L', '14/02/2010'], ['LL', '14 February 2010'], ['LLL', '14 February 2010 3:25 PM'], ['LLLL', 'Sunday, 14 February 2010 3:25 PM'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 3:25 PM'], ['llll', 'Sun, 14 Feb 2010 3:25 PM'], ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split( '_' ), i; for (i = 0; i < expected.length; i++) { assert.equal( moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i] ); } }); test('format week', function (assert) { var expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split( '_' ), i; for (i = 0; i < expected.length; i++) { assert.equal( moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i] ); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 44 }), true), 'a few seconds', '44 seconds = a few seconds' ); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 45 }), true), 'a minute', '45 seconds = a minute' ); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 89 }), true), 'a minute', '89 seconds = a minute' ); assert.equal( start.from(moment([2007, 1, 28]).add({ s: 90 }), true), '2 minutes', '90 seconds = 2 minutes' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 44 }), true), '44 minutes', '44 minutes = 44 minutes' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 45 }), true), 'an hour', '45 minutes = an hour' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 89 }), true), 'an hour', '89 minutes = an hour' ); assert.equal( start.from(moment([2007, 1, 28]).add({ m: 90 }), true), '2 hours', '90 minutes = 2 hours' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 5 }), true), '5 hours', '5 hours = 5 hours' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 21 }), true), '21 hours', '21 hours = 21 hours' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 22 }), true), 'a day', '22 hours = a day' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 35 }), true), 'a day', '35 hours = a day' ); assert.equal( start.from(moment([2007, 1, 28]).add({ h: 36 }), true), '2 days', '36 hours = 2 days' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 1 }), true), 'a day', '1 day = a day' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 5 }), true), '5 days', '5 days = 5 days' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 25 }), true), '25 days', '25 days = 25 days' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 26 }), true), 'a month', '26 days = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 30 }), true), 'a month', '30 days = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 43 }), true), 'a month', '43 days = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 46 }), true), '2 months', '46 days = 2 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 74 }), true), '2 months', '75 days = 2 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 76 }), true), '3 months', '76 days = 3 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ M: 1 }), true), 'a month', '1 month = a month' ); assert.equal( start.from(moment([2007, 1, 28]).add({ M: 5 }), true), '5 months', '5 months = 5 months' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 345 }), true), 'a year', '345 days = a year' ); assert.equal( start.from(moment([2007, 1, 28]).add({ d: 548 }), true), '2 years', '548 days = 2 years' ); assert.equal( start.from(moment([2007, 1, 28]).add({ y: 1 }), true), 'a year', '1 year = a year' ); assert.equal( start.from(moment([2007, 1, 28]).add({ y: 5 }), true), '5 years', '5 years = 5 years' ); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal( moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past' ); }); test('fromNow', function (assert) { assert.equal( moment().add({ s: 30 }).fromNow(), 'in a few seconds', 'in a few seconds' ); assert.equal(moment().add({ d: 5 }).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal( moment(a).calendar(), 'Today at 12:00 PM', 'today at the same time' ); assert.equal( moment(a).add({ m: 25 }).calendar(), 'Today at 12:25 PM', 'Now plus 25 min' ); assert.equal( moment(a).add({ h: 1 }).calendar(), 'Today at 1:00 PM', 'Now plus 1 hour' ); assert.equal( moment(a).add({ d: 1 }).calendar(), 'Tomorrow at 12:00 PM', 'tomorrow at the same time' ); assert.equal( moment(a).subtract({ h: 1 }).calendar(), 'Today at 11:00 AM', 'Now minus 1 hour' ); assert.equal( moment(a).subtract({ d: 1 }).calendar(), 'Yesterday at 12:00 PM', 'yesterday at the same time' ); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); assert.equal( m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time' ); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal( m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day' ); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal( m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day' ); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); assert.equal( m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time' ); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal( m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day' ); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal( m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day' ); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({ w: 1 }), weeksFromNow = moment().add({ w: 1 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal( weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week' ); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal( weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks' ); }); test('weeks year starting sunday formatted', function (assert) { assert.equal( moment([2012, 0, 1]).format('w ww wo'), '1 01 1st', 'Jan 1 2012 should be week 1' ); assert.equal( moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1' ); assert.equal( moment([2012, 0, 8]).format('w ww wo'), '2 02 2nd', 'Jan 8 2012 should be week 2' ); assert.equal( moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2' ); assert.equal( moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', 'Jan 15 2012 should be week 3' ); }); // Concrete test for Locale#weekdaysMin test('Weekdays sort by locale', function (assert) { assert.deepEqual( moment().localeData('en-in').weekdays(), 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), 'weekdays start on Sunday' ); assert.deepEqual( moment().localeData('en-in').weekdays(true), 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), 'locale-sorted weekdays start on Sunday' ); assert.deepEqual( moment().localeData('en-in').weekdaysShort(), 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), 'weekdaysShort start on Sunday' ); assert.deepEqual( moment().localeData('en-in').weekdaysShort(true), 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), 'locale-sorted weekdaysShort start on Sunday' ); assert.deepEqual( moment().localeData('en-in').weekdaysMin(), 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), 'weekdaysMin start on Sunday' ); assert.deepEqual( moment().localeData('en-in').weekdaysMin(true), 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), 'locale-sorted weekdaysMin start on Sunday' ); });
var common = require("./common") , odbc = require("../") , pool = new odbc.Pool() , connectionString = common.connectionString , connections = [] , connectCount = 10; openConnectionsUsingPool(connections); function openConnectionsUsingPool(connections) { for (var x = 0; x <= connectCount; x++) { (function (connectionIndex) { console.error("Opening connection #", connectionIndex); pool.open(connectionString, function (err, connection) { if (err) { console.error("error: ", err.message); process.exit(-1); } connections.push(connection); if (connectionIndex == connectCount) { closeConnections(connections); } }); })(x); } } function closeConnections (connections) { pool.close(function () { console.error("pool closed"); }); }
module.exports = x => alert(x)
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var message_constants_1 = require("../../binary-protocol/src/message-constants"); /** * This class represents a single remote procedure * call made from the client to the server. It's main function * is to encapsulate the logic around timeouts and to convert the * incoming response data */ var RPC = /** @class */ (function () { function RPC(name, correlationId, data, response, options, services) { this.name = name; this.correlationId = correlationId; this.response = response; this.options = options; this.services = services; this.onTimeout = this.onTimeout.bind(this); var message = { topic: message_constants_1.TOPIC.RPC, action: message_constants_1.RPC_ACTIONS.REQUEST, correlationId: correlationId, name: name, parsedData: data }; this.acceptTimeout = this.services.timeoutRegistry.add({ message: { topic: message_constants_1.TOPIC.RPC, action: message_constants_1.RPC_ACTIONS.ACCEPT, name: this.name, correlationId: this.correlationId }, event: message_constants_1.RPC_ACTIONS.ACCEPT_TIMEOUT, duration: this.options.rpcAcceptTimeout, callback: this.onTimeout }); this.responseTimeout = this.services.timeoutRegistry.add({ message: { topic: message_constants_1.TOPIC.RPC, action: message_constants_1.RPC_ACTIONS.REQUEST, name: this.name, correlationId: this.correlationId }, event: message_constants_1.RPC_ACTIONS.RESPONSE_TIMEOUT, duration: this.options.rpcResponseTimeout, callback: this.onTimeout }); this.services.connection.sendMessage(message); } /** * Called once an ack message is received from the server */ RPC.prototype.accept = function () { this.services.timeoutRegistry.clear(this.acceptTimeout); }; /** * Called once a response message is received from the server. */ RPC.prototype.respond = function (data) { this.response(null, data); this.complete(); }; /** * Called once an error is received from the server. */ RPC.prototype.error = function (data) { this.response(data); this.complete(); }; /** * Callback for error messages received from the server. Once * an error is received the request is considered completed. Even * if a response arrives later on it will be ignored / cause an * UNSOLICITED_MESSAGE error */ RPC.prototype.onTimeout = function (event, message) { this.response(message_constants_1.RPC_ACTIONS[event]); this.complete(); }; /** * Called after either an error or a response * was received */ RPC.prototype.complete = function () { this.services.timeoutRegistry.clear(this.acceptTimeout); this.services.timeoutRegistry.clear(this.responseTimeout); }; return RPC; }()); exports.RPC = RPC;
import * as i0 from '@angular/core'; import { forwardRef, EventEmitter, Component, ChangeDetectionStrategy, ViewEncapsulation, Output, ContentChild, Input, ContentChildren, NgModule } from '@angular/core'; import * as i1 from '@angular/common'; import { CommonModule } from '@angular/common'; import { Header, PrimeTemplate, SharedModule } from 'primeng/api'; import { DomHandler } from 'primeng/dom'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import * as Quill from 'quill'; const EDITOR_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => Editor), multi: true }; class Editor { constructor(el) { this.el = el; this.onTextChange = new EventEmitter(); this.onSelectionChange = new EventEmitter(); this.onInit = new EventEmitter(); this.onModelChange = () => { }; this.onModelTouched = () => { }; } ngAfterViewInit() { let editorElement = DomHandler.findSingle(this.el.nativeElement, 'div.p-editor-content'); let toolbarElement = DomHandler.findSingle(this.el.nativeElement, 'div.p-editor-toolbar'); let defaultModule = { toolbar: toolbarElement }; let modules = this.modules ? Object.assign(Object.assign({}, defaultModule), this.modules) : defaultModule; this.quill = new Quill(editorElement, { modules: modules, placeholder: this.placeholder, readOnly: this.readonly, theme: 'snow', formats: this.formats, bounds: this.bounds, debug: this.debug, scrollingContainer: this.scrollingContainer }); if (this.value) { this.quill.setContents(this.quill.clipboard.convert(this.value)); } this.quill.on('text-change', (delta, oldContents, source) => { if (source === 'user') { let html = DomHandler.findSingle(editorElement, '.ql-editor').innerHTML; let text = this.quill.getText().trim(); if (html === '<p><br></p>') { html = null; } this.onTextChange.emit({ htmlValue: html, textValue: text, delta: delta, source: source }); this.onModelChange(html); this.onModelTouched(); } }); this.quill.on('selection-change', (range, oldRange, source) => { this.onSelectionChange.emit({ range: range, oldRange: oldRange, source: source }); }); this.onInit.emit({ editor: this.quill }); } ngAfterContentInit() { this.templates.forEach((item) => { switch (item.getType()) { case 'header': this.headerTemplate = item.template; break; } }); } writeValue(value) { this.value = value; if (this.quill) { if (value) this.quill.setContents(this.quill.clipboard.convert(value)); else this.quill.setText(''); } } registerOnChange(fn) { this.onModelChange = fn; } registerOnTouched(fn) { this.onModelTouched = fn; } getQuill() { return this.quill; } get readonly() { return this._readonly; } set readonly(val) { this._readonly = val; if (this.quill) { if (this._readonly) this.quill.disable(); else this.quill.enable(); } } } Editor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Editor, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Component }); Editor.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.0.5", type: Editor, selector: "p-editor", inputs: { style: "style", styleClass: "styleClass", placeholder: "placeholder", formats: "formats", modules: "modules", bounds: "bounds", scrollingContainer: "scrollingContainer", debug: "debug", readonly: "readonly" }, outputs: { onTextChange: "onTextChange", onSelectionChange: "onSelectionChange", onInit: "onInit" }, providers: [EDITOR_VALUE_ACCESSOR], queries: [{ propertyName: "toolbar", first: true, predicate: Header, descendants: true }, { propertyName: "templates", predicate: PrimeTemplate }], ngImport: i0, template: ` <div [ngClass]="'p-editor-container'" [class]="styleClass"> <div class="p-editor-toolbar" *ngIf="toolbar || headerTemplate"> <ng-content select="p-header"></ng-content> <ng-container *ngTemplateOutlet="headerTemplate"></ng-container> </div> <div class="p-editor-toolbar" *ngIf="!toolbar && !headerTemplate"> <span class="ql-formats"> <select class="ql-header"> <option value="1">Heading</option> <option value="2">Subheading</option> <option selected>Normal</option> </select> <select class="ql-font"> <option selected>Sans Serif</option> <option value="serif">Serif</option> <option value="monospace">Monospace</option> </select> </span> <span class="ql-formats"> <button class="ql-bold" aria-label="Bold" type="button"></button> <button class="ql-italic" aria-label="Italic" type="button"></button> <button class="ql-underline" aria-label="Underline" type="button"></button> </span> <span class="ql-formats"> <select class="ql-color"></select> <select class="ql-background"></select> </span> <span class="ql-formats"> <button class="ql-list" value="ordered" aria-label="Ordered List" type="button"></button> <button class="ql-list" value="bullet" aria-label="Unordered List" type="button"></button> <select class="ql-align"> <option selected></option> <option value="center"></option> <option value="right"></option> <option value="justify"></option> </select> </span> <span class="ql-formats"> <button class="ql-link" aria-label="Insert Link" type="button"></button> <button class="ql-image" aria-label="Insert Image" type="button"></button> <button class="ql-code-block" aria-label="Insert Code Block" type="button"></button> </span> <span class="ql-formats"> <button class="ql-clean" aria-label="Remove Styles" type="button"></button> </span> </div> <div class="p-editor-content" [ngStyle]="style"></div> </div> `, isInline: true, styles: [".p-editor-container .p-editor-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options .ql-picker-item{width:auto;height:auto}"], directives: [{ type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet"] }, { type: i1.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: Editor, decorators: [{ type: Component, args: [{ selector: 'p-editor', template: ` <div [ngClass]="'p-editor-container'" [class]="styleClass"> <div class="p-editor-toolbar" *ngIf="toolbar || headerTemplate"> <ng-content select="p-header"></ng-content> <ng-container *ngTemplateOutlet="headerTemplate"></ng-container> </div> <div class="p-editor-toolbar" *ngIf="!toolbar && !headerTemplate"> <span class="ql-formats"> <select class="ql-header"> <option value="1">Heading</option> <option value="2">Subheading</option> <option selected>Normal</option> </select> <select class="ql-font"> <option selected>Sans Serif</option> <option value="serif">Serif</option> <option value="monospace">Monospace</option> </select> </span> <span class="ql-formats"> <button class="ql-bold" aria-label="Bold" type="button"></button> <button class="ql-italic" aria-label="Italic" type="button"></button> <button class="ql-underline" aria-label="Underline" type="button"></button> </span> <span class="ql-formats"> <select class="ql-color"></select> <select class="ql-background"></select> </span> <span class="ql-formats"> <button class="ql-list" value="ordered" aria-label="Ordered List" type="button"></button> <button class="ql-list" value="bullet" aria-label="Unordered List" type="button"></button> <select class="ql-align"> <option selected></option> <option value="center"></option> <option value="right"></option> <option value="justify"></option> </select> </span> <span class="ql-formats"> <button class="ql-link" aria-label="Insert Link" type="button"></button> <button class="ql-image" aria-label="Insert Image" type="button"></button> <button class="ql-code-block" aria-label="Insert Code Block" type="button"></button> </span> <span class="ql-formats"> <button class="ql-clean" aria-label="Remove Styles" type="button"></button> </span> </div> <div class="p-editor-content" [ngStyle]="style"></div> </div> `, providers: [EDITOR_VALUE_ACCESSOR], changeDetection: ChangeDetectionStrategy.OnPush, styleUrls: ['./editor.css'], encapsulation: ViewEncapsulation.None }] }], ctorParameters: function () { return [{ type: i0.ElementRef }]; }, propDecorators: { onTextChange: [{ type: Output }], onSelectionChange: [{ type: Output }], toolbar: [{ type: ContentChild, args: [Header] }], style: [{ type: Input }], styleClass: [{ type: Input }], placeholder: [{ type: Input }], formats: [{ type: Input }], modules: [{ type: Input }], bounds: [{ type: Input }], scrollingContainer: [{ type: Input }], debug: [{ type: Input }], onInit: [{ type: Output }], templates: [{ type: ContentChildren, args: [PrimeTemplate] }], readonly: [{ type: Input }] } }); class EditorModule { } EditorModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: EditorModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); EditorModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: EditorModule, declarations: [Editor], imports: [CommonModule], exports: [Editor, SharedModule] }); EditorModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: EditorModule, imports: [[CommonModule], SharedModule] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: EditorModule, decorators: [{ type: NgModule, args: [{ imports: [CommonModule], exports: [Editor, SharedModule], declarations: [Editor] }] }] }); /** * Generated bundle index. Do not edit. */ export { EDITOR_VALUE_ACCESSOR, Editor, EditorModule }; //# sourceMappingURL=primeng-editor.js.map
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.7_A3_T12; * @section: 15.10.2.7; * @assertion: The production QuantifierPrefix :: + evaluates by returning the two results 1 and \infty; * @description: Execute /(b+)(b+)(b+)/.exec("abbbbbbbc") and check results; */ __executed = /(b+)(b+)(b+)/.exec("abbbbbbbc"); __expected = ["bbbbbbb","bbbbb","b","b"]; __expected.index = 1; __expected.input = "abbbbbbbc"; //CHECK#1 if (__executed.length !== __expected.length) { $ERROR('#1: __executed = /(b+)(b+)(b+)/.exec("abbbbbbbc"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length); } //CHECK#2 if (__executed.index !== __expected.index) { $ERROR('#2: __executed = /(b+)(b+)(b+)/.exec("abbbbbbbc"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index); } //CHECK#3 if (__executed.input !== __expected.input) { $ERROR('#3: __executed = /(b+)(b+)(b+)/.exec("abbbbbbbc"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input); } //CHECK#4 for(var index=0; index<__expected.length; index++) { if (__executed[index] !== __expected[index]) { $ERROR('#4: __executed = /(b+)(b+)(b+)/.exec("abbbbbbbc"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]); } }
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var cors = require('cors'); var app = express(); // Allow CORS, you may want to configure this for your domains app.use(cors()); require('./bootstrap/middleware')(app); // Mail isn't needed. If you want it THERE BE DRAGONS // require('./bootstrap/mail')(app); require('./bootstrap/mongo'); require('./app/models'); require('./app/transformers'); app.use(require('./app/middleware/xmen')); app.use(require('./app/middleware/origin-signing')); app.oauth = require('./app/oauth'); app.all('/oauth/token', app.oauth.grant()); var routes = require('./app/http/routes'); app.use('/', routes); require('./bootstrap/errors')(app); app.use(app.oauth.errorHandler()); module.exports = app;
define(function (require, exports, module) {// https://www.npmjs.org/package/react-interpolate-component 'use strict'; var React = require('react'); var merge = require('./utils/merge'); var ValidComponentChildren = require('./utils/ValidComponentChildren'); var REGEXP = /\%\((.+?)\)s/; var Interpolate = React.createClass({ displayName: 'Interpolate', propTypes: { format: React.PropTypes.string }, getDefaultProps: function() { return { component: React.DOM.span }; }, render: function() { var format = ValidComponentChildren.hasValidComponent(this.props.children) ? this.props.children : this.props.format; var parent = this.props.component; var unsafe = this.props.unsafe === true; var props = merge(this.props); delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { var content = format.split(REGEXP).reduce(function(memo, match, index) { var html; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (React.isValidComponent(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return parent(props); } else { var args = format.split(REGEXP).reduce(function(memo, match, index) { var child; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, [props]); return parent.apply(null, args); } } }); module.exports = Interpolate; });
export default function (searchString, position) { position = position || 0; return this.substr(position, searchString.length) === searchString; }
(function() { var _ = typeof require == 'function' ? require('..') : window._; QUnit.module('Collections'); test('each', function(assert) { _.each([1, 2, 3], function(num, i) { assert.equal(num, i + 1, 'each iterators provide value and iteration count'); }); var answers = []; _.each([1, 2, 3], function(num){ answers.push(num * this.multiplier); }, {multiplier: 5}); assert.deepEqual(answers, [5, 10, 15], 'context object property accessed'); answers = []; _.each([1, 2, 3], function(num){ answers.push(num); }); assert.deepEqual(answers, [1, 2, 3], 'aliased as "forEach"'); answers = []; var obj = {one: 1, two: 2, three: 3}; obj.constructor.prototype.four = 4; _.each(obj, function(value, key){ answers.push(key); }); assert.deepEqual(answers, ['one', 'two', 'three'], 'iterating over objects works, and ignores the object prototype.'); delete obj.constructor.prototype.four; // ensure the each function is JITed _(1000).times(function() { _.each([], function(){}); }); var count = 0; obj = {1: 'foo', 2: 'bar', 3: 'baz'}; _.each(obj, function(){ count++; }); assert.equal(count, 3, 'the fun should be called only 3 times'); var answer = null; _.each([1, 2, 3], function(num, index, arr){ if (_.include(arr, num)) answer = true; }); assert.ok(answer, 'can reference the original collection from inside the iterator'); answers = 0; _.each(null, function(){ ++answers; }); assert.equal(answers, 0, 'handles a null properly'); _.each(false, function(){}); var a = [1, 2, 3]; assert.strictEqual(_.each(a, function(){}), a); assert.strictEqual(_.each(null, function(){}), null); }); test('forEach', function(assert) { assert.strictEqual(_.each, _.forEach, 'alias for each'); }); test('lookupIterator with contexts', function(assert) { _.each([true, false, 'yes', '', 0, 1, {}], function(context) { _.each([1], function() { assert.equal(this, context); }, context); }); }); test('Iterating objects with sketchy length properties', function(assert) { var functions = [ 'each', 'map', 'filter', 'find', 'some', 'every', 'max', 'min', 'groupBy', 'countBy', 'partition', 'indexBy' ]; var reducers = ['reduce', 'reduceRight']; var tricks = [ {length: '5'}, { length: { valueOf: _.constant(5) } }, {length: Math.pow(2, 53) + 1}, {length: Math.pow(2, 53)}, {length: null}, {length: -2}, {length: new Number(15)} ]; assert.expect(tricks.length * (functions.length + reducers.length + 4)); _.each(tricks, function(trick) { var length = trick.length; assert.strictEqual(_.size(trick), 1, 'size on obj with length: ' + length); assert.deepEqual(_.toArray(trick), [length], 'toArray on obj with length: ' + length); assert.deepEqual(_.shuffle(trick), [length], 'shuffle on obj with length: ' + length); assert.deepEqual(_.sample(trick), length, 'sample on obj with length: ' + length); _.each(functions, function(method) { _[method](trick, function(val, key) { assert.strictEqual(key, 'length', method + ': ran with length = ' + val); }); }); _.each(reducers, function(method) { assert.strictEqual(_[method](trick), trick.length, method); }); }); }); test('Resistant to collection length and properties changing while iterating', function(assert) { var collection = [ 'each', 'map', 'filter', 'find', 'some', 'every', 'max', 'min', 'reject', 'groupBy', 'countBy', 'partition', 'indexBy', 'reduce', 'reduceRight' ]; var array = [ 'findIndex', 'findLastIndex' ]; var object = [ 'mapObject', 'findKey', 'pick', 'omit' ]; _.each(collection.concat(array), function(method) { var sparseArray = [1, 2, 3]; sparseArray.length = 100; var answers = 0; _[method](sparseArray, function(){ ++answers; return method === 'every' ? true : null; }, {}); assert.equal(answers, 100, method + ' enumerates [0, length)'); var growingCollection = [1, 2, 3], count = 0; _[method](growingCollection, function() { if (count < 10) growingCollection.push(count++); return method === 'every' ? true : null; }, {}); assert.equal(count, 3, method + ' is resistant to length changes'); }); _.each(collection.concat(object), function(method) { var changingObject = {0: 0, 1: 1}, count = 0; _[method](changingObject, function(val) { if (count < 10) changingObject[++count] = val + 1; return method === 'every' ? true : null; }, {}); assert.equal(count, 2, method + ' is resistant to property changes'); }); }); test('map', function(assert) { var doubled = _.map([1, 2, 3], function(num){ return num * 2; }); assert.deepEqual(doubled, [2, 4, 6], 'doubled numbers'); var tripled = _.map([1, 2, 3], function(num){ return num * this.multiplier; }, {multiplier: 3}); assert.deepEqual(tripled, [3, 6, 9], 'tripled numbers with context'); doubled = _([1, 2, 3]).map(function(num){ return num * 2; }); assert.deepEqual(doubled, [2, 4, 6], 'OO-style doubled numbers'); var ids = _.map({length: 2, 0: {id: '1'}, 1: {id: '2'}}, function(n){ return n.id; }); assert.deepEqual(ids, ['1', '2'], 'Can use collection methods on Array-likes.'); assert.deepEqual(_.map(null, _.noop), [], 'handles a null properly'); assert.deepEqual(_.map([1], function() { return this.length; }, [5]), [1], 'called with context'); // Passing a property name like _.pluck. var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}]; assert.deepEqual(_.map(people, 'name'), ['moe', 'curly'], 'predicate string map to object properties'); }); test('collect', function(assert) { assert.strictEqual(_.map, _.collect, 'alias for map'); }); test('reduce', function(assert) { var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0); assert.equal(sum, 6, 'can sum up an array'); var context = {multiplier: 3}; sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num * this.multiplier; }, 0, context); assert.equal(sum, 18, 'can reduce with a context object'); sum = _.inject([1, 2, 3], function(memo, num){ return memo + num; }, 0); assert.equal(sum, 6, 'aliased as "inject"'); sum = _([1, 2, 3]).reduce(function(memo, num){ return memo + num; }, 0); assert.equal(sum, 6, 'OO-style reduce'); sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }); assert.equal(sum, 6, 'default initial value'); var prod = _.reduce([1, 2, 3, 4], function(memo, num){ return memo * num; }); assert.equal(prod, 24, 'can reduce via multiplication'); assert.ok(_.reduce(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); assert.equal(_.reduce([], _.noop, void 0), void 0, 'undefined can be passed as a special case'); assert.equal(_.reduce([_], _.noop), _, 'collection of length one with no initial value returns the first item'); assert.equal(_.reduce([], _.noop), void 0, 'returns undefined when collection is empty and no initial value'); }); test('foldl', function(assert) { assert.strictEqual(_.reduce, _.foldl, 'alias for reduce'); }); test('reduceRight', function(assert) { var list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }, ''); assert.equal(list, 'bazbarfoo', 'can perform right folds'); list = _.reduceRight(['foo', 'bar', 'baz'], function(memo, str){ return memo + str; }); assert.equal(list, 'bazbarfoo', 'default initial value'); var sum = _.reduceRight({a: 1, b: 2, c: 3}, function(memo, num){ return memo + num; }); assert.equal(sum, 6, 'default initial value on object'); assert.ok(_.reduceRight(null, _.noop, 138) === 138, 'handles a null (with initial value) properly'); assert.equal(_.reduceRight([_], _.noop), _, 'collection of length one with no initial value returns the first item'); assert.equal(_.reduceRight([], _.noop, void 0), void 0, 'undefined can be passed as a special case'); assert.equal(_.reduceRight([], _.noop), void 0, 'returns undefined when collection is empty and no initial value'); // Assert that the correct arguments are being passed. var args, init = {}, object = {a: 1, b: 2}, lastKey = _.keys(object).pop(); var expected = lastKey === 'a' ? [init, 1, 'a', object] : [init, 2, 'b', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, init); assert.deepEqual(args, expected); // And again, with numeric keys. object = {2: 'a', 1: 'b'}; lastKey = _.keys(object).pop(); args = null; expected = lastKey === '2' ? [init, 'a', '2', object] : [init, 'b', '1', object]; _.reduceRight(object, function() { if (!args) args = _.toArray(arguments); }, init); assert.deepEqual(args, expected); }); test('foldr', function(assert) { assert.strictEqual(_.reduceRight, _.foldr, 'alias for reduceRight'); }); test('find', function(assert) { var array = [1, 2, 3, 4]; assert.strictEqual(_.find(array, function(n) { return n > 2; }), 3, 'should return first found `value`'); assert.strictEqual(_.find(array, function() { return false; }), void 0, 'should return `undefined` if `value` is not found'); array.dontmatch = 55; assert.strictEqual(_.find(array, function(x) { return x === 55; }), void 0, 'iterates array-likes correctly'); // Matching an object like _.findWhere. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; assert.deepEqual(_.find(list, {a: 1}), {a: 1, b: 2}, 'can be used as findWhere'); assert.deepEqual(_.find(list, {b: 4}), {a: 1, b: 4}); assert.ok(!_.find(list, {c: 1}), 'undefined when not found'); assert.ok(!_.find([], {c: 1}), 'undefined when searching empty list'); var result = _.find([1, 2, 3], function(num){ return num * 2 === 4; }); assert.equal(result, 2, 'found the first "2" and broke the loop'); var obj = { a: {x: 1, z: 3}, b: {x: 2, z: 2}, c: {x: 3, z: 4}, d: {x: 4, z: 1} }; assert.deepEqual(_.find(obj, {x: 2}), {x: 2, z: 2}, 'works on objects'); assert.deepEqual(_.find(obj, {x: 2, z: 1}), void 0); assert.deepEqual(_.find(obj, function(x) { return x.x === 4; }), {x: 4, z: 1}); _.findIndex([{a: 1}], function(a, key, o) { assert.equal(key, 0); assert.deepEqual(o, [{a: 1}]); assert.strictEqual(this, _, 'called with context'); }, _); }); test('detect', function(assert) { assert.strictEqual(_.detect, _.find, 'alias for detect'); }); test('filter', function(assert) { var evenArray = [1, 2, 3, 4, 5, 6]; var evenObject = {one: 1, two: 2, three: 3}; var isEven = function(num){ return num % 2 === 0; }; assert.deepEqual(_.filter(evenArray, isEven), [2, 4, 6]); assert.deepEqual(_.filter(evenObject, isEven), [2], 'can filter objects'); assert.deepEqual(_.filter([{}, evenObject, []], 'two'), [evenObject], 'predicate string map to object properties'); _.filter([1], function() { assert.equal(this, evenObject, 'given context'); }, evenObject); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.deepEqual(_.filter(list, {a: 1}), [{a: 1, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]); assert.deepEqual(_.filter(list, {b: 2}), [{a: 1, b: 2}, {a: 2, b: 2}]); assert.deepEqual(_.filter(list, {}), list, 'Empty object accepts all items'); assert.deepEqual(_(list).filter({}), list, 'OO-filter'); }); test('select', function(assert) { assert.strictEqual(_.filter, _.select, 'alias for filter'); }); test('reject', function(assert) { var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 === 0; }); assert.deepEqual(odds, [1, 3, 5], 'rejected each even number'); var context = 'obj'; var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ assert.equal(context, 'obj'); return num % 2 !== 0; }, context); assert.deepEqual(evens, [2, 4, 6], 'rejected each odd number'); assert.deepEqual(_.reject([odds, {one: 1, two: 2, three: 3}], 'two'), [odds], 'predicate string map to object properties'); // Can be used like _.where. var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.deepEqual(_.reject(list, {a: 1}), [{a: 2, b: 2}]); assert.deepEqual(_.reject(list, {b: 2}), [{a: 1, b: 3}, {a: 1, b: 4}]); assert.deepEqual(_.reject(list, {}), [], 'Returns empty list given empty object'); assert.deepEqual(_.reject(list, []), [], 'Returns empty list given empty array'); }); test('every', function(assert) { assert.ok(_.every([], _.identity), 'the empty set'); assert.ok(_.every([true, true, true], _.identity), 'every true values'); assert.ok(!_.every([true, false, true], _.identity), 'one false value'); assert.ok(_.every([0, 10, 28], function(num){ return num % 2 === 0; }), 'even numbers'); assert.ok(!_.every([0, 11, 28], function(num){ return num % 2 === 0; }), 'an odd number'); assert.ok(_.every([1], _.identity) === true, 'cast to boolean - true'); assert.ok(_.every([0], _.identity) === false, 'cast to boolean - false'); assert.ok(!_.every([void 0, void 0, void 0], _.identity), 'works with arrays of undefined'); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.ok(!_.every(list, {a: 1, b: 2}), 'Can be called with object'); assert.ok(_.every(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; assert.ok(_.every(list, {b: 2}), 'Can be called with object'); assert.ok(!_.every(list, 'c'), 'String mapped to object property'); assert.ok(_.every({a: 1, b: 2, c: 3, d: 4}, _.isNumber), 'takes objects'); assert.ok(!_.every({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); assert.ok(_.every(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); assert.ok(!_.every(['a', 'b', 'c', 'd', 'f'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); test('all', function(assert) { assert.strictEqual(_.all, _.every, 'alias for all'); }); test('some', function(assert) { assert.ok(!_.some([]), 'the empty set'); assert.ok(!_.some([false, false, false]), 'all false values'); assert.ok(_.some([false, false, true]), 'one true value'); assert.ok(_.some([null, 0, 'yes', false]), 'a string'); assert.ok(!_.some([null, 0, '', false]), 'falsy values'); assert.ok(!_.some([1, 11, 29], function(num){ return num % 2 === 0; }), 'all odd numbers'); assert.ok(_.some([1, 10, 29], function(num){ return num % 2 === 0; }), 'an even number'); assert.ok(_.some([1], _.identity) === true, 'cast to boolean - true'); assert.ok(_.some([0], _.identity) === false, 'cast to boolean - false'); assert.ok(_.some([false, false, true])); var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; assert.ok(!_.some(list, {a: 5, b: 2}), 'Can be called with object'); assert.ok(_.some(list, 'a'), 'String mapped to object property'); list = [{a: 1, b: 2}, {a: 2, b: 2, c: true}]; assert.ok(_.some(list, {b: 2}), 'Can be called with object'); assert.ok(!_.some(list, 'd'), 'String mapped to object property'); assert.ok(_.some({a: '1', b: '2', c: '3', d: '4', e: 6}, _.isNumber), 'takes objects'); assert.ok(!_.some({a: 1, b: 2, c: 3, d: 4}, _.isObject), 'takes objects'); assert.ok(_.some(['a', 'b', 'c', 'd'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); assert.ok(!_.some(['x', 'y', 'z'], _.hasOwnProperty, {a: 1, b: 2, c: 3, d: 4}), 'context works'); }); test('any', function(assert) { assert.strictEqual(_.any, _.some, 'alias for any'); }); test('includes', function(assert) { _.each([null, void 0, 0, 1, NaN, {}, []], function(val) { assert.strictEqual(_.includes(val, 'hasOwnProperty'), false); }); assert.strictEqual(_.includes([1, 2, 3], 2), true, 'two is in the array'); assert.ok(!_.includes([1, 3, 9], 2), 'two is not in the array'); assert.strictEqual(_.includes([5, 4, 3, 2, 1], 5, true), true, 'doesn\'t delegate to binary search'); assert.ok(_.includes({moe: 1, larry: 3, curly: 9}, 3) === true, '_.includes on objects checks their values'); assert.ok(_([1, 2, 3]).includes(2), 'OO-style includes'); }); test('include', function(assert) { assert.strictEqual(_.includes, _.include, 'alias for includes'); }); test('contains', function(assert) { assert.strictEqual(_.includes, _.contains, 'alias for includes'); var numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3]; assert.strictEqual(_.includes(numbers, 1, 1), true, 'contains takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, -1), false, 'contains takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, -2), false, 'contains takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, -3), true, 'contains takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, 6), true, 'contains takes a fromIndex'); assert.strictEqual(_.includes(numbers, 1, 7), false, 'contains takes a fromIndex'); assert.ok(_.every([1, 2, 3], _.partial(_.contains, numbers)), 'fromIndex is guarded'); }); test('includes with NaN', function(assert) { assert.strictEqual(_.includes([1, 2, NaN, NaN], NaN), true, 'Expected [1, 2, NaN] to contain NaN'); assert.strictEqual(_.includes([1, 2, Infinity], NaN), false, 'Expected [1, 2, NaN] to contain NaN'); }); test('includes with +- 0', function(assert) { _.each([-0, +0], function(val) { assert.strictEqual(_.includes([1, 2, val, val], val), true); assert.strictEqual(_.includes([1, 2, val, val], -val), true); assert.strictEqual(_.includes([-1, 1, 2], -val), false); }); }); test('invoke', 5, function(assert) { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, 'sort'); assert.deepEqual(result[0], [1, 5, 7], 'first array sorted'); assert.deepEqual(result[1], [1, 2, 3], 'second array sorted'); _.invoke([{ method: function() { assert.deepEqual(_.toArray(arguments), [1, 2, 3], 'called with arguments'); } }], 'method', 1, 2, 3); assert.deepEqual(_.invoke([{a: null}, {}, {a: _.constant(1)}], 'a'), [null, void 0, 1], 'handles null & undefined'); assert.throws(function() { _.invoke([{a: 1}], 'a'); }, TypeError, 'throws for non-functions'); }); test('invoke w/ function reference', function(assert) { var list = [[5, 1, 7], [3, 2, 1]]; var result = _.invoke(list, Array.prototype.sort); assert.deepEqual(result[0], [1, 5, 7], 'first array sorted'); assert.deepEqual(result[1], [1, 2, 3], 'second array sorted'); assert.deepEqual(_.invoke([1, 2, 3], function(a) { return a + this; }, 5), [6, 7, 8], 'receives params from invoke'); }); // Relevant when using ClojureScript test('invoke when strings have a call method', function(assert) { String.prototype.call = function() { return 42; }; var list = [[5, 1, 7], [3, 2, 1]]; var s = 'foo'; assert.equal(s.call(), 42, 'call function exists'); var result = _.invoke(list, 'sort'); assert.deepEqual(result[0], [1, 5, 7], 'first array sorted'); assert.deepEqual(result[1], [1, 2, 3], 'second array sorted'); delete String.prototype.call; assert.equal(s.call, void 0, 'call function removed'); }); test('pluck', function(assert) { var people = [{name: 'moe', age: 30}, {name: 'curly', age: 50}]; assert.deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'pulls names out of objects'); assert.deepEqual(_.pluck(people, 'address'), [void 0, void 0], 'missing properties are returned as undefined'); //compat: most flexible handling of edge cases assert.deepEqual(_.pluck([{'[object Object]': 1}], {}), [1]); }); test('where', function(assert) { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}]; var result = _.where(list, {a: 1}); assert.equal(result.length, 3); assert.equal(result[result.length - 1].b, 4); result = _.where(list, {b: 2}); assert.equal(result.length, 2); assert.equal(result[0].a, 1); result = _.where(list, {}); assert.equal(result.length, list.length); function test() {} test.map = _.map; assert.deepEqual(_.where([_, {a: 1, b: 2}, _], test), [_, _], 'checks properties given function'); }); test('findWhere', function(assert) { var list = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 1, b: 3}, {a: 1, b: 4}, {a: 2, b: 4}]; var result = _.findWhere(list, {a: 1}); assert.deepEqual(result, {a: 1, b: 2}); result = _.findWhere(list, {b: 4}); assert.deepEqual(result, {a: 1, b: 4}); result = _.findWhere(list, {c: 1}); assert.ok(_.isUndefined(result), 'undefined when not found'); result = _.findWhere([], {c: 1}); assert.ok(_.isUndefined(result), 'undefined when searching empty list'); function test() {} test.map = _.map; assert.equal(_.findWhere([_, {a: 1, b: 2}, _], test), _, 'checks properties given function'); function TestClass() { this.y = 5; this.x = 'foo'; } var expect = {c: 1, x: 'foo', y: 5}; assert.deepEqual(_.findWhere([{y: 5, b: 6}, expect], new TestClass()), expect, 'uses class instance properties'); }); test('max', function(assert) { assert.equal(-Infinity, _.max(null), 'can handle null/undefined'); assert.equal(-Infinity, _.max(void 0), 'can handle null/undefined'); assert.equal(-Infinity, _.max(null, _.identity), 'can handle null/undefined'); assert.equal(3, _.max([1, 2, 3]), 'can perform a regular Math.max'); var neg = _.max([1, 2, 3], function(num){ return -num; }); assert.equal(neg, 1, 'can perform a computation-based max'); assert.equal(-Infinity, _.max({}), 'Maximum value of an empty object'); assert.equal(-Infinity, _.max([]), 'Maximum value of an empty array'); assert.equal(_.max({a: 'a'}), -Infinity, 'Maximum value of a non-numeric collection'); assert.equal(299999, _.max(_.range(1, 300000)), 'Maximum value of a too-big array'); assert.equal(3, _.max([1, 2, 3, 'test']), 'Finds correct max in array starting with num and containing a NaN'); assert.equal(3, _.max(['test', 1, 2, 3]), 'Finds correct max in array starting with NaN'); assert.deepEqual([3, 6], _.map([[1, 2, 3], [4, 5, 6]], _.max), 'Finds correct max in array when mapping through multiple arrays'); var a = {x: -Infinity}; var b = {x: -Infinity}; var iterator = function(o){ return o.x; }; assert.equal(_.max([a, b], iterator), a, 'Respects iterator return value of -Infinity'); assert.deepEqual(_.max([{a: 1}, {a: 0, b: 3}, {a: 4}, {a: 2}], 'a'), {a: 4}, 'String keys use property iterator'); assert.deepEqual(_.max([0, 2], function(c){ return c * this.x; }, {x: 1}), 2, 'Iterator context'); assert.deepEqual(_.max([[1], [2, 3], [-1, 4], [5]], 0), [5], 'Lookup falsy iterator'); assert.deepEqual(_.max([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: 2}, 'Lookup falsy iterator'); }); test('min', function(assert) { assert.equal(Infinity, _.min(null), 'can handle null/undefined'); assert.equal(Infinity, _.min(void 0), 'can handle null/undefined'); assert.equal(Infinity, _.min(null, _.identity), 'can handle null/undefined'); assert.equal(1, _.min([1, 2, 3]), 'can perform a regular Math.min'); var neg = _.min([1, 2, 3], function(num){ return -num; }); assert.equal(neg, 3, 'can perform a computation-based min'); assert.equal(Infinity, _.min({}), 'Minimum value of an empty object'); assert.equal(Infinity, _.min([]), 'Minimum value of an empty array'); assert.equal(_.min({a: 'a'}), Infinity, 'Minimum value of a non-numeric collection'); assert.deepEqual([1, 4], _.map([[1, 2, 3], [4, 5, 6]], _.min), 'Finds correct min in array when mapping through multiple arrays'); var now = new Date(9999999999); var then = new Date(0); assert.equal(_.min([now, then]), then); assert.equal(1, _.min(_.range(1, 300000)), 'Minimum value of a too-big array'); assert.equal(1, _.min([1, 2, 3, 'test']), 'Finds correct min in array starting with num and containing a NaN'); assert.equal(1, _.min(['test', 1, 2, 3]), 'Finds correct min in array starting with NaN'); var a = {x: Infinity}; var b = {x: Infinity}; var iterator = function(o){ return o.x; }; assert.equal(_.min([a, b], iterator), a, 'Respects iterator return value of Infinity'); assert.deepEqual(_.min([{a: 1}, {a: 0, b: 3}, {a: 4}, {a: 2}], 'a'), {a: 0, b: 3}, 'String keys use property iterator'); assert.deepEqual(_.min([0, 2], function(c){ return c * this.x; }, {x: -1}), 2, 'Iterator context'); assert.deepEqual(_.min([[1], [2, 3], [-1, 4], [5]], 0), [-1, 4], 'Lookup falsy iterator'); assert.deepEqual(_.min([{0: 1}, {0: 2}, {0: -1}, {a: 1}], 0), {0: -1}, 'Lookup falsy iterator'); }); test('sortBy', function(assert) { var people = [{name: 'curly', age: 50}, {name: 'moe', age: 30}]; people = _.sortBy(people, function(person){ return person.age; }); assert.deepEqual(_.pluck(people, 'name'), ['moe', 'curly'], 'stooges sorted by age'); var list = [void 0, 4, 1, void 0, 3, 2]; assert.deepEqual(_.sortBy(list, _.identity), [1, 2, 3, 4, void 0, void 0], 'sortBy with undefined values'); list = ['one', 'two', 'three', 'four', 'five']; var sorted = _.sortBy(list, 'length'); assert.deepEqual(sorted, ['one', 'two', 'four', 'five', 'three'], 'sorted by length'); function Pair(x, y) { this.x = x; this.y = y; } var stableArray = [ new Pair(1, 1), new Pair(1, 2), new Pair(1, 3), new Pair(1, 4), new Pair(1, 5), new Pair(1, 6), new Pair(2, 1), new Pair(2, 2), new Pair(2, 3), new Pair(2, 4), new Pair(2, 5), new Pair(2, 6), new Pair(void 0, 1), new Pair(void 0, 2), new Pair(void 0, 3), new Pair(void 0, 4), new Pair(void 0, 5), new Pair(void 0, 6) ]; var stableObject = _.object('abcdefghijklmnopqr'.split(''), stableArray); var actual = _.sortBy(stableArray, function(pair) { return pair.x; }); assert.deepEqual(actual, stableArray, 'sortBy should be stable for arrays'); assert.deepEqual(_.sortBy(stableArray, 'x'), stableArray, 'sortBy accepts property string'); actual = _.sortBy(stableObject, function(pair) { return pair.x; }); assert.deepEqual(actual, stableArray, 'sortBy should be stable for objects'); list = ['q', 'w', 'e', 'r', 't', 'y']; assert.deepEqual(_.sortBy(list), ['e', 'q', 'r', 't', 'w', 'y'], 'uses _.identity if iterator is not specified'); }); test('groupBy', function(assert) { var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; }); assert.ok('0' in parity && '1' in parity, 'created a group for each value'); assert.deepEqual(parity[0], [2, 4, 6], 'put each even number in the right group'); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.groupBy(list, 'length'); assert.deepEqual(grouped['3'], ['one', 'two', 'six', 'ten']); assert.deepEqual(grouped['4'], ['four', 'five', 'nine']); assert.deepEqual(grouped['5'], ['three', 'seven', 'eight']); var context = {}; _.groupBy([{}], function(){ assert.ok(this === context); }, context); grouped = _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); assert.equal(grouped.constructor.length, 1); assert.equal(grouped.hasOwnProperty.length, 2); var array = [{}]; _.groupBy(array, function(value, index, obj){ assert.ok(obj === array); }); array = [1, 2, 1, 2, 3]; grouped = _.groupBy(array); assert.equal(grouped['1'].length, 2); assert.equal(grouped['3'].length, 1); var matrix = [ [1, 2], [1, 3], [2, 3] ]; assert.deepEqual(_.groupBy(matrix, 0), {1: [[1, 2], [1, 3]], 2: [[2, 3]]}); assert.deepEqual(_.groupBy(matrix, 1), {2: [[1, 2]], 3: [[1, 3], [2, 3]]}); }); test('indexBy', function(assert) { var parity = _.indexBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); assert.equal(parity['true'], 4); assert.equal(parity['false'], 5); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.indexBy(list, 'length'); assert.equal(grouped['3'], 'ten'); assert.equal(grouped['4'], 'nine'); assert.equal(grouped['5'], 'eight'); var array = [1, 2, 1, 2, 3]; grouped = _.indexBy(array); assert.equal(grouped['1'], 1); assert.equal(grouped['2'], 2); assert.equal(grouped['3'], 3); }); test('countBy', function(assert) { var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 === 0; }); assert.equal(parity['true'], 2); assert.equal(parity['false'], 3); var list = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']; var grouped = _.countBy(list, 'length'); assert.equal(grouped['3'], 4); assert.equal(grouped['4'], 3); assert.equal(grouped['5'], 3); var context = {}; _.countBy([{}], function(){ assert.ok(this === context); }, context); grouped = _.countBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor'; }); assert.equal(grouped.constructor, 1); assert.equal(grouped.hasOwnProperty, 2); var array = [{}]; _.countBy(array, function(value, index, obj){ assert.ok(obj === array); }); array = [1, 2, 1, 2, 3]; grouped = _.countBy(array); assert.equal(grouped['1'], 2); assert.equal(grouped['3'], 1); }); test('shuffle', function(assert) { assert.deepEqual(_.shuffle([1]), [1], 'behaves correctly on size 1 arrays'); var numbers = _.range(20); var shuffled = _.shuffle(numbers); assert.notDeepEqual(numbers, shuffled, 'does change the order'); // Chance of false negative: 1 in ~2.4*10^18 assert.notStrictEqual(numbers, shuffled, 'original object is unmodified'); assert.deepEqual(numbers, _.sortBy(shuffled), 'contains the same members before and after shuffle'); shuffled = _.shuffle({a: 1, b: 2, c: 3, d: 4}); assert.equal(shuffled.length, 4); assert.deepEqual(shuffled.sort(), [1, 2, 3, 4], 'works on objects'); }); test('sample', function(assert) { assert.strictEqual(_.sample([1]), 1, 'behaves correctly when no second parameter is given'); assert.deepEqual(_.sample([1, 2, 3], -2), [], 'behaves correctly on negative n'); var numbers = _.range(10); var allSampled = _.sample(numbers, 10).sort(); assert.deepEqual(allSampled, numbers, 'contains the same members before and after sample'); allSampled = _.sample(numbers, 20).sort(); assert.deepEqual(allSampled, numbers, 'also works when sampling more objects than are present'); assert.ok(_.contains(numbers, _.sample(numbers)), 'sampling a single element returns something from the array'); assert.strictEqual(_.sample([]), void 0, 'sampling empty array with no number returns undefined'); assert.notStrictEqual(_.sample([], 5), [], 'sampling empty array with a number returns an empty array'); assert.notStrictEqual(_.sample([1, 2, 3], 0), [], 'sampling an array with 0 picks returns an empty array'); assert.deepEqual(_.sample([1, 2], -1), [], 'sampling a negative number of picks returns an empty array'); assert.ok(_.contains([1, 2, 3], _.sample({a: 1, b: 2, c: 3})), 'sample one value from an object'); var partialSample = _.sample(_.range(1000), 10); var partialSampleSorted = partialSample.sort(); assert.notDeepEqual(partialSampleSorted, _.range(10), 'samples from the whole array, not just the beginning'); }); test('toArray', function(assert) { assert.ok(!_.isArray(arguments), 'arguments object is not an array'); assert.ok(_.isArray(_.toArray(arguments)), 'arguments object converted into array'); var a = [1, 2, 3]; assert.ok(_.toArray(a) !== a, 'array is cloned'); assert.deepEqual(_.toArray(a), [1, 2, 3], 'cloned array contains same elements'); var numbers = _.toArray({one: 1, two: 2, three: 3}); assert.deepEqual(numbers, [1, 2, 3], 'object flattened into array'); var astral = _.toArray('\udfff💩poop💩\ud800'); assert.deepEqual(astral, ['\udfff', '💩', 'p', 'o', 'o', 'p', '💩', '\ud800'], 'maintains astral characters'); assert.deepEqual(_.toArray(''), [], 'empty string into empty array'); if (typeof document != 'undefined') { // test in IE < 9 var actual; try { actual = _.toArray(document.childNodes); } catch(e) { /* ignored */ } assert.deepEqual(actual, _.map(document.childNodes, _.identity), 'works on NodeList'); } }); test('size', function(assert) { assert.equal(_.size({one: 1, two: 2, three: 3}), 3, 'can compute the size of an object'); assert.equal(_.size([1, 2, 3]), 3, 'can compute the size of an array'); assert.equal(_.size({length: 3, 0: 0, 1: 0, 2: 0}), 3, 'can compute the size of Array-likes'); var func = function() { return _.size(arguments); }; assert.equal(func(1, 2, 3, 4), 4, 'can test the size of the arguments object'); assert.equal(_.size('hello'), 5, 'can compute the size of a string literal'); assert.equal(_.size(new String('hello')), 5, 'can compute the size of string object'); assert.equal(_.size(null), 0, 'handles nulls'); assert.equal(_.size(0), 0, 'handles numbers'); }); test('partition', function(assert) { var list = [0, 1, 2, 3, 4, 5]; assert.deepEqual(_.partition(list, function(x) { return x < 4; }), [[0, 1, 2, 3], [4, 5]], 'handles bool return values'); assert.deepEqual(_.partition(list, function(x) { return x & 1; }), [[1, 3, 5], [0, 2, 4]], 'handles 0 and 1 return values'); assert.deepEqual(_.partition(list, function(x) { return x - 3; }), [[0, 1, 2, 4, 5], [3]], 'handles other numeric return values'); assert.deepEqual(_.partition(list, function(x) { return x > 1 ? null : true; }), [[0, 1], [2, 3, 4, 5]], 'handles null return values'); assert.deepEqual(_.partition(list, function(x) { if (x < 2) return true; }), [[0, 1], [2, 3, 4, 5]], 'handles undefined return values'); assert.deepEqual(_.partition({a: 1, b: 2, c: 3}, function(x) { return x > 1; }), [[2, 3], [1]], 'handles objects'); assert.deepEqual(_.partition(list, function(x, index) { return index % 2; }), [[1, 3, 5], [0, 2, 4]], 'can reference the array index'); assert.deepEqual(_.partition(list, function(x, index, arr) { return x === arr.length - 1; }), [[5], [0, 1, 2, 3, 4]], 'can reference the collection'); // Default iterator assert.deepEqual(_.partition([1, false, true, '']), [[1, true], [false, '']], 'Default iterator'); assert.deepEqual(_.partition([{x: 1}, {x: 0}, {x: 1}], 'x'), [[{x: 1}, {x: 1}], [{x: 0}]], 'Takes a string'); // Context var predicate = function(x){ return x === this.x; }; assert.deepEqual(_.partition([1, 2, 3], predicate, {x: 2}), [[2], [1, 3]], 'partition takes a context argument'); assert.deepEqual(_.partition([{a: 1}, {b: 2}, {a: 1, b: 2}], {a: 1}), [[{a: 1}, {a: 1, b: 2}], [{b: 2}]], 'predicate can be object'); var object = {a: 1}; _.partition(object, function(val, key, obj) { assert.equal(val, 1); assert.equal(key, 'a'); assert.equal(obj, object); assert.equal(this, predicate); }, predicate); }); if (typeof document != 'undefined') { test('Can use various collection methods on NodeLists', function(assert) { var parent = document.createElement('div'); parent.innerHTML = '<span id=id1></span>textnode<span id=id2></span>'; var elementChildren = _.filter(parent.childNodes, _.isElement); assert.equal(elementChildren.length, 2); assert.deepEqual(_.map(elementChildren, 'id'), ['id1', 'id2']); assert.deepEqual(_.map(parent.childNodes, 'nodeType'), [1, 3, 1]); assert.ok(!_.every(parent.childNodes, _.isElement)); assert.ok(_.some(parent.childNodes, _.isElement)); function compareNode(node) { return _.isElement(node) ? node.id.charAt(2) : void 0; } assert.equal(_.max(parent.childNodes, compareNode), _.last(parent.childNodes)); assert.equal(_.min(parent.childNodes, compareNode), _.first(parent.childNodes)); }); } }());
/* global diff_match_patch */ var TEXT_DIFF = 2; var DEFAULT_MIN_LENGTH = 60; var cachedDiffPatch = null; var getDiffMatchPatch = function() { /*jshint camelcase: false */ if (!cachedDiffPatch) { var instance; if (typeof diff_match_patch !== 'undefined') { // already loaded, probably a browser instance = typeof diff_match_patch === 'function' ? new diff_match_patch() : new diff_match_patch.diff_match_patch(); } else if (typeof require === 'function') { try { var dmpModuleName = 'diff_match_patch_uncompressed'; var dmp = require('../../public/external/' + dmpModuleName); instance = new dmp.diff_match_patch(); } catch (err) { instance = null; } } if (!instance) { var error = new Error('text diff_match_patch library not found'); error.diff_match_patch_not_found = true; throw error; } cachedDiffPatch = { diff: function(txt1, txt2) { return instance.patch_toText(instance.patch_make(txt1, txt2)); }, patch: function(txt1, patch) { var results = instance.patch_apply(instance.patch_fromText(patch), txt1); for (var i = 0; i < results[1].length; i++) { if (!results[1][i]) { var error = new Error('text patch failed'); error.textPatchFailed = true; } } return results[0]; } }; } return cachedDiffPatch; }; var diffFilter = function textsDiffFilter(context) { if (context.leftType !== 'string') { return; } var minLength = (context.options && context.options.textDiff && context.options.textDiff.minLength) || DEFAULT_MIN_LENGTH; if (context.left.length < minLength || context.right.length < minLength) { context.setResult([context.left, context.right]).exit(); return; } // large text, use a text-diff algorithm var diff = getDiffMatchPatch().diff; context.setResult([diff(context.left, context.right), 0, TEXT_DIFF]).exit(); }; diffFilter.filterName = 'texts'; var patchFilter = function textsPatchFilter(context) { if (context.nested) { return; } if (context.delta[2] !== TEXT_DIFF) { return; } // text-diff, use a text-patch algorithm var patch = getDiffMatchPatch().patch; context.setResult(patch(context.left, context.delta[0])).exit(); }; patchFilter.filterName = 'texts'; var textDeltaReverse = function(delta) { var i, l, lines, line, lineTmp, header = null, headerRegex = /^@@ +\-(\d+),(\d+) +\+(\d+),(\d+) +@@$/, lineHeader, lineAdd, lineRemove; lines = delta.split('\n'); for (i = 0, l = lines.length; i < l; i++) { line = lines[i]; var lineStart = line.slice(0, 1); if (lineStart === '@') { header = headerRegex.exec(line); lineHeader = i; lineAdd = null; lineRemove = null; // fix header lines[lineHeader] = '@@ -' + header[3] + ',' + header[4] + ' +' + header[1] + ',' + header[2] + ' @@'; } else if (lineStart === '+') { lineAdd = i; lines[i] = '-' + lines[i].slice(1); if (lines[i - 1].slice(0, 1) === '+') { // swap lines to keep default order (-+) lineTmp = lines[i]; lines[i] = lines[i - 1]; lines[i - 1] = lineTmp; } } else if (lineStart === '-') { lineRemove = i; lines[i] = '+' + lines[i].slice(1); } } return lines.join('\n'); }; var reverseFilter = function textsReverseFilter(context) { if (context.nested) { return; } if (context.delta[2] !== TEXT_DIFF) { return; } // text-diff, use a text-diff algorithm context.setResult([textDeltaReverse(context.delta[0]), 0, TEXT_DIFF]).exit(); }; reverseFilter.filterName = 'texts'; exports.diffFilter = diffFilter; exports.patchFilter = patchFilter; exports.reverseFilter = reverseFilter;
// Generated by CoffeeScript 1.10.0 (function() { var JSONStorage, KEY_FOR_EMPTY_STRING, LocalStorage, MetaKey, QUOTA_EXCEEDED_ERR, StorageEvent, _emptyDirectory, _escapeKey, _rm, createMap, events, fs, path, writeSync, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; path = require('path'); fs = require('fs'); events = require('events'); writeSync = require('write-file-atomic').sync; KEY_FOR_EMPTY_STRING = '---.EMPTY_STRING.---'; _emptyDirectory = function(target) { var i, len, p, ref, results; ref = fs.readdirSync(target); results = []; for (i = 0, len = ref.length; i < len; i++) { p = ref[i]; results.push(_rm(path.join(target, p))); } return results; }; _rm = function(target) { if (fs.statSync(target).isDirectory()) { _emptyDirectory(target); return fs.rmdirSync(target); } else { return fs.unlinkSync(target); } }; _escapeKey = function(key) { var newKey; if (key === '') { newKey = KEY_FOR_EMPTY_STRING; } else { newKey = key.toString(); } return newKey; }; QUOTA_EXCEEDED_ERR = (function(superClass) { extend(QUOTA_EXCEEDED_ERR, superClass); function QUOTA_EXCEEDED_ERR(message) { this.message = message != null ? message : 'Unknown error.'; if (Error.captureStackTrace != null) { Error.captureStackTrace(this, this.constructor); } this.name = this.constructor.name; } QUOTA_EXCEEDED_ERR.prototype.toString = function() { return this.name + ": " + this.message; }; return QUOTA_EXCEEDED_ERR; })(Error); StorageEvent = (function() { function StorageEvent(key1, oldValue1, newValue1, url, storageArea) { this.key = key1; this.oldValue = oldValue1; this.newValue = newValue1; this.url = url; this.storageArea = storageArea != null ? storageArea : 'localStorage'; } return StorageEvent; })(); MetaKey = (function() { function MetaKey(key1, index1) { this.key = key1; this.index = index1; if (!(this instanceof MetaKey)) { return new MetaKey(this.key, this.index); } } return MetaKey; })(); createMap = function() { var Map; Map = function() {}; Map.prototype = Object.create(null); return new Map(); }; LocalStorage = (function(superClass) { var instanceMap; extend(LocalStorage, superClass); instanceMap = {}; function LocalStorage(_location, quota) { this._location = _location; this.quota = quota != null ? quota : 5 * 1024 * 1024; if (!(this instanceof LocalStorage)) { return new LocalStorage(this._location, this.quota); } this._location = path.resolve(this._location); if (instanceMap[this._location] != null) { return instanceMap[this._location]; } this.length = 0; this._bytesInUse = 0; this._keys = []; this._metaKeyMap = createMap(); this._eventUrl = "pid:" + process.pid; this._init(); this._QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR; instanceMap[this._location] = this; return instanceMap[this._location]; } LocalStorage.prototype._init = function() { var _MetaKey, _decodedKey, _keys, error, i, index, k, len, stat; try { stat = fs.statSync(this._location); if ((stat != null) && !stat.isDirectory()) { throw new Error("A file exists at the location '" + this._location + "' when trying to create/open localStorage"); } this._bytesInUse = 0; this.length = 0; _keys = fs.readdirSync(this._location); for (index = i = 0, len = _keys.length; i < len; index = ++i) { k = _keys[index]; _decodedKey = decodeURIComponent(k); this._keys.push(_decodedKey); _MetaKey = new MetaKey(k, index); this._metaKeyMap[_decodedKey] = _MetaKey; stat = this._getStat(k); if ((stat != null ? stat.size : void 0) != null) { _MetaKey.size = stat.size; this._bytesInUse += stat.size; } } this.length = _keys.length; } catch (error) { fs.mkdirSync(this._location); } }; LocalStorage.prototype.setItem = function(key, value) { var encodedKey, evnt, existsBeforeSet, filename, hasListeners, metaKey, oldLength, oldValue, valueString, valueStringLength; hasListeners = events.EventEmitter.listenerCount(this, 'storage'); oldValue = null; if (hasListeners) { oldValue = this.getItem(key); } key = _escapeKey(key); encodedKey = encodeURIComponent(key); filename = path.join(this._location, encodedKey); valueString = value.toString(); valueStringLength = valueString.length; metaKey = this._metaKeyMap[key]; existsBeforeSet = !!metaKey; if (existsBeforeSet) { oldLength = metaKey.size; } else { oldLength = 0; } if (this._bytesInUse - oldLength + valueStringLength > this.quota) { throw new QUOTA_EXCEEDED_ERR(); } writeSync(filename, valueString, 'utf8'); if (!existsBeforeSet) { metaKey = new MetaKey(encodedKey, (this._keys.push(key)) - 1); metaKey.size = valueStringLength; this._metaKeyMap[key] = metaKey; this.length += 1; this._bytesInUse += valueStringLength; } if (hasListeners) { evnt = new StorageEvent(key, oldValue, value, this._eventUrl); return this.emit('storage', evnt); } }; LocalStorage.prototype.getItem = function(key) { var filename, metaKey; key = _escapeKey(key); metaKey = this._metaKeyMap[key]; if (!!metaKey) { filename = path.join(this._location, metaKey.key); return fs.readFileSync(filename, 'utf8'); } else { return null; } }; LocalStorage.prototype._getStat = function(key) { var error, filename; key = _escapeKey(key); filename = path.join(this._location, encodeURIComponent(key)); try { return fs.statSync(filename); } catch (error) { return null; } }; LocalStorage.prototype.removeItem = function(key) { var evnt, filename, hasListeners, k, meta, metaKey, oldValue, ref, v; key = _escapeKey(key); metaKey = this._metaKeyMap[key]; if (!!metaKey) { hasListeners = events.EventEmitter.listenerCount(this, 'storage'); oldValue = null; if (hasListeners) { oldValue = this.getItem(key); } delete this._metaKeyMap[key]; this.length -= 1; this._bytesInUse -= metaKey.size; filename = path.join(this._location, metaKey.key); this._keys.splice(metaKey.index, 1); ref = this._metaKeyMap; for (k in ref) { v = ref[k]; meta = this._metaKeyMap[k]; if (meta.index > metaKey.index) { meta.index -= 1; } } _rm(filename); if (hasListeners) { evnt = new StorageEvent(key, oldValue, null, this._eventUrl); return this.emit('storage', evnt); } } }; LocalStorage.prototype.key = function(n) { return this._keys[n]; }; LocalStorage.prototype.clear = function() { var evnt; _emptyDirectory(this._location); this._metaKeyMap = createMap(); this._keys = []; this.length = 0; this._bytesInUse = 0; if (events.EventEmitter.listenerCount(this, 'storage')) { evnt = new StorageEvent(null, null, null, this._eventUrl); return this.emit('storage', evnt); } }; LocalStorage.prototype._getBytesInUse = function() { return this._bytesInUse; }; LocalStorage.prototype._deleteLocation = function() { delete instanceMap[this._location]; _rm(this._location); this._metaKeyMap = {}; this._keys = []; this.length = 0; return this._bytesInUse = 0; }; return LocalStorage; })(events.EventEmitter); JSONStorage = (function(superClass) { extend(JSONStorage, superClass); function JSONStorage() { return JSONStorage.__super__.constructor.apply(this, arguments); } JSONStorage.prototype.setItem = function(key, value) { var newValue; newValue = JSON.stringify(value); return JSONStorage.__super__.setItem.call(this, key, newValue); }; JSONStorage.prototype.getItem = function(key) { return JSON.parse(JSONStorage.__super__.getItem.call(this, key)); }; return JSONStorage; })(LocalStorage); exports.LocalStorage = LocalStorage; exports.JSONStorage = JSONStorage; exports.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR; }).call(this);
var Helpers = { error: function() { return Session.get('error'); }, toLowerCase: function(text) { return text && text.toLowerCase(); }, toUpperCase: function(text) { return text && text.toUpperCase(); }, firstChar: function(text) { return text && text[0].toUpperCase(); }, session: function(prop) { return Session.get(prop); }, isTrue: function(a, b) { return a == b; }, getUser: function(userId) { return Users.findOne(userId); } }; Template.warning.helpers({ warning: function() { return Utils.Warning.get(); } }); // Register all Helpers _.each(Helpers, function(fn, name) { Blaze.registerHelper(name, fn); }); // XXX I believe we should compute a HTML rendered field on the server that // would handle markdown, emojies and user mentions. We can simply have two // fields, one source, and one compiled version (in HTML) and send only the // compiled version to most users -- who don't need to edit. // In the meantime, all the transformation are done on the client using the // Blaze API. var at = HTML.CharRef({html: '&commat;', str: '@'}); Blaze.Template.registerHelper('mentions', new Template('mentions', function() { var view = this; var content = Blaze.toHTML(view.templateContentBlock); var currentBoard = Boards.findOne(Router.current().params.boardId); var knowedUsers = _.map(currentBoard.members, function(member) { member.username = Users.findOne(member.userId).username; return member; }); var mentionRegex = /\B@(\w*)/gi; var currentMention, knowedUser, href, linkClass, linkValue, link; while (currentMention = mentionRegex.exec(content)) { knowedUser = _.findWhere(knowedUsers, { username: currentMention[1] }); if (! knowedUser) continue; linkValue = [' ', at, knowedUser.username]; href = Router.url('Profile', { username: knowedUser.username }); linkClass = 'atMention' + (knowedUser.userId === Meteor.userId() ? ' me' : ''); link = HTML.A({ href: href, "class": linkClass }, linkValue); content = content.replace(currentMention[0], Blaze.toHTML(link)); } return HTML.Raw(content); }));
/*! jQuery UI - v1.10.4 - 2014-05-18 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional["en-AU"]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional["en-AU"])});
const BaseChecker = require('./../base-checker') const ruleId = 'no-inline-assembly' const meta = { type: 'security', docs: { description: `Avoid to use inline assembly. It is acceptable only in rare cases.`, category: 'Security Rules' }, isDefault: false, recommended: true, defaultSetup: 'warn', schema: null } class NoInlineAssemblyChecker extends BaseChecker { constructor(reporter) { super(reporter, ruleId, meta) } InlineAssemblyStatement(node) { this.error(node) } error(node) { this.warn(node, 'Avoid to use inline assembly. It is acceptable only in rare cases') } } module.exports = NoInlineAssemblyChecker
if (typeof print !== 'function') { print = console.log; } function test() { var tmp1 = []; var tmp2 = []; var i, n, buf; var inp1, inp2; print('build'); buf = new Uint8Array(1024); for (i = 0; i < 1024; i++) { buf[i] = Math.random() * 128; // restrict to ASCII } tmp1 = new TextDecoder().decode(buf); print(tmp1.length); for (i = 0; i < 1024; i++) { tmp2.push(tmp1); } tmp2 = new TextEncoder().encode(tmp2.join('')); print(tmp2.length); print('run'); inp1 = Duktape.enc('jx', { foo: tmp2 }); inp2 = Duktape.enc('jx', { foox: tmp2 }); for (i = 0; i < 1000; i++) { var res1 = Duktape.dec('jx', inp1); var res2 = Duktape.dec('jx', inp2); } } try { test(); } catch (e) { print(e.stack || e); throw e; }
angular .module('app', [ 'ui.router' ]) .config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider) { $locationProvider.html5Mode(true);// use the HTML5 History API -- removes the # $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: 'app/templates/home.html', controller: 'democratCtrl' }) .state('work', { url: '/work', templateUrl: 'app/templates/work.html', controller: 'workCtrl' }) .state('mission', { url: '/mission', templateUrl: 'app/templates/mission.html', controller: 'missionCtrl' }) .state('news', { url: '/news', templateUrl: 'app/templates/news.html', controller: 'newsCtrl' }) .state('contact', { url: '/contact', templateUrl: 'app/templates/contact.html', controller: 'contactCtrl' }) }])
import Mirage from 'ember-cli-mirage'; import Server from 'ember-cli-mirage/server'; import Model from 'ember-cli-mirage/orm/model'; import Serializer from 'ember-cli-mirage/serializer'; import {module, test} from 'qunit'; module('Integration | Serializers | Base | Full Request', { beforeEach: function() { this.server = new Server({ environment: 'development', models: { author: Model.extend({ posts: Mirage.hasMany() }), post: Model.extend({ author: Mirage.belongsTo(), comments: Mirage.hasMany() }), comment: Model.extend({ post: Mirage.belongsTo() }), }, serializers: { application: Serializer.extend({ embed: true, root: false }), author: Serializer.extend({ embed: true, attrs: ['id', 'first'], relationships: ['posts'] }) } }); this.server.timing = 0; this.server.logging = false; }, afterEach: function() { this.server.shutdown(); } }); test('the appropriate serializer is used', function(assert) { assert.expect(1); var done = assert.async(); let author = this.server.schema.author.create({ first: 'Link', last: 'of Hyrule', age: 323 }); author.createPost({title: 'Lorem ipsum'}); this.server.get('/authors/:id', function(schema, request) { let id = request.params.id; return schema.author.find(id); }); $.ajax({ method: 'GET', url: '/authors/1' }).done(function(res) { assert.deepEqual(res, { author: { id: 1, first: 'Link', posts: [ {id: 1, title: 'Lorem ipsum'} ] } }); done(); }); }); test('a response falls back to the application serializer, if it exists', function(assert) { assert.expect(1); var done = assert.async(); this.server.schema.post.create({ title: 'Lorem', date: '20001010' }); this.server.get('/posts/:id', function(schema, request) { let id = request.params.id; return schema.post.find(id); }); $.ajax({ method: 'GET', url: '/posts/1' }).done(function(res) { assert.deepEqual(res, { id: 1, title: 'Lorem', date: '20001010' }); done(); }); });
(function () { var paste = (function (domGlobals) { 'use strict'; var Cell = function (initial) { var value = initial; var get = function () { return value; }; var set = function (v) { value = v; }; var clone = function () { return Cell(get()); }; return { get: get, set: set, clone: clone }; }; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); var hasProPlugin = function (editor) { if (/(^|[ ,])powerpaste([, ]|$)/.test(editor.settings.plugins) && global.get('powerpaste')) { if (typeof domGlobals.window.console !== 'undefined' && domGlobals.window.console.log) { domGlobals.window.console.log('PowerPaste is incompatible with Paste plugin! Remove \'paste\' from the \'plugins\' option.'); } return true; } else { return false; } }; var DetectProPlugin = { hasProPlugin: hasProPlugin }; var get = function (clipboard, quirks) { return { clipboard: clipboard, quirks: quirks }; }; var Api = { get: get }; var firePastePreProcess = function (editor, html, internal, isWordHtml) { return editor.fire('PastePreProcess', { content: html, internal: internal, wordContent: isWordHtml }); }; var firePastePostProcess = function (editor, node, internal, isWordHtml) { return editor.fire('PastePostProcess', { node: node, internal: internal, wordContent: isWordHtml }); }; var firePastePlainTextToggle = function (editor, state) { return editor.fire('PastePlainTextToggle', { state: state }); }; var firePaste = function (editor, ieFake) { return editor.fire('paste', { ieFake: ieFake }); }; var Events = { firePastePreProcess: firePastePreProcess, firePastePostProcess: firePastePostProcess, firePastePlainTextToggle: firePastePlainTextToggle, firePaste: firePaste }; var shouldPlainTextInform = function (editor) { return editor.getParam('paste_plaintext_inform', true); }; var shouldBlockDrop = function (editor) { return editor.getParam('paste_block_drop', false); }; var shouldPasteDataImages = function (editor) { return editor.getParam('paste_data_images', false); }; var shouldFilterDrop = function (editor) { return editor.getParam('paste_filter_drop', true); }; var getPreProcess = function (editor) { return editor.getParam('paste_preprocess'); }; var getPostProcess = function (editor) { return editor.getParam('paste_postprocess'); }; var getWebkitStyles = function (editor) { return editor.getParam('paste_webkit_styles'); }; var shouldRemoveWebKitStyles = function (editor) { return editor.getParam('paste_remove_styles_if_webkit', true); }; var shouldMergeFormats = function (editor) { return editor.getParam('paste_merge_formats', true); }; var isSmartPasteEnabled = function (editor) { return editor.getParam('smart_paste', true); }; var isPasteAsTextEnabled = function (editor) { return editor.getParam('paste_as_text', false); }; var getRetainStyleProps = function (editor) { return editor.getParam('paste_retain_style_properties'); }; var getWordValidElements = function (editor) { var defaultValidElements = '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' + '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' + 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody'; return editor.getParam('paste_word_valid_elements', defaultValidElements); }; var shouldConvertWordFakeLists = function (editor) { return editor.getParam('paste_convert_word_fake_lists', true); }; var shouldUseDefaultFilters = function (editor) { return editor.getParam('paste_enable_default_filters', true); }; var Settings = { shouldPlainTextInform: shouldPlainTextInform, shouldBlockDrop: shouldBlockDrop, shouldPasteDataImages: shouldPasteDataImages, shouldFilterDrop: shouldFilterDrop, getPreProcess: getPreProcess, getPostProcess: getPostProcess, getWebkitStyles: getWebkitStyles, shouldRemoveWebKitStyles: shouldRemoveWebKitStyles, shouldMergeFormats: shouldMergeFormats, isSmartPasteEnabled: isSmartPasteEnabled, isPasteAsTextEnabled: isPasteAsTextEnabled, getRetainStyleProps: getRetainStyleProps, getWordValidElements: getWordValidElements, shouldConvertWordFakeLists: shouldConvertWordFakeLists, shouldUseDefaultFilters: shouldUseDefaultFilters }; var shouldInformUserAboutPlainText = function (editor, userIsInformedState) { return userIsInformedState.get() === false && Settings.shouldPlainTextInform(editor); }; var displayNotification = function (editor, message) { editor.notificationManager.open({ text: editor.translate(message), type: 'info' }); }; var togglePlainTextPaste = function (editor, clipboard, userIsInformedState) { if (clipboard.pasteFormat.get() === 'text') { clipboard.pasteFormat.set('html'); Events.firePastePlainTextToggle(editor, false); } else { clipboard.pasteFormat.set('text'); Events.firePastePlainTextToggle(editor, true); if (shouldInformUserAboutPlainText(editor, userIsInformedState)) { displayNotification(editor, 'Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.'); userIsInformedState.set(true); } } editor.focus(); }; var Actions = { togglePlainTextPaste: togglePlainTextPaste }; var register = function (editor, clipboard, userIsInformedState) { editor.addCommand('mceTogglePlainTextPaste', function () { Actions.togglePlainTextPaste(editor, clipboard, userIsInformedState); }); editor.addCommand('mceInsertClipboardContent', function (ui, value) { if (value.content) { clipboard.pasteHtml(value.content, value.internal); } if (value.text) { clipboard.pasteText(value.text); } }); }; var Commands = { register: register }; var global$1 = tinymce.util.Tools.resolve('tinymce.Env'); var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay'); var global$3 = tinymce.util.Tools.resolve('tinymce.util.Tools'); var global$4 = tinymce.util.Tools.resolve('tinymce.util.VK'); var internalMimeType = 'x-tinymce/html'; var internalMark = '<!-- ' + internalMimeType + ' -->'; var mark = function (html) { return internalMark + html; }; var unmark = function (html) { return html.replace(internalMark, ''); }; var isMarked = function (html) { return html.indexOf(internalMark) !== -1; }; var InternalHtml = { mark: mark, unmark: unmark, isMarked: isMarked, internalHtmlMime: function () { return internalMimeType; } }; var global$5 = tinymce.util.Tools.resolve('tinymce.html.Entities'); var isPlainText = function (text) { return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text); }; var toBRs = function (text) { return text.replace(/\r?\n/g, '<br>'); }; var openContainer = function (rootTag, rootAttrs) { var key; var attrs = []; var tag = '<' + rootTag; if (typeof rootAttrs === 'object') { for (key in rootAttrs) { if (rootAttrs.hasOwnProperty(key)) { attrs.push(key + '="' + global$5.encodeAllRaw(rootAttrs[key]) + '"'); } } if (attrs.length) { tag += ' ' + attrs.join(' '); } } return tag + '>'; }; var toBlockElements = function (text, rootTag, rootAttrs) { var blocks = text.split(/\n\n/); var tagOpen = openContainer(rootTag, rootAttrs); var tagClose = '</' + rootTag + '>'; var paragraphs = global$3.map(blocks, function (p) { return p.split(/\n/).join('<br />'); }); var stitch = function (p) { return tagOpen + p + tagClose; }; return paragraphs.length === 1 ? paragraphs[0] : global$3.map(paragraphs, stitch).join(''); }; var convert = function (text, rootTag, rootAttrs) { return rootTag ? toBlockElements(text, rootTag, rootAttrs) : toBRs(text); }; var Newlines = { isPlainText: isPlainText, convert: convert, toBRs: toBRs, toBlockElements: toBlockElements }; var global$6 = tinymce.util.Tools.resolve('tinymce.html.DomParser'); var global$7 = tinymce.util.Tools.resolve('tinymce.html.Node'); var global$8 = tinymce.util.Tools.resolve('tinymce.html.Schema'); var global$9 = tinymce.util.Tools.resolve('tinymce.html.Serializer'); function filter(content, items) { global$3.each(items, function (v) { if (v.constructor === RegExp) { content = content.replace(v, ''); } else { content = content.replace(v[0], v[1]); } }); return content; } function innerText(html) { var schema = global$8(); var domParser = global$6({}, schema); var text = ''; var shortEndedElements = schema.getShortEndedElements(); var ignoreElements = global$3.makeMap('script noscript style textarea video audio iframe object', ' '); var blockElements = schema.getBlockElements(); function walk(node) { var name = node.name, currentNode = node; if (name === 'br') { text += '\n'; return; } if (name === 'wbr') { return; } if (shortEndedElements[name]) { text += ' '; } if (ignoreElements[name]) { text += ' '; return; } if (node.type === 3) { text += node.value; } if (!node.shortEnded) { if (node = node.firstChild) { do { walk(node); } while (node = node.next); } } if (blockElements[name] && currentNode.next) { text += '\n'; if (name === 'p') { text += '\n'; } } } html = filter(html, [/<!\[[^\]]+\]>/g]); walk(domParser.parse(html)); return text; } function trimHtml(html) { function trimSpaces(all, s1, s2) { if (!s1 && !s2) { return ' '; } return '\xA0'; } html = filter(html, [ /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig, /<!--StartFragment-->|<!--EndFragment-->/g, [ /( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g, trimSpaces ], /<br class="Apple-interchange-newline">/g, /<br>$/i ]); return html; } function createIdGenerator(prefix) { var count = 0; return function () { return prefix + count++; }; } var isMsEdge = function () { return domGlobals.navigator.userAgent.indexOf(' Edge/') !== -1; }; var Utils = { filter: filter, innerText: innerText, trimHtml: trimHtml, createIdGenerator: createIdGenerator, isMsEdge: isMsEdge }; function isWordContent(content) { return /<font face="Times New Roman"|class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i.test(content) || /class="OutlineElement/.test(content) || /id="?docs\-internal\-guid\-/.test(content); } function isNumericList(text) { var found, patterns; patterns = [ /^[IVXLMCD]{1,2}\.[ \u00a0]/, /^[ivxlmcd]{1,2}\.[ \u00a0]/, /^[a-z]{1,2}[\.\)][ \u00a0]/, /^[A-Z]{1,2}[\.\)][ \u00a0]/, /^[0-9]+\.[ \u00a0]/, /^[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]+\.[ \u00a0]/, /^[\u58f1\u5f10\u53c2\u56db\u4f0d\u516d\u4e03\u516b\u4e5d\u62fe]+\.[ \u00a0]/ ]; text = text.replace(/^[\u00a0 ]+/, ''); global$3.each(patterns, function (pattern) { if (pattern.test(text)) { found = true; return false; } }); return found; } function isBulletList(text) { return /^[\s\u00a0]*[\u2022\u00b7\u00a7\u25CF]\s*/.test(text); } function convertFakeListsToProperLists(node) { var currentListNode, prevListNode, lastLevel = 1; function getText(node) { var txt = ''; if (node.type === 3) { return node.value; } if (node = node.firstChild) { do { txt += getText(node); } while (node = node.next); } return txt; } function trimListStart(node, regExp) { if (node.type === 3) { if (regExp.test(node.value)) { node.value = node.value.replace(regExp, ''); return false; } } if (node = node.firstChild) { do { if (!trimListStart(node, regExp)) { return false; } } while (node = node.next); } return true; } function removeIgnoredNodes(node) { if (node._listIgnore) { node.remove(); return; } if (node = node.firstChild) { do { removeIgnoredNodes(node); } while (node = node.next); } } function convertParagraphToLi(paragraphNode, listName, start) { var level = paragraphNode._listLevel || lastLevel; if (level !== lastLevel) { if (level < lastLevel) { if (currentListNode) { currentListNode = currentListNode.parent.parent; } } else { prevListNode = currentListNode; currentListNode = null; } } if (!currentListNode || currentListNode.name !== listName) { prevListNode = prevListNode || currentListNode; currentListNode = new global$7(listName, 1); if (start > 1) { currentListNode.attr('start', '' + start); } paragraphNode.wrap(currentListNode); } else { currentListNode.append(paragraphNode); } paragraphNode.name = 'li'; if (level > lastLevel && prevListNode) { prevListNode.lastChild.append(currentListNode); } lastLevel = level; removeIgnoredNodes(paragraphNode); trimListStart(paragraphNode, /^\u00a0+/); trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/); trimListStart(paragraphNode, /^\u00a0+/); } var elements = []; var child = node.firstChild; while (typeof child !== 'undefined' && child !== null) { elements.push(child); child = child.walk(); if (child !== null) { while (typeof child !== 'undefined' && child.parent !== node) { child = child.walk(); } } } for (var i = 0; i < elements.length; i++) { node = elements[i]; if (node.name === 'p' && node.firstChild) { var nodeText = getText(node); if (isBulletList(nodeText)) { convertParagraphToLi(node, 'ul'); continue; } if (isNumericList(nodeText)) { var matches = /([0-9]+)\./.exec(nodeText); var start = 1; if (matches) { start = parseInt(matches[1], 10); } convertParagraphToLi(node, 'ol', start); continue; } if (node._listLevel) { convertParagraphToLi(node, 'ul', 1); continue; } currentListNode = null; } else { prevListNode = currentListNode; currentListNode = null; } } } function filterStyles(editor, validStyles, node, styleValue) { var outputStyles = {}, matches; var styles = editor.dom.parseStyle(styleValue); global$3.each(styles, function (value, name) { switch (name) { case 'mso-list': matches = /\w+ \w+([0-9]+)/i.exec(styleValue); if (matches) { node._listLevel = parseInt(matches[1], 10); } if (/Ignore/i.test(value) && node.firstChild) { node._listIgnore = true; node.firstChild._listIgnore = true; } break; case 'horiz-align': name = 'text-align'; break; case 'vert-align': name = 'vertical-align'; break; case 'font-color': case 'mso-foreground': name = 'color'; break; case 'mso-background': case 'mso-highlight': name = 'background'; break; case 'font-weight': case 'font-style': if (value !== 'normal') { outputStyles[name] = value; } return; case 'mso-element': if (/^(comment|comment-list)$/i.test(value)) { node.remove(); return; } break; } if (name.indexOf('mso-comment') === 0) { node.remove(); return; } if (name.indexOf('mso-') === 0) { return; } if (Settings.getRetainStyleProps(editor) === 'all' || validStyles && validStyles[name]) { outputStyles[name] = value; } }); if (/(bold)/i.test(outputStyles['font-weight'])) { delete outputStyles['font-weight']; node.wrap(new global$7('b', 1)); } if (/(italic)/i.test(outputStyles['font-style'])) { delete outputStyles['font-style']; node.wrap(new global$7('i', 1)); } outputStyles = editor.dom.serializeStyle(outputStyles, node.name); if (outputStyles) { return outputStyles; } return null; } var filterWordContent = function (editor, content) { var retainStyleProperties, validStyles; retainStyleProperties = Settings.getRetainStyleProps(editor); if (retainStyleProperties) { validStyles = global$3.makeMap(retainStyleProperties.split(/[, ]/)); } content = Utils.filter(content, [ /<br class="?Apple-interchange-newline"?>/gi, /<b[^>]+id="?docs-internal-[^>]*>/gi, /<!--[\s\S]+?-->/gi, /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, [ /<(\/?)s>/gi, '<$1strike>' ], [ /&nbsp;/gi, '\xA0' ], [ /<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function (str, spaces) { return spaces.length > 0 ? spaces.replace(/./, ' ').slice(Math.floor(spaces.length / 2)).split('').join('\xA0') : ''; } ] ]); var validElements = Settings.getWordValidElements(editor); var schema = global$8({ valid_elements: validElements, valid_children: '-li[p]' }); global$3.each(schema.elements, function (rule) { if (!rule.attributes.class) { rule.attributes.class = {}; rule.attributesOrder.push('class'); } if (!rule.attributes.style) { rule.attributes.style = {}; rule.attributesOrder.push('style'); } }); var domParser = global$6({}, schema); domParser.addAttributeFilter('style', function (nodes) { var i = nodes.length, node; while (i--) { node = nodes[i]; node.attr('style', filterStyles(editor, validStyles, node, node.attr('style'))); if (node.name === 'span' && node.parent && !node.attributes.length) { node.unwrap(); } } }); domParser.addAttributeFilter('class', function (nodes) { var i = nodes.length, node, className; while (i--) { node = nodes[i]; className = node.attr('class'); if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) { node.remove(); } node.attr('class', null); } }); domParser.addNodeFilter('del', function (nodes) { var i = nodes.length; while (i--) { nodes[i].remove(); } }); domParser.addNodeFilter('a', function (nodes) { var i = nodes.length, node, href, name; while (i--) { node = nodes[i]; href = node.attr('href'); name = node.attr('name'); if (href && href.indexOf('#_msocom_') !== -1) { node.remove(); continue; } if (href && href.indexOf('file://') === 0) { href = href.split('#')[1]; if (href) { href = '#' + href; } } if (!href && !name) { node.unwrap(); } else { if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) { node.unwrap(); continue; } node.attr({ href: href, name: name }); } } }); var rootNode = domParser.parse(content); if (Settings.shouldConvertWordFakeLists(editor)) { convertFakeListsToProperLists(rootNode); } content = global$9({ validate: editor.settings.validate }, schema).serialize(rootNode); return content; }; var preProcess = function (editor, content) { return Settings.shouldUseDefaultFilters(editor) ? filterWordContent(editor, content) : content; }; var WordFilter = { preProcess: preProcess, isWordContent: isWordContent }; var processResult = function (content, cancelled) { return { content: content, cancelled: cancelled }; }; var postProcessFilter = function (editor, html, internal, isWordHtml) { var tempBody = editor.dom.create('div', { style: 'display:none' }, html); var postProcessArgs = Events.firePastePostProcess(editor, tempBody, internal, isWordHtml); return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented()); }; var filterContent = function (editor, content, internal, isWordHtml) { var preProcessArgs = Events.firePastePreProcess(editor, content, internal, isWordHtml); if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) { return postProcessFilter(editor, preProcessArgs.content, internal, isWordHtml); } else { return processResult(preProcessArgs.content, preProcessArgs.isDefaultPrevented()); } }; var process = function (editor, html, internal) { var isWordHtml = WordFilter.isWordContent(html); var content = isWordHtml ? WordFilter.preProcess(editor, html) : html; return filterContent(editor, content, internal, isWordHtml); }; var ProcessFilters = { process: process }; var removeMeta = function (editor, html) { var body = editor.dom.create('body', {}, html); global$3.each(body.querySelectorAll('meta'), function (elm) { return elm.parentNode.removeChild(elm); }); return body.innerHTML; }; var pasteHtml = function (editor, html) { editor.insertContent(removeMeta(editor, html), { merge: Settings.shouldMergeFormats(editor), paste: true }); return true; }; var isAbsoluteUrl = function (url) { return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url); }; var isImageUrl = function (url) { return isAbsoluteUrl(url) && /.(gif|jpe?g|png)$/.test(url); }; var createImage = function (editor, url, pasteHtmlFn) { editor.undoManager.extra(function () { pasteHtmlFn(editor, url); }, function () { editor.insertContent('<img src="' + url + '">'); }); return true; }; var createLink = function (editor, url, pasteHtmlFn) { editor.undoManager.extra(function () { pasteHtmlFn(editor, url); }, function () { editor.execCommand('mceInsertLink', false, url); }); return true; }; var linkSelection = function (editor, html, pasteHtmlFn) { return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false; }; var insertImage = function (editor, html, pasteHtmlFn) { return isImageUrl(html) ? createImage(editor, html, pasteHtmlFn) : false; }; var smartInsertContent = function (editor, html) { global$3.each([ linkSelection, insertImage, pasteHtml ], function (action) { return action(editor, html, pasteHtml) !== true; }); }; var insertContent = function (editor, html) { if (Settings.isSmartPasteEnabled(editor) === false) { pasteHtml(editor, html); } else { smartInsertContent(editor, html); } }; var SmartPaste = { isImageUrl: isImageUrl, isAbsoluteUrl: isAbsoluteUrl, insertContent: insertContent }; var constant = function (value) { return function () { return value; }; }; function curry(fn) { var initialArgs = []; for (var _i = 1; _i < arguments.length; _i++) { initialArgs[_i - 1] = arguments[_i]; } return function () { var restArgs = []; for (var _i = 0; _i < arguments.length; _i++) { restArgs[_i] = arguments[_i]; } var all = initialArgs.concat(restArgs); return fn.apply(null, all); }; } var never = constant(false); var always = constant(true); var never$1 = never; var always$1 = always; var none = function () { return NONE; }; var NONE = function () { var eq = function (o) { return o.isNone(); }; var call = function (thunk) { return thunk(); }; var id = function (n) { return n; }; var noop = function () { }; var nul = function () { return null; }; var undef = function () { return undefined; }; var me = { fold: function (n, s) { return n(); }, is: never$1, isSome: never$1, isNone: always$1, getOr: id, getOrThunk: call, getOrDie: function (msg) { throw new Error(msg || 'error: getOrDie called on none.'); }, getOrNull: nul, getOrUndefined: undef, or: id, orThunk: call, map: none, ap: none, each: noop, bind: none, flatten: none, exists: never$1, forall: always$1, filter: none, equals: eq, equals_: eq, toArray: function () { return []; }, toString: constant('none()') }; if (Object.freeze) Object.freeze(me); return me; }(); var some = function (a) { var constant_a = function () { return a; }; var self = function () { return me; }; var map = function (f) { return some(f(a)); }; var bind = function (f) { return f(a); }; var me = { fold: function (n, s) { return s(a); }, is: function (v) { return a === v; }, isSome: always$1, isNone: never$1, getOr: constant_a, getOrThunk: constant_a, getOrDie: constant_a, getOrNull: constant_a, getOrUndefined: constant_a, or: self, orThunk: self, map: map, ap: function (optfab) { return optfab.fold(none, function (fab) { return some(fab(a)); }); }, each: function (f) { f(a); }, bind: bind, flatten: constant_a, exists: bind, forall: bind, filter: function (f) { return f(a) ? me : NONE; }, equals: function (o) { return o.is(a); }, equals_: function (o, elementEq) { return o.fold(never$1, function (b) { return elementEq(a, b); }); }, toArray: function () { return [a]; }, toString: function () { return 'some(' + a + ')'; } }; return me; }; var from = function (value) { return value === null || value === undefined ? NONE : some(value); }; var Option = { some: some, none: none, from: from }; var typeOf = function (x) { if (x === null) return 'null'; var t = typeof x; if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) return 'array'; if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) return 'string'; return t; }; var isType = function (type) { return function (value) { return typeOf(value) === type; }; }; var isFunction = isType('function'); var slice = Array.prototype.slice; var map = function (xs, f) { var len = xs.length; var r = new Array(len); for (var i = 0; i < len; i++) { var x = xs[i]; r[i] = f(x, i, xs); } return r; }; var each = function (xs, f) { for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; f(x, i, xs); } }; var filter$1 = function (xs, pred) { var r = []; for (var i = 0, len = xs.length; i < len; i++) { var x = xs[i]; if (pred(x, i, xs)) { r.push(x); } } return r; }; var from$1 = isFunction(Array.from) ? Array.from : function (x) { return slice.call(x); }; var nu = function (baseFn) { var data = Option.none(); var callbacks = []; var map = function (f) { return nu(function (nCallback) { get(function (data) { nCallback(f(data)); }); }); }; var get = function (nCallback) { if (isReady()) call(nCallback); else callbacks.push(nCallback); }; var set = function (x) { data = Option.some(x); run(callbacks); callbacks = []; }; var isReady = function () { return data.isSome(); }; var run = function (cbs) { each(cbs, call); }; var call = function (cb) { data.each(function (x) { domGlobals.setTimeout(function () { cb(x); }, 0); }); }; baseFn(set); return { get: get, map: map, isReady: isReady }; }; var pure = function (a) { return nu(function (callback) { callback(a); }); }; var LazyValue = { nu: nu, pure: pure }; var bounce = function (f) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var me = this; domGlobals.setTimeout(function () { f.apply(me, args); }, 0); }; }; var nu$1 = function (baseFn) { var get = function (callback) { baseFn(bounce(callback)); }; var map = function (fab) { return nu$1(function (callback) { get(function (a) { var value = fab(a); callback(value); }); }); }; var bind = function (aFutureB) { return nu$1(function (callback) { get(function (a) { aFutureB(a).get(callback); }); }); }; var anonBind = function (futureB) { return nu$1(function (callback) { get(function (a) { futureB.get(callback); }); }); }; var toLazy = function () { return LazyValue.nu(get); }; var toCached = function () { var cache = null; return nu$1(function (callback) { if (cache === null) { cache = toLazy(); } cache.get(callback); }); }; return { map: map, bind: bind, anonBind: anonBind, toLazy: toLazy, toCached: toCached, get: get }; }; var pure$1 = function (a) { return nu$1(function (callback) { callback(a); }); }; var Future = { nu: nu$1, pure: pure$1 }; var par = function (asyncValues, nu) { return nu(function (callback) { var r = []; var count = 0; var cb = function (i) { return function (value) { r[i] = value; count++; if (count >= asyncValues.length) { callback(r); } }; }; if (asyncValues.length === 0) { callback([]); } else { each(asyncValues, function (asyncValue, i) { asyncValue.get(cb(i)); }); } }); }; var par$1 = function (futures) { return par(futures, Future.nu); }; var mapM = function (array, fn) { var futures = map(array, fn); return par$1(futures); }; var value = function () { var subject = Cell(Option.none()); var clear = function () { subject.set(Option.none()); }; var set = function (s) { subject.set(Option.some(s)); }; var on = function (f) { subject.get().each(f); }; var isSet = function () { return subject.get().isSome(); }; return { clear: clear, set: set, isSet: isSet, on: on }; }; var pasteHtml$1 = function (editor, html, internalFlag) { var internal = internalFlag ? internalFlag : InternalHtml.isMarked(html); var args = ProcessFilters.process(editor, InternalHtml.unmark(html), internal); if (args.cancelled === false) { SmartPaste.insertContent(editor, args.content); } }; var pasteText = function (editor, text) { text = editor.dom.encode(text).replace(/\r\n/g, '\n'); text = Newlines.convert(text, editor.settings.forced_root_block, editor.settings.forced_root_block_attrs); pasteHtml$1(editor, text, false); }; var getDataTransferItems = function (dataTransfer) { var items = {}; var mceInternalUrlPrefix = 'data:text/mce-internal,'; if (dataTransfer) { if (dataTransfer.getData) { var legacyText = dataTransfer.getData('Text'); if (legacyText && legacyText.length > 0) { if (legacyText.indexOf(mceInternalUrlPrefix) === -1) { items['text/plain'] = legacyText; } } } if (dataTransfer.types) { for (var i = 0; i < dataTransfer.types.length; i++) { var contentType = dataTransfer.types[i]; try { items[contentType] = dataTransfer.getData(contentType); } catch (ex) { items[contentType] = ''; } } } } return items; }; var getClipboardContent = function (editor, clipboardEvent) { var content = getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer); return Utils.isMsEdge() ? global$3.extend(content, { 'text/html': '' }) : content; }; var hasContentType = function (clipboardContent, mimeType) { return mimeType in clipboardContent && clipboardContent[mimeType].length > 0; }; var hasHtmlOrText = function (content) { return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain'); }; var getBase64FromUri = function (uri) { var idx; idx = uri.indexOf(','); if (idx !== -1) { return uri.substr(idx + 1); } return null; }; var isValidDataUriImage = function (settings, imgElm) { return settings.images_dataimg_filter ? settings.images_dataimg_filter(imgElm) : true; }; var extractFilename = function (editor, str) { var m = str.match(/([\s\S]+?)\.(?:jpeg|jpg|png|gif)$/i); return m ? editor.dom.encode(m[1]) : null; }; var uniqueId = Utils.createIdGenerator('mceclip'); var pasteImage = function (editor, imageItem) { var base64 = getBase64FromUri(imageItem.uri); var id = uniqueId(); var name = editor.settings.images_reuse_filename && imageItem.blob.name ? extractFilename(editor, imageItem.blob.name) : id; var img = new domGlobals.Image(); img.src = imageItem.uri; if (isValidDataUriImage(editor.settings, img)) { var blobCache = editor.editorUpload.blobCache; var blobInfo = void 0, existingBlobInfo = void 0; existingBlobInfo = blobCache.findFirst(function (cachedBlobInfo) { return cachedBlobInfo.base64() === base64; }); if (!existingBlobInfo) { blobInfo = blobCache.create(id, imageItem.blob, base64, name); blobCache.add(blobInfo); } else { blobInfo = existingBlobInfo; } pasteHtml$1(editor, '<img src="' + blobInfo.blobUri() + '">', false); } else { pasteHtml$1(editor, '<img src="' + imageItem.uri + '">', false); } }; var isClipboardEvent = function (event) { return event.type === 'paste'; }; var readBlobsAsDataUris = function (items) { return mapM(items, function (item) { return Future.nu(function (resolve) { var blob = item.getAsFile ? item.getAsFile() : item; var reader = new window.FileReader(); reader.onload = function () { resolve({ blob: blob, uri: reader.result }); }; reader.readAsDataURL(blob); }); }); }; var getImagesFromDataTransfer = function (dataTransfer) { var items = dataTransfer.items ? map(from$1(dataTransfer.items), function (item) { return item.getAsFile(); }) : []; var files = dataTransfer.files ? from$1(dataTransfer.files) : []; var images = filter$1(items.length > 0 ? items : files, function (file) { return /^image\/(jpeg|png|gif|bmp)$/.test(file.type); }); return images; }; var pasteImageData = function (editor, e, rng) { var dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer; if (editor.settings.paste_data_images && dataTransfer) { var images = getImagesFromDataTransfer(dataTransfer); if (images.length > 0) { e.preventDefault(); readBlobsAsDataUris(images).get(function (blobResults) { if (rng) { editor.selection.setRng(rng); } each(blobResults, function (result) { pasteImage(editor, result); }); }); return true; } } return false; }; var isBrokenAndroidClipboardEvent = function (e) { var clipboardData = e.clipboardData; return domGlobals.navigator.userAgent.indexOf('Android') !== -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0; }; var isKeyboardPasteEvent = function (e) { return global$4.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45; }; var registerEventHandlers = function (editor, pasteBin, pasteFormat) { var keyboardPasteEvent = value(); var keyboardPastePlainTextState; editor.on('keydown', function (e) { function removePasteBinOnKeyUp(e) { if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) { pasteBin.remove(); } } if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) { keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86; if (keyboardPastePlainTextState && global$1.webkit && domGlobals.navigator.userAgent.indexOf('Version/') !== -1) { return; } e.stopImmediatePropagation(); keyboardPasteEvent.set(e); window.setTimeout(function () { keyboardPasteEvent.clear(); }, 100); if (global$1.ie && keyboardPastePlainTextState) { e.preventDefault(); Events.firePaste(editor, true); return; } pasteBin.remove(); pasteBin.create(); editor.once('keyup', removePasteBinOnKeyUp); editor.once('paste', function () { editor.off('keyup', removePasteBinOnKeyUp); }); } }); function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal) { var content, isPlainTextHtml; if (hasContentType(clipboardContent, 'text/html')) { content = clipboardContent['text/html']; } else { content = pasteBin.getHtml(); internal = internal ? internal : InternalHtml.isMarked(content); if (pasteBin.isDefaultContent(content)) { plainTextMode = true; } } content = Utils.trimHtml(content); pasteBin.remove(); isPlainTextHtml = internal === false && Newlines.isPlainText(content); if (!content.length || isPlainTextHtml) { plainTextMode = true; } if (plainTextMode) { if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) { content = clipboardContent['text/plain']; } else { content = Utils.innerText(content); } } if (pasteBin.isDefaultContent(content)) { if (!isKeyBoardPaste) { editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.'); } return; } if (plainTextMode) { pasteText(editor, content); } else { pasteHtml$1(editor, content, internal); } } var getLastRng = function () { return pasteBin.getLastRng() || editor.selection.getRng(); }; editor.on('paste', function (e) { var isKeyBoardPaste = keyboardPasteEvent.isSet(); var clipboardContent = getClipboardContent(editor, e); var plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState; var internal = hasContentType(clipboardContent, InternalHtml.internalHtmlMime()); keyboardPastePlainTextState = false; if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) { pasteBin.remove(); return; } if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) { pasteBin.remove(); return; } if (!isKeyBoardPaste) { e.preventDefault(); } if (global$1.ie && (!isKeyBoardPaste || e.ieFake) && !hasContentType(clipboardContent, 'text/html')) { pasteBin.create(); editor.dom.bind(pasteBin.getEl(), 'paste', function (e) { e.stopPropagation(); }); editor.getDoc().execCommand('Paste', false, null); clipboardContent['text/html'] = pasteBin.getHtml(); } if (hasContentType(clipboardContent, 'text/html')) { e.preventDefault(); if (!internal) { internal = InternalHtml.isMarked(clipboardContent['text/html']); } insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal); } else { global$2.setEditorTimeout(editor, function () { insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal); }, 0); } }); }; var registerEventsAndFilters = function (editor, pasteBin, pasteFormat) { registerEventHandlers(editor, pasteBin, pasteFormat); var src; editor.parser.addNodeFilter('img', function (nodes, name, args) { var isPasteInsert = function (args) { return args.data && args.data.paste === true; }; var remove = function (node) { if (!node.attr('data-mce-object') && src !== global$1.transparentSrc) { node.remove(); } }; var isWebKitFakeUrl = function (src) { return src.indexOf('webkit-fake-url') === 0; }; var isDataUri = function (src) { return src.indexOf('data:') === 0; }; if (!editor.settings.paste_data_images && isPasteInsert(args)) { var i = nodes.length; while (i--) { src = nodes[i].attributes.map.src; if (!src) { continue; } if (isWebKitFakeUrl(src)) { remove(nodes[i]); } else if (!editor.settings.allow_html_data_urls && isDataUri(src)) { remove(nodes[i]); } } } }); }; var getPasteBinParent = function (editor) { return global$1.ie && editor.inline ? domGlobals.document.body : editor.getBody(); }; var isExternalPasteBin = function (editor) { return getPasteBinParent(editor) !== editor.getBody(); }; var delegatePasteEvents = function (editor, pasteBinElm, pasteBinDefaultContent) { if (isExternalPasteBin(editor)) { editor.dom.bind(pasteBinElm, 'paste keyup', function (e) { if (!isDefault(editor, pasteBinDefaultContent)) { editor.fire('paste'); } }); } }; var create = function (editor, lastRngCell, pasteBinDefaultContent) { var dom = editor.dom, body = editor.getBody(); var pasteBinElm; lastRngCell.set(editor.selection.getRng()); pasteBinElm = editor.dom.add(getPasteBinParent(editor), 'div', { 'id': 'mcepastebin', 'class': 'mce-pastebin', 'contentEditable': true, 'data-mce-bogus': 'all', 'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0' }, pasteBinDefaultContent); if (global$1.ie || global$1.gecko) { dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535); } dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function (e) { e.stopPropagation(); }); delegatePasteEvents(editor, pasteBinElm, pasteBinDefaultContent); pasteBinElm.focus(); editor.selection.select(pasteBinElm, true); }; var remove = function (editor, lastRngCell) { if (getEl(editor)) { var pasteBinClone = void 0; var lastRng = lastRngCell.get(); while (pasteBinClone = editor.dom.get('mcepastebin')) { editor.dom.remove(pasteBinClone); editor.dom.unbind(pasteBinClone); } if (lastRng) { editor.selection.setRng(lastRng); } } lastRngCell.set(null); }; var getEl = function (editor) { return editor.dom.get('mcepastebin'); }; var getHtml = function (editor) { var pasteBinElm, pasteBinClones, i, dirtyWrappers, cleanWrapper; var copyAndRemove = function (toElm, fromElm) { toElm.appendChild(fromElm); editor.dom.remove(fromElm, true); }; pasteBinClones = global$3.grep(getPasteBinParent(editor).childNodes, function (elm) { return elm.id === 'mcepastebin'; }); pasteBinElm = pasteBinClones.shift(); global$3.each(pasteBinClones, function (pasteBinClone) { copyAndRemove(pasteBinElm, pasteBinClone); }); dirtyWrappers = editor.dom.select('div[id=mcepastebin]', pasteBinElm); for (i = dirtyWrappers.length - 1; i >= 0; i--) { cleanWrapper = editor.dom.create('div'); pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]); copyAndRemove(cleanWrapper, dirtyWrappers[i]); } return pasteBinElm ? pasteBinElm.innerHTML : ''; }; var getLastRng = function (lastRng) { return lastRng.get(); }; var isDefaultContent = function (pasteBinDefaultContent, content) { return content === pasteBinDefaultContent; }; var isPasteBin = function (elm) { return elm && elm.id === 'mcepastebin'; }; var isDefault = function (editor, pasteBinDefaultContent) { var pasteBinElm = getEl(editor); return isPasteBin(pasteBinElm) && isDefaultContent(pasteBinDefaultContent, pasteBinElm.innerHTML); }; var PasteBin = function (editor) { var lastRng = Cell(null); var pasteBinDefaultContent = '%MCEPASTEBIN%'; return { create: function () { return create(editor, lastRng, pasteBinDefaultContent); }, remove: function () { return remove(editor, lastRng); }, getEl: function () { return getEl(editor); }, getHtml: function () { return getHtml(editor); }, getLastRng: function () { return getLastRng(lastRng); }, isDefault: function () { return isDefault(editor, pasteBinDefaultContent); }, isDefaultContent: function (content) { return isDefaultContent(pasteBinDefaultContent, content); } }; }; var Clipboard = function (editor, pasteFormat) { var pasteBin = PasteBin(editor); editor.on('preInit', function () { return registerEventsAndFilters(editor, pasteBin, pasteFormat); }); return { pasteFormat: pasteFormat, pasteHtml: function (html, internalFlag) { return pasteHtml$1(editor, html, internalFlag); }, pasteText: function (text) { return pasteText(editor, text); }, pasteImageData: function (e, rng) { return pasteImageData(editor, e, rng); }, getDataTransferItems: getDataTransferItems, hasHtmlOrText: hasHtmlOrText, hasContentType: hasContentType }; }; var noop = function () { }; var hasWorkingClipboardApi = function (clipboardData) { return global$1.iOS === false && clipboardData !== undefined && typeof clipboardData.setData === 'function' && Utils.isMsEdge() !== true; }; var setHtml5Clipboard = function (clipboardData, html, text) { if (hasWorkingClipboardApi(clipboardData)) { try { clipboardData.clearData(); clipboardData.setData('text/html', html); clipboardData.setData('text/plain', text); clipboardData.setData(InternalHtml.internalHtmlMime(), html); return true; } catch (e) { return false; } } else { return false; } }; var setClipboardData = function (evt, data, fallback, done) { if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) { evt.preventDefault(); done(); } else { fallback(data.html, done); } }; var fallback = function (editor) { return function (html, done) { var markedHtml = InternalHtml.mark(html); var outer = editor.dom.create('div', { 'contenteditable': 'false', 'data-mce-bogus': 'all' }); var inner = editor.dom.create('div', { contenteditable: 'true' }, markedHtml); editor.dom.setStyles(outer, { position: 'fixed', top: '0', left: '-3000px', width: '1000px', overflow: 'hidden' }); outer.appendChild(inner); editor.dom.add(editor.getBody(), outer); var range = editor.selection.getRng(); inner.focus(); var offscreenRange = editor.dom.createRng(); offscreenRange.selectNodeContents(inner); editor.selection.setRng(offscreenRange); setTimeout(function () { editor.selection.setRng(range); outer.parentNode.removeChild(outer); done(); }, 0); }; }; var getData = function (editor) { return { html: editor.selection.getContent({ contextual: true }), text: editor.selection.getContent({ format: 'text' }) }; }; var isTableSelection = function (editor) { return !!editor.dom.getParent(editor.selection.getStart(), 'td[data-mce-selected],th[data-mce-selected]', editor.getBody()); }; var hasSelectedContent = function (editor) { return !editor.selection.isCollapsed() || isTableSelection(editor); }; var cut = function (editor) { return function (evt) { if (hasSelectedContent(editor)) { setClipboardData(evt, getData(editor), fallback(editor), function () { setTimeout(function () { editor.execCommand('Delete'); }, 0); }); } }; }; var copy = function (editor) { return function (evt) { if (hasSelectedContent(editor)) { setClipboardData(evt, getData(editor), fallback(editor), noop); } }; }; var register$1 = function (editor) { editor.on('cut', cut(editor)); editor.on('copy', copy(editor)); }; var CutCopy = { register: register$1 }; var global$a = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils'); var getCaretRangeFromEvent = function (editor, e) { return global$a.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc()); }; var isPlainTextFileUrl = function (content) { var plainTextContent = content['text/plain']; return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false; }; var setFocusedRange = function (editor, rng) { editor.focus(); editor.selection.setRng(rng); }; var setup = function (editor, clipboard, draggingInternallyState) { if (Settings.shouldBlockDrop(editor)) { editor.on('dragend dragover draggesture dragdrop drop drag', function (e) { e.preventDefault(); e.stopPropagation(); }); } if (!Settings.shouldPasteDataImages(editor)) { editor.on('drop', function (e) { var dataTransfer = e.dataTransfer; if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) { e.preventDefault(); } }); } editor.on('drop', function (e) { var dropContent, rng; rng = getCaretRangeFromEvent(editor, e); if (e.isDefaultPrevented() || draggingInternallyState.get()) { return; } dropContent = clipboard.getDataTransferItems(e.dataTransfer); var internal = clipboard.hasContentType(dropContent, InternalHtml.internalHtmlMime()); if ((!clipboard.hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && clipboard.pasteImageData(e, rng)) { return; } if (rng && Settings.shouldFilterDrop(editor)) { var content_1 = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain']; if (content_1) { e.preventDefault(); global$2.setEditorTimeout(editor, function () { editor.undoManager.transact(function () { if (dropContent['mce-internal']) { editor.execCommand('Delete'); } setFocusedRange(editor, rng); content_1 = Utils.trimHtml(content_1); if (!dropContent['text/html']) { clipboard.pasteText(content_1); } else { clipboard.pasteHtml(content_1, internal); } }); }); } } }); editor.on('dragstart', function (e) { draggingInternallyState.set(true); }); editor.on('dragover dragend', function (e) { if (Settings.shouldPasteDataImages(editor) && draggingInternallyState.get() === false) { e.preventDefault(); setFocusedRange(editor, getCaretRangeFromEvent(editor, e)); } if (e.type === 'dragend') { draggingInternallyState.set(false); } }); }; var DragDrop = { setup: setup }; var setup$1 = function (editor) { var plugin = editor.plugins.paste; var preProcess = Settings.getPreProcess(editor); if (preProcess) { editor.on('PastePreProcess', function (e) { preProcess.call(plugin, plugin, e); }); } var postProcess = Settings.getPostProcess(editor); if (postProcess) { editor.on('PastePostProcess', function (e) { postProcess.call(plugin, plugin, e); }); } }; var PrePostProcess = { setup: setup$1 }; function addPreProcessFilter(editor, filterFunc) { editor.on('PastePreProcess', function (e) { e.content = filterFunc(editor, e.content, e.internal, e.wordContent); }); } function addPostProcessFilter(editor, filterFunc) { editor.on('PastePostProcess', function (e) { filterFunc(editor, e.node); }); } function removeExplorerBrElementsAfterBlocks(editor, html) { if (!WordFilter.isWordContent(html)) { return html; } var blockElements = []; global$3.each(editor.schema.getBlockElements(), function (block, blockName) { blockElements.push(blockName); }); var explorerBlocksRegExp = new RegExp('(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:<br>&nbsp;[\\s\\r\\n]+|<br>)*', 'g'); html = Utils.filter(html, [[ explorerBlocksRegExp, '$1' ]]); html = Utils.filter(html, [ [ /<br><br>/g, '<BR><BR>' ], [ /<br>/g, ' ' ], [ /<BR><BR>/g, '<br>' ] ]); return html; } function removeWebKitStyles(editor, content, internal, isWordHtml) { if (isWordHtml || internal) { return content; } var webKitStylesSetting = Settings.getWebkitStyles(editor); var webKitStyles; if (Settings.shouldRemoveWebKitStyles(editor) === false || webKitStylesSetting === 'all') { return content; } if (webKitStylesSetting) { webKitStyles = webKitStylesSetting.split(/[, ]/); } if (webKitStyles) { var dom_1 = editor.dom, node_1 = editor.selection.getNode(); content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function (all, before, value, after) { var inputStyles = dom_1.parseStyle(dom_1.decode(value)); var outputStyles = {}; if (webKitStyles === 'none') { return before + after; } for (var i = 0; i < webKitStyles.length; i++) { var inputValue = inputStyles[webKitStyles[i]], currentValue = dom_1.getStyle(node_1, webKitStyles[i], true); if (/color/.test(webKitStyles[i])) { inputValue = dom_1.toHex(inputValue); currentValue = dom_1.toHex(currentValue); } if (currentValue !== inputValue) { outputStyles[webKitStyles[i]] = inputValue; } } outputStyles = dom_1.serializeStyle(outputStyles, 'span'); if (outputStyles) { return before + ' style="' + outputStyles + '"' + after; } return before + after; }); } else { content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3'); } content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function (all, before, value, after) { return before + ' style="' + value + '"' + after; }); return content; } function removeUnderlineAndFontInAnchor(editor, root) { editor.$('a', root).find('font,u').each(function (i, node) { editor.dom.remove(node, true); }); } var setup$2 = function (editor) { if (global$1.webkit) { addPreProcessFilter(editor, removeWebKitStyles); } if (global$1.ie) { addPreProcessFilter(editor, removeExplorerBrElementsAfterBlocks); addPostProcessFilter(editor, removeUnderlineAndFontInAnchor); } }; var Quirks = { setup: setup$2 }; var stateChange = function (editor, clipboard, e) { var ctrl = e.control; ctrl.active(clipboard.pasteFormat.get() === 'text'); editor.on('PastePlainTextToggle', function (e) { ctrl.active(e.state); }); }; var register$2 = function (editor, clipboard) { var postRender = curry(stateChange, editor, clipboard); editor.addButton('pastetext', { active: false, icon: 'pastetext', tooltip: 'Paste as text', cmd: 'mceTogglePlainTextPaste', onPostRender: postRender }); editor.addMenuItem('pastetext', { text: 'Paste as text', selectable: true, active: clipboard.pasteFormat, cmd: 'mceTogglePlainTextPaste', onPostRender: postRender }); }; var Buttons = { register: register$2 }; global.add('paste', function (editor) { if (DetectProPlugin.hasProPlugin(editor) === false) { var userIsInformedState = Cell(false); var draggingInternallyState = Cell(false); var pasteFormat = Cell(Settings.isPasteAsTextEnabled(editor) ? 'text' : 'html'); var clipboard = Clipboard(editor, pasteFormat); var quirks = Quirks.setup(editor); Buttons.register(editor, clipboard); Commands.register(editor, clipboard, userIsInformedState); PrePostProcess.setup(editor); CutCopy.register(editor); DragDrop.setup(editor, clipboard, draggingInternallyState); return Api.get(clipboard, quirks); } }); function Plugin () { } return Plugin; }(window)); })();
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Wrapper around {@link goog.ui.Dialog}, to provide * dialogs that are smarter about interacting with a rich text editor. * */ goog.provide('goog.ui.editor.AbstractDialog'); goog.provide('goog.ui.editor.AbstractDialog.Builder'); goog.provide('goog.ui.editor.AbstractDialog.EventType'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.events.EventTarget'); goog.require('goog.string'); goog.require('goog.ui.Dialog'); // *** Public interface ***************************************************** // /** * Creates an object that represents a dialog box. * @param {goog.dom.DomHelper} domHelper DomHelper to be used to create the * dialog's dom structure. * @constructor * @extends {goog.events.EventTarget} */ goog.ui.editor.AbstractDialog = function(domHelper) { goog.events.EventTarget.call(this); this.dom = domHelper; }; goog.inherits(goog.ui.editor.AbstractDialog, goog.events.EventTarget); /** * Causes the dialog box to appear, centered on the screen. Lazily creates the * dialog if needed. */ goog.ui.editor.AbstractDialog.prototype.show = function() { // Lazily create the wrapped dialog to be shown. if (!this.dialogInternal_) { this.dialogInternal_ = this.createDialogControl(); this.dialogInternal_.addEventListener(goog.ui.Dialog.EventType.AFTER_HIDE, this.handleAfterHide_, false, this); } this.dialogInternal_.setVisible(true); }; /** * Hides the dialog, causing AFTER_HIDE to fire. */ goog.ui.editor.AbstractDialog.prototype.hide = function() { if (this.dialogInternal_) { // This eventually fires the wrapped dialog's AFTER_HIDE event, calling our // handleAfterHide_(). this.dialogInternal_.setVisible(false); } }; /** * @return {boolean} Whether the dialog is open. */ goog.ui.editor.AbstractDialog.prototype.isOpen = function() { return !!this.dialogInternal_ && this.dialogInternal_.isVisible(); }; /** * Runs the handler registered on the OK button event and closes the dialog if * that handler succeeds. * This is useful in cases such as double-clicking an item in the dialog is * equivalent to selecting it and clicking the default button. * @protected */ goog.ui.editor.AbstractDialog.prototype.processOkAndClose = function() { // Fake an OK event from the wrapped dialog control. var evt = new goog.ui.Dialog.Event(goog.ui.Dialog.DefaultButtonKeys.OK, null); if (this.handleOk(evt)) { // handleOk calls dispatchEvent, so if any listener calls preventDefault it // will return false and we won't hide the dialog. this.hide(); } }; // *** Dialog events ******************************************************** // /** * Event type constants for events the dialog fires. * @enum {string} */ goog.ui.editor.AbstractDialog.EventType = { // This event is fired after the dialog is hidden, no matter if it was closed // via OK or Cancel or is being disposed without being hidden first. AFTER_HIDE: 'afterhide', // Either the cancel or OK events can be canceled via preventDefault or by // returning false from their handlers to stop the dialog from closing. CANCEL: 'cancel', OK: 'ok' }; // *** Inner helper class *************************************************** // /** * A builder class for the dialog control. All methods except build return this. * @param {goog.ui.editor.AbstractDialog} editorDialog Editor dialog object * that will wrap the wrapped dialog object this builder will create. * @constructor */ goog.ui.editor.AbstractDialog.Builder = function(editorDialog) { // We require the editor dialog to be passed in so that the builder can set up // ok/cancel listeners by default, making it easier for most dialogs. this.editorDialog_ = editorDialog; this.wrappedDialog_ = new goog.ui.Dialog('', true, this.editorDialog_.dom); this.buttonSet_ = new goog.ui.Dialog.ButtonSet(this.editorDialog_.dom); this.buttonHandlers_ = {}; this.addClassName(goog.getCssName('tr-dialog')); }; /** * Sets the title of the dialog. * @param {string} title Title HTML (escaped). * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.setTitle = function(title) { this.wrappedDialog_.setTitle(title); return this; }; /** * Adds an OK button to the dialog. Clicking this button will cause {@link * handleOk} to run, subsequently dispatching an OK event. * @param {string=} opt_label The caption for the button, if not "OK". * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addOkButton = function(opt_label) { var key = goog.ui.Dialog.DefaultButtonKeys.OK; /** @desc Label for an OK button in an editor dialog. */ var MSG_TR_DIALOG_OK = goog.getMsg('OK'); // True means this is the default/OK button. this.buttonSet_.set(key, opt_label || MSG_TR_DIALOG_OK, true); this.buttonHandlers_[key] = goog.bind(this.editorDialog_.handleOk, this.editorDialog_); return this; }; /** * Adds a Cancel button to the dialog. Clicking this button will cause {@link * handleCancel} to run, subsequently dispatching a CANCEL event. * @param {string=} opt_label The caption for the button, if not "Cancel". * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addCancelButton = function(opt_label) { var key = goog.ui.Dialog.DefaultButtonKeys.CANCEL; /** @desc Label for a cancel button in an editor dialog. */ var MSG_TR_DIALOG_CANCEL = goog.getMsg('Cancel'); // False means it's not the OK button, true means it's the Cancel button. this.buttonSet_.set(key, opt_label || MSG_TR_DIALOG_CANCEL, false, true); this.buttonHandlers_[key] = goog.bind(this.editorDialog_.handleCancel, this.editorDialog_); return this; }; /** * Adds a custom button to the dialog. * @param {string} label The caption for the button. * @param {function(goog.ui.Dialog.EventType):*} handler Function called when * the button is clicked. It is recommended that this function be a method * in the concrete subclass of AbstractDialog using this Builder, and that * it dispatch an event (see {@link handleOk}). * @param {string=} opt_buttonId Identifier to be used to access the button when * calling AbstractDialog.getButtonElement(). * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addButton = function(label, handler, opt_buttonId) { // We don't care what the key is, just that we can match the button with the // handler function later. var key = opt_buttonId || goog.string.createUniqueString(); this.buttonSet_.set(key, label); this.buttonHandlers_[key] = handler; return this; }; /** * Puts a CSS class on the dialog's main element. * @param {string} className The class to add. * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.addClassName = function(className) { goog.dom.classes.add(this.wrappedDialog_.getDialogElement(), className); return this; }; /** * Sets the content element of the dialog. * @param {Element} contentElem An element for the main body. * @return {goog.ui.editor.AbstractDialog.Builder} This. */ goog.ui.editor.AbstractDialog.Builder.prototype.setContent = function(contentElem) { goog.dom.appendChild(this.wrappedDialog_.getContentElement(), contentElem); return this; }; /** * Builds the wrapped dialog control. May only be called once, after which * no more methods may be called on this builder. * @return {goog.ui.Dialog} The wrapped dialog control. */ goog.ui.editor.AbstractDialog.Builder.prototype.build = function() { if (this.buttonSet_.isEmpty()) { // If caller didn't set any buttons, add an OK and Cancel button by default. this.addOkButton(); this.addCancelButton(); } this.wrappedDialog_.setButtonSet(this.buttonSet_); var handlers = this.buttonHandlers_; this.buttonHandlers_ = null; this.wrappedDialog_.addEventListener(goog.ui.Dialog.EventType.SELECT, // Listen for the SELECT event, which means a button was clicked, and // call the handler associated with that button via the key property. function(e) { if (handlers[e.key]) { return handlers[e.key](e); } }); // All editor dialogs are modal. this.wrappedDialog_.setModal(true); var dialog = this.wrappedDialog_; this.wrappedDialog_ = null; return dialog; }; /** * Editor dialog that will wrap the wrapped dialog this builder will create. * @type {goog.ui.editor.AbstractDialog} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.editorDialog_; /** * wrapped dialog control being built by this builder. * @type {goog.ui.Dialog} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.wrappedDialog_; /** * Set of buttons to be added to the wrapped dialog control. * @type {goog.ui.Dialog.ButtonSet} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.buttonSet_; /** * Map from keys that will be returned in the wrapped dialog SELECT events to * handler functions to be called to handle those events. * @type {Object} * @private */ goog.ui.editor.AbstractDialog.Builder.prototype.buttonHandlers_; // *** Protected interface ************************************************** // /** * The DOM helper for the parent document. * @type {goog.dom.DomHelper} * @protected */ goog.ui.editor.AbstractDialog.prototype.dom; /** * Creates and returns the goog.ui.Dialog control that is being wrapped * by this object. * @return {goog.ui.Dialog} Created Dialog control. * @protected */ goog.ui.editor.AbstractDialog.prototype.createDialogControl = goog.abstractMethod; /** * Returns the HTML Button element for the OK button in this dialog. * @return {Element} The button element if found, else null. * @protected */ goog.ui.editor.AbstractDialog.prototype.getOkButtonElement = function() { return this.getButtonElement(goog.ui.Dialog.DefaultButtonKeys.OK); }; /** * Returns the HTML Button element for the Cancel button in this dialog. * @return {Element} The button element if found, else null. * @protected */ goog.ui.editor.AbstractDialog.prototype.getCancelButtonElement = function() { return this.getButtonElement(goog.ui.Dialog.DefaultButtonKeys.CANCEL); }; /** * Returns the HTML Button element for the button added to this dialog with * the given button id. * @param {string} buttonId The id of the button to get. * @return {Element} The button element if found, else null. * @protected */ goog.ui.editor.AbstractDialog.prototype.getButtonElement = function(buttonId) { return this.dialogInternal_.getButtonSet().getButton(buttonId); }; /** * Creates and returns the event object to be used when dispatching the OK * event to listeners, or returns null to prevent the dialog from closing. * Subclasses should override this to return their own subclass of * goog.events.Event that includes all data a plugin would need from the dialog. * @param {goog.events.Event} e The event object dispatched by the wrapped * dialog. * @return {goog.events.Event} The event object to be used when dispatching the * OK event to listeners. * @protected */ goog.ui.editor.AbstractDialog.prototype.createOkEvent = goog.abstractMethod; /** * Handles the event dispatched by the wrapped dialog control when the user * clicks the OK button. Attempts to create the OK event object and dispatches * it if successful. * @param {goog.ui.Dialog.Event} e wrapped dialog OK event object. * @return {boolean} Whether the default action (closing the dialog) should * still be executed. This will be false if the OK event could not be * created to be dispatched, or if any listener to that event returs false * or calls preventDefault. * @protected */ goog.ui.editor.AbstractDialog.prototype.handleOk = function(e) { var eventObj = this.createOkEvent(e); if (eventObj) { return this.dispatchEvent(eventObj); } else { return false; } }; /** * Handles the event dispatched by the wrapped dialog control when the user * clicks the Cancel button. Simply dispatches a CANCEL event. * @return {boolean} Returns false if any of the handlers called prefentDefault * on the event or returned false themselves. * @protected */ goog.ui.editor.AbstractDialog.prototype.handleCancel = function() { return this.dispatchEvent(goog.ui.editor.AbstractDialog.EventType.CANCEL); }; /** * Disposes of the dialog. If the dialog is open, it will be hidden and * AFTER_HIDE will be dispatched. * @override * @protected */ goog.ui.editor.AbstractDialog.prototype.disposeInternal = function() { if (this.dialogInternal_) { this.hide(); this.dialogInternal_.dispose(); this.dialogInternal_ = null; } goog.ui.editor.AbstractDialog.superClass_.disposeInternal.call(this); }; // *** Private implementation *********************************************** // /** * The wrapped dialog widget. * @type {goog.ui.Dialog} * @private */ goog.ui.editor.AbstractDialog.prototype.dialogInternal_; /** * Cleans up after the dialog is hidden and fires the AFTER_HIDE event. Should * be a listener for the wrapped dialog's AFTER_HIDE event. * @private */ goog.ui.editor.AbstractDialog.prototype.handleAfterHide_ = function() { this.dispatchEvent(goog.ui.editor.AbstractDialog.EventType.AFTER_HIDE); };
'use strict'; /** * @ngdoc directive * @name ng.directive:ngClick * * @description * The ngClick directive allows you to specify custom behavior when * an element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return { compile: function($element, attr) { var fn = $parse(attr[directiveName]); return function(scope, element, attr) { element.on(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; } }; }]; } ); /** * @ngdoc directive * @name ng.directive:ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * a dblclick. (The Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-dblclick="count = count + 1" ng-init="count=0"> Increment (on double click) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-mousedown="count = count + 1" ng-init="count=0"> Increment (on mouse down) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-mouseup="count = count + 1" ng-init="count=0"> Increment (on mouse up) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-mouseover="count = count + 1" ng-init="count=0"> Increment (when mouse is over) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-mouseenter="count = count + 1" ng-init="count=0"> Increment (when mouse enters) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-mouseleave="count = count + 1" ng-init="count=0"> Increment (when mouse leaves) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-mousemove="count = count + 1" ng-init="count=0"> Increment (when mouse moves) </button> count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <doc:example> <doc:source> <input ng-keydown="count = count + 1" ng-init="count=0"> key down count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <doc:example> <doc:source> <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngKeypress * * @description * Specify custom behavior on keypress event. * * @element ANY * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example <doc:example> <doc:source> <input ng-keypress="count = count + 1" ng-init="count=0"> key press count: {{count}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page) **but only if the form does not contain an `action` * attribute**. * * @element form * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngFocus * * @description * Specify custom behavior on focus event. * * @element window, input, select, textarea, a * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon * focus. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngBlur * * @description * Specify custom behavior on blur event. * * @element window, input, select, textarea, a * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon * blur. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngCopy * * @description * Specify custom behavior on copy event. * * @element window, input, select, textarea, a * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon * copy. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> copied: {{copied}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngCut * * @description * Specify custom behavior on cut event. * * @element window, input, select, textarea, a * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon * cut. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> cut: {{cut}} </doc:source> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngPaste * * @description * Specify custom behavior on paste event. * * @element window, input, select, textarea, a * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon * paste. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> pasted: {{paste}} </doc:source> </doc:example> */
/** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/ /*global module, require, sinon*/ /** * Assertions matching the test spy retrieval interface. * * @author Christian Johansen (christian@cjohansen.no) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ "use strict"; (function (sinon, global) { var commonJSModule = typeof module == "object" && typeof require == "function"; var slice = Array.prototype.slice; var assert; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function verifyIsStub() { var method; for (var i = 0, l = arguments.length; i < l; ++i) { method = arguments[i]; if (!method) { assert.fail("fake is not a spy"); } if (typeof method != "function") { assert.fail(method + " is not a function"); } if (typeof method.getCall != "function") { assert.fail(method + " is not stubbed"); } } } function failAssertion(object, msg) { object = object || global; var failMethod = object.fail || assert.fail; failMethod.call(object, msg); } function mirrorPropAsAssertion(name, method, message) { if (arguments.length == 2) { message = method; method = name; } assert[name] = function (fake) { verifyIsStub(fake); var args = slice.call(arguments, 1); var failed = false; if (typeof method == "function") { failed = !method(fake); } else { failed = typeof fake[method] == "function" ? !fake[method].apply(fake, args) : !fake[method]; } if (failed) { failAssertion(this, fake.printf.apply(fake, [message].concat(args))); } else { assert.pass(name); } }; } function exposedName(prefix, prop) { return !prefix || /^fail/.test(prop) ? prop : prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); }; assert = { failException: "AssertError", fail: function fail(message) { var error = new Error(message); error.name = this.failException || assert.failException; throw error; }, pass: function pass(assertion) {}, callOrder: function assertCallOrder() { verifyIsStub.apply(null, arguments); var expected = "", actual = ""; if (!sinon.calledInOrder(arguments)) { try { expected = [].join.call(arguments, ", "); actual = sinon.orderByFirstCall(slice.call(arguments)).join(", "); } catch (e) { // If this fails, we'll just fall back to the blank string } failAssertion(this, "expected " + expected + " to be " + "called in order but were called as " + actual); } else { assert.pass("callOrder"); } }, callCount: function assertCallCount(method, count) { verifyIsStub(method); if (method.callCount != count) { var msg = "expected %n to be called " + sinon.timesInWords(count) + " but was called %c%C"; failAssertion(this, method.printf(msg)); } else { assert.pass("callCount"); } }, expose: function expose(target, options) { if (!target) { throw new TypeError("target is null or undefined"); } var o = options || {}; var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; for (var method in this) { if (method != "export" && (includeFail || !/^(fail)/.test(method))) { target[exposedName(prefix, method)] = this[method]; } } return target; } }; mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, "expected %n to not have been called but was called %c%C"); mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); mirrorPropAsAssertion("threw", "%n did not throw exception%C"); mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); if (commonJSModule) { module.exports = assert; } else { sinon.assert = assert; } }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : global));
import type { NodePath } from "babel-traverse"; import { visitors } from "babel-traverse"; import ReplaceSupers from "babel-helper-replace-supers"; import optimiseCall from "babel-helper-optimise-call-expression"; import * as defineMap from "babel-helper-define-map"; import template from "babel-template"; import * as t from "babel-types"; let buildDerivedConstructor = template(` (function () { super(...arguments); }) `); let noMethodVisitor = { "FunctionExpression|FunctionDeclaration"(path) { if (!path.is("shadow")) { path.skip(); } }, Method(path) { path.skip(); } }; let verifyConstructorVisitor = visitors.merge([noMethodVisitor, { Super(path) { if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { throw path.buildCodeFrameError("'super.*' is not allowed before super()"); } }, CallExpression: { exit(path) { if (path.get("callee").isSuper()) { this.hasBareSuper = true; if (!this.isDerived) { throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); } } } }, ThisExpression(path) { if (this.isDerived && !this.hasBareSuper) { if (!path.inShadow("this")) { throw path.buildCodeFrameError("'this' is not allowed before super()"); } } } }]); let findThisesVisitor = visitors.merge([noMethodVisitor, { ThisExpression(path) { this.superThises.push(path); } }]); export default class ClassTransformer { constructor(path: NodePath, file) { this.parent = path.parent; this.scope = path.scope; this.node = path.node; this.path = path; this.file = file; this.clearDescriptors(); this.instancePropBody = []; this.instancePropRefs = {}; this.staticPropBody = []; this.body = []; this.bareSuperAfter = []; this.bareSupers = []; this.pushedConstructor = false; this.pushedInherits = false; this.isLoose = false; this.superThises = []; // class id this.classId = this.node.id; // this is the name of the binding that will **always** reference the class we've constructed this.classRef = this.node.id || this.scope.generateUidIdentifier("class"); this.superName = this.node.superClass || t.identifier("Function"); this.isDerived = !!this.node.superClass; } run() { let superName = this.superName; let file = this.file; let body = this.body; // let constructorBody = this.constructorBody = t.blockStatement([]); this.constructor = this.buildConstructor(); // let closureParams = []; let closureArgs = []; // if (this.isDerived) { closureArgs.push(superName); superName = this.scope.generateUidIdentifierBasedOnNode(superName); closureParams.push(superName); this.superName = superName; } // this.buildBody(); // make sure this class isn't directly called constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [ t.thisExpression(), this.classRef ]))); body = body.concat(this.staticPropBody.map((fn) => fn(this.classRef))); if (this.classId) { // named class with only a constructor if (body.length === 1) return t.toExpression(body[0]); } // body.push(t.returnStatement(this.classRef)); let container = t.functionExpression(null, closureParams, t.blockStatement(body)); container.shadow = true; return t.callExpression(container, closureArgs); } buildConstructor() { let func = t.functionDeclaration(this.classRef, [], this.constructorBody); t.inherits(func, this.node); return func; } pushToMap(node, enumerable, kind = "value", scope?) { let mutatorMap; if (node.static) { this.hasStaticDescriptors = true; mutatorMap = this.staticMutatorMap; } else { this.hasInstanceDescriptors = true; mutatorMap = this.instanceMutatorMap; } let map = defineMap.push(mutatorMap, node, kind, this.file, scope); if (enumerable) { map.enumerable = t.booleanLiteral(true); } return map; } /** * [Please add a description.] * https://www.youtube.com/watch?v=fWNaR-rxAic */ constructorMeMaybe() { let hasConstructor = false; let paths = this.path.get("body.body"); for (let path of (paths: Array)) { hasConstructor = path.equals("kind", "constructor"); if (hasConstructor) break; } if (hasConstructor) return; let params, body; if (this.isDerived) { let constructor = buildDerivedConstructor().expression; params = constructor.params; body = constructor.body; } else { params = []; body = t.blockStatement([]); } this.path.get("body").unshiftContainer("body", t.classMethod( "constructor", t.identifier("constructor"), params, body )); } buildBody() { this.constructorMeMaybe(); this.pushBody(); this.verifyConstructor(); if (this.userConstructor) { let constructorBody = this.constructorBody; constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); t.inherits(this.constructor, this.userConstructor); t.inherits(constructorBody, this.userConstructor.body); } this.pushDescriptors(); } pushBody() { let classBodyPaths: Array<Object> = this.path.get("body.body"); for (let path of classBodyPaths) { let node = path.node; if (path.isClassProperty()) { throw path.buildCodeFrameError("Missing class properties transform."); } if (node.decorators) { throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one."); } if (t.isClassMethod(node)) { let isConstructor = node.kind === "constructor"; if (isConstructor) { path.traverse(verifyConstructorVisitor, this); if (!this.hasBareSuper && this.isDerived) { throw path.buildCodeFrameError("missing super() call in constructor"); } } let replaceSupers = new ReplaceSupers({ forceSuperMemoisation: isConstructor, methodPath: path, methodNode: node, objectRef: this.classRef, superRef: this.superName, isStatic: node.static, isLoose: this.isLoose, scope: this.scope, file: this.file }, true); replaceSupers.replace(); if (isConstructor) { this.pushConstructor(replaceSupers, node, path); } else { this.pushMethod(node, path); } } } } clearDescriptors() { this.hasInstanceDescriptors = false; this.hasStaticDescriptors = false; this.instanceMutatorMap = {}; this.staticMutatorMap = {}; } pushDescriptors() { this.pushInherits(); let body = this.body; let instanceProps; let staticProps; if (this.hasInstanceDescriptors) { instanceProps = defineMap.toClassObject(this.instanceMutatorMap); } if (this.hasStaticDescriptors) { staticProps = defineMap.toClassObject(this.staticMutatorMap); } if (instanceProps || staticProps) { if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); let nullNode = t.nullLiteral(); // (Constructor, instanceDescriptors, staticDescriptors, instanceInitializers, staticInitializers) let args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; if (instanceProps) args[1] = instanceProps; if (staticProps) args[2] = staticProps; if (this.instanceInitializersId) { args[3] = this.instanceInitializersId; body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); } if (this.staticInitializersId) { args[4] = this.staticInitializersId; body.unshift(this.buildObjectAssignment(this.staticInitializersId)); } let lastNonNullIndex = 0; for (let i = 0; i < args.length; i++) { if (args[i] !== nullNode) lastNonNullIndex = i; } args = args.slice(0, lastNonNullIndex + 1); body.push(t.expressionStatement( t.callExpression(this.file.addHelper("createClass"), args) )); } this.clearDescriptors(); } buildObjectAssignment(id) { return t.variableDeclaration("var", [ t.variableDeclarator(id, t.objectExpression([])) ]); } wrapSuperCall(bareSuper, superRef, thisRef, body) { let bareSuperNode = bareSuper.node; if (this.isLoose) { bareSuperNode.arguments.unshift(t.thisExpression()); if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) { // special case single arguments spread bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument; bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply")); } else { bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call")); } } else { bareSuperNode = optimiseCall( t.callExpression( t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.classRef] ), t.thisExpression(), bareSuperNode.arguments ); } let call = t.callExpression( this.file.addHelper("possibleConstructorReturn"), [t.thisExpression(), bareSuperNode] ); let bareSuperAfter = this.bareSuperAfter.map(fn => fn(thisRef)); if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { // this super call is the last statement in the body so we can just straight up // turn it into a return if (this.superThises.length || bareSuperAfter.length) { bareSuper.scope.push({ id: thisRef }); call = t.assignmentExpression("=", thisRef, call); } if (bareSuperAfter.length) { call = t.toSequenceExpression([call, ...bareSuperAfter, thisRef]); } bareSuper.parentPath.replaceWith(t.returnStatement(call)); } else { bareSuper.replaceWithMultiple([ t.variableDeclaration("var", [ t.variableDeclarator(thisRef, call) ]), ...bareSuperAfter, t.expressionStatement(thisRef) ]); } } verifyConstructor() { if (!this.isDerived) return; let path = this.userConstructorPath; let body = path.get("body"); path.traverse(findThisesVisitor, this); let guaranteedSuperBeforeFinish = !!this.bareSupers.length; let superRef = this.superName || t.identifier("Function"); let thisRef = path.scope.generateUidIdentifier("this"); for (let bareSuper of this.bareSupers) { this.wrapSuperCall(bareSuper, superRef, thisRef, body); if (guaranteedSuperBeforeFinish) { bareSuper.find(function (parentPath) { // hit top so short circuit if (parentPath === path) { return true; } if (parentPath.isLoop() || parentPath.isConditional()) { guaranteedSuperBeforeFinish = false; return true; } }); } } for (let thisPath of this.superThises) { thisPath.replaceWith(thisRef); } let wrapReturn = returnArg => t.callExpression( this.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || []) ); // if we have a return as the last node in the body then we've already caught that // return let bodyPaths = body.get("body"); if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); } for (let returnPath of this.superReturns) { returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument)); } } /** * Push a method to its respective mutatorMap. */ pushMethod(node: { type: "ClassMethod" }, path?: NodePath) { let scope = path ? path.scope : this.scope; if (node.kind === "method") { if (this._processMethod(node, scope)) return; } this.pushToMap(node, false, null, scope); } _processMethod() { return false; } /** * Replace the constructor body of our class. */ pushConstructor(replaceSupers, method: { type: "ClassMethod" }, path: NodePath) { this.bareSupers = replaceSupers.bareSupers; this.superReturns = replaceSupers.returns; // https://github.com/babel/babel/issues/1077 if (path.scope.hasOwnBinding(this.classRef.name)) { path.scope.rename(this.classRef.name); } let construct = this.constructor; this.userConstructorPath = path; this.userConstructor = method; this.hasConstructor = true; t.inheritsComments(construct, method); construct._ignoreUserWhitespace = true; construct.params = method.params; t.inherits(construct.body, method.body); construct.body.directives = method.body.directives; // push constructor to body this._pushConstructor(); } _pushConstructor() { if (this.pushedConstructor) return; this.pushedConstructor = true; // we haven't pushed any descriptors yet if (this.hasInstanceDescriptors || this.hasStaticDescriptors) { this.pushDescriptors(); } this.body.push(this.constructor); this.pushInherits(); } /** * Push inherits helper to body. */ pushInherits() { if (!this.isDerived || this.pushedInherits) return; // Unshift to ensure that the constructor inheritance is set up before // any properties can be assigned to the prototype. this.pushedInherits = true; this.body.unshift(t.expressionStatement(t.callExpression( this.file.addHelper("inherits"), [this.classRef, this.superName] ))); } }
var struct_jmcpp_1_1_multi_unread_msg_count_changed_event = [ [ "conId", "struct_jmcpp_1_1_multi_unread_msg_count_changed_event.html#ac314e5a2b50bc3c17fd9a9f76ef0eff6", null ], [ "unreadMsgCount", "struct_jmcpp_1_1_multi_unread_msg_count_changed_event.html#af6ee70f5b5c66dfafdd34c99b56c0064", null ], [ "lastMessageTime", "struct_jmcpp_1_1_multi_unread_msg_count_changed_event.html#ae743014317672d0ce91ba781da3dd63d", null ] ];
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'sourcedialog', 'gu', { toolbar: 'મૂળ કે પ્રાથમિક દસ્તાવેજ', title: 'મૂળ કે પ્રાથમિક દસ્તાવેજ' } );
import { Tinytest } from "./tinytest.js"; import { ServerTestResultsSubscription, ServerTestResultsCollection, } from "./model.js"; const hasOwn = Object.prototype.hasOwnProperty; export { Tinytest }; // Like Tinytest._runTests, but runs the tests on both the client and // the server. Sets a 'server' flag on test results that came from the // server. // // Options: // serial if true, will not run tests in parallel. Currently this means // running the server tests before running the client tests. // Default is currently true (serial operation), but we will likely // change this to false in future. Tinytest._runTestsEverywhere = function (onReport, onComplete, pathPrefix, options) { var runId = Random.id(); var localComplete = false; var localStarted = false; var remoteComplete = false; var done = false; options = { serial: true, ...options, }; var serial = !!options.serial; var maybeDone = function () { if (!done && localComplete && remoteComplete) { done = true; onComplete && onComplete(); } if (serial && remoteComplete && !localStarted) { startLocalTests(); } }; var startLocalTests = function() { localStarted = true; Tinytest._runTests(onReport, function () { localComplete = true; maybeDone(); }, pathPrefix); }; var handle; Meteor.connection.registerStore(ServerTestResultsCollection, { update(msg) { // We only should call _runTestsEverywhere once per client-page-load, so // we really only should see one runId here. if (msg.id !== runId) { return; } if (! msg.fields) { return; } // This will only work for added & changed messages. // hope that is all you get. Object.keys(msg.fields).forEach(key => { // Skip the 'complete' report (deal with it last) if (key === 'complete') { return; } const report = msg.fields[key]; report.events.forEach(event => { delete event.cookie; // can't debug a server test on the client.. }); report.server = true; onReport(report); }); // Now that we've processed all the other messages, // check if we have the 'complete' message if (hasOwn.call(msg.fields, 'complete')) { remoteComplete = true; handle.stop(); Meteor.call('tinytest/clearResults', runId); maybeDone(); } } }); handle = Meteor.subscribe(ServerTestResultsSubscription, runId); Meteor.call('tinytest/run', runId, pathPrefix, function (error, result) { if (error) { // XXX better report error throw new Error("Test server returned an error"); } }); if (!serial) { startLocalTests(); } };
import DS from 'ember-data'; const { attr, Model } = DS; export default Model.extend({ title: attr('string'), body: attr('string') });
/* This Source Code Form is subject to the terms of the MIT license * If a copy of the MIT license was not distributed with this file, you can * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */ /* This widget allows you to create a tooltip by: * a) Manually calling Tooltip.create( "Some message" ); * b) Applying it to all elements with a given root element with a data-tooltip attribute, * by calling Tooltip.apply( rootElement ); */ define( [], function() { var __tooltipClass = "butter-tooltip", __tooltipOnClass = "tooltip-on", __toolTipNoHoverClass = "tooltip-no-hover", _registeredTooltips = {}, ToolTipObj, ToolTip; function register( tooltip ) { _registeredTooltips[ tooltip.name ] = tooltip; } function isRegistered( name ) { return !!_registeredTooltips[ name ]; } // ToolTip Constructor ToolTipObj = function( options ) { if ( options && options.name && isRegistered( options.name ) ) { return; } var parentElement, name, message, top, left, error, destroyed = false, tooltipElement = document.createElement( "div" ); tooltipElement.classList.add( __tooltipClass ); tooltipElement.classList.add( options.name ); Object.defineProperty( this, "message", { get: function() { return message; }, set: function( newMessage ) { if ( newMessage && typeof newMessage === "string" ) { message = newMessage; tooltipElement.innerHTML = newMessage; } }, enumerable: true }); Object.defineProperty( this, "hidden", { get: function() { return !tooltipElement.classList.contains( __tooltipOnClass ); }, set: function( hidden ) { if ( hidden || hidden === undefined ) { tooltipElement.classList.remove( __tooltipOnClass ); } else { tooltipElement.classList.add( __tooltipOnClass ); } }, enumerable: true }); Object.defineProperty( this, "hover", { get: function() { return !tooltipElement.classList.contains( __toolTipNoHoverClass ); }, set: function( hover ) { if ( hover || hover === undefined ) { tooltipElement.classList.remove( __toolTipNoHoverClass ); } else { tooltipElement.classList.add( __toolTipNoHoverClass ); } }, enumerable: true }); Object.defineProperty( this, "top", { get: function() { return top; }, set: function( newTop ) { if ( parentElement && newTop && typeof newTop === "string" ) { top = newTop; tooltipElement.style.top = newTop; } }, enumerable: true }); Object.defineProperty( this, "left", { get: function() { return left; }, set: function( newLeft ) { if ( parentElement && newLeft && typeof newLeft === "string" ) { left = newLeft; tooltipElement.style.left = newLeft; } }, enumerable: true }); Object.defineProperty( this, "tooltipElement", { get: function() { return tooltipElement; }, enumerable: true }); Object.defineProperty( this, "parent", { get: function() { return parentElement; }, set: function( newParent ) { if ( newParent ) { // Parent must be relative or absolute for tooltip to be positioned properly if ( [ "absolute", "relative", "fixed" ].indexOf( getComputedStyle( newParent ).getPropertyValue( "position" ) ) === -1 ) { newParent.style.position = "relative"; } parentElement = newParent; parentElement.appendChild( tooltipElement ); } }, enumerable: true }); Object.defineProperty( this, "name", { get: function() { return name; }, enumerable: true }); Object.defineProperty( this, "error", { get: function() { return error; }, set: function( value ) { error = !!value; if ( error ) { tooltipElement.classList.add( "tooltip-error" ); } else { tooltipElement.classList.remove( "tooltip-error" ); } }, enumerable: true }); Object.defineProperty( this, "destroyed", { get: function() { return destroyed; }, enumerable: true }); this.destroy = function() { if ( !destroyed ) { if ( parentElement && tooltipElement.parentNode === parentElement ) { parentElement.removeChild( tooltipElement ); } _registeredTooltips[ name ] = undefined; destroyed = true; } }; this.parent = options.element; this.top = options.top || parentElement.getBoundingClientRect().height + "px"; this.left = options.left || "50%"; this.message = options.message || parentElement.getAttribute( "data-tooltip" ) || parentElement.getAttribute( "title" ) || ""; this.hidden = options.hidden; this.hover = options.hover; this.error = options.error; name = options.name; if ( name ) { register( this ); } return this; }; ToolTip = { /** * Member: create * * Creates a tooltip inside a given element, with optional message. * Usage: * Tooltip.create({ * name: "tooltip-name" * element: myParentElement, * message: "This is my message", * top: 14px, * left: 30px, * hidden: true, * hover: true, * error: true * }); */ create: function( options ) { var newToolTip = new ToolTipObj( options ); return newToolTip.tooltipElement; }, /** * Member: apply * * Creates a tooltip inside all elements of a given root element with data-tooltip attribute */ apply: function( rootElement ) { var elements, i, l; rootElement = rootElement || document; elements = rootElement.querySelectorAll( "[data-tooltip]" ); for ( i = 0, l = elements.length; i < l; i++ ) { ToolTip.create({ element: elements[ i ] }); } }, /** * Member: get * * Get a tooltip reference by name */ get: function( title ){ return _registeredTooltips[ title ]; } }; return ToolTip; });
var _curry3 = require('./internal/_curry3'); /** * Returns the result of "setting" the portion of the given data structure * focused by the given lens to the result of applying the given function to * the focused value. * * @func * @memberOf R * @since v0.16.0 * @category Object * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s * @sig Lens s a -> (a -> a) -> s -> s * @param {Lens} lens * @param {*} v * @param {*} x * @return {*} * @see R.prop, R.lensIndex, R.lensProp * @example * * var headLens = R.lensIndex(0); * * R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] */ module.exports = (function() { var Identity = function(x) { return {value: x, map: function(f) { return Identity(f(x)); }}; }; return _curry3(function over(lens, f, x) { return lens(function(y) { return Identity(f(y)); })(x).value; }); }());
/*! jQuery UI - v1.10.4 - 2014-05-18 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function(t){t.effects.effect.shake=function(e,i){var s,n=t(this),a=["position","top","bottom","left","right","height","width"],o=t.effects.setMode(n,e.mode||"effect"),r=e.direction||"left",l=e.distance||20,h=e.times||3,c=2*h+1,u=Math.round(e.duration/c),d="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},g={},m={},v=n.queue(),_=v.length;for(t.effects.save(n,a),n.show(),t.effects.createWrapper(n),f[d]=(p?"-=":"+=")+l,g[d]=(p?"+=":"-=")+2*l,m[d]=(p?"-=":"+=")+2*l,n.animate(f,u,e.easing),s=1;h>s;s++)n.animate(g,u,e.easing).animate(m,u,e.easing);n.animate(g,u,e.easing).animate(f,u/2,e.easing).queue(function(){"hide"===o&&n.hide(),t.effects.restore(n,a),t.effects.removeWrapper(n),i()}),_>1&&v.splice.apply(v,[1,0].concat(v.splice(_,c+1))),n.dequeue()}})(jQuery);
import{generateUtilityClass,generateUtilityClasses}from"@material-ui/unstyled";export function getFormHelperTextUtilityClasses(e){return generateUtilityClass("MuiFormHelperText",e)};var formHelperTextClasses=generateUtilityClasses("MuiFormHelperText",["root","error","disabled","sizeSmall","sizeMedium","contained","focused","filled","required"]);export default formHelperTextClasses;
'use strict'; var path = require('path') , util = require('util') , EventEmitter = require('events').EventEmitter , logger = require(path.join(__dirname, 'logger.js')) , sampler = require(path.join(__dirname, 'sampler.js')) , NAMES = require(path.join(__dirname, 'metrics', 'names.js')) , CollectorAPI = require(path.join(__dirname, 'collector', 'api.js')) , ErrorTracer = require(path.join(__dirname, 'error.js')) , Metrics = require(path.join(__dirname, 'metrics.js')) , MetricNormalizer = require(path.join(__dirname, 'metrics', 'normalizer.js')) , MetricMapper = require(path.join(__dirname, 'metrics', 'mapper.js')) , TraceAggregator = require(path.join(__dirname, 'transaction', 'trace', 'aggregator.js')) ; /* * * CONSTANTS * */ var STATES = [ 'stopped', // start state 'starting', // handshaking with NR 'connected', // connected to collector 'disconnected', // disconnected from collector 'started', // up and running 'stopping', // shutting down 'errored' // stopped due to error ]; // just to make clear what's going on var TO_MILLIS = 1e3 , FROM_MILLIS = 1e-3 ; /** * There's a lot of stuff in this constructor, due to Agent acting as the * orchestrator for New Relic within instrumented applications. * * This constructor can throw if, for some reason, the configuration isn't * available. Don't try to recover here, because without configuration the * agent can't be brought up to a useful state. */ function Agent(config) { EventEmitter.call(this); if (!config) throw new Error("Agent must be created with a configuration!"); this._state = 'stopped'; this.config = config; this.config.on('apdex_t', this._apdexTChange.bind(this)); this.config.on('data_report_period', this._harvesterIntervalChange.bind(this)); this.environment = require(path.join(__dirname, 'environment')); this.version = this.config.version; this.collector = new CollectorAPI(this); // error tracing this.errors = new ErrorTracer(this.config); // metrics this.mapper = new MetricMapper(); this.metricNameNormalizer = new MetricNormalizer(this.config, 'metric name'); this.config.on( 'metric_name_rules', this.metricNameNormalizer.load.bind(this.metricNameNormalizer) ); this.metrics = new Metrics(this.config.apdex_t, this.mapper, this.metricNameNormalizer); // transaction naming this.transactionNameNormalizer = new MetricNormalizer(this.config, 'transaction name'); this.config.on( 'transaction_name_rules', this.transactionNameNormalizer.load.bind(this.transactionNameNormalizer) ); this.urlNormalizer = new MetricNormalizer(this.config, 'URL'); this.config.on('url_rules', this.urlNormalizer.load.bind(this.urlNormalizer)); // user naming and ignoring rules this.userNormalizer = new MetricNormalizer(this.config, 'user'); this.userNormalizer.loadFromConfig(); // transaction traces this.tracer = this._setupTracer(); this.traces = new TraceAggregator(this.config); // supportability if (this.config.debug.internal_metrics) { this.config.debug.supportability = new Metrics( this.config.apdex_t, this.mapper, this.metricNameNormalizer ); } // hidden class this.harvesterHandle = null; // agent events this.on('transactionFinished', this._transactionFinished.bind(this)); } util.inherits(Agent, EventEmitter); /** * The agent is meant to only exist once per application, but the singleton is * managed by index.js. An agent will be created even if the agent's disabled by * the configuration. * * @config {boolean} agent_enabled Whether to start up the agent. * * @param {Function} callback Continuation and error handler. */ Agent.prototype.start = function (callback) { if (!callback) throw new TypeError("callback required!"); var agent = this; this.state('starting'); if (this.config.agent_enabled !== true) { logger.warn("The New Relic Node.js agent is disabled by its configuration. " + "Not starting!"); this.state('stopped'); return process.nextTick(callback); } if (!(this.config.license_key)) { logger.error("A valid account license key cannot be found. " + "Has a license key been specified in the agent configuration " + "file or via the NEW_RELIC_LICENSE_KEY environment variable?"); this.state('errored'); return process.nextTick(function () { callback(new Error("Not starting without license key!")); }); } sampler.start(agent); logger.info("Starting New Relic for Node.js connection process."); this.collector.connect(function (error, config) { if (error) { agent.state('errored'); return callback(error, config); } if (agent.collector.isConnected()) { // harvest immediately for quicker data display agent.harvest(function (error) { agent._startHarvester(agent.config.data_report_period); agent.state('started'); callback(error, config); }); } else { process.nextTick(function () { callback(null, config); }); } }); }; /** * Any memory claimed by the agent will be retained after stopping. * * FIXME: make it possible to dispose of the agent, as well as do a * "hard" restart. This requires working with shimmer to strip the * current instrumentation and patch to the module loader. */ Agent.prototype.stop = function (callback) { if (!callback) throw new TypeError("callback required!"); var agent = this; this.state('stopping'); this._stopHarvester(); sampler.stop(); if (this.collector.isConnected()) { this.collector.shutdown(function (error) { if (error) { agent.state('errored'); logger.warn(error, "Got error shutting down connection to New Relic:"); } else { agent.state('stopped'); logger.info("Stopped New Relic for Node.js."); } callback(error); }); } else { process.nextTick(callback); } }; /** * On agent startup, an interval timer is started that calls this method once * a minute, which in turn invokes the pieces of the harvest cycle. It calls * the various collector API methods in order, bailing out if one of them fails, * to ensure that the agents don't pummel the collector if it's already * struggling. */ Agent.prototype.harvest = function (callback) { if (!callback) throw new TypeError("callback required!"); var agent = this; if (this.collector.isConnected()) { agent._sendMetrics(function (error) { if (error) return callback(error); agent._sendErrors(function (error) { if (error) return callback(error); agent._sendTrace(callback); }); }); } else { process.nextTick(function () { callback(new Error("Not connected to New Relic!")); }); } }; /** * Public interface for passing configuration data from the collector * on to the configuration, in an effort to keep them at least somewhat * decoupled. * * @param {object} configuration New config JSON from the collector. */ Agent.prototype.reconfigure = function reconfigure(configuration) { if (!configuration) throw new TypeError("must pass configuration"); this.config.onConnect(configuration); }; /** * Make it easier to determine what state the agent thinks it's in (needed * for a few tests, but fragile). * * FIXME: remove the need for this * * @param {string} newState The new state of the agent. */ Agent.prototype.state = function state(newState) { if (STATES.indexOf(newState) === -1) { throw new TypeError("Invalid state " + newState); } logger.debug("Agent state changed from %s to %s.", this._state, newState); this._state = newState; this.emit(this._state); }; /** * Server-side configuration value. * * @param {number} apdexT Apdex tolerating value, in seconds. */ Agent.prototype._apdexTChange = function (apdexT) { logger.debug("Apdex tolerating value changed to %s.", apdexT); this.metrics.apdexT = apdexT; if (this.config.debug.supportability) { this.config.debug.supportability.apdexT = apdexT; } }; /** * Server-side configuration value. When run, forces a harvest cycle * so as to not cause the agent to go too long without reporting. * * @param {number} interval Time in seconds between harvest runs. */ Agent.prototype._harvesterIntervalChange = function (interval, callback) { var agent = this; // only change the setup if the harvester is currently running if (this.harvesterHandle) { // force a harvest now, to be safe this.harvest(function (error) { agent._restartHarvester(interval); if (callback) callback(error); }); } else { if (callback) process.nextTick(callback); } }; /** * Restart the harvest cycle timer. * * @param {number} harvestSeconds How many seconds between harvests. */ Agent.prototype._restartHarvester = function (harvestSeconds) { this._stopHarvester(); this._startHarvester(harvestSeconds); }; /** * Safely stop the harvest cycle timer. */ Agent.prototype._stopHarvester = function () { if (this.harvesterHandle) clearInterval(this.harvesterHandle); this.harvesterHandle = undefined; }; /** * Safely start the harvest cycle timer, and ensure that the harvest * cycle won't keep an application from exiting if nothing else is * happening to keep it up. * * @param {number} harvestSeconds How many seconds between harvests. */ Agent.prototype._startHarvester = function (harvestSeconds) { var agent = this; function onError(error) { if (error) { logger.info(error, "Error on submission to New Relic (data held for redelivery):"); } } function harvester() { agent.harvest(onError); } this.harvesterHandle = setInterval(harvester, harvestSeconds * TO_MILLIS); // timer.unref is 0.9+ if (this.harvesterHandle.unref) this.harvesterHandle.unref(); }; /** * To develop the current transaction tracer, I created a tracing tracer that * tracks when transactions, segments and function calls are proxied. This is * used by the tests, but can also be dumped and logged, and is useful for * figuring out where in the execution chain tracing is breaking down. * * @param object config Agent configuration. * * @returns Tracer Either a debugging or production transaction tracer. */ Agent.prototype._setupTracer = function () { var Tracer; var debug = this.config.debug; if (debug && debug.tracer_tracing) { Tracer = require(path.join(__dirname, 'transaction', 'tracer', 'debug')); } else { Tracer = require(path.join(__dirname, 'transaction', 'tracer')); } return new Tracer(this); }; /** * The pieces of supportability metrics are scattered all over the place -- only * send supportability metrics if they're explicitly enabled in the * configuration. * * @param {Function} callback Gets any delivery errors. */ Agent.prototype._sendMetrics = function (callback) { var agent = this; if (this.collector.isConnected()) { if (this.errors.errorCount > 0) { var count = this.errors.errorCount; this.metrics.getOrCreateMetric(NAMES.ERRORS.ALL).incrementCallCount(count); } if (this.config.debug.supportability) { this.metrics.merge(this.config.debug.supportability); } // wait to check until all the standard stuff has been added if (this.metrics.toJSON().length < 1) { logger.debug("No metrics to send."); return process.nextTick(callback); } var metrics = this.metrics , beginSeconds = metrics.started * FROM_MILLIS , endSeconds = Date.now() * FROM_MILLIS , payload = [this.config.run_id, beginSeconds, endSeconds, metrics] ; // reset now to avoid losing metrics that come in after delivery starts this.metrics = new Metrics( this.config.apdex_t, this.mapper, this.metricNameNormalizer ); this.collector.metricData(payload, function (error, rules) { if (error) agent.metrics.merge(metrics); if (rules) agent.mapper.load(rules); callback(error); }); } else { process.nextTick(function () { callback(new Error("not connected to New Relic (metrics will be held)")); }); } }; /** * The error tracer doesn't know about the agent, and the connection * doesn't know about the error tracer. Only the agent knows about both. * * @param {Function} callback Gets any delivery errors. */ Agent.prototype._sendErrors = function (callback) { var agent = this; if (this.config.collect_errors && this.config.error_collector.enabled) { if (!this.collector.isConnected()) { return process.nextTick(function () { callback(new Error("not connected to New Relic (errors will be held)")); }); } else if (this.errors.errors < 1) { logger.debug("No errors to send."); return process.nextTick(callback); } var errors = this.errors.errors , payload = [this.config.run_id, errors] ; // reset now to avoid losing errors that come in after delivery starts this.errors = new ErrorTracer(agent.config); this.collector.errorData(payload, function (error) { if (error) agent.errors.merge(errors); callback(error); }); } else { process.nextTick(callback); } }; /** * The trace aggregator has its own harvester, which is already * asynchronous, due to its need to compress the nested transaction * trace data. * * @param {Function} callback Gets any encoding or delivery errors. */ Agent.prototype._sendTrace = function (callback) { var agent = this; if (this.config.collect_traces && this.config.transaction_tracer.enabled) { if (!this.collector.isConnected()) { return process.nextTick(function () { callback(new Error("not connected to New Relic (slow trace data will be held)")); }); } this.traces.harvest(function (error, encoded, trace) { if (error || !encoded) return callback(error); var payload = [agent.config.run_id, [encoded]]; agent.collector.transactionSampleData(payload, function (error) { if (!error) agent.traces.reset(trace); callback(error); }); }); } else { process.nextTick(callback); } }; /** * Put all the logic for handing finalized transactions off to the tracers and * metric collections in one place. * * @param {Transaction} transaction Newly-finalized transaction. */ Agent.prototype._transactionFinished = function (transaction) { // only available when this.config.debug.tracer_tracing is true if (transaction.describer) { logger.trace({trace_dump : transaction.describer.verbose}, "Dumped transaction state."); } if (!transaction.ignore) { if (transaction.forceIgnore === false) { logger.debug("Explicitly not ignoring %s.", transaction.name); } this.metrics.merge(transaction.metrics); this.errors.onTransactionFinished(transaction, this.metrics); this.traces.add(transaction); } else { if (transaction.forceIgnore === true) { logger.debug("Explicitly ignoring %s.", transaction.name); } else { logger.debug("Ignoring %s.", transaction.name); } } }; /** * Get the current transaction (if there is one) from the tracer. * * @returns {Transaction} The current transaction. */ Agent.prototype.getTransaction = function () { return this.tracer.getTransaction(); }; module.exports = Agent;
/** * @fileoverview Tests for max-nested-callbacks rule. * @author Ian Christian Myers * @copyright 2013 Ian Christian Myers. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), ESLintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/max-nested-callbacks", { valid: [ { code: "foo(function() { bar(thing, function(data) {}); });", args: [1, 3] }, { code: "var foo = function() {}; bar(function(){ baz(function() { qux(foo); }) });", args: [1, 2] }, { code: "fn(function(){}, function(){}, function(){});", args: [1, 2] }, { code: "fn(() => {}, function(){}, function(){});", args: [1, 2], ecmaFeatures: { arrowFunctions: true } } ], invalid: [ { code: "foo(function() { bar(thing, function(data) { baz(function() {}); }); });", args: [1, 2], errors: [{ message: "Too many nested callbacks (3). Maximum allowed is 2.", type: "FunctionExpression"}] }, { code: "foo(function() { bar(thing, (data) => { baz(function() {}); }); });", args: [1, 2], ecmaFeatures: { arrowFunctions: true }, errors: [{ message: "Too many nested callbacks (3). Maximum allowed is 2.", type: "FunctionExpression"}] }, { code: "foo(() => { bar(thing, (data) => { baz( () => {}); }); });", args: [1, 2], ecmaFeatures: { arrowFunctions: true }, errors: [{ message: "Too many nested callbacks (3). Maximum allowed is 2.", type: "ArrowFunctionExpression"}] }, { code: "foo(function() { if (isTrue) { bar(function(data) { baz(function() {}); }); } });", args: [1, 2], errors: [{ message: "Too many nested callbacks (3). Maximum allowed is 2.", type: "FunctionExpression"}] } ] });
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('charts-legend', function (Y, NAME) { /** * Adds legend functionality to charts. * * @module charts * @submodule charts-legend */ var DOCUMENT = Y.config.doc, TOP = "top", RIGHT = "right", BOTTOM = "bottom", LEFT = "left", EXTERNAL = "external", HORIZONTAL = "horizontal", VERTICAL = "vertical", WIDTH = "width", HEIGHT = "height", POSITION = "position", _X = "x", _Y = "y", PX = "px", LEGEND = { setter: function(val) { var legend = this.get("legend"); if(legend) { legend.destroy(true); } if(val instanceof Y.ChartLegend) { legend = val; legend.set("chart", this); } else { val.chart = this; if(!val.hasOwnProperty("render")) { val.render = this.get("contentBox"); val.includeInChartLayout = true; } legend = new Y.ChartLegend(val); } return legend; } }, /** * Contains methods for displaying items horizontally in a legend. * * @module charts * @submodule charts-legend * @class HorizontalLegendLayout */ HorizontalLegendLayout = { /** * Displays items horizontally in a legend. * * @method _positionLegendItems * @param {Array} items Array of items to display in the legend. * @param {Number} maxWidth The width of the largest item in the legend. * @param {Number} maxHeight The height of the largest item in the legend. * @param {Number} totalWidth The total width of all items in a legend. * @param {Number} totalHeight The total height of all items in a legend. * @param {Number} padding The left, top, right and bottom padding properties for the legend. * @param {Number} horizontalGap The horizontal distance between items in a legend. * @param {Number} verticalGap The vertical distance between items in a legend. * @param {String} hAlign The horizontal alignment of the legend. * @param {String} vAlign The vertical alignment of the legend. * @protected */ _positionLegendItems: function(items, maxWidth, maxHeight, totalWidth, totalHeight, padding, horizontalGap, verticalGap, hAlign, vAlign) { var i = 0, rowIterator = 0, item, node, itemWidth, itemHeight, len, width = this.get("width"), rows, rowsLen, row, totalWidthArray, legendWidth, topHeight = padding.top - verticalGap, limit = width - (padding.left + padding.right), left, top, right, bottom; HorizontalLegendLayout._setRowArrays(items, limit, horizontalGap); rows = HorizontalLegendLayout.rowArray; totalWidthArray = HorizontalLegendLayout.totalWidthArray; rowsLen = rows.length; for(; rowIterator < rowsLen; ++ rowIterator) { topHeight += verticalGap; row = rows[rowIterator]; len = row.length; legendWidth = HorizontalLegendLayout.getStartPoint(width, totalWidthArray[rowIterator], hAlign, padding); for(i = 0; i < len; ++i) { item = row[i]; node = item.node; itemWidth = item.width; itemHeight = item.height; item.x = legendWidth; item.y = 0; left = !isNaN(left) ? Math.min(left, legendWidth) : legendWidth; top = !isNaN(top) ? Math.min(top, topHeight) : topHeight; right = !isNaN(right) ? Math.max(legendWidth + itemWidth, right) : legendWidth + itemWidth; bottom = !isNaN(bottom) ? Math.max(topHeight + itemHeight, bottom) : topHeight + itemHeight; node.setStyle("left", legendWidth + PX); node.setStyle("top", topHeight + PX); legendWidth += itemWidth + horizontalGap; } topHeight += item.height; } this._contentRect = { left: left, top: top, right: right, bottom: bottom }; if(this.get("includeInChartLayout")) { this.set("height", topHeight + padding.bottom); } }, /** * Creates row and total width arrays used for displaying multiple rows of * legend items based on the items, available width and horizontalGap for the legend. * * @method _setRowArrays * @param {Array} items Array of legend items to display in a legend. * @param {Number} limit Total available width for displaying items in a legend. * @param {Number} horizontalGap Horizontal distance between items in a legend. * @protected */ _setRowArrays: function(items, limit, horizontalGap) { var item = items[0], rowArray = [[item]], i = 1, rowIterator = 0, len = items.length, totalWidth = item.width, itemWidth, totalWidthArray = [[totalWidth]]; for(; i < len; ++i) { item = items[i]; itemWidth = item.width; if((totalWidth + horizontalGap + itemWidth) <= limit) { totalWidth += horizontalGap + itemWidth; rowArray[rowIterator].push(item); } else { totalWidth = horizontalGap + itemWidth; if(rowArray[rowIterator]) { rowIterator += 1; } rowArray[rowIterator] = [item]; } totalWidthArray[rowIterator] = totalWidth; } HorizontalLegendLayout.rowArray = rowArray; HorizontalLegendLayout.totalWidthArray = totalWidthArray; }, /** * Returns the starting x-coordinate for a row of legend items. * * @method getStartPoint * @param {Number} w Width of the legend. * @param {Number} totalWidth Total width of all labels in the row. * @param {String} align Horizontal alignment of items for the legend. * @param {Object} padding Object contain left, top, right and bottom padding properties. * @return Number * @protected */ getStartPoint: function(w, totalWidth, align, padding) { var startPoint; switch(align) { case LEFT : startPoint = padding.left; break; case "center" : startPoint = (w - totalWidth) * 0.5; break; case RIGHT : startPoint = w - totalWidth - padding.right; break; } return startPoint; } }, /** * Contains methods for displaying items vertically in a legend. * * @module charts * @submodule charts-legend * @class VerticalLegendLayout */ VerticalLegendLayout = { /** * Displays items vertically in a legend. * * @method _positionLegendItems * @param {Array} items Array of items to display in the legend. * @param {Number} maxWidth The width of the largest item in the legend. * @param {Number} maxHeight The height of the largest item in the legend. * @param {Number} totalWidth The total width of all items in a legend. * @param {Number} totalHeight The total height of all items in a legend. * @param {Number} padding The left, top, right and bottom padding properties for the legend. * @param {Number} horizontalGap The horizontal distance between items in a legend. * @param {Number} verticalGap The vertical distance between items in a legend. * @param {String} hAlign The horizontal alignment of the legend. * @param {String} vAlign The vertical alignment of the legend. * @protected */ _positionLegendItems: function(items, maxWidth, maxHeight, totalWidth, totalHeight, padding, horizontalGap, verticalGap, hAlign, vAlign) { var i = 0, columnIterator = 0, item, node, itemHeight, itemWidth, len, height = this.get("height"), columns, columnsLen, column, totalHeightArray, legendHeight, leftWidth = padding.left - horizontalGap, legendWidth, limit = height - (padding.top + padding.bottom), left, top, right, bottom; VerticalLegendLayout._setColumnArrays(items, limit, verticalGap); columns = VerticalLegendLayout.columnArray; totalHeightArray = VerticalLegendLayout.totalHeightArray; columnsLen = columns.length; for(; columnIterator < columnsLen; ++ columnIterator) { leftWidth += horizontalGap; column = columns[columnIterator]; len = column.length; legendHeight = VerticalLegendLayout.getStartPoint(height, totalHeightArray[columnIterator], vAlign, padding); legendWidth = 0; for(i = 0; i < len; ++i) { item = column[i]; node = item.node; itemHeight = item.height; itemWidth = item.width; item.y = legendHeight; item.x = leftWidth; left = !isNaN(left) ? Math.min(left, leftWidth) : leftWidth; top = !isNaN(top) ? Math.min(top, legendHeight) : legendHeight; right = !isNaN(right) ? Math.max(leftWidth + itemWidth, right) : leftWidth + itemWidth; bottom = !isNaN(bottom) ? Math.max(legendHeight + itemHeight, bottom) : legendHeight + itemHeight; node.setStyle("left", leftWidth + PX); node.setStyle("top", legendHeight + PX); legendHeight += itemHeight + verticalGap; legendWidth = Math.max(legendWidth, item.width); } leftWidth += legendWidth; } this._contentRect = { left: left, top: top, right: right, bottom: bottom }; if(this.get("includeInChartLayout")) { this.set("width", leftWidth + padding.right); } }, /** * Creates column and total height arrays used for displaying multiple columns of * legend items based on the items, available height and verticalGap for the legend. * * @method _setColumnArrays * @param {Array} items Array of legend items to display in a legend. * @param {Number} limit Total available height for displaying items in a legend. * @param {Number} verticalGap Vertical distance between items in a legend. * @protected */ _setColumnArrays: function(items, limit, verticalGap) { var item = items[0], columnArray = [[item]], i = 1, columnIterator = 0, len = items.length, totalHeight = item.height, itemHeight, totalHeightArray = [[totalHeight]]; for(; i < len; ++i) { item = items[i]; itemHeight = item.height; if((totalHeight + verticalGap + itemHeight) <= limit) { totalHeight += verticalGap + itemHeight; columnArray[columnIterator].push(item); } else { totalHeight = verticalGap + itemHeight; if(columnArray[columnIterator]) { columnIterator += 1; } columnArray[columnIterator] = [item]; } totalHeightArray[columnIterator] = totalHeight; } VerticalLegendLayout.columnArray = columnArray; VerticalLegendLayout.totalHeightArray = totalHeightArray; }, /** * Returns the starting y-coordinate for a column of legend items. * * @method getStartPoint * @param {Number} h Height of the legend. * @param {Number} totalHeight Total height of all labels in the column. * @param {String} align Vertical alignment of items for the legend. * @param {Object} padding Object contain left, top, right and bottom padding properties. * @return Number * @protected */ getStartPoint: function(h, totalHeight, align, padding) { var startPoint; switch(align) { case TOP : startPoint = padding.top; break; case "middle" : startPoint = (h - totalHeight) * 0.5; break; case BOTTOM : startPoint = h - totalHeight - padding.bottom; break; } return startPoint; } }, CartesianChartLegend = Y.Base.create("cartesianChartLegend", Y.CartesianChart, [], { /** * Redraws and position all the components of the chart instance. * * @method _redraw * @private */ _redraw: function() { if(this._drawing) { this._callLater = true; return; } this._drawing = true; this._callLater = false; var w = this.get("width"), h = this.get("height"), layoutBoxDimensions = this._getLayoutBoxDimensions(), leftPaneWidth = layoutBoxDimensions.left, rightPaneWidth = layoutBoxDimensions.right, topPaneHeight = layoutBoxDimensions.top, bottomPaneHeight = layoutBoxDimensions.bottom, leftAxesCollection = this.get("leftAxesCollection"), rightAxesCollection = this.get("rightAxesCollection"), topAxesCollection = this.get("topAxesCollection"), bottomAxesCollection = this.get("bottomAxesCollection"), i = 0, l, axis, graphOverflow = "visible", graph = this.get("graph"), topOverflow, bottomOverflow, leftOverflow, rightOverflow, graphWidth, graphHeight, graphX, graphY, allowContentOverflow = this.get("allowContentOverflow"), diff, rightAxesXCoords, leftAxesXCoords, topAxesYCoords, bottomAxesYCoords, legend = this.get("legend"), graphRect = {}; if(leftAxesCollection) { leftAxesXCoords = []; l = leftAxesCollection.length; for(i = l - 1; i > -1; --i) { leftAxesXCoords.unshift(leftPaneWidth); leftPaneWidth += leftAxesCollection[i].get("width"); } } if(rightAxesCollection) { rightAxesXCoords = []; l = rightAxesCollection.length; i = 0; for(i = l - 1; i > -1; --i) { rightPaneWidth += rightAxesCollection[i].get("width"); rightAxesXCoords.unshift(w - rightPaneWidth); } } if(topAxesCollection) { topAxesYCoords = []; l = topAxesCollection.length; for(i = l - 1; i > -1; --i) { topAxesYCoords.unshift(topPaneHeight); topPaneHeight += topAxesCollection[i].get("height"); } } if(bottomAxesCollection) { bottomAxesYCoords = []; l = bottomAxesCollection.length; for(i = l - 1; i > -1; --i) { bottomPaneHeight += bottomAxesCollection[i].get("height"); bottomAxesYCoords.unshift(h - bottomPaneHeight); } } graphWidth = w - (leftPaneWidth + rightPaneWidth); graphHeight = h - (bottomPaneHeight + topPaneHeight); graphRect.left = leftPaneWidth; graphRect.top = topPaneHeight; graphRect.bottom = h - bottomPaneHeight; graphRect.right = w - rightPaneWidth; if(!allowContentOverflow) { topOverflow = this._getTopOverflow(leftAxesCollection, rightAxesCollection); bottomOverflow = this._getBottomOverflow(leftAxesCollection, rightAxesCollection); leftOverflow = this._getLeftOverflow(bottomAxesCollection, topAxesCollection); rightOverflow = this._getRightOverflow(bottomAxesCollection, topAxesCollection); diff = topOverflow - topPaneHeight; if(diff > 0) { graphRect.top = topOverflow; if(topAxesYCoords) { i = 0; l = topAxesYCoords.length; for(; i < l; ++i) { topAxesYCoords[i] += diff; } } } diff = bottomOverflow - bottomPaneHeight; if(diff > 0) { graphRect.bottom = h - bottomOverflow; if(bottomAxesYCoords) { i = 0; l = bottomAxesYCoords.length; for(; i < l; ++i) { bottomAxesYCoords[i] -= diff; } } } diff = leftOverflow - leftPaneWidth; if(diff > 0) { graphRect.left = leftOverflow; if(leftAxesXCoords) { i = 0; l = leftAxesXCoords.length; for(; i < l; ++i) { leftAxesXCoords[i] += diff; } } } diff = rightOverflow - rightPaneWidth; if(diff > 0) { graphRect.right = w - rightOverflow; if(rightAxesXCoords) { i = 0; l = rightAxesXCoords.length; for(; i < l; ++i) { rightAxesXCoords[i] -= diff; } } } } graphWidth = graphRect.right - graphRect.left; graphHeight = graphRect.bottom - graphRect.top; graphX = graphRect.left; graphY = graphRect.top; if(legend) { if(legend.get("includeInChartLayout")) { switch(legend.get("position")) { case "left" : legend.set("y", graphY); legend.set("height", graphHeight); break; case "top" : legend.set("x", graphX); legend.set("width", graphWidth); break; case "bottom" : legend.set("x", graphX); legend.set("width", graphWidth); break; case "right" : legend.set("y", graphY); legend.set("height", graphHeight); break; } } } if(topAxesCollection) { l = topAxesCollection.length; i = 0; for(; i < l; i++) { axis = topAxesCollection[i]; if(axis.get("width") !== graphWidth) { axis.set("width", graphWidth); } axis.get("boundingBox").setStyle("left", graphX + PX); axis.get("boundingBox").setStyle("top", topAxesYCoords[i] + PX); } if(axis._hasDataOverflow()) { graphOverflow = "hidden"; } } if(bottomAxesCollection) { l = bottomAxesCollection.length; i = 0; for(; i < l; i++) { axis = bottomAxesCollection[i]; if(axis.get("width") !== graphWidth) { axis.set("width", graphWidth); } axis.get("boundingBox").setStyle("left", graphX + PX); axis.get("boundingBox").setStyle("top", bottomAxesYCoords[i] + PX); } if(axis._hasDataOverflow()) { graphOverflow = "hidden"; } } if(leftAxesCollection) { l = leftAxesCollection.length; i = 0; for(; i < l; ++i) { axis = leftAxesCollection[i]; axis.get("boundingBox").setStyle("top", graphY + PX); axis.get("boundingBox").setStyle("left", leftAxesXCoords[i] + PX); if(axis.get("height") !== graphHeight) { axis.set("height", graphHeight); } } if(axis._hasDataOverflow()) { graphOverflow = "hidden"; } } if(rightAxesCollection) { l = rightAxesCollection.length; i = 0; for(; i < l; ++i) { axis = rightAxesCollection[i]; axis.get("boundingBox").setStyle("top", graphY + PX); axis.get("boundingBox").setStyle("left", rightAxesXCoords[i] + PX); if(axis.get("height") !== graphHeight) { axis.set("height", graphHeight); } } if(axis._hasDataOverflow()) { graphOverflow = "hidden"; } } this._drawing = false; if(this._callLater) { this._redraw(); return; } if(graph) { graph.get("boundingBox").setStyle("left", graphX + PX); graph.get("boundingBox").setStyle("top", graphY + PX); graph.set("width", graphWidth); graph.set("height", graphHeight); graph.get("boundingBox").setStyle("overflow", graphOverflow); } if(this._overlay) { this._overlay.setStyle("left", graphX + PX); this._overlay.setStyle("top", graphY + PX); this._overlay.setStyle("width", graphWidth + PX); this._overlay.setStyle("height", graphHeight + PX); } }, /** * Positions the legend in a chart and returns the properties of the legend to be used in the * chart's layout algorithm. * * @method _getLayoutDimensions * @return {Object} The left, top, right and bottom values for the legend. * @protected */ _getLayoutBoxDimensions: function() { var box = { top: 0, right: 0, bottom: 0, left: 0 }, legend = this.get("legend"), position, direction, dimension, size, w = this.get(WIDTH), h = this.get(HEIGHT), gap; if(legend && legend.get("includeInChartLayout")) { gap = legend.get("styles").gap; position = legend.get(POSITION); if(position != EXTERNAL) { direction = legend.get("direction"); dimension = direction == HORIZONTAL ? HEIGHT : WIDTH; size = legend.get(dimension); box[position] = size + gap; switch(position) { case TOP : legend.set(_Y, 0); break; case BOTTOM : legend.set(_Y, h - size); break; case RIGHT : legend.set(_X, w - size); break; case LEFT: legend.set(_X, 0); break; } } } return box; }, /** * Destructor implementation for the CartesianChart class. Calls destroy on all axes, series, legend (if available) and the Graph instance. * Removes the tooltip and overlay HTML elements. * * @method destructor * @protected */ destructor: function() { var legend = this.get("legend"); if(legend) { legend.destroy(true); } } }, { ATTRS: { legend: LEGEND } }); Y.CartesianChart = CartesianChartLegend; var PieChartLegend = Y.Base.create("pieChartLegend", Y.PieChart, [], { /** * Redraws the chart instance. * * @method _redraw * @private */ _redraw: function() { if(this._drawing) { this._callLater = true; return; } this._drawing = true; this._callLater = false; var graph = this.get("graph"), w = this.get("width"), h = this.get("height"), graphWidth, graphHeight, legend = this.get("legend"), x = 0, y = 0, legendX = 0, legendY = 0, legendWidth, legendHeight, dimension, gap, position, direction; if(graph) { if(legend) { position = legend.get("position"); direction = legend.get("direction"); graphWidth = graph.get("width"); graphHeight = graph.get("height"); legendWidth = legend.get("width"); legendHeight = legend.get("height"); gap = legend.get("styles").gap; if((direction == "vertical" && (graphWidth + legendWidth + gap !== w)) || (direction == "horizontal" && (graphHeight + legendHeight + gap !== h))) { switch(legend.get("position")) { case LEFT : dimension = Math.min(w - (legendWidth + gap), h); legendHeight = h; x = legendWidth + gap; legend.set(HEIGHT, legendHeight); break; case TOP : dimension = Math.min(h - (legendHeight + gap), w); legendWidth = w; y = legendHeight + gap; legend.set(WIDTH, legendWidth); break; case RIGHT : dimension = Math.min(w - (legendWidth + gap), h); legendHeight = h; legendX = dimension + gap; legend.set(HEIGHT, legendHeight); break; case BOTTOM : dimension = Math.min(h - (legendHeight + gap), w); legendWidth = w; legendY = dimension + gap; legend.set(WIDTH, legendWidth); break; } graph.set(WIDTH, dimension); graph.set(HEIGHT, dimension); } else { switch(legend.get("position")) { case LEFT : x = legendWidth + gap; break; case TOP : y = legendHeight + gap; break; case RIGHT : legendX = graphWidth + gap; break; case BOTTOM : legendY = graphHeight + gap; break; } } } else { graph.set(_X, 0); graph.set(_Y, 0); graph.set(WIDTH, w); graph.set(HEIGHT, h); } } this._drawing = false; if(this._callLater) { this._redraw(); return; } if(graph) { graph.set(_X, x); graph.set(_Y, y); } if(legend) { legend.set(_X, legendX); legend.set(_Y, legendY); } } }, { ATTRS: { /** * The legend for the chart. * * @attribute * @type Legend */ legend: LEGEND } }); Y.PieChart = PieChartLegend; /** * ChartLegend provides a legend for a chart. * * @class ChartLegend * @module charts * @submodule charts-legend * @extends Widget */ Y.ChartLegend = Y.Base.create("chartlegend", Y.Widget, [Y.Renderer], { /** * Initializes the chart. * * @method initializer * @private */ initializer: function() { this._items = []; }, /** * @method renderUI * @private */ renderUI: function() { var bb = this.get("boundingBox"), cb = this.get("contentBox"), styles = this.get("styles").background, background = new Y.Rect({ graphic: cb, fill: styles.fill, stroke: styles.border }); bb.setStyle("display", "block"); bb.setStyle("position", "absolute"); this.set("background", background); }, /** * @method bindUI * @private */ bindUI: function() { this.get("chart").after("seriesCollectionChange", Y.bind(this._updateHandler, this)); this.after("stylesChange", this._updateHandler); this.after("positionChange", this._positionChangeHandler); this.after("widthChange", this._handleSizeChange); this.after("heightChange", this._handleSizeChange); }, /** * @method syncUI * @private */ syncUI: function() { var w = this.get("width"), h = this.get("height"); if(isFinite(w) && isFinite(h) && w > 0 && h > 0) { this._drawLegend(); } }, /** * Handles changes to legend. * * @method _updateHandler * @param {Object} e Event object * @private */ _updateHandler: function(e) { if(this.get("rendered")) { this._drawLegend(); } }, /** * Handles position changes. * * @method _positionChangeHandler * @param {Object} e Event object * @private */ _positionChangeHandler: function(e) { var chart = this.get("chart"), parentNode = this._parentNode; if(parentNode && ((chart && this.get("includeInChartLayout")))) { this.fire("legendRendered"); } else if(this.get("rendered")) { this._drawLegend(); } }, /** * Updates the legend when the size changes. * * @method _handleSizeChange * @param {Object} e Event object. * @private */ _handleSizeChange: function(e) { var attrName = e.attrName, pos = this.get(POSITION), vert = pos == LEFT || pos == RIGHT, hor = pos == BOTTOM || pos == TOP; if((hor && attrName == WIDTH) || (vert && attrName == HEIGHT)) { this._drawLegend(); } }, /** * Draws the legend * * @method _drawLegend * @private */ _drawLegend: function() { if(this._drawing) { this._callLater = true; return; } this._drawing = true; this._callLater = false; if(this.get("includeInChartLayout")) { this.get("chart")._itemRenderQueue.unshift(this); } var chart = this.get("chart"), node = this.get("contentBox"), seriesCollection = chart.get("seriesCollection"), series, styles = this.get("styles"), padding = styles.padding, itemStyles = styles.item, seriesStyles, hSpacing = itemStyles.hSpacing, vSpacing = itemStyles.vSpacing, hAlign = styles.hAlign, vAlign = styles.vAlign, marker = styles.marker, labelStyles = itemStyles.label, displayName, layout = this._layout[this.get("direction")], i, len, isArray, shape, shapeClass, item, fill, border, fillColors, borderColors, borderWeight, items = [], markerWidth = marker.width, markerHeight = marker.height, totalWidth = 0 - hSpacing, totalHeight = 0 - vSpacing, maxWidth = 0, maxHeight = 0, itemWidth, itemHeight; if(marker && marker.shape) { shape = marker.shape; } this._destroyLegendItems(); if(chart instanceof Y.PieChart) { series = seriesCollection[0]; displayName = series.get("categoryAxis").getDataByKey(series.get("categoryKey")); seriesStyles = series.get("styles").marker; fillColors = seriesStyles.fill.colors; borderColors = seriesStyles.border.colors; borderWeight = seriesStyles.border.weight; i = 0; len = displayName.length; shape = shape || Y.Circle; isArray = Y.Lang.isArray(shape); for(; i < len; ++i) { shape = isArray ? shape[i] : shape; fill = { color: fillColors[i] }; border = { colors: borderColors[i], weight: borderWeight }; displayName = chart.getSeriesItems(series, i).category.value; item = this._getLegendItem(node, this._getShapeClass(shape), fill, border, labelStyles, markerWidth, markerHeight, displayName); itemWidth = item.width; itemHeight = item.height; maxWidth = Math.max(maxWidth, itemWidth); maxHeight = Math.max(maxHeight, itemHeight); totalWidth += itemWidth + hSpacing; totalHeight += itemHeight + vSpacing; items.push(item); } } else { i = 0; len = seriesCollection.length; for(; i < len; ++i) { series = seriesCollection[i]; seriesStyles = this._getStylesBySeriesType(series, shape); if(!shape) { shape = seriesStyles.shape; if(!shape) { shape = Y.Circle; } } shapeClass = Y.Lang.isArray(shape) ? shape[i] : shape; item = this._getLegendItem(node, this._getShapeClass(shape), seriesStyles.fill, seriesStyles.border, labelStyles, markerWidth, markerHeight, series.get("valueDisplayName")); itemWidth = item.width; itemHeight = item.height; maxWidth = Math.max(maxWidth, itemWidth); maxHeight = Math.max(maxHeight, itemHeight); totalWidth += itemWidth + hSpacing; totalHeight += itemHeight + vSpacing; items.push(item); } } this._drawing = false; if(this._callLater) { this._drawLegend(); } else { layout._positionLegendItems.apply(this, [items, maxWidth, maxHeight, totalWidth, totalHeight, padding, hSpacing, vSpacing, hAlign, vAlign]); this._updateBackground(styles); this.fire("legendRendered"); } }, /** * Updates the background for the legend. * * @method _updateBackground * @param {Object} styles Reference to the legend's styles attribute * @private */ _updateBackground: function(styles) { var backgroundStyles = styles.background, contentRect = this._contentRect, padding = styles.padding, x = contentRect.left - padding.left, y = contentRect.top - padding.top, w = contentRect.right - x + padding.right, h = contentRect.bottom - y + padding.bottom; this.get("background").set({ fill: backgroundStyles.fill, stroke: backgroundStyles.border, width: w, height: h, x: x, y: y }); }, /** * Retrieves the marker styles based on the type of series. For series that contain a marker, the marker styles are returned. * * @method _getStylesBySeriesType * @param {CartesianSeries | PieSeries} The series in which the style properties will be received. * @return Object An object containing fill, border and shape information. * @private */ _getStylesBySeriesType: function(series) { var styles = series.get("styles"), color; if(series instanceof Y.LineSeries || series instanceof Y.StackedLineSeries) { styles = series.get("styles").line; color = styles.color || series._getDefaultColor(series.get("graphOrder"), "line"); return { border: { weight: 1, color: color }, fill: { color: color } }; } else if(series instanceof Y.AreaSeries || series instanceof Y.StackedAreaSeries) { styles = series.get("styles").area; color = styles.color || series._getDefaultColor(series.get("graphOrder"), "slice"); return { border: { weight: 1, color: color }, fill: { color: color } }; } else { styles = series.get("styles").marker; return { fill: styles.fill, border: { weight: styles.border.weight, color: styles.border.color, shape: styles.shape }, shape: styles.shape }; } }, /** * Returns a legend item consisting of the following properties: * <dl> * <dt>node</dt><dd>The `Node` containing the legend item elements.</dd> * <dt>shape</dt><dd>The `Shape` element for the legend item.</dd> * <dt>textNode</dt><dd>The `Node` containing the text></dd> * <dt>text</dt><dd></dd> * </dl> * * @method _getLegendItem * @param {Node} shapeProps Reference to the `node` attribute. * @param {String | Class} shapeClass The type of shape * @param {Object} fill Properties for the shape's fill * @param {Object} border Properties for the shape's border * @param {String} text String to be rendered as the legend's text * @param {Number} width Total width of the legend item * @param {Number} height Total height of the legend item * @param {HTML | String} text Text for the legendItem * @return Object * @private */ _getLegendItem: function(node, shapeClass, fill, border, labelStyles, w, h, text) { var containerNode = Y.one(DOCUMENT.createElement("div")), textField = Y.one(DOCUMENT.createElement("span")), shape, dimension, padding, left, item; containerNode.setStyle(POSITION, "absolute"); textField.setStyle(POSITION, "absolute"); textField.setStyles(labelStyles); textField.appendChild(DOCUMENT.createTextNode(text)); containerNode.appendChild(textField); node.appendChild(containerNode); dimension = textField.get("offsetHeight"); padding = dimension - h; left = w + padding + 2; textField.setStyle("left", left + PX); containerNode.setStyle("height", dimension + PX); containerNode.setStyle("width", (left + textField.get("offsetWidth")) + PX); shape = new shapeClass({ fill: fill, stroke: border, width: w, height: h, x: padding * 0.5, y: padding * 0.5, w: w, h: h, graphic: containerNode }); textField.setStyle("left", dimension + PX); item = { node: containerNode, width: containerNode.get("offsetWidth"), height: containerNode.get("offsetHeight"), shape: shape, textNode: textField, text: text }; this._items.push(item); return item; }, /** * Evaluates and returns correct class for drawing a shape. * * @method _getShapeClass * @return Shape * @private */ _getShapeClass: function() { var graphic = this.get("background").get("graphic"); return graphic._getShapeClass.apply(graphic, arguments); }, /** * Returns the default hash for the `styles` attribute. * * @method _getDefaultStyles * @return Object * @protected */ _getDefaultStyles: function() { var styles = { padding: { top: 8, right: 8, bottom: 8, left: 9 }, gap: 10, hAlign: "center", vAlign: "top", marker: this._getPlotDefaults(), item: { hSpacing: 10, vSpacing: 5, label: { color:"#808080", fontSize:"85%", whiteSpace: "nowrap" } }, background: { shape: "rect", fill:{ color:"#faf9f2" }, border: { color:"#dad8c9", weight: 1 } } }; return styles; }, /** * Gets the default values for series that use the utility. This method is used by * the class' `styles` attribute's getter to get build default values. * * @method _getPlotDefaults * @return Object * @protected */ _getPlotDefaults: function() { var defs = { width: 10, height: 10 }; return defs; }, /** * Destroys legend items. * * @method _destroyLegendItems * @private */ _destroyLegendItems: function() { var item; if(this._items) { while(this._items.length > 0) { item = this._items.shift(); item.shape.get("graphic").destroy(); item.node.empty(); item.node.destroy(true); item.node = null; item = null; } } this._items = []; }, /** * Maps layout classes. * * @property _layout * @private */ _layout: { vertical: VerticalLegendLayout, horizontal: HorizontalLegendLayout }, /** * Destructor implementation ChartLegend class. Removes all items and the Graphic instance from the widget. * * @method destructor * @protected */ destructor: function() { var background = this.get("background"), backgroundGraphic; this._destroyLegendItems(); if(background) { backgroundGraphic = background.get("graphic"); if(backgroundGraphic) { backgroundGraphic.destroy(); } else { background.destroy(); } } } }, { ATTRS: { /** * Indicates whether the chart's contentBox is the parentNode for the legend. * * @attribute includeInChartLayout * @type Boolean * @private */ includeInChartLayout: { value: false }, /** * Reference to the `Chart` instance. * * @attribute chart * @type Chart */ chart: { setter: function(val) { this.after("legendRendered", Y.bind(val._itemRendered, val)); return val; } }, /** * Indicates the direction in relation of the legend's layout. The `direction` of the legend is determined by its * `position` value. * * @attribute direction * @type String */ direction: { value: "vertical" }, /** * Indicates the position and direction of the legend. Possible values are `left`, `top`, `right` and `bottom`. Values of `left` and * `right` values have a `direction` of `vertical`. Values of `top` and `bottom` values have a `direction` of `horizontal`. * * @attribute position * @type String */ position: { lazyAdd: false, value: "right", setter: function(val) { if(val == TOP || val == BOTTOM) { this.set("direction", HORIZONTAL); } else if(val == LEFT || val == RIGHT) { this.set("direction", VERTICAL); } return val; } }, /** * The width of the legend. Depending on the implementation of the ChartLegend, this value is `readOnly`. * By default, the legend is included in the layout of the `Chart` that it references. Under this circumstance, * `width` is always `readOnly`. When the legend is rendered in its own dom element, the `readOnly` status is * determined by the direction of the legend. If the `position` is `left` or `right` or the `direction` is * `vertical`, width is `readOnly`. If the position is `top` or `bottom` or the `direction` is `horizontal`, * width can be explicitly set. If width is not explicitly set, the width will be determined by the width of the * legend's parent element. * * @attribute width * @type Number */ width: { getter: function() { var chart = this.get("chart"), parentNode = this._parentNode; if(parentNode) { if((chart && this.get("includeInChartLayout")) || this._width) { if(!this._width) { this._width = 0; } return this._width; } else { return parentNode.get("offsetWidth"); } } return ""; }, setter: function(val) { this._width = val; return val; } }, /** * The height of the legend. Depending on the implementation of the ChartLegend, this value is `readOnly`. * By default, the legend is included in the layout of the `Chart` that it references. Under this circumstance, * `height` is always `readOnly`. When the legend is rendered in its own dom element, the `readOnly` status is * determined by the direction of the legend. If the `position` is `top` or `bottom` or the `direction` is * `horizontal`, height is `readOnly`. If the position is `left` or `right` or the `direction` is `vertical`, * height can be explicitly set. If height is not explicitly set, the height will be determined by the width of the * legend's parent element. * * @attribute height * @type Number */ height: { valueFn: "_heightGetter", getter: function() { var chart = this.get("chart"), parentNode = this._parentNode; if(parentNode) { if((chart && this.get("includeInChartLayout")) || this._height) { if(!this._height) { this._height = 0; } return this._height; } else { return parentNode.get("offsetHeight"); } } return ""; }, setter: function(val) { this._height = val; return val; } }, /** * Indicates the x position of legend. * * @attribute x * @type Number * @readOnly */ x: { lazyAdd: false, value: 0, setter: function(val) { var node = this.get("boundingBox"); if(node) { node.setStyle(LEFT, val + PX); } return val; } }, /** * Indicates the y position of legend. * * @attribute y * @type Number * @readOnly */ y: { lazyAdd: false, value: 0, setter: function(val) { var node = this.get("boundingBox"); if(node) { node.setStyle(TOP, val + PX); } return val; } }, /** * Array of items contained in the legend. Each item is an object containing the following properties: * * <dl> * <dt>node</dt><dd>Node containing text for the legend item.</dd> * <dt>marker</dt><dd>Shape for the legend item.</dd> * </dl> * * @attribute items * @type Array * @readOnly */ items: { getter: function() { return this._items; } }, /** * Background for the legend. * * @attribute background * @type Rect */ background: {} /** * Properties used to display and style the ChartLegend. This attribute is inherited from `Renderer`. * Below are the default values: * * <dl> * <dt>gap</dt><dd>Distance, in pixels, between the `ChartLegend` instance and the chart's content. When `ChartLegend` * is rendered within a `Chart` instance this value is applied.</dd> * <dt>hAlign</dt><dd>Defines the horizontal alignment of the `items` in a `ChartLegend` rendered in a horizontal direction. * This value is applied when the instance's `position` is set to top or bottom. This attribute can be set to left, center * or right. The default value is center.</dd> * <dt>vAlign</dt><dd>Defines the vertical alignment of the `items` in a `ChartLegend` rendered in vertical direction. This * value is applied when the instance's `position` is set to left or right. The attribute can be set to top, middle or * bottom. The default value is middle.</dd> * <dt>item</dt><dd>Set of style properties applied to the `items` of the `ChartLegend`. * <dl> * <dt>hSpacing</dt><dd>Horizontal distance, in pixels, between legend `items`.</dd> * <dt>vSpacing</dt><dd>Vertical distance, in pixels, between legend `items`.</dd> * <dt>label</dt><dd>Properties for the text of an `item`. * <dl> * <dt>color</dt><dd>Color of the text. The default values is "#808080".</dd> * <dt>fontSize</dt><dd>Font size for the text. The default value is "85%".</dd> * </dl> * </dd> * <dt>marker</dt><dd>Properties for the `item` markers. * <dl> * <dt>width</dt><dd>Specifies the width of the markers.</dd> * <dt>height</dt><dd>Specifies the height of the markers.</dd> * </dl> * </dd> * </dl> * </dd> * <dt>background</dt><dd>Properties for the `ChartLegend` background. * <dl> * <dt>fill</dt><dd>Properties for the background fill. * <dl> * <dt>color</dt><dd>Color for the fill. The default value is "#faf9f2".</dd> * </dl> * </dd> * <dt>border</dt><dd>Properties for the background border. * <dl> * <dt>color</dt><dd>Color for the border. The default value is "#dad8c9".</dd> * <dt>weight</dt><dd>Weight of the border. The default values is 1.</dd> * </dl> * </dd> * </dl> * </dd> * </dl> * * @attribute styles * @type Object */ } }); /** * The Chart class is the basic application used to create a chart. * * @module charts * @class Chart * @constructor */ function Chart(cfg) { if(cfg.type != "pie") { return new Y.CartesianChart(cfg); } else { return new Y.PieChart(cfg); } } Y.Chart = Chart; }, '3.8.0pr2', {"requires": ["charts-base"]});
// wrapped by build app define("d3/src/selection/data", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ import "../arrays/map"; import "../arrays/set"; import "selection"; d3_selectionPrototype.data = function(value, key) { var i = -1, n = this.length, group, node; // If no value is specified, return the first value. if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; if (key) { var nodeByKeyValue = new d3_Map, keyValues = new Array(n), keyValue; for (i = -1; ++i < n;) { if (nodeByKeyValue.has(keyValue = key.call(node = group[i], node.__data__, i))) { exitNodes[i] = node; // duplicate selection key } else { nodeByKeyValue.set(keyValue, node); } keyValues[i] = keyValue; } for (i = -1; ++i < m;) { if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { enterNodes[i] = d3_selection_dataNode(nodeData); } else if (node !== true) { // no duplicate data key updateNodes[i] = node; node.__data__ = nodeData; } nodeByKeyValue.set(keyValue, true); } for (i = -1; ++i < n;) { if (nodeByKeyValue.get(keyValues[i]) !== true) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0;) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; } else { enterNodes[i] = d3_selection_dataNode(nodeData); } } for (; i < m; ++i) { enterNodes[i] = d3_selection_dataNode(groupData[i]); } for (; i < n; ++i) { exitNodes[i] = group[i]; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; }; function d3_selection_dataNode(data) { return {__data__: data}; } });
var assert = require('assert'); var R = require('..'); describe('nthChar', function() { it('returns the nth character of the given string', function() { assert.strictEqual(R.nthChar(2, 'Ramda'), 'm'); }); it('accepts negative offsets', function() { assert.strictEqual(R.nthChar(-2, 'Ramda'), 'd'); }); it('is curried', function() { assert.strictEqual(R.nthChar(2)('Ramda'), 'm'); }); });
/** * The `Matter.Svg` module contains methods for converting SVG images into an array of vector points. * * See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js) * and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples. * * @class Svg */ var Svg = {}; module.exports = Svg; var Bounds = require('../geometry/Bounds'); (function() { /** * Converts an SVG path into an array of vector points. * If the input path forms a concave shape, you must decompose the result into convex parts before use. * See `Bodies.fromVertices` which provides support for this. * Note that this function is not guaranteed to support complex paths (such as those with holes). * @method pathToVertices * @param {SVGPathElement} path * @param {Number} [sampleLength=15] * @return {Vector[]} points */ Svg.pathToVertices = function(path, sampleLength) { // https://github.com/wout/svg.topoly.js/blob/master/svg.topoly.js var i, il, total, point, segment, segments, segmentsQueue, lastSegment, lastPoint, segmentIndex, points = [], lx, ly, length = 0, x = 0, y = 0; sampleLength = sampleLength || 15; var addPoint = function(px, py, pathSegType) { // all odd-numbered path types are relative except PATHSEG_CLOSEPATH (1) var isRelative = pathSegType % 2 === 1 && pathSegType > 1; // when the last point doesn't equal the current point add the current point if (!lastPoint || px != lastPoint.x || py != lastPoint.y) { if (lastPoint && isRelative) { lx = lastPoint.x; ly = lastPoint.y; } else { lx = 0; ly = 0; } var point = { x: lx + px, y: ly + py }; // set last point if (isRelative || !lastPoint) { lastPoint = point; } points.push(point); x = lx + px; y = ly + py; } }; var addSegmentPoint = function(segment) { var segType = segment.pathSegTypeAsLetter.toUpperCase(); // skip path ends if (segType === 'Z') return; // map segment to x and y switch (segType) { case 'M': case 'L': case 'T': case 'C': case 'S': case 'Q': x = segment.x; y = segment.y; break; case 'H': x = segment.x; break; case 'V': y = segment.y; break; } addPoint(x, y, segment.pathSegType); }; // ensure path is absolute _svgPathToAbsolute(path); // get total length total = path.getTotalLength(); // queue segments segments = []; for (i = 0; i < path.pathSegList.numberOfItems; i += 1) segments.push(path.pathSegList.getItem(i)); segmentsQueue = segments.concat(); // sample through path while (length < total) { // get segment at position segmentIndex = path.getPathSegAtLength(length); segment = segments[segmentIndex]; // new segment if (segment != lastSegment) { while (segmentsQueue.length && segmentsQueue[0] != segment) addSegmentPoint(segmentsQueue.shift()); lastSegment = segment; } // add points in between when curving // TODO: adaptive sampling switch (segment.pathSegTypeAsLetter.toUpperCase()) { case 'C': case 'T': case 'S': case 'Q': case 'A': point = path.getPointAtLength(length); addPoint(point.x, point.y, 0); break; } // increment by sample value length += sampleLength; } // add remaining segments not passed by sampling for (i = 0, il = segmentsQueue.length; i < il; ++i) addSegmentPoint(segmentsQueue[i]); return points; }; var _svgPathToAbsolute = function(path) { // http://phrogz.net/convert-svg-path-to-all-absolute-commands var x0, y0, x1, y1, x2, y2, segs = path.pathSegList, x = 0, y = 0, len = segs.numberOfItems; for (var i = 0; i < len; ++i) { var seg = segs.getItem(i), segType = seg.pathSegTypeAsLetter; if (/[MLHVCSQTA]/.test(segType)) { if ('x' in seg) x = seg.x; if ('y' in seg) y = seg.y; } else { if ('x1' in seg) x1 = x + seg.x1; if ('x2' in seg) x2 = x + seg.x2; if ('y1' in seg) y1 = y + seg.y1; if ('y2' in seg) y2 = y + seg.y2; if ('x' in seg) x += seg.x; if ('y' in seg) y += seg.y; switch (segType) { case 'm': segs.replaceItem(path.createSVGPathSegMovetoAbs(x, y), i); break; case 'l': segs.replaceItem(path.createSVGPathSegLinetoAbs(x, y), i); break; case 'h': segs.replaceItem(path.createSVGPathSegLinetoHorizontalAbs(x), i); break; case 'v': segs.replaceItem(path.createSVGPathSegLinetoVerticalAbs(y), i); break; case 'c': segs.replaceItem(path.createSVGPathSegCurvetoCubicAbs(x, y, x1, y1, x2, y2), i); break; case 's': segs.replaceItem(path.createSVGPathSegCurvetoCubicSmoothAbs(x, y, x2, y2), i); break; case 'q': segs.replaceItem(path.createSVGPathSegCurvetoQuadraticAbs(x, y, x1, y1), i); break; case 't': segs.replaceItem(path.createSVGPathSegCurvetoQuadraticSmoothAbs(x, y), i); break; case 'a': segs.replaceItem(path.createSVGPathSegArcAbs(x, y, seg.r1, seg.r2, seg.angle, seg.largeArcFlag, seg.sweepFlag), i); break; case 'z': case 'Z': x = x0; y = y0; break; } } if (segType == 'M' || segType == 'm') { x0 = x; y0 = y; } } }; })();
"use strict";import H from"../../Core/Globals.js";import HighContrastDarkTheme from"../../Extensions/Themes/HighContrastDark.js";H.theme=HighContrastDarkTheme.options,HighContrastDarkTheme.apply();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends2 = require('babel-runtime/helpers/extends'); var _extends3 = _interopRequireDefault(_extends2); var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties'); var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _simpleAssign = require('simple-assign'); var _simpleAssign2 = _interopRequireDefault(_simpleAssign); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _keycode = require('keycode'); var _keycode2 = _interopRequireDefault(_keycode); var _colorManipulator = require('../utils/colorManipulator'); var _EnhancedButton = require('../internal/EnhancedButton'); var _EnhancedButton2 = _interopRequireDefault(_EnhancedButton); var _cancel = require('../svg-icons/navigation/cancel'); var _cancel2 = _interopRequireDefault(_cancel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getStyles(props, context, state) { var chip = context.muiTheme.chip; var backgroundColor = props.backgroundColor || chip.backgroundColor; var focusColor = (0, _colorManipulator.emphasize)(backgroundColor, 0.08); var pressedColor = (0, _colorManipulator.emphasize)(backgroundColor, 0.12); return { avatar: { marginRight: -4 }, deleteIcon: { color: state.deleteHovered ? (0, _colorManipulator.fade)(chip.deleteIconColor, 0.4) : chip.deleteIconColor, cursor: 'pointer', margin: '4px 4px 0px -8px' }, label: { color: props.labelColor || chip.textColor, fontSize: chip.fontSize, fontWeight: chip.fontWeight, lineHeight: '32px', paddingLeft: 12, paddingRight: 12, userSelect: 'none', whiteSpace: 'nowrap' }, root: { backgroundColor: state.clicked ? pressedColor : state.focused || state.hovered ? focusColor : backgroundColor, borderRadius: 16, boxShadow: state.clicked ? chip.shadow : null, cursor: props.onTouchTap ? 'pointer' : 'default', display: 'flex', whiteSpace: 'nowrap', width: 'fit-content' } }; } var Chip = function (_Component) { (0, _inherits3.default)(Chip, _Component); function Chip() { var _ref; var _temp, _this, _ret; (0, _classCallCheck3.default)(this, Chip); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = Chip.__proto__ || (0, _getPrototypeOf2.default)(Chip)).call.apply(_ref, [this].concat(args))), _this), _this.state = { clicked: false, deleteHovered: false, focused: false, hovered: false }, _this.handleBlur = function (event) { _this.setState({ clicked: false, focused: false }); _this.props.onBlur(event); }, _this.handleFocus = function (event) { if (_this.props.onTouchTap || _this.props.onRequestDelete) { _this.setState({ focused: true }); } _this.props.onFocus(event); }, _this.handleKeyboardFocus = function (event, keyboardFocused) { if (keyboardFocused) { _this.handleFocus(); _this.props.onFocus(event); } else { _this.handleBlur(); } _this.props.onKeyboardFocus(event, keyboardFocused); }, _this.handleKeyDown = function (event) { if ((0, _keycode2.default)(event) === 'backspace') { event.preventDefault(); if (_this.props.onRequestDelete) { _this.props.onRequestDelete(event); } } _this.props.onKeyDown(event); }, _this.handleMouseDown = function (event) { // Only listen to left clicks if (event.button === 0) { event.stopPropagation(); if (_this.props.onTouchTap) { _this.setState({ clicked: true }); } } _this.props.onMouseDown(event); }, _this.handleMouseEnter = function (event) { if (_this.props.onTouchTap) { _this.setState({ hovered: true }); } _this.props.onMouseEnter(event); }, _this.handleMouseEnterDeleteIcon = function () { _this.setState({ deleteHovered: true }); }, _this.handleMouseLeave = function (event) { _this.setState({ clicked: false, hovered: false }); _this.props.onMouseLeave(event); }, _this.handleMouseLeaveDeleteIcon = function () { _this.setState({ deleteHovered: false }); }, _this.handleMouseUp = function (event) { _this.setState({ clicked: false }); _this.props.onMouseUp(event); }, _this.handleTouchTapDeleteIcon = function (event) { // Stop the event from bubbling up to the `Chip` event.stopPropagation(); _this.props.onRequestDelete(event); }, _this.handleTouchEnd = function (event) { _this.setState({ clicked: false }); _this.props.onTouchEnd(event); }, _this.handleTouchStart = function (event) { event.stopPropagation(); if (_this.props.onTouchTap) { _this.setState({ clicked: true }); } _this.props.onTouchStart(event); }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret); } (0, _createClass3.default)(Chip, [{ key: 'render', value: function render() { var buttonEventHandlers = { onBlur: this.handleBlur, onFocus: this.handleFocus, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave, onMouseUp: this.handleMouseUp, onTouchEnd: this.handleTouchEnd, onTouchStart: this.handleTouchStart, onKeyboardFocus: this.handleKeyboardFocus }; var prepareStyles = this.context.muiTheme.prepareStyles; var styles = getStyles(this.props, this.context, this.state); var _props = this.props, childrenProp = _props.children, style = _props.style, className = _props.className, labelStyle = _props.labelStyle, labelColor = _props.labelColor, backgroundColor = _props.backgroundColor, onRequestDelete = _props.onRequestDelete, other = (0, _objectWithoutProperties3.default)(_props, ['children', 'style', 'className', 'labelStyle', 'labelColor', 'backgroundColor', 'onRequestDelete']); var deletable = this.props.onRequestDelete; var avatar = null; var deleteIcon = deletable ? _react2.default.createElement(_cancel2.default, { color: styles.deleteIcon.color, style: styles.deleteIcon, onTouchTap: this.handleTouchTapDeleteIcon, onMouseEnter: this.handleMouseEnterDeleteIcon, onMouseLeave: this.handleMouseLeaveDeleteIcon }) : null; var children = childrenProp; var childCount = _react2.default.Children.count(children); // If the first child is an avatar, extract it and style it if (childCount > 1) { children = _react2.default.Children.toArray(children); if (_react2.default.isValidElement(children[0]) && children[0].type.muiName === 'Avatar') { avatar = children.shift(); avatar = _react2.default.cloneElement(avatar, { style: (0, _simpleAssign2.default)(styles.avatar, avatar.props.style), size: 32 }); } } return _react2.default.createElement( _EnhancedButton2.default, (0, _extends3.default)({}, other, buttonEventHandlers, { className: className, containerElement: 'div' // Firefox doesn't support nested buttons , disableTouchRipple: true, disableFocusRipple: true, style: (0, _simpleAssign2.default)(styles.root, style) }), avatar, _react2.default.createElement( 'span', { style: prepareStyles((0, _simpleAssign2.default)(styles.label, labelStyle)) }, children ), deleteIcon ); } }]); return Chip; }(_react.Component); Chip.defaultProps = { onBlur: function onBlur() {}, onFocus: function onFocus() {}, onKeyDown: function onKeyDown() {}, onKeyboardFocus: function onKeyboardFocus() {}, onMouseDown: function onMouseDown() {}, onMouseEnter: function onMouseEnter() {}, onMouseLeave: function onMouseLeave() {}, onMouseUp: function onMouseUp() {}, onTouchEnd: function onTouchEnd() {}, onTouchStart: function onTouchStart() {} }; Chip.contextTypes = { muiTheme: _react.PropTypes.object.isRequired }; process.env.NODE_ENV !== "production" ? Chip.propTypes = { /** * Override the background color of the chip. */ backgroundColor: _react.PropTypes.string, /** * Used to render elements inside the Chip. */ children: _react.PropTypes.node, /** * CSS `className` of the root element. */ className: _react.PropTypes.node, /** * Override the label color. */ labelColor: _react.PropTypes.string, /** * Override the inline-styles of the label. */ labelStyle: _react.PropTypes.object, /** @ignore */ onBlur: _react.PropTypes.func, /** @ignore */ onFocus: _react.PropTypes.func, /** @ignore */ onKeyDown: _react.PropTypes.func, /** @ignore */ onKeyboardFocus: _react.PropTypes.func, /** @ignore */ onMouseDown: _react.PropTypes.func, /** @ignore */ onMouseEnter: _react.PropTypes.func, /** @ignore */ onMouseLeave: _react.PropTypes.func, /** @ignore */ onMouseUp: _react.PropTypes.func, /** * Callback function fired when the delete icon is clicked. If set, the delete icon will be shown. * @param {object} event `touchTap` event targeting the element. */ onRequestDelete: _react.PropTypes.func, /** @ignore */ onTouchEnd: _react.PropTypes.func, /** @ignore */ onTouchStart: _react.PropTypes.func, /** * Callback function fired when the `Chip` element is touch-tapped. * * @param {object} event TouchTap event targeting the element. */ onTouchTap: _react.PropTypes.func, /** * Override the inline-styles of the root element. */ style: _react.PropTypes.object } : void 0; exports.default = Chip;
/** * jQuery EasyUI 1.3.6 * * Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved. * * Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt * To use it on other terms please contact us at info@jeasyui.com * */ (function($){ function _1(_2){ var _3=$.data(_2,"datebox"); var _4=_3.options; $(_2).addClass("datebox-f").combo($.extend({},_4,{onShowPanel:function(){ _5(); _10(_2,$(_2).datebox("getText"),true); _4.onShowPanel.call(_2); }})); $(_2).combo("textbox").parent().addClass("datebox"); if(!_3.calendar){ _6(); } _10(_2,_4.value); function _6(){ var _7=$(_2).combo("panel").css("overflow","hidden"); _7.panel("options").onBeforeDestroy=function(){ var sc=$(this).find(".calendar-shared"); if(sc.length){ sc.insertBefore(sc[0].pholder); } }; var cc=$("<div class=\"datebox-calendar-inner\"></div>").appendTo(_7); if(_4.sharedCalendar){ var sc=$(_4.sharedCalendar); if(!sc[0].pholder){ sc[0].pholder=$("<div class=\"calendar-pholder\" style=\"display:none\"></div>").insertAfter(sc); } sc.addClass("calendar-shared").appendTo(cc); if(!sc.hasClass("calendar")){ sc.calendar(); } _3.calendar=sc; }else{ _3.calendar=$("<div></div>").appendTo(cc).calendar(); } $.extend(_3.calendar.calendar("options"),{fit:true,border:false,onSelect:function(_8){ var _9=$(this.target).datebox("options"); _10(this.target,_9.formatter.call(this.target,_8)); $(this.target).combo("hidePanel"); _9.onSelect.call(_2,_8); }}); var _a=$("<div class=\"datebox-button\"><table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%\"><tr></tr></table></div>").appendTo(_7); var tr=_a.find("tr"); for(var i=0;i<_4.buttons.length;i++){ var td=$("<td></td>").appendTo(tr); var _b=_4.buttons[i]; var t=$("<a href=\"javascript:void(0)\"></a>").html($.isFunction(_b.text)?_b.text(_2):_b.text).appendTo(td); t.bind("click",{target:_2,handler:_b.handler},function(e){ e.data.handler.call(this,e.data.target); }); } tr.find("td").css("width",(100/_4.buttons.length)+"%"); }; function _5(){ var _c=$(_2).combo("panel"); var cc=_c.children("div.datebox-calendar-inner"); _c.children()._outerWidth(_c.width()); _3.calendar.appendTo(cc); _3.calendar[0].target=_2; if(_4.panelHeight!="auto"){ var _d=_c.height(); _c.children().not(cc).each(function(){ _d-=$(this).outerHeight(); }); cc._outerHeight(_d); } _3.calendar.calendar("resize"); }; }; function _e(_f,q){ _10(_f,q,true); }; function _11(_12){ var _13=$.data(_12,"datebox"); var _14=_13.options; var _15=_13.calendar.calendar("options").current; if(_15){ _10(_12,_14.formatter.call(_12,_15)); $(_12).combo("hidePanel"); } }; function _10(_16,_17,_18){ var _19=$.data(_16,"datebox"); var _1a=_19.options; var _1b=_19.calendar; $(_16).combo("setValue",_17); _1b.calendar("moveTo",_1a.parser.call(_16,_17)); if(!_18){ if(_17){ _17=_1a.formatter.call(_16,_1b.calendar("options").current); $(_16).combo("setValue",_17).combo("setText",_17); }else{ $(_16).combo("setText",_17); } } }; $.fn.datebox=function(_1c,_1d){ if(typeof _1c=="string"){ var _1e=$.fn.datebox.methods[_1c]; if(_1e){ return _1e(this,_1d); }else{ return this.combo(_1c,_1d); } } _1c=_1c||{}; return this.each(function(){ var _1f=$.data(this,"datebox"); if(_1f){ $.extend(_1f.options,_1c); }else{ $.data(this,"datebox",{options:$.extend({},$.fn.datebox.defaults,$.fn.datebox.parseOptions(this),_1c)}); } _1(this); }); }; $.fn.datebox.methods={options:function(jq){ var _20=jq.combo("options"); return $.extend($.data(jq[0],"datebox").options,{originalValue:_20.originalValue,disabled:_20.disabled,readonly:_20.readonly}); },calendar:function(jq){ return $.data(jq[0],"datebox").calendar; },setValue:function(jq,_21){ return jq.each(function(){ _10(this,_21); }); },reset:function(jq){ return jq.each(function(){ var _22=$(this).datebox("options"); $(this).datebox("setValue",_22.originalValue); }); }}; $.fn.datebox.parseOptions=function(_23){ return $.extend({},$.fn.combo.parseOptions(_23),$.parser.parseOptions(_23,["sharedCalendar"])); }; $.fn.datebox.defaults=$.extend({},$.fn.combo.defaults,{panelWidth:180,panelHeight:"auto",sharedCalendar:null,keyHandler:{up:function(e){ },down:function(e){ },left:function(e){ },right:function(e){ },enter:function(e){ _11(this); },query:function(q,e){ _e(this,q); }},currentText:"Today",closeText:"Close",okText:"Ok",buttons:[{text:function(_24){ return $(_24).datebox("options").currentText; },handler:function(_25){ $(_25).datebox("calendar").calendar({year:new Date().getFullYear(),month:new Date().getMonth()+1,current:new Date()}); _11(_25); }},{text:function(_26){ return $(_26).datebox("options").closeText; },handler:function(_27){ $(this).closest("div.combo-panel").panel("close"); }}],formatter:function(_28){ var y=_28.getFullYear(); var m=_28.getMonth()+1; var d=_28.getDate(); return m+"/"+d+"/"+y; },parser:function(s){ var t=Date.parse(s); if(!isNaN(t)){ return new Date(t); }else{ return new Date(); } },onSelect:function(_29){ }}); })(jQuery);
/*! ======================================================= VERSION 9.1.0 ========================================================= */ "use strict"; function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; } /*! ========================================================= * bootstrap-slider.js * * Maintainers: * Kyle Kemp * - Twitter: @seiyria * - Github: seiyria * Rohit Kalkur * - Twitter: @Rovolutionary * - Github: rovolution * * ========================================================= * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ /** * Bridget makes jQuery widgets * v1.0.1 * MIT license */ (function (factory) { if (typeof define === "function" && define.amd) { define(["jquery"], factory); } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) { var jQuery; try { jQuery = require("jquery"); } catch (err) { jQuery = null; } module.exports = factory(jQuery); } else if (window) { window.Slider = factory(window.jQuery); } })(function ($) { // Constants var NAMESPACE_MAIN = 'slider'; var NAMESPACE_ALTERNATE = 'bootstrapSlider'; // Polyfill console methods if (!window.console) { window.console = {}; } if (!window.console.log) { window.console.log = function () {}; } if (!window.console.warn) { window.console.warn = function () {}; } // Reference to Slider constructor var Slider; (function ($) { 'use strict'; // -------------------------- utils -------------------------- // var slice = Array.prototype.slice; function noop() {} // -------------------------- definition -------------------------- // function defineBridget($) { // bail if no jQuery if (!$) { return; } // -------------------------- addOptionMethod -------------------------- // /** * adds option method -> $().plugin('option', {...}) * @param {Function} PluginClass - constructor class */ function addOptionMethod(PluginClass) { // don't overwrite original option method if (PluginClass.prototype.option) { return; } // option setter PluginClass.prototype.option = function (opts) { // bail out if not an object if (!$.isPlainObject(opts)) { return; } this.options = $.extend(true, this.options, opts); }; } // -------------------------- plugin bridge -------------------------- // // helper function for logging errors // $.error breaks jQuery chaining var logError = typeof console === 'undefined' ? noop : function (message) { console.error(message); }; /** * jQuery plugin bridge, access methods like $elem.plugin('method') * @param {String} namespace - plugin name * @param {Function} PluginClass - constructor class */ function bridge(namespace, PluginClass) { // add to jQuery fn namespace $.fn[namespace] = function (options) { if (typeof options === 'string') { // call plugin method when first argument is a string // get arguments for method var args = slice.call(arguments, 1); for (var i = 0, len = this.length; i < len; i++) { var elem = this[i]; var instance = $.data(elem, namespace); if (!instance) { logError("cannot call methods on " + namespace + " prior to initialization; " + "attempted to call '" + options + "'"); continue; } if (!$.isFunction(instance[options]) || options.charAt(0) === '_') { logError("no such method '" + options + "' for " + namespace + " instance"); continue; } // trigger method with arguments var returnValue = instance[options].apply(instance, args); // break look and return first value if provided if (returnValue !== undefined && returnValue !== instance) { return returnValue; } } // return this if no return value return this; } else { var objects = this.map(function () { var instance = $.data(this, namespace); if (instance) { // apply options & init instance.option(options); instance._init(); } else { // initialize new instance instance = new PluginClass(this, options); $.data(this, namespace, instance); } return $(this); }); if (!objects || objects.length > 1) { return objects; } else { return objects[0]; } } }; } // -------------------------- bridget -------------------------- // /** * converts a Prototypical class into a proper jQuery plugin * the class must have a ._init method * @param {String} namespace - plugin name, used in $().pluginName * @param {Function} PluginClass - constructor class */ $.bridget = function (namespace, PluginClass) { addOptionMethod(PluginClass); bridge(namespace, PluginClass); }; return $.bridget; } // get jquery from browser global defineBridget($); })($); /************************************************* BOOTSTRAP-SLIDER SOURCE CODE **************************************************/ (function ($) { var ErrorMsgs = { formatInvalidInputErrorMsg: function formatInvalidInputErrorMsg(input) { return "Invalid input value '" + input + "' passed in"; }, callingContextNotSliderInstance: "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method" }; var SliderScale = { linear: { toValue: function toValue(percentage) { var rawValue = percentage / 100 * (this.options.max - this.options.min); var shouldAdjustWithBase = true; if (this.options.ticks_positions.length > 0) { var minv, maxv, minp, maxp = 0; for (var i = 1; i < this.options.ticks_positions.length; i++) { if (percentage <= this.options.ticks_positions[i]) { minv = this.options.ticks[i - 1]; minp = this.options.ticks_positions[i - 1]; maxv = this.options.ticks[i]; maxp = this.options.ticks_positions[i]; break; } } var partialPercentage = (percentage - minp) / (maxp - minp); rawValue = minv + partialPercentage * (maxv - minv); shouldAdjustWithBase = false; } var adjustment = shouldAdjustWithBase ? this.options.min : 0; var value = adjustment + Math.round(rawValue / this.options.step) * this.options.step; if (value < this.options.min) { return this.options.min; } else if (value > this.options.max) { return this.options.max; } else { return value; } }, toPercentage: function toPercentage(value) { if (this.options.max === this.options.min) { return 0; } if (this.options.ticks_positions.length > 0) { var minv, maxv, minp, maxp = 0; for (var i = 0; i < this.options.ticks.length; i++) { if (value <= this.options.ticks[i]) { minv = i > 0 ? this.options.ticks[i - 1] : 0; minp = i > 0 ? this.options.ticks_positions[i - 1] : 0; maxv = this.options.ticks[i]; maxp = this.options.ticks_positions[i]; break; } } if (i > 0) { var partialPercentage = (value - minv) / (maxv - minv); return minp + partialPercentage * (maxp - minp); } } return 100 * (value - this.options.min) / (this.options.max - this.options.min); } }, logarithmic: { /* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */ toValue: function toValue(percentage) { var min = this.options.min === 0 ? 0 : Math.log(this.options.min); var max = Math.log(this.options.max); var value = Math.exp(min + (max - min) * percentage / 100); value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step; /* Rounding to the nearest step could exceed the min or * max, so clip to those values. */ if (value < this.options.min) { return this.options.min; } else if (value > this.options.max) { return this.options.max; } else { return value; } }, toPercentage: function toPercentage(value) { if (this.options.max === this.options.min) { return 0; } else { var max = Math.log(this.options.max); var min = this.options.min === 0 ? 0 : Math.log(this.options.min); var v = value === 0 ? 0 : Math.log(value); return 100 * (v - min) / (max - min); } } } }; /************************************************* CONSTRUCTOR **************************************************/ Slider = function (element, options) { createNewSlider.call(this, element, options); return this; }; function createNewSlider(element, options) { /* The internal state object is used to store data about the current 'state' of slider. This includes values such as the `value`, `enabled`, etc... */ this._state = { value: null, enabled: null, offset: null, size: null, percentage: null, inDrag: false, over: false }; if (typeof element === "string") { this.element = document.querySelector(element); } else if (element instanceof HTMLElement) { this.element = element; } /************************************************* Process Options **************************************************/ options = options ? options : {}; var optionTypes = Object.keys(this.defaultOptions); for (var i = 0; i < optionTypes.length; i++) { var optName = optionTypes[i]; // First check if an option was passed in via the constructor var val = options[optName]; // If no data attrib, then check data atrributes val = typeof val !== 'undefined' ? val : getDataAttrib(this.element, optName); // Finally, if nothing was specified, use the defaults val = val !== null ? val : this.defaultOptions[optName]; // Set all options on the instance of the Slider if (!this.options) { this.options = {}; } this.options[optName] = val; } /* Validate `tooltip_position` against 'orientation` - if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation` -- default for "vertical" -> "right" -- default for "horizontal" -> "left" */ if (this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) { this.options.tooltip_position = "right"; } else if (this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) { this.options.tooltip_position = "top"; } function getDataAttrib(element, optName) { var dataName = "data-slider-" + optName.replace(/_/g, '-'); var dataValString = element.getAttribute(dataName); try { return JSON.parse(dataValString); } catch (err) { return dataValString; } } /************************************************* Create Markup **************************************************/ var origWidth = this.element.style.width; var updateSlider = false; var parent = this.element.parentNode; var sliderTrackSelection; var sliderTrackLow, sliderTrackHigh; var sliderMinHandle; var sliderMaxHandle; if (this.sliderElem) { updateSlider = true; } else { /* Create elements needed for slider */ this.sliderElem = document.createElement("div"); this.sliderElem.className = "slider"; /* Create slider track elements */ var sliderTrack = document.createElement("div"); sliderTrack.className = "slider-track"; sliderTrackLow = document.createElement("div"); sliderTrackLow.className = "slider-track-low"; sliderTrackSelection = document.createElement("div"); sliderTrackSelection.className = "slider-selection"; sliderTrackHigh = document.createElement("div"); sliderTrackHigh.className = "slider-track-high"; sliderMinHandle = document.createElement("div"); sliderMinHandle.className = "slider-handle min-slider-handle"; sliderMinHandle.setAttribute('role', 'slider'); sliderMinHandle.setAttribute('aria-valuemin', this.options.min); sliderMinHandle.setAttribute('aria-valuemax', this.options.max); sliderMaxHandle = document.createElement("div"); sliderMaxHandle.className = "slider-handle max-slider-handle"; sliderMaxHandle.setAttribute('role', 'slider'); sliderMaxHandle.setAttribute('aria-valuemin', this.options.min); sliderMaxHandle.setAttribute('aria-valuemax', this.options.max); sliderTrack.appendChild(sliderTrackLow); sliderTrack.appendChild(sliderTrackSelection); sliderTrack.appendChild(sliderTrackHigh); /* Add aria-labelledby to handle's */ var isLabelledbyArray = Array.isArray(this.options.labelledby); if (isLabelledbyArray && this.options.labelledby[0]) { sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby[0]); } if (isLabelledbyArray && this.options.labelledby[1]) { sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby[1]); } if (!isLabelledbyArray && this.options.labelledby) { sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby); sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby); } /* Create ticks */ this.ticks = []; if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { this.ticksContainer = document.createElement('div'); this.ticksContainer.className = 'slider-tick-container'; for (i = 0; i < this.options.ticks.length; i++) { var tick = document.createElement('div'); tick.className = 'slider-tick'; this.ticks.push(tick); this.ticksContainer.appendChild(tick); } sliderTrackSelection.className += " tick-slider-selection"; } this.tickLabels = []; if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) { this.tickLabelContainer = document.createElement('div'); this.tickLabelContainer.className = 'slider-tick-label-container'; for (i = 0; i < this.options.ticks_labels.length; i++) { var label = document.createElement('div'); var noTickPositionsSpecified = this.options.ticks_positions.length === 0; var tickLabelsIndex = this.options.reversed && noTickPositionsSpecified ? this.options.ticks_labels.length - (i + 1) : i; label.className = 'slider-tick-label'; label.innerHTML = this.options.ticks_labels[tickLabelsIndex]; this.tickLabels.push(label); this.tickLabelContainer.appendChild(label); } } var createAndAppendTooltipSubElements = function createAndAppendTooltipSubElements(tooltipElem) { var arrow = document.createElement("div"); arrow.className = "tooltip-arrow"; var inner = document.createElement("div"); inner.className = "tooltip-inner"; tooltipElem.appendChild(arrow); tooltipElem.appendChild(inner); }; /* Create tooltip elements */ var sliderTooltip = document.createElement("div"); sliderTooltip.className = "tooltip tooltip-main"; sliderTooltip.setAttribute('role', 'presentation'); createAndAppendTooltipSubElements(sliderTooltip); var sliderTooltipMin = document.createElement("div"); sliderTooltipMin.className = "tooltip tooltip-min"; sliderTooltipMin.setAttribute('role', 'presentation'); createAndAppendTooltipSubElements(sliderTooltipMin); var sliderTooltipMax = document.createElement("div"); sliderTooltipMax.className = "tooltip tooltip-max"; sliderTooltipMax.setAttribute('role', 'presentation'); createAndAppendTooltipSubElements(sliderTooltipMax); /* Append components to sliderElem */ this.sliderElem.appendChild(sliderTrack); this.sliderElem.appendChild(sliderTooltip); this.sliderElem.appendChild(sliderTooltipMin); this.sliderElem.appendChild(sliderTooltipMax); if (this.tickLabelContainer) { this.sliderElem.appendChild(this.tickLabelContainer); } if (this.ticksContainer) { this.sliderElem.appendChild(this.ticksContainer); } this.sliderElem.appendChild(sliderMinHandle); this.sliderElem.appendChild(sliderMaxHandle); /* Append slider element to parent container, right before the original <input> element */ parent.insertBefore(this.sliderElem, this.element); /* Hide original <input> element */ this.element.style.display = "none"; } /* If JQuery exists, cache JQ references */ if ($) { this.$element = $(this.element); this.$sliderElem = $(this.sliderElem); } /************************************************* Setup **************************************************/ this.eventToCallbackMap = {}; this.sliderElem.id = this.options.id; this.touchCapable = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch; this.touchX = 0; this.touchY = 0; this.tooltip = this.sliderElem.querySelector('.tooltip-main'); this.tooltipInner = this.tooltip.querySelector('.tooltip-inner'); this.tooltip_min = this.sliderElem.querySelector('.tooltip-min'); this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner'); this.tooltip_max = this.sliderElem.querySelector('.tooltip-max'); this.tooltipInner_max = this.tooltip_max.querySelector('.tooltip-inner'); if (SliderScale[this.options.scale]) { this.options.scale = SliderScale[this.options.scale]; } if (updateSlider === true) { // Reset classes this._removeClass(this.sliderElem, 'slider-horizontal'); this._removeClass(this.sliderElem, 'slider-vertical'); this._removeClass(this.tooltip, 'hide'); this._removeClass(this.tooltip_min, 'hide'); this._removeClass(this.tooltip_max, 'hide'); // Undo existing inline styles for track ["left", "top", "width", "height"].forEach(function (prop) { this._removeProperty(this.trackLow, prop); this._removeProperty(this.trackSelection, prop); this._removeProperty(this.trackHigh, prop); }, this); // Undo inline styles on handles [this.handle1, this.handle2].forEach(function (handle) { this._removeProperty(handle, 'left'); this._removeProperty(handle, 'top'); }, this); // Undo inline styles and classes on tooltips [this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function (tooltip) { this._removeProperty(tooltip, 'left'); this._removeProperty(tooltip, 'top'); this._removeProperty(tooltip, 'margin-left'); this._removeProperty(tooltip, 'margin-top'); this._removeClass(tooltip, 'right'); this._removeClass(tooltip, 'top'); }, this); } if (this.options.orientation === 'vertical') { this._addClass(this.sliderElem, 'slider-vertical'); this.stylePos = 'top'; this.mousePos = 'pageY'; this.sizePos = 'offsetHeight'; } else { this._addClass(this.sliderElem, 'slider-horizontal'); this.sliderElem.style.width = origWidth; this.options.orientation = 'horizontal'; this.stylePos = 'left'; this.mousePos = 'pageX'; this.sizePos = 'offsetWidth'; } this._setTooltipPosition(); /* In case ticks are specified, overwrite the min and max bounds */ if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { this.options.max = Math.max.apply(Math, this.options.ticks); this.options.min = Math.min.apply(Math, this.options.ticks); } if (Array.isArray(this.options.value)) { this.options.range = true; this._state.value = this.options.value; } else if (this.options.range) { // User wants a range, but value is not an array this._state.value = [this.options.value, this.options.max]; } else { this._state.value = this.options.value; } this.trackLow = sliderTrackLow || this.trackLow; this.trackSelection = sliderTrackSelection || this.trackSelection; this.trackHigh = sliderTrackHigh || this.trackHigh; if (this.options.selection === 'none') { this._addClass(this.trackLow, 'hide'); this._addClass(this.trackSelection, 'hide'); this._addClass(this.trackHigh, 'hide'); } this.handle1 = sliderMinHandle || this.handle1; this.handle2 = sliderMaxHandle || this.handle2; if (updateSlider === true) { // Reset classes this._removeClass(this.handle1, 'round triangle'); this._removeClass(this.handle2, 'round triangle hide'); for (i = 0; i < this.ticks.length; i++) { this._removeClass(this.ticks[i], 'round triangle hide'); } } var availableHandleModifiers = ['round', 'triangle', 'custom']; var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1; if (isValidHandleType) { this._addClass(this.handle1, this.options.handle); this._addClass(this.handle2, this.options.handle); for (i = 0; i < this.ticks.length; i++) { this._addClass(this.ticks[i], this.options.handle); } } this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; this.setValue(this._state.value); /****************************************** Bind Event Listeners ******************************************/ // Bind keyboard handlers this.handle1Keydown = this._keydown.bind(this, 0); this.handle1.addEventListener("keydown", this.handle1Keydown, false); this.handle2Keydown = this._keydown.bind(this, 1); this.handle2.addEventListener("keydown", this.handle2Keydown, false); this.mousedown = this._mousedown.bind(this); this.touchstart = this._touchstart.bind(this); this.touchmove = this._touchmove.bind(this); if (this.touchCapable) { // Bind touch handlers this.sliderElem.addEventListener("touchstart", this.touchstart, false); this.sliderElem.addEventListener("touchmove", this.touchmove, false); } this.sliderElem.addEventListener("mousedown", this.mousedown, false); // Bind window handlers this.resize = this._resize.bind(this); window.addEventListener("resize", this.resize, false); // Bind tooltip-related handlers if (this.options.tooltip === 'hide') { this._addClass(this.tooltip, 'hide'); this._addClass(this.tooltip_min, 'hide'); this._addClass(this.tooltip_max, 'hide'); } else if (this.options.tooltip === 'always') { this._showTooltip(); this._alwaysShowTooltip = true; } else { this.showTooltip = this._showTooltip.bind(this); this.hideTooltip = this._hideTooltip.bind(this); this.sliderElem.addEventListener("mouseenter", this.showTooltip, false); this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false); this.handle1.addEventListener("focus", this.showTooltip, false); this.handle1.addEventListener("blur", this.hideTooltip, false); this.handle2.addEventListener("focus", this.showTooltip, false); this.handle2.addEventListener("blur", this.hideTooltip, false); } if (this.options.enabled) { this.enable(); } else { this.disable(); } } /************************************************* INSTANCE PROPERTIES/METHODS - Any methods bound to the prototype are considered part of the plugin's `public` interface **************************************************/ Slider.prototype = { _init: function _init() {}, // NOTE: Must exist to support bridget constructor: Slider, defaultOptions: { id: "", min: 0, max: 10, step: 1, precision: 0, orientation: 'horizontal', value: 5, range: false, selection: 'before', tooltip: 'show', tooltip_split: false, handle: 'round', reversed: false, enabled: true, formatter: function formatter(val) { if (Array.isArray(val)) { return val[0] + " : " + val[1]; } else { return val; } }, natural_arrow_keys: false, ticks: [], ticks_positions: [], ticks_labels: [], ticks_snap_bounds: 0, scale: 'linear', focus: false, tooltip_position: null, labelledby: null }, getElement: function getElement() { return this.sliderElem; }, getValue: function getValue() { if (this.options.range) { return this._state.value; } else { return this._state.value[0]; } }, setValue: function setValue(val, triggerSlideEvent, triggerChangeEvent) { if (!val) { val = 0; } var oldValue = this.getValue(); this._state.value = this._validateInputValue(val); var applyPrecision = this._applyPrecision.bind(this); if (this.options.range) { this._state.value[0] = applyPrecision(this._state.value[0]); this._state.value[1] = applyPrecision(this._state.value[1]); this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0])); this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1])); } else { this._state.value = applyPrecision(this._state.value); this._state.value = [Math.max(this.options.min, Math.min(this.options.max, this._state.value))]; this._addClass(this.handle2, 'hide'); if (this.options.selection === 'after') { this._state.value[1] = this.options.max; } else { this._state.value[1] = this.options.min; } } if (this.options.max > this.options.min) { this._state.percentage = [this._toPercentage(this._state.value[0]), this._toPercentage(this._state.value[1]), this.options.step * 100 / (this.options.max - this.options.min)]; } else { this._state.percentage = [0, 0, 100]; } this._layout(); var newValue = this.options.range ? this._state.value : this._state.value[0]; this._setDataVal(newValue); if (triggerSlideEvent === true) { this._trigger('slide', newValue); } if (oldValue !== newValue && triggerChangeEvent === true) { this._trigger('change', { oldValue: oldValue, newValue: newValue }); } return this; }, destroy: function destroy() { // Remove event handlers on slider elements this._removeSliderEventHandlers(); // Remove the slider from the DOM this.sliderElem.parentNode.removeChild(this.sliderElem); /* Show original <input> element */ this.element.style.display = ""; // Clear out custom event bindings this._cleanUpEventCallbacksMap(); // Remove data values this.element.removeAttribute("data"); // Remove JQuery handlers/data if ($) { this._unbindJQueryEventHandlers(); this.$element.removeData('slider'); } }, disable: function disable() { this._state.enabled = false; this.handle1.removeAttribute("tabindex"); this.handle2.removeAttribute("tabindex"); this._addClass(this.sliderElem, 'slider-disabled'); this._trigger('slideDisabled'); return this; }, enable: function enable() { this._state.enabled = true; this.handle1.setAttribute("tabindex", 0); this.handle2.setAttribute("tabindex", 0); this._removeClass(this.sliderElem, 'slider-disabled'); this._trigger('slideEnabled'); return this; }, toggle: function toggle() { if (this._state.enabled) { this.disable(); } else { this.enable(); } return this; }, isEnabled: function isEnabled() { return this._state.enabled; }, on: function on(evt, callback) { this._bindNonQueryEventHandler(evt, callback); return this; }, off: function off(evt, callback) { if ($) { this.$element.off(evt, callback); this.$sliderElem.off(evt, callback); } else { this._unbindNonQueryEventHandler(evt, callback); } }, getAttribute: function getAttribute(attribute) { if (attribute) { return this.options[attribute]; } else { return this.options; } }, setAttribute: function setAttribute(attribute, value) { this.options[attribute] = value; return this; }, refresh: function refresh() { this._removeSliderEventHandlers(); createNewSlider.call(this, this.element, this.options); if ($) { // Bind new instance of slider to the element $.data(this.element, 'slider', this); } return this; }, relayout: function relayout() { this._resize(); this._layout(); return this; }, /******************************+ HELPERS - Any method that is not part of the public interface. - Place it underneath this comment block and write its signature like so: _fnName : function() {...} ********************************/ _removeSliderEventHandlers: function _removeSliderEventHandlers() { // Remove keydown event listeners this.handle1.removeEventListener("keydown", this.handle1Keydown, false); this.handle2.removeEventListener("keydown", this.handle2Keydown, false); if (this.showTooltip) { this.handle1.removeEventListener("focus", this.showTooltip, false); this.handle2.removeEventListener("focus", this.showTooltip, false); } if (this.hideTooltip) { this.handle1.removeEventListener("blur", this.hideTooltip, false); this.handle2.removeEventListener("blur", this.hideTooltip, false); } // Remove event listeners from sliderElem if (this.showTooltip) { this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false); } if (this.hideTooltip) { this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false); } this.sliderElem.removeEventListener("touchstart", this.touchstart, false); this.sliderElem.removeEventListener("touchmove", this.touchmove, false); this.sliderElem.removeEventListener("mousedown", this.mousedown, false); // Remove window event listener window.removeEventListener("resize", this.resize, false); }, _bindNonQueryEventHandler: function _bindNonQueryEventHandler(evt, callback) { if (this.eventToCallbackMap[evt] === undefined) { this.eventToCallbackMap[evt] = []; } this.eventToCallbackMap[evt].push(callback); }, _unbindNonQueryEventHandler: function _unbindNonQueryEventHandler(evt, callback) { var callbacks = this.eventToCallbackMap[evt]; if (callbacks !== undefined) { for (var i = 0; i < callbacks.length; i++) { if (callbacks[i] === callback) { callbacks.splice(i, 1); break; } } } }, _cleanUpEventCallbacksMap: function _cleanUpEventCallbacksMap() { var eventNames = Object.keys(this.eventToCallbackMap); for (var i = 0; i < eventNames.length; i++) { var eventName = eventNames[i]; this.eventToCallbackMap[eventName] = null; } }, _showTooltip: function _showTooltip() { if (this.options.tooltip_split === false) { this._addClass(this.tooltip, 'in'); this.tooltip_min.style.display = 'none'; this.tooltip_max.style.display = 'none'; } else { this._addClass(this.tooltip_min, 'in'); this._addClass(this.tooltip_max, 'in'); this.tooltip.style.display = 'none'; } this._state.over = true; }, _hideTooltip: function _hideTooltip() { if (this._state.inDrag === false && this.alwaysShowTooltip !== true) { this._removeClass(this.tooltip, 'in'); this._removeClass(this.tooltip_min, 'in'); this._removeClass(this.tooltip_max, 'in'); } this._state.over = false; }, _layout: function _layout() { var positionPercentages; if (this.options.reversed) { positionPercentages = [100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]]; } else { positionPercentages = [this._state.percentage[0], this._state.percentage[1]]; } this.handle1.style[this.stylePos] = positionPercentages[0] + '%'; this.handle1.setAttribute('aria-valuenow', this._state.value[0]); this.handle2.style[this.stylePos] = positionPercentages[1] + '%'; this.handle2.setAttribute('aria-valuenow', this._state.value[1]); /* Position ticks and labels */ if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) { var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width'; var styleMargin = this.options.orientation === 'vertical' ? 'marginTop' : 'marginLeft'; var labelSize = this._state.size / (this.options.ticks.length - 1); if (this.tickLabelContainer) { var extraMargin = 0; if (this.options.ticks_positions.length === 0) { if (this.options.orientation !== 'vertical') { this.tickLabelContainer.style[styleMargin] = -labelSize / 2 + 'px'; } extraMargin = this.tickLabelContainer.offsetHeight; } else { /* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */ for (i = 0; i < this.tickLabelContainer.childNodes.length; i++) { if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) { extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight; } } } if (this.options.orientation === 'horizontal') { this.sliderElem.style.marginBottom = extraMargin + 'px'; } } for (var i = 0; i < this.options.ticks.length; i++) { var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]); if (this.options.reversed) { percentage = 100 - percentage; } this.ticks[i].style[this.stylePos] = percentage + '%'; /* Set class labels to denote whether ticks are in the selection */ this._removeClass(this.ticks[i], 'in-selection'); if (!this.options.range) { if (this.options.selection === 'after' && percentage >= positionPercentages[0]) { this._addClass(this.ticks[i], 'in-selection'); } else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) { this._addClass(this.ticks[i], 'in-selection'); } } else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) { this._addClass(this.ticks[i], 'in-selection'); } if (this.tickLabels[i]) { this.tickLabels[i].style[styleSize] = labelSize + 'px'; if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) { this.tickLabels[i].style.position = 'absolute'; this.tickLabels[i].style[this.stylePos] = percentage + '%'; this.tickLabels[i].style[styleMargin] = -labelSize / 2 + 'px'; } else if (this.options.orientation === 'vertical') { this.tickLabels[i].style['marginLeft'] = this.sliderElem.offsetWidth + 'px'; this.tickLabelContainer.style['marginTop'] = this.sliderElem.offsetWidth / 2 * -1 + 'px'; } } } } var formattedTooltipVal; if (this.options.range) { formattedTooltipVal = this.options.formatter(this._state.value); this._setText(this.tooltipInner, formattedTooltipVal); this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0]) / 2 + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } var innerTooltipMinText = this.options.formatter(this._state.value[0]); this._setText(this.tooltipInner_min, innerTooltipMinText); var innerTooltipMaxText = this.options.formatter(this._state.value[1]); this._setText(this.tooltipInner_max, innerTooltipMaxText); this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px'); } this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px'); } } else { formattedTooltipVal = this.options.formatter(this._state.value[0]); this._setText(this.tooltipInner, formattedTooltipVal); this.tooltip.style[this.stylePos] = positionPercentages[0] + '%'; if (this.options.orientation === 'vertical') { this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px'); } else { this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px'); } } if (this.options.orientation === 'vertical') { this.trackLow.style.top = '0'; this.trackLow.style.height = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; this.trackHigh.style.bottom = '0'; this.trackHigh.style.height = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; } else { this.trackLow.style.left = '0'; this.trackLow.style.width = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) + '%'; this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; this.trackHigh.style.right = '0'; this.trackHigh.style.width = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%'; var offset_min = this.tooltip_min.getBoundingClientRect(); var offset_max = this.tooltip_max.getBoundingClientRect(); if (this.options.tooltip_position === 'bottom') { if (offset_min.right > offset_max.left) { this._removeClass(this.tooltip_max, 'bottom'); this._addClass(this.tooltip_max, 'top'); this.tooltip_max.style.top = ''; this.tooltip_max.style.bottom = 22 + 'px'; } else { this._removeClass(this.tooltip_max, 'top'); this._addClass(this.tooltip_max, 'bottom'); this.tooltip_max.style.top = this.tooltip_min.style.top; this.tooltip_max.style.bottom = ''; } } else { if (offset_min.right > offset_max.left) { this._removeClass(this.tooltip_max, 'top'); this._addClass(this.tooltip_max, 'bottom'); this.tooltip_max.style.top = 18 + 'px'; } else { this._removeClass(this.tooltip_max, 'bottom'); this._addClass(this.tooltip_max, 'top'); this.tooltip_max.style.top = this.tooltip_min.style.top; } } } }, _resize: function _resize(ev) { /*jshint unused:false*/ this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; this._layout(); }, _removeProperty: function _removeProperty(element, prop) { if (element.style.removeProperty) { element.style.removeProperty(prop); } else { element.style.removeAttribute(prop); } }, _mousedown: function _mousedown(ev) { if (!this._state.enabled) { return false; } this._state.offset = this._offset(this.sliderElem); this._state.size = this.sliderElem[this.sizePos]; var percentage = this._getPercentage(ev); if (this.options.range) { var diff1 = Math.abs(this._state.percentage[0] - percentage); var diff2 = Math.abs(this._state.percentage[1] - percentage); this._state.dragged = diff1 < diff2 ? 0 : 1; this._adjustPercentageForRangeSliders(percentage); } else { this._state.dragged = 0; } this._state.percentage[this._state.dragged] = percentage; this._layout(); if (this.touchCapable) { document.removeEventListener("touchmove", this.mousemove, false); document.removeEventListener("touchend", this.mouseup, false); } if (this.mousemove) { document.removeEventListener("mousemove", this.mousemove, false); } if (this.mouseup) { document.removeEventListener("mouseup", this.mouseup, false); } this.mousemove = this._mousemove.bind(this); this.mouseup = this._mouseup.bind(this); if (this.touchCapable) { // Touch: Bind touch events: document.addEventListener("touchmove", this.mousemove, false); document.addEventListener("touchend", this.mouseup, false); } // Bind mouse events: document.addEventListener("mousemove", this.mousemove, false); document.addEventListener("mouseup", this.mouseup, false); this._state.inDrag = true; var newValue = this._calculateValue(); this._trigger('slideStart', newValue); this._setDataVal(newValue); this.setValue(newValue, false, true); this._pauseEvent(ev); if (this.options.focus) { this._triggerFocusOnHandle(this._state.dragged); } return true; }, _touchstart: function _touchstart(ev) { if (ev.changedTouches === undefined) { this._mousedown(ev); return; } var touch = ev.changedTouches[0]; this.touchX = touch.pageX; this.touchY = touch.pageY; }, _triggerFocusOnHandle: function _triggerFocusOnHandle(handleIdx) { if (handleIdx === 0) { this.handle1.focus(); } if (handleIdx === 1) { this.handle2.focus(); } }, _keydown: function _keydown(handleIdx, ev) { if (!this._state.enabled) { return false; } var dir; switch (ev.keyCode) { case 37: // left case 40: // down dir = -1; break; case 39: // right case 38: // up dir = 1; break; } if (!dir) { return; } // use natural arrow keys instead of from min to max if (this.options.natural_arrow_keys) { var ifVerticalAndNotReversed = this.options.orientation === 'vertical' && !this.options.reversed; var ifHorizontalAndReversed = this.options.orientation === 'horizontal' && this.options.reversed; if (ifVerticalAndNotReversed || ifHorizontalAndReversed) { dir = -dir; } } var val = this._state.value[handleIdx] + dir * this.options.step; if (this.options.range) { val = [!handleIdx ? val : this._state.value[0], handleIdx ? val : this._state.value[1]]; } this._trigger('slideStart', val); this._setDataVal(val); this.setValue(val, true, true); this._setDataVal(val); this._trigger('slideStop', val); this._layout(); this._pauseEvent(ev); return false; }, _pauseEvent: function _pauseEvent(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } if (ev.preventDefault) { ev.preventDefault(); } ev.cancelBubble = true; ev.returnValue = false; }, _mousemove: function _mousemove(ev) { if (!this._state.enabled) { return false; } var percentage = this._getPercentage(ev); this._adjustPercentageForRangeSliders(percentage); this._state.percentage[this._state.dragged] = percentage; this._layout(); var val = this._calculateValue(true); this.setValue(val, true, true); return false; }, _touchmove: function _touchmove(ev) { if (ev.changedTouches === undefined) { return; } var touch = ev.changedTouches[0]; var xDiff = touch.pageX - this.touchX; var yDiff = touch.pageY - this.touchY; if (!this._state.inDrag) { // Vertical Slider if (this.options.orientation === 'vertical' && xDiff <= 5 && xDiff >= -5 && (yDiff >= 15 || yDiff <= -15)) { this._mousedown(ev); } // Horizontal slider. else if (yDiff <= 5 && yDiff >= -5 && (xDiff >= 15 || xDiff <= -15)) { this._mousedown(ev); } } }, _adjustPercentageForRangeSliders: function _adjustPercentageForRangeSliders(percentage) { if (this.options.range) { var precision = this._getNumDigitsAfterDecimalPlace(percentage); precision = precision ? precision - 1 : 0; var percentageWithAdjustedPrecision = this._applyToFixedAndParseFloat(percentage, precision); if (this._state.dragged === 0 && this._applyToFixedAndParseFloat(this._state.percentage[1], precision) < percentageWithAdjustedPrecision) { this._state.percentage[0] = this._state.percentage[1]; this._state.dragged = 1; } else if (this._state.dragged === 1 && this._applyToFixedAndParseFloat(this._state.percentage[0], precision) > percentageWithAdjustedPrecision) { this._state.percentage[1] = this._state.percentage[0]; this._state.dragged = 0; } } }, _mouseup: function _mouseup() { if (!this._state.enabled) { return false; } if (this.touchCapable) { // Touch: Unbind touch event handlers: document.removeEventListener("touchmove", this.mousemove, false); document.removeEventListener("touchend", this.mouseup, false); } // Unbind mouse event handlers: document.removeEventListener("mousemove", this.mousemove, false); document.removeEventListener("mouseup", this.mouseup, false); this._state.inDrag = false; if (this._state.over === false) { this._hideTooltip(); } var val = this._calculateValue(true); this._layout(); this._setDataVal(val); this._trigger('slideStop', val); return false; }, _calculateValue: function _calculateValue(snapToClosestTick) { var val; if (this.options.range) { val = [this.options.min, this.options.max]; if (this._state.percentage[0] !== 0) { val[0] = this._toValue(this._state.percentage[0]); val[0] = this._applyPrecision(val[0]); } if (this._state.percentage[1] !== 100) { val[1] = this._toValue(this._state.percentage[1]); val[1] = this._applyPrecision(val[1]); } } else { val = this._toValue(this._state.percentage[0]); val = parseFloat(val); val = this._applyPrecision(val); } if (snapToClosestTick) { var min = [val, Infinity]; for (var i = 0; i < this.options.ticks.length; i++) { var diff = Math.abs(this.options.ticks[i] - val); if (diff <= min[1]) { min = [this.options.ticks[i], diff]; } } if (min[1] <= this.options.ticks_snap_bounds) { return min[0]; } } return val; }, _applyPrecision: function _applyPrecision(val) { var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step); return this._applyToFixedAndParseFloat(val, precision); }, _getNumDigitsAfterDecimalPlace: function _getNumDigitsAfterDecimalPlace(num) { var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); if (!match) { return 0; } return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)); }, _applyToFixedAndParseFloat: function _applyToFixedAndParseFloat(num, toFixedInput) { var truncatedNum = num.toFixed(toFixedInput); return parseFloat(truncatedNum); }, /* Credits to Mike Samuel for the following method! Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number */ _getPercentage: function _getPercentage(ev) { if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) { ev = ev.touches[0]; } var eventPosition = ev[this.mousePos]; var sliderOffset = this._state.offset[this.stylePos]; var distanceToSlide = eventPosition - sliderOffset; // Calculate what percent of the length the slider handle has slid var percentage = distanceToSlide / this._state.size * 100; percentage = Math.round(percentage / this._state.percentage[2]) * this._state.percentage[2]; if (this.options.reversed) { percentage = 100 - percentage; } // Make sure the percent is within the bounds of the slider. // 0% corresponds to the 'min' value of the slide // 100% corresponds to the 'max' value of the slide return Math.max(0, Math.min(100, percentage)); }, _validateInputValue: function _validateInputValue(val) { if (typeof val === 'number') { return val; } else if (Array.isArray(val)) { this._validateArray(val); return val; } else { throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(val)); } }, _validateArray: function _validateArray(val) { for (var i = 0; i < val.length; i++) { var input = val[i]; if (typeof input !== 'number') { throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(input)); } } }, _setDataVal: function _setDataVal(val) { this.element.setAttribute('data-value', val); this.element.setAttribute('value', val); this.element.value = val; }, _trigger: function _trigger(evt, val) { val = val || val === 0 ? val : undefined; var callbackFnArray = this.eventToCallbackMap[evt]; if (callbackFnArray && callbackFnArray.length) { for (var i = 0; i < callbackFnArray.length; i++) { var callbackFn = callbackFnArray[i]; callbackFn(val); } } /* If JQuery exists, trigger JQuery events */ if ($) { this._triggerJQueryEvent(evt, val); } }, _triggerJQueryEvent: function _triggerJQueryEvent(evt, val) { var eventData = { type: evt, value: val }; this.$element.trigger(eventData); this.$sliderElem.trigger(eventData); }, _unbindJQueryEventHandlers: function _unbindJQueryEventHandlers() { this.$element.off(); this.$sliderElem.off(); }, _setText: function _setText(element, text) { if (typeof element.textContent !== "undefined") { element.textContent = text; } else if (typeof element.innerText !== "undefined") { element.innerText = text; } }, _removeClass: function _removeClass(element, classString) { var classes = classString.split(" "); var newClasses = element.className; for (var i = 0; i < classes.length; i++) { var classTag = classes[i]; var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)"); newClasses = newClasses.replace(regex, " "); } element.className = newClasses.trim(); }, _addClass: function _addClass(element, classString) { var classes = classString.split(" "); var newClasses = element.className; for (var i = 0; i < classes.length; i++) { var classTag = classes[i]; var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)"); var ifClassExists = regex.test(newClasses); if (!ifClassExists) { newClasses += " " + classTag; } } element.className = newClasses.trim(); }, _offsetLeft: function _offsetLeft(obj) { return obj.getBoundingClientRect().left; }, _offsetTop: function _offsetTop(obj) { var offsetTop = obj.offsetTop; while ((obj = obj.offsetParent) && !isNaN(obj.offsetTop)) { offsetTop += obj.offsetTop; if (obj.tagName !== 'BODY') { offsetTop -= obj.scrollTop; } } return offsetTop; }, _offset: function _offset(obj) { return { left: this._offsetLeft(obj), top: this._offsetTop(obj) }; }, _css: function _css(elementRef, styleName, value) { if ($) { $.style(elementRef, styleName, value); } else { var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) { return letter.toUpperCase(); }); elementRef.style[style] = value; } }, _toValue: function _toValue(percentage) { return this.options.scale.toValue.apply(this, [percentage]); }, _toPercentage: function _toPercentage(value) { return this.options.scale.toPercentage.apply(this, [value]); }, _setTooltipPosition: function _setTooltipPosition() { var tooltips = [this.tooltip, this.tooltip_min, this.tooltip_max]; if (this.options.orientation === 'vertical') { var tooltipPos = this.options.tooltip_position || 'right'; var oppositeSide = tooltipPos === 'left' ? 'right' : 'left'; tooltips.forEach((function (tooltip) { this._addClass(tooltip, tooltipPos); tooltip.style[oppositeSide] = '100%'; }).bind(this)); } else if (this.options.tooltip_position === 'bottom') { tooltips.forEach((function (tooltip) { this._addClass(tooltip, 'bottom'); tooltip.style.top = 22 + 'px'; }).bind(this)); } else { tooltips.forEach((function (tooltip) { this._addClass(tooltip, 'top'); tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px'; }).bind(this)); } } }; /********************************* Attach to global namespace *********************************/ if ($) { (function () { var autoRegisterNamespace = undefined; if (!$.fn.slider) { $.bridget(NAMESPACE_MAIN, Slider); autoRegisterNamespace = NAMESPACE_MAIN; } else { window.console.warn("bootstrap-slider.js - WARNING: $.fn.slider namespace is already bound. Use the $.fn.bootstrapSlider namespace instead."); autoRegisterNamespace = NAMESPACE_ALTERNATE; } $.bridget(NAMESPACE_ALTERNATE, Slider); // Auto-Register data-provide="slider" Elements $(function () { $("input[data-provide=slider]")[autoRegisterNamespace](); }); })(); } })($); return Slider; });
/*! * froala_editor v2.7.6 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2018 Froala Labs */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === 'object' && module.exports) { // Node/CommonJS module.exports = function( root, jQuery ) { if ( jQuery === undefined ) { // require('jQuery') returns a factory that requires window to // build a jQuery instance, we normalize how we use modules // that require this pattern but the window provided is a noop // if it's defined (how jquery works) if ( typeof window !== 'undefined' ) { jQuery = require('jquery'); } else { jQuery = require('jquery')(root); } } return factory(jQuery); }; } else { // Browser globals factory(window.jQuery); } }(function ($) { /** * Korean */ $.FE.LANGUAGE['ko'] = { translation: { // Place holder "Type something": "\ub0b4\uc6a9\uc744 \uc785\ub825\ud558\uc138\uc694", // Basic formatting "Bold": "\uad75\uac8c", "Italic": "\uae30\uc6b8\uc784\uaf34", "Underline": "\ubc11\uc904", "Strikethrough": "\ucde8\uc18c\uc120", // Main buttons "Insert": "\uc0bd\uc785", "Delete": "\uc0ad\uc81c", "Cancel": "\ucde8\uc18c", "OK": "\uc2b9\uc778", "Back": "\ub4a4\ub85c", "Remove": "\uc81c\uac70", "More": "\ub354", "Update": "\uc5c5\ub370\uc774\ud2b8", "Style": "\uc2a4\ud0c0\uc77c", // Font "Font Family": "\uae00\uaf34", "Font Size": "\ud3f0\ud2b8 \ud06c\uae30", // Colors "Colors": "\uc0c9\uc0c1", "Background": "\ubc30\uacbd", "Text": "\ud14d\uc2a4\ud2b8", "HEX Color": "\ud5e5\uc2a4 \uc0c9\uc0c1", // Paragraphs "Paragraph Format": "\ub2e8\ub77d", "Normal": "\ud45c\uc900", "Code": "\ucf54\ub4dc", "Heading 1": "\uc81c\ubaa9 1", "Heading 2": "\uc81c\ubaa9 2", "Heading 3": "\uc81c\ubaa9 3", "Heading 4": "\uc81c\ubaa9 4", // Style "Paragraph Style": "\ub2e8\ub77d \uc2a4\ud0c0\uc77c", "Inline Style": "\uc778\ub77c\uc778 \uc2a4\ud0c0\uc77c", // Alignment "Align": "\uc815\ub82c", "Align Left": "\uc67c\ucabd\uc815\ub82c", "Align Center": "\uac00\uc6b4\ub370\uc815\ub82c", "Align Right": "\uc624\ub978\ucabd\uc815\ub82c", "Align Justify": "\uc591\ucabd\uc815\ub82c", "None": "\uc5c6\uc74c", // Lists "Ordered List": "\uc22b\uc790\ub9ac\uc2a4\ud2b8", "Unordered List": "\uc810 \ub9ac\uc2a4\ud2b8", // Indent "Decrease Indent": "\ub0b4\uc5b4\uc4f0\uae30", "Increase Indent": "\ub4e4\uc5ec\uc4f0\uae30", // Links "Insert Link": "\ub9c1\ud06c \uc0bd\uc785", "Open in new tab": "\uc0c8 \ud0ed\uc5d0\uc11c \uc5f4\uae30", "Open Link": "\ub9c1\ud06c \uc5f4\uae30", "Edit Link": "\ud3b8\uc9d1 \ub9c1\ud06c", "Unlink": "\ub9c1\ud06c\uc0ad\uc81c", "Choose Link": "\ub9c1\ud06c\ub97c \uc120\ud0dd", // Images "Insert Image": "\uc774\ubbf8\uc9c0 \uc0bd\uc785", "Upload Image": "\uc774\ubbf8\uc9c0 \uc5c5\ub85c\ub4dc", "By URL": "URL \ub85c", "Browse": "\uac80\uc0c9", "Drop image": "\uc774\ubbf8\uc9c0\ub97c \ub4dc\ub798\uadf8&\ub4dc\ub86d", "or click": "\ub610\ub294 \ud074\ub9ad", "Manage Images": "\uc774\ubbf8\uc9c0 \uad00\ub9ac", "Loading": "\ub85c\ub4dc", "Deleting": "\uc0ad\uc81c", "Tags": "\ud0dc\uadf8", "Are you sure? Image will be deleted.": "\ud655\uc2e4\ud55c\uac00\uc694? \uc774\ubbf8\uc9c0\uac00 \uc0ad\uc81c\ub429\ub2c8\ub2e4.", "Replace": "\uad50\uccb4", "Uploading": "\uc5c5\ub85c\ub4dc", "Loading image": "\uc774\ubbf8\uc9c0 \ub85c\ub4dc \uc911", "Display": "\ub514\uc2a4\ud50c\ub808\uc774", "Inline": "\uc778\ub77c\uc778", "Break Text": "\uad6c\ubd84 \ud14d\uc2a4\ud2b8", "Alternate Text": "\ub300\uccb4 \ud14d\uc2a4\ud2b8", "Change Size": "\ud06c\uae30 \ubcc0\uacbd", "Width": "\ud3ed", "Height": "\ub192\uc774", "Something went wrong. Please try again.": "\ubb38\uc81c\uac00 \ubc1c\uc0dd\ud588\uc2b5\ub2c8\ub2e4. \ub2e4\uc2dc \uc2dc\ub3c4\ud558\uc2ed\uc2dc\uc624.", "Image Caption": "\uc774\ubbf8\uc9c0 \ucea1\uc158", "Advanced Edit": "\uace0\uae09 \ud3b8\uc9d1", // Video "Insert Video": "\ub3d9\uc601\uc0c1 \uc0bd\uc785", "Embedded Code": "\uc784\ubca0\ub514\ub4dc \ucf54\ub4dc", "Paste in a video URL": "\ub3d9\uc601\uc0c1 URL\uc5d0 \ubd99\uc5ec \ub123\uae30", "Drop video": "\ub3d9\uc601\uc0c1\uc744 \ub4dc\ub798\uadf8&\ub4dc\ub86d", "Your browser does not support HTML5 video.": "\uadc0\ud558\uc758 \ube0c\ub77c\uc6b0\uc800\ub294 html5 video\ub97c \uc9c0\uc6d0\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.", "Upload Video": "\ub3d9\uc601\uc0c1 \uc5c5\ub85c\ub4dc", // Tables "Insert Table": "\ud45c \uc0bd\uc785", "Table Header": "\ud45c \ud5e4\ub354", "Remove Table": "\ud45c \uc81c\uac70", "Table Style": "\ud45c \uc2a4\ud0c0\uc77c", "Horizontal Align": "\uc218\ud3c9 \uc815\ub82c", "Row": "\ud589", "Insert row above": "\uc55e\uc5d0 \ud589\uc744 \uc0bd\uc785", "Insert row below": "\ub4a4\uc5d0 \ud589\uc744 \uc0bd\uc785", "Delete row": "\ud589 \uc0ad\uc81c", "Column": "\uc5f4", "Insert column before": "\uc55e\uc5d0 \uc5f4\uc744 \uc0bd\uc785", "Insert column after": "\ub4a4\uc5d0 \uc5f4\uc744 \uc0bd\uc785", "Delete column": "\uc5f4 \uc0ad\uc81c", "Cell": "\uc140", "Merge cells": "\uc140 \ud569\uce58\uae30", "Horizontal split": "\uc218\ud3c9 \ubd84\ud560", "Vertical split": "\uc218\uc9c1 \ubd84\ud560", "Cell Background": "\uc140 \ubc30\uacbd", "Vertical Align": "\uc218\uc9c1 \uc815\ub82c", "Top": "\uc704\ucabd \uc815\ub82c", "Middle": "\uac00\uc6b4\ub370 \uc815\ub82c", "Bottom": "\uc544\ub798\ucabd \uc815\ub82c", "Align Top": "\uc704\ucabd\uc73c\ub85c \uc815\ub82c\ud569\ub2c8\ub2e4.", "Align Middle": "\uac00\uc6b4\ub370\ub85c \uc815\ub82c\ud569\ub2c8\ub2e4.", "Align Bottom": "\uc544\ub798\ucabd\uc73c\ub85c \uc815\ub82c\ud569\ub2c8\ub2e4.", "Cell Style": "\uc140 \uc2a4\ud0c0\uc77c", // Files "Upload File": "\ud30c\uc77c \ucca8\ubd80", "Drop file": "\ud30c\uc77c\uc744 \ub4dc\ub798\uadf8&\ub4dc\ub86d", // Emoticons "Emoticons": "\uc774\ubaa8\ud2f0\ucf58", "Grinning face": "\uc5bc\uad74 \uc6c3\uae30\ub9cc", "Grinning face with smiling eyes": "\ubbf8\uc18c\ub294 \ub208\uc744 \uac00\uc9c4 \uc5bc\uad74 \uc6c3\uae30\ub9cc", "Face with tears of joy": "\uae30\uc068\uc758 \ub208\ubb3c\ub85c \uc5bc\uad74", "Smiling face with open mouth": "\uc624\ud508 \uc785\uc73c\ub85c \uc6c3\ub294 \uc5bc\uad74", "Smiling face with open mouth and smiling eyes": "\uc624\ud508 \uc785\uc73c\ub85c \uc6c3\ub294 \uc5bc\uad74\uacfc \ub208\uc744 \ubbf8\uc18c", "Smiling face with open mouth and cold sweat": "\uc785\uc744 \uc5f4\uace0 \uc2dd\uc740 \ub540\uacfc \ud568\uaed8 \uc6c3\ub294 \uc5bc\uad74", "Smiling face with open mouth and tightly-closed eyes": "\uc624\ud508 \uc785\uacfc \ubc00\uc811\ud558\uac8c \ub2eb\ud78c \ub41c \ub208\uc744 \uac00\uc9c4 \uc6c3\ub294 \uc5bc\uad74", "Smiling face with halo": "\ud6c4\uad11 \uc6c3\ub294 \uc5bc\uad74", "Smiling face with horns": "\ubfd4 \uc6c3\ub294 \uc5bc\uad74", "Winking face": "\uc5bc\uad74 \uc719\ud06c", "Smiling face with smiling eyes": "\uc6c3\ub294 \ub208\uc73c\ub85c \uc6c3\ub294 \uc5bc\uad74", "Face savoring delicious food": "\ub9db\uc788\ub294 \uc74c\uc2dd\uc744 \uc74c\ubbf8 \uc5bc\uad74", "Relieved face": "\uc548\ub3c4 \uc5bc\uad74", "Smiling face with heart-shaped eyes": "\ud558\ud2b8 \ubaa8\uc591\uc758 \ub208\uc73c\ub85c \uc6c3\ub294 \uc5bc\uad74", "Smiling face with sunglasses": "\uc120\uae00\ub77c\uc2a4 \uc6c3\ub294 \uc5bc\uad74", "Smirking face": "\ub3c8\uc744 \uc9c0\ubd88 \uc5bc\uad74", "Neutral face": "\uc911\ub9bd \uc5bc\uad74", "Expressionless face": "\ubb34\ud45c\uc815 \uc5bc\uad74", "Unamused face": "\uc990\uac81\uac8c\ud558\uc9c0 \uc5bc\uad74", "Face with cold sweat": "\uc2dd\uc740 \ub540\uacfc \uc5bc\uad74", "Pensive face": "\uc7a0\uaca8\uc788\ub294 \uc5bc\uad74", "Confused face": "\ud63c\ub780 \uc5bc\uad74", "Confounded face": "\ub9dd\ud560 \uac83 \uc5bc\uad74", "Kissing face": "\uc5bc\uad74\uc744 \ud0a4\uc2a4", "Face throwing a kiss": "\ud0a4\uc2a4\ub97c \ub358\uc9c0\uace0 \uc5bc\uad74", "Kissing face with smiling eyes": "\ubbf8\uc18c\ub294 \ub208\uc744 \uac00\uc9c4 \uc5bc\uad74\uc744 \ud0a4\uc2a4", "Kissing face with closed eyes": "\ub2eb\ud78c \ub41c \ub208\uc744 \uac00\uc9c4 \uc5bc\uad74\uc744 \ud0a4\uc2a4", "Face with stuck out tongue": "\ub0b4\ubc00 \ud600 \uc5bc\uad74", "Face with stuck out tongue and winking eye": "\ub0b4\ubc00 \ud600\uc640 \uc719\ud06c \ub208\uacfc \uc5bc\uad74", "Face with stuck out tongue and tightly-closed eyes": "\ubc16\uc73c\ub85c \ubd99\uc5b4 \ud600\uc640 \ubc00\uc811\ud558\uac8c \ub2eb\ud78c \ub41c \ub208\uc744 \uac00\uc9c4 \uc5bc\uad74", "Disappointed face": "\uc2e4\ub9dd \uc5bc\uad74", "Worried face": "\uac71\uc815 \uc5bc\uad74", "Angry face": "\uc131\ub09c \uc5bc\uad74", "Pouting face": "\uc5bc\uad74\uc744 \uc090", "Crying face": "\uc5bc\uad74 \uc6b0\ub294", "Persevering face": "\uc5bc\uad74\uc744 \uc778\ub0b4", "Face with look of triumph": "\uc2b9\ub9ac\uc758 \ud45c\uc815\uc73c\ub85c \uc5bc\uad74", "Disappointed but relieved face": "\uc2e4\ub9dd\ud558\uc9c0\ub9cc \uc5bc\uad74\uc744 \uc548\uc2ec", "Frowning face with open mouth": "\uc624\ud508 \uc785\uc73c\ub85c \uc5bc\uad74\uc744 \ucc21\uadf8\ub9bc", "Anguished face": "\uace0\ub1cc\uc758 \uc5bc\uad74", "Fearful face": "\ubb34\uc11c\uc6b4 \uc5bc\uad74", "Weary face": "\uc9c0\uce5c \uc5bc\uad74", "Sleepy face": "\uc2ac\ub9ac\ud53c \uc5bc\uad74", "Tired face": "\ud53c\uace4 \uc5bc\uad74", "Grimacing face": "\uc5bc\uad74\uc744 \ucc21\uadf8\ub9b0", "Loudly crying face": "\ud070 \uc18c\ub9ac\ub85c \uc5bc\uad74\uc744 \uc6b8\uace0", "Face with open mouth": "\uc624\ud508 \uc785\uc73c\ub85c \uc5bc\uad74", "Hushed face": "\uc870\uc6a9\ud55c \uc5bc\uad74", "Face with open mouth and cold sweat": "\uc785\uc744 \uc5f4\uace0 \uc2dd\uc740 \ub540\uc73c\ub85c \uc5bc\uad74", "Face screaming in fear": "\uacf5\ud3ec\uc5d0 \ube44\uba85 \uc5bc\uad74", "Astonished face": "\ub180\ub77c \uc5bc\uad74", "Flushed face": "\ud50c\ub7ec\uc2dc \uc5bc\uad74", "Sleeping face": "\uc5bc\uad74 \uc7a0\uc790\ub294", "Dizzy face": "\ub514\uc9c0 \uc5bc\uad74", "Face without mouth": "\uc785\uc5c6\uc774 \uc5bc\uad74", "Face with medical mask": "\uc758\ub8cc \ub9c8\uc2a4\ud06c\ub85c \uc5bc\uad74", // Line breaker "Break": "\ub2e8\uc808", // Math "Subscript": "\uc544\ub798 \ucca8\uc790", "Superscript": "\uc704 \ucca8\uc790", // Full screen "Fullscreen": "\uc804\uccb4 \ud654\uba74", // Horizontal line "Insert Horizontal Line": "\uc218\ud3c9\uc120\uc744 \uc0bd\uc785", // Clear formatting "Clear Formatting": "\uc11c\uc2dd \uc81c\uac70", // Undo, redo "Undo": "\uc2e4\ud589 \ucde8\uc18c", "Redo": "\ub418\ub3cc\ub9ac\uae30", // Select all "Select All": "\uc804\uccb4\uc120\ud0dd", // Code view "Code View": "\ucf54\ub4dc\ubcf4\uae30", // Quote "Quote": "\uc778\uc6a9", "Increase": "\uc99d\uac00", "Decrease": "\uac10\uc18c", // Quick Insert "Quick Insert": "\ube60\ub978 \uc0bd\uc785", // Spcial Characters "Special Characters": "\ud2b9\uc218 \ubb38\uc790", "Latin": "\ub77c\ud2f4\uc5b4", "Greek": "\uadf8\ub9ac\uc2a4\uc5b4", "Cyrillic": "\ud0a4\ub9b4 \ubb38\uc790", "Punctuation": "\ubb38\uc7a5\ubd80\ud638", "Currency": "\ud1b5\ud654", "Arrows": "\ud654\uc0b4\ud45c", "Math": "\uc218\ud559", "Misc": "\uadf8 \uc678", // Print. "Print": "\uc778\uc1c4", // Spell Checker. "Spell Checker": "\ub9de\ucda4\ubc95 \uac80\uc0ac\uae30", // Help "Help": "\ub3c4\uc6c0\ub9d0", "Shortcuts": "\ub2e8\ucd95\ud0a4", "Inline Editor": "\uc778\ub77c\uc778 \uc5d0\ub514\ud130", "Show the editor": "\uc5d0\ub514\ud130 \ubcf4\uae30", "Common actions": "\uc77c\ubc18 \ub3d9\uc791", "Copy": "\ubcf5\uc0ac\ud558\uae30", "Cut": "\uc798\ub77c\ub0b4\uae30", "Paste": "\ubd99\uc5ec\ub123\uae30", "Basic Formatting": "\uae30\ubcf8 \uc11c\uc2dd", "Increase quote level": "\uc778\uc6a9 \uc99d\uac00", "Decrease quote level": "\uc778\uc6a9 \uac10\uc18c", "Image / Video": "\uc774\ubbf8\uc9c0 / \ub3d9\uc601\uc0c1", "Resize larger": "\ud06c\uae30\ub97c \ub354 \ud06c\uac8c \uc870\uc815", "Resize smaller": "\ud06c\uae30\ub97c \ub354 \uc791\uac8c \uc870\uc815", "Table": "\ud45c", "Select table cell": "\ud45c \uc140 \uc120\ud0dd", "Extend selection one cell": "\uc140\uc758 \uc120\ud0dd \ubc94\uc704\ub97c \ud655\uc7a5", "Extend selection one row": "\ud589\uc758 \uc120\ud0dd \ubc94\uc704\ub97c \ud655\uc7a5", "Navigation": "\ub124\ube44\uac8c\uc774\uc158", "Focus popup / toolbar": "\ud31d\uc5c5 / \ud234\ubc14\ub97c \ud3ec\ucee4\uc2a4", "Return focus to previous position": "\uc774\uc804 \uc704\uce58\ub85c \ud3ec\ucee4\uc2a4 \ub418\ub3cc\ub9ac\uae30", // Embed.ly "Embed URL": "\uc784\ubca0\ub4dc URL", "Paste in a URL to embed": "\uc784\ubca0\ub4dc URL\uc5d0 \ubd99\uc5ec \ub123\uae30", // Word Paste. "The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "\ubd99\uc5ec\ub123\uc740 \ubb38\uc11c\ub294 \ub9c8\uc774\ud06c\ub85c\uc18c\ud504\ud2b8 \uc6cc\ub4dc\uc5d0\uc11c \uac00\uc838\uc654\uc2b5\ub2c8\ub2e4. \ud3ec\ub9f7\uc744 \uc720\uc9c0\ud558\uac70\ub098 \uc815\ub9ac \ud558\uc2dc\uaca0\uc2b5\ub2c8\uae4c?", "Keep": "\uc720\uc9c0", "Clean": "\uc815\ub9ac", "Word Paste Detected": "\uc6cc\ub4dc \ubd99\uc5ec \ub123\uae30\uac00 \uac80\ucd9c \ub418\uc5c8\uc2b5\ub2c8\ub2e4." }, direction: "ltr" }; }));
/*! jQuery Fancytree Plugin - 2.28.0 - 2018-03-02T20:59:49Z * https://github.com/mar10/fancytree * Copyright (c) 2018 Martin Wendt; Licensed MIT */ /*! jQuery UI - v1.12.1 - 2017-02-23 * http://jqueryui.com * Includes: widget.js, position.js, keycode.js, scroll-parent.js, unique-id.js, effect.js, effects/effect-blind.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ /* NOTE: Original jQuery UI wrapper was replaced with a simple IIFE. See README-Fancytree.md */ (function( $ ) { $.ui = $.ui || {}; var version = $.ui.version = "1.12.1"; /*! * jQuery UI Widget 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Widget //>>group: Core //>>description: Provides a factory for creating stateful widgets with a common API. //>>docs: http://api.jqueryui.com/jQuery.widget/ //>>demos: http://jqueryui.com/widget/ var widgetUuid = 0; var widgetSlice = Array.prototype.slice; $.cleanData = ( function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // Http://bugs.jquery.com/ticket/8235 } catch ( e ) {} } orig( elems ); }; } )( $.cleanData ); $.widget = function( name, base, prototype ) { var existingConstructor, constructor, basePrototype; // ProxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) var proxiedPrototype = {}; var namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; var fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } if ( $.isArray( prototype ) ) { prototype = $.extend.apply( null, [ {} ].concat( prototype ) ); } // Create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // Allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // Allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // Extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // Copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // Track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] } ); basePrototype = new base(); // We need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = ( function() { function _super() { return base.prototype[ prop ].apply( this, arguments ); } function _superApply( args ) { return base.prototype[ prop ].apply( this, args ); } return function() { var __super = this._super; var __superApply = this._superApply; var returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; } )(); } ); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName } ); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // Redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); } ); // Remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widgetSlice.call( arguments, 1 ); var inputIndex = 0; var inputLength = input.length; var key; var value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string"; var args = widgetSlice.call( arguments, 1 ); var returnValue = this; if ( isMethodCall ) { // If this is an empty collection, we need to have the instance method // return undefined instead of the jQuery instance if ( !this.length && options === "instance" ) { returnValue = undefined; } else { this.each( function() { var methodValue; var instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } } ); } } else { // Allow multiple hashes to be passed on init if ( args.length ) { options = $.widget.extend.apply( null, [ options ].concat( args ) ); } this.each( function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } } ); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { classes: {}, disabled: false, // Callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widgetUuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.bindings = $(); this.hoverable = $(); this.focusable = $(); this.classesElementLookup = {}; if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } } ); this.document = $( element.style ? // Element within the document element.ownerDocument : // Element is window or document element.document || element ); this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow ); } this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this._create(); if ( this.options.disabled ) { this._setOptionDisabled( this.options.disabled ); } this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: function() { return {}; }, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { var that = this; this._destroy(); $.each( this.classesElementLookup, function( key, value ) { that._removeClass( value, key ); } ); // We can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .off( this.eventNamespace ) .removeData( this.widgetFullName ); this.widget() .off( this.eventNamespace ) .removeAttr( "aria-disabled" ); // Clean up events and states this.bindings.off( this.eventNamespace ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key; var parts; var curOption; var i; if ( arguments.length === 0 ) { // Don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { if ( key === "classes" ) { this._setOptionClasses( value ); } this.options[ key ] = value; if ( key === "disabled" ) { this._setOptionDisabled( value ); } return this; }, _setOptionClasses: function( value ) { var classKey, elements, currentElements; for ( classKey in value ) { currentElements = this.classesElementLookup[ classKey ]; if ( value[ classKey ] === this.options.classes[ classKey ] || !currentElements || !currentElements.length ) { continue; } // We are doing this to create a new jQuery object because the _removeClass() call // on the next line is going to destroy the reference to the current elements being // tracked. We need to save a copy of this collection so that we can add the new classes // below. elements = $( currentElements.get() ); this._removeClass( currentElements, classKey ); // We don't use _addClass() here, because that uses this.options.classes // for generating the string of classes. We want to use the value passed in from // _setOption(), this is the new value of the classes option which was passed to // _setOption(). We pass this value directly to _classes(). elements.addClass( this._classes( { element: elements, keys: classKey, classes: value, add: true } ) ); } }, _setOptionDisabled: function( value ) { this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this._removeClass( this.hoverable, null, "ui-state-hover" ); this._removeClass( this.focusable, null, "ui-state-focus" ); } }, enable: function() { return this._setOptions( { disabled: false } ); }, disable: function() { return this._setOptions( { disabled: true } ); }, _classes: function( options ) { var full = []; var that = this; options = $.extend( { element: this.element, classes: this.options.classes || {} }, options ); function processClassString( classes, checkOption ) { var current, i; for ( i = 0; i < classes.length; i++ ) { current = that.classesElementLookup[ classes[ i ] ] || $(); if ( options.add ) { current = $( $.unique( current.get().concat( options.element.get() ) ) ); } else { current = $( current.not( options.element ).get() ); } that.classesElementLookup[ classes[ i ] ] = current; full.push( classes[ i ] ); if ( checkOption && options.classes[ classes[ i ] ] ) { full.push( options.classes[ classes[ i ] ] ); } } } this._on( options.element, { "remove": "_untrackClassesElement" } ); if ( options.keys ) { processClassString( options.keys.match( /\S+/g ) || [], true ); } if ( options.extra ) { processClassString( options.extra.match( /\S+/g ) || [] ); } return full.join( " " ); }, _untrackClassesElement: function( event ) { var that = this; $.each( that.classesElementLookup, function( key, value ) { if ( $.inArray( event.target, value ) !== -1 ) { that.classesElementLookup[ key ] = $( value.not( event.target ).get() ); } } ); }, _removeClass: function( element, keys, extra ) { return this._toggleClass( element, keys, extra, false ); }, _addClass: function( element, keys, extra ) { return this._toggleClass( element, keys, extra, true ); }, _toggleClass: function( element, keys, extra, add ) { add = ( typeof add === "boolean" ) ? add : extra; var shift = ( typeof element === "string" || element === null ), options = { extra: shift ? keys : extra, keys: shift ? element : keys, element: shift ? this.element : element, add: add }; options.element.toggleClass( this._classes( options ), add ); return this; }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement; var instance = this; // No suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // No element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // Allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // Copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ); var eventName = match[ 1 ] + instance.eventNamespace; var selector = match[ 2 ]; if ( selector ) { delegateElement.on( eventName, selector, handlerProxy ); } else { element.on( eventName, handlerProxy ); } } ); }, _off: function( element, eventName ) { eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.off( eventName ).off( eventName ); // Clear the stack to avoid memory leaks (#10056) this.bindings = $( this.bindings.not( element ).get() ); this.focusable = $( this.focusable.not( element ).get() ); this.hoverable = $( this.hoverable.not( element ).get() ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { this._addClass( $( event.currentTarget ), null, "ui-state-hover" ); }, mouseleave: function( event ) { this._removeClass( $( event.currentTarget ), null, "ui-state-hover" ); } } ); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { this._addClass( $( event.currentTarget ), null, "ui-state-focus" ); }, focusout: function( event ) { this._removeClass( $( event.currentTarget ), null, "ui-state-focus" ); } } ); }, _trigger: function( type, event, data ) { var prop, orig; var callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // The original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // Copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions; var effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue( function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); } ); } }; } ); var widget = $.widget; /*! * jQuery UI Position 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/position/ */ //>>label: Position //>>group: Core //>>description: Positions elements relative to other elements. //>>docs: http://api.jqueryui.com/position/ //>>demos: http://jqueryui.com/position/ ( function() { var cachedScrollbarWidth, max = Math.max, abs = Math.abs, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[ 0 ]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div " + "style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'>" + "<div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[ 0 ]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[ 0 ].clientWidth; } div.remove(); return ( cachedScrollbarWidth = w1 - w2 ); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[ 0 ] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9, hasOffset = !isWindow && !isDocument; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: withinElement.outerWidth(), height: withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // Make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[ 0 ].preventDefault ) { // Force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // Clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // Force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1 ) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // Calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // Reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; } ); // Normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each( function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem } ); } } ); if ( options.using ) { // Adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); } ); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // Element is wider than within if ( data.collisionWidth > outerWidth ) { // Element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // Element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // Element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // Too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // Too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // Adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // Element is taller than within if ( data.collisionHeight > outerHeight ) { // Element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // Element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // Element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // Too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // Too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // Adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; } )(); var position = $.ui.position; /*! * jQuery UI Keycode 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Keycode //>>group: Core //>>description: Provide keycodes as keynames //>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/ var keycode = $.ui.keyCode = { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 }; /*! * jQuery UI Scroll Parent 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: scrollParent //>>group: Core //>>description: Get the closest ancestor element that is scrollable. //>>docs: http://api.jqueryui.com/scrollParent/ var scrollParent = $.fn.scrollParent = function( includeHidden ) { var position = this.css( "position" ), excludeStaticParent = position === "absolute", overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/, scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); } ).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }; /*! * jQuery UI Unique ID 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: uniqueId //>>group: Core //>>description: Functions to generate and remove uniqueId's //>>docs: http://api.jqueryui.com/uniqueId/ var uniqueId = $.fn.extend( { uniqueId: ( function() { var uuid = 0; return function() { return this.each( function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } } ); }; } )(), removeUniqueId: function() { return this.each( function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } } ); } } ); /*! * jQuery UI Effects 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Effects Core //>>group: Effects // jscs:disable maximumLineLength //>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects. // jscs:enable maximumLineLength //>>docs: http://api.jqueryui.com/category/effects-core/ //>>demos: http://jqueryui.com/effect/ var dataSpace = "ui-effects-", dataSpaceStyle = "ui-effects-style", dataSpaceAnimated = "ui-effects-animated", // Create a local jQuery because jQuery Color relies on it and the // global may not exist with AMD and a custom build (#10199) jQuery = $; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ ( function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " + "borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // Plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // A set of RE's that can match strings and generate color tuples. stringParsers = [ { re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, 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*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // This regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // This regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } } ], // JQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // Element for support tests supportElem = jQuery( "<p>" )[ 0 ], // Colors = jQuery.Color.names colors, // Local aliases of functions called often each = jQuery.each; // Determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // Define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; } ); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return ( allowEmpty || !prop.def ) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // We add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return ( value + type.mod ) % type.mod; } // For now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // If this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // Exit each( stringParsers ) here because we matched return false; } } ); // Found a stringParser that handled it if ( rgba.length ) { // If this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // Named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // More than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); } ); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } } ); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // If the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // If the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // This is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); } ); // Everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // Use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } } ); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if ( isCache ) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } } ); } return same; } ); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } } ); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // If null, don't override start value if ( endValue === null ) { return; } // If null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } } ); return this[ spaceName ]( result ); }, blend: function( opaque ) { // If we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; } ) ); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; } ); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // Catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; } ); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // Default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; } ).join( "" ); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } } ); color.fn.parse.prototype = color.fn; // Hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + ( q - p ) * h * 6; } if ( h * 2 < 1 ) { return q; } if ( h * 3 < 2 ) { return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6; } return p; } spaces.hsla.to = function( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // Chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // Makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // Generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); } ); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // Makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // Alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; } ); } ); // Add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( ( backgroundColor === "" || backgroundColor === "transparent" ) && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch ( e ) { // Wrapped to prevent IE from throwing errors on "invalid" values like // 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; } ); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; } ); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; } )( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ ( function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each( [ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; } ); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // Support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // Support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // Map the animated objects to store the original styles. allAnimations = allAnimations.map( function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; } ); // Apply class change applyClassChange = function() { $.each( classAnimationActions, function( i, action ) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } } ); }; applyClassChange(); // Map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map( function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; } ); // Apply original class animated.attr( "class", baseClass ); // Map all animated objects again - this time collecting a promise allAnimations = allAnimations.map( function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend( {}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } } ); this.el.animate( this.diff, opts ); return dfd.promise(); } ); // Once all animations have completed: $.when.apply( $, allAnimations.get() ).done( function() { // Set the final class applyClassChange(); // For each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function( key ) { el.css( key, "" ); } ); } ); // This is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); } ); } ); }; $.fn.extend( { addClass: ( function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; } )( $.fn.addClass ), removeClass: ( function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; } )( $.fn.removeClass ), toggleClass: ( function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // Without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, ( force ? { add: classNames } : { remove: classNames } ), speed, easing, callback ); } } else { // Without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; } )( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback ) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } } ); } )(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ ( function() { if ( $.expr && $.expr.filters && $.expr.filters.animated ) { $.expr.filters.animated = ( function( orig ) { return function( elem ) { return !!$( elem ).data( dataSpaceAnimated ) || orig( elem ); }; } )( $.expr.filters.animated ); } if ( $.uiBackCompat !== false ) { $.extend( $.effects, { // Saves a set of properties in a data storage save: function( element, set ) { var i = 0, length = set.length; for ( ; i < length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i = 0, length = set.length; for ( ; i < length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if ( mode === "toggle" ) { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // If the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" ) ) { return element.parent(); } // Wrap the element var props = { width: element.outerWidth( true ), height: element.outerHeight( true ), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css( { fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 } ), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // Support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch ( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).trigger( "focus" ); } // Hotfix for jQuery 1.4 since some change in wrap() seems to actually // lose the reference to the wrapped element wrapper = element.parent(); // Transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css( { position: "relative" } ); element.css( { position: "relative" } ); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) } ); $.each( [ "top", "left", "bottom", "right" ], function( i, pos ) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } } ); element.css( { position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" } ); } element.css( size ); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).trigger( "focus" ); } } return element; } } ); } $.extend( $.effects, { version: "1.12.1", define: function( name, mode, effect ) { if ( !effect ) { effect = mode; mode = "effect"; } $.effects.effect[ name ] = effect; $.effects.effect[ name ].mode = mode; return effect; }, scaledDimensions: function( element, percent, direction ) { if ( percent === 0 ) { return { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; } var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1, y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1; return { height: element.height() * y, width: element.width() * x, outerHeight: element.outerHeight() * y, outerWidth: element.outerWidth() * x }; }, clipToBox: function( animation ) { return { width: animation.clip.right - animation.clip.left, height: animation.clip.bottom - animation.clip.top, left: animation.clip.left, top: animation.clip.top }; }, // Injects recently queued functions to be first in line (after "inprogress") unshift: function( element, queueLength, count ) { var queue = element.queue(); if ( queueLength > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queueLength, count ) ) ); } element.dequeue(); }, saveStyle: function( element ) { element.data( dataSpaceStyle, element[ 0 ].style.cssText ); }, restoreStyle: function( element ) { element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || ""; element.removeData( dataSpaceStyle ); }, mode: function( element, mode ) { var hidden = element.is( ":hidden" ); if ( mode === "toggle" ) { mode = hidden ? "show" : "hide"; } if ( hidden ? mode === "hide" : mode === "show" ) { mode = "none"; } return mode; }, // Translates a [top,left] array into a baseline value getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Creates a placeholder element so that the original element can be made absolute createPlaceholder: function( element ) { var placeholder, cssPosition = element.css( "position" ), position = element.position(); // Lock in margins first to account for form elements, which // will change margin if you explicitly set height // see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380 // Support: Safari element.css( { marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ); if ( /^(static|relative)/.test( cssPosition ) ) { cssPosition = "absolute"; placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( { // Convert inline to inline block to account for inline elements // that turn to inline block based on content (like img) display: /^(inline|ruby)/.test( element.css( "display" ) ) ? "inline-block" : "block", visibility: "hidden", // Margins need to be set to account for margin collapse marginTop: element.css( "marginTop" ), marginBottom: element.css( "marginBottom" ), marginLeft: element.css( "marginLeft" ), marginRight: element.css( "marginRight" ), "float": element.css( "float" ) } ) .outerWidth( element.outerWidth() ) .outerHeight( element.outerHeight() ) .addClass( "ui-effects-placeholder" ); element.data( dataSpace + "placeholder", placeholder ); } element.css( { position: cssPosition, left: position.left, top: position.top } ); return placeholder; }, removePlaceholder: function( element ) { var dataKey = dataSpace + "placeholder", placeholder = element.data( dataKey ); if ( placeholder ) { placeholder.remove(); element.removeData( dataKey ); } }, // Removes a placeholder if it exists and restores // properties that were modified during placeholder creation cleanUp: function( element ) { $.effects.restoreStyle( element ); $.effects.removePlaceholder( element ); }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } } ); return value; } } ); // Return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // Allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // Convert to an object effect = { effect: effect }; // Catch (effect, null, ...) if ( options == null ) { options = {}; } // Catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // Catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // Catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // Add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend( { effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), effectMethod = $.effects.effect[ args.effect ], defaultMode = effectMethod.mode, queue = args.queue, queueName = queue || "fx", complete = args.complete, mode = args.mode, modes = [], prefilter = function( next ) { var el = $( this ), normalizedMode = $.effects.mode( el, mode ) || defaultMode; // Sentinel for duck-punching the :animated psuedo-selector el.data( dataSpaceAnimated, true ); // Save effect mode for later use, // we can't just call $.effects.mode again later, // as the .show() below destroys the initial state modes.push( normalizedMode ); // See $.uiBackCompat inside of run() for removal of defaultMode in 1.13 if ( defaultMode && ( normalizedMode === "show" || ( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) { el.show(); } if ( !defaultMode || normalizedMode !== "none" ) { $.effects.saveStyle( el ); } if ( $.isFunction( next ) ) { next(); } }; if ( $.fx.off || !effectMethod ) { // Delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, complete ); } else { return this.each( function() { if ( complete ) { complete.call( this ); } } ); } } function run( next ) { var elem = $( this ); function cleanup() { elem.removeData( dataSpaceAnimated ); $.effects.cleanUp( elem ); if ( args.mode === "hide" ) { elem.hide(); } done(); } function done() { if ( $.isFunction( complete ) ) { complete.call( elem[ 0 ] ); } if ( $.isFunction( next ) ) { next(); } } // Override mode option on a per element basis, // as toggle can be either show or hide depending on element state args.mode = modes.shift(); if ( $.uiBackCompat !== false && !defaultMode ) { if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { // Call the core method to track "olddisplay" properly elem[ mode ](); done(); } else { effectMethod.call( elem[ 0 ], args, done ); } } else { if ( args.mode === "none" ) { // Call the core method to track "olddisplay" properly elem[ mode ](); done(); } else { effectMethod.call( elem[ 0 ], args, cleanup ); } } } // Run prefilter on all elements first to ensure that // any showing or hiding happens before placeholder creation, // which ensures that any layout changes are correctly captured. return queue === false ? this.each( prefilter ).each( run ) : this.queue( queueName, prefilter ).queue( queueName, run ); }, show: ( function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; } )( $.fn.show ), hide: ( function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; } )( $.fn.hide ), toggle: ( function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; } )( $.fn.toggle ), cssUnit: function( key ) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } } ); return val; }, cssClip: function( clipObj ) { if ( clipObj ) { return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " + clipObj.bottom + "px " + clipObj.left + "px)" ); } return parseClip( this.css( "clip" ), this ); }, transfer: function( options, done ) { var element = $( this ), target = $( options.to ), targetFixed = target.css( "position" ) === "fixed", body = $( "body" ), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop, left: endPosition.left - fixLeft, height: target.innerHeight(), width: target.innerWidth() }, startPosition = element.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( "body" ) .addClass( options.className ) .css( { top: startPosition.top - fixTop, left: startPosition.left - fixLeft, height: element.innerHeight(), width: element.innerWidth(), position: targetFixed ? "fixed" : "absolute" } ) .animate( animation, options.duration, options.easing, function() { transfer.remove(); if ( $.isFunction( done ) ) { done(); } } ); } } ); function parseClip( str, element ) { var outerWidth = element.outerWidth(), outerHeight = element.outerHeight(), clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/, values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ]; return { top: parseFloat( values[ 1 ] ) || 0, right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ), bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ), left: parseFloat( values[ 4 ] ) || 0 }; } $.fx.step.clip = function( fx ) { if ( !fx.clipInit ) { fx.start = $( fx.elem ).cssClip(); if ( typeof fx.end === "string" ) { fx.end = parseClip( fx.end, fx.elem ); } fx.clipInit = true; } $( fx.elem ).cssClip( { top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top, right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right, bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom, left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left } ); }; } )(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ ( function() { // Based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; } ); $.extend( baseEasings, { Sine: function( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * ( p - 1 ) ) * Math.sin( ( ( p - 1 ) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } } ); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; } ); } )(); var effect = $.effects; /*! * jQuery UI Effects Blind 1.12.1 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license */ //>>label: Blind Effect //>>group: Effects //>>description: Blinds the element. //>>docs: http://api.jqueryui.com/blind-effect/ //>>demos: http://jqueryui.com/effect/ var effectsEffectBlind = $.effects.define( "blind", "hide", function( options, done ) { var map = { up: [ "bottom", "top" ], vertical: [ "bottom", "top" ], down: [ "top", "bottom" ], left: [ "right", "left" ], horizontal: [ "right", "left" ], right: [ "left", "right" ] }, element = $( this ), direction = options.direction || "up", start = element.cssClip(), animate = { clip: $.extend( {}, start ) }, placeholder = $.effects.createPlaceholder( element ); animate.clip[ map[ direction ][ 0 ] ] = animate.clip[ map[ direction ][ 1 ] ]; if ( options.mode === "show" ) { element.cssClip( animate.clip ); if ( placeholder ) { placeholder.css( $.effects.clipToBox( animate ) ); } animate.clip = start; } if ( placeholder ) { placeholder.animate( $.effects.clipToBox( animate ), options.duration, options.easing ); } element.animate( animate, { queue: false, duration: options.duration, easing: options.easing, complete: done } ); } ); // NOTE: Original jQuery UI wrapper was replaced. See README-Fancytree.md // })); })(jQuery); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! Fancytree Core *//*! * jquery.fancytree.js * Tree view control with support for lazy loading and much more. * https://github.com/mar10/fancytree/ * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ /** Core Fancytree module. */ // UMD wrapper for the Fancytree core module ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree.ui-deps" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree.ui-deps"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; // prevent duplicate loading if ( $.ui && $.ui.fancytree ) { $.ui.fancytree.warn("Fancytree: ignored duplicate include"); return; } /* ***************************************************************************** * Private functions and variables */ var i, attr, FT = null, // initialized below TEST_IMG = new RegExp(/\.|\//), // strings are considered image urls if they contain '.' or '/' REX_HTML = /[&<>"'\/]/g, // Escape those characters REX_TOOLTIP = /[<>"'\/]/g, // Don't escape `&` in tooltips RECURSIVE_REQUEST_ERROR = "$recursive_request", ENTITY_MAP = {"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;", "/": "&#x2F;"}, IGNORE_KEYCODES = { 16: true, 17: true, 18: true }, SPECIAL_KEYCODES = { 8: "backspace", 9: "tab", 10: "return", 13: "return", // 16: null, 17: null, 18: null, // ignore shift, ctrl, alt 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"}, MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" }, // Boolean attributes that can be set with equivalent class names in the LI tags // Note: v2.23: checkbox and hideCheckbox are *not* in this list CLASS_ATTRS = "active expanded focus folder lazy radiogroup selected unselectable unselectableIgnore".split(" "), CLASS_ATTR_MAP = {}, // Top-level Fancytree attributes, that can be set by dict TREE_ATTRS = "columns types".split(" "), // TREE_ATTR_MAP = {}, // Top-level FancytreeNode attributes, that can be set by dict NODE_ATTRS = "checkbox expanded extraClasses folder icon iconTooltip key lazy partsel radiogroup refKey selected statusNodeType title tooltip type unselectable unselectableIgnore unselectableStatus".split(" "), NODE_ATTR_MAP = {}, // Mapping of lowercase -> real name (because HTML5 data-... attribute only supports lowercase) NODE_ATTR_LOWERCASE_MAP = {}, // Attribute names that should NOT be added to node.data NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true}; for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; } for(i=0; i<NODE_ATTRS.length; i++) { attr = NODE_ATTRS[i]; NODE_ATTR_MAP[attr] = true; if( attr !== attr.toLowerCase() ) { NODE_ATTR_LOWERCASE_MAP[attr.toLowerCase()] = attr; } } // for(i=0; i<TREE_ATTRS.length; i++) { // TREE_ATTR_MAP[TREE_ATTRS[i]] = true; // } function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; // consoleApply("assert", [!!cond, msg]); $.error("Fancytree assertion failed" + msg); } } _assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)"); function consoleApply(method, args){ var i, s, fn = window.console ? window.console[method] : null; if(fn){ try{ fn.apply(window.console, args); } catch(e) { // IE 8? s = ""; for( i=0; i<args.length; i++ ) { s += args[i]; } fn(s); } } } /* support: IE8 Polyfil for Date.now() */ if( !Date.now ) { Date.now = function now() { return new Date().getTime(); }; } /*Return true if x is a FancytreeNode.*/ function _isNode(x){ return !!(x.tree && x.statusNodeType !== undefined); } /** Return true if dotted version string is equal or higher than requested version. * * See http://jsfiddle.net/mar10/FjSAN/ */ function isVersionAtLeast(dottedVersion, major, minor, patch){ var i, v, t, verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }), testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); }); for( i = 0; i < testParts.length; i++ ){ v = verParts[i] || 0; t = testParts[i] || 0; if( v !== t ){ return ( v > t ); } } return true; } /** Return a wrapper that calls sub.methodName() and exposes * this : tree * this._local : tree.ext.EXTNAME * this._super : base.methodName.call() * this._superApply : base.methodName.apply() */ function _makeVirtualFunction(methodName, tree, base, extension, extName){ // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName); // if(rexTestSuper && !rexTestSuper.test(func)){ // // extension.methodName() doesn't call _super(), so no wrapper required // return func; // } // Use an immediate function as closure var proxy = (function(){ var prevFunc = tree[methodName], // org. tree method or prev. proxy baseFunc = extension[methodName], // _local = tree.ext[extName], _super = function(){ return prevFunc.apply(tree, arguments); }, _superApply = function(args){ return prevFunc.apply(tree, args); }; // Return the wrapper function return function(){ var prevLocal = tree._local, prevSuper = tree._super, prevSuperApply = tree._superApply; try{ tree._local = _local; tree._super = _super; tree._superApply = _superApply; return baseFunc.apply(tree, arguments); }finally{ tree._local = prevLocal; tree._super = prevSuper; tree._superApply = prevSuperApply; } }; })(); // end of Immediate Function return proxy; } /** * Subclass `base` by creating proxy functions */ function _subclassObject(tree, base, extension, extName){ // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName); for(var attrName in extension){ if(typeof extension[attrName] === "function"){ if(typeof tree[attrName] === "function"){ // override existing method tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else if(attrName.charAt(0) === "_"){ // Create private methods in tree.ext.EXTENSION namespace tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else{ $.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName); } }else{ // Create member variables in tree.ext.EXTENSION namespace if(attrName !== "options"){ tree.ext[extName][attrName] = extension[attrName]; } } } } function _getResolvedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.resolve();}).promise(); }else{ return $.Deferred(function(){this.resolveWith(context, argArray);}).promise(); } } function _getRejectedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.reject();}).promise(); }else{ return $.Deferred(function(){this.rejectWith(context, argArray);}).promise(); } } function _makeResolveFunc(deferred, context){ return function(){ deferred.resolveWith(context); }; } function _getElementDataAsDict($el){ // Evaluate 'data-NAME' attributes with special treatment for 'data-json'. var d = $.extend({}, $el.data()), json = d.json; delete d.fancytree; // added to container by widget factory (old jQuery UI) delete d.uiFancytree; // added to container by widget factory if( json ) { delete d.json; // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5) d = $.extend(d, json); } return d; } function _escapeTooltip(s){ return ("" + s).replace(REX_TOOLTIP, function(s) { return ENTITY_MAP[s]; }); } // TODO: use currying function _makeNodeTitleMatcher(s){ s = s.toLowerCase(); return function(node){ return node.title.toLowerCase().indexOf(s) >= 0; }; } function _makeNodeTitleStartMatcher(s){ var reMatch = new RegExp("^" + s, "i"); return function(node){ return reMatch.test(node.title); }; } /* ***************************************************************************** * FancytreeNode */ /** * Creates a new FancytreeNode * * @class FancytreeNode * @classdesc A FancytreeNode represents the hierarchical data model and operations. * * @param {FancytreeNode} parent * @param {NodeData} obj * * @property {Fancytree} tree The tree instance * @property {FancytreeNode} parent The parent node * @property {string} key Node id (must be unique inside the tree) * @property {string} title Display name (may contain HTML) * @property {object} data Contains all extra data that was passed on node creation * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br> * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array * to define a node that has no children. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property. * @property {string} extraClasses Additional CSS classes, added to the node's `&lt;span>`.<br> * Note: use `node.add/remove/toggleClass()` to modify. * @property {boolean} folder Folder nodes have different default icons and click behavior.<br> * Note: Also non-folders may have children. * @property {string} statusNodeType null for standard nodes. Otherwise type of special system node: 'error', 'loading', 'nodata', or 'paging'. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion. * @property {boolean} selected Use isSelected(), setSelected() to access this property. * @property {string} tooltip Alternative description used as hover popup * @property {string} iconTooltip Description used as hover popup for icon. @since 2.27 * @property {string} type Node type, used with tree.types map. @since 2.27 */ function FancytreeNode(parent, obj){ var i, l, name, cl; this.parent = parent; this.tree = parent.tree; this.ul = null; this.li = null; // <li id='key' ftnode=this> tag this.statusNodeType = null; // if this is a temp. node to display the status of its parent this._isLoading = false; // if this node itself is loading this._error = null; // {message: '...'} if a load error occurred this.data = {}; // TODO: merge this code with node.toDict() // copy attributes from obj object for(i=0, l=NODE_ATTRS.length; i<l; i++){ name = NODE_ATTRS[i]; this[name] = obj[name]; } // unselectableIgnore and unselectableStatus imply unselectable if( this.unselectableIgnore != null || this.unselectableStatus != null ) { this.unselectable = true; } if( obj.hideCheckbox ) { $.error("'hideCheckbox' node option was removed in v2.23.0: use 'checkbox: false'"); } // node.data += obj.data if(obj.data){ $.extend(this.data, obj.data); } // Copy all other attributes to this.data.NAME for(name in obj){ if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = obj.NAME this.data[name] = obj[name]; } } // Fix missing key if( this.key == null ){ // test for null OR undefined if( this.tree.options.defaultKey ) { this.key = this.tree.options.defaultKey(this); _assert(this.key, "defaultKey() must return a unique key"); } else { this.key = "_" + (FT._nextNodeKey++); } } else { this.key = "" + this.key; // Convert to string (#217) } // Fix tree.activeNode // TODO: not elegant: we use obj.active as marker to set tree.activeNode // when loading from a dictionary. if(obj.active){ _assert(this.tree.activeNode === null, "only one active node allowed"); this.tree.activeNode = this; } if( obj.selected ){ // #186 this.tree.lastSelectedNode = this; } // TODO: handle obj.focus = true // Create child nodes cl = obj.children; if( cl ){ if( cl.length ){ this._setChildren(cl); } else { // if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded' this.children = this.lazy ? [] : null; } } else { this.children = null; } // Add to key/ref map (except for root node) // if( parent ) { this.tree._callHook("treeRegisterNode", this.tree, true, this); // } } FancytreeNode.prototype = /** @lends FancytreeNode# */{ /* Return the direct child FancytreeNode with a given key, index. */ _findDirectChild: function(ptr){ var i, l, cl = this.children; if(cl){ if(typeof ptr === "string"){ for(i=0, l=cl.length; i<l; i++){ if(cl[i].key === ptr){ return cl[i]; } } }else if(typeof ptr === "number"){ return this.children[ptr]; }else if(ptr.parent === this){ return ptr; } } return null; }, // TODO: activate() // TODO: activateSilently() /* Internal helper called in recursive addChildren sequence.*/ _setChildren: function(children){ _assert(children && (!this.children || this.children.length === 0), "only init supported"); this.children = []; for(var i=0, l=children.length; i<l; i++){ this.children.push(new FancytreeNode(this, children[i])); } }, /** * Append (or insert) a list of child nodes. * * @param {NodeData[]} children array of child node definitions (also single child accepted) * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such). * If omitted, the new children are appended. * @returns {FancytreeNode} first child added * * @see FancytreeNode#applyPatch */ addChildren: function(children, insertBefore){ var i, l, pos, origFirstChild = this.getFirstChild(), origLastChild = this.getLastChild(), firstNode = null, nodeList = []; if($.isPlainObject(children) ){ children = [children]; } if(!this.children){ this.children = []; } for(i=0, l=children.length; i<l; i++){ nodeList.push(new FancytreeNode(this, children[i])); } firstNode = nodeList[0]; if(insertBefore == null){ this.children = this.children.concat(nodeList); }else{ // Returns null if insertBefore is not a direct child: insertBefore = this._findDirectChild(insertBefore); pos = $.inArray(insertBefore, this.children); _assert(pos >= 0, "insertBefore must be an existing child"); // insert nodeList after children[pos] this.children.splice.apply(this.children, [pos, 0].concat(nodeList)); } if ( origFirstChild && !insertBefore ) { // #708: Fast path -- don't render every child of root, just the new ones! // #723, #729: but only if it's appended to an existing child list for(i=0, l=nodeList.length; i<l; i++) { nodeList[i].render(); // New nodes were never rendered before } // Adjust classes where status may have changed // Has a first child if (origFirstChild !== this.getFirstChild()) { // Different first child -- recompute classes origFirstChild.renderStatus(); } if (origLastChild !== this.getLastChild()) { // Different last child -- recompute classes origLastChild.renderStatus(); } } else if( !this.parent || this.parent.ul || this.tr ){ // render if the parent was rendered (or this is a root node) this.render(); } if( this.tree.options.selectMode === 3 ){ this.fixSelection3FromEndNodes(); } this.triggerModifyChild("add", nodeList.length === 1 ? nodeList[0] : null); return firstNode; }, /** * Add class to node's span tag and to .extraClasses. * * @param {string} className class name * * @since 2.17 */ addClass: function(className){ return this.toggleClass(className, true); }, /** * Append or prepend a node, or append a child node. * * This a convenience function that calls addChildren() * * @param {NodeData} node node definition * @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child') * @returns {FancytreeNode} new node */ addNode: function(node, mode){ if(mode === undefined || mode === "over"){ mode = "child"; } switch(mode){ case "after": return this.getParent().addChildren(node, this.getNextSibling()); case "before": return this.getParent().addChildren(node, this); case "firstChild": // Insert before the first child if any var insertBefore = (this.children ? this.children[0] : null); return this.addChildren(node, insertBefore); case "child": case "over": return this.addChildren(node); } _assert(false, "Invalid mode: " + mode); }, /**Add child status nodes that indicate 'More...', etc. * * This also maintains the node's `partload` property. * @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes. * @param {string} [mode='child'] 'child'|firstChild' * @since 2.15 */ addPagingNode: function(node, mode){ var i, n; mode = mode || "child"; if( node === false ) { for(i=this.children.length-1; i >= 0; i--) { n = this.children[i]; if( n.statusNodeType === "paging" ) { this.removeChild(n); } } this.partload = false; return; } node = $.extend({ title: this.tree.options.strings.moreData, statusNodeType: "paging", icon: false }, node); this.partload = true; return this.addNode(node, mode); }, /** * Append new node after this. * * This a convenience function that calls addNode(node, 'after') * * @param {NodeData} node node definition * @returns {FancytreeNode} new node */ appendSibling: function(node){ return this.addNode(node, "after"); }, /** * Modify existing child nodes. * * @param {NodePatch} patch * @returns {$.Promise} * @see FancytreeNode#addChildren */ applyPatch: function(patch) { // patch [key, null] means 'remove' if(patch === null){ this.remove(); return _getResolvedPromise(this); } // TODO: make sure that root node is not collapsed or modified // copy (most) attributes to node.ATTR or node.data.ATTR var name, promise, v, IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global for(name in patch){ v = patch[name]; if( !IGNORE_MAP[name] && !$.isFunction(v)){ if(NODE_ATTR_MAP[name]){ this[name] = v; }else{ this.data[name] = v; } } } // Remove and/or create children if(patch.hasOwnProperty("children")){ this.removeChildren(); if(patch.children){ // only if not null and not empty list // TODO: addChildren instead? this._setChildren(patch.children); } // TODO: how can we APPEND or INSERT child nodes? } if(this.isVisible()){ this.renderTitle(); this.renderStatus(); } // Expand collapse (final step, since this may be async) if(patch.hasOwnProperty("expanded")){ promise = this.setExpanded(patch.expanded); }else{ promise = _getResolvedPromise(this); } return promise; }, /** Collapse all sibling nodes. * @returns {$.Promise} */ collapseSiblings: function() { return this.tree._callHook("nodeCollapseSiblings", this); }, /** Copy this node as sibling or child of `node`. * * @param {FancytreeNode} node source node * @param {string} [mode=child] 'before' | 'after' | 'child' * @param {Function} [map] callback function(NodeData) that could modify the new node * @returns {FancytreeNode} new */ copyTo: function(node, mode, map) { return node.addNode(this.toDict(true, map), mode); }, /** Count direct and indirect children. * * @param {boolean} [deep=true] pass 'false' to only count direct children * @returns {int} number of child nodes */ countChildren: function(deep) { var cl = this.children, i, l, n; if( !cl ){ return 0; } n = cl.length; if(deep !== false){ for(i=0, l=n; i<l; i++){ n += cl[i].countChildren(); } } return n; }, // TODO: deactivate() /** Write to browser console if debugLevel >= 4 (prepending node info) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.tree.options.debugLevel >= 4 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, /** Deprecated. * @deprecated since 2014-02-16. Use resetLazy() instead. */ discard: function(){ this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."); return this.resetLazy(); }, /** Remove DOM elements for all descendents. May be called on .collapse event * to keep the DOM small. * @param {boolean} [includeSelf=false] */ discardMarkup: function(includeSelf){ var fn = includeSelf ? "nodeRemoveMarkup" : "nodeRemoveChildMarkup"; this.tree._callHook(fn, this); }, /** Write error to browser console if debugLevel >= 1 (prepending tree info) * * @param {*} msg string or object or array of such */ error: function(msg){ if( this.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("error", arguments); } }, /**Find all nodes that match condition (excluding self). * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) */ findAll: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = []; this.visit(function(n){ if(match(n)){ res.push(n); } }); return res; }, /**Find first node that matches condition (excluding self). * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @see FancytreeNode#findAll */ findFirst: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = null; this.visit(function(n){ if(match(n)){ res = n; return false; } }); return res; }, /* Apply selection state (internal use only) */ _changeSelectStatusAttrs: function(state) { var changed = false, opts = this.tree.options, unselectable = FT.evalOption("unselectable", this, this, opts, false), unselectableStatus = FT.evalOption("unselectableStatus", this, this, opts, undefined); if( unselectable && unselectableStatus != null ) { state = unselectableStatus; } switch(state){ case false: changed = ( this.selected || this.partsel ); this.selected = false; this.partsel = false; break; case true: changed = ( !this.selected || !this.partsel ); this.selected = true; this.partsel = true; break; case undefined: changed = ( this.selected || !this.partsel ); this.selected = false; this.partsel = true; break; default: _assert(false, "invalid state: " + state); } // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed); if( changed ){ this.renderStatus(); } return changed; }, /** * Fix selection status, after this node was (de)selected in multi-hier mode. * This includes (de)selecting all children. */ fixSelection3AfterClick: function(callOpts) { var flag = this.isSelected(); // this.debug("fixSelection3AfterClick()"); this.visit(function(node){ node._changeSelectStatusAttrs(flag); }); this.fixSelection3FromEndNodes(callOpts); }, /** * Fix selection status for multi-hier mode. * Only end-nodes are considered to update the descendants branch and parents. * Should be called after this node has loaded new children or after * children have been modified using the API. */ fixSelection3FromEndNodes: function(callOpts) { var opts = this.tree.options; // this.debug("fixSelection3FromEndNodes()"); _assert(opts.selectMode === 3, "expected selectMode 3"); // Visit all end nodes and adjust their parent's `selected` and `partsel` // attributes. Return selection state true, false, or undefined. function _walk(node){ var i, l, child, s, state, allSelected, someSelected, unselIgnore, unselState, children = node.children; if( children && children.length ){ // check all children recursively allSelected = true; someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // the selection state of a node is not relevant; we need the end-nodes s = _walk(child); // if( !child.unselectableIgnore ) { unselIgnore = FT.evalOption("unselectableIgnore", child, child, opts, false); if( !unselIgnore ) { if( s !== false ) { someSelected = true; } if( s !== true ) { allSelected = false; } } } state = allSelected ? true : (someSelected ? undefined : false); }else{ // This is an end-node: simply report the status unselState = FT.evalOption("unselectableStatus", node, node, opts, undefined); state = ( unselState == null ) ? !!node.selected : !!unselState; } node._changeSelectStatusAttrs(state); return state; } _walk(this); // Update parent's state this.visitParents(function(node){ var i, l, child, state, unselIgnore, unselState, children = node.children, allSelected = true, someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; unselIgnore = FT.evalOption("unselectableIgnore", child, child, opts, false); if( !unselIgnore ) { unselState = FT.evalOption("unselectableStatus", child, child, opts, undefined); state = ( unselState == null ) ? !!child.selected : !!unselState; // When fixing the parents, we trust the sibling status (i.e. // we don't recurse) if( state || child.partsel ) { someSelected = true; } if( !state ) { allSelected = false; } } } state = allSelected ? true : (someSelected ? undefined : false); node._changeSelectStatusAttrs(state); }); }, // TODO: focus() /** * Update node data. If dict contains 'children', then also replace * the hole sub tree. * @param {NodeData} dict * * @see FancytreeNode#addChildren * @see FancytreeNode#applyPatch */ fromDict: function(dict) { // copy all other attributes to this.data.xxx for(var name in dict){ if(NODE_ATTR_MAP[name]){ // node.NAME = dict.NAME this[name] = dict[name]; }else if(name === "data"){ // node.data += dict.data $.extend(this.data, dict.data); }else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = dict.NAME this.data[name] = dict[name]; } } if(dict.children){ // recursively set children and render this.removeChildren(); this.addChildren(dict.children); } this.renderTitle(); /* var children = dict.children; if(children === undefined){ this.data = $.extend(this.data, dict); this.render(); return; } dict = $.extend({}, dict); dict.children = undefined; this.data = $.extend(this.data, dict); this.removeChildren(); this.addChild(children); */ }, /** Return the list of child nodes (undefined for unexpanded lazy nodes). * @returns {FancytreeNode[] | undefined} */ getChildren: function() { if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes? return undefined; // Lazy node: unloaded, currently loading, or load error } return this.children; }, /** Return the first child node or null. * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.children ? this.children[0] : null; }, /** Return the 0-based child index. * @returns {int} */ getIndex: function() { // return this.parent.children.indexOf(this); return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7 }, /** Return the hierarchical child index (1-based, e.g. '3.2.4'). * @param {string} [separator="."] * @param {int} [digits=1] * @returns {string} */ getIndexHier: function(separator, digits) { separator = separator || "."; var s, res = []; $.each(this.getParentList(false, true), function(i, o){ s = "" + (o.getIndex() + 1); if( digits ){ // prepend leading zeroes s = ("0000000" + s).substr(-digits); } res.push(s); }); return res.join(separator); }, /** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32". * @param {boolean} [excludeSelf=false] * @returns {string} */ getKeyPath: function(excludeSelf) { var path = [], sep = this.tree.options.keyPathSeparator; this.visitParents(function(n){ if(n.parent){ path.unshift(n.key); } }, !excludeSelf); return sep + path.join(sep); }, /** Return the last child of this node or null. * @returns {FancytreeNode | null} */ getLastChild: function() { return this.children ? this.children[this.children.length - 1] : null; }, /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... . * @returns {int} */ getLevel: function() { var level = 0, dtn = this.parent; while( dtn ) { level++; dtn = dtn.parent; } return level; }, /** Return the successor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getNextSibling: function() { // TODO: use indexOf, if available: (not in IE6) if( this.parent ){ var i, l, ac = this.parent.children; for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null if( ac[i] === this ){ return ac[i+1]; } } } return null; }, /** Return the parent node (null for the system root node). * @returns {FancytreeNode | null} */ getParent: function() { // TODO: return null for top-level nodes? return this.parent; }, /** Return an array of all parent nodes (top-down). * @param {boolean} [includeRoot=false] Include the invisible system root node. * @param {boolean} [includeSelf=false] Include the node itself. * @returns {FancytreeNode[]} */ getParentList: function(includeRoot, includeSelf) { var l = [], dtn = includeSelf ? this : this.parent; while( dtn ) { if( includeRoot || dtn.parent ){ l.unshift(dtn); } dtn = dtn.parent; } return l; }, /** Return the predecessor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getPrevSibling: function() { if( this.parent ){ var i, l, ac = this.parent.children; for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null if( ac[i] === this ){ return ac[i-1]; } } } return null; }, /** * Return an array of selected descendant nodes. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { var nodeList = []; this.visit(function(node){ if( node.selected ) { nodeList.push(node); if( stopOnParents === true ){ return "skip"; // stop processing this branch } } }); return nodeList; }, /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded). * @returns {boolean | undefined} */ hasChildren: function() { if(this.lazy){ if(this.children == null ){ // null or undefined: Not yet loaded return undefined; }else if(this.children.length === 0){ // Loaded, but response was empty return false; }else if(this.children.length === 1 && this.children[0].isStatusNode() ){ // Currently loading or load error return undefined; } return true; } return !!( this.children && this.children.length ); }, /** Return true if node has keyboard focus. * @returns {boolean} */ hasFocus: function() { return (this.tree.hasFocus() && this.tree.focusNode === this); }, /** Write to browser console if debugLevel >= 3 (prepending node info) * * @param {*} msg string or object or array of such */ info: function(msg){ if( this.tree.options.debugLevel >= 3 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /** Return true if node is active (see also FancytreeNode#isSelected). * @returns {boolean} */ isActive: function() { return (this.tree.activeNode === this); }, /** Return true if node is vertically below `otherNode`, i.e. rendered in a subsequent row. * @param {FancytreeNode} otherNode * @returns {boolean} * @since 2.28 */ isBelowOf: function(otherNode) { return (this.getIndexHier(".", 5) > otherNode.getIndexHier(".", 5)); }, /** Return true if node is a direct child of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isChildOf: function(otherNode) { return (this.parent && this.parent === otherNode); }, /** Return true, if node is a direct or indirect sub node of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isDescendantOf: function(otherNode) { if(!otherNode || otherNode.tree !== this.tree){ return false; } var p = this.parent; while( p ) { if( p === otherNode ){ return true; } if( p === p.parent ) { $.error("Recursive parent link: " + p); } p = p.parent; } return false; }, /** Return true if node is expanded. * @returns {boolean} */ isExpanded: function() { return !!this.expanded; }, /** Return true if node is the first node of its parent's children. * @returns {boolean} */ isFirstSibling: function() { var p = this.parent; return !p || p.children[0] === this; }, /** Return true if node is a folder, i.e. has the node.folder attribute set. * @returns {boolean} */ isFolder: function() { return !!this.folder; }, /** Return true if node is the last node of its parent's children. * @returns {boolean} */ isLastSibling: function() { var p = this.parent; return !p || p.children[p.children.length-1] === this; }, /** Return true if node is lazy (even if data was already loaded) * @returns {boolean} */ isLazy: function() { return !!this.lazy; }, /** Return true if node is lazy and loaded. For non-lazy nodes always return true. * @returns {boolean} */ isLoaded: function() { return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node }, /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending. * @returns {boolean} */ isLoading: function() { return !!this._isLoading; }, /* * @deprecated since v2.4.0: Use isRootNode() instead */ isRoot: function() { return this.isRootNode(); }, /** Return true if node is partially selected (tri-state). * @returns {boolean} * @since 2.23 */ isPartsel: function() { return !this.selected && !!this.partsel; }, /** (experimental) Return true if this is partially loaded. * @returns {boolean} * @since 2.15 */ isPartload: function() { return !!this.partload; }, /** Return true if this is the (invisible) system root node. * @returns {boolean} * @since 2.4 */ isRootNode: function() { return (this.tree.rootNode === this); }, /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive). * @returns {boolean} */ isSelected: function() { return !!this.selected; }, /** Return true if this node is a temporarily generated system node like * 'loading', 'paging', or 'error' (node.statusNodeType contains the type). * @returns {boolean} */ isStatusNode: function() { return !!this.statusNodeType; }, /** Return true if this node is a status node of type 'paging'. * @returns {boolean} * @since 2.15 */ isPagingNode: function() { return this.statusNodeType === "paging"; }, /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node. * @returns {boolean} * @since 2.4 */ isTopLevel: function() { return (this.tree.rootNode === this.parent); }, /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false. * @returns {boolean} */ isUndefined: function() { return this.hasChildren() === undefined; // also checks if the only child is a status node }, /** Return true if all parent nodes are expanded. Note: this does not check * whether the node is scrolled into the visible part of the screen. * @returns {boolean} */ isVisible: function() { var i, l, parents = this.getParentList(false, false); for(i=0, l=parents.length; i<l; i++){ if( ! parents[i].expanded ){ return false; } } return true; }, /** Deprecated. * @deprecated since 2014-02-16: use load() instead. */ lazyLoad: function(discard) { this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."); return this.load(discard); }, /** * Load all children of a lazy node if neccessary. The <i>expanded</i> state is maintained. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. Otherwise this method does nothing if the node was already loaded. * @returns {$.Promise} */ load: function(forceReload) { var res, source, that = this, wasExpanded = this.isExpanded(); _assert( this.isLazy(), "load() requires a lazy node" ); // _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" ); if( !forceReload && !this.isUndefined() ) { return _getResolvedPromise(this); } if( this.isLoaded() ){ this.resetLazy(); // also collapses } // This method is also called by setExpanded() and loadKeyPath(), so we // have to avoid recursion. source = this.tree._triggerNodeEvent("lazyLoad", this); if( source === false ) { // #69 return _getResolvedPromise(this); } _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); res = this.tree._callHook("nodeLoadChildren", this, source); if( wasExpanded ) { this.expanded = true; res.always(function(){ that.render(); }); } else { res.always(function(){ that.renderStatus(); // fix expander icon to 'loaded' }); } return res; }, /** Expand all parents and optionally scroll into visible area as neccessary. * Promise is resolved, when lazy loading and animations are done. * @param {object} [opts] passed to `setExpanded()`. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true} * @returns {$.Promise} */ makeVisible: function(opts) { var i, that = this, deferreds = [], dfd = new $.Deferred(), parents = this.getParentList(false, false), len = parents.length, effects = !(opts && opts.noAnimation === true), scroll = !(opts && opts.scrollIntoView === false); // Expand bottom-up, so only the top node is animated for(i = len - 1; i >= 0; i--){ // that.debug("pushexpand" + parents[i]); deferreds.push(parents[i].setExpanded(true, opts)); } $.when.apply($, deferreds).done(function(){ // All expands have finished // that.debug("expand DONE", scroll); if( scroll ){ that.scrollIntoView(effects).done(function(){ // that.debug("scroll DONE"); dfd.resolve(); }); } else { dfd.resolve(); } }); return dfd.promise(); }, /** Move this node to targetNode. * @param {FancytreeNode} targetNode * @param {string} mode <pre> * 'child': append this node as last child of targetNode. * This is the default. To be compatble with the D'n'd * hitMode, we also accept 'over'. * 'firstChild': add this node as first child of targetNode. * 'before': add this node as sibling before targetNode. * 'after': add this node as sibling after targetNode.</pre> * @param {function} [map] optional callback(FancytreeNode) to allow modifcations */ moveTo: function(targetNode, mode, map) { if(mode === undefined || mode === "over"){ mode = "child"; } else if ( mode === "firstChild" ) { if( targetNode.children && targetNode.children.length ) { mode = "before"; targetNode = targetNode.children[0]; } else { mode = "child"; } } var pos, prevParent = this.parent, targetParent = (mode === "child") ? targetNode : targetNode.parent; if(this === targetNode){ return; }else if( !this.parent ){ $.error("Cannot move system root"); }else if( targetParent.isDescendantOf(this) ){ $.error("Cannot move a node to its own descendant"); } if( targetParent !== prevParent ) { prevParent.triggerModifyChild("remove", this); } // Unlink this node from current parent if( this.parent.children.length === 1 ) { if( this.parent === targetParent ){ return; // #258 } this.parent.children = this.parent.lazy ? [] : null; this.parent.expanded = false; } else { pos = $.inArray(this, this.parent.children); _assert(pos >= 0, "invalid source parent"); this.parent.children.splice(pos, 1); } // Remove from source DOM parent // if(this.parent.ul){ // this.parent.ul.removeChild(this.li); // } // Insert this node to target parent's child list this.parent = targetParent; if( targetParent.hasChildren() ) { switch(mode) { case "child": // Append to existing target children targetParent.children.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0, "invalid target parent"); targetParent.children.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0, "invalid target parent"); targetParent.children.splice(pos+1, 0, this); break; default: $.error("Invalid mode " + mode); } } else { targetParent.children = [ this ]; } // Parent has no <ul> tag yet: // if( !targetParent.ul ) { // // This is the parent's first child: create UL tag // // (Hidden, because it will be // targetParent.ul = document.createElement("ul"); // targetParent.ul.style.display = "none"; // targetParent.li.appendChild(targetParent.ul); // } // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded)) // if(this.li){ // targetParent.ul.appendChild(this.li); // }^ // Let caller modify the nodes if( map ){ targetNode.visit(map, true); } if( targetParent === prevParent ) { targetParent.triggerModifyChild("move", this); } else { // prevParent.triggerModifyChild("remove", this); targetParent.triggerModifyChild("add", this); } // Handle cross-tree moves if( this.tree !== targetNode.tree ) { // Fix node.tree for all source nodes // _assert(false, "Cross-tree move is not yet implemented."); this.warn("Cross-tree moveTo is experimantal!"); this.visit(function(n){ // TODO: fix selection state and activation, ... n.tree = targetNode.tree; }, true); } // A collaposed node won't re-render children, so we have to remove it manually // if( !targetParent.expanded ){ // prevParent.ul.removeChild(this.li); // } // Update HTML markup if( !prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) { targetParent.render(); } // TODO: fix selection state // TODO: fix active state /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel()); if ( opts.minExpandLevel >= ftnode.getLevel() ) { // tree.logDebug ("Force expand for %o", ftnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // DT issue #82: only if not initializing, because the children may not exist yet // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing ) // ftnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( ftnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return ftnode; */ }, /** Set focus relative to this node and optionally activate. * * @param {number} where The keyCode that would normally trigger this move, * e.g. `$.ui.keyCode.LEFT` would collapse the node if it * is expanded or move to the parent oterwise. * @param {boolean} [activate=true] * @returns {$.Promise} */ navigate: function(where, activate) { var i, parents, res, handled = true, KC = $.ui.keyCode, sib = null; // Navigate to node function _goto(n){ if( n ){ // setFocus/setActive will scroll later (if autoScroll is specified) try { n.makeVisible({scrollIntoView: false}); } catch(e) {} // #272 // Node may still be hidden by a filter if( ! $(n.span).is(":visible") ) { n.debug("Navigate: skipping hidden node"); n.navigate(where, activate); return; } return activate === false ? n.setFocus() : n.setActive(); } } switch( where ) { case KC.BACKSPACE: if( this.parent && this.parent.parent ) { res = _goto(this.parent); } break; case KC.HOME: this.tree.visit(function(n){ // goto first visible node if( $(n.span).is(":visible") ) { res = _goto(n); return false; } }); break; case KC.END: this.tree.visit(function(n){ // goto last visible node if( $(n.span).is(":visible") ) { res = n; } }); if( res ) { res = _goto(res); } break; case KC.LEFT: if( this.expanded ) { this.setExpanded(false); res = _goto(this); } else if( this.parent && this.parent.parent ) { res = _goto(this.parent); } break; case KC.RIGHT: if( !this.expanded && (this.children || this.lazy) ) { this.setExpanded(); res = _goto(this); } else if( this.children && this.children.length ) { res = _goto(this.children[0]); } break; case KC.UP: sib = this.getPrevSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getPrevSibling(); } while( sib && sib.expanded && sib.children && sib.children.length ) { sib = sib.children[sib.children.length - 1]; } if( !sib && this.parent && this.parent.parent ){ sib = this.parent; } res = _goto(sib); break; case KC.DOWN: if( this.expanded && this.children && this.children.length ) { sib = this.children[0]; } else { parents = this.getParentList(false, true); for(i=parents.length-1; i>=0; i--) { sib = parents[i].getNextSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getNextSibling(); } if( sib ){ break; } } } res = _goto(sib); break; default: handled = false; } return res || _getResolvedPromise(); }, /** * Remove this node (not allowed for system root). */ remove: function() { return this.parent.removeChild(this); }, /** * Remove childNode from list of direct children. * @param {FancytreeNode} childNode */ removeChild: function(childNode) { return this.tree._callHook("nodeRemoveChild", this, childNode); }, /** * Remove all child nodes and descendents. This converts the node into a leaf.<br> * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy() * in order to trigger lazyLoad on next expand. */ removeChildren: function() { return this.tree._callHook("nodeRemoveChildren", this); }, /** * Remove class from node's span tag and .extraClasses. * * @param {string} className class name * * @since 2.17 */ removeClass: function(className){ return this.toggleClass(className, false); }, /** * This method renders and updates all HTML markup that is required * to display this node in its current state.<br> * Note: * <ul> * <li>It should only be neccessary to call this method after the node object * was modified by direct access to its properties, because the common * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...) * already handle this. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus} * are implied. If changes are more local, calling only renderTitle() or * renderStatus() may be sufficient and faster. * </ul> * * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed */ render: function(force, deep) { return this.tree._callHook("nodeRender", this, force, deep); }, /** Create HTML markup for the node's outer &lt;span> (expander, checkbox, icon, and title). * Implies {@link FancytreeNode#renderStatus}. * @see Fancytree_Hooks#nodeRenderTitle */ renderTitle: function() { return this.tree._callHook("nodeRenderTitle", this); }, /** Update element's CSS classes according to node state. * @see Fancytree_Hooks#nodeRenderStatus */ renderStatus: function() { return this.tree._callHook("nodeRenderStatus", this); }, /** * (experimental) Replace this node with `source`. * (Currently only available for paging nodes.) * @param {NodeData[]} source List of child node definitions * @since 2.15 */ replaceWith: function(source) { var res, parent = this.parent, pos = $.inArray(this, parent.children), that = this; _assert( this.isPagingNode(), "replaceWith() currently requires a paging status node" ); res = this.tree._callHook("nodeLoadChildren", this, source); res.done(function(data){ // New nodes are currently children of `this`. var children = that.children; // Prepend newly loaded child nodes to `this` // Move new children after self for( i=0; i<children.length; i++ ) { children[i].parent = parent; } parent.children.splice.apply(parent.children, [pos + 1, 0].concat(children)); // Remove self that.children = null; that.remove(); // Redraw new nodes parent.render(); // TODO: set node.partload = false if this was tha last paging node? // parent.addPagingNode(false); }).fail(function(){ that.setExpanded(); }); return res; // $.error("Not implemented: replaceWith()"); }, /** * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad * event is triggered on next expand. */ resetLazy: function() { this.removeChildren(); this.expanded = false; this.lazy = true; this.children = undefined; this.renderStatus(); }, /** Schedule activity for delayed execution (cancel any pending request). * scheduleAction('cancel') will only cancel a pending request (if any). * @param {string} mode * @param {number} ms */ scheduleAction: function(mode, ms) { if( this.tree.timer ) { clearTimeout(this.tree.timer); // this.tree.debug("clearTimeout(%o)", this.tree.timer); } this.tree.timer = null; var self = this; // required for closures switch (mode) { case "cancel": // Simply made sure that timer was cleared break; case "expand": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger expand"); self.setExpanded(true); }, ms); break; case "activate": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger activate"); self.setActive(true); }, ms); break; default: $.error("Invalid mode " + mode); } // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer); }, /** * * @param {boolean | PlainObject} [effects=false] animation options. * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in * any case, even if `this` is outside the scroll pane. * @returns {$.Promise} */ scrollIntoView: function(effects, options) { if( options !== undefined && _isNode(options) ) { this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."); options = {topNode: options}; } // this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent); // this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container; var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop, opts = $.extend({ effects: (effects === true) ? {duration: 200, queue: false} : effects, scrollOfs: this.tree.options.scrollOfs, scrollParent: this.tree.options.scrollParent || this.tree.$container, topNode: null }, options), dfd = new $.Deferred(), that = this, nodeHeight = $(this.span).height(), $container = $(opts.scrollParent), topOfs = opts.scrollOfs.top || 0, bottomOfs = opts.scrollOfs.bottom || 0, containerHeight = $container.height(),// - topOfs - bottomOfs, scrollTop = $container.scrollTop(), $animateTarget = $container, isParentWindow = $container[0] === window, topNode = opts.topNode || null, newScrollTop = null; // this.debug("scrollIntoView(), scrollTop=" + scrollTop, opts.scrollOfs); // _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets if( !$(this.span).is(":visible") ) { // We cannot calc offsets for hidden elements this.warn("scrollIntoView(): node is invisible."); return _getResolvedPromise(); } if( isParentWindow ) { nodeY = $(this.span).offset().top; topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0; $animateTarget = $("html,body"); } else { _assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be a simple element or `window`, not document or body."); containerOffsetTop = $container.offset().top, nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0; horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight)); containerHeight -= horzScrollbarHeight; } // this.debug(" scrollIntoView(), nodeY=" + nodeY + ", containerHeight=" + containerHeight); if( nodeY < (scrollTop + topOfs) ){ // Node is above visible container area newScrollTop = nodeY - topOfs; // this.debug(" scrollIntoView(), UPPER newScrollTop=" + newScrollTop); }else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){ newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs; // this.debug(" scrollIntoView(), LOWER newScrollTop=" + newScrollTop); // If a topNode was passed, make sure that it is never scrolled // outside the upper border if(topNode){ _assert(topNode.isRootNode() || $(topNode.span).is(":visible"), "topNode must be visible"); if( topNodeY < newScrollTop ){ newScrollTop = topNodeY - topOfs; // this.debug(" scrollIntoView(), TOP newScrollTop=" + newScrollTop); } } } if(newScrollTop !== null){ // this.debug(" scrollIntoView(), SET newScrollTop=" + newScrollTop); if(opts.effects){ opts.effects.complete = function(){ dfd.resolveWith(that); }; $animateTarget.stop(true).animate({ scrollTop: newScrollTop }, opts.effects); }else{ $animateTarget[0].scrollTop = newScrollTop; dfd.resolveWith(this); } }else{ dfd.resolveWith(this); } return dfd.promise(); }, /**Activate this node. * @param {boolean} [flag=true] pass false to deactivate * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false} * @returns {$.Promise} */ setActive: function(flag, opts){ return this.tree._callHook("nodeSetActive", this, flag, opts); }, /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done. * @param {boolean} [flag=true] pass false to collapse * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} */ setExpanded: function(flag, opts){ return this.tree._callHook("nodeSetExpanded", this, flag, opts); }, /**Set keyboard focus to this node. * @param {boolean} [flag=true] pass false to blur * @see Fancytree#setFocus */ setFocus: function(flag){ return this.tree._callHook("nodeSetFocus", this, flag); }, /**Select this node, i.e. check the checkbox. * @param {boolean} [flag=true] pass false to deselect * @param {object} [opts] additional options. Defaults to {noEvents: false, p * propagateDown: null, propagateUp: null, callback: null } */ setSelected: function(flag, opts){ return this.tree._callHook("nodeSetSelected", this, flag, opts); }, /**Mark a lazy node as 'error', 'loading', 'nodata', or 'ok'. * @param {string} status 'error'|'empty'|'ok' * @param {string} [message] * @param {string} [details] */ setStatus: function(status, message, details){ return this.tree._callHook("nodeSetStatus", this, status, message, details); }, /**Rename this node. * @param {string} title */ setTitle: function(title){ this.title = title; this.renderTitle(); this.triggerModify("rename"); }, /**Sort child list by title. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title). * @param {boolean} [deep=false] pass true to sort all descendant nodes */ sortChildren: function(cmp, deep) { var i,l, cl = this.children; if( !cl ){ return; } cmp = cmp || function(a, b) { var x = a.title.toLowerCase(), y = b.title.toLowerCase(); return x === y ? 0 : x > y ? 1 : -1; }; cl.sort(cmp); if( deep ){ for(i=0, l=cl.length; i<l; i++){ if( cl[i].children ){ cl[i].sortChildren(cmp, "$norender$"); } } } if( deep !== "$norender$" ){ this.render(); } this.triggerModifyChild("sort"); }, /** Convert node (or whole branch) into a plain object. * * The result is compatible with node.addChildren(). * * @param {boolean} [recursive=false] include child nodes * @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications * @returns {NodeData} */ toDict: function(recursive, callback) { var i, l, node, dict = {}, self = this; $.each(NODE_ATTRS, function(i, a){ if(self[a] || self[a] === false){ dict[a] = self[a]; } }); if(!$.isEmptyObject(this.data)){ dict.data = $.extend({}, this.data); if($.isEmptyObject(dict.data)){ delete dict.data; } } if( callback ){ callback(dict, self); } if( recursive ) { if(this.hasChildren()){ dict.children = []; for(i=0, l=this.children.length; i<l; i++ ){ node = this.children[i]; if( !node.isStatusNode() ){ dict.children.push(node.toDict(true, callback)); } } }else{ // dict.children = null; } } return dict; }, /** * Set, clear, or toggle class of node's span tag and .extraClasses. * * @param {string} className class name (separate multiple classes by space) * @param {boolean} [flag] true/false to add/remove class. If omitted, class is toggled. * @returns {boolean} true if a class was added * * @since 2.17 */ toggleClass: function(value, flag){ var className, hasClass, rnotwhite = ( /\S+/g ), classNames = value.match( rnotwhite ) || [], i = 0, wasAdded = false, statusElem = this[this.tree.statusClassPropName], curClasses = (" " + (this.extraClasses || "") + " "); // this.info("toggleClass('" + value + "', " + flag + ")", curClasses); // Modify DOM element directly if it already exists if( statusElem ) { $(statusElem).toggleClass(value, flag); } // Modify node.extraClasses to make this change persistent // Toggle if flag was not passed while ( className = classNames[ i++ ] ) { hasClass = curClasses.indexOf(" " + className + " ") >= 0; flag = (flag === undefined) ? (!hasClass) : !!flag; if ( flag ) { if( !hasClass ) { curClasses += className + " "; wasAdded = true; } } else { while ( curClasses.indexOf( " " + className + " " ) > -1 ) { curClasses = curClasses.replace( " " + className + " ", " " ); } } } this.extraClasses = $.trim(curClasses); // this.info("-> toggleClass('" + value + "', " + flag + "): '" + this.extraClasses + "'"); return wasAdded; }, /** Flip expanded status. */ toggleExpanded: function(){ return this.tree._callHook("nodeToggleExpanded", this); }, /** Flip selection status. */ toggleSelected: function(){ return this.tree._callHook("nodeToggleSelected", this); }, toString: function() { return "FancytreeNode@" + this.key + "[title='" + this.title + "']"; // return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>"; }, /** * Trigger `modifyChild` event on a parent to signal that a child was modified. * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ... * @param {FancytreeNode} [childNode] * @param {object} [extra] */ triggerModifyChild: function(operation, childNode, extra){ var data, modifyChild = this.tree.options.modifyChild; if ( modifyChild ){ if( childNode && childNode.parent !== this ) { $.error("childNode " + childNode + " is not a child of " + this); } data = { node: this, tree: this.tree, operation: operation, childNode: childNode || null }; if( extra ) { $.extend(data, extra); } modifyChild({type: "modifyChild"}, data); } }, /** * Trigger `modifyChild` event on node.parent(!). * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ... * @param {object} [extra] */ triggerModify: function(operation, extra){ this.parent.triggerModifyChild(operation, this, extra); }, /** Call fn(node) for all child nodes in hierarchical order (depth-first).<br> * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visit: function(fn, includeSelf) { var i, l, res = true, children = this.children; if( includeSelf === true ) { res = fn(this); if( res === false || res === "skip" ){ return res; } } if(children){ for(i=0, l=children.length; i<l; i++){ res = children[i].visit(fn, true); if( res === false ){ break; } } } return res; }, /** Call fn(node) for all child nodes and recursively load lazy children.<br> * <b>Note:</b> If you need this method, you probably should consider to review * your architecture! Recursivley loading nodes is a perfect way for lazy * programmers to flood the server with requests ;-) * * @param {function} [fn] optional callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {$.Promise} * @since 2.4 */ visitAndLoad: function(fn, includeSelf, _recursion) { var dfd, res, loaders, node = this; // node.debug("visitAndLoad"); if( fn && includeSelf === true ) { res = fn(node); if( res === false || res === "skip" ) { return _recursion ? res : _getResolvedPromise(); } } if( !node.children && !node.lazy ) { return _getResolvedPromise(); } dfd = new $.Deferred(); loaders = []; // node.debug("load()..."); node.load().done(function(){ // node.debug("load()... done."); for(var i=0, l=node.children.length; i<l; i++){ res = node.children[i].visitAndLoad(fn, true, true); if( res === false ) { dfd.reject(); break; } else if ( res !== "skip" ) { loaders.push(res); // Add promise to the list } } $.when.apply(this, loaders).then(function(){ dfd.resolve(); }); }); return dfd.promise(); }, /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitParents: function(fn, includeSelf) { // Visit parent nodes (bottom up) if(includeSelf && fn(this) === false){ return false; } var p = this.parent; while( p ) { if(fn(p) === false){ return false; } p = p.parent; } return true; }, /** Call fn(node) for all sibling nodes.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitSiblings: function(fn, includeSelf) { var i, l, n, ac = this.parent.children; for (i=0, l=ac.length; i<l; i++) { n = ac[i]; if ( includeSelf || n !== this ){ if( fn(n) === false ) { return false; } } } return true; }, /** Write warning to browser console if debugLevel >= 2 (prepending node info) * * @param {*} msg string or object or array of such */ warn: function(msg){ if( this.tree.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } } }; /* ***************************************************************************** * Fancytree */ /** * Construct a new tree object. * * @class Fancytree * @classdesc The controller behind a fancytree. * This class also contains 'hook methods': see {@link Fancytree_Hooks}. * * @param {Widget} widget * * @property {string} _id Automatically generated unique tree instance ID, e.g. "1". * @property {string} _ns Automatically generated unique tree namespace, e.g. ".fancytree-1". * @property {FancytreeNode} activeNode Currently active node or null. * @property {string} ariaPropName Property name of FancytreeNode that contains the element which will receive the aria attributes. * Typically "li", but "tr" for table extension. * @property {jQueryObject} $container Outer &lt;ul> element (or &lt;table> element for ext-table). * @property {jQueryObject} $div A jQuery object containing the element used to instantiate the tree widget (`widget.element`) * @property {object|array} columns Recommended place to store shared column meta data. @since 2.27 * @property {object} data Metadata, i.e. properties that may be passed to `source` in addition to a children array. * @property {object} ext Hash of all active plugin instances. * @property {FancytreeNode} focusNode Currently focused node or null. * @property {FancytreeNode} lastSelectedNode Used to implement selectMode 1 (single select) * @property {string} nodeContainerAttrName Property name of FancytreeNode that contains the outer element of single nodes. * Typically "li", but "tr" for table extension. * @property {FancytreeOptions} options Current options, i.e. default options + options passed to constructor. * @property {FancytreeNode} rootNode Invisible system root node. * @property {string} statusClassPropName Property name of FancytreeNode that contains the element which will receive the status classes. * Typically "span", but "tr" for table extension. * @property {object} types Map for shared type specific meta data, used with node.type attribute. @since 2.27 * @property {object} widget Base widget instance. */ function Fancytree(widget) { this.widget = widget; this.$div = widget.element; this.options = widget.options; if( this.options ) { if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) { this.options.lazyLoad = function() { FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."); return widget.options.lazyload.apply(this, arguments); }; } if( $.isFunction(this.options.loaderror) ) { $.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."); } if( this.options.fx !== undefined ) { FT.warn("The 'fx' option was replaced by 'toggleEffect' since 2014-11-30."); } if( this.options.removeNode !== undefined ) { $.error("The 'removeNode' event was replaced by 'modifyChild' since 2.20 (2016-09-10)."); } } this.ext = {}; // Active extension instances this.types = {}; this.columns = {}; // allow to init tree.data.foo from <div data-foo=''> this.data = _getElementDataAsDict(this.$div); // TODO: use widget.uuid instead? this._id = $.ui.fancytree._nextId++; // TODO: use widget.eventNamespace instead? this._ns = ".fancytree-" + this._id; // append for namespaced events this.activeNode = null; this.focusNode = null; this._hasFocus = null; this._tempCache = {}; this._lastMousedownNode = null; this._enableUpdate = true; this.lastSelectedNode = null; this.systemFocusElement = null; this.lastQuicksearchTerm = ""; this.lastQuicksearchTime = 0; this.statusClassPropName = "span"; this.ariaPropName = "li"; this.nodeContainerAttrName = "li"; // Remove previous markup if any this.$div.find(">ul.fancytree-container").remove(); // Create a node without parent. var fakeParent = { tree: this }, $ul; this.rootNode = new FancytreeNode(fakeParent, { title: "root", key: "root_" + this._id, children: null, expanded: true }); this.rootNode.parent = null; // Create root markup $ul = $("<ul>", { "class": "ui-fancytree fancytree-container fancytree-plain" }).appendTo(this.$div); this.$container = $ul; this.rootNode.ul = $ul[0]; if(this.options.debugLevel == null){ this.options.debugLevel = FT.debugLevel; } // // Add container to the TAB chain // // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant // // #577: Allow to set tabindex to "0", "-1" and "" // this.$container.attr("tabindex", this.options.tabindex); // if( this.options.rtl ) { // this.$container.attr("DIR", "RTL").addClass("fancytree-rtl"); // // }else{ // // this.$container.attr("DIR", null).removeClass("fancytree-rtl"); // } // if(this.options.aria){ // this.$container.attr("role", "tree"); // if( this.options.selectMode !== 1 ) { // this.$container.attr("aria-multiselectable", true); // } // } } Fancytree.prototype = /** @lends Fancytree# */{ /* Return a context object that can be re-used for _callHook(). * @param {Fancytree | FancytreeNode | EventData} obj * @param {Event} originalEvent * @param {Object} extra * @returns {EventData} */ _makeHookContext: function(obj, originalEvent, extra) { var ctx, tree; if(obj.node !== undefined){ // obj is already a context object if(originalEvent && obj.originalEvent !== originalEvent){ $.error("invalid args"); } ctx = obj; }else if(obj.tree){ // obj is a FancytreeNode tree = obj.tree; ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent, typeInfo: tree.types[obj.type] || {}}; }else if(obj.widget){ // obj is a Fancytree ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent }; }else{ $.error("invalid args"); } if(extra){ $.extend(ctx, extra); } return ctx; }, /* Trigger a hook function: funcName(ctx, [...]). * * @param {string} funcName * @param {Fancytree|FancytreeNode|EventData} contextObject * @param {any} [_extraArgs] optional additional arguments * @returns {any} */ _callHook: function(funcName, contextObject, _extraArgs) { var ctx = this._makeHookContext(contextObject), fn = this[funcName], args = Array.prototype.slice.call(arguments, 2); if(!$.isFunction(fn)){ $.error("_callHook('" + funcName + "') is not a function"); } args.unshift(ctx); // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args); return fn.apply(this, args); }, _setExpiringValue: function(key, value, ms){ this._tempCache[key] = {value: value, expire: Date.now() + (+ms || 50)}; }, _getExpiringValue: function(key){ var entry = this._tempCache[key]; if( entry && entry.expire > Date.now() ) { return entry.value; } delete this._tempCache[key]; return null; }, /* Check if current extensions dependencies are met and throw an error if not. * * This method may be called inside the `treeInit` hook for custom extensions. * * @param {string} extension name of the required extension * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter) * @param {string} [message] optional error message (defaults to a descriptve error message) */ _requireExtension: function(name, required, before, message) { before = !!before; var thisName = this._local.name, extList = this.options.extensions, isBefore = $.inArray(name, extList) < $.inArray(thisName, extList), isMissing = required && this.ext[name] == null, badOrder = !isMissing && before != null && (before !== isBefore); _assert(thisName && thisName !== name, "invalid or same name"); if( isMissing || badOrder ){ if( !message ){ if( isMissing || required ){ message = "'" + thisName + "' extension requires '" + name + "'"; if( badOrder ){ message += " to be registered " + (before ? "before" : "after") + " itself"; } }else{ message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`"; } } $.error(message); return false; } return true; }, /** Activate node with a given key and fire focus and activate events. * * A previously activated node will be deactivated. * If activeVisible option is set, all parents will be expanded as necessary. * Pass key = false, to deactivate the current node only. * @param {string} key * @returns {FancytreeNode} activated node (null, if not found) */ activateKey: function(key) { var node = this.getNodeByKey(key); if(node){ node.setActive(); }else if(this.activeNode){ this.activeNode.setActive(false); } return node; }, /** (experimental) Add child status nodes that indicate 'More...', .... * @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes. * @param {string} [mode='append'] 'child'|firstChild' * @since 2.15 */ addPagingNode: function(node, mode){ return this.rootNode.addPagingNode(node, mode); }, /** (experimental) Modify existing data model. * * @param {Array} patchList array of [key, NodePatch] arrays * @returns {$.Promise} resolved, when all patches have been applied * @see TreePatch */ applyPatch: function(patchList) { var dfd, i, p2, key, patch, node, patchCount = patchList.length, deferredList = []; for(i=0; i<patchCount; i++){ p2 = patchList[i]; _assert(p2.length === 2, "patchList must be an array of length-2-arrays"); key = p2[0]; patch = p2[1]; node = (key === null) ? this.rootNode : this.getNodeByKey(key); if(node){ dfd = new $.Deferred(); deferredList.push(dfd); node.applyPatch(patch).always(_makeResolveFunc(dfd, node)); }else{ this.warn("could not find node with key '" + key + "'"); } } // Return a promise that is resolved, when ALL patches were applied return $.when.apply($, deferredList).promise(); }, /* TODO: implement in dnd extension cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } }, */ /** Remove all nodes. * @since 2.14 */ clear: function(source) { this._callHook("treeClear", this); }, /** Return the number of nodes. * @returns {integer} */ count: function() { return this.rootNode.countChildren(); }, /** Write to browser console if debugLevel >= 4 (prepending tree name) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.options.debugLevel >= 4 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, // TODO: disable() // TODO: enable() /** Temporarily suppress rendering to improve performance on bulk-updates. * * @param {boolean} flag * @returns {boolean} previous status * @since 2.19 */ enableUpdate: function(flag) { flag = ( flag !== false ); /*jshint -W018 */ // Confusing use of '!' if ( !!this._enableUpdate === !!flag ) { return flag; } /*jshint +W018 */ this._enableUpdate = flag; if ( flag ) { this.debug("enableUpdate(true): redraw "); //, this._dirtyRoots); this.render(); } else { // this._dirtyRoots = null; this.debug("enableUpdate(false)..."); } return !flag; // return previous value }, /**Find all nodes that matches condition. * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) * @see FancytreeNode#findAll * @since 2.12 */ findAll: function(match) { return this.rootNode.findAll(match); }, /**Find first node that matches condition. * * @param {string | function(node)} match title string to search for, or a * callback function that returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @see FancytreeNode#findFirst * @since 2.12 */ findFirst: function(match) { return this.rootNode.findFirst(match); }, /** Find the next visible node that starts with `match`, starting at `startNode` * and wrap-around at the end. * * @param {string|function} match * @param {FancytreeNode} [startNode] defaults to first node * @returns {FancytreeNode} matching node or null */ findNextNode: function(match, startNode, visibleOnly) { match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match; startNode = startNode || this.getFirstChild(); var stopNode = null, parentChildren = startNode.parent.children, matchingNode = null, walkVisible = function(parent, idx, fn) { var i, grandParent, parentChildren = parent.children, siblingCount = parentChildren.length, node = parentChildren[idx]; // visit node itself if( node && fn(node) === false ) { return false; } // visit descendants if( node && node.children && node.expanded ) { if( walkVisible(node, 0, fn) === false ) { return false; } } // visit subsequent siblings for( i = idx + 1; i < siblingCount; i++ ) { if( walkVisible(parent, i, fn) === false ) { return false; } } // visit parent's subsequent siblings grandParent = parent.parent; if( grandParent ) { return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn); } else { // wrap-around: restart with first node return walkVisible(parent, 0, fn); } }; walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){ // Stop iteration if we see the start node a second time if( node === stopNode ) { return false; } stopNode = stopNode || node; // Ignore nodes hidden by a filter if( ! $(node.span).is(":visible") ) { node.debug("quicksearch: skipping hidden node"); return; } // Test if we found a match, but search for a second match if this // was the currently active node if( match(node) ) { // node.debug("quicksearch match " + node.title, startNode); matchingNode = node; if( matchingNode !== startNode ) { return false; } } }); return matchingNode; }, // TODO: fromDict /** * Generate INPUT elements that can be submitted with html forms. * * In selectMode 3 only the topmost selected nodes are considered, unless * `opts.stopOnParents: false` is passed. * * @example * // Generate input elements for active and selected nodes * tree.generateFormElements(); * // Generate input elements selected nodes, using a custom `name` attribute * tree.generateFormElements("cust_sel", false); * // Generate input elements using a custom filter * tree.generateFormElements(true, true, { filter: function(node) { * return node.isSelected() && node.data.yes; * }}); * * @param {boolean | string} [selected=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID[]') * @param {boolean | string} [active=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID_active') * @param {object} [opts] default { filter: null, stopOnParents: true } */ generateFormElements: function(selected, active, opts) { opts = opts || {}; var nodeList, selectedName = (typeof selected === "string") ? selected : "ft_" + this._id + "[]", activeName = (typeof active === "string") ? active : "ft_" + this._id + "_active", id = "fancytree_result_" + this._id, $result = $("#" + id), stopOnParents = this.options.selectMode === 3 && opts.stopOnParents !== false; if($result.length){ $result.empty(); }else{ $result = $("<div>", { id: id }).hide().insertAfter(this.$container); } if(active !== false && this.activeNode){ $result.append($("<input>", { type: "radio", name: activeName, value: this.activeNode.key, checked: true })); } function _appender( node ) { $result.append($("<input>", { type: "checkbox", name: selectedName, value: node.key, checked: true })); } if ( opts.filter ) { this.visit(function(node) { var res = opts.filter(node); if( res === "skip" ) { return res; } if ( res !== false ) { _appender(node); } }); } else if ( selected !== false ) { nodeList = this.getSelectedNodes(stopOnParents); $.each(nodeList, function(idx, node) { _appender(node); }); } }, /** * Return the currently active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.activeNode; }, /** Return the first top level node if any (not the invisible root node). * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.rootNode.getFirstChild(); }, /** * Return node that has keyboard focus or null. * @returns {FancytreeNode} */ getFocusNode: function() { return this.focusNode; }, /** * Return node with a given key or null if not found. * * Not * @param {string} key * @param {FancytreeNode} [searchRoot] only search below this node * @returns {FancytreeNode | null} */ getNodeByKey: function(key, searchRoot) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). var el, match; // TODO: use tree.keyMap if available // TODO: check opts.generateIds === true if(!searchRoot){ el = document.getElementById(this.options.idPrefix + key); if( el ){ return el.ftnode ? el.ftnode : null; } } // Not found in the DOM, but still may be in an unrendered part of tree searchRoot = searchRoot || this.rootNode; match = null; searchRoot.visit(function(node){ if(node.key === key) { match = node; return false; // Stop iteration } }, true); return match; }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.rootNode; }, /** * Return an array of selected nodes. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { return this.rootNode.getSelectedNodes(stopOnParents); }, /** Return true if the tree control has keyboard focus * @returns {boolean} */ hasFocus: function(){ return !!this._hasFocus; }, /** Write to browser console if debugLevel >= 3 (prepending tree name) * @param {*} msg string or object or array of such */ info: function(msg){ if( this.options.debugLevel >= 3 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /* TODO: isInitializing: function() { return ( this.phase=="init" || this.phase=="postInit" ); }, TODO: isReloading: function() { return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound; }, TODO: isUserEvent: function() { return ( this.phase=="userEvent" ); }, */ /** * Make sure that a node with a given ID is loaded, by traversing - and * loading - its parents. This method is meant for lazy hierarchies. * A callback is executed for every node as we go. * @example * // Resolve using node.key: * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){ * if(status === "loaded") { * console.log("loaded intermediate node " + node); * }else if(status === "ok") { * node.activate(); * } * }); * // Use deferred promise: * tree.loadKeyPath("/_3/_23/_26/_27").progress(function(data){ * if(data.status === "loaded") { * console.log("loaded intermediate node " + data.node); * }else if(data.status === "ok") { * node.activate(); * } * }).done(function(){ * ... * }); * // Custom path segment resolver: * tree.loadKeyPath("/321/431/21/2", { * matchKey: function(node, key){ * return node.data.refKey === key; * }, * callback: function(node, status){ * if(status === "loaded") { * console.log("loaded intermediate node " + node); * }else if(status === "ok") { * node.activate(); * } * } * }); * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7') * @param {function | object} optsOrCallback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error'). * Pass an object to define custom key matchers for the path segments: {callback: function, matchKey: function}. * @returns {$.Promise} */ loadKeyPath: function(keyPathList, optsOrCallback) { var callback, i, path, self = this, dfd = new $.Deferred(), parent = this.getRootNode(), sep = this.options.keyPathSeparator, pathSegList = [], opts = $.extend({}, optsOrCallback); // Prepare options if( typeof optsOrCallback === "function" ) { callback = optsOrCallback; } else if ( optsOrCallback && optsOrCallback.callback ) { callback = optsOrCallback.callback; } opts.callback = function(ctx, node, status){ if( callback ) { callback.call(ctx, node, status); } dfd.notifyWith(ctx, [{node: node, status: status}]); }; if( opts.matchKey == null ) { opts.matchKey = function(node, key) { return node.key === key; }; } // Convert array of path strings to array of segment arrays if(!$.isArray(keyPathList)){ keyPathList = [keyPathList]; } for(i=0; i<keyPathList.length; i++){ path = keyPathList[i]; // strip leading slash if(path.charAt(0) === sep){ path = path.substr(1); } // segListMap[path] = { parent: parent, segList: path.split(sep) }; pathSegList.push(path.split(sep)); // targetList.push({ parent: parent, segList: path.split(sep)/* , path: path*/}); } // The timeout forces async behavior always (even if nodes are all loaded) // This way a potential progress() event will fire. setTimeout(function(){ self._loadKeyPathImpl(dfd, opts, parent, pathSegList).done(function(){ dfd.resolve(); }); }, 0); return dfd.promise(); }, /* * Resolve a list of paths, relative to one parent node. */ _loadKeyPathImpl: function(dfd, opts, parent, pathSegList) { var deferredList, i, key, node, remainMap, tmpParent, segList, subDfd, self = this; function __findChild(parent, key){ // console.log("__findChild", key, parent); var i, l, cl = parent.children; if( cl ) { for(i=0, l=cl.length; i<l; i++){ if( opts.matchKey(cl[i], key)) { return cl[i]; } } } return null; } // console.log("_loadKeyPathImpl, parent=", parent, ", pathSegList=", pathSegList); // Pass 1: // Handle all path segments for nodes that are already loaded. // Collect distinct top-most lazy nodes in a map. // Note that we can use node.key to de-dupe entries, even if a custom matcher would // look for other node attributes. // map[node.key] => {node: node, pathList: [list of remaining rest-paths]} remainMap = {}; for(i=0; i<pathSegList.length; i++){ segList = pathSegList[i]; // target = targetList[i]; // Traverse and pop path segments (i.e. keys), until we hit a lazy, unloaded node tmpParent = parent; while(segList.length){ key = segList.shift(); node = __findChild(tmpParent, key); if(!node){ this.warn("loadKeyPath: key not found: " + key + " (parent: " + tmpParent + ")"); opts.callback(this, key, "error"); break; }else if(segList.length === 0){ opts.callback(this, node, "ok"); break; }else if(!node.lazy || (node.hasChildren() !== undefined )){ opts.callback(this, node, "loaded"); tmpParent = node; }else{ opts.callback(this, node, "loaded"); key = node.key; //target.segList.join(sep); if(remainMap[key]){ remainMap[key].pathSegList.push(segList); }else{ remainMap[key] = {parent: node, pathSegList: [segList]}; } break; } } } // console.log("_loadKeyPathImpl AFTER pass 1, remainMap=", remainMap); // Now load all lazy nodes and continue iteration for remaining paths deferredList = []; // Avoid jshint warning 'Don't make functions within a loop.': function __lazyload(dfd, parent, pathSegList){ // console.log("__lazyload", parent, "pathSegList=", pathSegList); opts.callback(self, parent, "loading"); parent.load().done(function(){ self._loadKeyPathImpl.call(self, dfd, opts, parent, pathSegList) .always(_makeResolveFunc(dfd, self)); }).fail(function(errMsg){ self.warn("loadKeyPath: error loading lazy " + parent); opts.callback(self, node, "error"); dfd.rejectWith(self); }); } // remainMap contains parent nodes, each with a list of relative sub-paths. // We start loading all of them now, and pass the the list to each loader. for(var nodeKey in remainMap){ var remain = remainMap[nodeKey]; // console.log("for(): remain=", remain, "remainMap=", remainMap); // key = remain.segList.shift(); // node = __findChild(remain.parent, key); // if (node == null) { // #576 // // Issue #576, refactored for v2.27: // // The root cause was, that sometimes the wrong parent was used here // // to find the next segment. // // Falling back to getNodeByKey() was a hack that no longer works if a custom // // matcher is used, because we cannot assume that a single segment-key is unique // // throughout the tree. // self.error("loadKeyPath: error loading child by key '" + key + "' (parent: " + target.parent + ")", target); // // node = self.getNodeByKey(key); // continue; // } subDfd = new $.Deferred(); deferredList.push(subDfd); __lazyload(subDfd, remain.parent, remain.pathSegList); } // Return a promise that is resolved, when ALL paths were loaded return $.when.apply($, deferredList).promise(); }, /** Re-fire beforeActivate, activate, and (optional) focus events. * Calling this method in the `init` event, will activate the node that * was marked 'active' in the source data, and optionally set the keyboard * focus. * @param [setFocus=false] */ reactivate: function(setFocus) { var res, node = this.activeNode; if( !node ) { return _getResolvedPromise(); } this.activeNode = null; // Force re-activating res = node.setActive(true, {noFocus: true}); if( setFocus ){ node.setFocus(); } return res; }, /** Reload tree from source and return a promise. * @param [source] optional new source (defaults to initial source data) * @returns {$.Promise} */ reload: function(source) { this._callHook("treeClear", this); return this._callHook("treeLoad", this, source); }, /**Render tree (i.e. create DOM elements for all top-level nodes). * @param {boolean} [force=false] create DOM elemnts, even if parent is collapsed * @param {boolean} [deep=false] */ render: function(force, deep) { return this.rootNode.render(force, deep); }, /**(De)select all nodes. * @param {boolean} [flag=true] * @since 2.28 */ selectAll: function(flag) { this.visit(function(node){ node.setSelected(flag); }); }, // TODO: selectKey: function(key, select) // TODO: serializeArray: function(stopOnParents) /** * @param {boolean} [flag=true] */ setFocus: function(flag) { return this._callHook("treeSetFocus", this, flag); }, /** * Return all nodes as nested list of {@link NodeData}. * * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children) * @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications * @returns {Array | object} * @see FancytreeNode#toDict */ toDict: function(includeRoot, callback){ var res = this.rootNode.toDict(true, callback); return includeRoot ? res : res.children; }, /* Implicitly called for string conversions. * @returns {string} */ toString: function(){ return "Fancytree@" + this._id; // return "<Fancytree(#" + this._id + ")>"; }, /* _trigger a widget event with additional node ctx. * @see EventData */ _triggerNodeEvent: function(type, node, originalEvent, extra) { // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx); var ctx = this._makeHookContext(node, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /* _trigger a widget event with additional tree data. */ _triggerTreeEvent: function(type, originalEvent, extra) { // this.debug("_trigger(" + type + ")", ctx); var ctx = this._makeHookContext(this, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /** Call fn(node) for all nodes in hierarchical order (depth-first). * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @returns {boolean} false, if the iterator was stopped. */ visit: function(fn) { return this.rootNode.visit(fn, false); }, /** Call fn(node) for all nodes in vertical order, top down (or bottom up).<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {object} [options] * Defaults: * {start: First top node, reverse: false, includeSelf: true, includeHidden: false} * @returns {boolean} * @since 2.28 */ visitRows: function(fn, opts) { if( opts && opts.reverse ) { delete opts.reverse; return this._visitRowsUp(fn, opts); } var i, nextIdx, parent, res, siblings, siblingOfs = 0, skipFirstNode = (opts.includeSelf === false), includeHidden = !!opts.includeHidden, node = opts.start || this.rootNode.children[0]; parent = node.parent; while( parent ) { // visit siblings siblings = parent.children; nextIdx = siblings.indexOf(node) + siblingOfs; for( i=nextIdx; i<siblings.length; i++) { node = siblings[i]; if( !skipFirstNode && fn(node) === false ) { return false; } skipFirstNode = false; // Dive into node's child nodes if( node.children && node.children.length && (includeHidden || node.expanded) ) { // Disable warning: Functions declared within loops referencing an outer // scoped variable may lead to confusing semantics: /*jshint -W083 */ res = node.visit(function(n) { if( fn(n) === false ) { return false; } if( !includeHidden && n.children && !n.expanded ) { return "skip"; } }, false); /*jshint +W083 */ if( res === false ) { return false; } } } // Visit parent nodes (bottom up) node = parent; parent = parent.parent; siblingOfs = 1; // } return true; }, /* Call fn(node) for all nodes in vertical order, bottom up. */ _visitRowsUp: function(fn, opts) { var children, idx, parent, includeHidden = !!opts.includeHidden, node = opts.start || this.rootNode.children[0]; while( true ) { parent = node.parent; children = parent.children; if( children[0] === node ) { // If this is already the first sibling, goto parent node = parent; children = parent.children; } else { // Otherwise, goto prev. sibling idx = children.indexOf(node); node = children[idx-1]; // If the prev. sibling has children, follow down to last descendant while( (includeHidden || node.expanded) && node.children && node.children.length ) { children = node.children; parent = node; node = children[children.length - 1]; } } // Skip invisible if( !includeHidden && !$(node.span).is(":visible") ) { continue; } if( fn(node) === false ) { return false; } } }, /** Write warning to browser console if debugLevel >= 2 (prepending tree info) * * @param {*} msg string or object or array of such */ warn: function(msg){ if( this.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } } }; /** * These additional methods of the {@link Fancytree} class are 'hook functions' * that can be used and overloaded by extensions. * (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.) * @mixin Fancytree_Hooks */ $.extend(Fancytree.prototype, /** @lends Fancytree_Hooks# */ { /** Default handling for mouse click events. * * @param {EventData} ctx */ nodeClick: function(ctx) { var activate, expand, // event = ctx.originalEvent, targetType = ctx.targetType, node = ctx.node; // this.debug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which, ctx); // TODO: use switch // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample) if( targetType === "expander" ) { if( node.isLoading() ) { // #495: we probably got a click event while a lazy load is pending. // The 'expanded' state is not yet set, so 'toggle' would expand // and trigger lazyLoad again. // It would be better to allow to collapse/expand the status node // while loading (instead of ignoring), but that would require some // more work. node.debug("Got 2nd click while loading: ignored"); return; } // Clicking the expander icon always expands/collapses this._callHook("nodeToggleExpanded", ctx); } else if( targetType === "checkbox" ) { // Clicking the checkbox always (de)selects this._callHook("nodeToggleSelected", ctx); if( ctx.options.focusOnSelect ) { // #358 this._callHook("nodeSetFocus", ctx, true); } } else { // Honor `clickFolderMode` for expand = false; activate = true; if( node.folder ) { switch( ctx.options.clickFolderMode ) { case 2: // expand only expand = true; activate = false; break; case 3: // expand and activate activate = true; expand = true; //!node.isExpanded(); break; // else 1 or 4: just activate } } if( activate ) { this.nodeSetFocus(ctx); this._callHook("nodeSetActive", ctx, true); } if( expand ) { if(!activate){ // this._callHook("nodeSetFocus", ctx); } // this._callHook("nodeSetExpanded", ctx, true); this._callHook("nodeToggleExpanded", ctx); } } // Make sure that clicks stop, otherwise <a href='#'> jumps to the top // if(event.target.localName === "a" && event.target.className === "fancytree-title"){ // event.preventDefault(); // } // TODO: return promise? }, /** Collapse all other children of same parent. * * @param {EventData} ctx * @param {object} callOpts */ nodeCollapseSiblings: function(ctx, callOpts) { // TODO: return promise? var ac, i, l, node = ctx.node; if( node.parent ){ ac = node.parent.children; for (i=0, l=ac.length; i<l; i++) { if ( ac[i] !== node && ac[i].expanded ){ this._callHook("nodeSetExpanded", ac[i], false, callOpts); } } } }, /** Default handling for mouse douleclick events. * @param {EventData} ctx */ nodeDblclick: function(ctx) { // TODO: return promise? if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) { // this.nodeSetFocus(ctx); // this._callHook("nodeSetActive", ctx, true); this._callHook("nodeToggleExpanded", ctx); } // TODO: prevent text selection on dblclicks if( ctx.targetType === "title" ) { ctx.originalEvent.preventDefault(); } }, /** Default handling for mouse keydown events. * * NOTE: this may be called with node == null if tree (but no node) has focus. * @param {EventData} ctx */ nodeKeydown: function(ctx) { // TODO: return promise? var matchNode, stamp, res, focusNode, event = ctx.originalEvent, node = ctx.node, tree = ctx.tree, opts = ctx.options, which = event.which, whichChar = String.fromCharCode(which), clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey), $target = $(event.target), handled = true, activate = !(event.ctrlKey || !opts.autoActivate ); // (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); // FT.debug("eventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.eventToString(event) + '"'); // Set focus to active (or first node) if no other node has the focus yet if( !node ){ focusNode = (this.getActiveNode() || this.getFirstChild()); if (focusNode){ focusNode.setFocus(); node = ctx.node = this.focusNode; node.debug("Keydown force focus on active node"); } } if( opts.quicksearch && clean && /\w/.test(whichChar) && !SPECIAL_KEYCODES[which] && // #659 !$target.is(":input:enabled") ) { // Allow to search for longer streaks if typed in quickly stamp = Date.now(); if( stamp - tree.lastQuicksearchTime > 500 ) { tree.lastQuicksearchTerm = ""; } tree.lastQuicksearchTime = stamp; tree.lastQuicksearchTerm += whichChar; // tree.debug("quicksearch find", tree.lastQuicksearchTerm); matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode()); if( matchNode ) { matchNode.setActive(); } event.preventDefault(); return; } switch( FT.eventToString(event) ) { case "+": case "=": // 187: '+' @ Chrome, Safari tree.nodeSetExpanded(ctx, true); break; case "-": tree.nodeSetExpanded(ctx, false); break; case "space": if( node.isPagingNode() ) { tree._triggerNodeEvent("clickPaging", ctx, event); } else if( FT.evalOption("checkbox", node, node, opts, false) ) { // #768 tree.nodeToggleSelected(ctx); }else{ tree.nodeSetActive(ctx, true); } break; case "return": tree.nodeSetActive(ctx, true); break; case "home": case "end": case "backspace": case "left": case "right": case "up": case "down": res = node.navigate(event.which, activate); break; default: handled = false; } if(handled){ event.preventDefault(); } }, // /** Default handling for mouse keypress events. */ // nodeKeypress: function(ctx) { // var event = ctx.originalEvent; // }, // /** Trigger lazyLoad event (async). */ // nodeLazyLoad: function(ctx) { // var node = ctx.node; // if(this._triggerNodeEvent()) // }, /** Load child nodes (async). * * @param {EventData} ctx * @param {object[]|object|string|$.Promise|function} source * @returns {$.Promise} The deferred will be resolved as soon as the (ajax) * data was rendered. */ nodeLoadChildren: function(ctx, source) { var ajax, delay, dfd, tree = ctx.tree, node = ctx.node, requestId = Date.now(); if($.isFunction(source)){ source = source.call(tree, {type: "source"}, ctx); _assert(!$.isFunction(source), "source callback must not return another function"); } if(source.url){ if( node._requestId ) { node.warn("Recursive load request #" + requestId + " while #" + node._requestId + " is pending."); // } else { // node.debug("Send load request #" + requestId); } // `source` is an Ajax options object ajax = $.extend({}, ctx.options.ajax, source); node._requestId = requestId; if(ajax.debugDelay){ // simulate a slow server delay = ajax.debugDelay; if($.isArray(delay)){ // random delay range [min..max] delay = delay[0] + Math.random() * (delay[1] - delay[0]); } node.warn("nodeLoadChildren waiting debugDelay " + Math.round(delay) + " ms ..."); ajax.debugDelay = false; dfd = $.Deferred(function (dfd) { setTimeout(function () { $.ajax(ajax) .done(function () { dfd.resolveWith(this, arguments); }) .fail(function () { dfd.rejectWith(this, arguments); }); }, delay); }); }else{ dfd = $.ajax(ajax); } // Defer the deferred: we want to be able to reject, even if ajax // resolved ok. source = new $.Deferred(); dfd.done(function (data, textStatus, jqXHR) { var errorObj, res; if((this.dataType === "json" || this.dataType === "jsonp") && typeof data === "string"){ $.error("Ajax request returned a string (did you get the JSON dataType wrong?)."); } if( node._requestId && node._requestId > requestId ) { // The expected request time stamp is later than `requestId` // (which was kept as as closure variable to this handler function) // node.warn("Ignored load response for obsolete request #" + requestId + " (expected #" + node._requestId + ")"); source.rejectWith(this, [RECURSIVE_REQUEST_ERROR]); return; // } else { // node.debug("Response returned for load request #" + requestId); } // postProcess is similar to the standard ajax dataFilter hook, // but it is also called for JSONP if( ctx.options.postProcess ){ try { res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, { response: data, error: null, dataType: this.dataType }); } catch(e) { res = { error: e, message: "" + e, details: "postProcess failed"}; } if( res.error ) { errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error}; errorObj = tree._makeHookContext(node, null, errorObj); source.rejectWith(this, [errorObj]); return; } data = $.isArray(res) ? res : data; } else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) { // Process ASPX WebMethod JSON object inside "d" property data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d; } source.resolveWith(this, [data]); }).fail(function (jqXHR, textStatus, errorThrown) { var errorObj = tree._makeHookContext(node, null, { error: jqXHR, args: Array.prototype.slice.call(arguments), message: errorThrown, details: jqXHR.status + ": " + errorThrown }); source.rejectWith(this, [errorObj]); }); } // #383: accept and convert ECMAScript 6 Promise if( $.isFunction(source.then) && $.isFunction(source["catch"]) ) { dfd = source; source = new $.Deferred(); dfd.then(function(value){ source.resolve(value); }, function(reason){ source.reject(reason); }); } if($.isFunction(source.promise)){ // `source` is a deferred, i.e. ajax request // _assert(!node.isLoading(), "recursive load"); tree.nodeSetStatus(ctx, "loading"); source.done(function (children) { tree.nodeSetStatus(ctx, "ok"); node._requestId = null; }).fail(function(error){ var ctxErr; if ( error === RECURSIVE_REQUEST_ERROR ) { node.warn("Ignored response for obsolete load request #" + requestId + " (expected #" + node._requestId + ")"); return; } else if (error.node && error.error && error.message) { // error is already a context object ctxErr = error; } else { ctxErr = tree._makeHookContext(node, null, { error: error, // it can be jqXHR or any custom error args: Array.prototype.slice.call(arguments), message: error ? (error.message || error.toString()) : "" }); if( ctxErr.message === "[object Object]" ) { ctxErr.message = ""; } } node.warn("Load children failed (" + ctxErr.message + ")", ctxErr); if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) { tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details); } }); } else { if( ctx.options.postProcess ){ // #792: Call postProcess for non-deferred source var res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, { response: source, error: null, dataType: typeof source }); source = $.isArray(res) ? res : source; } } // $.when(source) resolves also for non-deferreds return $.when(source).done(function(children){ var metaData; if( $.isPlainObject(children) ){ // We got {foo: 'abc', children: [...]} // Copy extra properties to tree.data.foo _assert(node.isRootNode(), "source may only be an object for root nodes (expecting an array of child objects otherwise)"); _assert($.isArray(children.children), "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')"); metaData = children; children = children.children; delete metaData.children; // Copy some attributes to tree.data $.each(TREE_ATTRS, function(i, attr) { if( metaData[attr] !== undefined ){ tree[attr] = metaData[attr]; delete metaData[attr]; } }); // Copy all other attributes to tree.data.NAME $.extend(tree.data, metaData); } _assert($.isArray(children), "expected array of children"); node._setChildren(children); // trigger fancytreeloadchildren tree._triggerNodeEvent("loadChildren", node); }); }, /** [Not Implemented] */ nodeLoadKeyPath: function(ctx, keyPathList) { // TODO: implement and improve // http://code.google.com/p/dynatree/issues/detail?id=222 }, /** * Remove a single direct child of ctx.node. * @param {EventData} ctx * @param {FancytreeNode} childNode dircect child of ctx.node */ nodeRemoveChild: function(ctx, childNode) { var idx, node = ctx.node, // opts = ctx.options, subCtx = $.extend({}, ctx, {node: childNode}), children = node.children; // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString()); if( children.length === 1 ) { _assert(childNode === children[0], "invalid single child"); return this.nodeRemoveChildren(ctx); } if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveMarkup(subCtx); this.nodeRemoveChildren(subCtx); idx = $.inArray(childNode, children); _assert(idx >= 0, "invalid child"); // Notify listeners node.triggerModifyChild("remove", childNode); // Unlink to support GC childNode.visit(function(n){ n.parent = null; }, true); this._callHook("treeRegisterNode", this, false, childNode); // remove from child list children.splice(idx, 1); }, /**Remove HTML markup for all descendents of ctx.node. * @param {EventData} ctx */ nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveChildMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.ul){ if( node.isRootNode() ) { $(node.ul).empty(); } else { $(node.ul).remove(); node.ul = null; } node.visit(function(n){ n.li = n.ul = null; }); } }, /**Remove all descendants of ctx.node. * @param {EventData} ctx */ nodeRemoveChildren: function(ctx) { var subCtx, tree = ctx.tree, node = ctx.node, children = node.children; // opts = ctx.options; // FT.debug("nodeRemoveChildren()", node.toString()); if(!children){ return; } if( this.activeNode && this.activeNode.isDescendantOf(node)){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && this.focusNode.isDescendantOf(node)){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveChildMarkup(ctx); // Unlink children to support GC // TODO: also delete this.children (not possible using visit()) subCtx = $.extend({}, ctx); node.triggerModifyChild("remove", null); node.visit(function(n){ n.parent = null; tree._callHook("treeRegisterNode", tree, false, n); }); if( node.lazy ){ // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes node.children = []; } else{ node.children = null; } if( !node.isRootNode() ) { node.expanded = false; // #449, #459 } this.nodeRenderStatus(ctx); }, /**Remove HTML markup for ctx.node and all its descendents. * @param {EventData} ctx */ nodeRemoveMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.li){ $(node.li).remove(); node.li = null; } this.nodeRemoveChildMarkup(ctx); }, /** * Create `&lt;li>&lt;span>..&lt;/span> .. &lt;/li>` tags for this node. * * This method takes care that all HTML markup is created that is required * to display this node in its current state. * * Call this method to create new nodes, or after the strucuture * was changed (e.g. after moving this node or adding/removing children) * nodeRenderTitle() and nodeRenderStatus() are implied. * * &lt;code> * &lt;li id='KEY' ftnode=NODE> * &lt;span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'> * &lt;span class="fancytree-expander">&lt;/span> * &lt;span class="fancytree-checkbox">&lt;/span> // only present in checkbox mode * &lt;span class="fancytree-icon">&lt;/span> * &lt;a href="#" class="fancytree-title"> Node 1 &lt;/a> * &lt;/span> * &lt;ul> // only present if node has children * &lt;li id='KEY' ftnode=NODE> child1 ... &lt;/li> * &lt;li id='KEY' ftnode=NODE> child2 ... &lt;/li> * &lt;/ul> * &lt;/li> * &lt;/code> * * @param {EventData} ctx * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { /* This method must take care of all cases where the current data mode * (i.e. node hierarchy) does not match the current markup. * * - node was not yet rendered: * create markup * - node was rendered: exit fast * - children have been added * - children have been removed */ var childLI, childNode1, childNode2, i, l, next, subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, firstTime = false, parent = node.parent, isRootNode = !parent, children = node.children, successorLi = null; // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString()); if( tree._enableUpdate === false ) { // tree.debug("no render", tree._enableUpdate); return; } if( ! isRootNode && ! parent.ul ) { // Calling node.collapse on a deep, unrendered node return; } _assert(isRootNode || parent.ul, "parent UL must exist"); // Render the node if( !isRootNode ){ // Discard markup on force-mode, or if it is not linked to parent <ul> if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){ if( node.li.parentNode === node.parent.ul ){ // #486: store following node, so we can insert the new markup there later successorLi = node.li.nextSibling; }else{ // May happen, when a top-level node was dropped over another this.debug("Unlinking " + node + " (must be child of " + node.parent + ")"); } // this.debug("nodeRemoveMarkup..."); this.nodeRemoveMarkup(ctx); } // Create <li><span /> </li> // node.debug("render..."); if( !node.li ) { // node.debug("render... really"); firstTime = true; node.li = document.createElement("li"); node.li.ftnode = node; if( node.key && opts.generateIds ){ node.li.id = opts.idPrefix + node.key; } node.span = document.createElement("span"); node.span.className = "fancytree-node"; if( aria && !node.tr ) { $(node.li).attr("role", "treeitem"); } node.li.appendChild(node.span); // Create inner HTML for the <span> (expander, checkbox, icon, and title) this.nodeRenderTitle(ctx); // Allow tweaking and binding, after node was created for the first time if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } }else{ // this.nodeRenderTitle(ctx); this.nodeRenderStatus(ctx); } // Allow tweaking after node state was rendered if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } } // Visit child nodes if( children ){ if( isRootNode || node.expanded || deep === true ) { // Create a UL to hold the children if( !node.ul ){ node.ul = document.createElement("ul"); if((collapsed === true && !_recursive) || !node.expanded){ // hide top UL, so we can use an animation to show it later node.ul.style.display = "none"; } if(aria){ $(node.ul).attr("role", "group"); } if ( node.li ) { // issue #67 node.li.appendChild(node.ul); } else { node.tree.$div.append(node.ul); } } // Add child markup for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); this.nodeRender(subCtx, force, deep, false, true); } // Remove <li> if nodes have moved to another parent childLI = node.ul.firstChild; while( childLI ){ childNode2 = childLI.ftnode; if( childNode2 && childNode2.parent !== node ) { node.debug("_fixParent: remove missing " + childNode2, childLI); next = childLI.nextSibling; childLI.parentNode.removeChild(childLI); childLI = next; }else{ childLI = childLI.nextSibling; } } // Make sure, that <li> order matches node.children order. childLI = node.ul.firstChild; for(i=0, l=children.length-1; i<l; i++) { childNode1 = children[i]; childNode2 = childLI.ftnode; if( childNode1 !== childNode2 ) { // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2); node.ul.insertBefore(childNode1.li, childNode2.li); } else { childLI = childLI.nextSibling; } } } }else{ // No children: remove markup if any if( node.ul ){ // alert("remove child markup for " + node); this.warn("remove child markup for " + node); this.nodeRemoveChildMarkup(ctx); } } if( !isRootNode ){ // Update element classes according to node state // this.nodeRenderStatus(ctx); // Finally add the whole structure to the DOM, so the browser can render if( firstTime ){ // #486: successorLi is set, if we re-rendered (i.e. discarded) // existing markup, which we want to insert at the same position. // (null is equivalent to append) // parent.ul.appendChild(node.li); parent.ul.insertBefore(node.li, successorLi); } } }, /** Create HTML inside the node's outer &lt;span> (i.e. expander, checkbox, * icon, and title). * * nodeRenderStatus() is implied. * @param {EventData} ctx * @param {string} [title] optinal new title */ nodeRenderTitle: function(ctx, title) { // set node connector images, links and text var checkbox, className, icon, nodeTitle, role, tabindex, tooltip, iconTooltip, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, level = node.getLevel(), ares = []; if(title !== undefined){ node.title = title; } if ( !node.span || tree._enableUpdate === false ) { // Silently bail out if node was not rendered yet, assuming // node.render() will be called as the node becomes visible return; } // Connector (expanded, expandable or simple) role = (aria && node.hasChildren() !== false) ? " role='button'" : ""; if( level < opts.minExpandLevel ) { if( !node.lazy ) { node.expanded = true; } if(level > 1){ ares.push("<span " + role + " class='fancytree-expander fancytree-expander-fixed'></span>"); } // .. else (i.e. for root level) skip expander/connector alltogether } else { ares.push("<span " + role + " class='fancytree-expander'></span>"); } // Checkbox mode checkbox = FT.evalOption("checkbox", node, node, opts, false); if( checkbox && !node.isStatusNode() ) { role = aria ? " role='checkbox'" : ""; className = "fancytree-checkbox"; if( checkbox === "radio" || (node.parent && node.parent.radiogroup) ) { className += " fancytree-radio"; } ares.push("<span " + role + " class='" + className + "'></span>"); } // Folder or doctype icon if( node.data.iconClass !== undefined ) { // 2015-11-16 // Handle / warn about backward compatibility if( node.icon ) { $.error("'iconClass' node option is deprecated since v2.14.0: use 'icon' only instead"); } else { node.warn("'iconClass' node option is deprecated since v2.14.0: use 'icon' instead"); node.icon = node.data.iconClass; } } // If opts.icon is a callback and returns something other than undefined, use that // else if node.icon is a boolean or string, use that // else if opts.icon is a boolean or string, use that // else show standard icon (which may be different for folders or documents) icon = FT.evalOption("icon", node, node, opts, true); // if( typeof icon !== "boolean" ) { // // icon is defined, but not true/false: must be a string // icon = "" + icon; // } if( icon !== false ) { role = aria ? " role='presentation'" : ""; iconTooltip = FT.evalOption("iconTooltip", node, node, opts, null); iconTooltip = iconTooltip ? " title='" + _escapeTooltip(iconTooltip) + "'" : ""; if ( typeof icon === "string" ) { if( TEST_IMG.test(icon) ) { // node.icon is an image url. Prepend imagePath icon = (icon.charAt(0) === "/") ? icon : ((opts.imagePath || "") + icon); ares.push("<img src='" + icon + "' class='fancytree-icon'" + iconTooltip + " alt='' />"); } else { ares.push("<span " + role + " class='fancytree-custom-icon " + icon + "'" + iconTooltip + "></span>"); } } else if ( icon.text ) { ares.push("<span " + role + " class='fancytree-custom-icon " + (icon.addClass || "") + "'" + iconTooltip + ">" + FT.escapeHtml(icon.text) + "</span>"); } else if ( icon.html ) { ares.push("<span " + role + " class='fancytree-custom-icon " + (icon.addClass || "") + "'" + iconTooltip + ">" + icon.html + "</span>"); } else { // standard icon: theme css will take care of this ares.push("<span " + role + " class='fancytree-icon'" + iconTooltip + "></span>"); } } // Node title nodeTitle = ""; if ( opts.renderTitle ){ nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || ""; } if ( !nodeTitle ) { tooltip = FT.evalOption("tooltip", node, node, opts, null); if( tooltip === true ) { tooltip = node.title; } // if( node.tooltip ) { // tooltip = node.tooltip; // } else if ( opts.tooltip ) { // tooltip = opts.tooltip === true ? node.title : opts.tooltip.call(tree, node); // } tooltip = tooltip ? " title='" + _escapeTooltip(tooltip) + "'" : ""; tabindex = opts.titlesTabbable ? " tabindex='0'" : ""; nodeTitle = "<span class='fancytree-title'" + tooltip + tabindex + ">" + (opts.escapeTitles ? FT.escapeHtml(node.title) : node.title) + "</span>"; } ares.push(nodeTitle); // Note: this will trigger focusout, if node had the focus //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly node.span.innerHTML = ares.join(""); // Update CSS classes this.nodeRenderStatus(ctx); if ( opts.enhanceTitle ){ ctx.$title = $(">span.fancytree-title", node.span); nodeTitle = opts.enhanceTitle.call(tree, {type: "enhanceTitle"}, ctx) || ""; } }, /** Update element classes according to node state. * @param {EventData} ctx */ nodeRenderStatus: function(ctx) { // Set classes for current status var $ariaElem, node = ctx.node, tree = ctx.tree, opts = ctx.options, // nodeContainer = node[tree.nodeContainerAttrName], hasChildren = node.hasChildren(), isLastSib = node.isLastSibling(), aria = opts.aria, cn = opts._classNames, cnList = [], statusElem = node[tree.statusClassPropName]; if( !statusElem || tree._enableUpdate === false ){ // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway) return; } if( aria ) { $ariaElem = $(node.tr || node.li); } // Build a list of class names that we will add to the node <span> cnList.push(cn.node); if( tree.activeNode === node ){ cnList.push(cn.active); // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // tree.$container.removeAttr("tabindex"); // }else{ // $(">span.fancytree-title", statusElem).removeAttr("tabindex"); // tree.$container.attr("tabindex", "0"); } if( tree.focusNode === node ){ cnList.push(cn.focused); } if( node.expanded ){ cnList.push(cn.expanded); } if( aria ){ if (hasChildren !== false) { $ariaElem.attr("aria-expanded", Boolean(node.expanded)); } else { $ariaElem.removeAttr("aria-expanded"); } } if( node.folder ){ cnList.push(cn.folder); } if( hasChildren !== false ){ cnList.push(cn.hasChildren); } // TODO: required? if( isLastSib ){ cnList.push(cn.lastsib); } if( node.lazy && node.children == null ){ cnList.push(cn.lazy); } if( node.partload ){ cnList.push(cn.partload); } if( node.partsel ){ cnList.push(cn.partsel); } if( FT.evalOption("unselectable", node, node, opts, false) ){ cnList.push(cn.unselectable); } if( node._isLoading ){ cnList.push(cn.loading); } if( node._error ){ cnList.push(cn.error); } if( node.statusNodeType ) { cnList.push(cn.statusNodePrefix + node.statusNodeType); } if( node.selected ){ cnList.push(cn.selected); if(aria){ $ariaElem.attr("aria-selected", true); } }else if(aria){ $ariaElem.attr("aria-selected", false); } if( node.extraClasses ){ cnList.push(node.extraClasses); } // IE6 doesn't correctly evaluate multiple class names, // so we create combined class names that can be used in the CSS if( hasChildren === false ){ cnList.push(cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "") ); }else{ cnList.push(cn.combinedExpanderPrefix + (node.expanded ? "e" : "c") + (node.lazy && node.children == null ? "d" : "") + (isLastSib ? "l" : "") ); } cnList.push(cn.combinedIconPrefix + (node.expanded ? "e" : "c") + (node.folder ? "f" : "") ); // node.span.className = cnList.join(" "); statusElem.className = cnList.join(" "); // TODO: we should not set this in the <span> tag also, if we set it here: // Maybe most (all) of the classes should be set in LI instead of SPAN? if(node.li){ // #719: we have to consider that there may be already other classes: $(node.li).toggleClass(cn.lastsib, isLastSib); } }, /** Activate node. * flag defaults to true. * If flag is true, the node is activated (must be a synchronous operation) * If flag is false, the node is deactivated (must be a synchronous operation) * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false} * @returns {$.Promise} */ nodeSetActive: function(ctx, flag, callOpts) { // Handle user click / [space] / [enter], according to clickFolderMode. callOpts = callOpts || {}; var subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = (callOpts.noEvents === true), noFocus = (callOpts.noFocus === true), isActive = (node === tree.activeNode); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetActive", flag); if(isActive === flag){ // Nothing to do return _getResolvedPromise(node); }else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } if(flag){ if(tree.activeNode){ _assert(tree.activeNode !== node, "node was active (inconsistency)"); subCtx = $.extend({}, ctx, {node: tree.activeNode}); tree.nodeSetActive(subCtx, false); _assert(tree.activeNode === null, "deactivate was out of sync?"); } if(opts.activeVisible){ // If no focus is set (noFocus: true) and there is no focused node, this node is made visible. node.makeVisible({scrollIntoView: noFocus && tree.focusNode == null}); } tree.activeNode = node; tree.nodeRenderStatus(ctx); if( !noFocus ) { tree.nodeSetFocus(ctx); } if( !noEvents ) { tree._triggerNodeEvent("activate", node, ctx.originalEvent); } }else{ _assert(tree.activeNode === node, "node was not active (inconsistency)"); tree.activeNode = null; this.nodeRenderStatus(ctx); if( !noEvents ) { ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent); } } return _getResolvedPromise(node); }, /** Expand or collapse node, return Deferred.promise. * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} The deferred will be resolved as soon as the (lazy) * data was retrieved, rendered, and the expand animation finshed. */ nodeSetExpanded: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var _afterLoad, dfd, i, l, parents, prevAC, node = ctx.node, tree = ctx.tree, opts = ctx.options, noAnimation = (callOpts.noAnimation === true), noEvents = (callOpts.noEvents === true); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetExpanded(" + flag + ")"); if((node.expanded && flag) || (!node.expanded && !flag)){ // Nothing to do // node.debug("nodeSetExpanded(" + flag + "): nothing to do"); return _getResolvedPromise(node); }else if(flag && !node.lazy && !node.hasChildren() ){ // Prevent expanding of empty nodes // return _getRejectedPromise(node, ["empty"]); return _getResolvedPromise(node); }else if( !flag && node.getLevel() < opts.minExpandLevel ) { // Prevent collapsing locked levels return _getRejectedPromise(node, ["locked"]); }else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } // If this node inside a collpased node, no animation and scrolling is needed if( !noAnimation && !node.isVisible() ) { noAnimation = callOpts.noAnimation = true; } dfd = new $.Deferred(); // Auto-collapse mode: collapse all siblings if( flag && !node.expanded && opts.autoCollapse ) { parents = node.getParentList(false, true); prevAC = opts.autoCollapse; try{ opts.autoCollapse = false; for(i=0, l=parents.length; i<l; i++){ // TODO: should return promise? this._callHook("nodeCollapseSiblings", parents[i], callOpts); } }finally{ opts.autoCollapse = prevAC; } } // Trigger expand/collapse after expanding dfd.done(function(){ var lastChild = node.getLastChild(); if( flag && opts.autoScroll && !noAnimation && lastChild ) { // Scroll down to last child, but keep current node visible lastChild.scrollIntoView(true, {topNode: node}).always(function(){ if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } }); } else { if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } } }); // vvv Code below is executed after loading finished: _afterLoad = function(callback){ var cn = opts._classNames, isVisible, isExpanded, effect = opts.toggleEffect; node.expanded = flag; // Create required markup, but make sure the top UL is hidden, so we // can animate later tree._callHook("nodeRender", ctx, false, false, true); // Hide children, if node is collapsed if( node.ul ) { isVisible = (node.ul.style.display !== "none"); isExpanded = !!node.expanded; if ( isVisible === isExpanded ) { node.warn("nodeSetExpanded: UL.style.display already set"); } else if ( !effect || noAnimation ) { node.ul.style.display = ( node.expanded || !parent ) ? "" : "none"; } else { // The UI toggle() effect works with the ext-wide extension, // while jQuery.animate() has problems when the title span // has positon: absolute. // Since jQuery UI 1.12, the blind effect requires the parent // element to have 'position: relative'. // See #716, #717 $(node.li).addClass(cn.animating); // #717 // node.info("fancytree-animating start: " + node.li.className); $(node.ul) .addClass(cn.animating) // # 716 .toggle(effect.effect, effect.options, effect.duration, function(){ // node.info("fancytree-animating end: " + node.li.className); $(this).removeClass(cn.animating); // #716 $(node.li).removeClass(cn.animating); // #717 callback(); }); return; } } callback(); }; // ^^^ Code above is executed after loading finshed. // Load lazy nodes, if any. Then continue with _afterLoad() if(flag && node.lazy && node.hasChildren() === undefined){ // node.debug("nodeSetExpanded: load start..."); node.load().done(function(){ // node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad(function () { dfd.resolveWith(node); }); }).fail(function(errMsg){ _afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); }); /* var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent); _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); node.debug("nodeSetExpanded: load start..."); this._callHook("nodeLoadChildren", ctx, source).done(function(){ node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad.call(tree); }).fail(function(errMsg){ dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); */ }else{ _afterLoad(function () { dfd.resolveWith(node); }); } // node.debug("nodeSetExpanded: returns"); return dfd.promise(); }, /** Focus or blur this node. * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetFocus: function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node, opts = tree.options, // et = ctx.originalEvent && ctx.originalEvent.type, isInput = ctx.originalEvent ? $(ctx.originalEvent.target).is(":input") : false; flag = (flag !== false); // (node || tree).debug("nodeSetFocus(" + flag + "), event: " + et + ", isInput: "+ isInput); // Blur previous node if any if(tree.focusNode){ if(tree.focusNode === node && flag){ // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, {node: tree.focusNode}); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if(flag){ if( !this.hasFocus() ){ node.debug("nodeSetFocus: forcing container focus"); this._callHook("treeSetFocus", ctx, true, {calledByNode: true}); } node.makeVisible({scrollIntoView: false}); tree.focusNode = node; if( opts.titlesTabbable ) { if( !isInput ) { // #621 $(node.span).find(".fancytree-title").focus(); } } else { // We cannot set KB focus to a node, so use the tree container // #563, #570: IE scrolls on every call to .focus(), if the container // is partially outside the viewport. So do it only, when absolutely // neccessary: if( $(document.activeElement).closest(".fancytree-container").length === 0 ) { $(tree.$container).focus(); } } if( opts.aria ){ // Set active descendant to node's span ID (create one, if needed) $(tree.$container).attr("aria-activedescendant", $( node.tr || node.li ).uniqueId().attr("id")); // "ftal_" + opts.idPrefix + node.key); } // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // if( opts.autoActivate ){ // tree.nodeSetActive(ctx, true); // } if( opts.autoScroll ){ node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }, /** (De)Select node, return new status (sync). * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false, * propagateDown: null, propagateUp: null, * callback: null, * } * @returns {boolean} previous status */ nodeSetSelected: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = (callOpts.noEvents === true), parent = node.parent; // flag defaults to true flag = (flag !== false); // node.debug("nodeSetSelected(" + flag + ")", ctx); // Cannot (de)select unselectable nodes directly (only by propagation or // by setting the `.selected` property) if( FT.evalOption("unselectable", node, node, opts, false) ){ return; } // Remember the user's intent, in case down -> up propagation prevents // applying it to node.selected node._lastSelectIntent = flag; // Nothing to do? /*jshint -W018 */ // Confusing use of '!' if( !!node.selected === flag ){ if( opts.selectMode === 3 && node.partsel && !flag ){ // If propagation prevented selecting this node last time, we still // want to allow to apply setSelected(false) now }else{ return flag; } } /*jshint +W018 */ if( !noEvents && this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ) { return !!node.selected; } if(flag && opts.selectMode === 1){ // single selection mode (we don't uncheck all tree nodes, for performance reasons) if(tree.lastSelectedNode){ tree.lastSelectedNode.setSelected(false); } node.selected = flag; }else if(opts.selectMode === 3 && parent && !parent.radiogroup && !node.radiogroup){ // multi-hierarchical selection mode node.selected = flag; node.fixSelection3AfterClick(callOpts); }else if(parent && parent.radiogroup){ node.visitSiblings(function(n){ n._changeSelectStatusAttrs(flag && n === node); }, true); }else{ // default: selectMode: 2, multi selection mode node.selected = flag; } this.nodeRenderStatus(ctx); tree.lastSelectedNode = flag ? node : null; if( !noEvents ) { tree._triggerNodeEvent("select", ctx); } }, /** Show node status (ok, loading, error, nodata) using styles and a dummy child node. * * @param {EventData} ctx * @param status * @param message * @param details * @since 2.3 */ nodeSetStatus: function(ctx, status, message, details) { var node = ctx.node, tree = ctx.tree; function _clearStatusNode() { // Remove dedicated dummy node, if any var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { try{ // I've seen exceptions here with loadKeyPath... if(node.ul){ node.ul.removeChild(firstChild.li); firstChild.li = null; // avoid leaks (DT issue 215) } }catch(e){} if( node.children.length === 1 ){ node.children = []; }else{ node.children.shift(); } } } function _setStatusNode(data, type) { // Create/modify the dedicated dummy node for 'loading...' or // 'error!' status. (only called for direct child of the invisible // system root) var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $.extend(firstChild, data); firstChild.statusNodeType = type; tree._callHook("nodeRenderTitle", firstChild); } else { node._setChildren([data]); node.children[0].statusNodeType = type; tree.render(); } return node.children[0]; } switch( status ){ case "ok": _clearStatusNode(); node._isLoading = false; node._error = null; node.renderStatus(); break; case "loading": if( !node.parent ) { _setStatusNode({ title: tree.options.strings.loading + (message ? " (" + message + ")" : ""), // icon: true, // needed for 'loding' icon checkbox: false, tooltip: details }, status); } node._isLoading = true; node._error = null; node.renderStatus(); break; case "error": _setStatusNode({ title: tree.options.strings.loadError + (message ? " (" + message + ")" : ""), // icon: false, checkbox: false, tooltip: details }, status); node._isLoading = false; node._error = { message: message, details: details }; node.renderStatus(); break; case "nodata": _setStatusNode({ title: tree.options.strings.noData, // icon: false, checkbox: false, tooltip: details }, status); node._isLoading = false; node._error = null; node.renderStatus(); break; default: $.error("invalid node status " + status); } }, /** * * @param {EventData} ctx */ nodeToggleExpanded: function(ctx) { return this.nodeSetExpanded(ctx, !ctx.node.expanded); }, /** * @param {EventData} ctx */ nodeToggleSelected: function(ctx) { var node = ctx.node, flag = !node.selected; // In selectMode: 3 this node may be unselected+partsel, even if // setSelected(true) was called before, due to `unselectable` children. // In this case, we now toggle as `setSelected(false)` if( node.partsel && !node.selected && node._lastSelectIntent === true ) { flag = false; node.selected = true; // so it is not considered 'nothing to do' } node._lastSelectIntent = flag; return this.nodeSetSelected(ctx, flag); }, /** Remove all nodes. * @param {EventData} ctx */ treeClear: function(ctx) { var tree = ctx.tree; tree.activeNode = null; tree.focusNode = null; tree.$div.find(">ul.fancytree-container").empty(); // TODO: call destructors and remove reference loops tree.rootNode.children = null; }, /** Widget was created (called only once, even it re-initialized). * @param {EventData} ctx */ treeCreate: function(ctx) { }, /** Widget was destroyed. * @param {EventData} ctx */ treeDestroy: function(ctx) { this.$div.find(">ul.fancytree-container").remove(); this.$source && this.$source.removeClass("fancytree-helper-hidden"); }, /** Widget was (re-)initialized. * @param {EventData} ctx */ treeInit: function(ctx) { var tree = ctx.tree, opts = tree.options; //this.debug("Fancytree.treeInit()"); // Add container to the TAB chain // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant // #577: Allow to set tabindex to "0", "-1" and "" tree.$container.attr("tabindex", opts.tabindex); // Copy some attributes to tree.data $.each(TREE_ATTRS, function(i, attr) { if( opts[attr] !== undefined ){ tree.info("Move option " + attr + " to tree"); tree[attr] = opts[attr]; delete opts[attr]; } }); if( opts.rtl ) { tree.$container.attr("DIR", "RTL").addClass("fancytree-rtl"); }else{ tree.$container.removeAttr("DIR").removeClass("fancytree-rtl"); } if( opts.aria ){ tree.$container.attr("role", "tree"); if( opts.selectMode !== 1 ) { tree.$container.attr("aria-multiselectable", true); } } this.treeLoad(ctx); }, /** Parse Fancytree from source, as configured in the options. * @param {EventData} ctx * @param {object} [source] optional new source (use last data otherwise) */ treeLoad: function(ctx, source) { var metaData, type, $ul, tree = ctx.tree, $container = ctx.widget.element, dfd, // calling context for root node rootCtx = $.extend({}, ctx, {node: this.rootNode}); if(tree.rootNode.children){ this.treeClear(ctx); } source = source || this.options.source; if(!source){ type = $container.data("type") || "html"; switch(type){ case "html": $ul = $container.find(">ul:first"); $ul.addClass("ui-fancytree-source fancytree-helper-hidden"); source = $.ui.fancytree.parseHtml($ul); // allow to init tree.data.foo from <ul data-foo=''> this.data = $.extend(this.data, _getElementDataAsDict($ul)); break; case "json": source = $.parseJSON($container.text()); // $container already contains the <ul>, but we remove the plain (json) text // $container.empty(); $container.contents().filter(function(){ return (this.nodeType === 3); }).remove(); if( $.isPlainObject(source) ){ // We got {foo: 'abc', children: [...]} _assert($.isArray(source.children), "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')"); metaData = source; source = source.children; delete metaData.children; // Copy some attributes to tree.data $.each(TREE_ATTRS, function(i, attr) { if( metaData[attr] !== undefined ){ tree[attr] = metaData[attr]; delete metaData[attr]; } }); // Copy extra properties to tree.data.foo $.extend(tree.data, metaData); } break; default: $.error("Invalid data-type: " + type); } }else if(typeof source === "string"){ // TODO: source is an element ID $.error("Not implemented"); } // Trigger fancytreeinit after nodes have been loaded dfd = this.nodeLoadChildren(rootCtx, source).done(function(){ tree.render(); if( ctx.options.selectMode === 3 ){ tree.rootNode.fixSelection3FromEndNodes(); } if( tree.activeNode && tree.options.activeVisible ) { tree.activeNode.makeVisible(); } tree._triggerTreeEvent("init", null, { status: true }); }).fail(function(){ tree.render(); tree._triggerTreeEvent("init", null, { status: false }); }); return dfd; }, /** Node was inserted into or removed from the tree. * @param {EventData} ctx * @param {boolean} add * @param {FancytreeNode} node */ treeRegisterNode: function(ctx, add, node) { }, /** Widget got focus. * @param {EventData} ctx * @param {boolean} [flag=true] */ treeSetFocus: function(ctx, flag, callOpts) { var targetNode; flag = (flag !== false); // this.debug("treeSetFocus(" + flag + "), callOpts: ", callOpts, this.hasFocus()); // this.debug(" focusNode: " + this.focusNode); // this.debug(" activeNode: " + this.activeNode); if( flag !== this.hasFocus() ){ this._hasFocus = flag; if( !flag && this.focusNode ) { // Node also looses focus if widget blurs this.focusNode.setFocus(false); } else if ( flag && (!callOpts || !callOpts.calledByNode) ) { $(this.$container).focus(); } this.$container.toggleClass("fancytree-treefocus", flag); this._triggerTreeEvent(flag ? "focusTree" : "blurTree"); if( flag && !this.activeNode ) { // #712: Use last mousedowned node ('click' event fires after focusin) targetNode = this._lastMousedownNode || this.getFirstChild(); targetNode && targetNode.setFocus(); } } }, /** Widget option was set using `$().fancytree("option", "foo", "bar")`. * @param {EventData} ctx * @param {string} key option name * @param {any} value option value */ treeSetOption: function(ctx, key, value) { var tree = ctx.tree, callDefault = true, callCreate = false, callRender = false; switch( key ) { case "aria": case "checkbox": case "icon": case "minExpandLevel": case "tabindex": // tree._callHook("treeCreate", tree); callCreate = true; callRender = true; break; case "escapeTitles": case "tooltip": callRender = true; break; case "rtl": if( value === false ) { tree.$container.removeAttr("DIR").removeClass("fancytree-rtl"); }else{ tree.$container.attr("DIR", "RTL").addClass("fancytree-rtl"); } callRender = true; break; case "source": callDefault = false; tree._callHook("treeLoad", tree, value); callRender = true; break; } tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">"); if(callDefault){ if( this.widget._super ) { // jQuery UI 1.9+ this.widget._super.call( this.widget, key, value ); } else { // jQuery UI <= 1.8, we have to manually invoke the _setOption method from the base widget $.Widget.prototype._setOption.call(this.widget, key, value); } } if(callCreate){ tree._callHook("treeCreate", tree); } if(callRender){ tree.render(true, false); // force, not-deep } } }); /* ****************************************************************************** * jQuery UI widget boilerplate */ /** * The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br> * This constructor is not called directly. Use `$(selector).fancytree({})` * to initialize the plugin instead.<br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members: * var tree = $("#tree").fancytree("getTree"); * var node = $("#tree").fancytree("getActiveNode", "1234"); * </pre> * * @mixin Fancytree_Widget */ $.widget("ui.fancytree", /** @lends Fancytree_Widget# */ { /**These options will be used as defaults * @type {FancytreeOptions} */ options: { activeVisible: true, ajax: { type: "GET", cache: false, // false: Append random '_' argument to the request url to prevent caching. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable dataType: "json" // Expect json format and pass json object to callbacks. }, // aria: true, autoActivate: true, autoCollapse: false, autoScroll: false, checkbox: false, clickFolderMode: 4, debugLevel: null, // 0..4 (null: use global setting $.ui.fancytree.debugInfo) disabled: false, // TODO: required anymore? enableAspx: true, escapeTitles: false, extensions: [], // fx: { height: "toggle", duration: 200 }, // toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 }, // toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 }, toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }, generateIds: false, icon: true, idPrefix: "ft_", focusOnSelect: false, keyboard: true, keyPathSeparator: "/", minExpandLevel: 1, quicksearch: false, rtl: false, scrollOfs: {top: 0, bottom: 0}, scrollParent: null, selectMode: 2, strings: { loading: "Loading...", // &#8230; would be escaped when escapeTitles is true loadError: "Load error!", moreData: "More...", noData: "No data." }, tabindex: "0", titlesTabbable: false, tooltip: false, _classNames: { node: "fancytree-node", folder: "fancytree-folder", animating: "fancytree-animating", combinedExpanderPrefix: "fancytree-exp-", combinedIconPrefix: "fancytree-ico-", hasChildren: "fancytree-has-children", active: "fancytree-active", selected: "fancytree-selected", expanded: "fancytree-expanded", lazy: "fancytree-lazy", focused: "fancytree-focused", partload: "fancytree-partload", partsel: "fancytree-partsel", radio: "fancytree-radio", // radiogroup: "fancytree-radiogroup", unselectable: "fancytree-unselectable", lastsib: "fancytree-lastsib", loading: "fancytree-loading", error: "fancytree-error", statusNodePrefix: "fancytree-statusnode-" }, // events lazyLoad: null, postProcess: null }, /* Set up the widget, Called on first $().fancytree() */ _create: function() { this.tree = new Fancytree(this); this.$source = this.source || this.element.data("type") === "json" ? this.element : this.element.find(">ul:first"); // Subclass Fancytree instance with all enabled extensions var extension, extName, i, opts = this.options, extensions = opts.extensions, base = this.tree; for(i=0; i<extensions.length; i++){ extName = extensions[i]; extension = $.ui.fancytree._extensions[extName]; if(!extension){ $.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)"); } // Add extension options as tree.options.EXTENSION // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName); this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]); // Add a namespace tree.ext.EXTENSION, to hold instance data _assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'"); // this.tree[extName] = extension; this.tree.ext[extName] = {}; // Subclass Fancytree methods using proxies. _subclassObject(this.tree, base, extension, extName); // current extension becomes base for the next extension base = extension; } // if( opts.icons !== undefined ) { // 2015-11-16 if( opts.icon !== true ) { $.error("'icons' tree option is deprecated since v2.14.0: use 'icon' only instead"); } else { this.tree.warn("'icons' tree option is deprecated since v2.14.0: use 'icon' instead"); opts.icon = opts.icons; } } if( opts.iconClass !== undefined ) { // 2015-11-16 if( opts.icon ) { $.error("'iconClass' tree option is deprecated since v2.14.0: use 'icon' only instead"); } else { this.tree.warn("'iconClass' tree option is deprecated since v2.14.0: use 'icon' instead"); opts.icon = opts.iconClass; } } if( opts.tabbable !== undefined ) { // 2016-04-04 opts.tabindex = opts.tabbable ? "0" : "-1"; this.tree.warn("'tabbable' tree option is deprecated since v2.17.0: use 'tabindex='" + opts.tabindex + "' instead"); } // this.tree._callHook("treeCreate", this.tree); // Note: 'fancytreecreate' event is fired by widget base class // this.tree._triggerTreeEvent("create"); }, /* Called on every $().fancytree() */ _init: function() { this.tree._callHook("treeInit", this.tree); // TODO: currently we call bind after treeInit, because treeInit // might change tree.$container. // It would be better, to move event binding into hooks altogether this._bind(); }, /* Use the _setOption method to respond to changes to options */ _setOption: function(key, value) { return this.tree._callHook("treeSetOption", this.tree, key, value); }, /** Use the destroy method to clean up any modifications your widget has made to the DOM */ destroy: function() { this._unbind(); this.tree._callHook("treeDestroy", this.tree); // In jQuery UI 1.8, you must invoke the destroy method from the base widget $.Widget.prototype.destroy.call(this); // TODO: delete tree and nodes to make garbage collect easier? // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method }, // ------------------------------------------------------------------------- /* Remove all event handlers for our namespace */ _unbind: function() { var ns = this.tree._ns; this.element.off(ns); this.tree.$container.off(ns); $(document).off(ns); }, /* Add mouse and kyboard handlers to the container */ _bind: function() { var that = this, opts = this.options, tree = this.tree, ns = tree._ns // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" ) ; // Remove all previuous handlers for this tree this._unbind(); //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container); // tree.debug("bind events; container: ", tree.$container); tree.$container.on("focusin" + ns + " focusout" + ns, function(event){ var node = FT.getNode(event), flag = (event.type === "focusin"); // tree.treeOnFocusInOut.call(tree, event); // tree.debug("Tree container got event " + event.type, node, event, FT.getEventTarget(event)); if( flag && tree._getExpiringValue("focusin") ) { // #789: IE 11 may send duplicate focusin events FT.info("Ignored double focusin."); return; } tree._setExpiringValue("focusin", true, 50); if( flag && !node ) { // #789: IE 11 may send focusin before mousdown(?) node = tree._getExpiringValue("mouseDownNode"); if( node ) { FT.info("Reconstruct mouse target for focusin from recent event."); } } if(node){ // For example clicking into an <input> that is part of a node tree._callHook("nodeSetFocus", tree._makeHookContext(node, event), flag); }else{ if( tree.tbody && $(event.target).parents("table.fancytree-container > thead").length ) { // #767: ignore events in the table's header tree.debug("Ignore focus event outside table body.", event); } else { tree._callHook("treeSetFocus", tree, flag); } } }).on("selectstart" + ns, "span.fancytree-title", function(event){ // prevent mouse-drags to select text ranges // tree.debug("<span title> got event " + event.type); event.preventDefault(); }).on("keydown" + ns, function(event){ // TODO: also bind keyup and keypress // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus()); // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){ if(opts.disabled || opts.keyboard === false ){ return true; } var res, node = tree.focusNode, // node may be null ctx = tree._makeHookContext(node || tree, event), prevPhase = tree.phase; try { tree.phase = "userEvent"; // If a 'fancytreekeydown' handler returns false, skip the default // handling (implemented by tree.nodeKeydown()). if(node){ res = tree._triggerNodeEvent("keydown", node, event); }else{ res = tree._triggerTreeEvent("keydown", event); } if ( res === "preventNav" ){ res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls } else if ( res !== false ){ res = tree._callHook("nodeKeydown", ctx); } return res; } finally { tree.phase = prevPhase; } }).on("mousedown" + ns, function(event){ var et = FT.getEventTarget(event); // that.tree.debug("event(" + event.type + "): node: ", et.node); // #712: Store the clicked node, so we can use it when we get a focusin event // ('click' event fires after focusin) // tree.debug("event(" + event.type + "): node: ", et.node); tree._lastMousedownNode = et ? et.node : null; // #789: Store the node also for a short period, so we can use it // in a *resulting* focusin event tree._setExpiringValue("mouseDownNode", tree._lastMousedownNode); }).on("click" + ns + " dblclick" + ns, function(event){ if(opts.disabled){ return true; } var ctx, et = FT.getEventTarget(event), node = et.node, tree = that.tree, prevPhase = tree.phase; // that.tree.debug("event(" + event.type + "): node: ", node); if( !node ){ return true; // Allow bubbling of other events } ctx = tree._makeHookContext(node, event); // that.tree.debug("event(" + event.type + "): node: ", node); try { tree.phase = "userEvent"; switch(event.type) { case "click": ctx.targetType = et.type; if( node.isPagingNode() ) { return tree._triggerNodeEvent("clickPaging", ctx, event) === true; } return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx); case "dblclick": ctx.targetType = et.type; return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx); } } finally { tree.phase = prevPhase; } }); }, /** Return the active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.tree.activeNode; }, /** Return the matching node or null. * @param {string} key * @returns {FancytreeNode} */ getNodeByKey: function(key) { return this.tree.getNodeByKey(key); }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.tree.rootNode; }, /** Return the current tree instance. * @returns {Fancytree} */ getTree: function() { return this.tree; } }); // $.ui.fancytree was created by the widget factory. Create a local shortcut: FT = $.ui.fancytree; /** * Static members in the `$.ui.fancytree` namespace.<br> * <br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access static members: * var node = $.ui.fancytree.getNode(element); * alert($.ui.fancytree.version); * </pre> * * @mixin Fancytree_Static */ $.extend($.ui.fancytree, /** @lends Fancytree_Static# */ { /** @type {string} */ version: "2.28.0", // Set to semver by 'grunt release' /** @type {string} */ buildType: "production", // Set to 'production' by 'grunt build' /** @type {int} */ debugLevel: 3, // Set to 3 by 'grunt build' // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel _nextId: 1, _nextNodeKey: 1, _extensions: {}, // focusTree: null, /** Expose class object as $.ui.fancytree._FancytreeClass */ _FancytreeClass: Fancytree, /** Expose class object as $.ui.fancytree._FancytreeNodeClass */ _FancytreeNodeClass: FancytreeNode, /* Feature checks to provide backwards compatibility */ jquerySupports: { // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at positionMyOfs: isVersionAtLeast($.ui.version, 1, 9) }, /** Throw an error if condition fails (debug method). * @param {boolean} cond * @param {string} msg */ assert: function(cond, msg){ return _assert(cond, msg); }, /** Create a new Fancytree instance on a target element. * * @param {Element | jQueryObject | string} el Target DOM element or selector * @param {FancytreeOptions} [opts] Fancytree options * @returns {Fancytree} new tree instance * @example * var tree = $.ui.fancytree.createTree("#tree", { * source: {url: "my/webservice"} * }); // Create tree for this matching element * * @since 2.25 */ createTree: function(el, opts){ var tree = $(el).fancytree(opts).fancytree("getTree"); return tree; }, /** Return a function that executes *fn* at most every *timeout* ms. * @param {integer} timeout * @param {function} fn * @param {boolean} [invokeAsap=false] * @param {any} [ctx] */ debounce: function(timeout, fn, invokeAsap, ctx) { var timer; if(arguments.length === 3 && typeof invokeAsap !== "boolean") { ctx = invokeAsap; invokeAsap = false; } return function() { var args = arguments; ctx = ctx || this; invokeAsap && !timer && fn.apply(ctx, args); clearTimeout(timer); timer = setTimeout(function() { invokeAsap || fn.apply(ctx, args); timer = null; }, timeout); }; }, /** Write message to console if debugLevel >= 4 * @param {string} msg */ debug: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 4) && consoleApply("log", arguments); }, /** Write error message to console if debugLevel >= 1. * @param {string} msg */ error: function(msg){ ($.ui.fancytree.debugLevel >= 1) && consoleApply("error", arguments); }, /** Convert &lt;, &gt;, &amp;, &quot;, &#39;, &#x2F; to the equivalent entities. * * @param {string} s * @returns {string} */ escapeHtml: function(s){ return ("" + s).replace(REX_HTML, function(s) { return ENTITY_MAP[s]; }); }, /** Make jQuery.position() arguments backwards compatible, i.e. if * jQuery UI version <= 1.8, convert * { my: "left+3 center", at: "left bottom", of: $target } * to * { my: "left center", at: "left bottom", of: $target, offset: "3 0" } * * See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at * and http://jsfiddle.net/mar10/6xtu9a4e/ */ fixPositionOptions: function(opts) { if( opts.offset || ("" + opts.my + opts.at ).indexOf("%") >= 0 ) { $.error("expected new position syntax (but '%' is not supported)"); } if( ! $.ui.fancytree.jquerySupports.positionMyOfs ) { var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined] myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.my), atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.at), // convert to numbers dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0), dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0); opts = $.extend({}, opts, { // make a copy and overwrite my: myParts[1] + " " + myParts[3], at: atParts[1] + " " + atParts[3] }); if( dx || dy ) { opts.offset = "" + dx + " " + dy; } } return opts; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {object} Return a {node: FancytreeNode, type: TYPE} object * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTarget: function(event){ var $target, tcn = event && event.target ? event.target.className : "", res = {node: this.getNode(event.target), type: undefined}; // We use a fast version of $(res.node).hasClass() // See http://jsperf.com/test-for-classname/2 if( /\bfancytree-title\b/.test(tcn) ){ res.type = "title"; }else if( /\bfancytree-expander\b/.test(tcn) ){ res.type = (res.node.hasChildren() === false ? "prefix" : "expander"); // }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){ }else if( /\bfancytree-checkbox\b/.test(tcn) ){ res.type = "checkbox"; }else if( /\bfancytree(-custom)?-icon\b/.test(tcn) ){ res.type = "icon"; }else if( /\bfancytree-node\b/.test(tcn) ){ // Somewhere near the title res.type = "title"; }else if( event && event.target ) { $target = $(event.target); if( $target.is("ul[role=group]") ) { // #nnn: Clicking right to a node may hit the surrounding UL FT.info("Ignoring click on outer UL."); res.node = null; }else if( $target.closest(".fancytree-title").length ) { // #228: clicking an embedded element inside a title res.type = "title"; }else if( $target.closest(".fancytree-checkbox").length ) { // E.g. <svg> inside checkbox span res.type = "checkbox"; }else if( $target.closest(".fancytree-expander").length ) { res.type = "expander"; } } return res; }, /** Return a string describing the affected node region for a mouse event. * * @param {Event} event Mouse event, e.g. click, mousemove, ... * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTargetType: function(event){ return this.getEventTarget(event).type; }, /** Return a FancytreeNode instance from element, event, or jQuery object. * * @param {Element | jQueryObject | Event} el * @returns {FancytreeNode} matching node or null */ getNode: function(el){ if(el instanceof FancytreeNode){ return el; // el already was a FancytreeNode }else if( el instanceof $ ){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } while( el ) { if(el.ftnode) { return el.ftnode; } el = el.parentNode; } return null; }, /** Return a Fancytree instance, from element, index, event, or jQueryObject. * * @param {Element | jQueryObject | Event | integer | string} [el] * @returns {Fancytree} matching tree or null * @example * $.ui.fancytree.getTree(); // Get first Fancytree instance on page * $.ui.fancytree.getTree(1); // Get second Fancytree instance on page * $.ui.fancytree.getTree("#tree"); // Get tree for this matching element * * @since 2.13 */ getTree: function(el){ var widget; if( el instanceof Fancytree ) { return el; // el already was a Fancytree } if( el === undefined ) { el = 0; // get first tree } if( typeof el === "number" ) { el = $(".fancytree-container").eq(el); // el was an integer: return nth instance } else if( typeof el === "string" ) { el = $(el).eq(0); // el was a selector: use first match } else if( el.selector !== undefined ) { el = el.eq(0); // el was a jQuery object: use the first DOM element } else if( el.originalEvent !== undefined ) { el = $(el.target); // el was an Event } el = el.closest(":ui-fancytree"); widget = el.data("ui-fancytree") || el.data("fancytree"); // the latter is required by jQuery <= 1.8 return widget ? widget.tree : null; }, /** Return an option value that has a default, but may be overridden by a * callback or a node instance attribute. * * Evaluation sequence:<br> * * If tree.options.<optionName> is a callback that returns something, use that.<br> * Else if node.<optionName> is defined, use that.<br> * Else if tree.options.<optionName> is a value, use that.<br> * Else use `defaultValue`. * * @param {string} optionName name of the option property (on node and tree) * @param {FancytreeNode} node passed to the callback * @param {object} nodeObject where to look for the local option property, e.g. `node` or `node.data` * @param {object} treeOption where to look for the tree option, e.g. `tree.options` or `tree.options.dnd5` * @param {any} [defaultValue] * @returns {any} * * @example * // Check for node.foo, tree,options.foo(), and tree.options.foo: * $.ui.fancytree.evalOption("foo", node, node, tree.options); * // Check for node.data.bar, tree,options.qux.bar(), and tree.options.qux.bar: * $.ui.fancytree.evalOption("bar", node, node.data, tree.options.qux); * * @since 2.22 */ evalOption: function(optionName, node, nodeObject, treeOptions, defaultValue) { var ctx, res, tree = node.tree, treeOpt = treeOptions[optionName], nodeOpt = nodeObject[optionName]; if( $.isFunction(treeOpt) ) { ctx = { node: node, tree: tree, widget: tree.widget, options: tree.widget.options, typeInfo: tree.types[node.type] || {} }; res = treeOpt.call(tree, {type: optionName}, ctx); if( res == null ) { res = nodeOpt; } } else { res = (nodeOpt != null) ? nodeOpt : treeOpt; } if( res == null ) { res = defaultValue; // no option set at all: return default } return res; }, /** Set expander, checkbox, or node icon, supporting string and object format. * * @param {Element | jQueryObject} span * @param {string} baseClass * @param {string | object} icon * @since 2.27 */ setSpanIcon: function( span, baseClass, icon ) { var $span = $( span ); if( typeof icon === "string" ) { $span.attr( "class", baseClass + " " + icon ); } else { // support object syntax: { text: ligature, addClasse: classname } if( icon.text ) { $span.text( "" + icon.text ); } else if ( icon.html ) { span.innerHTML = icon.html; } $span.attr( "class", baseClass + " " + ( icon.addClass || "" ) ); } }, /** Convert a keydown or mouse event to a canonical string like 'ctrl+a', * 'ctrl+shift+f2', 'shift+leftdblclick'. * * This is especially handy for switch-statements in event handlers. * * @param {event} * @returns {string} * * @example switch( $.ui.fancytree.eventToString(event) ) { case "-": tree.nodeSetExpanded(ctx, false); break; case "shift+return": tree.nodeSetActive(ctx, true); break; case "down": res = node.navigate(event.which, activate); break; default: handled = false; } if( handled ){ event.preventDefault(); } */ eventToString: function(event) { // Poor-man's hotkeys. See here for a complete implementation: // https://github.com/jeresig/jquery.hotkeys var which = event.which, et = event.type, s = []; if( event.altKey ) { s.push("alt"); } if( event.ctrlKey ) { s.push("ctrl"); } if( event.metaKey ) { s.push("meta"); } if( event.shiftKey ) { s.push("shift"); } if( et === "click" || et === "dblclick" ) { s.push(MOUSE_BUTTONS[event.button] + et); } else { if( !IGNORE_KEYCODES[which] ) { s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() ); } } return s.join("+"); }, /** Write message to console if debugLevel >= 3 * @param {string} msg */ info: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 3) && consoleApply("info", arguments); }, /* @deprecated: use eventToString(event) instead. */ keyEventToString: function(event) { this.warn("keyEventToString() is deprecated: use eventToString()"); return this.eventToString(event); }, /** Return a wrapped handler method, that provides `this.super`. * * @example // Implement `opts.createNode` event to add the 'draggable' attribute $.ui.fancytree.overrideMethod(ctx.options, "createNode", function(event, data) { // Default processing if any this._super.apply(this, arguments); // Add 'draggable' attribute data.node.span.draggable = true; }); * * @param {object} instance * @param {string} methodName * @param {function} handler */ overrideMethod: function(instance, methodName, handler){ var prevSuper, _super = instance[methodName] || $.noop; // context = context || this; instance[methodName] = function() { try { prevSuper = this._super; this._super = _super; return handler.apply(this, arguments); } finally { this._super = prevSuper; } }; }, /** * Parse tree data from HTML <ul> markup * * @param {jQueryObject} $ul * @returns {NodeData[]} */ parseHtml: function($ul) { // TODO: understand this: /*jshint validthis:true */ var classes, className, extraClasses, i, iPos, l, tmp, tmp2, $children = $ul.find(">li"), children = []; $children.each(function() { var allData, lowerCaseAttr, $li = $(this), $liSpan = $li.find(">span:first", this), $liA = $liSpan.length ? null : $li.find(">a:first"), d = { tooltip: null, data: {} }; if( $liSpan.length ) { d.title = $liSpan.html(); } else if( $liA && $liA.length ) { // If a <li><a> tag is specified, use it literally and extract href/target. d.title = $liA.html(); d.data.href = $liA.attr("href"); d.data.target = $liA.attr("target"); d.tooltip = $liA.attr("title"); } else { // If only a <li> tag is specified, use the trimmed string up to // the next child <ul> tag. d.title = $li.html(); iPos = d.title.search(/<ul/i); if( iPos >= 0 ){ d.title = d.title.substring(0, iPos); } } d.title = $.trim(d.title); // Make sure all fields exist for(i=0, l=CLASS_ATTRS.length; i<l; i++){ d[CLASS_ATTRS[i]] = undefined; } // Initialize to `true`, if class is set and collect extraClasses classes = this.className.split(" "); extraClasses = []; for(i=0, l=classes.length; i<l; i++){ className = classes[i]; if(CLASS_ATTR_MAP[className]){ d[className] = true; }else{ extraClasses.push(className); } } d.extraClasses = extraClasses.join(" "); // Parse node options from ID, title and class attributes tmp = $li.attr("title"); if( tmp ){ d.tooltip = tmp; // overrides <a title='...'> } tmp = $li.attr("id"); if( tmp ){ d.key = tmp; } // Translate hideCheckbox -> checkbox:false if( $li.attr("hideCheckbox") ){ d.checkbox = false; } // Add <li data-NAME='...'> as node.data.NAME allData = _getElementDataAsDict($li); if( allData && !$.isEmptyObject(allData) ) { // #507: convert data-hidecheckbox (lower case) to hideCheckbox for( lowerCaseAttr in NODE_ATTR_LOWERCASE_MAP ) { if( allData.hasOwnProperty(lowerCaseAttr) ) { allData[NODE_ATTR_LOWERCASE_MAP[lowerCaseAttr]] = allData[lowerCaseAttr]; delete allData[lowerCaseAttr]; } } // #56: Allow to set special node.attributes from data-... for(i=0, l=NODE_ATTRS.length; i<l; i++){ tmp = NODE_ATTRS[i]; tmp2 = allData[tmp]; if( tmp2 != null ) { delete allData[tmp]; d[tmp] = tmp2; } } // All other data-... goes to node.data... $.extend(d.data, allData); } // Recursive reading of child nodes, if LI tag contains an UL tag $ul = $li.find(">ul:first"); if( $ul.length ) { d.children = $.ui.fancytree.parseHtml($ul); }else{ d.children = d.lazy ? undefined : null; } children.push(d); // FT.debug("parse ", d, children); }); return children; }, /** Add Fancytree extension definition to the list of globally available extensions. * * @param {object} definition */ registerExtension: function(definition){ _assert(definition.name != null, "extensions must have a `name` property."); _assert(definition.version != null, "extensions must have a `version` property."); $.ui.fancytree._extensions[definition.name] = definition; }, /** Inverse of escapeHtml(). * * @param {string} s * @returns {string} */ unescapeHtml: function(s){ var e = document.createElement("div"); e.innerHTML = s; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; }, /** Write warning message to console if debugLevel >= 2. * @param {string} msg */ warn: function(msg){ ($.ui.fancytree.debugLevel >= 2) && consoleApply("warn", arguments); } }); // Value returned by `require('jquery.fancytree')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.childcounter.js' */// Extending Fancytree // =================== // // See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code. // // Every extension should have a comment header containing some information // about the author, copyright and licensing. Also a pointer to the latest // source code. // Prefix with `/*!` so the comment is not removed by the minifier. /*! * jquery.fancytree.childcounter.js * * Add a child counter bubble to tree nodes. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ // To keep the global namespace clean, we wrap everything in a closure. // The UMD wrapper pattern defines the dependencies on jQuery and the // Fancytree core module, and makes sure that we can use the `require()` // syntax with package loaders. ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { // Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) "use strict"; // The [coding guidelines](http://contribute.jquery.org/style-guide/js/) // require jshint compliance. // But for this sample, we want to allow unused variables for demonstration purpose. /*jshint unused:false */ // Adding methods // -------------- // New member functions can be added to the `Fancytree` class. // This function will be available for every tree instance: // // var tree = $("#tree").fancytree("getTree"); // tree.countSelected(false); $.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){ var tree = this, treeOptions = tree.options; return tree.getSelectedNodes(topOnly).length; }; // The `FancytreeNode` class can also be easily extended. This would be called // like // node.updateCounters(); // // It is also good practice to add a docstring comment. /** * [ext-childcounter] Update counter badges for `node` and its parents. * May be called in the `loadChildren` event, to update parents of lazy loaded * nodes. * @alias FancytreeNode#updateCounters * @requires jquery.fancytree.childcounters.js */ $.ui.fancytree._FancytreeNodeClass.prototype.updateCounters = function(){ var node = this, $badge = $("span.fancytree-childcounter", node.span), extOpts = node.tree.options.childcounter, count = node.countChildren(extOpts.deep); node.data.childCounter = count; if( (count || !extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ) { if( !$badge.length ) { $badge = $("<span class='fancytree-childcounter'/>").appendTo($("span.fancytree-icon", node.span)); } $badge.text(count); } else { $badge.remove(); } if( extOpts.deep && !node.isTopLevel() && !node.isRoot() ) { node.parent.updateCounters(); } }; // Finally, we can extend the widget API and create functions that are called // like so: // // $("#tree").fancytree("widgetMethod1", "abc"); $.ui.fancytree.prototype.widgetMethod1 = function(arg1){ var tree = this.tree; return arg1; }; // Register a Fancytree extension // ------------------------------ // A full blown extension, extension is available for all trees and can be // enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)): // // <script src="../src/jquery.fancytree.js"></script> // <script src="../src/jquery.fancytree.childcounter.js"></script> // ... // // $("#tree").fancytree({ // extensions: ["childcounter"], // childcounter: { // hideExpanded: true // }, // ... // }); // /* 'childcounter' extension */ $.ui.fancytree.registerExtension({ // Every extension must be registered by a unique name. name: "childcounter", // Version information should be compliant with [semver](http://semver.org) version: "2.28.0", // Extension specific options and their defaults. // This options will be available as `tree.options.childcounter.hideExpanded` options: { deep: true, hideZeros: true, hideExpanded: false }, // Attributes other than `options` (or functions) can be defined here, and // will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`. // They can also be accessed as `this._local.foo` from within the extension // methods. foo: 42, // Local functions are prefixed with an underscore '_'. // Callable as `this._local._appendCounter()`. _appendCounter: function(bar){ var tree = this; }, // **Override virtual methods for this extension.** // // Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'. // with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData) // for details) and an extended calling context:<br> // `this` : the Fancytree instance<br> // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br> // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree) // // See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html). /* Init */ // `treeInit` is triggered when a tree is initalized. We can set up classes or // bind event handlers here... treeInit: function(ctx){ var tree = this, // same as ctx.tree, opts = ctx.options, extOpts = ctx.options.childcounter; // Optionally check for dependencies with other extensions /* this._requireExtension("glyph", false, false); */ // Call the base implementation this._superApply(arguments); // Add a class to the tree container this.$container.addClass("fancytree-ext-childcounter"); }, // Destroy this tree instance (we only call the default implementation, so // this method could as well be omitted). treeDestroy: function(ctx){ this._superApply(arguments); }, // Overload the `renderTitle` hook, to append a counter badge nodeRenderTitle: function(ctx, title) { var node = ctx.node, extOpts = ctx.options.childcounter, count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter; // Let the base implementation render the title // We use `_super()` instead of `_superApply()` here, since it is a little bit // more performant when called often this._super(ctx, title); // Append a counter badge if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){ $("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count)); } }, // Overload the `setExpanded` hook, so the counters are updated nodeSetExpanded: function(ctx, flag, callOpts) { var tree = ctx.tree, node = ctx.node; // Let the base implementation expand/collapse the node, then redraw the title // after the animation has finished return this._superApply(arguments).always(function(){ tree.nodeRenderTitle(ctx); }); } // End of extension definition }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.clones.js' *//*! * * jquery.fancytree.clones.js * Support faster lookup of nodes by key and shared ref-ids. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /******************************************************************************* * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; $.error("Assertion failed" + msg); } } /* Return first occurrence of member from array. */ function _removeArrayMember(arr, elem) { // TODO: use Array.indexOf for IE >= 9 var i; for (i = arr.length - 1; i >= 0; i--) { if (arr[i] === elem) { arr.splice(i, 1); return true; } } return false; } // /** // * Calculate a 32 bit FNV-1a hash // * Found here: https://gist.github.com/vaiorabbit/5657561 // * Ref.: http://isthe.com/chongo/tech/comp/fnv/ // * // * @param {string} str the input value // * @param {boolean} [asString=false] set to true to return the hash value as // * 8-digit hex string instead of an integer // * @param {integer} [seed] optionally pass the hash of the previous chunk // * @returns {integer | string} // */ // function hashFnv32a(str, asString, seed) { // /*jshint bitwise:false */ // var i, l, // hval = (seed === undefined) ? 0x811c9dc5 : seed; // for (i = 0, l = str.length; i < l; i++) { // hval ^= str.charCodeAt(i); // hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); // } // if( asString ){ // // Convert to 8 digit hex string // return ("0000000" + (hval >>> 0).toString(16)).substr(-8); // } // return hval >>> 0; // } /** * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} key ASCII only * @param {boolean} [asString=false] * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ function hashMurmur3(key, asString, seed) { /*jshint bitwise:false */ var h1b, k1, remainder = key.length & 3, bytes = key.length - remainder, h1 = seed, c1 = 0xcc9e2d51, c2 = 0x1b873593, i = 0; while (i < bytes) { k1 = ((key.charCodeAt(i) & 0xff)) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); } k1 = 0; switch (remainder) { /*jshint -W086:true */ case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; h1 ^= h1 >>> 16; if( asString ){ // Convert to 8 digit hex string return ("0000000" + (h1 >>> 0).toString(16)).substr(-8); } return h1 >>> 0; } // console.info(hashMurmur3("costarring")); // console.info(hashMurmur3("costarring", true)); // console.info(hashMurmur3("liquid")); // console.info(hashMurmur3("liquid", true)); /* * Return a unique key for node by calculationg the hash of the parents refKey-list */ function calcUniqueKey(node) { var key, path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; }); path = path.join("/"); key = "id_" + hashMurmur3(path, true); // node.debug(path + " -> " + key); return key; } /** * [ext-clones] Return a list of clone-nodes or null. * @param {boolean} [includeSelf=false] * @returns {FancytreeNode[] | null} * * @alias FancytreeNode#getCloneList * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){ var key, tree = this.tree, refList = tree.refMap[this.refKey] || null, keyMap = tree.keyMap; if( refList ) { key = this.key; // Convert key list to node list if( includeSelf ) { refList = $.map(refList, function(val){ return keyMap[val]; }); } else { refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; }); if( refList.length < 1 ) { refList = null; } } } return refList; }; /** * [ext-clones] Return true if this node has at least another clone with same refKey. * @returns {boolean} * * @alias FancytreeNode#isClone * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){ var refKey = this.refKey || null, refList = refKey && this.tree.refMap[refKey] || null; return !!(refList && refList.length > 1); }; /** * [ext-clones] Update key and/or refKey for an existing node. * @param {string} key * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#reRegister * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){ key = (key == null) ? null : "" + key; refKey = (refKey == null) ? null : "" + refKey; // this.debug("reRegister", key, refKey); var tree = this.tree, prevKey = this.key, prevRefKey = this.refKey, keyMap = tree.keyMap, refMap = tree.refMap, refList = refMap[prevRefKey] || null, // curCloneKeys = refList ? node.getCloneList(true), modified = false; // Key has changed: update all references if( key != null && key !== this.key ) { if( keyMap[key] ) { $.error("[ext-clones] reRegister(" + key + "): already exists: " + this); } // Update keyMap delete keyMap[prevKey]; keyMap[key] = this; // Update refMap if( refList ) { refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? key : e; }); } this.key = key; modified = true; } // refKey has changed if( refKey != null && refKey !== this.refKey ) { // Remove previous refKeys if( refList ){ if( refList.length === 1 ){ delete refMap[prevRefKey]; }else{ refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? null : e; }); } } // Add refKey if( refMap[refKey] ) { refMap[refKey].append(key); }else{ refMap[refKey] = [ this.key ]; } this.refKey = refKey; modified = true; } return modified; }; /** * [ext-clones] Define a refKey for an existing node. * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#setRefKey * @requires jquery.fancytree.clones.js * @since 2.16 */ $.ui.fancytree._FancytreeNodeClass.prototype.setRefKey = function(refKey){ return this.reRegister(null, refKey); }; /** * [ext-clones] Return all nodes with a given refKey (null if not found). * @param {string} refKey * @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node * @returns {FancytreeNode[] | null} * @alias Fancytree#getNodesByRef * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){ var keyMap = this.keyMap, refList = this.refMap[refKey] || null; if( refList ) { // Convert key list to node list if( rootNode ) { refList = $.map(refList, function(val){ var node = keyMap[val]; return node.isDescendantOf(rootNode) ? node : null; }); }else{ refList = $.map(refList, function(val){ return keyMap[val]; }); } if( refList.length < 1 ) { refList = null; } } return refList; }; /** * [ext-clones] Replace a refKey with a new one. * @param {string} oldRefKey * @param {string} newRefKey * @alias Fancytree#changeRefKey * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) { var i, node, keyMap = this.keyMap, refList = this.refMap[oldRefKey] || null; if (refList) { for (i = 0; i < refList.length; i++) { node = keyMap[refList[i]]; node.refKey = newRefKey; } delete this.refMap[oldRefKey]; this.refMap[newRefKey] = refList; } }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "clones", version: "2.28.0", // Default options for this extension. options: { highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone }, treeCreate: function(ctx){ this._superApply(arguments); ctx.tree.refMap = {}; ctx.tree.keyMap = {}; }, treeInit: function(ctx){ this.$container.addClass("fancytree-ext-clones"); _assert(ctx.options.defaultKey == null); // Generate unique / reproducible default keys ctx.options.defaultKey = function(node){ return calcUniqueKey(node); }; // The default implementation loads initial data this._superApply(arguments); }, treeClear: function(ctx){ ctx.tree.refMap = {}; ctx.tree.keyMap = {}; return this._superApply(arguments); }, treeRegisterNode: function(ctx, add, node) { var refList, len, tree = ctx.tree, keyMap = tree.keyMap, refMap = tree.refMap, key = node.key, refKey = (node && node.refKey != null) ? "" + node.refKey : null; // ctx.tree.debug("clones.treeRegisterNode", add, node); if( node.isStatusNode() ){ return this._super(ctx, add, node); } if( add ) { if( keyMap[node.key] != null ) { $.error("clones.treeRegisterNode: node.key already exists: " + node); } keyMap[key] = node; if( refKey ) { refList = refMap[refKey]; if( refList ) { refList.push(key); if( refList.length === 2 && ctx.options.clones.highlightClones ) { // Mark peer node, if it just became a clone (no need to // mark current node, since it will be rendered later anyway) keyMap[refList[0]].renderStatus(); } } else { refMap[refKey] = [key]; } // node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]); } }else { if( keyMap[key] == null ) { $.error("clones.treeRegisterNode: node.key not registered: " + node.key); } delete keyMap[key]; if( refKey ) { refList = refMap[refKey]; // node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]); if( refList ) { len = refList.length; if( len <= 1 ){ _assert(len === 1); _assert(refList[0] === key); delete refMap[refKey]; }else{ _removeArrayMember(refList, key); // Unmark peer node, if this was the only clone if( len === 2 && ctx.options.clones.highlightClones ) { // node.debug("clones.treeRegisterNode: last =>", node.getCloneList()); keyMap[refList[0]].renderStatus(); } } // node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]); } } } return this._super(ctx, add, node); }, nodeRenderStatus: function(ctx) { var $span, res, node = ctx.node; res = this._super(ctx); if( ctx.options.clones.highlightClones ) { $span = $(node[ctx.tree.statusClassPropName]); // Only if span already exists if( $span.length && node.isClone() ){ // node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones); $span.addClass("fancytree-clone"); } } return res; }, nodeSetActive: function(ctx, flag, callOpts) { var res, scpn = ctx.tree.statusClassPropName, node = ctx.node; res = this._superApply(arguments); if( ctx.options.clones.highlightActiveClones && node.isClone() ) { $.each(node.getCloneList(true), function(idx, n){ // n.debug("clones.nodeSetActive: ", flag !== false); $(n[scpn]).toggleClass("fancytree-active-clone", flag !== false); }); } return res; } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.dnd5.js' *//*! * jquery.fancytree.dnd5.js * * Drag-and-drop support (native HTML5). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ /* #TODO Compatiblity when dragging between *separate* windows: Drag from Chrome Edge FF IE11 Safari To Chrome ok ok ok NO ? Edge ok ok ok NO ? FF ok ok ok NO ? IE 11 ok ok ok ok ? Safari ? ? ? ? ok */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /* ***************************************************************************** * Private functions and variables */ var FT = $.ui.fancytree, isMac = /Mac/.test(navigator.platform), classDragSource = "fancytree-drag-source", classDragRemove = "fancytree-drag-remove", classDropAccept = "fancytree-drop-accept", classDropAfter = "fancytree-drop-after", classDropBefore = "fancytree-drop-before", classDropOver = "fancytree-drop-over", classDropReject = "fancytree-drop-reject", classDropTarget = "fancytree-drop-target", nodeMimeType = "application/x-fancytree-node", $dropMarker = null, SOURCE_NODE = null, SOURCE_NODE_LIST = null, $sourceList = null, DRAG_ENTER_RESPONSE = null, LAST_HIT_MODE = null; /* */ function _clearGlobals() { SOURCE_NODE = null; SOURCE_NODE_LIST = null; $sourceList = null; DRAG_ENTER_RESPONSE = null; } /* Convert number to string and prepend +/-; return empty string for 0.*/ function offsetString(n){ return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n)); } /* Convert a dragEnter() or dragOver() response to a canonical form. * Return false or plain object * @param {string|object|boolean} r * @return {object|false} */ function normalizeDragEnterResponse(r) { var res; if( !r ){ return false; } if ( $.isPlainObject(r) ) { res = { over: !!r.over, before: !!r.before, after: !!r.after }; }else if ( $.isArray(r) ) { res = { over: ($.inArray("over", r) >= 0), before: ($.inArray("before", r) >= 0), after: ($.inArray("after", r) >= 0) }; }else{ res = { over: ((r === true) || (r === "over")), before: ((r === true) || (r === "before")), after: ((r === true) || (r === "after")) }; } if( Object.keys(res).length === 0 ) { return false; } // if( Object.keys(res).length === 1 ) { // res.unique = res[0]; // } return res; } /* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */ function autoScroll(tree, event) { var spOfs, scrollTop, delta, dndOpts = tree.options.dnd5, sp = tree.$scrollParent[0], sensitivity = dndOpts.scrollSensitivity, speed = dndOpts.scrollSpeed, scrolled = 0; if ( sp !== document && sp.tagName !== "HTML" ) { spOfs = tree.$scrollParent.offset(); scrollTop = sp.scrollTop; if ( spOfs.top + sp.offsetHeight - event.pageY < sensitivity ) { delta = (sp.scrollHeight - tree.$scrollParent.innerHeight() - scrollTop); // console.log ("sp.offsetHeight: " + sp.offsetHeight // + ", spOfs.top: " + spOfs.top // + ", scrollTop: " + scrollTop // + ", innerHeight: " + tree.$scrollParent.innerHeight() // + ", scrollHeight: " + sp.scrollHeight // + ", delta: " + delta // ); if( delta > 0 ) { sp.scrollTop = scrolled = scrollTop + speed; } } else if ( scrollTop > 0 && event.pageY - spOfs.top < sensitivity ) { sp.scrollTop = scrolled = scrollTop - speed; } } else { scrollTop = $(document).scrollTop(); if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) { scrolled = scrollTop - speed; $(document).scrollTop(scrolled); } else if ($(window).height() - (event.pageY - scrollTop) < sensitivity) { scrolled = scrollTop + speed; $(document).scrollTop(scrolled); } } if( scrolled ) { tree.debug("autoScroll: " + scrolled + "px"); } return scrolled; } /* Handle dragover event (fired every x ms) and return hitMode. */ function handleDragOver(event, data) { // Implement auto-scrolling if ( data.options.dnd5.scroll ) { autoScroll(data.tree, event); } // Bail out with previous response if we get an invalid dragover if( !data.node ) { data.tree.warn("Ignore dragover for non-node"); //, event, data); return LAST_HIT_MODE; } var markerOffsetX, nodeOfs, relPosY, //res, // eventHash = getEventHash(event), hitMode = null, tree = data.tree, options = tree.options, dndOpts = options.dnd5, targetNode = data.node, sourceNode = data.otherNode, markerAt = "center", $target = $(targetNode.span), $targetTitle = $target.find("span.fancytree-title"); if(DRAG_ENTER_RESPONSE === false){ tree.info("Ignore dragover, since dragenter returned false"); //, event, data); // $.error("assert failed: dragenter returned false"); return false; } else if(typeof DRAG_ENTER_RESPONSE === "string") { $.error("assert failed: dragenter returned string"); // Use hitMode from onEnter if provided. // hitMode = DRAG_ENTER_RESPONSE; } else { // Calculate hitMode from relative cursor position. nodeOfs = $target.offset(); relPosY = (event.pageY - nodeOfs.top) / $target.height(); if( DRAG_ENTER_RESPONSE.after && relPosY > 0.75 ){ hitMode = "after"; } else if(!DRAG_ENTER_RESPONSE.over && DRAG_ENTER_RESPONSE.after && relPosY > 0.5 ){ hitMode = "after"; } else if(DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) { hitMode = "before"; } else if(!DRAG_ENTER_RESPONSE.over && DRAG_ENTER_RESPONSE.before && relPosY <= 0.5) { hitMode = "before"; } else if(DRAG_ENTER_RESPONSE.over) { hitMode = "over"; } // Prevent no-ops like 'before source node' // TODO: these are no-ops when moving nodes, but not in copy mode if( dndOpts.preventVoidMoves ){ if(targetNode === sourceNode){ targetNode.debug("Drop over source node prevented."); hitMode = null; }else if(hitMode === "before" && sourceNode && targetNode === sourceNode.getNextSibling()){ targetNode.debug("Drop after source node prevented."); hitMode = null; }else if(hitMode === "after" && sourceNode && targetNode === sourceNode.getPrevSibling()){ targetNode.debug("Drop before source node prevented."); hitMode = null; }else if(hitMode === "over" && sourceNode && sourceNode.parent === targetNode && sourceNode.isLastSibling() ){ targetNode.debug("Drop last child over own parent prevented."); hitMode = null; } } } // Let callback modify the calculated hitMode data.hitMode = hitMode; if(hitMode && dndOpts.dragOver){ // TODO: http://code.google.com/p/dynatree/source/detail?r=625 dndOpts.dragOver(targetNode, data); hitMode = data.hitMode; } // LAST_DROP_EFFECT = data.dataTransfer.dropEffect; // LAST_EFFECT_ALLOWED = data.dataTransfer.effectAllowed; LAST_HIT_MODE = hitMode; // if( hitMode === "after" || hitMode === "before" || hitMode === "over" ){ markerOffsetX = dndOpts.dropMarkerOffsetX || 0; switch(hitMode){ case "before": markerAt = "top"; markerOffsetX += (dndOpts.dropMarkerInsertOffsetX || 0); break; case "after": markerAt = "bottom"; markerOffsetX += (dndOpts.dropMarkerInsertOffsetX || 0); break; } $dropMarker .toggleClass(classDropAfter, hitMode === "after") .toggleClass(classDropOver, hitMode === "over") .toggleClass(classDropBefore, hitMode === "before") .show() .position(FT.fixPositionOptions({ my: "left" + offsetString(markerOffsetX) + " center", at: "left " + markerAt, of: $targetTitle })); } else { $dropMarker.hide(); // console.log("hide dropmarker") } $(targetNode.span) .toggleClass(classDropTarget, hitMode === "after" || hitMode === "before" || hitMode === "over") .toggleClass(classDropAfter, hitMode === "after") .toggleClass(classDropBefore, hitMode === "before") .toggleClass(classDropAccept, hitMode === "over") .toggleClass(classDropReject, hitMode === false); return hitMode; } /* Guess dropEffect from modifier keys. * Safari: * It seems that `dataTransfer.dropEffect` can only be set on dragStart, and will remain * even if the cursor changes when [Alt] or [Ctrl] are pressed (?) * Using rules suggested here: * https://ux.stackexchange.com/a/83769 * @returns * 'copy', 'link', 'move', or 'none' */ function getDropEffect(event, data) { var dndOpts = data.options.dnd5, res = dndOpts.dropEffectDefault // dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer, ; // Use callback if any: if( dndOpts.dropEffect ) { return dndOpts.dropEffect(event, data); } if( isMac ) { if( event.metaKey && event.altKey ) { // Mac: [Control] + [Option] return "link"; } else if( event.metaKey ) { // Mac: [Command] return "move"; } else if( event.altKey ) { // Mac: [Option] return "copy"; } } else { if( event.ctrlKey ) { // Windows: [Ctrl] return "copy"; } else if( event.shiftKey ) { // Windows: [Shift] return "move"; } else if( event.altKey ) { // Windows: [Alt] return "link"; } } // data.tree.debug("getDropEffect: " + res); return res; } /* ***************************************************************************** * */ $.ui.fancytree.registerExtension({ name: "dnd5", version: "2.28.0", // Default options for this extension. options: { autoExpandMS: 1500, // Expand nodes after n milliseconds of hovering dropMarkerInsertOffsetX: -16,// Additional offset for drop-marker with hitMode = "before"/"after" dropMarkerOffsetX: -24, // Absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop) multiSource: false, // true: Drag multiple (i.e. selected) nodes. dragImage: null, // Callback(node, data) that can be used to call dataTransfer.setDragImage(). dropEffect: null, // Callback(node, data) that returns 'copy', 'link', 'move', or 'none'. dropEffectDefault: "move", // Default dropEffect ('copy', 'link', or 'move'). preventForeignNodes: false, // Prevent dropping nodes from different Fancytrees preventNonNodes: false, // Prevent dropping items other than Fancytree nodes preventRecursiveMoves: true, // Prevent dropping nodes on own descendants preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. scroll: true, // Enable auto-scrolling while dragging scrollSensitivity: 20, // Active top/bottom margin in pixel scrollSpeed: 5, // Pixel per event setTextTypeJson: false, // Allow dragging of nodes to different IE windows // Events (drag support) dragStart: null, // Callback(sourceNode, data), return true, to enable dnd drag dragDrag: $.noop, // Callback(sourceNode, data) dragEnd: $.noop, // Callback(sourceNode, data) // Events (drop support) dragEnter: null, // Callback(targetNode, data), return true, to enable dnd drop dragOver: $.noop, // Callback(targetNode, data) dragExpand: $.noop, // Callback(targetNode, data), return false to prevent autoExpand dragDrop: $.noop, // Callback(targetNode, data) dragLeave: $.noop // Callback(targetNode, data) }, treeInit: function(ctx){ var $dragImage, $extraHelper, $temp, tree = ctx.tree, opts = ctx.options, glyph = opts.glyph || null, dndOpts = opts.dnd5, getNode = FT.getNode; if( $.inArray("dnd", opts.extensions) >= 0 ) { $.error("Extensions 'dnd' and 'dnd5' are mutually exclusive."); } if( dndOpts.dragStop ) { $.error("dragStop is not used by ext-dnd5. Use dragEnd instead."); } // Implement `opts.createNode` event to add the 'draggable' attribute // #680: this must happen before calling super.treeInit() if( dndOpts.dragStart ) { FT.overrideMethod(ctx.options, "createNode", function(event, data) { // Default processing if any this._super.apply(this, arguments); data.node.span.draggable = true; }); } this._superApply(arguments); this.$container.addClass("fancytree-ext-dnd5"); // Store the current scroll parent, which may be the tree // container, any enclosing div, or the document. // #761: scrollParent() always needs a container child $temp = $("<span>").appendTo(this.$container); this.$scrollParent = $temp.scrollParent(); $temp.remove(); $dropMarker = $("#fancytree-drop-marker"); if( !$dropMarker.length ) { $dropMarker = $("<div id='fancytree-drop-marker'></div>") .hide() .css({ "z-index": 1000, // Drop marker should not steal dragenter/dragover events: "pointer-events": "none" }).prependTo("body"); if( glyph ) { FT.setSpanIcon($dropMarker[0], glyph.map._addClass, glyph.map.dropMarker); // $dropMarker.addClass(glyph.map._addClass + " " + glyph.map.dropMarker); } } // Enable drag support if dragStart() is specified: if( dndOpts.dragStart ) { // Bind drag event handlers tree.$container.on("dragstart drag dragend", function(event){ var json, node = getNode(event), dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer, data = { node: node, tree: tree, options: tree.options, originalEvent: event, dataTransfer: dataTransfer, // dropEffect: undefined, // set by dragend isCancelled: undefined // set by dragend }, dropEffect = getDropEffect(event, data), isMove = dropEffect === "move"; // console.log(event.type, "dropEffect: " + dropEffect); switch( event.type ) { case "dragstart": // Store current source node in different formats SOURCE_NODE = node; // Also optionally store selected nodes if( dndOpts.multiSource === false ) { SOURCE_NODE_LIST = [node]; } else if( dndOpts.multiSource === true ) { SOURCE_NODE_LIST = tree.getSelectedNodes(); if( !node.isSelected() ) { SOURCE_NODE_LIST.unshift(node); } } else { SOURCE_NODE_LIST = dndOpts.multiSource(node, data); } // Cache as array of jQuery objects for faster access: $sourceList = $($.map(SOURCE_NODE_LIST, function(n){ return n.span; })); // Set visual feedback $sourceList.addClass(classDragSource); // Set payload // Note: // Transfer data is only accessible on dragstart and drop! // For all other events the formats and kinds in the drag // data store list of items representing dragged data can be // enumerated, but the data itself is unavailable and no new // data can be added. json = JSON.stringify(node.toDict()); try { dataTransfer.setData(nodeMimeType, json); dataTransfer.setData("text/html", $(node.span).html()); dataTransfer.setData("text/plain", node.title); } catch(ex) { // IE only accepts 'text' type tree.warn("Could not set data (IE only accepts 'text') - " + ex); } // We always need to set the 'text' type if we want to drag // Because IE 11 only accepts this single type. // If we pass JSON here, IE can can access all node properties, // even when the source lives in another window. (D'n'd inside // the same window will always work.) // The drawback is, that in this case ALL browsers will see // the JSON representation as 'text', so dragging // to a text field will insert the JSON string instead of // the node title. if( dndOpts.setTextTypeJson ) { dataTransfer.setData("text", json); } else { dataTransfer.setData("text", node.title); } // Set the allowed and current drag mode (move, copy, or link) dataTransfer.effectAllowed = "all"; // "copyMove" // dropEffect = "move"; $extraHelper = null; if( dndOpts.dragImage ) { // Let caller set a custom drag image using dataTransfer.setDragImage() // and/or modify visual feedback otherwise. dndOpts.dragImage(node, data); } else { // Set the title as drag image (otherwise it would contain the expander) $dragImage = $(node.span).find(".fancytree-title"); if( SOURCE_NODE_LIST && SOURCE_NODE_LIST.length > 1 ) { // Add a counter badge to node title if dragging more than one node. // We want this, because the element that is used as drag image // must be *visible* in the DOM, so we cannot create some hidden // custom markup. // See https://kryogenix.org/code/browser/custom-drag-image.html // Also, since IE 11 and Edge don't support setDragImage() alltogether, // it gives som feedback to the user. // The badge will be removed later on drag end. $extraHelper = $("<span class='fancytree-childcounter'/>") .text("+" + (SOURCE_NODE_LIST.length - 1)) .appendTo($dragImage); } if( dataTransfer.setDragImage ) { // IE 11 and Edge do not support this dataTransfer.setDragImage( $dragImage[0], -10, -10); } } // Let user modify above settings return dndOpts.dragStart(node, data) !== false; case "drag": // Called every few miliseconds // data.tree.info("drag", SOURCE_NODE) $sourceList.toggleClass(classDragRemove, isMove); dndOpts.dragDrag(node, data); break; case "dragend": $sourceList.removeClass(classDragSource + " " + classDragRemove); _clearGlobals(); // data.dropEffect = dropEffect; data.isCancelled = (dropEffect === "none"); $dropMarker.hide(); // Take this badge off of me - I can't use it anymore: if( $extraHelper ) { $extraHelper.remove(); $extraHelper = null; } dndOpts.dragEnd(node, data); break; } }); } // Enable drop support if dragEnter() is specified: if( dndOpts.dragEnter ) { // Bind drop event handlers tree.$container.on("dragenter dragover dragleave drop", function(event){ var json, nodeData, r, res, allowDrop = null, node = getNode(event), dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer, // dropEffect = getDropEffect(dataTransfer, opts), data = { node: node, tree: tree, options: tree.options, hitMode: DRAG_ENTER_RESPONSE, originalEvent: event, dataTransfer: dataTransfer, otherNode: SOURCE_NODE || null, otherNodeList: SOURCE_NODE_LIST || null, otherNodeData: null, // set by drop event dropEffect: undefined, // set by drop event isCancelled: undefined // set by drop event }; switch( event.type ) { case "dragenter": // The dragenter event is fired when a dragged element or // text selection enters a valid drop target. if( !node ) { // Sometimes we get dragenter for the container element tree.debug("Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className); DRAG_ENTER_RESPONSE = false; break; } $(node.span) .addClass(classDropOver) .removeClass(classDropAccept + " " + classDropReject); if( dndOpts.preventNonNodes && !nodeData ) { node.debug("Reject dropping a non-node."); DRAG_ENTER_RESPONSE = false; break; } else if( dndOpts.preventForeignNodes && (!SOURCE_NODE || SOURCE_NODE.tree !== node.tree ) ) { node.debug("Reject dropping a foreign node."); DRAG_ENTER_RESPONSE = false; break; } // NOTE: dragenter is fired BEFORE the dragleave event // of the previous element! // https://www.w3.org/Bugs/Public/show_bug.cgi?id=19041 setTimeout(function(){ // node.info("DELAYED " + event.type, event.target, DRAG_ENTER_RESPONSE); // Auto-expand node (only when 'over' the node, not 'before', or 'after') if( dndOpts.autoExpandMS && node.hasChildren() !== false && !node.expanded && (!dndOpts.dragExpand || dndOpts.dragExpand(node, data) !== false) ) { node.scheduleAction("expand", dndOpts.autoExpandMS); } }, 0); $dropMarker.show(); // Call dragEnter() to figure out if (and where) dropping is allowed if( dndOpts.preventRecursiveMoves && node.isDescendantOf(data.otherNode) ){ node.debug("Reject dropping below own ancestor."); res = false; }else{ r = dndOpts.dragEnter(node, data); res = normalizeDragEnterResponse(r); } DRAG_ENTER_RESPONSE = res; allowDrop = res && ( res.over || res.before || res.after ); break; case "dragover": // The dragover event is fired when an element or text // selection is being dragged over a valid drop target // (every few hundred milliseconds). // console.log(event.type, "dropEffect: " + dataTransfer.dropEffect) LAST_HIT_MODE = handleDragOver(event, data); allowDrop = !!LAST_HIT_MODE; break; case "dragleave": // NOTE: dragleave is fired AFTER the dragenter event of the // FOLLOWING element. if( !node ) { tree.debug("Ignore non-node " + event.type + ": " + event.target.tagName + "." + event.target.className); break; } if( !$(node.span).hasClass(classDropOver) ) { node.debug("Ignore dragleave (multi)"); //, event.currentTarget); break; } $(node.span).removeClass(classDropOver + " " + classDropAccept + " " + classDropReject); node.scheduleAction("cancel"); dndOpts.dragLeave(node, data); $dropMarker.hide(); break; case "drop": // Data is only readable in the (dragenter and) drop event: if( $.inArray(nodeMimeType, dataTransfer.types) >= 0 ) { nodeData = dataTransfer.getData(nodeMimeType); tree.info(event.type + ": getData('application/x-fancytree-node'): '" + nodeData + "'"); } if( !nodeData ) { // 1. Source is not a Fancytree node, or // 2. If the FT mime type was set, but returns '', this // is probably IE 11 (which only supports 'text') nodeData = dataTransfer.getData("text"); tree.info(event.type + ": getData('text'): '" + nodeData + "'"); } if( nodeData ) { try { // 'text' type may contain JSON if IE is involved // and setTextTypeJson option was set json = JSON.parse(nodeData); if( json.title !== undefined ) { data.otherNodeData = json; } } catch(ex) { // assume 'text' type contains plain text, so `otherNodeData` // should not be set } } tree.debug(event.type + ": nodeData: '" + nodeData + "', otherNodeData: ", data.otherNodeData); $(node.span).removeClass(classDropOver + " " + classDropAccept + " " + classDropReject); $dropMarker.hide(); data.hitMode = LAST_HIT_MODE; data.dropEffect = dataTransfer.dropEffect; data.isCancelled = data.dropEffect === "none"; // Let user implement the actual drop operation dndOpts.dragDrop(node, data); // Prevent browser's default drop handling event.preventDefault(); _clearGlobals(); break; } // Dnd API madness: we must PREVENT default handling to enable dropping if( allowDrop ) { event.preventDefault(); return false; } }); } } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.edit.js' *//*! * jquery.fancytree.edit.js * * Make node titles editable. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /******************************************************************************* * Private functions and variables */ var isMac = /Mac/.test(navigator.platform), escapeHtml = $.ui.fancytree.escapeHtml, unescapeHtml = $.ui.fancytree.unescapeHtml; /** * [ext-edit] Start inline editing of current node title. * * @alias FancytreeNode#editStart * @requires Fancytree */ $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){ var $input, node = this, tree = this.tree, local = tree.ext.edit, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), eventData = { node: node, tree: tree, options: tree.options, isNew: $(node[tree.statusClassPropName]).hasClass("fancytree-edit-new"), orgTitle: node.title, input: null, dirty: false }; // beforeEdit may want to modify the title before editing if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) { return false; } $.ui.fancytree.assert(!local.currentNode, "recursive edit"); local.currentNode = this; local.eventData = eventData; // Disable standard Fancytree mouse- and key handling tree.widget._unbind(); // #116: ext-dnd prevents the blur event, so we have to catch outer clicks $(document).on("mousedown.fancytree-edit", function(event){ if( ! $(event.target).hasClass("fancytree-edit-input") ){ node.editEnd(true, event); } }); // Replace node with <input> $input = $("<input />", { "class": "fancytree-edit-input", type: "text", value: tree.options.escapeTitles ? eventData.orgTitle : unescapeHtml(eventData.orgTitle) }); local.eventData.input = $input; if ( instOpts.adjustWidthOfs != null ) { $input.width($title.width() + instOpts.adjustWidthOfs); } if ( instOpts.inputCss != null ) { $input.css(instOpts.inputCss); } $title.html($input); // Focus <input> and bind keyboard handler $input .focus() .change(function(event){ $input.addClass("fancytree-edit-dirty"); }).keydown(function(event){ switch( event.which ) { case $.ui.keyCode.ESCAPE: node.editEnd(false, event); break; case $.ui.keyCode.ENTER: node.editEnd(true, event); return false; // so we don't start editmode on Mac } event.stopPropagation(); }).blur(function(event){ return node.editEnd(true, event); }); instOpts.edit.call(node, {type: "edit"}, eventData); }; /** * [ext-edit] Stop inline editing. * @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified) * @alias FancytreeNode#editEnd * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){ var newVal, node = this, tree = this.tree, local = tree.ext.edit, eventData = local.eventData, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), $input = $title.find("input.fancytree-edit-input"); if( instOpts.trim ) { $input.val($.trim($input.val())); } newVal = $input.val(); eventData.dirty = ( newVal !== node.title ); eventData.originalEvent = _event; // Find out, if saving is required if( applyChanges === false ) { // If true/false was passed, honor this (except in rename mode, if unchanged) eventData.save = false; } else if( eventData.isNew ) { // In create mode, we save everything, except for empty text eventData.save = (newVal !== ""); } else { // In rename mode, we save everyting, except for empty or unchanged text eventData.save = eventData.dirty && (newVal !== ""); } // Allow to break (keep editor open), modify input, or re-define data.save if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){ return false; } if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){ return false; } $input .removeClass("fancytree-edit-dirty") .off(); // Unbind outer-click handler $(document).off(".fancytree-edit"); if( eventData.save ) { // # 171: escape user input (not required if global escaping is on) node.setTitle( tree.options.escapeTitles ? newVal : escapeHtml(newVal) ); node.setFocus(); }else{ if( eventData.isNew ) { node.remove(); node = eventData.node = null; local.relatedNode.setFocus(); } else { node.renderTitle(); node.setFocus(); } } local.eventData = null; local.currentNode = null; local.relatedNode = null; // Re-enable mouse and keyboard handling tree.widget._bind(); // Set keyboard focus, even if setFocus() claims 'nothing to do' $(tree.$container).focus(); eventData.input = null; instOpts.close.call(node, {type: "close"}, eventData); return true; }; /** * [ext-edit] Create a new child or sibling node and start edit mode. * * @param {String} [mode='child'] 'before', 'after', or 'child' * @param {Object} [init] NodeData (or simple title string) * @alias FancytreeNode#editCreateNode * @requires jquery.fancytree.edit.js * @since 2.4 */ $.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){ var newNode, tree = this.tree, self = this; mode = mode || "child"; if( init == null ) { init = { title: "" }; } else if( typeof init === "string" ) { init = { title: init }; } else { $.ui.fancytree.assert($.isPlainObject(init)); } // Make sure node is expanded (and loaded) in 'child' mode if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) { this.setExpanded().done(function(){ self.editCreateNode(mode, init); }); return; } newNode = this.addNode(init, mode); // #644: Don't filter new nodes. newNode.match = true; $(newNode[tree.statusClassPropName]) .removeClass("fancytree-hide") .addClass("fancytree-match"); newNode.makeVisible(/*{noAnimation: true}*/).done(function(){ $(newNode[tree.statusClassPropName]).addClass("fancytree-edit-new"); self.tree.ext.edit.relatedNode = self; newNode.editStart(); }); }; /** * [ext-edit] Check if any node in this tree in edit mode. * * @returns {FancytreeNode | null} * @alias Fancytree#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeClass.prototype.isEditing = function(){ return this.ext.edit ? this.ext.edit.currentNode : null; }; /** * [ext-edit] Check if this node is in edit mode. * @returns {Boolean} true if node is currently beeing edited * @alias FancytreeNode#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){ return this.tree.ext.edit ? this.tree.ext.edit.currentNode === this : false; }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "edit", version: "2.28.0", // Default options for this extension. options: { adjustWidthOfs: 4, // null: don't adjust input size to content allowEmpty: false, // Prevent empty input inputCss: {minWidth: "3em"}, // triggerCancel: ["esc", "tab", "click"], triggerStart: ["f2", "mac+enter", "shift+click"], trim: true, // Trim whitespace before save // Events: beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available) beforeEdit: $.noop, // Return false to prevent edit mode close: $.noop, // Editor was removed edit: $.noop, // Editor was opened (available as data.input) // keypress: $.noop, // Not yet implemented save: $.noop // Save data.input.val() or return false to keep editor open }, // Local attributes currentNode: null, treeInit: function(ctx){ this._superApply(arguments); this.$container.addClass("fancytree-ext-edit"); }, nodeClick: function(ctx) { if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){ if( ctx.originalEvent.shiftKey ){ ctx.node.editStart(); return false; } } if( $.inArray("clickActive", ctx.options.edit.triggerStart) >= 0 ){ // Only when click was inside title text (not aynwhere else in the row) if( ctx.node.isActive() && !ctx.node.isEditing() && $(ctx.originalEvent.target).hasClass("fancytree-title") ){ ctx.node.editStart(); return false; } } return this._superApply(arguments); }, nodeDblclick: function(ctx) { if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } return this._superApply(arguments); }, nodeKeydown: function(ctx) { switch( ctx.originalEvent.which ) { case 113: // [F2] if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } break; case $.ui.keyCode.ENTER: if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){ ctx.node.editStart(); return false; } break; } return this._superApply(arguments); } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.filter.js' *//*! * jquery.fancytree.filter.js * * Remove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /******************************************************************************* * Private functions and variables */ var KeyNoData = "__not_found__", escapeHtml = $.ui.fancytree.escapeHtml; function _escapeRegex(str){ /*jshint regexdash:true */ return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1"); } function extractHtmlText(s){ if( s.indexOf(">") >= 0 ) { return $("<div/>").html(s).text(); } return s; } $.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, _opts){ var match, statusNode, re, reHighlight, temp, count = 0, treeOpts = this.options, escapeTitles = treeOpts.escapeTitles, prevAutoCollapse = treeOpts.autoCollapse, opts = $.extend({}, treeOpts.filter, _opts), hideMode = opts.mode === "hide", leavesOnly = !!opts.leavesOnly && !branchMode; // Default to 'match title substring (not case sensitive)' if(typeof filter === "string"){ if( filter === "" ) { this.warn("Fancytree passing an empty string as a filter is handled as clearFilter()."); this.clearFilter(); return; } if( opts.fuzzy ) { // See https://codereview.stackexchange.com/questions/23899/faster-javascript-fuzzy-string-matching-function/23905#23905 // and http://www.quora.com/How-is-the-fuzzy-search-algorithm-in-Sublime-Text-designed // and http://www.dustindiaz.com/autocomplete-fuzzy-matching match = filter.split("").reduce(function(a, b) { return a + "[^" + b + "]*" + b; }); } else { match = _escapeRegex(filter); // make sure a '.' is treated literally } re = new RegExp(".*" + match + ".*", "i"); reHighlight = new RegExp(_escapeRegex(filter), "gi"); filter = function(node){ if( !node.title ) { return false; } var text = escapeTitles ? node.title : extractHtmlText(node.title), res = !!re.test(text); if( res && opts.highlight ) { if( escapeTitles ) { // #740: we must not apply the marks to escaped entity names, e.g. `&quot;` // Use some exotic characters to mark matches: temp = text.replace(reHighlight, function(s){ return "\uFFF7" + s + "\uFFF8"; }); // now we can escape the title... node.titleWithHighlight = escapeHtml(temp) // ... and finally insert the desired `<mark>` tags .replace(/\uFFF7/g, "<mark>") .replace(/\uFFF8/g, "</mark>"); } else { node.titleWithHighlight = text.replace(reHighlight, function(s){ return "<mark>" + s + "</mark>"; }); } // node.debug("filter", escapeTitles, text, node.titleWithHighlight); } return res; }; } this.enableFilter = true; this.lastFilterArgs = arguments; this.$div.addClass("fancytree-ext-filter"); if( hideMode ){ this.$div.addClass("fancytree-ext-filter-hide"); } else { this.$div.addClass("fancytree-ext-filter-dimm"); } this.$div.toggleClass("fancytree-ext-filter-hide-expanders", !!opts.hideExpanders); // Reset current filter this.visit(function(node){ delete node.match; delete node.titleWithHighlight; node.subMatchCount = 0; }); statusNode = this.getRootNode()._findDirectChild(KeyNoData); if( statusNode ) { statusNode.remove(); } // Adjust node.hide, .match, and .subMatchCount properties treeOpts.autoCollapse = false; // #528 this.visit(function(node){ if ( leavesOnly && node.children != null ) { return; } var res = filter(node), matchedByBranch = false; if( res === "skip" ) { node.visit(function(c){ c.match = false; }, true); return "skip"; } if( !res && (branchMode || res === "branch") && node.parent.match ) { res = true; matchedByBranch = true; } if( res ) { count++; node.match = true; node.visitParents(function(p){ p.subMatchCount += 1; // Expand match (unless this is no real match, but only a node in a matched branch) if( opts.autoExpand && !matchedByBranch && !p.expanded ) { p.setExpanded(true, {noAnimation: true, noEvents: true, scrollIntoView: false}); p._filterAutoExpanded = true; } }); } }); treeOpts.autoCollapse = prevAutoCollapse; if( count === 0 && opts.nodata && hideMode ) { statusNode = opts.nodata; if( $.isFunction(statusNode) ) { statusNode = statusNode(); } if( statusNode === true ) { statusNode = {}; } else if( typeof statusNode === "string" ) { statusNode = { title: statusNode }; } statusNode = $.extend({ statusNodeType: "nodata", key: KeyNoData, title: this.options.strings.noData }, statusNode); this.getRootNode().addNode(statusNode).match = true; } // Redraw whole tree this.render(); return count; }; /** * [ext-filter] Dimm or hide nodes. * * @param {function | string} filter * @param {boolean} [opts={autoExpand: false, leavesOnly: false}] * @returns {integer} count * @alias Fancytree#filterNodes * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, opts) { if( typeof opts === "boolean" ) { opts = { leavesOnly: opts }; this.warn("Fancytree.filterNodes() leavesOnly option is deprecated since 2.9.0 / 2015-04-19. Use opts.leavesOnly instead."); } return this._applyFilterImpl(filter, false, opts); }; /** * @deprecated */ $.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){ this.warn("Fancytree.applyFilter() is deprecated since 2.1.0 / 2014-05-29. Use .filterNodes() instead."); return this.filterNodes.apply(this, arguments); }; /** * [ext-filter] Dimm or hide whole branches. * * @param {function | string} filter * @param {boolean} [opts={autoExpand: false}] * @returns {integer} count * @alias Fancytree#filterBranches * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter, opts){ return this._applyFilterImpl(filter, true, opts); }; /** * [ext-filter] Reset the filter. * * @alias Fancytree#clearFilter * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){ var $title, statusNode = this.getRootNode()._findDirectChild(KeyNoData), escapeTitles = this.options.escapeTitles, enhanceTitle = this.options.enhanceTitle; if( statusNode ) { statusNode.remove(); } this.visit(function(node){ if( node.match && node.span ) { // #491, #601 $title = $(node.span).find(">span.fancytree-title"); if( escapeTitles ) { $title.text(node.title); } else { $title.html(node.title); } if( enhanceTitle ) { enhanceTitle({type: "enhanceTitle"}, {node: node, $title: $title}); } } delete node.match; delete node.subMatchCount; delete node.titleWithHighlight; if ( node.$subMatchBadge ) { node.$subMatchBadge.remove(); delete node.$subMatchBadge; } if( node._filterAutoExpanded && node.expanded ) { node.setExpanded(false, {noAnimation: true, noEvents: true, scrollIntoView: false}); } delete node._filterAutoExpanded; }); this.enableFilter = false; this.lastFilterArgs = null; this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide"); this.render(); }; /** * [ext-filter] Return true if a filter is currently applied. * * @returns {Boolean} * @alias Fancytree#isFilterActive * @requires jquery.fancytree.filter.js * @since 2.13 */ $.ui.fancytree._FancytreeClass.prototype.isFilterActive = function(){ return !!this.enableFilter; }; /** * [ext-filter] Return true if this node is matched by current filter (or no filter is active). * * @returns {Boolean} * @alias FancytreeNode#isMatched * @requires jquery.fancytree.filter.js * @since 2.13 */ $.ui.fancytree._FancytreeNodeClass.prototype.isMatched = function(){ return !(this.tree.enableFilter && !this.match); }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "filter", version: "2.28.0", // Default options for this extension. options: { autoApply: true, // Re-apply last filter if lazy data is loaded autoExpand: false, // Expand all branches that contain matches while filtered counter: true, // Show a badge with number of matching child nodes near parent icons fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar' hideExpandedCounter: true, // Hide counter badge if parent is expanded hideExpanders: false, // Hide expanders if all child nodes are hidden by filter highlight: true, // Highlight matches by wrapping inside <mark> tags leavesOnly: false, // Match end nodes only nodata: true, // Display a 'no data' status node if result is empty mode: "dimm" // Grayout unmatched nodes (pass "hide" to remove unmatched node instead) }, nodeLoadChildren: function(ctx, source) { return this._superApply(arguments).done(function() { if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) { ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs); } }); }, nodeSetExpanded: function(ctx, flag, callOpts) { delete ctx.node._filterAutoExpanded; // Make sure counter badge is displayed again, when node is beeing collapsed if( !flag && ctx.options.filter.hideExpandedCounter && ctx.node.$subMatchBadge ) { ctx.node.$subMatchBadge.show(); } return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { // Set classes for current status var res, node = ctx.node, tree = ctx.tree, opts = ctx.options.filter, $title = $(node.span).find("span.fancytree-title"), $span = $(node[tree.statusClassPropName]), enhanceTitle = ctx.options.enhanceTitle, escapeTitles = ctx.options.escapeTitles; res = this._super(ctx); // nothing to do, if node was not yet rendered if( !$span.length || !tree.enableFilter ) { return res; } $span .toggleClass("fancytree-match", !!node.match) .toggleClass("fancytree-submatch", !!node.subMatchCount) .toggleClass("fancytree-hide", !(node.match || node.subMatchCount)); // Add/update counter badge if( opts.counter && node.subMatchCount && (!node.isExpanded() || !opts.hideExpandedCounter) ) { if( !node.$subMatchBadge ) { node.$subMatchBadge = $("<span class='fancytree-childcounter'/>"); $("span.fancytree-icon, span.fancytree-custom-icon", node.span).append(node.$subMatchBadge); } node.$subMatchBadge.show().text(node.subMatchCount); } else if ( node.$subMatchBadge ) { node.$subMatchBadge.hide(); } // node.debug("nodeRenderStatus", node.titleWithHighlight, node.title) // #601: also chek for $title.length, because we don't need to render // if node.span is null (i.e. not rendered) if( node.span && (!node.isEditing || !node.isEditing.call(node)) ) { if( node.titleWithHighlight ) { $title.html(node.titleWithHighlight); } else if ( escapeTitles ) { $title.text(node.title); } else { $title.html(node.title); } if( enhanceTitle ) { enhanceTitle({type: "enhanceTitle"}, {node: node, $title: $title}); } } return res; } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.glyph.js' *//*! * jquery.fancytree.glyph.js * * Use glyph-fonts, ligature-fonts, or SVG icons instead of icon sprites. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /* ***************************************************************************** * Private functions and variables */ var FT = $.ui.fancytree, PRESETS = { "awesome3": { // Outdated! _addClass: "", checkbox: "icon-check-empty", checkboxSelected: "icon-check", checkboxUnknown: "icon-check icon-muted", dragHelper: "icon-caret-right", dropMarker: "icon-caret-right", error: "icon-exclamation-sign", expanderClosed: "icon-caret-right", expanderLazy: "icon-angle-right", expanderOpen: "icon-caret-down", loading: "icon-refresh icon-spin", nodata: "icon-meh", noExpander: "", radio: "icon-circle-blank", radioSelected: "icon-circle", // radioUnknown: "icon-circle icon-muted", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "icon-file-alt", docOpen: "icon-file-alt", folder: "icon-folder-close-alt", folderOpen: "icon-folder-open-alt" }, "awesome4": { _addClass: "fa", checkbox: "fa-square-o", checkboxSelected: "fa-check-square-o", checkboxUnknown: "fa-square fancytree-helper-indeterminate-cb", dragHelper: "fa-arrow-right", dropMarker: "fa-long-arrow-right", error: "fa-warning", expanderClosed: "fa-caret-right", expanderLazy: "fa-angle-right", expanderOpen: "fa-caret-down", loading: "fa-spinner fa-pulse", nodata: "fa-meh-o", noExpander: "", radio: "fa-circle-thin", // "fa-circle-o" radioSelected: "fa-circle", // radioUnknown: "fa-dot-circle-o", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "fa-file-o", docOpen: "fa-file-o", folder: "fa-folder-o", folderOpen: "fa-folder-open-o" }, "awesome5": { // fontawesome 5 have several different base classes // "far, fas, fal and fab" The rendered svg puts that prefix // in a different location so we have to keep them separate here _addClass: "", checkbox: "far fa-square", checkboxSelected: "far fa-check-square", // checkboxUnknown: "far fa-window-close", checkboxUnknown: "fas fa-square fancytree-helper-indeterminate-cb", radio: "far fa-circle", radioSelected: "fas fa-circle", radioUnknown: "far fa-dot-circle", dragHelper: "fas fa-arrow-right", dropMarker: "fas fa-long-arrow-right", error: "fas fa-exclamation-triangle", expanderClosed: "fas fa-caret-right", expanderLazy: "fas fa-angle-right", expanderOpen: "fas fa-caret-down", loading: "fas fa-spinner fa-pulse", nodata: "far fa-meh", noExpander: "", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "far fa-file", docOpen: "far fa-file", folder: "far fa-folder", folderOpen: "far fa-folder-open" }, "bootstrap3": { _addClass: "glyphicon", checkbox: "glyphicon-unchecked", checkboxSelected: "glyphicon-check", checkboxUnknown: "glyphicon-expand fancytree-helper-indeterminate-cb", // "glyphicon-share", dragHelper: "glyphicon-play", dropMarker: "glyphicon-arrow-right", error: "glyphicon-warning-sign", expanderClosed: "glyphicon-menu-right", // glyphicon-plus-sign expanderLazy: "glyphicon-menu-right", // glyphicon-plus-sign expanderOpen: "glyphicon-menu-down", // glyphicon-minus-sign loading: "glyphicon-refresh fancytree-helper-spin", nodata: "glyphicon-info-sign", noExpander: "", radio: "glyphicon-remove-circle", // "glyphicon-unchecked", radioSelected: "glyphicon-ok-circle", // "glyphicon-check", // radioUnknown: "glyphicon-ban-circle", // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: "glyphicon-file", docOpen: "glyphicon-file", folder: "glyphicon-folder-close", folderOpen: "glyphicon-folder-open" }, "material": { _addClass: "material-icons", checkbox: { text: "check_box_outline_blank" }, checkboxSelected: { text: "check_box" }, checkboxUnknown: { text: "indeterminate_check_box" }, dragHelper: { text: "play_arrow" }, dropMarker: { text: "arrow-forward" }, error: { text: "warning" }, expanderClosed: { text: "chevron_right" }, expanderLazy: { text: "last_page" }, expanderOpen: { text: "expand_more" }, loading: { text: "autorenew", addClass: "fancytree-helper-spin" }, nodata: { text: "info" }, noExpander: { text: "" }, radio: { text: "radio_button_unchecked" }, radioSelected: { text: "radio_button_checked" }, // Default node icons. // (Use tree.options.icon callback to define custom icons based on node data) doc: { text: "insert_drive_file" }, docOpen: { text: "insert_drive_file" }, folder: { text: "folder" }, folderOpen: { text: "folder_open" } } }; function setIcon( span, baseClass, opts, type ) { var map = opts.map, icon = map[ type ], $span = $( span ), setClass = baseClass + " " + (map._addClass || ""); if( typeof icon === "string" ) { $span.attr( "class", setClass + " " + icon ); } else if ( icon ) { if( icon.text ) { // $span.text( "" + icon.text ); span.textContent = "" + icon.text; } else if ( icon.html ) { // $(span).append($(icon.html)); span.innerHTML = icon.html; } $span.attr( "class", setClass + " " + ( icon.addClass || "" ) ); } } $.ui.fancytree.registerExtension({ name: "glyph", version: "2.28.0", // Default options for this extension. options: { preset: null, // 'awesome3', 'awesome4', 'bootstrap3', 'material' map: { } }, treeInit: function(ctx){ var tree = ctx.tree, opts = ctx.options.glyph; if( opts.preset ) { FT.assert( !!PRESETS[opts.preset], "Invalid value for `options.glyph.preset`: " + opts.preset); opts.map = $.extend({}, PRESETS[opts.preset], opts.map); } else { tree.warn("ext-glyph: missing `preset` option."); } this._superApply(arguments); tree.$container.addClass("fancytree-ext-glyph"); }, nodeRenderStatus: function(ctx) { var checkbox, icon, res, span, node = ctx.node, $span = $( node.span ), opts = ctx.options.glyph; res = this._super(ctx); if( node.isRoot() ){ return res; } span = $span.children("span.fancytree-expander").get(0); if( span ){ // if( node.isLoading() ){ // icon = "loading"; if( node.expanded && node.hasChildren() ){ icon = "expanderOpen"; }else if( node.isUndefined() ){ icon = "expanderLazy"; }else if( node.hasChildren() ){ icon = "expanderClosed"; }else{ icon = "noExpander"; } // span.className = "fancytree-expander " + map[icon]; setIcon( span, "fancytree-expander", opts, icon ); } if( node.tr ){ span = $("td", node.tr).find("span.fancytree-checkbox").get(0); }else{ span = $span.children("span.fancytree-checkbox").get(0); } if( span ) { checkbox = FT.evalOption("checkbox", node, node, opts, false); if( (node.parent && node.parent.radiogroup ) || checkbox === "radio" ) { icon = node.selected ? "radioSelected" : "radio"; setIcon( span, "fancytree-checkbox fancytree-radio", opts, icon ); } else { icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox"); // span.className = "fancytree-checkbox " + map[icon]; setIcon( span, "fancytree-checkbox", opts, icon ); } } // Standard icon (note that this does not match .fancytree-custom-icon, // that might be set by opts.icon callbacks) span = $span.children("span.fancytree-icon").get(0); if( span ){ if( node.statusNodeType ){ icon = node.statusNodeType; // loading, error }else if( node.folder ){ icon = ( node.expanded && node.hasChildren() ) ? "folderOpen" : "folder"; }else{ icon = node.expanded ? "docOpen" : "doc"; } setIcon( span, "fancytree-icon", opts, icon ); } return res; }, nodeSetStatus: function(ctx, status, message, details) { var res, span, opts = ctx.options.glyph, node = ctx.node; res = this._superApply(arguments); if( status === "error" || status === "loading" || status === "nodata" ){ if(node.parent){ span = $("span.fancytree-expander", node.span).get(0); if( span ) { setIcon( span, "fancytree-expander", opts, status ); } }else{ // span = $(".fancytree-statusnode-" + status, node[this.nodeContainerAttrName]) .find("span.fancytree-icon").get(0); if( span ) { setIcon( span, "fancytree-icon", opts, status ); } } } return res; } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.gridnav.js' *//*! * jquery.fancytree.gridnav.js * * Support keyboard navigation for trees with embedded input controls. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./jquery.fancytree", "./jquery.fancytree.table" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree.table"); // core + table module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /******************************************************************************* * Private functions and variables */ // Allow these navigation keys even when input controls are focused var KC = $.ui.keyCode, // which keys are *not* handled by embedded control, but passed to tree // navigation handler: NAV_KEYS = { "text": [KC.UP, KC.DOWN], "checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "link": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "select-one": [KC.LEFT, KC.RIGHT], "select-multiple": [KC.LEFT, KC.RIGHT] }; /* Calculate TD column index (considering colspans).*/ function getColIdx($tr, $td) { var colspan, td = $td.get(0), idx = 0; $tr.children().each(function () { if( this === td ) { return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return idx; } /* Find TD at given column index (considering colspans).*/ function findTdAtColIdx($tr, colIdx) { var colspan, res = null, idx = 0; $tr.children().each(function () { if( idx >= colIdx ) { res = $(this); return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return res; } /* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */ function findNeighbourTd($target, keyCode){ var $tr, colIdx, $td = $target.closest("td"), $tdNext = null; switch( keyCode ){ case KC.LEFT: $tdNext = $td.prev(); break; case KC.RIGHT: $tdNext = $td.next(); break; case KC.UP: case KC.DOWN: $tr = $td.parent(); colIdx = getColIdx($tr, $td); while( true ) { $tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next(); if( !$tr.length ) { break; } // Skip hidden rows if( $tr.is(":hidden") ) { continue; } // Find adjacent cell in the same column $tdNext = findTdAtColIdx($tr, colIdx); // Skip cells that don't conatain a focusable element if( $tdNext && $tdNext.find(":input,a").length ) { break; } } break; } return $tdNext; } /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "gridnav", version: "2.28.0", // Default options for this extension. options: { autofocusInput: false, // Focus first embedded input if node gets activated handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node }, treeInit: function(ctx){ // gridnav requires the table extension to be loaded before itself this._requireExtension("table", true, true); this._superApply(arguments); this.$container.addClass("fancytree-ext-gridnav"); // Activate node if embedded input gets focus (due to a click) this.$container.on("focusin", function(event){ var ctx2, node = $.ui.fancytree.getNode(event.target); if( node && !node.isActive() ){ // Call node.setActive(), but also pass the event ctx2 = ctx.tree._makeHookContext(node, event); ctx.tree._callHook("nodeSetActive", ctx2, true); } }); }, nodeSetActive: function(ctx, flag, callOpts) { var $outer, opts = ctx.options.gridnav, node = ctx.node, event = ctx.originalEvent || {}, triggeredByInput = $(event.target).is(":input"); flag = (flag !== false); this._superApply(arguments); if( flag ){ if( ctx.options.titlesTabbable ){ if( !triggeredByInput ) { $(node.span).find("span.fancytree-title").focus(); node.setFocus(); } // If one node is tabbable, the container no longer needs to be ctx.tree.$container.attr("tabindex", "-1"); // ctx.tree.$container.removeAttr("tabindex"); } else if( opts.autofocusInput && !triggeredByInput ){ // Set focus to input sub input (if node was clicked, but not // when TAB was pressed ) $outer = $(node.tr || node.span); $outer.find(":input:enabled:first").focus(); } } }, nodeKeydown: function(ctx) { var inputType, handleKeys, $td, opts = ctx.options.gridnav, event = ctx.originalEvent, $target = $(event.target); if( $target.is(":input:enabled") ) { inputType = $target.prop("type"); } else if( $target.is("a") ) { inputType = "link"; } // ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType); if( inputType && opts.handleCursorKeys ){ handleKeys = NAV_KEYS[inputType]; if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){ $td = findNeighbourTd($target, event.which); if( $td && $td.length ) { // ctx.node.debug("ignore keydown in input", event.which, handleKeys); $td.find(":input:enabled,a").focus(); // Prevent Fancytree default navigation return false; } } return true; } // ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType); return this._superApply(arguments); } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.persist.js' *//*! * jquery.fancytree.persist.js * * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @depends: js-cookie or jquery-cookie * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /* global Cookies:false */ /******************************************************************************* * Private functions and variables */ var cookieStore = null, localStorageStore = window.localStorage ? { get: function(key){ return window.localStorage.getItem(key); }, set: function(key, value){ window.localStorage.setItem(key, value); }, remove: function(key){ window.localStorage.removeItem(key); } } : null, sessionStorageStore = window.sessionStorage ? { get: function(key){ return window.sessionStorage.getItem(key); }, set: function(key, value){ window.sessionStorage.setItem(key, value); }, remove: function(key){ window.sessionStorage.removeItem(key); } } : null, _assert = $.ui.fancytree.assert, ACTIVE = "active", EXPANDED = "expanded", FOCUS = "focus", SELECTED = "selected"; if( typeof Cookies === "function" ) { // Assume https://github.com/js-cookie/js-cookie cookieStore = { get: Cookies.get, set: function(key, value) { Cookies.set(key, value, this.options.persist.cookie); }, remove: Cookies.remove }; } else if ( $ && typeof $.cookie === "function" ) { // Fall back to https://github.com/carhartl/jquery-cookie cookieStore = { get: $.cookie, set: function(key, value) { $.cookie.set(key, value, this.options.persist.cookie); }, remove: $.removeCookie }; } /* Recursively load lazy nodes * @param {string} mode 'load', 'expand', false */ function _loadLazyNodes(tree, local, keyList, mode, dfd) { var i, key, l, node, foundOne = false, expandOpts = tree.options.persist.expandOpts, deferredList = [], missingKeyList = []; keyList = keyList || []; dfd = dfd || $.Deferred(); for( i=0, l=keyList.length; i<l; i++ ) { key = keyList[i]; node = tree.getNodeByKey(key); if( node ) { if( mode && node.isUndefined() ) { foundOne = true; tree.debug("_loadLazyNodes: " + node + " is lazy: loading..."); if( mode === "expand" ) { deferredList.push(node.setExpanded(true, expandOpts)); } else { deferredList.push(node.load()); } } else { tree.debug("_loadLazyNodes: " + node + " already loaded."); node.setExpanded(true, expandOpts); } } else { missingKeyList.push(key); tree.debug("_loadLazyNodes: " + node + " was not yet found."); } } $.when.apply($, deferredList).always(function(){ // All lazy-expands have finished if( foundOne && missingKeyList.length > 0 ) { // If we read new nodes from server, try to resolve yet-missing keys _loadLazyNodes(tree, local, missingKeyList, mode, dfd); } else { if( missingKeyList.length ) { tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList); for( i=0, l=missingKeyList.length; i<l; i++ ) { key = keyList[i]; local._appendKey(EXPANDED, keyList[i], false); } } dfd.resolve(); } }); return dfd; } /** * [ext-persist] Remove persistence data of the given type(s). * Called like * $("#tree").fancytree("getTree").clearCookies("active expanded focus selected"); * * @alias Fancytree#clearPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.clearPersistData = function(types){ var local = this.ext.persist, prefix = local.cookiePrefix; types = types || "active expanded focus selected"; if(types.indexOf(ACTIVE) >= 0){ local._data(prefix + ACTIVE, null); } if(types.indexOf(EXPANDED) >= 0){ local._data(prefix + EXPANDED, null); } if(types.indexOf(FOCUS) >= 0){ local._data(prefix + FOCUS, null); } if(types.indexOf(SELECTED) >= 0){ local._data(prefix + SELECTED, null); } }; $.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){ this.warn("'tree.clearCookies()' is deprecated since v2.27.0: use 'clearPersistData()' instead."); return this.clearPersistData(types); }; /** * [ext-persist] Return persistence information from cookies * * Called like * $("#tree").fancytree("getTree").getPersistData(); * * @alias Fancytree#getPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){ var local = this.ext.persist, prefix = local.cookiePrefix, delim = local.cookieDelimiter, res = {}; res[ACTIVE] = local._data(prefix + ACTIVE); res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim); res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim); res[FOCUS] = local._data(prefix + FOCUS); return res; }; /* ***************************************************************************** * Extension code */ $.ui.fancytree.registerExtension({ name: "persist", version: "2.28.0", // Default options for this extension. options: { cookieDelimiter: "~", cookiePrefix: undefined, // 'fancytree-<treeId>-' by default cookie: { raw: false, expires: "", path: "", domain: "", secure: false }, expandLazy: false, // true: recursively expand and load lazy nodes expandOpts: undefined, // optional `opts` argument passed to setExpanded() fireActivate: true, // false: suppress `activate` event after active node was restored overrideSource: true, // true: cookie takes precedence over `source` data attributes. store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore types: "active expanded focus selected" }, /* Generic read/write string data to cookie, sessionStorage or localStorage. */ _data: function(key, value){ var store = this._local.store; if( value === undefined ) { return store.get.call(this, key); } else if ( value === null ) { store.remove.call(this, key); } else { store.set.call(this, key, value); } }, /* Append `key` to a cookie. */ _appendKey: function(type, key, flag){ key = "" + key; // #90 var local = this._local, instOpts = this.options.persist, delim = instOpts.cookieDelimiter, cookieName = local.cookiePrefix + type, data = local._data(cookieName), keyList = data ? data.split(delim) : [], idx = $.inArray(key, keyList); // Remove, even if we add a key, so the key is always the last entry if(idx >= 0){ keyList.splice(idx, 1); } // Append key to cookie if(flag){ keyList.push(key); } local._data(cookieName, keyList.join(delim)); }, treeInit: function(ctx){ var tree = ctx.tree, opts = ctx.options, local = this._local, instOpts = this.options.persist; // // For 'auto' or 'cookie' mode, the cookie plugin must be available // _assert((instOpts.store !== "auto" && instOpts.store !== "cookie") || cookieStore, // "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js"); local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-"); local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0; local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0; local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0; local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0; local.store = null; if( instOpts.store === "auto" ) { instOpts.store = localStorageStore ? "local" : "cookie"; } if( $.isPlainObject(instOpts.store) ) { local.store = instOpts.store; } else if( instOpts.store === "cookie" ) { local.store = cookieStore; } else if( instOpts.store === "local" ){ local.store = (instOpts.store === "local") ? localStorageStore : sessionStorageStore; } else if( instOpts.store === "session" ){ local.store = (instOpts.store === "local") ? localStorageStore : sessionStorageStore; } _assert(local.store, "Need a valid store."); // Bind init-handler to apply cookie state tree.$div.on("fancytreeinit", function(event){ if ( tree._triggerTreeEvent("beforeRestore", null, {}) === false ) { return; } var cookie, dfd, i, keyList, node, prevFocus = local._data(local.cookiePrefix + FOCUS), // record this before node.setActive() overrides it; noEvents = instOpts.fireActivate === false; // tree.debug("document.cookie:", document.cookie); cookie = local._data(local.cookiePrefix + EXPANDED); keyList = cookie && cookie.split(instOpts.cookieDelimiter); if( local.storeExpanded ) { // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load' // Also remove expand-cookies for unmatched nodes dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null); } else { // nothing to do dfd = new $.Deferred().resolve(); } dfd.done(function(){ if(local.storeSelected){ cookie = local._data(local.cookiePrefix + SELECTED); if(cookie){ keyList = cookie.split(instOpts.cookieDelimiter); for(i=0; i<keyList.length; i++){ node = tree.getNodeByKey(keyList[i]); if(node){ if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){ // node.setSelected(); node.selected = true; node.renderStatus(); } }else{ // node is no longer member of the tree: remove from cookie also local._appendKey(SELECTED, keyList[i], false); } } } // In selectMode 3 we have to fix the child nodes, since we // only stored the selected *top* nodes if( tree.options.selectMode === 3 ){ tree.visit(function(n){ if( n.selected ) { n.fixSelection3AfterClick(); return "skip"; } }); } } if(local.storeActive){ cookie = local._data(local.cookiePrefix + ACTIVE); if(cookie && (opts.persist.overrideSource || !tree.activeNode)){ node = tree.getNodeByKey(cookie); if(node){ node.debug("persist: set active", cookie); // We only want to set the focus if the container // had the keyboard focus before node.setActive(true, { noFocus: true, noEvents: noEvents }); } } } if(local.storeFocus && prevFocus){ node = tree.getNodeByKey(prevFocus); if(node){ // node.debug("persist: set focus", cookie); if( tree.options.titlesTabbable ) { $(node.span).find(".fancytree-title").focus(); } else { $(tree.$container).focus(); } // node.setFocus(); } } tree._triggerTreeEvent("restore", null, {}); }); }); // Init the tree return this._superApply(arguments); }, nodeSetActive: function(ctx, flag, callOpts) { var res, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeActive){ local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null); } return res; }, nodeSetExpanded: function(ctx, flag, callOpts) { var res, node = ctx.node, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeExpanded){ local._appendKey(EXPANDED, node.key, flag); } return res; }, nodeSetFocus: function(ctx, flag) { var res, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if( local.storeFocus ) { local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null); } return res; }, nodeSetSelected: function(ctx, flag, callOpts) { var res, selNodes, tree = ctx.tree, node = ctx.node, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeSelected){ if( tree.options.selectMode === 3 ){ // In selectMode 3 we only store the the selected *top* nodes. // De-selecting a node may also de-select some parents, so we // calculate the current status again selNodes = $.map(tree.getSelectedNodes(true), function(n){ return n.key; }); selNodes = selNodes.join(ctx.options.persist.cookieDelimiter); local._data(local.cookiePrefix + SELECTED, selNodes); } else { // beforeSelect can prevent the change - flag doesn't reflect the node.selected state local._appendKey(SELECTED, node.key, node.selected); } } return res; } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.table.js' *//*! * jquery.fancytree.table.js * * Render tree as table (aka 'tree grid', 'table tree'). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ msg = msg || ""; if(!cond){ $.error("Assertion failed " + msg); } } function insertFirstChild(referenceNode, newNode) { referenceNode.insertBefore(newNode, referenceNode.firstChild); } function insertSiblingAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } /* Show/hide all rows that are structural descendants of `parent`. */ function setChildRowVisibility(parent, flag) { parent.visit(function(node){ var tr = node.tr; // currentFlag = node.hide ? false : flag; // fix for ext-filter if(tr){ tr.style.display = (node.hide || !flag) ? "none" : ""; } if(!node.expanded){ return "skip"; } }); } /* Find node that is rendered in previous row. */ function findPrevRowNode(node){ var i, last, prev, parent = node.parent, siblings = parent ? parent.children : null; if(siblings && siblings.length > 1 && siblings[0] !== node){ // use the lowest descendant of the preceeding sibling i = $.inArray(node, siblings); prev = siblings[i - 1]; _assert(prev.tr); // descend to lowest child (with a <tr> tag) while(prev.children && prev.children.length){ last = prev.children[prev.children.length - 1]; if(!last.tr){ break; } prev = last; } }else{ // if there is no preceding sibling, use the direct parent prev = parent; } return prev; } /* Render callback for 'wide' mode. */ // function _renderStatusNodeWide(event, data) { // var node = data.node, // nodeColumnIdx = data.options.table.nodeColumnIdx, // $tdList = $(node.tr).find(">td"); // $tdList.eq(nodeColumnIdx).attr("colspan", data.tree.columnCount); // $tdList.not(":eq(" + nodeColumnIdx + ")").remove(); // } $.ui.fancytree.registerExtension({ name: "table", version: "2.28.0", // Default options for this extension. options: { checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx) // customStatus: false, // true: generate renderColumns events for status nodes indentation: 16, // indent every node level by 16px nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0) }, // Overide virtual methods for this extension. // `this` : is this extension object // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree) treeInit: function(ctx){ var i, columnCount, n, $row, $tbody, tree = ctx.tree, opts = ctx.options, tableOpts = opts.table, $table = tree.widget.element; if( tableOpts.customStatus != null ) { if( opts.renderStatusColumns != null) { $.error("The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' only instead."); } else { tree.warn("The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' instead."); opts.renderStatusColumns = tableOpts.customStatus; } } if( opts.renderStatusColumns ) { if( opts.renderStatusColumns === true ) { opts.renderStatusColumns = opts.renderColumns; // } else if( opts.renderStatusColumns === "wide" ) { // opts.renderStatusColumns = _renderStatusNodeWide; } } $table.addClass("fancytree-container fancytree-ext-table"); $tbody = $table.find(">tbody"); if( !$tbody.length ) { // TODO: not sure if we can rely on browsers to insert missing <tbody> before <tr>s: if( $table.find(">tr").length ) { $.error("Expected table > tbody > tr. If you see this please open an issue."); } $tbody = $("<tbody>").appendTo($table); } tree.tbody = $tbody[0]; // Prepare row templates: // Determine column count from table header if any columnCount = $("thead >tr:last >th", $table).length; // Read TR templates from tbody if any $row = $tbody.children("tr:first"); if( $row.length ) { n = $row.children("td").length; if( columnCount && n !== columnCount ) { tree.warn("Column count mismatch between thead (" + columnCount + ") and tbody (" + n + "): using tbody."); columnCount = n; } $row = $row.clone(); } else { // Only thead is defined: create default row markup _assert(columnCount >= 1, "Need either <thead> or <tbody> with <td> elements to determine column count."); $row = $("<tr />"); for(i=0; i<columnCount; i++) { $row.append("<td />"); } } $row.find(">td").eq(tableOpts.nodeColumnIdx) .html("<span class='fancytree-node' />"); if( opts.aria ) { $row.attr("role", "row"); $row.find("td").attr("role", "gridcell"); } tree.rowFragment = document.createDocumentFragment(); tree.rowFragment.appendChild($row.get(0)); // // If tbody contains a second row, use this as status node template // $row = $tbody.children("tr:eq(1)"); // if( $row.length === 0 ) { // tree.statusRowFragment = tree.rowFragment; // } else { // $row = $row.clone(); // tree.statusRowFragment = document.createDocumentFragment(); // tree.statusRowFragment.appendChild($row.get(0)); // } // $tbody.empty(); // Make sure that status classes are set on the node's <tr> elements tree.statusClassPropName = "tr"; tree.ariaPropName = "tr"; this.nodeContainerAttrName = "tr"; // #489: make sure $container is set to <table>, even if ext-dnd is listed before ext-table tree.$container = $table; this._superApply(arguments); // standard Fancytree created a root UL $(tree.rootNode.ul).remove(); tree.rootNode.ul = null; // Add container to the TAB chain // #577: Allow to set tabindex to "0", "-1" and "" this.$container.attr("tabindex", opts.tabindex); // this.$container.attr("tabindex", opts.tabbable ? "0" : "-1"); if(opts.aria) { tree.$container .attr("role", "treegrid") .attr("aria-readonly", true); } }, nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveChildMarkup()"); node.visit(function(n){ if(n.tr){ $(n.tr).remove(); n.tr = null; } }); }, nodeRemoveMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveMarkup()"); if(node.tr){ $(node.tr).remove(); node.tr = null; } this.nodeRemoveChildMarkup(ctx); }, /* Override standard render. */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx, tree = ctx.tree, node = ctx.node, opts = ctx.options, isRootNode = !node.parent; if( tree._enableUpdate === false ) { // $.ui.fancytree.debug("*** nodeRender _enableUpdate: false"); return; } if( !_recursive ){ ctx.hasCollapsedParents = node.parent && !node.parent.expanded; } // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr)); if( !isRootNode ){ if( node.tr && force ) { this.nodeRemoveMarkup(ctx); } if( !node.tr ) { if( ctx.hasCollapsedParents && !deep ) { // #166: we assume that the parent will be (recursively) rendered // later anyway. // node.debug("nodeRender ignored due to unrendered parent"); return; } // Create new <tr> after previous row // if( node.isStatusNode() ) { // newRow = tree.statusRowFragment.firstChild.cloneNode(true); // } else { newRow = tree.rowFragment.firstChild.cloneNode(true); // } prevNode = findPrevRowNode(node); // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key); _assert(prevNode); if(collapsed === true && _recursive){ // hide all child rows, so we can use an animation to show it later newRow.style.display = "none"; }else if(deep && ctx.hasCollapsedParents){ // also hide this row if deep === true but any parent is collapsed newRow.style.display = "none"; // newRow.style.color = "red"; } if(!prevNode.tr){ _assert(!prevNode.parent, "prev. row must have a tr, or be system root"); // tree.tbody.appendChild(newRow); insertFirstChild(tree.tbody, newRow); // #675 }else{ insertSiblingAfter(prevNode.tr, newRow); } node.tr = newRow; if( node.key && opts.generateIds ){ node.tr.id = opts.idPrefix + node.key; } node.tr.ftnode = node; // if(opts.aria){ // $(node.tr).attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key); // } node.span = $("span.fancytree-node", node.tr).get(0); // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // Allow tweaking, binding, after node was created for the first time // tree._triggerNodeEvent("createNode", ctx); if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } } else { if( force ) { // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // triggers renderColumns() } else { // Update element classes according to node state this.nodeRenderStatus(ctx); } } } // Allow tweaking after node state was rendered // tree._triggerNodeEvent("renderNode", ctx); if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } // Visit child nodes // Add child markup children = node.children; if(children && (isRootNode || deep || node.expanded)){ for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded; this.nodeRender(subCtx, force, deep, collapsed, true); } } // Make sure, that <tr> order matches node.children order. if(children && !_recursive){ // we only have to do it once, for the root branch prevTr = node.tr || null; firstTr = tree.tbody.firstChild; // Iterate over all descendants node.visit(function(n){ if(n.tr){ if(!n.parent.expanded && n.tr.style.display !== "none"){ // fix after a node was dropped over a collapsed n.tr.style.display = "none"; setChildRowVisibility(n, false); } if(n.tr.previousSibling !== prevTr){ node.debug("_fixOrder: mismatch at node: " + n); var nextTr = prevTr ? prevTr.nextSibling : firstTr; tree.tbody.insertBefore(n.tr, nextTr); } prevTr = n.tr; } }); } // Update element classes according to node state // if(!isRootNode){ // this.nodeRenderStatus(ctx); // } }, nodeRenderTitle: function(ctx, title) { var $cb, res, node = ctx.node, opts = ctx.options, isStatusNode = node.isStatusNode(); res = this._super(ctx, title); if( node.isRootNode() ) { return res; } // Move checkbox to custom column if(opts.checkbox && !isStatusNode && opts.table.checkboxColumnIdx != null ){ $cb = $("span.fancytree-checkbox", node.span); //.detach(); $(node.tr).find("td").eq(+opts.table.checkboxColumnIdx).html($cb); } // Update element classes according to node state this.nodeRenderStatus(ctx); if( isStatusNode ) { if( opts.renderStatusColumns ) { // Let user code write column content opts.renderStatusColumns.call(ctx.tree, {type: "renderStatusColumns"}, ctx); } // else: default rendering for status node: leave other cells empty } else if ( opts.renderColumns ) { opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx); } return res; }, nodeRenderStatus: function(ctx) { var indent, node = ctx.node, opts = ctx.options; this._super(ctx); $(node.tr).removeClass("fancytree-node"); // indent indent = (node.getLevel() - 1) * opts.table.indentation; $(node.span).css({paddingLeft: indent + "px"}); // #460 // $(node.span).css({marginLeft: indent + "px"}); }, /* Expand node, return Deferred.promise. */ nodeSetExpanded: function(ctx, flag, callOpts) { // flag defaults to true flag = (flag !== false); if((ctx.node.expanded && flag) || (!ctx.node.expanded && !flag)) { // Expanded state isn't changed - just call base implementation return this._superApply(arguments); } var dfd = new $.Deferred(), subOpts = $.extend({}, callOpts, {noEvents: true, noAnimation: true}); callOpts = callOpts || {}; function _afterExpand(ok) { setChildRowVisibility(ctx.node, flag); if( ok ) { if( flag && ctx.options.autoScroll && !callOpts.noAnimation && ctx.node.hasChildren() ) { // Scroll down to last child, but keep current node visible ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){ if( !callOpts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); }); } else { if( !callOpts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); } } else { if( !callOpts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.rejectWith(ctx.node); } } // Call base-expand with disabled events and animation this._super(ctx, flag, subOpts).done(function () { _afterExpand(true); }).fail(function () { _afterExpand(false); }); return dfd.promise(); }, nodeSetStatus: function(ctx, status, message, details) { if(status === "ok"){ var node = ctx.node, firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $(firstChild.tr).remove(); } } return this._superApply(arguments); }, treeClear: function(ctx) { this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode)); return this._superApply(arguments); }, treeDestroy: function(ctx) { this.$container.find("tbody").empty(); this.$source && this.$source.removeClass("fancytree-helper-hidden"); return this._superApply(arguments); } /*, treeSetFocus: function(ctx, flag) { // alert("treeSetFocus" + ctx.tree.$container); ctx.tree.$container.focus(); $.ui.fancytree.focusTree = ctx.tree; }*/ }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.themeroller.js' *//*! * jquery.fancytree.themeroller.js * * Enable jQuery UI ThemeRoller styles. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @see http://jqueryui.com/themeroller/ * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "themeroller", version: "2.28.0", // Default options for this extension. options: { activeClass: "ui-state-active", // Class added to active node // activeClass: "ui-state-highlight", addClass: "ui-corner-all", // Class added to all nodes focusClass: "ui-state-focus", // Class added to focused node hoverClass: "ui-state-hover", // Class added to hovered node selectedClass: "ui-state-highlight" // Class added to selected nodes // selectedClass: "ui-state-active" }, treeInit: function(ctx){ var $el = ctx.widget.element, opts = ctx.options.themeroller; this._superApply(arguments); if($el[0].nodeName === "TABLE"){ $el.addClass("ui-widget ui-corner-all"); $el.find(">thead tr").addClass("ui-widget-header"); $el.find(">tbody").addClass("ui-widget-conent"); }else{ $el.addClass("ui-widget ui-widget-content ui-corner-all"); } $el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){ var node = $.ui.fancytree.getNode(event.target), flag = (event.type === "mouseenter"); $(node.tr ? node.tr : node.span) .toggleClass(opts.hoverClass + " " + opts.addClass, flag); }); }, treeDestroy: function(ctx){ this._superApply(arguments); ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all"); }, nodeRenderStatus: function(ctx){ var classes = {}, node = ctx.node, $el = $(node.tr ? node.tr : node.span), opts = ctx.options.themeroller; this._super(ctx); /* .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons. */ // Set ui-state-* class (handle the case that the same class is assigned // to different states) classes[opts.activeClass] = false; classes[opts.focusClass] = false; classes[opts.selectedClass] = false; if( node.isActive() ) { classes[opts.activeClass] = true; } if( node.hasFocus() ) { classes[opts.focusClass] = true; } // activeClass takes precedence before selectedClass: if( node.isSelected() && !node.isActive() ) { classes[opts.selectedClass] = true; } $el.toggleClass(opts.activeClass, classes[opts.activeClass]); $el.toggleClass(opts.focusClass, classes[opts.focusClass]); $el.toggleClass(opts.selectedClass, classes[opts.selectedClass]); // Additional classes (e.g. 'ui-corner-all') $el.addClass(opts.addClass); } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure /*! Extension 'jquery.fancytree.wide.js' *//*! * jquery.fancytree.wide.js * Support for 100% wide selection bars. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2018, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.28.0 * @date 2018-03-02T20:59:49Z */ ;(function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery", "./jquery.fancytree" ], factory ); } else if ( typeof module === "object" && module.exports ) { // Node/CommonJS require("./jquery.fancytree"); module.exports = factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }( function( $ ) { "use strict"; var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"] /******************************************************************************* * Private functions and variables */ // var _assert = $.ui.fancytree.assert; /* Calculate inner width without scrollbar */ // function realInnerWidth($el) { // // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/ // // inst.contWidth = parseFloat(this.$container.css("width"), 10); // // 'Client width without scrollbar' - 'padding' // return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10)); // } /* Create a global embedded CSS style for the tree. */ function defineHeadStyleElement(id, cssText) { id = "fancytree-style-" + id; var $headStyle = $("#" + id); if( !cssText ) { $headStyle.remove(); return null; } if( !$headStyle.length ) { $headStyle = $("<style />") .attr("id", id) .addClass("fancytree-style") .prop("type", "text/css") .appendTo("head"); } try { $headStyle.html(cssText); } catch ( e ) { // fix for IE 6-8 $headStyle[0].styleSheet.cssText = cssText; } return $headStyle; } /* Calculate the CSS rules that indent title spans. */ function renderLevelCss(containerId, depth, levelOfs, lineOfs, labelOfs, measureUnit) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for(i = 0; i < depth; i++) { rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }"); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push( "#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title, " + "#" + containerId + " li.fancytree-animating span.fancytree-title " + // #716 "{ padding-left: " + labelOfs + measureUnit + "; position: static; width: auto; }"); return rules.join("\n"); } // /** // * [ext-wide] Recalculate the width of the selection bar after the tree container // * was resized.<br> // * May be called explicitly on container resize, since there is no resize event // * for DIV tags. // * // * @alias Fancytree#wideUpdate // * @requires jquery.fancytree.wide.js // */ // $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){ // var inst = this.ext.wide, // prevCw = inst.contWidth, // prevLo = inst.lineOfs; // inst.contWidth = realInnerWidth(this.$container); // // Each title is precceeded by 2 or 3 icons (16px + 3 margin) // // + 1px title border and 3px title padding // // TODO: use code from treeInit() below // inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19; // if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) { // this.debug("wideUpdate: " + inst.contWidth); // this.visit(function(node){ // node.tree._callHook("nodeRenderTitle", node); // }); // } // }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "wide", version: "2.28.0", // Default options for this extension. options: { iconWidth: null, // Adjust this if @fancy-icon-width != "16px" iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px" labelSpacing: null, // Adjust this if padding between icon and label != "3px" levelOfs: null // Adjust this if ul padding != "16px" }, treeCreate: function(ctx){ this._superApply(arguments); this.$container.addClass("fancytree-ext-wide"); var containerId, cssText, iconSpacingUnit, labelSpacingUnit, iconWidthUnit, levelOfsUnit, instOpts = ctx.options.wide, // css sniffing $dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />") .appendTo(ctx.tree.$container), $dummyIcon = $dummyLI.find(".fancytree-icon"), $dummyUL = $dummyLI.find("ul"), // $dummyTitle = $dummyLI.find(".fancytree-title"), iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"), iconWidth = instOpts.iconWidth || $dummyIcon.css("width"), labelSpacing = instOpts.labelSpacing || "3px", levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left"); $dummyLI.remove(); iconSpacingUnit = iconSpacing.match(reNumUnit)[2]; iconSpacing = parseFloat(iconSpacing, 10); labelSpacingUnit = labelSpacing.match(reNumUnit)[2]; labelSpacing = parseFloat(labelSpacing, 10); iconWidthUnit = iconWidth.match(reNumUnit)[2]; iconWidth = parseFloat(iconWidth, 10); levelOfsUnit = levelOfs.match(reNumUnit)[2]; if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit || labelSpacingUnit !== iconWidthUnit ) { $.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit"); } this._local.measureUnit = iconWidthUnit; this._local.levelOfs = parseFloat(levelOfs); this._local.lineOfs = (1 + (ctx.options.checkbox ? 1 : 0) + (ctx.options.icon === false ? 0 : 1)) * (iconWidth + iconSpacing) + iconSpacing; this._local.labelOfs = labelSpacing; this._local.maxDepth = 10; // Get/Set a unique Id on the container (if not already exists) containerId = this.$container.uniqueId().attr("id"); // Generated css rules for some levels (extended on demand) cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.labelOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); }, treeDestroy: function(ctx){ // Remove generated css rules defineHeadStyleElement(this.$container.attr("id"), null); return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { var containerId, cssText, res, node = ctx.node, level = node.getLevel(); res = this._super(ctx); // Generate some more level-n rules if required if( level > this._local.maxDepth ) { containerId = this.$container.attr("id"); this._local.maxDepth *= 2; node.debug("Define global ext-wide css up to level " + this._local.maxDepth); cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.labelSpacing, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); } // Add level-n class to apply indentation padding. // (Setting element style would not work, since it cannot easily be // overriden while animations run) $(node.span).addClass("fancytree-level-" + level); return res; } }); // Value returned by `require('jquery.fancytree..')` return $.ui.fancytree; })); // End of closure // Value returned by `require('jquery.fancytree')` return $.ui.fancytree; })); // End of closure
function createResult(ctx, next) { return { status: next.status, context: ctx, output: next.output, completed: next.status == COMPLETED }; } export var COMPLETED = 'completed'; export var CANCELLED = 'cancelled'; export var REJECTED = 'rejected'; export var RUNNING = 'running'; export class Pipeline { constructor() { this.steps = []; } withStep(step) { var run, steps, i, l; if (typeof step == 'function') { run = step; } else if (step.isMultiStep) { steps = step.getSteps(); for (i = 0, l = steps.length; i < l; i++) { this.withStep(steps[i]); } return this; } else { run = step.run.bind(step); } this.steps.push(run); return this; } run(ctx) { var index = -1, steps = this.steps, next, currentStep; next = function() { index++; if (index < steps.length) { currentStep = steps[index]; try { return currentStep(ctx, next); } catch(e) { return next.reject(e); } } else { return next.complete(); } }; next.complete = output => { next.status = COMPLETED; next.output = output; return Promise.resolve(createResult(ctx, next)); }; next.cancel = reason => { next.status = CANCELLED; next.output = reason; return Promise.resolve(createResult(ctx, next)); }; next.reject = error => { next.status = REJECTED; next.output = error; return Promise.reject(createResult(ctx, next)); }; next.status = RUNNING; return next(); } }