code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/** * @depends {nrs.js} */ var NRS = (function(NRS, $, undefined) { NRS.newlyCreatedAccount = false; NRS.allowLoginViaEnter = function() { $("#login_password").keypress(function(e) { if (e.which == '13') { e.preventDefault(); var password = $("#login_password").val(); NRS.login(password); } }); } NRS.showLoginOrWelcomeScreen = function() { if (NRS.hasLocalStorage && localStorage.getItem("logged_in")) { NRS.showLoginScreen(); } else { NRS.showWelcomeScreen(); } } NRS.showLoginScreen = function() { $("#account_phrase_custom_panel, #account_phrase_generator_panel, #welcome_panel, #custom_passphrase_link").hide(); $("#account_phrase_custom_panel :input:not(:button):not([type=submit])").val(""); $("#account_phrase_generator_panel :input:not(:button):not([type=submit])").val(""); $("#login_panel").show(); setTimeout(function() { $("#login_password").focus() }, 10); } NRS.showWelcomeScreen = function() { $("#login_panel, account_phrase_custom_panel, #account_phrase_generator_panel, #account_phrase_custom_panel, #welcome_panel, #custom_passphrase_link").hide(); $("#welcome_panel").show(); } NRS.registerUserDefinedAccount = function() { $("#account_phrase_generator_panel, #login_panel, #welcome_panel, #custom_passphrase_link").hide(); $("#account_phrase_custom_panel :input:not(:button):not([type=submit])").val(""); $("#account_phrase_generator_panel :input:not(:button):not([type=submit])").val(""); $("#account_phrase_custom_panel").show(); $("#registration_password").focus(); } NRS.registerAccount = function() { $("#login_panel, #welcome_panel").hide(); $("#account_phrase_generator_panel").show(); $("#account_phrase_generator_panel step_3 .callout").hide(); var $loading = $("#account_phrase_generator_loading"); var $loaded = $("#account_phrase_generator_loaded"); if (window.crypto || window.msCrypto) { $loading.find("span.loading_text").html($.t("generating_passphrase_wait")); } $loading.show(); $loaded.hide(); if (typeof PassPhraseGenerator == "undefined") { $.when( $.getScript("js/crypto/3rdparty/seedrandom.js"), $.getScript("js/crypto/passphrasegenerator.js") ).done(function() { $loading.hide(); $loaded.show(); PassPhraseGenerator.generatePassPhrase("#account_phrase_generator_panel"); }).fail(function(jqxhr, settings, exception) { alert($.t("error_word_list")); }); } else { $loading.hide(); $loaded.show(); PassPhraseGenerator.generatePassPhrase("#account_phrase_generator_panel"); } } NRS.verifyGeneratedPassphrase = function() { var password = $.trim($("#account_phrase_generator_panel .step_3 textarea").val()); if (password != PassPhraseGenerator.passPhrase) { $("#account_phrase_generator_panel .step_3 .callout").show(); } else { NRS.newlyCreatedAccount = true; NRS.login(password); PassPhraseGenerator.reset(); $("#account_phrase_generator_panel textarea").val(""); $("#account_phrase_generator_panel .step_3 .callout").hide(); } } $("#account_phrase_custom_panel form").submit(function(event) { event.preventDefault() var password = $("#registration_password").val(); var repeat = $("#registration_password_repeat").val(); var error = ""; if (password.length < 35) { error = $.t("error_passphrase_length"); } else if (password.length < 50 && (!password.match(/[A-Z]/) || !password.match(/[0-9]/))) { error = $.t("error_passphrase_strength"); } else if (password != repeat) { error = $.t("error_passphrase_match"); } if (error) { $("#account_phrase_custom_panel .callout").first().removeClass("callout-info").addClass("callout-danger").html(error); } else { $("#registration_password, #registration_password_repeat").val(""); NRS.login(password); } }); NRS.login = function(password, callback) { if (!password.length) { $.growl($.t("error_passphrase_required_login"), { "type": "danger", "offset": 10 }); return; } else if (!NRS.isTestNet && password.length < 12 && $("#login_check_password_length").val() == 1) { $("#login_check_password_length").val(0); $("#login_error .callout").html($.t("error_passphrase_login_length")); $("#login_error").show(); return; } $("#login_password, #registration_password, #registration_password_repeat").val(""); $("#login_check_password_length").val(1); NRS.sendRequest("getBlockchainStatus", function(response) { if (response.errorCode) { $.growl($.t("error_server_connect"), { "type": "danger", "offset": 10 }); return; } NRS.state = response; //this is done locally.. NRS.sendRequest("getAccountId", { "secretPhrase": password }, function(response) { if (!response.errorCode) { NRS.account = String(response.accountId).escapeHTML(); NRS.publicKey = NRS.getPublicKey(converters.stringToHexString(password)); } if (!NRS.account) { $.growl($.t("error_find_account_id"), { "type": "danger", "offset": 10 }); return; } var nxtAddress = new NxtAddress(); if (nxtAddress.set(NRS.account)) { NRS.accountRS = nxtAddress.toString(); } else { $.growl($.t("error_generate_account_id"), { "type": "danger", "offset": 10 }); return; } NRS.sendRequest("getAccountPublicKey", { "account": NRS.account }, function(response) { if (response && response.publicKey && response.publicKey != NRS.generatePublicKey(password)) { $.growl($.t("error_account_taken"), { "type": "danger", "offset": 10 }); return; } if ($("#remember_password").is(":checked")) { NRS.rememberPassword = true; $("#remember_password").prop("checked", false); NRS.setPassword(password); $(".secret_phrase, .show_secret_phrase").hide(); $(".hide_secret_phrase").show(); } $("#account_id").html(String(NRS.accountRS).escapeHTML()).css("font-size", "12px"); var passwordNotice = ""; if (password.length < 35) { passwordNotice = $.t("error_passphrase_length_secure"); } else if (password.length < 50 && (!password.match(/[A-Z]/) || !password.match(/[0-9]/))) { passwordNotice = $.t("error_passphrase_strength_secure"); } if (passwordNotice) { $.growl("<strong>" + $.t("warning") + "</strong>: " + passwordNotice, { "type": "danger" }); } if (NRS.state) { NRS.checkBlockHeight(); } NRS.getAccountInfo(true, function() { if (NRS.accountInfo.currentLeasingHeightFrom) { NRS.isLeased = (NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom && NRS.lastBlockHeight <= NRS.accountInfo.currentLeasingHeightTo); } else { NRS.isLeased = false; } //forging requires password to be sent to the server, so we don't do it automatically if not localhost if (!NRS.accountInfo.publicKey || NRS.accountInfo.effectiveBalanceNXT == 0 || !NRS.isLocalHost || NRS.downloadingBlockchain || NRS.isLeased) { $("#forging_indicator").removeClass("forging"); $("#forging_indicator span").html($.t("not_forging")).attr("data-i18n", "not_forging"); $("#forging_indicator").show(); NRS.isForging = false; } else if (NRS.isLocalHost) { NRS.sendRequest("startForging", { "secretPhrase": password }, function(response) { if ("deadline" in response) { $("#forging_indicator").addClass("forging"); $("#forging_indicator span").html($.t("forging")).attr("data-i18n", "forging"); NRS.isForging = true; } else { $("#forging_indicator").removeClass("forging"); $("#forging_indicator span").html($.t("not_forging")).attr("data-i18n", "not_forging"); NRS.isForging = false; } $("#forging_indicator").show(); }); } }); //NRS.getAccountAliases(); NRS.unlock(); if (NRS.isOutdated) { $.growl($.t("nrs_update_available"), { "type": "danger" }); } if (!NRS.downloadingBlockchain) { NRS.checkIfOnAFork(); } NRS.setupClipboardFunctionality(); if (callback) { callback(); } NRS.checkLocationHash(password); $(window).on("hashchange", NRS.checkLocationHash); NRS.getInitialTransactions(); }); }); }); } $("#logout_button_container").on("show.bs.dropdown", function(e) { if (!NRS.isForging) { e.preventDefault(); } }); NRS.showLockscreen = function() { if (NRS.hasLocalStorage && localStorage.getItem("logged_in")) { setTimeout(function() { $("#login_password").focus() }, 10); } else { NRS.showWelcomeScreen(); } $("#center").show(); } NRS.unlock = function() { if (NRS.hasLocalStorage && !localStorage.getItem("logged_in")) { localStorage.setItem("logged_in", true); } var userStyles = ["header", "sidebar", "boxes"]; for (var i = 0; i < userStyles.length; i++) { var color = NRS.settings[userStyles[i] + "_color"]; if (color) { NRS.updateStyle(userStyles[i], color); } } var contentHeaderHeight = $(".content-header").height(); var navBarHeight = $("nav.navbar").height(); // $(".content-splitter-right").css("bottom", (contentHeaderHeight + navBarHeight + 10) + "px"); $("#lockscreen").hide(); $("body, html").removeClass("lockscreen"); $("#login_error").html("").hide(); $(document.documentElement).scrollTop(0); } $("#logout_button").click(function(e) { if (!NRS.isForging) { e.preventDefault(); NRS.logout(); } }); NRS.logout = function(stopForging) { if (stopForging && NRS.isForging) { $("#stop_forging_modal .show_logout").show(); $("#stop_forging_modal").modal("show"); } else { NRS.setDecryptionPassword(""); NRS.setPassword(""); window.location.reload(); } } NRS.setPassword = function(password) { NRS.setEncryptionPassword(password); NRS.setServerPassword(password); } return NRS; }(NRS || {}, jQuery));
metrospark/czarcraft
html/ui/js/nrs.login.js
JavaScript
lgpl-2.1
10,072
// Copyright 2009 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. goog.provide('goog.editor.plugins.equation.EquationBubble'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Command'); goog.require('goog.editor.plugins.AbstractBubblePlugin'); goog.require('goog.editor.plugins.equation.ImageRenderer'); goog.require('goog.string.Unicode'); goog.require('goog.ui.editor.Bubble'); /** * Property bubble plugin for equations. * * @constructor * @extends {goog.editor.plugins.AbstractBubblePlugin} */ goog.editor.plugins.equation.EquationBubble = function() { goog.base(this); }; goog.inherits(goog.editor.plugins.equation.EquationBubble, goog.editor.plugins.AbstractBubblePlugin); /** * Id for 'edit' link. * @type {string} * @private */ goog.editor.plugins.equation.EquationBubble.EDIT_ID_ = 'ee_bubble_edit'; /** * Id for 'remove' link. * @type {string} * @private */ goog.editor.plugins.equation.EquationBubble.REMOVE_ID_ = 'ee_remove_remove'; /** * @desc Label for the equation property bubble. */ var MSG_EE_BUBBLE_EQUATION = goog.getMsg('Equation:'); /** * @desc Link text for equation property bubble to edit the equation. */ var MSG_EE_BUBBLE_EDIT = goog.getMsg('Edit'); /** * @desc Link text for equation property bubble to remove the equation. */ var MSG_EE_BUBBLE_REMOVE = goog.getMsg('Remove'); /** @inheritDoc */ goog.editor.plugins.equation.EquationBubble.prototype.getTrogClassId = function() { return 'EquationBubble'; }; /** @inheritDoc */ goog.editor.plugins.equation.EquationBubble.prototype. getBubbleTargetFromSelection = function(selectedElement) { if (selectedElement && goog.editor.plugins.equation.ImageRenderer.isEquationElement( selectedElement)) { return selectedElement; } return null; }; /** @inheritDoc */ goog.editor.plugins.equation.EquationBubble.prototype.createBubbleContents = function(bubbleContainer) { goog.dom.appendChild(bubbleContainer, bubbleContainer.ownerDocument.createTextNode( MSG_EE_BUBBLE_EQUATION + goog.string.Unicode.NBSP)); this.createLink(goog.editor.plugins.equation.EquationBubble.EDIT_ID_, MSG_EE_BUBBLE_EDIT, this.editEquation_, bubbleContainer); goog.dom.appendChild(bubbleContainer, bubbleContainer.ownerDocument.createTextNode( MSG_EE_BUBBLE_EQUATION + goog.editor.plugins.AbstractBubblePlugin.DASH_NBSP_STRING)); this.createLink(goog.editor.plugins.equation.EquationBubble.REMOVE_ID_, MSG_EE_BUBBLE_REMOVE, this.removeEquation_, bubbleContainer); }; /** @inheritDoc */ goog.editor.plugins.equation.EquationBubble.prototype.getBubbleType = function() { return goog.dom.TagName.IMG; }; /** @inheritDoc */ goog.editor.plugins.equation.EquationBubble.prototype.getBubbleTitle = function() { /** @desc Title for the equation bubble. */ var MSG_EQUATION_BUBBLE_TITLE = goog.getMsg('Equation'); return MSG_EQUATION_BUBBLE_TITLE; }; /** * Removes the equation associated with the bubble. * @private */ goog.editor.plugins.equation.EquationBubble.prototype.removeEquation_ = function() { this.fieldObject.dispatchBeforeChange(); goog.dom.removeNode(this.getTargetElement()); this.closeBubble(); this.fieldObject.dispatchChange(); }; /** * Opens equation editor for the equation associated with the bubble. * @private */ goog.editor.plugins.equation.EquationBubble.prototype.editEquation_ = function() { var equationNode = this.getTargetElement(); this.closeBubble(); this.fieldObject.execCommand(goog.editor.Command.EQUATION, equationNode); };
turnonline/maven-optimizer-plugin
src/main/resources/org/ctoolkit/maven/plugins/optimizer/gc_closure/goog/editor/plugins/equation/equationbubble.js
JavaScript
lgpl-2.1
4,191
/* * JQuery zTree core 3.1 * http://code.google.com/p/jquerytree/ * * Copyright (c) 2010 Hunter.z (baby666.cn) * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2012-02-14 */ (function($){ var settings = {}, roots = {}, caches = {}, zId = 0, //default consts of core _consts = { event: { NODECREATED: "ztree_nodeCreated", CLICK: "ztree_click", EXPAND: "ztree_expand", COLLAPSE: "ztree_collapse", ASYNC_SUCCESS: "ztree_async_success", ASYNC_ERROR: "ztree_async_error" }, id: { A: "_a", ICON: "_ico", SPAN: "_span", SWITCH: "_switch", UL: "_ul" }, line: { ROOT: "root", ROOTS: "roots", CENTER: "center", BOTTOM: "bottom", NOLINE: "noline", LINE: "line" }, folder: { OPEN: "open", CLOSE: "close", DOCU: "docu" }, node: { CURSELECTED: "curSelectedNode" } }, //default setting of core _setting = { treeId: "", treeObj: null, view: { addDiyDom: null, autoCancelSelected: true, dblClickExpand: true, expandSpeed: "fast", fontCss: {}, nameIsHTML: false, selectedMulti: true, showIcon: true, showLine: true, showTitle: true }, data: { key: { children: "children", name: "name", title: "" }, simpleData: { enable: false, idKey: "id", pIdKey: "pId", rootPId: null }, keep: { parent: false, leaf: false } }, async: { enable: false, contentType: "application/x-www-form-urlencoded", type: "post", dataType: "text", url: "", autoParam: [], otherParam: [], dataFilter: null }, callback: { beforeAsync:null, beforeClick:null, beforeRightClick:null, beforeMouseDown:null, beforeMouseUp:null, beforeExpand:null, beforeCollapse:null, onAsyncError:null, onAsyncSuccess:null, onNodeCreated:null, onClick:null, onRightClick:null, onMouseDown:null, onMouseUp:null, onExpand:null, onCollapse:null } }, //default root of core //zTree use root to save full data _initRoot = function (setting) { var r = data.getRoot(setting); if (!r) { r = {}; data.setRoot(setting, r); } r.children = []; r.expandTriggerFlag = false; r.curSelectedList = []; r.noSelection = true; r.createdNodes = []; }, //default cache of core _initCache = function(setting) { var c = data.getCache(setting); if (!c) { c = {}; data.setCache(setting, c); } c.nodes = []; c.doms = []; }, //default bindEvent of core _bindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.unbind(c.NODECREATED); o.bind(c.NODECREATED, function (event, treeId, node) { tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); }); o.unbind(c.CLICK); o.bind(c.CLICK, function (event, treeId, node, clickFlag) { tools.apply(setting.callback.onClick, [event, treeId, node, clickFlag]); }); o.unbind(c.EXPAND); o.bind(c.EXPAND, function (event, treeId, node) { tools.apply(setting.callback.onExpand, [event, treeId, node]); }); o.unbind(c.COLLAPSE); o.bind(c.COLLAPSE, function (event, treeId, node) { tools.apply(setting.callback.onCollapse, [event, treeId, node]); }); o.unbind(c.ASYNC_SUCCESS); o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); }); o.unbind(c.ASYNC_ERROR); o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); }); }, //default event proxy of core _eventProxy = function(event) { var target = event.target, setting = settings[event.data.treeId], tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null, tmp = null; if (tools.eqs(event.type, "mousedown")) { treeEventType = "mousedown"; } else if (tools.eqs(event.type, "mouseup")) { treeEventType = "mouseup"; } else if (tools.eqs(event.type, "contextmenu")) { treeEventType = "contextmenu"; } else if (tools.eqs(event.type, "click")) { if (tools.eqs(target.tagName, "button")) { target.blur(); } if (tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.SWITCH) !== null) { tId = target.parentNode.id; nodeEventType = "switchNode"; } else { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tmp.parentNode.id; nodeEventType = "clickNode"; } } } else if (tools.eqs(event.type, "dblclick")) { treeEventType = "dblclick"; tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tmp.parentNode.id; nodeEventType = "switchNode"; } } if (treeEventType.length > 0 && tId.length == 0) { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) {tId = tmp.parentNode.id;} } // event to node if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "switchNode" : if (!node.isParent) { nodeEventType = ""; } else if (tools.eqs(event.type, "click") || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { nodeEventCallback = handler.onSwitchNode; } else { nodeEventType = ""; } break; case "clickNode" : nodeEventCallback = handler.onClickNode; break; } } // event to zTree switch (treeEventType) { case "mousedown" : treeEventCallback = handler.onZTreeMousedown; break; case "mouseup" : treeEventCallback = handler.onZTreeMouseup; break; case "dblclick" : treeEventCallback = handler.onZTreeDblclick; break; case "contextmenu" : treeEventCallback = handler.onZTreeContextmenu; break; } var proxyResult = { stop: false, node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of core _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; var childKey = setting.data.key.children; n.level = level; n.tId = setting.treeId + "_" + (++zId); n.parentTId = parentNode ? parentNode.tId : null; if (n[childKey] && n[childKey].length > 0) { if (typeof n.open == "string") n.open = tools.eqs(n.open, "true"); n.open = !!n.open; n.isParent = true; n.zAsync = true; } else { n.open = false; if (typeof n.isParent == "string") n.isParent = tools.eqs(n.isParent, "true"); n.isParent = !!n.isParent; n.zAsync = !n.isParent; } n.isFirstNode = isFirstNode; n.isLastNode = isLastNode; n.getParentNode = function() {return data.getNodeCache(setting, n.parentTId);}; n.getPreNode = function() {return data.getPreNode(setting, n);}; n.getNextNode = function() {return data.getNextNode(setting, n);}; n.isAjaxing = false; data.fixPIdKeyValue(setting, n); }, _init = { bind: [_bindEvent], caches: [_initCache], nodes: [_initNode], proxys: [_eventProxy], roots: [_initRoot], beforeA: [], afterA: [], innerBeforeA: [], innerAfterA: [], zTreeTools: [] }, //method of operate data data = { addNodeCache: function(setting, node) { data.getCache(setting).nodes[node.tId] = node; }, addAfterA: function(afterA) { _init.afterA.push(afterA); }, addBeforeA: function(beforeA) { _init.beforeA.push(beforeA); }, addInnerAfterA: function(innerAfterA) { _init.innerAfterA.push(innerAfterA); }, addInnerBeforeA: function(innerBeforeA) { _init.innerBeforeA.push(innerBeforeA); }, addInitBind: function(bindEvent) { _init.bind.push(bindEvent); }, addInitCache: function(initCache) { _init.caches.push(initCache); }, addInitNode: function(initNode) { _init.nodes.push(initNode); }, addInitProxy: function(initProxy) { _init.proxys.push(initProxy); }, addInitRoot: function(initRoot) { _init.roots.push(initRoot); }, addNodesData: function(setting, parentNode, nodes) { var childKey = setting.data.key.children; if (!parentNode[childKey]) parentNode[childKey] = []; if (parentNode[childKey].length > 0) { parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); } parentNode.isParent = true; parentNode[childKey] = parentNode[childKey].concat(nodes); }, addSelectedNode: function(setting, node) { var root = data.getRoot(setting); if (!data.isSelectedNode(setting, node)) { root.curSelectedList.push(node); } }, addCreatedNode: function(setting, node) { if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { var root = data.getRoot(setting); root.createdNodes.push(node); } }, addZTreeTools: function(zTreeTools) { _init.zTreeTools.push(zTreeTools); }, exSetting: function(s) { $.extend(true, _setting, s); }, fixPIdKeyValue: function(setting, node) { if (setting.data.simpleData.enable) { node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; } }, getAfterA: function(setting, node, array) { for (var i=0, j=_init.afterA.length; i<j; i++) { _init.afterA[i].apply(this, arguments); } }, getBeforeA: function(setting, node, array) { for (var i=0, j=_init.beforeA.length; i<j; i++) { _init.beforeA[i].apply(this, arguments); } }, getInnerAfterA: function(setting, node, array) { for (var i=0, j=_init.innerAfterA.length; i<j; i++) { _init.innerAfterA[i].apply(this, arguments); } }, getInnerBeforeA: function(setting, node, array) { for (var i=0, j=_init.innerBeforeA.length; i<j; i++) { _init.innerBeforeA[i].apply(this, arguments); } }, getCache: function(setting) { return caches[setting.treeId]; }, getNextNode: function(setting, node) { if (!node) return null; var childKey = setting.data.key.children, p = node.parentTId ? node.getParentNode() : data.getRoot(setting); if (node.isLastNode) { return null; } else if (node.isFirstNode) { return p[childKey][1]; } else { for (var i=1, l=p[childKey].length-1; i<l; i++) { if (p[childKey][i] === node) { return p[childKey][i+1]; } } } return null; }, getNodeByParam: function(setting, nodes, key, value) { if (!nodes || !key) return null; var childKey = setting.data.key.children; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i][key] == value) { return nodes[i]; } var tmp = data.getNodeByParam(setting, nodes[i][childKey], key, value); if (tmp) return tmp; } return null; }, getNodeCache: function(setting, tId) { if (!tId) return null; var n = caches[setting.treeId].nodes[tId]; return n ? n : null; }, getNodes: function(setting) { return data.getRoot(setting)[setting.data.key.children]; }, getNodesByParam: function(setting, nodes, key, value) { if (!nodes || !key) return []; var childKey = setting.data.key.children, result = []; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i][key] == value) { result.push(nodes[i]); } result = result.concat(data.getNodesByParam(setting, nodes[i][childKey], key, value)); } return result; }, getNodesByParamFuzzy: function(setting, nodes, key, value) { if (!nodes || !key) return []; var childKey = setting.data.key.children, result = []; for (var i = 0, l = nodes.length; i < l; i++) { if (typeof nodes[i][key] == "string" && nodes[i][key].indexOf(value)>-1) { result.push(nodes[i]); } result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); } return result; }, getPreNode: function(setting, node) { if (!node) return null; var childKey = setting.data.key.children, p = node.parentTId ? node.getParentNode() : data.getRoot(setting); if (node.isFirstNode) { return null; } else if (node.isLastNode) { return p[childKey][p[childKey].length-2]; } else { for (var i=1, l=p[childKey].length-1; i<l; i++) { if (p[childKey][i] === node) { return p[childKey][i-1]; } } } return null; }, getRoot: function(setting) { return setting ? roots[setting.treeId] : null; }, getSetting: function(treeId) { return settings[treeId]; }, getSettings: function() { return settings; }, getTitleKey: function(setting) { return setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title; }, getZTreeTools: function(treeId) { var r = this.getRoot(this.getSetting(treeId)); return r ? r.treeTools : null; }, initCache: function(setting) { for (var i=0, j=_init.caches.length; i<j; i++) { _init.caches[i].apply(this, arguments); } }, initNode: function(setting, level, node, parentNode, preNode, nextNode) { for (var i=0, j=_init.nodes.length; i<j; i++) { _init.nodes[i].apply(this, arguments); } }, initRoot: function(setting) { for (var i=0, j=_init.roots.length; i<j; i++) { _init.roots[i].apply(this, arguments); } }, isSelectedNode: function(setting, node) { var root = data.getRoot(setting); for (var i=0, j=root.curSelectedList.length; i<j; i++) { if(node === root.curSelectedList[i]) return true; } return false; }, removeNodeCache: function(setting, node) { var childKey = setting.data.key.children; if (node[childKey]) { for (var i=0, l=node[childKey].length; i<l; i++) { arguments.callee(setting, node[childKey][i]); } } delete data.getCache(setting).nodes[node.tId]; }, removeSelectedNode: function(setting, node) { var root = data.getRoot(setting); for (var i=0, j=root.curSelectedList.length; i<j; i++) { if(node === root.curSelectedList[i] || !data.getNodeCache(setting, root.curSelectedList[i].tId)) { root.curSelectedList.splice(i, 1); i--;j--; } } }, setCache: function(setting, cache) { caches[setting.treeId] = cache; }, setRoot: function(setting, root) { roots[setting.treeId] = root; }, setZTreeTools: function(setting, zTreeTools) { for (var i=0, j=_init.zTreeTools.length; i<j; i++) { _init.zTreeTools[i].apply(this, arguments); } }, transformToArrayFormat: function (setting, nodes) { if (!nodes) return []; var childKey = setting.data.key.children, r = []; if (tools.isArray(nodes)) { for (var i=0, l=nodes.length; i<l; i++) { r.push(nodes[i]); if (nodes[i][childKey]) r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey])); } } else { r.push(nodes); if (nodes[childKey]) r = r.concat(data.transformToArrayFormat(setting, nodes[childKey])); } return r; }, transformTozTreeFormat: function(setting, sNodes) { var i,l, key = setting.data.simpleData.idKey, parentKey = setting.data.simpleData.pIdKey, childKey = setting.data.key.children; if (!key || key=="" || !sNodes) return []; if (tools.isArray(sNodes)) { var r = []; var tmpMap = []; for (i=0, l=sNodes.length; i<l; i++) { tmpMap[sNodes[i][key]] = sNodes[i]; } for (i=0, l=sNodes.length; i<l; i++) { if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) { if (!tmpMap[sNodes[i][parentKey]][childKey]) tmpMap[sNodes[i][parentKey]][childKey] = []; tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]); } else { r.push(sNodes[i]); } } return r; }else { return [sNodes]; } } }, //method of event proxy event = { bindEvent: function(setting) { for (var i=0, j=_init.bind.length; i<j; i++) { _init.bind[i].apply(this, arguments); } }, bindTree: function(setting) { var eventParam = { treeId: setting.treeId }, o = setting.treeObj; o.unbind('click', event.proxy); o.bind('click', eventParam, event.proxy); o.unbind('dblclick', event.proxy); o.bind('dblclick', eventParam, event.proxy); o.unbind('mouseover', event.proxy); o.bind('mouseover', eventParam, event.proxy); o.unbind('mouseout', event.proxy); o.bind('mouseout', eventParam, event.proxy); o.unbind('mousedown', event.proxy); o.bind('mousedown', eventParam, event.proxy); o.unbind('mouseup', event.proxy); o.bind('mouseup', eventParam, event.proxy); o.unbind('contextmenu', event.proxy); o.bind('contextmenu', eventParam, event.proxy); }, doProxy: function(e) { var results = []; for (var i=0, j=_init.proxys.length; i<j; i++) { var proxyResult = _init.proxys[i].apply(this, arguments); results.push(proxyResult); if (proxyResult.stop) { break; } } return results; }, proxy: function(e) { var setting = data.getSetting(e.data.treeId); if (!tools.uCanDo(setting, e)) return true; var results = event.doProxy(e), r = true, x = false; for (var i=0, l=results.length; i<l; i++) { var proxyResult = results[i]; if (proxyResult.nodeEventCallback) { x = true; r = proxyResult.nodeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; } if (proxyResult.treeEventCallback) { x = true; r = proxyResult.treeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; } } try{ if (x && $("input:focus").length == 0) { tools.noSel(setting); } } catch(e) {} return r; } }, //method of event handler handler = { onSwitchNode: function (event, node) { var setting = settings[event.data.treeId]; if (node.open) { if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true; data.getRoot(setting).expandTriggerFlag = true; view.switchNode(setting, node); } else { if (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false) return true; data.getRoot(setting).expandTriggerFlag = true; view.switchNode(setting, node); } return true; }, onClickNode: function (event, node) { var setting = settings[event.data.treeId], clickFlag = ( (setting.view.autoCancelSelected && event.ctrlKey) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && event.ctrlKey && setting.view.selectedMulti) ? 2 : 1; if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true; if (clickFlag === 0) { view.cancelPreSelectedNode(setting, node); } else { view.selectNode(setting, node, clickFlag === 2); } setting.treeObj.trigger(consts.event.CLICK, [setting.treeId, node, clickFlag]); return true; }, onZTreeMousedown: function(event, node) { var setting = settings[event.data.treeId]; if (tools.apply(setting.callback.beforeMouseDown, [setting.treeId, node], true)) { tools.apply(setting.callback.onMouseDown, [event, setting.treeId, node]); } return true; }, onZTreeMouseup: function(event, node) { var setting = settings[event.data.treeId]; if (tools.apply(setting.callback.beforeMouseUp, [setting.treeId, node], true)) { tools.apply(setting.callback.onMouseUp, [event, setting.treeId, node]); } return true; }, onZTreeDblclick: function(event, node) { var setting = settings[event.data.treeId]; if (tools.apply(setting.callback.beforeDblClick, [setting.treeId, node], true)) { tools.apply(setting.callback.onDblClick, [event, setting.treeId, node]); } return true; }, onZTreeContextmenu: function(event, node) { var setting = settings[event.data.treeId]; if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) { tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]); } return (typeof setting.callback.onRightClick) != "function"; } }, //method of tools for zTree tools = { apply: function(fun, param, defaultValue) { if ((typeof fun) == "function") { return fun.apply(zt, param?param:[]); } return defaultValue; }, canAsync: function(setting, node) { var childKey = setting.data.key.children; return (node && node.isParent && !(node.zAsync || (node[childKey] && node[childKey].length > 0))); }, clone: function (jsonObj) { var buf; if (jsonObj instanceof Array) { buf = []; var i = jsonObj.length; while (i--) { buf[i] = arguments.callee(jsonObj[i]); } return buf; }else if (typeof jsonObj == "function"){ return jsonObj; }else if (jsonObj instanceof Object){ buf = {}; for (var k in jsonObj) { buf[k] = arguments.callee(jsonObj[k]); } return buf; }else{ return jsonObj; } }, eqs: function(str1, str2) { return str1.toLowerCase() === str2.toLowerCase(); }, isArray: function(arr) { return Object.prototype.toString.apply(arr) === "[object Array]"; }, getMDom: function (setting, curDom, targetExpr) { if (!curDom) return null; while (curDom && curDom.id !== setting.treeId) { for (var i=0, l=targetExpr.length; curDom.tagName && i<l; i++) { if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) { return curDom; } } curDom = curDom.parentNode; } return null; }, noSel: function(setting) { var r = data.getRoot(setting); if (r.noSelection) { try { window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } catch(e){} } }, uCanDo: function(setting, e) { return true; } }, //method of operate ztree dom view = { addNodes: function(setting, parentNode, newNodes, isSilent) { if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { return; } if (!tools.isArray(newNodes)) { newNodes = [newNodes]; } if (setting.data.simpleData.enable) { newNodes = data.transformTozTreeFormat(setting, newNodes); } if (parentNode) { var target_switchObj = $("#" + parentNode.tId + consts.id.SWITCH), target_icoObj = $("#" + parentNode.tId + consts.id.ICON), target_ulObj = $("#" + parentNode.tId + consts.id.UL); if (!parentNode.open) { view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); parentNode.open = false; target_ulObj.css({ "display": "none" }); } data.addNodesData(setting, parentNode, newNodes); view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); if (!isSilent) { view.expandCollapseParentNode(setting, parentNode, true); } } else { data.addNodesData(setting, data.getRoot(setting), newNodes); view.createNodes(setting, 0, newNodes, null); } }, appendNodes: function(setting, level, nodes, parentNode, initFlag, openFlag) { if (!nodes) return []; var html = [], childKey = setting.data.key.children, nameKey = setting.data.key.name, titleKey = data.getTitleKey(setting); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i], tmpPNode = (parentNode) ? parentNode: data.getRoot(setting), tmpPChild = tmpPNode[childKey], isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), isLastNode = (i == (nodes.length - 1)); if (initFlag) { data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); data.addNodeCache(setting, node); } var childHtml = []; if (node[childKey] && node[childKey].length > 0) { //make child html first, because checkType childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); } if (openFlag) { var url = view.makeNodeUrl(setting, node), fontcss = view.makeNodeFontCss(setting, node), fontStyle = []; for (var f in fontcss) { fontStyle.push(f, ":", fontcss[f], ";"); } html.push("<li id='", node.tId, "' class='level", node.level,"' treenode>", "<button type='button' hidefocus='true'",(node.isParent?"":"disabled")," id='", node.tId, consts.id.SWITCH, "' title='' class='", view.makeNodeLineClass(setting, node), "' treeNode", consts.id.SWITCH,"></button>"); data.getBeforeA(setting, node, html); html.push("<a id='", node.tId, consts.id.A, "' class='level", node.level,"' treeNode", consts.id.A," onclick=\"", (node.click || ''), "\" ", ((url != null && url.length > 0) ? "href='" + url + "'" : ""), " target='",view.makeNodeTarget(node),"' style='", fontStyle.join(''), "'"); if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && node[titleKey]) {html.push("title='", node[titleKey].replace(/'/g,"&#39;").replace(/</g,'&lt;').replace(/>/g,'&gt;'),"'");} html.push(">"); data.getInnerBeforeA(setting, node, html); var name = setting.view.nameIsHTML ? node[nameKey] : node[nameKey].replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); html.push("<button type='button' hidefocus='true' id='", node.tId, consts.id.ICON, "' title='' treeNode", consts.id.ICON," class='", view.makeNodeIcoClass(setting, node), "' style='", view.makeNodeIcoStyle(setting, node), "'></button><span id='", node.tId, consts.id.SPAN, "'>",name,"</span>"); data.getInnerAfterA(setting, node, html); html.push("</a>"); data.getAfterA(setting, node, html); if (node.isParent && node.open) { view.makeUlHtml(setting, node, html, childHtml.join('')); } html.push("</li>"); data.addCreatedNode(setting, node); } } return html; }, appendParentULDom: function(setting, node) { var html = [], nObj = $("#" + node.tId), ulObj = $("#" + node.tId + consts.id.UL), childKey = setting.data.key.children, childHtml = view.appendNodes(setting, node.level+1, node[childKey], node, false, true); view.makeUlHtml(setting, node, html, childHtml.join('')); if (!nObj.get(0) && !!node.parentTId) { view.appendParentULDom(setting, node.getParentNode()); nObj = $("#" + node.tId); } if (ulObj.get(0)) { ulObj.remove(); } nObj.append(html.join('')); view.createNodeCallback(setting); }, asyncNode: function(setting, node, isSilent, callback) { var i, l; if (node && !node.isParent) { tools.apply(callback); return false; } else if (node && node.isAjaxing) { return false; } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { tools.apply(callback); return false; } if (node) { node.isAjaxing = true; var icoObj = $("#" + node.tId + consts.id.ICON); icoObj.attr({"style":"", "class":"ico_loading"}); } var isJson = (setting.async.contentType == "application/json"), tmpParam = isJson ? "{" : "", jTemp=""; for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { var pKey = setting.async.autoParam[i].split("="), spKey = pKey; if (pKey.length>1) { spKey = pKey[1]; pKey = pKey[0]; } if (isJson) { jTemp = (typeof node[pKey] == "string") ? '"' : ''; tmpParam += '"' + spKey + ('":' + jTemp + node[pKey]).replace(/'/g,'\\\'') + jTemp + ','; } else { tmpParam += spKey + ("=" + node[pKey]).replace(/&/g,'%26') + "&"; } } if (tools.isArray(setting.async.otherParam)) { for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { if (isJson) { jTemp = (typeof setting.async.otherParam[i + 1] == "string") ? '"' : ''; tmpParam += '"' + setting.async.otherParam[i] + ('":' + jTemp + setting.async.otherParam[i + 1]).replace(/'/g,'\\\'') + jTemp + ","; } else { tmpParam += setting.async.otherParam[i] + ("=" + setting.async.otherParam[i + 1]).replace(/&/g,'%26') + "&"; } } } else { for (var p in setting.async.otherParam) { if (isJson) { jTemp = (typeof setting.async.otherParam[p] == "string") ? '"' : ''; tmpParam += '"' + p + ('":' + jTemp + setting.async.otherParam[p]).replace(/'/g,'\\\'') + jTemp + ","; } else { tmpParam += p + ("=" + setting.async.otherParam[p]).replace(/&/g,'%26') + "&"; } } } if (tmpParam.length > 1) tmpParam = tmpParam.substring(0, tmpParam.length-1); if (isJson) tmpParam += "}"; $.ajax({ contentType: setting.async.contentType, type: setting.async.type, url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), data: tmpParam, dataType: setting.async.dataType, success: function(msg) { var newNodes = []; try { if (!msg || msg.length == 0) { newNodes = []; } else if (typeof msg == "string") { newNodes = eval("(" + msg + ")"); } else { newNodes = msg; } } catch(err) {} if (node) { node.isAjaxing = null; node.zAsync = true; } view.setNodeLineIcos(setting, node); if (newNodes && newNodes != "") { newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); view.addNodes(setting, node, tools.clone(newNodes), !!isSilent); } else { view.addNodes(setting, node, [], !!isSilent); } setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); tools.apply(callback); }, error: function(XMLHttpRequest, textStatus, errorThrown) { view.setNodeLineIcos(setting, node); if (node) node.isAjaxing = null; setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); } }); return true; }, cancelPreSelectedNode: function (setting, node) { var list = data.getRoot(setting).curSelectedList; for (var i=0, j=list.length-1; j>=i; j--) { if (!node || node === list[j]) { $("#" + list[j].tId + consts.id.A).removeClass(consts.node.CURSELECTED); view.setNodeName(setting, list[j]); if (node) { data.removeSelectedNode(setting, node); break; } } } if (!node) data.getRoot(setting).curSelectedList = []; }, createNodeCallback: function(setting) { if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { var root = data.getRoot(setting); while (root.createdNodes.length>0) { var node = root.createdNodes.shift(); tools.apply(setting.view.addDiyDom, [setting.treeId, node]); if (!!setting.callback.onNodeCreated) { setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); } } } }, createNodes: function(setting, level, nodes, parentNode) { if (!nodes || nodes.length == 0) return; var root = data.getRoot(setting), childKey = setting.data.key.children, openFlag = !parentNode || parentNode.open || !!$("#" + parentNode[childKey][0].tId).get(0); root.createdNodes = []; var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); if (!parentNode) { setting.treeObj.append(zTreeHtml.join('')); } else { var ulObj = $("#" + parentNode.tId + consts.id.UL); if (ulObj.get(0)) { ulObj.append(zTreeHtml.join('')); } } view.createNodeCallback(setting); }, expandCollapseNode: function(setting, node, expandFlag, animateFlag, callback) { var root = data.getRoot(setting), childKey = setting.data.key.children; if (!node) { tools.apply(callback, []); return; } if (root.expandTriggerFlag) { var _callback = callback; callback = function(){ if (_callback) _callback(); if (node.open) { setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); } else { setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); } }; root.expandTriggerFlag = false; } if (node.open == expandFlag) { tools.apply(callback, []); return; } if (!node.open && node.isParent && ((!$("#" + node.tId + consts.id.UL).get(0)) || (node[childKey] && node[childKey].length>0 && !$("#" + node[childKey][0].tId).get(0)))) { view.appendParentULDom(setting, node); } var ulObj = $("#" + node.tId + consts.id.UL), switchObj = $("#" + node.tId + consts.id.SWITCH), icoObj = $("#" + node.tId + consts.id.ICON); if (node.isParent) { node.open = !node.open; if (node.iconOpen && node.iconClose) { icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); } if (node.open) { view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); view.replaceIcoClass(node, icoObj, consts.folder.OPEN); if (animateFlag == false || setting.view.expandSpeed == "") { ulObj.show(); tools.apply(callback, []); } else { if (node[childKey] && node[childKey].length > 0) { ulObj.slideDown(setting.view.expandSpeed, callback); } else { ulObj.show(); tools.apply(callback, []); } } } else { view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); if (animateFlag == false || setting.view.expandSpeed == "") { ulObj.hide(); tools.apply(callback, []); } else { ulObj.slideUp(setting.view.expandSpeed, callback); } } } else { tools.apply(callback, []); } }, expandCollapseParentNode: function(setting, node, expandFlag, animateFlag, callback) { if (!node) return; if (!node.parentTId) { view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); return; } else { view.expandCollapseNode(setting, node, expandFlag, animateFlag); } if (node.parentTId) { view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); } }, expandCollapseSonNode: function(setting, node, expandFlag, animateFlag, callback) { var root = data.getRoot(setting), childKey = setting.data.key.children, treeNodes = (node) ? node[childKey]: root[childKey], selfAnimateSign = (node) ? false : animateFlag, expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; data.getRoot(setting).expandTriggerFlag = false; if (treeNodes) { for (var i = 0, l = treeNodes.length; i < l; i++) { if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); } } data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); }, makeNodeFontCss: function(setting, node) { var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {}; }, makeNodeIcoClass: function(setting, node) { var icoCss = ["ico"]; if (!node.isAjaxing) { icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; if (node.isParent) { icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); } else { icoCss.push(consts.folder.DOCU); } } return icoCss.join('_'); }, makeNodeIcoStyle: function(setting, node) { var icoStyle = []; if (!node.isAjaxing) { var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { icoStyle.push("width:0px;height:0px;"); } } return icoStyle.join(''); }, makeNodeLineClass: function(setting, node) { var lineClass = []; if (setting.view.showLine) { if (node.level == 0 && node.isFirstNode && node.isLastNode) { lineClass.push(consts.line.ROOT); } else if (node.level == 0 && node.isFirstNode) { lineClass.push(consts.line.ROOTS); } else if (node.isLastNode) { lineClass.push(consts.line.BOTTOM); } else { lineClass.push(consts.line.CENTER); } } else { lineClass.push(consts.line.NOLINE); } if (node.isParent) { lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); } else { lineClass.push(consts.folder.DOCU); } return view.makeNodeLineClassEx(node) + lineClass.join('_'); }, makeNodeLineClassEx: function(node) { return "level" + node.level + " switch "; }, makeNodeTarget: function(node) { return (node.target || "_blank"); }, makeNodeUrl: function(setting, node) { return node.url ? node.url : null; }, makeUlHtml: function(setting, node, html, content) { html.push("<ul id='", node.tId, consts.id.UL, "' class='level", node.level, " ", view.makeUlLineClass(setting, node), "' style='display:", (node.open ? "block": "none"),"'>"); html.push(content); html.push("</ul>"); }, makeUlLineClass: function(setting, node) { return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); }, replaceIcoClass: function(node, obj, newName) { if (!obj || node.isAjaxing) return; var tmpName = obj.attr("class"); if (tmpName == undefined) return; var tmpList = tmpName.split("_"); switch (newName) { case consts.folder.OPEN: case consts.folder.CLOSE: case consts.folder.DOCU: tmpList[tmpList.length-1] = newName; break; } obj.attr("class", tmpList.join("_")); }, replaceSwitchClass: function(node, obj, newName) { if (!obj) return; var tmpName = obj.attr("class"); if (tmpName == undefined) return; var tmpList = tmpName.split("_"); switch (newName) { case consts.line.ROOT: case consts.line.ROOTS: case consts.line.CENTER: case consts.line.BOTTOM: case consts.line.NOLINE: tmpList[0] = view.makeNodeLineClassEx(node) + newName; break; case consts.folder.OPEN: case consts.folder.CLOSE: case consts.folder.DOCU: tmpList[1] = newName; break; } obj.attr("class", tmpList.join("_")); if (newName !== consts.folder.DOCU) { obj.removeAttr("disabled"); } else { obj.attr("disabled", "disabled"); } }, selectNode: function(setting, node, addFlag) { if (!addFlag) { view.cancelPreSelectedNode(setting); } $("#" + node.tId + consts.id.A).addClass(consts.node.CURSELECTED); data.addSelectedNode(setting, node); }, setNodeFontCss: function(setting, treeNode) { var aObj = $("#" + treeNode.tId + consts.id.A), fontCss = view.makeNodeFontCss(setting, treeNode); if (fontCss) { aObj.css(fontCss); } }, setNodeLineIcos: function(setting, node) { if (!node) return; var switchObj = $("#" + node.tId + consts.id.SWITCH), ulObj = $("#" + node.tId + consts.id.UL), icoObj = $("#" + node.tId + consts.id.ICON), ulLine = view.makeUlLineClass(setting, node); if (ulLine.length==0) { ulObj.removeClass(consts.line.LINE); } else { ulObj.addClass(ulLine); } switchObj.attr("class", view.makeNodeLineClass(setting, node)); if (node.isParent) { switchObj.removeAttr("disabled"); } else { switchObj.attr("disabled", "disabled"); } icoObj.removeAttr("style"); icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); icoObj.attr("class", view.makeNodeIcoClass(setting, node)); }, setNodeName: function(setting, node) { var nameKey = setting.data.key.name, titleKey = data.getTitleKey(setting), nObj = $("#" + node.tId + consts.id.SPAN); nObj.empty(); if (setting.view.nameIsHTML) { nObj.html(node[nameKey]); } else { nObj.text(node[nameKey]); } if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && node[titleKey]) { var aObj = $("#" + node.tId + consts.id.A); aObj.attr("title", node[titleKey]); } }, setNodeTarget: function(node) { var aObj = $("#" + node.tId + consts.id.A); aObj.attr("target", view.makeNodeTarget(node)); }, setNodeUrl: function(setting, node) { var aObj = $("#" + node.tId + consts.id.A), url = view.makeNodeUrl(setting, node); if (url == null || url.length == 0) { aObj.removeAttr("href"); } else { aObj.attr("href", url); } }, switchNode: function(setting, node) { if (node.open || !tools.canAsync(setting, node)) { view.expandCollapseNode(setting, node, !node.open); } else if (setting.async.enable) { if (!view.asyncNode(setting, node)) { view.expandCollapseNode(setting, node, !node.open); return; } } else if (node) { view.expandCollapseNode(setting, node, !node.open); } } }; // zTree defind $.fn.zTree = { consts : _consts, _z : { tools: tools, view: view, event: event, data: data }, getZTreeObj: function(treeId) { var o = data.getZTreeTools(treeId); return o ? o : null; }, init: function(obj, zSetting, zNodes) { var setting = tools.clone(_setting); $.extend(true, setting, zSetting); setting.treeId = obj.attr("id"); setting.treeObj = obj; setting.treeObj.empty(); settings[setting.treeId] = setting; if ($.browser.msie && parseInt($.browser.version)<7) { setting.view.expandSpeed = ""; } data.initRoot(setting); var root = data.getRoot(setting), childKey = setting.data.key.children; zNodes = zNodes ? tools.clone(tools.isArray(zNodes)? zNodes : [zNodes]) : []; if (setting.data.simpleData.enable) { root[childKey] = data.transformTozTreeFormat(setting, zNodes); } else { root[childKey] = zNodes; } data.initCache(setting); event.bindTree(setting); event.bindEvent(setting); var zTreeTools = { setting: setting, cancelSelectedNode : function(node) { view.cancelPreSelectedNode(this.setting, node); }, expandAll : function(expandFlag) { expandFlag = !!expandFlag; view.expandCollapseSonNode(this.setting, null, expandFlag, true); return expandFlag; }, expandNode : function(node, expandFlag, sonSign, focus, callbackFlag) { if (!node || !node.isParent) return null; if (expandFlag !== true && expandFlag !== false) { expandFlag = !node.open; } callbackFlag = !!callbackFlag; if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { return null; } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { return null; } if (expandFlag && node.parentTId) { view.expandCollapseParentNode(this.setting, node.getParentNode(), expandFlag, false); } if (expandFlag === node.open && !sonSign) { return null; } data.getRoot(setting).expandTriggerFlag = callbackFlag; if (sonSign) { view.expandCollapseSonNode(this.setting, node, expandFlag, true, function() { if (focus !== false) {$("#" + node.tId + consts.id.ICON).focus().blur();} }); } else { node.open = !expandFlag; view.switchNode(this.setting, node); if (focus !== false) {$("#" + node.tId + consts.id.ICON).focus().blur();} } return expandFlag; }, getNodes : function() { return data.getNodes(this.setting); }, getNodeByParam : function(key, value, parentNode) { if (!key) return null; return data.getNodeByParam(this.setting, parentNode?parentNode[this.setting.data.key.children]:data.getNodes(this.setting), key, value); }, getNodeByTId : function(tId) { return data.getNodeCache(this.setting, tId); }, getNodesByParam : function(key, value, parentNode) { if (!key) return null; return data.getNodesByParam(this.setting, parentNode?parentNode[this.setting.data.key.children]:data.getNodes(this.setting), key, value); }, getNodesByParamFuzzy : function(key, value, parentNode) { if (!key) return null; return data.getNodesByParamFuzzy(this.setting, parentNode?parentNode[this.setting.data.key.children]:data.getNodes(this.setting), key, value); }, getNodeIndex : function(node) { if (!node) return null; var childKey = setting.data.key.children, parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(this.setting); for (var i=0, l = parentNode[childKey].length; i < l; i++) { if (parentNode[childKey][i] == node) return i; } return -1; }, getSelectedNodes : function() { var r = [], list = data.getRoot(this.setting).curSelectedList; for (var i=0, l=list.length; i<l; i++) { r.push(list[i]); } return r; }, isSelectedNode : function(node) { return data.isSelectedNode(this.setting, node); }, reAsyncChildNodes : function(parentNode, reloadType, isSilent) { if (!this.setting.async.enable) return; var isRoot = !parentNode; if (isRoot) { parentNode = data.getRoot(this.setting); } if (reloadType=="refresh") { parentNode[this.setting.data.key.children] = []; if (isRoot) { this.setting.treeObj.empty(); } else { var ulObj = $("#" + parentNode.tId + consts.id.UL); ulObj.empty(); } } view.asyncNode(this.setting, isRoot? null:parentNode, !!isSilent); }, refresh : function() { this.setting.treeObj.empty(); var root = data.getRoot(this.setting), nodes = root[this.setting.data.key.children] data.initRoot(this.setting); root[this.setting.data.key.children] = nodes data.initCache(this.setting); view.createNodes(this.setting, 0, root[this.setting.data.key.children]); }, selectNode : function(node, addFlag) { if (!node) return; if (tools.uCanDo(this.setting)) { addFlag = setting.view.selectedMulti && addFlag; if (node.parentTId) { view.expandCollapseParentNode(this.setting, node.getParentNode(), true, false, function() { $("#" + node.tId + consts.id.ICON).focus().blur(); }); } else { $("#" + node.tId + consts.id.ICON).focus().blur(); } view.selectNode(this.setting, node, addFlag); } }, transformTozTreeNodes : function(simpleNodes) { return data.transformTozTreeFormat(this.setting, simpleNodes); }, transformToArray : function(nodes) { return data.transformToArrayFormat(this.setting, nodes); }, updateNode : function(node, checkTypeFlag) { if (!node) return; var nObj = $("#" + node.tId); if (nObj.get(0) && tools.uCanDo(this.setting)) { view.setNodeName(this.setting, node); view.setNodeTarget(node); view.setNodeUrl(this.setting, node); view.setNodeLineIcos(this.setting, node); view.setNodeFontCss(this.setting, node); } } } root.treeTools = zTreeTools; data.setZTreeTools(setting, zTreeTools); if (root[childKey] && root[childKey].length > 0) { view.createNodes(setting, 0, root[childKey]); } else if (setting.async.enable && setting.async.url && setting.async.url !== '') { view.asyncNode(setting); } return zTreeTools; } }; var zt = $.fn.zTree, consts = zt.consts; })(jQuery); /* * JQuery zTree excheck 3.1 * http://code.google.com/p/jquerytree/ * * Copyright (c) 2010 Hunter.z (baby666.cn) * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2012-02-14 */ (function($){ //default consts of excheck var _consts = { event: { CHECK: "ztree_check" }, id: { CHECK: "_check" }, checkbox: { STYLE: "checkbox", DEFAULT: "chk", DISABLED: "disable", FALSE: "false", TRUE: "true", FULL: "full", PART: "part", FOCUS: "focus" }, radio: { STYLE: "radio", TYPE_ALL: "all", TYPE_LEVEL: "level" } }, //default setting of excheck _setting = { check: { enable: false, autoCheckTrigger: false, chkStyle: _consts.checkbox.STYLE, nocheckInherit: false, radioType: _consts.radio.TYPE_LEVEL, chkboxType: { "Y": "ps", "N": "ps" } }, data: { key: { checked: "checked" } }, callback: { beforeCheck:null, onCheck:null } }, //default root of excheck _initRoot = function (setting) { var r = data.getRoot(setting); r.radioCheckedList = []; }, //default cache of excheck _initCache = function(treeId) {}, //default bind event of excheck _bindEvent = function(setting) { var o = setting.treeObj, c = consts.event; o.unbind(c.CHECK); o.bind(c.CHECK, function (event, treeId, node) { tools.apply(setting.callback.onCheck, [event, treeId, node]); }); }, //default event proxy of excheck _eventProxy = function(e) { var target = e.target, setting = data.getSetting(e.data.treeId), tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null; if (tools.eqs(e.type, "mouseover")) { if (setting.check.enable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = target.parentNode.id; nodeEventType = "mouseoverCheck"; } } else if (tools.eqs(e.type, "mouseout")) { if (setting.check.enable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = target.parentNode.id; nodeEventType = "mouseoutCheck"; } } else if (tools.eqs(e.type, "click")) { if (setting.check.enable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { tId = target.parentNode.id; nodeEventType = "checkNode"; } } if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "checkNode" : nodeEventCallback = _handler.onCheckNode; break; case "mouseoverCheck" : nodeEventCallback = _handler.onMouseoverCheck; break; case "mouseoutCheck" : nodeEventCallback = _handler.onMouseoutCheck; break; } } var proxyResult = { stop: false, node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of excheck _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; var checkedKey = setting.data.key.checked; if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); n[checkedKey] = !!n[checkedKey]; n.checkedOld = n[checkedKey]; n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); n.chkDisabled = !!n.chkDisabled || (parentNode && !!parentNode.chkDisabled); if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); n.halfCheck = !!n.halfCheck; n.check_Child_State = -1; n.check_Focus = false; n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; if (isLastNode) { data.makeChkFlag(setting, parentNode); } }, //add dom for check _beforeA = function(setting, node, html) { var checkedKey = setting.data.key.checked; if (setting.check.enable) { data.makeChkFlag(setting, node); if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && node[checkedKey] ) { var r = data.getRoot(setting); r.radioCheckedList.push(node); } html.push("<button type='button' ID='", node.tId, consts.id.CHECK, "' class='", view.makeChkClass(setting, node), "' treeNode", consts.id.CHECK," onfocus='this.blur();' ",(node.nocheck === true?"style='display:none;'":""),"></button>"); } }, //update zTreeObj, add method of check _zTreeTools = function(setting, zTreeTools) { zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { var checkedKey = this.setting.data.key.checked; if (node.chkDisabled === true) return; if (checked !== true && checked !== false) { checked = !node[checkedKey]; } callbackFlag = !!callbackFlag; if (node[checkedKey] === checked && !checkTypeFlag) { return; } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { return; } if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { node[checkedKey] = checked; var checkObj = $("#" + node.tId + consts.id.CHECK); if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); view.setChkClass(this.setting, checkObj, node); view.repairParentChkClassWithSelf(this.setting, node); if (callbackFlag) { setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]); } } } zTreeTools.checkAllNodes = function(checked) { view.repairAllChk(this.setting, !!checked); } zTreeTools.getCheckedNodes = function(checked) { var childKey = this.setting.data.key.children; checked = (checked !== false); return data.getTreeCheckedNodes(this.setting, data.getRoot(setting)[childKey], checked); } zTreeTools.getChangeCheckedNodes = function() { var childKey = this.setting.data.key.children; return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(setting)[childKey]); } zTreeTools.setChkDisabled = function(node, disabled) { disabled = !!disabled; view.repairSonChkDisabled(this.setting, node, disabled); if (!disabled) view.repairParentChkDisabled(this.setting, node, disabled); } var _updateNode = zTreeTools.updateNode; zTreeTools.updateNode = function(node, checkTypeFlag) { if (_updateNode) _updateNode.apply(zTreeTools, arguments); if (!node || !this.setting.check.enable) return; var nObj = $("#" + node.tId); if (nObj.get(0) && tools.uCanDo(this.setting)) { var checkObj = $("#" + node.tId + consts.id.CHECK); if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); view.setChkClass(this.setting, checkObj, node); view.repairParentChkClassWithSelf(this.setting, node); } } }, //method of operate data _data = { getRadioCheckedList: function(setting) { var checkedList = data.getRoot(setting).radioCheckedList; for (var i=0, j=checkedList.length; i<j; i++) { if(!data.getNodeCache(setting, checkedList[i].tId)) { checkedList.splice(i, 1); i--; j--; } } return checkedList; }, getCheckStatus: function(setting, node) { if (!setting.check.enable || node.nocheck) return null; var checkedKey = setting.data.key.checked, r = { checked: node[checkedKey], half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) }; return r; }, getTreeCheckedNodes: function(setting, nodes, checked, results) { if (!nodes) return []; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked; results = !results ? [] : results; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i].nocheck !== true && nodes[i][checkedKey] == checked) { results.push(nodes[i]); } data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); } return results; }, getTreeChangeCheckedNodes: function(setting, nodes, results) { if (!nodes) return []; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked; results = !results ? [] : results; for (var i = 0, l = nodes.length; i < l; i++) { if (nodes[i].nocheck !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { results.push(nodes[i]); } data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); } return results; }, makeChkFlag: function(setting, node) { if (!node) return; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, chkFlag = -1; if (node[childKey]) { var start = false; for (var i = 0, l = node[childKey].length; i < l; i++) { var cNode = node[childKey][i]; var tmp = -1; if (setting.check.chkStyle == consts.radio.STYLE) { if (cNode.nocheck === true) { tmp = cNode.check_Child_State; } else if (cNode.halfCheck === true) { tmp = 2; } else if (cNode.nocheck !== true && cNode[checkedKey]) { tmp = 2; } else { tmp = cNode.check_Child_State > 0 ? 2:0; } if (tmp == 2) { chkFlag = 2; break; } else if (tmp == 0){ chkFlag = 0; } } else if (setting.check.chkStyle == consts.checkbox.STYLE) { if (cNode.nocheck === true) { tmp = cNode.check_Child_State; } else if (cNode.halfCheck === true) { tmp = 1; } else if (cNode.nocheck !== true && cNode[checkedKey] ) { tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; } else { tmp = (cNode.check_Child_State > 0) ? 1 : 0; } if (tmp === 1) { chkFlag = 1; break; } else if (tmp === 2 && start && tmp !== chkFlag) { chkFlag = 1; break; } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { chkFlag = 1; break; } else if (tmp > -1) { chkFlag = tmp; } if (!start) start = (cNode.nocheck !== true); } } } node.check_Child_State = chkFlag; } }, //method of event proxy _event = { }, //method of event handler _handler = { onCheckNode: function (event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkedKey = setting.data.key.checked; if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; node[checkedKey] = !node[checkedKey]; view.checkNodeRelation(setting, node); var checkObj = $("#" + node.tId + consts.id.CHECK); view.setChkClass(setting, checkObj, node); view.repairParentChkClassWithSelf(setting, node); setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]); return true; }, onMouseoverCheck: function(event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkObj = $("#" + node.tId + consts.id.CHECK); node.check_Focus = true; view.setChkClass(setting, checkObj, node); return true; }, onMouseoutCheck: function(event, node) { if (node.chkDisabled === true) return false; var setting = data.getSetting(event.data.treeId), checkObj = $("#" + node.tId + consts.id.CHECK); node.check_Focus = false; view.setChkClass(setting, checkObj, node); return true; } }, //method of tools for zTree _tools = { }, //method of operate ztree dom _view = { checkNodeRelation: function(setting, node) { var pNode, i, l, childKey = setting.data.key.children, checkedKey = setting.data.key.checked, r = consts.radio; if (setting.check.chkStyle == r.STYLE) { var checkedList = data.getRadioCheckedList(setting); if (node[checkedKey]) { if (setting.check.radioType == r.TYPE_ALL) { for (i = checkedList.length-1; i >= 0; i--) { pNode = checkedList[i]; pNode[checkedKey] = false; checkedList.splice(i, 1); view.setChkClass(setting, $("#" + pNode.tId + consts.id.CHECK), pNode); if (pNode.parentTId != node.parentTId) { view.repairParentChkClassWithSelf(setting, pNode); } } checkedList.push(node); } else { var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); for (i = 0, l = parentNode[childKey].length; i < l; i++) { pNode = parentNode[childKey][i]; if (pNode[checkedKey] && pNode != node) { pNode[checkedKey] = false; view.setChkClass(setting, $("#" + pNode.tId + consts.id.CHECK), pNode); } } } } else if (setting.check.radioType == r.TYPE_ALL) { for (i = 0, l = checkedList.length; i < l; i++) { if (node == checkedList[i]) { checkedList.splice(i, 1); break; } } } } else { if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { view.setSonNodeCheckBox(setting, node, true); } if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { view.setSonNodeCheckBox(setting, node, false); } if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { view.setParentNodeCheckBox(setting, node, true); } if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { view.setParentNodeCheckBox(setting, node, false); } } }, makeChkClass: function(setting, node) { var checkedKey = setting.data.key.checked, c = consts.checkbox, r = consts.radio, fullStyle = ""; if (node.chkDisabled === true) { fullStyle = c.DISABLED; } else if (node.halfCheck) { fullStyle = c.PART; } else if (setting.check.chkStyle == r.STYLE) { fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; } else { fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART); } var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; return c.DEFAULT + " " + chkName; }, repairAllChk: function(setting, checked) { if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { var checkedKey = setting.data.key.checked, childKey = setting.data.key.children, root = data.getRoot(setting); for (var i = 0, l = root[childKey].length; i<l ; i++) { var node = root[childKey][i]; if (node.nocheck !== true) { node[checkedKey] = checked; } view.setSonNodeCheckBox(setting, node, checked); } } }, repairChkClass: function(setting, node) { if (!node) return; data.makeChkFlag(setting, node); var checkObj = $("#" + node.tId + consts.id.CHECK); view.setChkClass(setting, checkObj, node); }, repairParentChkClass: function(setting, node) { if (!node || !node.parentTId) return; var pNode = node.getParentNode(); view.repairChkClass(setting, pNode); view.repairParentChkClass(setting, pNode); }, repairParentChkClassWithSelf: function(setting, node) { if (!node) return; var childKey = setting.data.key.children; if (node[childKey] && node[childKey].length > 0) { view.repairParentChkClass(setting, node[childKey][0]); } else { view.repairParentChkClass(setting, node); } }, repairSonChkDisabled: function(setting, node, chkDisabled) { if (!node) return; var childKey = setting.data.key.children; if (node.chkDisabled != chkDisabled) { node.chkDisabled = chkDisabled; if (node.nocheck !== true) view.repairChkClass(setting, node); } if (node[childKey]) { for (var i = 0, l = node[childKey].length; i < l; i++) { var sNode = node[childKey][i]; view.repairSonChkDisabled(setting, sNode, chkDisabled); } } }, repairParentChkDisabled: function(setting, node, chkDisabled) { if (!node) return; if (node.chkDisabled != chkDisabled) { node.chkDisabled = chkDisabled; if (node.nocheck !== true) view.repairChkClass(setting, node); } view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled); }, setChkClass: function(setting, obj, node) { if (!obj) return; if (node.nocheck === true) { obj.hide(); } else { obj.show(); } obj.removeClass(); obj.addClass(view.makeChkClass(setting, node)); }, setParentNodeCheckBox: function(setting, node, value, srcNode) { var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, checkObj = $("#" + node.tId + consts.id.CHECK); if (!srcNode) srcNode = node; data.makeChkFlag(setting, node); if (node.nocheck !== true && node.chkDisabled !== true) { node[checkedKey] = value; view.setChkClass(setting, checkObj, node); if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true) { setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]); } } if (node.parentTId) { var pSign = true; if (!value) { var pNodes = node.getParentNode()[childKey]; for (var i = 0, l = pNodes.length; i < l; i++) { if ((pNodes[i].nocheck !== true && pNodes[i][checkedKey]) || (pNodes[i].nocheck === true && pNodes[i].check_Child_State > 0)) { pSign = false; break; } } } if (pSign) { view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); } } }, setSonNodeCheckBox: function(setting, node, value, srcNode) { if (!node) return; var childKey = setting.data.key.children, checkedKey = setting.data.key.checked, checkObj = $("#" + node.tId + consts.id.CHECK); if (!srcNode) srcNode = node; var hasDisable = false; if (node[childKey]) { for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { var sNode = node[childKey][i]; view.setSonNodeCheckBox(setting, sNode, value, srcNode); if (sNode.chkDisabled === true) hasDisable = true; } } if (node != data.getRoot(setting) && node.chkDisabled !== true) { if (hasDisable && node.nocheck !== true) { data.makeChkFlag(setting, node); } if (node.nocheck !== true) { node[checkedKey] = value; if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; } else { node.check_Child_State = -1; } view.setChkClass(setting, checkObj, node); if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true) { setting.treeObj.trigger(consts.event.CHECK, [setting.treeId, node]); } } } }, _z = { tools: _tools, view: _view, event: _event, data: _data }; $.extend(true, $.fn.zTree.consts, _consts); $.extend(true, $.fn.zTree._z, _z); var zt = $.fn.zTree, tools = zt._z.tools, consts = zt.consts, view = zt._z.view, data = zt._z.data, event = zt._z.event; data.exSetting(_setting); data.addInitBind(_bindEvent); data.addInitCache(_initCache); data.addInitNode(_initNode); data.addInitProxy(_eventProxy); data.addInitRoot(_initRoot); data.addBeforeA(_beforeA); data.addZTreeTools(_zTreeTools); var _createNodes = view.createNodes; view.createNodes = function(setting, level, nodes, parentNode) { if (_createNodes) _createNodes.apply(view, arguments); if (!nodes) return; view.repairParentChkClassWithSelf(setting, parentNode); } })(jQuery); /* * JQuery zTree exedit 3.1 * http://code.google.com/p/jquerytree/ * * Copyright (c) 2010 Hunter.z (baby666.cn) * * Licensed same as jquery - MIT License * http://www.opensource.org/licenses/mit-license.php * * email: hunter.z@263.net * Date: 2012-02-14 */ (function($){ //default consts of exedit var _consts = { event: { DRAG: "ztree_drag", DROP: "ztree_drop", REMOVE: "ztree_remove", RENAME: "ztree_rename" }, id: { EDIT: "_edit", INPUT: "_input", REMOVE: "_remove" }, move: { TYPE_INNER: "inner", TYPE_PREV: "prev", TYPE_NEXT: "next" }, node: { CURSELECTED_EDIT: "curSelectedNode_Edit", TMPTARGET_TREE: "tmpTargetzTree", TMPTARGET_NODE: "tmpTargetNode" } }, //default setting of exedit _setting = { edit: { enable: false, editNameSelectAll: false, showRemoveBtn: true, showRenameBtn: true, removeTitle: "remove", renameTitle: "rename", drag: { autoExpandTrigger: false, isCopy: true, isMove: true, prev: true, next: true, inner: true, minMoveSize: 5, borderMax: 10, borderMin: -5, maxShowNodeNum: 5, autoOpenTime: 500 } }, view: { addHoverDom: null, removeHoverDom: null }, callback: { beforeDrag:null, beforeDragOpen:null, beforeDrop:null, beforeEditName:null, beforeRemove:null, beforeRename:null, onDrag:null, onDrop:null, onRemove:null, onRename:null } }, //default root of exedit _initRoot = function (setting) { var r = data.getRoot(setting); r.curEditNode = null; r.curEditInput = null; r.curHoverNode = null; r.dragFlag = 0; r.dragNodeShowBefore = []; r.dragMaskList = new Array(); r.showHoverDom = true; }, //default cache of exedit _initCache = function(treeId) {}, //default bind event of exedit _bindEvent = function(setting) { var o = setting.treeObj; var c = consts.event; o.unbind(c.RENAME); o.bind(c.RENAME, function (event, treeId, treeNode) { tools.apply(setting.callback.onRename, [event, treeId, treeNode]); }); o.unbind(c.REMOVE); o.bind(c.REMOVE, function (event, treeId, treeNode) { tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); }); o.unbind(c.DRAG); o.bind(c.DRAG, function (event, treeId, treeNodes) { tools.apply(setting.callback.onDrag, [event, treeId, treeNodes]); }); o.unbind(c.DROP); o.bind(c.DROP, function (event, treeId, treeNodes, targetNode, moveType) { tools.apply(setting.callback.onDrop, [event, treeId, treeNodes, targetNode, moveType]); }); }, //default event proxy of exedit _eventProxy = function(e) { var target = e.target, setting = data.getSetting(e.data.treeId), relatedTarget = e.relatedTarget, tId = "", node = null, nodeEventType = "", treeEventType = "", nodeEventCallback = null, treeEventCallback = null, tmp = null; if (tools.eqs(e.type, "mouseover")) { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tmp.parentNode.id; nodeEventType = "hoverOverNode"; } } else if (tools.eqs(e.type, "mouseout")) { tmp = tools.getMDom(setting, relatedTarget, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (!tmp) { tId = "remove"; nodeEventType = "hoverOutNode"; } } else if (tools.eqs(e.type, "mousedown")) { tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); if (tmp) { tId = tmp.parentNode.id; nodeEventType = "mousedownNode"; } } if (tId.length>0) { node = data.getNodeCache(setting, tId); switch (nodeEventType) { case "mousedownNode" : nodeEventCallback = _handler.onMousedownNode; break; case "hoverOverNode" : nodeEventCallback = _handler.onHoverOverNode; break; case "hoverOutNode" : nodeEventCallback = _handler.onHoverOutNode; break; } } var proxyResult = { stop: false, node: node, nodeEventType: nodeEventType, nodeEventCallback: nodeEventCallback, treeEventType: treeEventType, treeEventCallback: treeEventCallback }; return proxyResult }, //default init node of exedit _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { if (!n) return; n.isHover = false; n.editNameFlag = false; }, //update zTreeObj, add method of edit _zTreeTools = function(setting, zTreeTools) { zTreeTools.addNodes = function(parentNode, newNodes, isSilent) { if (!newNodes) return null; if (!parentNode) parentNode = null; if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; var xNewNodes = tools.clone(tools.isArray(newNodes)? newNodes: [newNodes]); function addCallback() { view.addNodes(setting, parentNode, xNewNodes, (isSilent==true)); } if (setting.async.enable && tools.canAsync(setting, parentNode)) { view.asyncNode(setting, parentNode, isSilent, addCallback); } else { addCallback(); } return xNewNodes; } zTreeTools.cancelEditName = function(newName) { var root = data.getRoot(setting), nameKey = setting.data.key.name, node = root.curEditNode; if (!root.curEditNode) return; view.cancelCurEditNode(setting, newName?newName:node[nameKey]); } zTreeTools.copyNode = function(targetNode, node, moveType, isSilent) { if (!node) return null; if (targetNode && !targetNode.isParent && setting.data.keep.leaf && moveType === consts.move.TYPE_INNER) return null; var newNode = tools.clone(node); if (!targetNode) { targetNode = null; moveType = consts.move.TYPE_INNER; } if (moveType == consts.move.TYPE_INNER) { function copyCallback() { view.addNodes(setting, targetNode, [newNode], isSilent); } if (setting.async.enable && tools.canAsync(setting, targetNode)) { view.asyncNode(setting, targetNode, isSilent, copyCallback); } else { copyCallback(); } } else { view.addNodes(setting, targetNode.parentNode, [newNode], isSilent); view.moveNode(setting, targetNode, newNode, moveType, false, isSilent); } return newNode; } zTreeTools.editName = function(node) { if (!node || !node.tId || node !== data.getNodeCache(setting, node.tId)) return; if (node.parentTId) view.expandCollapseParentNode(setting, node.getParentNode(), true); view.editNode(setting, node) } zTreeTools.moveNode = function(targetNode, node, moveType, isSilent) { if (!node) return node; if (targetNode && !targetNode.isParent && setting.data.keep.leaf && moveType === consts.move.TYPE_INNER) { return null; } else if (targetNode && ((node.parentTId == targetNode.tId && moveType == consts.move.TYPE_INNER) || $("#" + node.tId).find("#" + targetNode.tId).length > 0)) { return null; } else if (!targetNode) { targetNode = null; } function moveCallback() { view.moveNode(setting, targetNode, node, moveType, false, isSilent); } if (setting.async.enable && tools.canAsync(setting, targetNode)) { view.asyncNode(setting, targetNode, isSilent, moveCallback); } else { moveCallback(); } return node; } zTreeTools.removeNode = function(node, callbackFlag) { if (!node) return; callbackFlag = !!callbackFlag; if (callbackFlag && tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return; view.removeNode(setting, node); if (callbackFlag) { this.setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]); } } zTreeTools.removeChildNodes = function(node) { if (!node) return null; var childKey = setting.data.key.children, nodes = node[childKey]; view.removeChildNodes(setting, node); return nodes ? nodes : null; } zTreeTools.setEditable = function(editable) { setting.edit.enable = editable; return this.refresh(); } }, //method of operate data _data = { setSonNodeLevel: function(setting, parentNode, node) { if (!node) return; var childKey = setting.data.key.children; node.level = (parentNode)? parentNode.level + 1 : 0; if (!node[childKey]) return; for (var i = 0, l = node[childKey].length; i < l; i++) { if (node[childKey][i]) data.setSonNodeLevel(setting, node, node[childKey][i]); } } }, //method of event proxy _event = { }, //method of event handler _handler = { onHoverOverNode: function(event, node) { var setting = data.getSetting(event.data.treeId), root = data.getRoot(setting); if (root.curHoverNode != node) { _handler.onHoverOutNode(event); } root.curHoverNode = node; view.addHoverDom(setting, node); }, onHoverOutNode: function(event, node) { var setting = data.getSetting(event.data.treeId), root = data.getRoot(setting); if (root.curHoverNode && !data.isSelectedNode(setting, root.curHoverNode)) { view.removeTreeDom(setting, root.curHoverNode); root.curHoverNode = null; } }, onMousedownNode: function(eventMouseDown, _node) { var i,l, setting = data.getSetting(eventMouseDown.data.treeId), root = data.getRoot(setting); //right click can't drag & drop if (eventMouseDown.button == 2 || !setting.edit.enable || (!setting.edit.drag.isCopy && !setting.edit.drag.isMove)) return true; //input of edit node name can't drag & drop var target = eventMouseDown.target, _nodes = data.getRoot(setting).curSelectedList, nodes = []; if (!data.isSelectedNode(setting, _node)) { nodes = [_node]; } else { for (i=0, l=_nodes.length; i<l; i++) { if (_nodes[i].editNameFlag && tools.eqs(target.tagName, "input") && target.getAttribute("treeNode"+consts.id.INPUT) !== null) { return true; } nodes.push(_nodes[i]); if (nodes[0].parentTId !== _nodes[i].parentTId) { nodes = [_node]; break; } } } view.editNodeBlur = true; view.cancelCurEditNode(setting, null, true); var doc = $(document), curNode, tmpArrow, tmpTarget, isOtherTree = false, targetSetting = setting, preNode, nextNode, preTmpTargetNodeId = null, preTmpMoveType = null, tmpTargetNodeId = null, moveType = consts.move.TYPE_INNER, mouseDownX = eventMouseDown.clientX, mouseDownY = eventMouseDown.clientY, startTime = (new Date()).getTime(); if (tools.uCanDo(setting)) { doc.bind("mousemove", _docMouseMove); } function _docMouseMove(event) { //avoid start drag after click node if (root.dragFlag == 0 && Math.abs(mouseDownX - event.clientX) < setting.edit.drag.minMoveSize && Math.abs(mouseDownY - event.clientY) < setting.edit.drag.minMoveSize) { return true; } var i, l, tmpNode, tmpDom, tmpNodes, childKey = setting.data.key.children; tools.noSel(setting); $("body").css("cursor", "pointer"); if (root.dragFlag == 0) { if (tools.apply(setting.callback.beforeDrag, [setting.treeId, nodes], true) == false) { _docMouseUp(event); return true; } for (i=0, l=nodes.length; i<l; i++) { if (i==0) { root.dragNodeShowBefore = []; } tmpNode = nodes[i]; if (tmpNode.isParent && tmpNode.open) { view.expandCollapseNode(setting, tmpNode, !tmpNode.open); root.dragNodeShowBefore[tmpNode.tId] = true; } else { root.dragNodeShowBefore[tmpNode.tId] = false; } } root.dragFlag = 1; root.showHoverDom = false; tools.showIfameMask(setting, true); //sort var isOrder = true, lastIndex = -1; if (nodes.length>1) { var pNodes = nodes[0].parentTId ? nodes[0].getParentNode()[childKey] : data.getNodes(setting); tmpNodes = []; for (i=0, l=pNodes.length; i<l; i++) { if (root.dragNodeShowBefore[pNodes[i].tId] !== undefined) { if (isOrder && lastIndex > -1 && (lastIndex+1) !== i) { isOrder = false; } tmpNodes.push(pNodes[i]); lastIndex = i; } if (nodes.length === tmpNodes.length) { nodes = tmpNodes; break; } } } if (isOrder) { preNode = nodes[0].getPreNode(); nextNode = nodes[nodes.length-1].getNextNode(); } //set node in selected curNode = $("<ul class='zTreeDragUL'></ul>"); for (i=0, l=nodes.length; i<l; i++) { tmpNode = nodes[i]; tmpNode.editNameFlag = false; view.selectNode(setting, tmpNode, i>0); view.removeTreeDom(setting, tmpNode); tmpDom = $("<li id='"+ tmpNode.tId +"_tmp'></li>"); tmpDom.append($("#" + tmpNode.tId + consts.id.A).clone()); tmpDom.css("padding", "0"); tmpDom.children("#" + tmpNode.tId + consts.id.A).removeClass(consts.node.CURSELECTED); curNode.append(tmpDom); if (i == setting.edit.drag.maxShowNodeNum-1) { tmpDom = $("<li id='"+ tmpNode.tId +"_moretmp'><a> ... </a></li>"); curNode.append(tmpDom); break; } } curNode.attr("id", nodes[0].tId + consts.id.UL + "_tmp"); curNode.addClass(setting.treeObj.attr("class")); curNode.appendTo("body"); tmpArrow = $("<button class='tmpzTreeMove_arrow'></button>"); tmpArrow.attr("id", "zTreeMove_arrow_tmp"); tmpArrow.appendTo("body"); setting.treeObj.trigger(consts.event.DRAG, [setting.treeId, nodes]); } if (root.dragFlag == 1 && tmpArrow.attr("id") != event.target.id) { if (tmpTarget) { tmpTarget.removeClass(consts.node.TMPTARGET_TREE); if (tmpTargetNodeId) $("#" + tmpTargetNodeId + consts.id.A, tmpTarget).removeClass(consts.node.TMPTARGET_NODE); } tmpTarget = null; tmpTargetNodeId = null; //judge drag & drop in multi ztree isOtherTree = false; targetSetting = setting; var settings = data.getSettings(); for (var s in settings) { if (settings[s].treeId && settings[s].edit.enable && settings[s].treeId != setting.treeId && (event.target.id == settings[s].treeId || $(event.target).parents("#" + settings[s].treeId).length>0)) { isOtherTree = true; targetSetting = settings[s]; } } var docScrollTop = doc.scrollTop(), docScrollLeft = doc.scrollLeft(), treeOffset = targetSetting.treeObj.offset(), scrollHeight = targetSetting.treeObj.get(0).scrollHeight, scrollWidth = targetSetting.treeObj.get(0).scrollWidth, dTop = (event.clientY + docScrollTop - treeOffset.top), dBottom = (targetSetting.treeObj.height() + treeOffset.top - event.clientY - docScrollTop), dLeft = (event.clientX + docScrollLeft - treeOffset.left), dRight = (targetSetting.treeObj.width() + treeOffset.left - event.clientX - docScrollLeft), isTop = (dTop < setting.edit.drag.borderMax && dTop > setting.edit.drag.borderMin), isBottom = (dBottom < setting.edit.drag.borderMax && dBottom > setting.edit.drag.borderMin), isLeft = (dLeft < setting.edit.drag.borderMax && dLeft > setting.edit.drag.borderMin), isRight = (dRight < setting.edit.drag.borderMax && dRight > setting.edit.drag.borderMin), isTreeInner = dTop > setting.edit.drag.borderMin && dBottom > setting.edit.drag.borderMin && dLeft > setting.edit.drag.borderMin && dRight > setting.edit.drag.borderMin, isTreeTop = (isTop && targetSetting.treeObj.scrollTop() <= 0), isTreeBottom = (isBottom && (targetSetting.treeObj.scrollTop() + targetSetting.treeObj.height()+10) >= scrollHeight), isTreeLeft = (isLeft && targetSetting.treeObj.scrollLeft() <= 0), isTreeRight = (isRight && (targetSetting.treeObj.scrollLeft() + targetSetting.treeObj.width()+10) >= scrollWidth); if (event.target.id && targetSetting.treeObj.find("#" + event.target.id).length > 0) { //get node <li> dom var targetObj = event.target; while (targetObj && targetObj.tagName && !tools.eqs(targetObj.tagName, "li") && targetObj.id != targetSetting.treeId) { targetObj = targetObj.parentNode; } var canMove = true; //don't move to self or children of self for (i=0, l=nodes.length; i<l; i++) { tmpNode = nodes[i]; if (targetObj.id === tmpNode.tId) { canMove = false; break; } else if ($("#" + tmpNode.tId).find("#" + targetObj.id).length > 0) { canMove = false; break; } } if (canMove) { if (event.target.id && (event.target.id == (targetObj.id + consts.id.A) || $(event.target).parents("#" + targetObj.id + consts.id.A).length > 0)) { tmpTarget = $(targetObj); tmpTargetNodeId = targetObj.id; } } } //the mouse must be in zTree tmpNode = nodes[0]; if (isTreeInner && (event.target.id == targetSetting.treeId || $(event.target).parents("#" + targetSetting.treeId).length>0)) { //judge mouse move in root of ztree if (!tmpTarget && (event.target.id == targetSetting.treeId || isTreeTop || isTreeBottom || isTreeLeft || isTreeRight) && (isOtherTree || (!isOtherTree && tmpNode.parentTId))) { tmpTarget = targetSetting.treeObj; } //auto scroll top if (isTop) { targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()-10); } else if (isBottom) { targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()+10); } if (isLeft) { targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()-10); } else if (isRight) { targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+10); } //auto scroll left if (tmpTarget && tmpTarget != targetSetting.treeObj && tmpTarget.offset().left < targetSetting.treeObj.offset().left) { targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+ tmpTarget.offset().left - targetSetting.treeObj.offset().left); } } curNode.css({ "top": (event.clientY + docScrollTop + 3) + "px", "left": (event.clientX + docScrollLeft + 3) + "px" }); var dX = 0; var dY = 0; if (tmpTarget && tmpTarget.attr("id")!=targetSetting.treeId) { var tmpTargetNode = tmpTargetNodeId == null ? null: data.getNodeCache(targetSetting, tmpTargetNodeId), isCopy = (event.ctrlKey && setting.edit.drag.isMove && setting.edit.drag.isCopy) || (!setting.edit.drag.isMove && setting.edit.drag.isCopy), isPrev = !!(preNode && tmpTargetNodeId === preNode.tId), isNext = !!(nextNode && tmpTargetNodeId === nextNode.tId), isInner = (tmpNode.parentTId && tmpNode.parentTId == tmpTargetNodeId), canPrev = (isCopy || !isNext) && tools.apply(targetSetting.edit.drag.prev, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.prev), canNext = (isCopy || !isPrev) && tools.apply(targetSetting.edit.drag.next, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.next), canInner = (isCopy || !isInner) && !(targetSetting.data.keep.leaf && !tmpTargetNode.isParent) && tools.apply(targetSetting.edit.drag.inner, [targetSetting.treeId, nodes, tmpTargetNode], !!targetSetting.edit.drag.inner); if (!canPrev && !canNext && !canInner) { tmpTarget = null; tmpTargetNodeId = ""; moveType = consts.move.TYPE_INNER; tmpArrow.css({ "display":"none" }); if (window.zTreeMoveTimer) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null } } else { var tmpTargetA = $("#" + tmpTargetNodeId + consts.id.A, tmpTarget); tmpTargetA.addClass(consts.node.TMPTARGET_NODE); var prevPercent = canPrev ? (canInner ? 0.25 : (canNext ? 0.5 : 1) ) : -1, nextPercent = canNext ? (canInner ? 0.75 : (canPrev ? 0.5 : 0) ) : -1, dY_percent = (event.clientY + docScrollTop - tmpTargetA.offset().top)/tmpTargetA.height(); if ((prevPercent==1 ||dY_percent<=prevPercent && dY_percent>=-.2) && canPrev) { dX = 1 - tmpArrow.width(); dY = 0 - tmpArrow.height()/2; moveType = consts.move.TYPE_PREV; } else if ((nextPercent==0 || dY_percent>=nextPercent && dY_percent<=1.2) && canNext) { dX = 1 - tmpArrow.width(); dY = tmpTargetA.height() - tmpArrow.height()/2; moveType = consts.move.TYPE_NEXT; }else { dX = 5 - tmpArrow.width(); dY = 0; moveType = consts.move.TYPE_INNER; } tmpArrow.css({ "display":"block", "top": (tmpTargetA.offset().top + dY) + "px", "left": (tmpTargetA.offset().left + dX) + "px" }); if (preTmpTargetNodeId != tmpTargetNodeId || preTmpMoveType != moveType) { startTime = (new Date()).getTime(); } if (tmpTargetNode && tmpTargetNode.isParent && moveType == consts.move.TYPE_INNER) { var startTimer = true; if (window.zTreeMoveTimer && window.zTreeMoveTargetNodeTId !== tmpTargetNode.tId) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null; } else if (window.zTreeMoveTimer && window.zTreeMoveTargetNodeTId === tmpTargetNode.tId) { startTimer = false; } if (startTimer) { window.zTreeMoveTimer = setTimeout(function() { if (moveType != consts.move.TYPE_INNER) return; if (tmpTargetNode && tmpTargetNode.isParent && !tmpTargetNode.open && (new Date()).getTime() - startTime > targetSetting.edit.drag.autoOpenTime && tools.apply(targetSetting.callback.beforeDragOpen, [targetSetting.treeId, tmpTargetNode], true)) { view.switchNode(targetSetting, tmpTargetNode); if (targetSetting.edit.drag.autoExpandTrigger) { targetSetting.treeObj.trigger(consts.event.EXPAND, [targetSetting.treeId, tmpTargetNode]); } } }, targetSetting.edit.drag.autoOpenTime+50); window.zTreeMoveTargetNodeTId = tmpTargetNode.tId; } } } } else { moveType = consts.move.TYPE_INNER; if (tmpTarget && tools.apply(targetSetting.edit.drag.inner, [targetSetting.treeId, nodes, null], !!targetSetting.edit.drag.inner)) { tmpTarget.addClass(consts.node.TMPTARGET_TREE); } else { tmpTarget = null; } tmpArrow.css({ "display":"none" }); if (window.zTreeMoveTimer) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null; } } preTmpTargetNodeId = tmpTargetNodeId; preTmpMoveType = moveType; } return false; } doc.bind("mouseup", _docMouseUp); function _docMouseUp(event) { if (window.zTreeMoveTimer) { clearTimeout(window.zTreeMoveTimer); window.zTreeMoveTargetNodeTId = null; } preTmpTargetNodeId = null; preTmpMoveType = null; doc.unbind("mousemove", _docMouseMove); doc.unbind("mouseup", _docMouseUp); doc.unbind("selectstart", _docSelect); $("body").css("cursor", "auto"); if (tmpTarget) { tmpTarget.removeClass(consts.node.TMPTARGET_TREE); if (tmpTargetNodeId) $("#" + tmpTargetNodeId + consts.id.A, tmpTarget).removeClass(consts.node.TMPTARGET_NODE); } tools.showIfameMask(setting, false); root.showHoverDom = true; if (root.dragFlag == 0) return; root.dragFlag = 0; var i, l, tmpNode, childKey = setting.data.key.children; for (i=0, l=nodes.length; i<l; i++) { tmpNode = nodes[i]; if (tmpNode.isParent && root.dragNodeShowBefore[tmpNode.tId] && !tmpNode.open) { view.expandCollapseNode(setting, tmpNode, !tmpNode.open); delete root.dragNodeShowBefore[tmpNode.tId]; } } if (curNode) curNode.remove(); if (tmpArrow) tmpArrow.remove(); var isCopy = (event.ctrlKey && setting.edit.drag.isMove && setting.edit.drag.isCopy) || (!setting.edit.drag.isMove && setting.edit.drag.isCopy); if (!isCopy && tmpTarget && tmpTargetNodeId && nodes[0].parentTId && tmpTargetNodeId==nodes[0].parentTId && moveType == consts.move.TYPE_INNER) { tmpTarget = null; } if (tmpTarget) { var dragTargetNode = tmpTargetNodeId == null ? null: data.getNodeCache(targetSetting, tmpTargetNodeId); if (tools.apply(setting.callback.beforeDrop, [targetSetting.treeId, nodes, dragTargetNode, moveType], true) == false) return; var newNodes = isCopy ? tools.clone(nodes) : nodes; function dropCallback() { if (isOtherTree) { if (!isCopy) { for(var i=0, l=nodes.length; i<l; i++) { view.removeNode(setting, nodes[i]); } } if (moveType == consts.move.TYPE_INNER) { view.addNodes(targetSetting, dragTargetNode, newNodes); } else { view.addNodes(targetSetting, dragTargetNode.getParentNode(), newNodes); if (moveType == consts.move.TYPE_PREV) { for (i=0, l=newNodes.length; i<l; i++) { view.moveNode(targetSetting, dragTargetNode, newNodes[i], moveType, false); } } else { for (i=-1, l=newNodes.length-1; i<l; l--) { view.moveNode(targetSetting, dragTargetNode, newNodes[l], moveType, false); } } } } else { if (isCopy && moveType == consts.move.TYPE_INNER) { view.addNodes(targetSetting, dragTargetNode, newNodes); } else { if (isCopy) { view.addNodes(targetSetting, dragTargetNode.getParentNode(), newNodes); } if (moveType == consts.move.TYPE_PREV) { for (i=0, l=newNodes.length; i<l; i++) { view.moveNode(targetSetting, dragTargetNode, newNodes[i], moveType, false); } } else { for (i=-1, l=newNodes.length-1; i<l; l--) { view.moveNode(targetSetting, dragTargetNode, newNodes[l], moveType, false); } } } } for (i=0, l=newNodes.length; i<l; i++) { view.selectNode(targetSetting, newNodes[i], i>0); } $("#" + newNodes[0].tId + consts.id.ICON).focus().blur(); } if (moveType == consts.move.TYPE_INNER && tools.canAsync(targetSetting, dragTargetNode)) { view.asyncNode(targetSetting, dragTargetNode, false, dropCallback); } else { dropCallback(); } setting.treeObj.trigger(consts.event.DROP, [targetSetting.treeId, newNodes, dragTargetNode, moveType]); } else { for (i=0, l=nodes.length; i<l; i++) { view.selectNode(targetSetting, nodes[i], i>0); } setting.treeObj.trigger(consts.event.DROP, [setting.treeId, null, null, null]); } } doc.bind("selectstart", _docSelect); function _docSelect() { return false; } //Avoid FireFox's Bug //If zTree Div CSS set 'overflow', so drag node outside of zTree, and event.target is error. if(eventMouseDown.preventDefault) { eventMouseDown.preventDefault(); } return true; } }, //method of tools for zTree _tools = { getAbs: function (obj) { var oRect = obj.getBoundingClientRect(); return [oRect.left,oRect.top] }, inputFocus: function(inputObj) { if (inputObj.get(0)) { inputObj.focus(); tools.setCursorPosition(inputObj.get(0), inputObj.val().length); } }, inputSelect: function(inputObj) { if (inputObj.get(0)) { inputObj.focus(); inputObj.select(); } }, setCursorPosition: function(obj, pos){ if(obj.setSelectionRange) { obj.focus(); obj.setSelectionRange(pos,pos); } else if (obj.createTextRange) { var range = obj.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, showIfameMask: function(setting, showSign) { var root = data.getRoot(setting); //clear full mask while (root.dragMaskList.length > 0) { root.dragMaskList[0].remove(); root.dragMaskList.shift(); } if (showSign) { //show mask var iframeList = $("iframe"); for (var i = 0, l = iframeList.length; i < l; i++) { var obj = iframeList.get(i), r = tools.getAbs(obj), dragMask = $("<div id='zTreeMask_" + i + "' class='zTreeMask' style='background-color:yellow;opacity: 0.3;filter: alpha(opacity=30); top:" + r[1] + "px; left:" + r[0] + "px; width:" + obj.offsetWidth + "px; height:" + obj.offsetHeight + "px;'></div>"); dragMask.appendTo("body"); root.dragMaskList.push(dragMask); } } } }, //method of operate ztree dom _view = { addEditBtn: function(setting, node) { if (node.editNameFlag || $("#" + node.tId + consts.id.EDIT).length > 0) { return; } if (!tools.apply(setting.edit.showRenameBtn, [setting.treeId, node], setting.edit.showRenameBtn)) { return; } var aObj = $("#" + node.tId + consts.id.A), editStr = "<button type='button' class='edit' id='" + node.tId + consts.id.EDIT + "' title='"+tools.apply(setting.edit.renameTitle, [setting.treeId, node], setting.edit.renameTitle)+"' treeNode"+consts.id.EDIT+" onfocus='this.blur();' style='display:none;'></button>"; aObj.append(editStr); $("#" + node.tId + consts.id.EDIT).bind('click', function() { if (!tools.uCanDo(setting) || tools.apply(setting.callback.beforeEditName, [setting.treeId, node], true) == false) return true; view.editNode(setting, node); return false; } ).show(); }, addRemoveBtn: function(setting, node) { if (node.editNameFlag || $("#" + node.tId + consts.id.REMOVE).length > 0) { return; } if (!tools.apply(setting.edit.showRemoveBtn, [setting.treeId, node], setting.edit.showRemoveBtn)) { return; } var aObj = $("#" + node.tId + consts.id.A), removeStr = "<button type='button' class='remove' id='" + node.tId + consts.id.REMOVE + "' title='"+tools.apply(setting.edit.removeTitle, [setting.treeId, node], setting.edit.removeTitle)+"' treeNode"+consts.id.REMOVE+" onfocus='this.blur();' style='display:none;'></button>"; aObj.append(removeStr); $("#" + node.tId + consts.id.REMOVE).bind('click', function() { if (!tools.uCanDo(setting) || tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return true; view.removeNode(setting, node); setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]); return false; } ).bind('mousedown', function(eventMouseDown) { return true; } ).show(); }, addHoverDom: function(setting, node) { if (data.getRoot(setting).showHoverDom) { node.isHover = true; if (setting.edit.enable) { view.addEditBtn(setting, node); view.addRemoveBtn(setting, node); } tools.apply(setting.view.addHoverDom, [setting.treeId, node]); } }, cancelCurEditNode: function (setting, forceName, isKey) { var root = data.getRoot(setting), nameKey = setting.data.key.name, node = root.curEditNode; if (node) { var inputObj = root.curEditInput; var newName = forceName ? forceName:inputObj.val(); if (!forceName && tools.apply(setting.callback.beforeRename, [setting.treeId, node, newName], true) === false) { node.editNameFlag = true; return false; } else { node[nameKey] = newName ? newName:inputObj.val(); if (!forceName) { setting.treeObj.trigger(consts.event.RENAME, [setting.treeId, node]); } } var aObj = $("#" + node.tId + consts.id.A); aObj.removeClass(consts.node.CURSELECTED_EDIT); inputObj.unbind(); view.setNodeName(setting, node); node.editNameFlag = false; root.curEditNode = null; root.curEditInput = null; view.selectNode(setting, node, false); } root.noSelection = true; return true; }, editNode: function(setting, node) { var root = data.getRoot(setting); view.editNodeBlur = false; if (data.isSelectedNode(setting, node) && root.curEditNode == node && node.editNameFlag) { setTimeout(function() {tools.inputFocus(root.curEditInput);}, 0); return; } var nameKey = setting.data.key.name; node.editNameFlag = true; view.removeTreeDom(setting, node); view.cancelCurEditNode(setting); view.selectNode(setting, node, false); $("#" + node.tId + consts.id.SPAN).html("<input type=text class='rename' id='" + node.tId + consts.id.INPUT + "' treeNode" + consts.id.INPUT + " >"); var inputObj = $("#" + node.tId + consts.id.INPUT); inputObj.attr("value", node[nameKey]); if (setting.edit.editNameSelectAll) { tools.inputSelect(inputObj); } else { tools.inputFocus(inputObj); } inputObj.bind('blur', function(event) { if (!view.editNodeBlur) { view.cancelCurEditNode(setting); } }).bind('keydown', function(event) { if (event.keyCode=="13") { view.editNodeBlur = true; view.cancelCurEditNode(setting, null, true); } else if (event.keyCode=="27") { view.cancelCurEditNode(setting, node[nameKey]); } }).bind('click', function(event) { return false; }).bind('dblclick', function(event) { return false; }); $("#" + node.tId + consts.id.A).addClass(consts.node.CURSELECTED_EDIT); root.curEditInput = inputObj; root.noSelection = false; root.curEditNode = node; }, moveNode: function(setting, targetNode, node, moveType, animateFlag, isSilent) { var root = data.getRoot(setting), childKey = setting.data.key.children; if (targetNode == node) return; if (setting.data.keep.leaf && targetNode && !targetNode.isParent && moveType == consts.move.TYPE_INNER) return; var oldParentNode = (node.parentTId ? node.getParentNode(): root), targetNodeIsRoot = (targetNode === null || targetNode == root); if (targetNodeIsRoot && targetNode === null) targetNode = root; if (targetNodeIsRoot) moveType = consts.move.TYPE_INNER; var targetParentNode = (targetNode.parentTId ? targetNode.getParentNode() : root); if (moveType != consts.move.TYPE_PREV && moveType != consts.move.TYPE_NEXT) { moveType = consts.move.TYPE_INNER; } //move node Dom var targetObj, target_ulObj; if (targetNodeIsRoot) { targetObj = setting.treeObj; target_ulObj = targetObj; } else if (!isSilent) { if (moveType == consts.move.TYPE_INNER) { view.expandCollapseNode(setting, targetNode, true, false); } else { view.expandCollapseNode(setting, targetNode.getParentNode(), true, false); } targetObj = $("#" + targetNode.tId); target_ulObj = $("#" + targetNode.tId + consts.id.UL); } var nodeDom = $("#" + node.tId).remove(); if (target_ulObj && moveType == consts.move.TYPE_INNER) { target_ulObj.append(nodeDom); } else if (targetObj && moveType == consts.move.TYPE_PREV) { targetObj.before(nodeDom); } else if (targetObj && moveType == consts.move.TYPE_NEXT) { targetObj.after(nodeDom); } //repair the data after move var i,l, tmpSrcIndex = -1, tmpTargetIndex = 0, oldNeighbor = null, newNeighbor = null, oldLevel = node.level; if (node.isFirstNode) { tmpSrcIndex = 0; if (oldParentNode[childKey].length > 1 ) { oldNeighbor = oldParentNode[childKey][1]; oldNeighbor.isFirstNode = true; } } else if (node.isLastNode) { tmpSrcIndex = oldParentNode[childKey].length -1; oldNeighbor = oldParentNode[childKey][tmpSrcIndex - 1]; oldNeighbor.isLastNode = true; } else { for (i = 0, l = oldParentNode[childKey].length; i < l; i++) { if (oldParentNode[childKey][i].tId == node.tId) { tmpSrcIndex = i; break; } } } if (tmpSrcIndex >= 0) { oldParentNode[childKey].splice(tmpSrcIndex, 1); } if (moveType != consts.move.TYPE_INNER) { for (i = 0, l = targetParentNode[childKey].length; i < l; i++) { if (targetParentNode[childKey][i].tId == targetNode.tId) tmpTargetIndex = i; } } if (moveType == consts.move.TYPE_INNER) { if (targetNodeIsRoot) { //parentTId of root node is null node.parentTId = null; } else { targetNode.isParent = true; targetNode.open = false; node.parentTId = targetNode.tId; } if (!targetNode[childKey]) targetNode[childKey] = new Array(); if (targetNode[childKey].length > 0) { newNeighbor = targetNode[childKey][targetNode[childKey].length - 1]; newNeighbor.isLastNode = false; } targetNode[childKey].splice(targetNode[childKey].length, 0, node); node.isLastNode = true; node.isFirstNode = (targetNode[childKey].length == 1); } else if (targetNode.isFirstNode && moveType == consts.move.TYPE_PREV) { targetParentNode[childKey].splice(tmpTargetIndex, 0, node); newNeighbor = targetNode; newNeighbor.isFirstNode = false; node.parentTId = targetNode.parentTId; node.isFirstNode = true; node.isLastNode = false; } else if (targetNode.isLastNode && moveType == consts.move.TYPE_NEXT) { targetParentNode[childKey].splice(tmpTargetIndex + 1, 0, node); newNeighbor = targetNode; newNeighbor.isLastNode = false; node.parentTId = targetNode.parentTId; node.isFirstNode = false; node.isLastNode = true; } else { if (moveType == consts.move.TYPE_PREV) { targetParentNode[childKey].splice(tmpTargetIndex, 0, node); } else { targetParentNode[childKey].splice(tmpTargetIndex + 1, 0, node); } node.parentTId = targetNode.parentTId; node.isFirstNode = false; node.isLastNode = false; } data.fixPIdKeyValue(setting, node); data.setSonNodeLevel(setting, node.getParentNode(), node); //repair node what been moved view.setNodeLineIcos(setting, node); view.repairNodeLevelClass(setting, node, oldLevel) //repair node's old parentNode dom if (!setting.data.keep.parent && oldParentNode[childKey].length < 1) { //old parentNode has no child nodes oldParentNode.isParent = false; oldParentNode.open = false; var tmp_ulObj = $("#" + oldParentNode.tId + consts.id.UL), tmp_switchObj = $("#" + oldParentNode.tId + consts.id.SWITCH), tmp_icoObj = $("#" + oldParentNode.tId + consts.id.ICON); view.replaceSwitchClass(oldParentNode, tmp_switchObj, consts.folder.DOCU); view.replaceIcoClass(oldParentNode, tmp_icoObj, consts.folder.DOCU); tmp_ulObj.css("display", "none"); } else if (oldNeighbor) { //old neigbor node view.setNodeLineIcos(setting, oldNeighbor); } //new neigbor node if (newNeighbor) { view.setNodeLineIcos(setting, newNeighbor); } //repair checkbox / radio if (setting.check.enable && view.repairChkClass) { view.repairChkClass(setting, oldParentNode); view.repairParentChkClassWithSelf(setting, oldParentNode); if (oldParentNode != node.parent) view.repairParentChkClassWithSelf(setting, node); } //expand parents after move if (!isSilent) { view.expandCollapseParentNode(setting, node.getParentNode(), true, animateFlag); } }, removeChildNodes: function(setting, node) { if (!node) return; var childKey = setting.data.key.children, nodes = node[childKey]; if (!nodes) return; $("#" + node.tId + consts.id.UL).remove(); for (var i = 0, l = nodes.length; i < l; i++) { data.removeNodeCache(setting, nodes[i]); } data.removeSelectedNode(setting); delete node[childKey]; if (!setting.data.keep.parent) { node.isParent = false; node.open = false; var tmp_switchObj = $("#" + node.tId + consts.id.SWITCH), tmp_icoObj = $("#" + node.tId + consts.id.ICON); view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); } }, removeEditBtn: function(node) { $("#" + node.tId + consts.id.EDIT).unbind().remove(); }, removeNode: function(setting, node) { var root = data.getRoot(setting), childKey = setting.data.key.children, parentNode = (node.parentTId) ? node.getParentNode() : root; if (root.curEditNode === node) root.curEditNode = null; node.isFirstNode = false; node.isLastNode = false; node.getPreNode = function() {return null;}; node.getNextNode = function() {return null;}; $("#" + node.tId).remove(); data.removeNodeCache(setting, node); data.removeSelectedNode(setting, node); for (var i = 0, l = parentNode[childKey].length; i < l; i++) { if (parentNode[childKey][i].tId == node.tId) { parentNode[childKey].splice(i, 1); break; } } var tmp_ulObj,tmp_switchObj,tmp_icoObj; //repair nodes old parent if (!setting.data.keep.parent && parentNode[childKey].length < 1) { //old parentNode has no child nodes parentNode.isParent = false; parentNode.open = false; tmp_ulObj = $("#" + parentNode.tId + consts.id.UL); tmp_switchObj = $("#" + parentNode.tId + consts.id.SWITCH); tmp_icoObj = $("#" + parentNode.tId + consts.id.ICON); view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); tmp_ulObj.css("display", "none"); } else if (setting.view.showLine && parentNode[childKey].length > 0) { //old parentNode has child nodes var newLast = parentNode[childKey][parentNode[childKey].length - 1]; newLast.isLastNode = true; newLast.isFirstNode = (parentNode[childKey].length == 1); tmp_ulObj = $("#" + newLast.tId + consts.id.UL); tmp_switchObj = $("#" + newLast.tId + consts.id.SWITCH); tmp_icoObj = $("#" + newLast.tId + consts.id.ICON); if (parentNode == root) { if (parentNode[childKey].length == 1) { //node was root, and ztree has only one root after move node view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); } else { var tmp_first_switchObj = $("#" + parentNode[childKey][0].tId + consts.id.SWITCH); view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); } } else { view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); } tmp_ulObj.removeClass(consts.line.LINE); } }, removeRemoveBtn: function(node) { $("#" + node.tId + consts.id.REMOVE).unbind().remove(); }, removeTreeDom: function(setting, node) { node.isHover = false; view.removeEditBtn(node); view.removeRemoveBtn(node); tools.apply(setting.view.removeHoverDom, [setting.treeId, node]); }, repairNodeLevelClass: function(setting, node, oldLevel) { if (oldLevel === node.level) return; var liObj = $("#" + node.tId), aObj = $("#" + node.tId + consts.id.A), ulObj = $("#" + node.tId + consts.id.UL), oldClass = "level" + oldLevel, newClass = "level" + node.level; liObj.removeClass(oldClass); liObj.addClass(newClass); aObj.removeClass(oldClass); aObj.addClass(newClass); ulObj.removeClass(oldClass); ulObj.addClass(newClass); } }, _z = { tools: _tools, view: _view, event: event, data: _data }; $.extend(true, $.fn.zTree.consts, _consts); $.extend(true, $.fn.zTree._z, _z); var zt = $.fn.zTree, tools = zt._z.tools, consts = zt.consts, view = zt._z.view, data = zt._z.data, event = zt._z.event; data.exSetting(_setting); data.addInitBind(_bindEvent); data.addInitCache(_initCache); data.addInitNode(_initNode); data.addInitProxy(_eventProxy); data.addInitRoot(_initRoot); data.addZTreeTools(_zTreeTools); var _cancelPreSelectedNode = view.cancelPreSelectedNode; view.cancelPreSelectedNode = function (setting, node) { var list = data.getRoot(setting).curSelectedList; for (var i=0, j=list.length; i<j; i++) { if (!node || node === list[i]) { view.removeTreeDom(setting, list[i]); if (node) break; } } if (_cancelPreSelectedNode) _cancelPreSelectedNode.apply(view, arguments); } var _createNodes = view.createNodes; view.createNodes = function(setting, level, nodes, parentNode) { if (_createNodes) { _createNodes.apply(view, arguments); } if (!nodes) return; if (view.repairParentChkClassWithSelf) { view.repairParentChkClassWithSelf(setting, parentNode); } } view.makeNodeUrl = function(setting, node) { return (node.url && !setting.edit.enable) ? node.url : null; } var _selectNode = view.selectNode; view.selectNode = function(setting, node, addFlag) { var root = data.getRoot(setting); if (data.isSelectedNode(setting, node) && root.curEditNode == node && node.editNameFlag) { return false; } if (_selectNode) _selectNode.apply(view, arguments); view.addHoverDom(setting, node); return true; } var _uCanDo = tools.uCanDo; tools.uCanDo = function(setting, e) { var root = data.getRoot(setting); if (e && (tools.eqs(e.type, "mouseover") || tools.eqs(e.type, "mouseout") || tools.eqs(e.type, "mousedown") || tools.eqs(e.type, "mouseup"))) { return true; } return (!root.curEditNode) && (_uCanDo ? _uCanDo.apply(view, arguments) : true); } })(jQuery);
yesan/Spacebuilder
Web/Scripts/jquery/zTree/jquery.ztree.all-3.1.js
JavaScript
lgpl-3.0
112,066
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>404 Not Found</title> </head><body> <h1>Not Found</h1> <p>The requested URL /js/sortable.js was not found on this server.</p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> </body></html>
greenpdx/taxnvote
data/pages/FullDataDictionary XML Schema Model_files/sortable.js
JavaScript
lgpl-3.0
331
/** * @license Highcharts JS v9.1.2 (2021-06-16) * @module highcharts/modules/broken-axis * @requires highcharts * * (c) 2009-2021 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import Highcharts from '../../Core/Globals.js'; import BrokenAxis from '../../Core/Axis/BrokenAxis.js'; var G = Highcharts; // Compositions BrokenAxis.compose(G.Axis, G.Series);
sfu-ireceptor/gateway
public/js/highcharts/code/es-modules/masters/modules/broken-axis.src.js
JavaScript
lgpl-3.0
389
/* Implement Github like autocomplete mentions http://ichord.github.com/At.js Copyright (c) 2013 chord.luo@gmail.com Licensed under the MIT license. */ /* 本插件操作 textarea 或者 input 内的插入符 只实现了获得插入符在文本框中的位置,我设置 插入符的位置. */ (function() { (function(factory) { factory(window.jQuery); })(function($) { "use strict"; var Caret, Mirror, methods, pluginName; pluginName = 'caret'; Caret = (function() { function Caret($inputor) { this.$inputor = $inputor; this.domInputor = this.$inputor[0]; } Caret.prototype.getPos = function() { var end, endRange, inputor, len, normalizedValue, pos, range, start, textInputRange; inputor = this.domInputor; inputor.focus(); if (document.selection) { /* #assume we select "HATE" in the inputor such as textarea -> { }. * start end-point. * / * < I really [HATE] IE > between the brackets is the selection range. * \ * end end-point. */ range = document.selection.createRange(); pos = 0; if (range && range.parentElement() === inputor) { normalizedValue = inputor.value.replace(/\r\n/g, "\n"); /* SOMETIME !!! "/r/n" is counted as two char. one line is two, two will be four. balalala. so we have to using the normalized one's length.; */ len = normalizedValue.length; /* <[ I really HATE IE ]>: the whole content in the inputor will be the textInputRange. */ textInputRange = inputor.createTextRange(); /* _here must be the position of bookmark. / <[ I really [HATE] IE ]> [---------->[ ] : this is what moveToBookmark do. < I really [[HATE] IE ]> : here is result. \ two brackets in should be in line. */ textInputRange.moveToBookmark(range.getBookmark()); endRange = inputor.createTextRange(); /* [--------------------->[] : if set false all end-point goto end. < I really [[HATE] IE []]> */ endRange.collapse(false); /* ___VS____ / \ < I really [[HATE] IE []]> \_endRange end-point. " > -1" mean the start end-point will be the same or right to the end end-point * simplelly, all in the end. */ if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) { start = end = len; } else { /* I really |HATE] IE ]> <-| I really[ [HATE] IE ]> <-[ I reall[y [HATE] IE ]> will return how many unit have moved. */ start = -textInputRange.moveStart("character", -len); end = -textInputRange.moveEnd("character", -len); } } } else { start = inputor.selectionStart; } return start; }; Caret.prototype.setPos = function(pos) { var inputor, range; inputor = this.domInputor; if (document.selection) { range = inputor.createTextRange(); range.move("character", pos); return range.select(); } else { return inputor.setSelectionRange(pos, pos); } }; Caret.prototype.getPosition = function(pos) { var $inputor, at_rect, format, h, html, mirror, start_range, x, y; $inputor = this.$inputor; format = function(value) { return value.replace(/</g, '&lt').replace(/>/g, '&gt').replace(/`/g, '&#96').replace(/"/g, '&quot').replace(/\r\n|\r|\n/g, "<br />"); }; if (pos === void 0) { pos = this.getPos(); } start_range = $inputor.val().slice(0, pos); html = "<span>" + format(start_range) + "</span>"; html += "<span id='caret'>|</span>"; mirror = new Mirror($inputor); at_rect = mirror.create(html).rect(); x = at_rect.left - $inputor.scrollLeft(); y = at_rect.top - $inputor.scrollTop(); h = at_rect.height; return { left: x, top: y, height: h }; }; Caret.prototype.getOffset = function(pos) { var $inputor, h, offset, position, x, y; $inputor = this.$inputor; offset = $inputor.offset(); position = this.getPosition(pos); x = offset.left + position.left; y = offset.top + position.top; h = position.height; return { left: x, top: y, height: h }; }; Caret.prototype.getIEPosition = function(pos) { var h, inputorOffset, offset, x, y; offset = this.getIEOffset(pos); inputorOffset = this.$inputor.offset(); x = offset.left - inputorOffset.left; y = offset.top - inputorOffset.top; h = offset.height; return { left: x, top: y, height: h }; }; Caret.prototype.getIEOffset = function(pos) { var h, range, x, y; range = this.domInputor.createTextRange(); if (pos) { range.move('character', pos); } x = range.boundingLeft + this.$inputor.scrollLeft(); y = range.boundingTop + $(window).scrollTop() + this.$inputor.scrollTop(); h = range.boundingHeight; return { left: x, top: y, height: h }; }; return Caret; })(); Mirror = (function() { Mirror.prototype.css_attr = ["overflowY", "height", "width", "paddingTop", "paddingLeft", "paddingRight", "paddingBottom", "marginTop", "marginLeft", "marginRight", "marginBottom", "fontFamily", "borderStyle", "borderWidth", "wordWrap", "fontSize", "lineHeight", "overflowX", "text-align"]; function Mirror($inputor) { this.$inputor = $inputor; } Mirror.prototype.mirrorCss = function() { var css, _this = this; css = { position: 'absolute', left: -9999, top: 0, zIndex: -20000, 'white-space': 'pre-wrap' }; $.each(this.css_attr, function(i, p) { return css[p] = _this.$inputor.css(p); }); return css; }; Mirror.prototype.create = function(html) { this.$mirror = $('<div></div>'); this.$mirror.css(this.mirrorCss()); this.$mirror.html(html); this.$inputor.after(this.$mirror); return this; }; Mirror.prototype.rect = function() { var $flag, pos, rect; $flag = this.$mirror.find("#caret"); pos = $flag.position(); rect = { left: pos.left, top: pos.top, height: $flag.height() }; this.$mirror.remove(); return rect; }; return Mirror; })(); methods = { pos: function(pos) { if (pos) { return this.setPos(pos); } else { return this.getPos(); } }, position: function(pos) { if (document.selection) { return this.getIEPosition(pos); } else { return this.getPosition(pos); } }, offset: function(pos) { if (document.selection) { return this.getIEOffset(pos); } else { return this.getOffset(pos); } } }; return $.fn.caret = function(method) { var caret; caret = new Caret(this); if (methods[method]) { return methods[method].apply(caret, Array.prototype.slice.call(arguments, 1)); } else { return $.error("Method " + method + " does not exist on jQuery.caret"); } }; }); }).call(this); /* Implement Github like autocomplete mentions http://ichord.github.com/At.js Copyright (c) 2013 chord.luo@gmail.com Licensed under the MIT license. */ (function() { var __slice = [].slice; (function(factory) { factory(window.jQuery); })(function($) { var $CONTAINER, Api, App, Controller, DEFAULT_CALLBACKS, DEFAULT_TPL, KEY_CODE, Model, View; App = (function() { function App(inputor) { this.current_flag = null; this.controllers = {}; this.$inputor = $(inputor); this.listen(); } App.prototype.controller = function(key) { return this.controllers[key || this.current_flag]; }; App.prototype.set_context_for = function(key) { this.current_flag = key; return this; }; App.prototype.reg = function(flag, setting) { var controller, _base; controller = (_base = this.controllers)[flag] || (_base[flag] = new Controller(this, flag)); if (setting.alias) { this.controllers[setting.alias] = controller; } controller.init(setting); return this; }; App.prototype.listen = function() { var _this = this; return this.$inputor.on('keyup.atwho', function(e) { return _this.on_keyup(e); }).on('keydown.atwho', function(e) { return _this.on_keydown(e); }).on('scroll.atwho', function(e) { var _ref; return (_ref = _this.controller()) != null ? _ref.view.hide() : void 0; }).on('blur.atwho', function(e) { var c; if (c = _this.controller()) { return c.view.hide(c.get_opt("display_timeout")); } }); }; App.prototype.dispatch = function() { var _this = this; return $.map(this.controllers, function(c) { if (c.look_up()) { return _this.set_context_for(c.key); } }); }; App.prototype.on_keyup = function(e) { var _ref; switch (e.keyCode) { case KEY_CODE.ESC: e.preventDefault(); if ((_ref = this.controller()) != null) { _ref.view.hide(); } break; case KEY_CODE.DOWN: case KEY_CODE.UP: $.noop(); break; default: this.dispatch(); } }; App.prototype.on_keydown = function(e) { var view, _ref; view = (_ref = this.controller()) != null ? _ref.view : void 0; if (!(view && view.visible())) { return; } switch (e.keyCode) { case KEY_CODE.ESC: e.preventDefault(); view.hide(); break; case KEY_CODE.UP: e.preventDefault(); view.prev(); break; case KEY_CODE.DOWN: e.preventDefault(); view.next(); break; case KEY_CODE.TAB: case KEY_CODE.ENTER: if (!view.visible()) { return; } e.preventDefault(); view.choose(); break; default: $.noop(); } }; return App; })(); Controller = (function() { var uuid, _uuid; _uuid = 0; uuid = function() { return _uuid += 1; }; function Controller(app, key) { this.app = app; this.key = key; this.$inputor = this.app.$inputor; this.id = this.$inputor[0].id || uuid(); this.setting = null; this.query = null; this.pos = 0; $CONTAINER.append(this.$el = $("<div id='atwho-ground-" + this.id + "'></div>")); this.model = new Model(this); this.view = new View(this); } Controller.prototype.init = function(setting) { this.setting = $.extend({}, this.setting || $.fn.atwho["default"], setting); return this.model.reload(this.setting.data); }; Controller.prototype.call_default = function() { var args, func_name; func_name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; try { return DEFAULT_CALLBACKS[func_name].apply(this, args); } catch (error) { return $.error("" + error + " Or maybe At.js doesn't have function " + func_name); } }; Controller.prototype.trigger = function(name, data) { var alias, event_name; data.push(this); alias = this.get_opt('alias'); event_name = alias ? "" + name + "-" + alias + ".atwho" : "" + name + ".atwho"; return this.$inputor.trigger(event_name, data); }; Controller.prototype.callbacks = function(func_name) { return this.get_opt("callbacks")[func_name] || DEFAULT_CALLBACKS[func_name]; }; Controller.prototype.get_opt = function(key, default_value) { try { return this.setting[key]; } catch (e) { return null; } }; Controller.prototype.catch_query = function() { var caret_pos, content, end, query, start, subtext; content = this.$inputor.val(); caret_pos = this.$inputor.caret('pos'); subtext = content.slice(0, caret_pos); query = this.callbacks("matcher").call(this, this.key, subtext, this.get_opt('start_with_space')); if (typeof query === "string" && query.length <= this.get_opt('max_len', 20)) { start = caret_pos - query.length; end = start + query.length; this.pos = start; query = { 'text': query.toLowerCase(), 'head_pos': start, 'end_pos': end }; this.trigger("matched", [this.key, query.text]); } else { this.view.hide(); } return this.query = query; }; Controller.prototype.rect = function() { var c, scale_bottom; c = this.$inputor.caret('offset', this.pos - 1); scale_bottom = document.selection ? 0 : 2; return { left: c.left, top: c.top, bottom: c.top + c.height + scale_bottom }; }; Controller.prototype.insert = function(str) { var $inputor, source, start_str, text; $inputor = this.$inputor; str = '' + str; source = $inputor.val(); start_str = source.slice(0, this.query['head_pos'] || 0); text = "" + start_str + str + " " + (source.slice(this.query['end_pos'] || 0)); $inputor.val(text); $inputor.caret('pos', start_str.length + str.length + 1); return $inputor.change(); }; Controller.prototype.render_view = function(data) { var search_key; search_key = this.get_opt("search_key"); data = this.callbacks("sorter").call(this, this.query.text, data.slice(0, 1001), search_key); return this.view.render(data.slice(0, this.get_opt('limit'))); }; Controller.prototype.look_up = function() { var query, _callback; if (!(query = this.catch_query())) { return; } _callback = function(data) { if (data && data.length > 0) { return this.render_view(data); } else { return this.view.hide(); } }; this.model.query(query.text, $.proxy(_callback, this)); return query; }; return Controller; })(); Model = (function() { var _storage; _storage = {}; function Model(context) { this.context = context; this.key = this.context.key; } Model.prototype.saved = function() { return this.fetch() > 0; }; Model.prototype.query = function(query, callback) { var data, search_key, _ref; data = this.fetch(); search_key = this.context.get_opt("search_key"); callback(data = this.context.callbacks('filter').call(this.context, query, data, search_key)); if (!(data && data.length > 0)) { return (_ref = this.context.callbacks('remote_filter')) != null ? _ref.call(this.context, query, callback) : void 0; } }; Model.prototype.fetch = function() { return _storage[this.key] || []; }; Model.prototype.save = function(data) { return _storage[this.key] = this.context.callbacks("before_save").call(this.context, data || []); }; Model.prototype.load = function(data) { if (!(this.saved() || !data)) { return this._load(data); } }; Model.prototype.reload = function(data) { return this._load(data); }; Model.prototype._load = function(data) { var _this = this; if (typeof data === "string") { return $.ajax(data, { dataType: "json" }).done(function(data) { return _this.save(data); }); } else { return this.save(data); } }; return Model; })(); View = (function() { function View(context) { this.context = context; this.key = this.context.key; this.id = this.context.get_opt("alias") || ("at-view-" + (this.key.charCodeAt(0))); this.$el = $("<div id='" + this.id + "' class='atwho-view'><ul id='" + this.id + "-ul' class='atwho-view-url'></ul></div>"); this.timeout_id = null; this.context.$el.append(this.$el); this.bind_event(); } View.prototype.bind_event = function() { var $menu, _this = this; $menu = this.$el.find('ul'); return $menu.on('mouseenter.view', 'li', function(e) { $menu.find('.cur').removeClass('cur'); return $(e.currentTarget).addClass('cur'); }).on('click', function(e) { _this.choose(); return e.preventDefault(); }); }; View.prototype.visible = function() { return this.$el.is(":visible"); }; View.prototype.choose = function() { var $li; $li = this.$el.find(".cur"); this.context.insert(this.context.callbacks("before_insert").call(this.context, $li.data("value"), $li)); this.context.trigger("inserted", [$li]); return this.hide(); }; View.prototype.reposition = function() { var offset, rect; rect = this.context.rect(); if (rect.bottom + this.$el.height() - $(window).scrollTop() > $(window).height()) { rect.bottom = rect.top - this.$el.height(); } offset = { left: rect.left, top: rect.bottom }; this.$el.offset(offset); return this.context.trigger("reposition", [offset]); }; View.prototype.next = function() { var cur, next; cur = this.$el.find('.cur').removeClass('cur'); next = cur.next(); if (!next.length) { next = this.$el.find('li:first'); } return next.addClass('cur'); }; View.prototype.prev = function() { var cur, prev; cur = this.$el.find('.cur').removeClass('cur'); prev = cur.prev(); if (!prev.length) { prev = this.$el.find('li:last'); } return prev.addClass('cur'); }; View.prototype.show = function() { if (!this.visible()) { this.$el.show(); } return this.reposition(); }; View.prototype.hide = function(time) { var callback, _this = this; if (isNaN(time && this.visible())) { return this.$el.hide(); } else { callback = function() { return _this.hide(); }; clearTimeout(this.timeout_id); return this.timeout_id = setTimeout(callback, time); } }; View.prototype.render = function(list) { var $li, $ul, item, li, tpl, _i, _len; if (!$.isArray(list || list.length <= 0)) { this.hide(); return; } this.$el.find('ul').empty(); $ul = this.$el.find('ul'); tpl = this.context.get_opt('tpl', DEFAULT_TPL); for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; li = this.context.callbacks("tpl_eval").call(this.context, tpl, item); $li = $(this.context.callbacks("highlighter").call(this.context, li, this.context.query.text)); $li.data("atwho-info", item); $ul.append($li); } this.show(); return $ul.find("li:first").addClass("cur"); }; return View; })(); KEY_CODE = { DOWN: 40, UP: 38, ESC: 27, TAB: 9, ENTER: 13 }; DEFAULT_CALLBACKS = { before_save: function(data) { var item, _i, _len, _results; if (!$.isArray(data)) { return data; } _results = []; for (_i = 0, _len = data.length; _i < _len; _i++) { item = data[_i]; if ($.isPlainObject(item)) { _results.push(item); } else { _results.push({ name: item }); } } return _results; }, matcher: function(flag, subtext, should_start_with_space) { var match, regexp; flag = flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); if (should_start_with_space) { flag = '(?:^|\\s)' + flag; } regexp = new RegExp(flag + '([A-Za-z0-9_\+\-]*)$|' + flag + '([^\\x00-\\xff]*)$', 'gi'); match = regexp.exec(subtext); if (match) { return match[2] || match[1]; } else { return null; } }, filter: function(query, data, search_key) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = data.length; _i < _len; _i++) { item = data[_i]; if (~item[search_key].toLowerCase().indexOf(query)) { _results.push(item); } } return _results; }, remote_filter: null, sorter: function(query, items, search_key) { var item, _i, _len, _results; if (!query) { return items; } _results = []; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; item.atwho_order = item[search_key].toLowerCase().indexOf(query); if (item.atwho_order > -1) { _results.push(item); } } return _results.sort(function(a, b) { return a.atwho_order - b.atwho_order; }); }, tpl_eval: function(tpl, map) { try { return tpl.replace(/\$\{([^\}]*)\}/g, function(tag, key, pos) { return map[key]; }); } catch (error) { return ""; } }, highlighter: function(li, query) { var regexp; if (!query) { return li; } regexp = new RegExp(">\\s*(\\w*)(" + query.replace("+", "\\+") + ")(\\w*)\\s*<", 'ig'); return li.replace(regexp, function(str, $1, $2, $3) { return '> ' + $1 + '<strong>' + $2 + '</strong>' + $3 + ' <'; }); }, before_insert: function(value, $li) { return value; } }; DEFAULT_TPL = "<li data-value='${name}'>${name}</li>"; Api = { init: function(options) { var $this, app; app = ($this = $(this)).data("atwho"); if (!app) { $this.data('atwho', (app = new App(this))); } return app.reg(options.at, options); }, load: function(key, data) { var c; if (c = this.controller(key)) { return c.model.load(data); } }, run: function() { return this.dispatch(); } }; $CONTAINER = $("<div id='atwho-container'></div>"); $.fn.atwho = function(method) { var _args; _args = arguments; $('body').append($CONTAINER); return this.filter('textarea, input').each(function() { var app; if (typeof method === 'object' || !method) { return Api.init.apply(this, _args); } else if (Api[method]) { if (app = $(this).data('atwho')) { return Api[method].apply(app, Array.prototype.slice.call(_args, 1)); } } else { return $.error("Method " + method + " does not exist on jQuery.caret"); } }); }; return $.fn.atwho["default"] = { at: void 0, alias: void 0, data: null, tpl: DEFAULT_TPL, callbacks: DEFAULT_CALLBACKS, search_key: "name", limit: 5, max_len: 20, start_with_space: true, display_timeout: 300 }; }); }).call(this);
SeekArt/IBOS
static/js/lib/atwho/jquery.atwho.js
JavaScript
lgpl-3.0
25,280
//function f(x) { // return x+1; //} // //var a = 42; //var b = f(a); //var c = this.f(a); var x={ a:function() {return 42}, b:function() {return this.a()}, c:function() {return a()} } var ta = x.a(); var tb = x.b(); var tc = x.c(); // SHOULD FAIL
keil/TbDA
test/micro/test104.js
JavaScript
apache-2.0
274
/* * Copyright 2015-2018 Jeeva Kandasamy (jkandasa@gmail.com) * and other contributors as indicated by the @author tags. * * 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. */ myControllerModule.controller('NodesController', function(alertService, $scope, NodesFactory, $stateParams, $state, $uibModal, displayRestError, CommonServices, mchelper, $filter, $interval) { //GUI page settings $scope.headerStringList = $filter('translate')('NODES_DETAIL'); $scope.noItemsSystemMsg = $filter('translate')('NO_NODES_SETUP'); $scope.noItemsSystemIcon = "fa fa-sitemap"; //load empty, configuration, etc., $scope.mchelper = mchelper; $scope.filteredList=[]; //data query details $scope.currentPage = 1; $scope.query = CommonServices.getQuery(); $scope.queryResponse = {}; //Get min number $scope.getMin = function(item1, item2){ return CommonServices.getMin(item1, item2); }; if($stateParams.gatewayId){ $scope.query.gatewayId = $stateParams.gatewayId; } $scope.isRunning = false; //get all Items $scope.getAllItems = function(){ if($scope.isRunning){ return; } $scope.isRunning = true; NodesFactory.getAll($scope.query, function(response) { $scope.queryResponse = response; $scope.filteredList = $scope.queryResponse.data; $scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount; $scope.isRunning = false; },function(error){ displayRestError.display(error); $scope.isRunning = false; }); } //Hold all the selected item ids $scope.itemIds = []; $scope.selectAllItems = function(){ CommonServices.selectAllItems($scope); }; $scope.selectItem = function(item){ CommonServices.selectItem($scope, item); }; //On page change $scope.pageChanged = function(newPage){ CommonServices.updatePageChange($scope, newPage); }; //Filter change method var filterChange = function (filters) { //Reset filter fields and update items CommonServices.updateFiltersChange($scope, filters); }; $scope.filterConfig = { fields: [ { id: 'name', title: $filter('translate')('NAME'), placeholder: $filter('translate')('FILTER_BY_NAME'), filterType: 'text' }, { id: 'state', title: $filter('translate')('STATUS'), placeholder: $filter('translate')('FILTER_BY_STATUS'), filterType: 'select', filterValues: ['Up','Down','Unavailable'], }, { id: 'type', title: 'Type', placeholder: $filter('translate')('FILTER_BY_TYPE'), filterType: 'select', filterValues: ['Node','Repeater node'], }, { id: 'eui', title: 'EUI', placeholder: $filter('translate')('FILTER_BY_EUI'), filterType: 'text', }, { id: 'version', title: 'Version', placeholder: $filter('translate')('FILTER_BY_VERSION'), filterType: 'text', }, { id: 'libVersion', title: 'Library Version', placeholder: $filter('translate')('FILTER_BY_LIBRARY_VERSION'), filterType: 'text', } ], resultsCount: $scope.filteredList.length, appliedFilters: [], onFilterChange: filterChange }; //Sort columns var sortChange = function (sortId, isAscending) { //Reset sort type and update items CommonServices.updateSortChange($scope, sortId, isAscending); }; $scope.sortConfig = { fields: [ { id: 'name', title: $filter('translate')('NAME'), sortType: 'text' }, { id: 'state', title: $filter('translate')('STATUS'), sortType: 'text' }, { id: 'eui', title: $filter('translate')('EUI'), sortType: 'text' }, { id: 'type', title: $filter('translate')('TYPE'), sortType: 'text' }, { id: 'version', title: $filter('translate')('VERSION'), sortType: 'text' }, { id: 'libVersion', title: $filter('translate')('LIBRARY_VERSION'), sortType: 'text' } ], onSortChange: sortChange }; //Delete Node(s) $scope.delete = function (size) { var modalInstance = $uibModal.open({ templateUrl: 'partials/common-html/delete-modal.html', controller: 'ControllerDeleteModal', size: size, resolve: {} }); modalInstance.result.then(function () { NodesFactory.deleteIds($scope.itemIds, function(response) { alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY')); //Update display table $scope.getAllItems(); $scope.itemIds = []; },function(error){ displayRestError.display(error); }); }), function () { //console.log('Modal dismissed at: ' + new Date()); } }; //Edit item $scope.edit = function () { if($scope.itemIds.length == 1){ $state.go("nodesAddEdit",{'id':$scope.itemIds[0]}); } }; //Upload Firmware $scope.uploadFirmware = function (size) { if($scope.itemIds.length > 0){ NodesFactory.uploadFirmware($scope.itemIds,function(response) { alertService.success($filter('translate')('FIRMWARE_UPLOAD_INITIATED')); },function(error){ displayRestError.display(error); }); } }; //Refresh nodes information $scope.refreshNodesInfo = function (size) { if($scope.itemIds.length > 0){ NodesFactory.executeNodeInfoUpdate($scope.itemIds,function(response) { alertService.success($filter('translate')('REFRESH_NODES_INFO_INITIATED_SUCCESSFULLY')); },function(error){ displayRestError.display(error); }); } }; //Reboot a Node $scope.reboot = function (size) { var addModalInstance = $uibModal.open({ templateUrl: 'partials/nodes/node-reboot-modal.html', controller: 'NodesControllerReboot', size: size, resolve: {} }); addModalInstance.result.then(function () { NodesFactory.reboot($scope.itemIds, function(response) { alertService.success($filter('translate')('REBOOT_INITIATED')); },function(error){ displayRestError.display(error); }); }), function () { //console.log('Modal dismissed at: ' + new Date()); } }; //Erase Configuration of Nodes $scope.eraseConfiguration = function (size) { var addModalInstance = $uibModal.open({ templateUrl: 'partials/nodes/node-erase-configuration-modal.html', controller: 'NodesControllerEraseConfiguration', size: size, resolve: {} }); addModalInstance.result.then(function () { NodesFactory.eraseConfiguration($scope.itemIds, function(response) { alertService.success($filter('translate')('ERASE_CONFIGURATION_INITIATED')); },function(error){ displayRestError.display(error); }); }), function () { //console.log('Modal dismissed at: ' + new Date()); } }; // global page refresh var promise = $interval($scope.getAllItems, mchelper.cfg.globalPageRefreshTime); // cancel interval on scope destroy $scope.$on('$destroy', function(){ $interval.cancel(promise); }); }); // Nodes other controllers //Add/Edit Node myControllerModule.controller('NodesControllerAddEdit', function ($scope, $stateParams, GatewaysFactory, NodesFactory, TypesFactory, mchelper, alertService, displayRestError, $filter, $state, CommonServices) { //Load mchelper variables to this scope $scope.mchelper = mchelper; $scope.cs = CommonServices; $scope.node = {}; $scope.node.altproperties='{}'; if($stateParams.id){ NodesFactory.get({"nodeId":$stateParams.id},function(response) { $scope.node = response; $scope.node.altproperties = angular.toJson(response.properties); },function(error){ displayRestError.display(error); }); } $scope.node.gateway = {}; $scope.gateways = TypesFactory.getGateways(); $scope.nodeTypes = TypesFactory.getNodeTypes(); $scope.nodeRstatuses = TypesFactory.getNodeRegistrationStatuses(); $scope.firmwares = TypesFactory.getFirmwares(); //GUI page settings $scope.showHeaderUpdate = $stateParams.id; $scope.headerStringAdd = $filter('translate')('ADD_NODE'); $scope.headerStringUpdate = $filter('translate')('UPDATE_NODE'); $scope.cancelButtonState = "nodesList"; //Cancel button state $scope.saveProgress = false; //$scope.isSettingChange = false; $scope.save = function(){ $scope.saveProgress = true; $scope.node.properties = angular.fromJson(JSON.stringify(eval('('+$scope.node.altproperties+')'))); console.log(angular.toJson($scope.node.altproperties)); if($stateParams.id){ NodesFactory.update($scope.node,function(response) { alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY')); $state.go("nodesList"); },function(error){ displayRestError.display(error); $scope.saveProgress = false; }); }else{ NodesFactory.create($scope.node,function(response) { alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY')); $state.go("nodesList"); },function(error){ displayRestError.display(error); $scope.saveProgress = false; }); } } }); //Node Detail myControllerModule.controller('NodesControllerDetail', function ($scope, $stateParams, mchelper, NodesFactory, TypesFactory, MetricsFactory, $filter, $timeout, $window) { //Load mchelper variables to this scope $scope.mchelper = mchelper; $scope.item = {}; $scope.headerStringList = $filter('translate')('NODE_DETAILS'); $scope.item = NodesFactory.get({"nodeId":$stateParams.id}); $scope.resourceCount = MetricsFactory.getResourceCount({"resourceType":"NODE", "resourceId":$stateParams.id}); $scope.chartOptions = { chart: { type: 'lineChart', noErrorCheck: true, height: 325, width:null, margin : { top: 0, right: 10, bottom: 90, left: 65 }, color: ["#2ca02c","#1f77b4", "#ff7f0e"], x: function(d){return d[0];}, y: function(d){return d[1];}, useVoronoi: false, clipEdge: false, transitionDuration: 500, useInteractiveGuideline: true, xAxis: { showMaxMin: false, tickFormat: function(d) { return d3.time.format('hh:mm:ss a')(new Date(d)) }, //axisLabel: 'Timestamp', rotateLabels: -20 }, yAxis: { tickFormat: function(d){ return d3.format(',.2f')(d) + ' %'; }, //axisLabel: '' } }, title: { enable: false, text: 'Title' } }; //pre select, should be updated from server TypesFactory.getMetricsSettings(function(response){ $scope.metricsSettings = response; $scope.chartEnableMinMax = $scope.metricsSettings.enabledMinMax; $scope.chartFromTimestamp = $scope.metricsSettings.defaultTimeRange.toString(); MetricsFactory.getBatteryMetrics({"nodeId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "start": new Date().getTime() - $scope.chartFromTimestamp},function(response){ $scope.batteryChartData = response; //Update display time format $scope.chartTimeFormat = response.timeFormat; $scope.chartOptions.chart.type = response.chartType; $scope.chartOptions.chart.interpolate = response.chartInterpolate; $scope.fetching = false; }); }); $scope.chartTimeFormat = mchelper.cfg.dateFormat; $scope.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, $scope.chartTimeFormat, mchelper.cfg.timezone)}; $scope.updateChart = function(){ MetricsFactory.getBatteryMetrics({"nodeId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "start": new Date().getTime() - $scope.chartFromTimestamp}, function(resource){ $scope.batteryChartData.chartData = resource.chartData; //Update display time format $scope.chartTimeFormat = resource.timeFormat; }); } //Graph resize issue, see: https://github.com/krispo/angular-nvd3/issues/40 $scope.$watch('fetching', function() { if(!$scope.fetching) { $timeout(function() { $window.dispatchEvent(new Event('resize')); $scope.fetching = true; }, 1000); } }); }); //Erase Configuration Modal myControllerModule.controller('NodesControllerEraseConfiguration', function ($scope, $uibModalInstance, $filter) { $scope.header = $filter('translate')('ERASE_CONFIGURATION_CONFIRMATION_TITLE'); $scope.eraseMsg = $filter('translate')('ERASE_CONFIGURATION_CONFIRMATION_MESSAGE'); $scope.eraseNodeConfiguration = function() {$uibModalInstance.close(); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); } }); //reboot Modal myControllerModule.controller('NodesControllerReboot', function ($scope, $uibModalInstance, $filter) { $scope.header = $filter('translate')('REBOOT_CONFIRMATION_TITLE'); $scope.rebootMsg = $filter('translate')('REBOOT_CONFIRMATION_MESSAGE'); $scope.reboot = function() {$uibModalInstance.close(); }; $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); } });
pgh70/mycontroller
dist/src/main/package/www/controllers/nodes.js
JavaScript
apache-2.0
14,045
/** * @license * Copyright 2015 Google Inc. 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 */ CLASS({ package: 'foam.apps.builder.datamodels.meta.descriptor', name: 'MetaDescriptor', documentation: function() {/* Describes a type (such as when creating a new property). Instances of $$DOC{ref:'foam.apps.builder.datamodels.meta.descriptor.PropertyMetaDescriptor'} may be edited and then used to create a corresponding $$DOC{ref:'Property'} instance. */}, properties: [ { type: 'String', name: 'model', documentation: function() {/* The model id of the new item. */}, }, { name: 'name', } ], methods: [ function createModel(opt_X) { var X = opt_X || this.Y; return X.lookup(this.model).create({ name: this.name }, X); } ], });
jlhughes/foam
js/foam/apps/builder/datamodels/meta/descriptor/MetaDescriptor.js
JavaScript
apache-2.0
1,025
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-multiple`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'multiple'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,15 L23,15 L23,1 L9,1 L9,5 M15,19 L19,19 L19,5 L5,5 L5,9 M1,23 L15,23 L15,9 L1,9 L1,23 L1,23 L1,23 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Multiple'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
linde12/grommet
src/js/components/icons/base/Multiple.js
JavaScript
apache-2.0
1,692
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core'; import thumbnail from './images/thumbnail.png'; import example1 from './images/MapBox.jpg'; import example2 from './images/MapBox2.jpg'; import controlPanel from './controlPanel'; const metadata = new ChartMetadata({ category: t('Map'), credits: ['https://www.mapbox.com/mapbox-gl-js/api/'], description: '', exampleGallery: [ { url: example1, description: t('Light mode') }, { url: example2, description: t('Dark mode') }, ], name: t('MapBox'), tags: [ t('Business'), t('Intensity'), t('Legacy'), t('Density'), t('Scatter'), t('Transformable'), ], thumbnail, useLegacyApi: true, }); export default class MapBoxChartPlugin extends ChartPlugin { constructor() { super({ loadChart: () => import('./MapBox'), loadTransformProps: () => import('./transformProps'), metadata, controlPanel, }); } }
apache/incubator-superset
superset-frontend/plugins/legacy-plugin-chart-map-box/src/index.js
JavaScript
apache-2.0
1,758
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. const getters = { device: state => state.app.device, version: state => state.app.version, theme: state => state.app.theme, color: state => state.app.color, metrics: state => state.app.metrics, token: state => state.user.token, project: state => state.user.project, avatar: state => state.user.avatar, nickname: state => state.user.name, apis: state => state.user.apis, features: state => state.user.features, userInfo: state => state.user.info, addRouters: state => state.permission.addRouters, multiTab: state => state.app.multiTab, asyncJobIds: state => state.user.asyncJobIds, isLdapEnabled: state => state.user.isLdapEnabled, cloudian: state => state.user.cloudian, zones: state => state.user.zones, timezoneoffset: state => state.user.timezoneoffset, usebrowsertimezone: state => state.user.usebrowsertimezone } export default getters
GabrielBrascher/cloudstack
ui/src/store/getters.js
JavaScript
apache-2.0
1,683
const { filterQuery } = require('./helpers') module.exports = (server, config, cache) => { return [ { /* Endpoint for users authentication. Unauthenticated users are redirected to it for user authentication (see configuration of `uaa-cookie` strategy). Is guarded by `uaa-oauth` strategy which triggers OAuth user authentiction using UAA. Sets `uaa-auth` cookie if the user has been authenticated successfully. */ method: 'GET', path: '/login', config: { auth: 'uaa-oauth', // /login is guarded by `uaa-oauth` strategy handler: (request, h) => { if (request.auth.isAuthenticated) { /* Sets uaa-auth cookie with value of user auth session_id. (see request.auth.session definition in hapi-auth-cookie/lib/index.js) */ const session_id = '' + request.auth.credentials.session_id request.cookieAuth.set({ session_id }) return h.redirect('/') } return h.response().code(401) } } }, { method: 'GET', path: '/account', config: { handler: async (request, h) => { let cached try { if (request.auth && request.auth.credentials && request.auth.credentials.session_id) { cached = await cache.get(request.auth.credentials.session_id) } } catch (error) { server.log(['error', 'authentication', 'session:get:account'], JSON.stringify(error)) } return (cached && cached.account && cached.account.profile) ? cached.account.profile : {} } } }, { method: 'GET', path: '/logout', config: { handler: async (request, h) => { try { await cache.drop(request.auth.credentials.session_id) /* Clears `uaa-auth` cookie. (see request.auth.session definition in hapi-auth-cookie/lib/index.js) */ request.cookieAuth.clear() } catch (error) { server.log(['error', 'authentication', 'session:logout'], JSON.stringify(error)) } /* Redirect to UAA logout. */ return h.redirect(config.get('authentication.logout_uri')) } } }, { method: 'POST', path: '/_filtered_msearch', config: { payload: { parse: false }, validate: { payload: null }, handler: async (request, h) => { const options = { method: 'POST', url: '/elasticsearch/_msearch', artifacts: true }; let cached try { cached = await cache.get(request.auth.credentials.session_id) if (cached.account.orgs.indexOf(config.get('authentication.cf_system_org')) === -1 && !(config.get('authentication.skip_authorization'))) { const modifiedPayload = []; const lines = request.payload.toString().split('\n') const numLines = lines.length; for (var i = 0; i < numLines - 1; i += 2) { const indexes = lines[i] let query = JSON.parse(lines[i + 1]) query = filterQuery(query, cached) modifiedPayload.push(indexes) modifiedPayload.push(JSON.stringify(query)) } options.payload = new Buffer(modifiedPayload.join('\n') + '\n') } else { options.payload = request.payload } } catch (error) { server.log(['error', 'authentication', 'session:get:_filtered_msearch'], JSON.stringify(error)) } finally { options.headers = request.headers delete options.headers.host delete options.headers['user-agent'] delete options.headers['accept-encoding'] options.headers['content-length'] = options.payload.length const resp = await server.inject(options) const response = h.response() response.code(resp.statusCode) response.type(resp.headers['content-type']) response.passThrough(true) return resp.result || resp.payload } } } }, { method: 'POST', path: '/{index}/_filtered_search', config: { payload: { parse: false }, validate: { payload: null }, handler: async (request, h) => { const options = { method: 'POST', url: '/elasticsearch/' + request.params.index + '/_search', artifacts: true } let cached try { cached = await cache.get(request.auth.credentials.session_id) if (cached && cached.account && cached.account.orgs && cached.account.orgs.indexOf(config.get('authentication.cf_system_org')) === -1 && !(config.get('authentication.skip_authorization'))) { let payload = JSON.parse(request.payload.toString() || '{}') payload = filterQuery(payload, cached) options.payload = new Buffer(JSON.stringify(payload)) } else { options.payload = request.payload } } catch (error) { server.log(['error', 'authentication', 'session:get:_filtered_search'], JSON.stringify(error)) } finally { options.headers = request.headers delete options.headers.host delete options.headers['user-agent'] delete options.headers['accept-encoding'] options.headers['content-length'] = (options.payload && options.payload.length) ? options.payload.length : 0 const resp = await server.inject(options) const response = h.response() response.code(resp.statusCode) response.type(resp.headers['content-type']) response.passThrough(true) return resp.result || resp.payload } } } } ] }
logsearch/logsearch-for-cloudfoundry
src/kibana-cf_authentication/server/routes.js
JavaScript
apache-2.0
6,173
/** * @license * Copyright 2016 Google Inc. 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 Tests for vsaq.questionnaire.items.UploadItem. */ goog.provide('vsaq.questionnaire.items.UploadItemTests'); goog.setTestOnly('vsaq.questionnaire.items.UploadItemTests'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.net.IframeIo'); goog.require('goog.net.XhrIo'); goog.require('goog.style'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.events'); goog.require('goog.testing.jsunit'); goog.require('goog.testing.mockmatchers'); goog.require('goog.testing.net.XhrIo'); goog.require('vsaq.questionnaire.items.UploadItem'); var CAPTION = 'uploaditem_caption'; var ID = 'uploaditem_id'; var VALUE = 'fileid|filename'; var upload; var stubs = new goog.testing.PropertyReplacer(); var mock; /** * Initializes variables used by all tests. */ function setUp() { stubs.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send); mock = new goog.testing.MockControl(); upload = new vsaq.questionnaire.items.UploadItem(ID, [], CAPTION); } /** * Resets mocks after each test. */ function tearDown() { goog.testing.net.XhrIo.cleanup(); stubs.reset(); } /** * Tests whether UploadItems are rendered correctly. */ function testUploadItem() { var el = upload.container; assertEquals(String(goog.dom.TagName.DIV), el.tagName); var desc = goog.dom.getFirstElementChild(el); assertEquals(CAPTION, goog.dom.getTextContent(desc)); var fileTypeDesc = goog.dom.getNextElementSibling(desc); assertEquals(String(goog.dom.TagName.DIV), fileTypeDesc.tagName); var form = goog.dom.getNextElementSibling(fileTypeDesc); assertEquals(upload.form_, form); assertEquals('multipart/form-data', form.enctype); var label = goog.dom.getFirstElementChild(form); assertEquals('uploaditem_id-label', label.id); assertEquals(upload.label_, label); var input = goog.dom.getNextElementSibling(label); assertEquals(String(goog.dom.TagName.INPUT), input.tagName); assertEquals('uploaditem_id-file', input.id); var dlLink = goog.dom.getNextElementSibling(input); assertEquals(String(goog.dom.TagName.A), dlLink.tagName); assertEquals('uploaditem_id-download', dlLink.id); var delLink = goog.dom.getNextElementSibling(dlLink); assertEquals(String(goog.dom.TagName.A), delLink.tagName); assertEquals('uploaditem_id-delete', delLink.id); } /** * Tests setting and retrieving the value of the item. */ function testUploadItemSetGetValue() { assertEquals('', upload.getValue()); upload.setValue(VALUE); assertEquals(VALUE, upload.getValue()); assertEquals('filename', upload.filename_); assertEquals('fileid', upload.fileId_); assertEquals(false, goog.style.isElementShown(upload.fileInput_)); assertEquals('Uploaded file: filename', goog.dom.getTextContent(upload.label_)); assertEquals(true, goog.style.isElementShown(upload.deleteLink_)); assertEquals(true, goog.style.isElementShown(upload.downloadLink_)); upload.setValue(''); assertEquals('', upload.getValue()); assertEquals('', upload.filename_); assertEquals('', upload.fileId_); assertEquals(true, goog.style.isElementShown(upload.fileInput_)); assertEquals('', goog.dom.getTextContent(upload.label_)); assertEquals(false, goog.style.isElementShown(upload.deleteLink_)); assertEquals(false, goog.style.isElementShown(upload.downloadLink_)); } /** * Tests whether UploadItems are rendered correctly with highlight. */ function testUploadItemRerender() { upload.setValue(''); upload.render(true); var el = upload.container; assertEquals(String(goog.dom.TagName.DIV), el.tagName); var desc = goog.dom.getFirstElementChild(el); assertEquals(CAPTION, goog.dom.getTextContent(desc)); var fileTypeDesc = goog.dom.getNextElementSibling(desc); assertEquals(String(goog.dom.TagName.DIV), fileTypeDesc.tagName); var form = goog.dom.getNextElementSibling(fileTypeDesc); assertEquals(upload.form_, form); assertEquals('multipart/form-data', form.enctype); var label = goog.dom.getFirstElementChild(form); assertEquals('uploaditem_id-label', label.id); assertEquals(upload.label_, label); var input = goog.dom.getNextElementSibling(label); assertEquals(String(goog.dom.TagName.INPUT), input.tagName); assertEquals('uploaditem_id-file', input.id); var dlLink = goog.dom.getNextElementSibling(input); assertEquals(String(goog.dom.TagName.A), dlLink.tagName); assertEquals('uploaditem_id-download', dlLink.id); var delLink = goog.dom.getNextElementSibling(dlLink); assertEquals(String(goog.dom.TagName.A), delLink.tagName); assertEquals('uploaditem_id-delete', delLink.id); } /** * Tests if upload items preserve value after re-render. */ function testUploadItemPreserveValue() { upload.setValue(VALUE); upload.render(); assertEquals(VALUE, upload.getValue()); assertEquals('filename', upload.filename_); assertEquals('fileid', upload.fileId_); assertEquals(false, goog.style.isElementShown(upload.fileInput_)); assertEquals('Uploaded file: filename', goog.dom.getTextContent(upload.label_)); assertEquals(true, goog.style.isElementShown(upload.deleteLink_)); assertEquals(true, goog.style.isElementShown(upload.downloadLink_)); } /** * Tests parsing of UploadItems. */ function testUploadItemParse() { var testStack = [{ 'type': 'upload', 'text': CAPTION, 'id': ID }]; upload = vsaq.questionnaire.items.UploadItem.parse(testStack); assert(upload instanceof vsaq.questionnaire.items.UploadItem); assertEquals(ID, upload.id); assertEquals(CAPTION, upload.text); assertEquals(0, testStack.length); assertFalse(upload.required); assertTrue(upload.auth != 'readonly'); testStack = [{ 'type': 'upload', 'text': CAPTION, 'id': ID, 'required': true, 'auth': 'readonly' }]; upload = vsaq.questionnaire.items.UploadItem.parse(testStack); assert(upload instanceof vsaq.questionnaire.items.UploadItem); assertEquals(ID, upload.id); assertEquals(CAPTION, upload.text); assertEquals(0, testStack.length); assertTrue(upload.required); assertEquals('readonly', upload.auth); } /** * Tests clicking the delete link. */ function testUploadItemDeleteLink() { upload.setValue(VALUE); mock.createMethodMock(upload, 'answerChanged'); mock.createMethodMock(window, 'confirm'); window.confirm(goog.testing.mockmatchers.isString).$returns(true); upload.answerChanged(); mock.$replayAll(); goog.testing.events.fireClickEvent(upload.deleteLink_); mock.$verifyAll(); assertEquals('', upload.getValue()); assertEquals('', upload.filename_); assertEquals('', upload.fileId_); assertEquals(true, goog.style.isElementShown(upload.fileInput_)); assertEquals('', goog.dom.getTextContent(upload.label_)); assertEquals(false, goog.style.isElementShown(upload.deleteLink_)); assertEquals(false, goog.style.isElementShown(upload.downloadLink_)); } /** * Tests handling of uploads. */ function testUploadItemHandleUpload() { var mockIframeIo = mock.createLooseMock(goog.net.IframeIo, true); var mockIframeIoConstructor = mock.createConstructorMock(goog.net, 'IframeIo'); // need to mock out fileInput_ as file input elements have a readonly value. upload.fileInput_ = goog.dom.createDom(goog.dom.TagName.INPUT); upload.fileInput_.value = 'test.pdf'; mockIframeIoConstructor().$returns(mockIframeIo); mockIframeIo.sendFromForm(upload.form_); mock.$replayAll(); upload.handleUpload_(); var xhrio = goog.testing.net.XhrIo.getSendInstances(); assertEquals(1, xhrio.length); xhrio = xhrio[0]; assertEquals('POST', xhrio.getLastMethod()); assertEquals('/ajax?f=GetUploadUrl', xhrio.getLastUri()); xhrio.simulateResponse(200, '{"url": "/upload123"}'); mock.$verifyAll(); assertEquals('Uploading...', goog.dom.getTextContent(upload.label_)); assertEquals(false, goog.style.isElementShown(upload.fileInput_)); } /** * Tests file uploads with an illegal extension. */ function testUploadItemHandleUploadIllegalExtension() { // need to mock out fileInput_ as file input elements have a readonly value. upload.fileInput_ = goog.dom.createDom(goog.dom.TagName.INPUT); upload.fileInput_.value = 'test.illegal'; upload.handleUpload_(); assertEquals('Invalid extension.', goog.dom.getTextContent(upload.label_)); assertEquals(true, goog.style.isElementShown(upload.fileInput_)); } /** * Tests handling of completed uploads. */ function testUploadItemHandleCompletedUpload() { var mockEvent = {}; mockEvent.target = {}; mockEvent.target.getResponseJson = function() { var mockReturn = {}; mockReturn['filename'] = 'filename'; mockReturn['fileId'] = 'fileid'; return mockReturn; }; mock.createMethodMock(upload, 'answerChanged'); upload.answerChanged(); mock.$replayAll(); upload.handleCompletedUpload_(mockEvent); mock.$verifyAll(); assertEquals('filename', upload.filename_); assertEquals('fileid', upload.fileId_); assertEquals('Uploaded file: filename', goog.dom.getTextContent(upload.label_)); assertEquals(true, goog.style.isElementShown(upload.deleteLink_)); assertEquals(true, goog.style.isElementShown(upload.downloadLink_)); }
google/vsaq
vsaq/static/questionnaire/uploaditem_test.js
JavaScript
apache-2.0
9,859
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function (config) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.filebrowserBrowseUrl = '/admin/ckfinder/ckfinder.html'; config.filebrowserImageBrowseUrl = '/admin/ckfinder/ckfinder.html?type=Images'; config.filebrowserFlashBrowseUrl = '/admin/ckfinder/ckfinder.html?type=Flash'; config.filebrowserUploadUrl = '/admin/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Files'; config.filebrowserImageUploadUrl = '/admin/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Images'; config.filebrowserFlashUploadUrl = '/admin/ckfinder/core/connector/java/connector.java?command=QuickUpload&type=Flash'; config.filebrowserWindowWidth = '1000'; config.filebrowserWindowHeight = '700'; config.removeDialogTabs = 'link:upload;image:Upload;flash:Upload;'; config.language = "zh-cn"; config.extraPlugins += (config.extraPlugins ? ',autoformat' : 'autoformat'); config.pasteFromWordIgnoreFontFace = false; config.pasteFromWordRemoveFontStyles = false; config.pasteFromWordRemoveStyles = false; };
hackingwu/EasyCMS
web/admin/ckeditor2/config.js
JavaScript
apache-2.0
1,347
// Copyright 2016 The Oppia 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 Service to validate the consistency of a collection. These * checks are performable in the frontend to avoid sending a potentially invalid * collection to the backend, which performs similar validation checks to these * in collection_domain.Collection and subsequent domain objects. */ oppia.factory('CollectionValidationService', [ 'SkillListObjectFactory', function(SkillListObjectFactory) { var _getStartingExplorationIds = function(collection) { var startingCollectionNodes = collection.getStartingCollectionNodes(); return startingCollectionNodes.map(function(collectionNode) { return collectionNode.getExplorationId(); }); }; var _getOverlappingPrerequisiteAcquiredSkills = function(collectionNode) { var prerequisiteSkillList = collectionNode.getPrerequisiteSkillList(); var acquiredSkillList = collectionNode.getAcquiredSkillList(); var overlappingSkillList = SkillListObjectFactory.create([]); prerequisiteSkillList.getSkills().forEach(function(skill) { if (acquiredSkillList.containsSkill(skill)) { overlappingSkillList.addSkill(skill); } }); return overlappingSkillList.getSkills(); }; var _getNextExplorationIds = function(collection, completedExpIds) { var acquiredSkillList = completedExpIds.reduce( function(skillList, explorationId) { var collectionNode = collection.getCollectionNodeByExplorationId( explorationId); skillList.addSkillsFromSkillList( collectionNode.getAcquiredSkillList()); return skillList; }, SkillListObjectFactory.create([])); // Pick all collection nodes whose prerequisite skills are satisified by // the currently acquired skills and which have not yet been completed. return collection.getExplorationIds().filter(function(explorationId) { var collectionNode = collection.getCollectionNodeByExplorationId( explorationId); return completedExpIds.indexOf(explorationId) == -1 && acquiredSkillList.isSupersetOfSkillList( collectionNode.getPrerequisiteSkillList()); }); }; var _getUnreachableExplorationIds = function(collection) { var completedExpIds = _getStartingExplorationIds(collection); var nextExpIds = _getNextExplorationIds(collection, completedExpIds); while (nextExpIds.length > 0) { completedExpIds = completedExpIds.concat(nextExpIds); nextExpIds = _getNextExplorationIds(collection, completedExpIds); } return collection.getExplorationIds().filter(function(explorationId) { return completedExpIds.indexOf(explorationId) == -1; }); }; var _getNonexistentExplorationIds = function(collection) { return collection.getCollectionNodes().filter(function(collectionNode) { return !collectionNode.doesExplorationExist(); }).map(function(collectionNode) { return collectionNode.getExplorationId(); }); }; var _getPrivateExplorationIds = function(collection) { return collection.getCollectionNodes().filter(function(collectionNode) { return collectionNode.isExplorationPrivate(); }).map(function(collectionNode) { return collectionNode.getExplorationId(); }); }; var _validateCollection = function(collection, isPublic) { // NOTE TO DEVELOPERS: Please ensure that this validation logic is the // same as that in core.domain.collection_domain.Collection.validate(). var issues = []; var collectionHasNodes = collection.getCollectionNodeCount() > 0; if (!collectionHasNodes) { issues.push( 'There should be at least 1 exploration in the collection'); } var startingExpIds = _getStartingExplorationIds(collection); if (collectionHasNodes && startingExpIds.length == 0) { issues.push( 'There should be at least 1 exploration initially available to the ' + 'learner'); } collection.getCollectionNodes().forEach(function(collectionNode) { var overlappingSkills = _getOverlappingPrerequisiteAcquiredSkills( collectionNode); if (overlappingSkills.length > 0) { issues.push('Exploration ' + collectionNode.getExplorationId() + ' has skills which are both required for playing it and acquired ' + 'after playing it: ' + overlappingSkills.join(', ')); } }); var unreachableExpIds = _getUnreachableExplorationIds(collection); if (unreachableExpIds.length != 0) { issues.push( 'The following exploration(s) are unreachable from the initial ' + 'exploration(s): ' + unreachableExpIds.join(', ')); } var nonexistentExpIds = _getNonexistentExplorationIds(collection); if (nonexistentExpIds.length != 0) { issues.push( 'The following exploration(s) either do not exist, or you do not ' + 'have edit access to add them to this collection: ' + nonexistentExpIds.join(', ')); } if (isPublic) { var privateExpIds = _getPrivateExplorationIds(collection); if (privateExpIds.length != 0) { issues.push( 'Private explorations cannot be added to a public collection: ' + privateExpIds.join(', ')); } } return issues; }; return { /** * Returns a list of error strings found when validating the provided * collection. The validation methods used in this function are written to * match the validations performed in the backend. This function is * expensive, so it should be called sparingly. */ findValidationIssuesForPrivateCollection: function(collection) { return _validateCollection(collection, false); }, /** * Behaves in the same way as findValidationIssuesForPrivateCollection(), * except additional validation checks are performed which are specific to * public collections. This function is expensive, so it should be called * sparingly. */ findValidationIssuesForPublicCollection: function(collection) { return _validateCollection(collection, true); } }; }]);
sdulal/oppia
core/templates/dev/head/domain/collection/CollectionValidationService.js
JavaScript
apache-2.0
6,956
// // page DV.page = DV.Class.extend({ init: function(argHash){ this.index = argHash.index; for(var key in argHash) this[key] = argHash[key]; this.el = $j(this.el); this.parent = this.el.parent(); this.pageNumberEl = this.el.find('span.DV-pageNumber'); this.pageImageEl = this.getPageImage(); this.pageEl = this.el.find('div.DV-page'); this.annotationContainerEl = this.el.find('div.DV-annotations'); this.coverEl = this.el.find('div.DV-cover'); this.application = this.set.application; this.loadTimer = null; this.hasLayerPage = false; this.hasLayerRegional = false; this.imgSource = null; this.offset = null; this.pageNumber = null; this.zoom = 1; this.annotations = []; this.activeAnnotation = null; // optimizations var m = this.application.models; this.model_document = m.document; this.model_pages = m.pages; this.model_annotations = m.annotations; this.model_chapters = m.chapters; }, // Set the image reference for the page for future updates setPageImage: function(){ this.pageImageEl = this.getPageImage(); }, // get page image to update getPageImage: function(){ return this.el.find('img.DV-pageImage'); }, // Bridge annotation methods annotationBridge: function(argHash){ switch(argHash.data.action){ case 'previous': argHash.data.page.activeAnnotation.previous(); break; case 'next': argHash.data.page.activeAnnotation.next(); break; case 'show': var _t = argHash.data.page || this; for(var i = 0; i < _t.annotations.length; i++){ if(_t.annotations[i].annotationEl[0].id==$j(argHash.element).closest('.DV-annotation')[0].id){ _t.annotations[i].show(); break; } } break; case 'hide': var _t = argHash.data.page || this; for(var i = 0; i < _t.annotations.length; i++){ if(_t.annotations[i].annotationEl[0].id==$j(argHash.element).closest('.DV-annotation')[0].id){ _t.annotations[i].hide(true); break; } } break; } }, // Get the offset for the page at its current index getOffset: function(){ return this.model_document.offsets[this.index]; }, // Draw the current page and its associated layers/annotations // Will stop if page index appears the same or force boolean is passed draw: function(argHash) { // Return immeditately if we don't need to redraw the page. if(this.index === argHash.index && !argHash.force && this.imgSource == this.model_pages.imageURL(this.index)){ return; } this.index = (argHash.force === true) ? this.index : argHash.index; var _types = []; var source = this.model_pages.imageURL(this.index); if(this.imgSource != source){ this.imgSource = source; var me = this; _.defer($j.proxy(this.loadImage,this)); }else{ } this.sizeImage(); this.position(); // Only draw annotations if page number has changed or forceAnnotationRedraw boolean is passed if(this.pageNumber != this.index+1 || argHash.forceAnnotationRedraw === true){ for(var i = 0; i < this.annotations.length;i++){ this.annotations[i].remove(); delete this.annotations[i]; this.hasLayerRegional = false; this.hasLayerPage = false; } this.annotations = []; // if there are annotations for this page, it will proceed and attempt to draw var byPage = this.model_annotations.byPage[this.index]; if (byPage) { // Loop through all annotations and add to page for (var i=0; i < byPage.length; i++) { var anno = byPage[i]; if(anno.id === this.application.annotationToLoadId){ var active = true; if (anno.id === this.application.annotationToLoadEdit) argHash.edit = true; }else{ var active = false; } if(anno.type == 'page'){ this.hasLayerPage = true; }else if(anno.type == 'regional'){ this.hasLayerRegional = true; } var newAnno = new DV.Annotation({ renderedHTML: $j('#DV-annotations .DV-annotation[rel=aid-'+anno.id+']').clone().attr('id','DV-annotation-'+anno.id), id: anno.id, page: this, pageEl: this.pageEl, annotationContainerEl : this.annotationContainerEl, pageNumber: this.pageNumber, state: 'collapsed', top: anno.y1, left: anno.x1, width: anno.x1 + anno.x2, height: anno.y1 + anno.y2, active: active, showEdit: argHash.edit, type: anno.type } ); this.annotations.push(newAnno); } } this.renderMeta({ pageNumber: this.index+1 }); } // Update the page type this.setPageType(); }, setPageType: function(){ if(this.annotations.length > 0){ if(this.hasLayerPage === true){ this.el.addClass('DV-layer-page'); } if(this.hasLayerRegional === true){ this.el.addClass('DV-layer-page'); } }else{ this.el.removeClass('DV-layer-page DV-layer-regional'); } }, // Position Y coordinate of this page in the view based on current offset in the Document model position: function(argHash){ this.el.css({ top: this.model_document.offsets[this.index] }); this.offset = this.getOffset(); }, // Render the page meta, currently only the page number renderMeta: function(argHash){ this.pageNumberEl.text('p. '+argHash.pageNumber); this.pageNumber = argHash.pageNumber; }, // Load the actual image loadImage : function(argHash) { if(this.loadTimer){ clearTimeout(this.loadTimer); delete this.loadTimer; } this.el.removeClass('DV-loaded').addClass('DV-loading'); // On image load, update the height for the page and initiate drawImage method to resize accordingly var pageModel = this.model_pages; var preloader = $j(new Image()); var me = this; var lazyImageLoader = function(){ if(me.loadTimer){ clearTimeout(me.loadTimer); delete me.loadTimer; } preloader.bind('load readystatechange',function(e){ if(this.complete || (this.readyState == 'complete' && e.type == 'readystatechange')){ pageModel.updateHeight(preloader[0], me.index); me.drawImage(preloader[0].src); clearTimeout(me.loadTimer); delete me.loadTimer; } }); var src = me.model_pages.imageURL(me.index); preloader[0].src = '#'; preloader[0].src = src; }; this.loadTimer = setTimeout(lazyImageLoader, 150); this.application.pageSet.redraw(); }, sizeImage : function() { var width = this.model_pages.width; var height = this.model_pages.getPageHeight(this.index); // Resize the cover. this.coverEl.css({width: width, height: height}); // Resize the image. this.pageImageEl.css({width: width, height: height}); // Resize the page container. this.el.css({height: height+this.model_document.additionalPaddingOnPage, width: width}); // Resize the page. this.pageEl.css({height: height, width: width}); }, // draw the image and update surrounding image containers with the right size drawImage: function(imageURL) { var imageHeight = this.model_pages.getPageHeight(this.index); // var imageUrl = this.model_pages.imageURL(this.index); if(imageURL == this.pageImageEl.attr('src') && imageHeight == this.pageImageEl.attr('height')) { // already scaled and drawn this.el.addClass('DV-loaded').removeClass('DV-loading'); return; } // Replace the image completely because of some funky loading bugs we were having this.pageImageEl.replaceWith('<img galleryimg="no" width="'+this.model_pages.width+'" height="'+imageHeight+'" class="DV-pageImage" src="'+imageURL+'" />'); // Update element reference this.setPageImage(); this.sizeImage(); // Update the status of the image load this.el.addClass('DV-loaded').removeClass('DV-loading'); } });
NYTimes/document-viewer
public/javascripts/DV/lib/page.js
JavaScript
apache-2.0
8,511
/** * Copyright 2016 The AMP HTML 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 Embeds a Soundcloud clip * * Example: * <code> * <amp-soundcloud * height=166 * data-trackid="243169232" * data-color="ff5500" * data-autoplay="true" * layout="fixed-height"> * </amp-soundcloud> * * */ import {Layout} from '../../../src/layout'; import {loadPromise} from '../../../src/event-helper'; class AmpSoundcloud extends AMP.BaseElement { /** @override */ preconnectCallback(onLayout) { this.preconnect.url('https://api.soundcloud.com/', onLayout); } /** @override */ isLayoutSupported(layout) { return layout == Layout.FIXED_HEIGHT; } /**@override*/ layoutCallback() { const height = this.element.getAttribute('height'); const color = this.element.getAttribute('data-color'); const visual = this.element.getAttribute('data-visual'); const url = "https://api.soundcloud.com/tracks/"; const trackid = AMP.assert( (this.element.getAttribute('data-trackid')), 'The data-trackid attribute is required for <amp-soundcloud> %s', this.element); const iframe = document.createElement('iframe'); iframe.setAttribute('frameborder', 'no'); iframe.setAttribute('scrolling', 'no'); iframe.src = "https://w.soundcloud.com/player/?" + "url=" + encodeURIComponent(url + trackid); if (visual) { iframe.src += "&visual=true"; } else if (color) { iframe.src += "&color=" + encodeURIComponent(color); } this.applyFillContent(iframe); iframe.height = height; this.element.appendChild(iframe); /** @private {?Element} */ this.iframe_ = iframe; return loadPromise(iframe); } /** @override */ documentInactiveCallback() { if (this.iframe_ && this.iframe_.contentWindow) { this.iframe_.contentWindow./*OK*/postMessage( JSON.stringify({method: 'pause'}), 'https://w.soundcloud.com'); } return true; } }; AMP.registerElement('amp-soundcloud', AmpSoundcloud);
Meggin/amphtml
extensions/amp-soundcloud/0.1/amp-soundcloud.js
JavaScript
apache-2.0
2,611
/* DreemGL is a collaboration between Teeming Society & Samsung Electronics, sponsored by Samsung and others. Copyright 2015-2016 Teeming Society. 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.*/ define(function(require, exports){ exports.noise = require('./noiselib') exports.pal = require('./palettelib') exports.math = require('./mathlib') exports.kali2d = function(pos, steps, space){ var v = pos for(var i = 0; i < 130; i ++){ if(i > int(steps)) break v = abs(v) v = v / (v.x * v.x + v.y * v.y) + space } return v } exports.fractzoom = function(pos, time, zoom){ var dt = sin((80/60)*time*math.PI) var mypos = pos.xy*.01*sin(0.04*time+0.05*dt) var dx = 0.01*sin(0.01*time) var dy = -0.01*sin(0.01*time) mypos = math.rotate2d(mypos,0.1*time) var kali1 = kali2d(mypos+vec2(0.0001*time), 30, vec2(-0.8280193310201044,-0.858019331020104-dx)) //var kali2 = kali2d(mypos+vec2(0.0001*time), 40, vec2(-0.8280193310201044,-0.858019331020104-dy)) //var c1 =vec4(d.y, 0. ,sin(0.1*time)*6*kali2.y, 1.) var c1 = pal.pal2(kali1.y+dt) //var c2 = pal.pal2(kali2.y+dt) //return mix(c1,c2,sin(length(pos-.5)+time)) var mp = highdefblirpy(pos.xy*0.05*sin(0.1*time), time,1.) return mix(pal.pal4(mp.r+0.1*time),c1,c1.b) } exports.highdefblirpy = function(pos, time, zoom){ var xs = 20. * zoom var ys = 22. * zoom var x = pos.x*xs+0.1*time var y = pos.y*ys var ns = noise.snoise3(x, y, 0.1*time) return pal.pal0(ns) + 0.5*(vec4(1.)*sin(-8*time + (length(pos-.5)-.01*ns+ .0001*noise.snoise3(x*10, y*10, 0.1*time))*2400)) } })
dreemproject/dreemgl
system/shaderlib/demolib.js
JavaScript
apache-2.0
2,070
module.exports = "3.2.0";
tijhaart/pouchdb-getting-started
bower_components/pouchdb/lib/version-browser.js
JavaScript
apache-2.0
26
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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. */ var InitiateViewOption = null; (function () { var deviceId = $(".device-id"); var deviceIdentifier = deviceId.data("deviceid"); var deviceType = deviceId.data("type"); var payload = [deviceIdentifier]; var operationTable; if (deviceType == "ios") { var serviceUrl = "/ios/operation/deviceinfo"; } else if (deviceType == "android") { var serviceUrl = "/mdm-android-agent/operation/device-info"; } if(serviceUrl){ invokerUtil.post(serviceUrl, payload, function(message){ $(".panel-body").show(); }, function (message) { var defaultInnerHTML = "<br><p class='fw-warning'>Device data might not be updated Please refresh this page<p>"; $(".panel-body").append(defaultInnerHTML); }); } $('.media.tab-responsive [data-toggle=tab]').on('shown.bs.tab', function(e){ var activeTabPane = $(e.target).attr('href'), activeCollpasePane = $(activeTabPane).find('[data-toggle=collapse]').data('target'), activeCollpasePaneSiblings = $(activeTabPane).siblings().find('[data-toggle=collapse]').data('target'), activeListGroupItem = $('.media .list-group-item.active'); $(activeCollpasePaneSiblings).collapse('hide'); $(activeCollpasePane).collapse('show'); positionArrow(activeListGroupItem); $(".panel-heading .caret-updown").removeClass("fw-sort-down"); $(".panel-heading.collapsed .caret-updown").addClass("fw-sort-up"); }); $('.media.tab-responsive .tab-content').on('shown.bs.collapse', function(e){ var activeTabPane = $(e.target).parent().attr('id'); $('.media.tab-responsive [data-toggle=tab][href=#'+activeTabPane+']').tab('show'); $(".panel-heading .caret-updown").removeClass("fw-sort-up"); $(".panel-heading.collapsed .caret-updown").addClass("fw-sort-down"); }); function positionArrow(selectedTab){ var selectedTabHeight = $(selectedTab).outerHeight(); var arrowPosition = 0; var totalHeight = 0; var arrow = $(".media .panel-group.tab-content .arrow-left"); var parentHeight = $(arrow).parent().outerHeight(); /*if($(selectedTab).prev().length){ $(selectedTab).prevAll().each(function() { totalHeight += $(this).outerHeight(); }); arrowPosition = totalHeight + (selectedTabHeight / 2); }else{ arrowPosition = selectedTabHeight / 2; }*/ if(arrowPosition >= parentHeight){ parentHeight = arrowPosition + 10; $(arrow).parent().height(parentHeight); }else{ $(arrow).parent().removeAttr("style"); } $(arrow).css("top",arrowPosition - 10); } $(document).ready(function(){ $(".device-detail-body").removeClass("hidden"); $("#loading-content").remove(); loadOperationBar(deviceType); loadOperationsLog(); loadApplicationsList(); loadPolicyCompliance(); $("#refresh-policy").click(function () { $('#policy-spinner').removeClass('hidden'); loadPolicyCompliance(); }); $("#refresh-apps").click(function () { $('#apps-spinner').removeClass('hidden'); loadApplicationsList(); }); $("#refresh-operations").click(function () { $('#operations-spinner').removeClass('hidden'); loadOperationsLog(true); }); }); function loadOperationsLog(update) { var operationsLog = $("#operations-log"); if (update) { operationTable = $('#operations-log-table').DataTable(); operationTable.ajax.reload(null, false); return; } operationTable = $('#operations-log-table').datatables_extended({ serverSide: true, processing: false, searching: false, ordering: false, pageLength : 10, order: [], ajax: { url : '/emm/api/operation/paginate', data : {deviceId : deviceIdentifier, deviceType: deviceType}, dataSrc: function ( json ) { $('#operations-spinner').addClass('hidden'); $("#operations-log-container").empty(); return json.data; } }, columnDefs: [ { targets: 0, data: 'code' }, { targets: 1, data: 'status', render: function ( status, type, row, meta ) { var html; switch (status) { case 'COMPLETED' : html = '<span><i class="fw fw-ok icon-success"></i> Completed</span>'; break; case 'PENDING' : html = '<span><i class="fw fw-warning icon-warning"></i> Pending</span>'; break; case 'ERROR' : html = '<span><i class="fw fw-error icon-danger"></i> Error</span>'; break; case 'IN_PROGRESS' : html = '<span><i class="fw fw-ok icon-warning"></i> In Progress</span>'; break; } return html; }}, { targets: 2, data: 'createdTimeStamp', render: function (date, type, row, meta) {; var value = String(date); return value.slice(0,16); } } ], "createdRow": function( row, data, dataIndex ) { $(row).attr('data-type', 'selectable'); $(row).attr('data-id', data.id); $.each($('td', row), function (colIndex) { switch(colIndex) { case 1: $(this).attr('data-grid-label', 'Code'); $(this).attr('data-display', data.code); break; case 2: $(this).attr('data-grid-label', 'Status'); $(this).attr('data-display', data.status); break; case 3: $(this).attr('data-grid-label', "Created Timestamp"); $(this).attr('data-display', data.createdTimeStamp); break; } }); } }); } function loadApplicationsList() { var applicationsList = $("#applications-list"); var deviceListingSrc = applicationsList.attr("src"); var deviceId = applicationsList.data("device-id"); var deviceType = applicationsList.data("device-type"); $.template("application-list", deviceListingSrc, function (template) { var serviceURL = "/mdm-admin/operations/"+deviceType+"/"+deviceId+"/apps"; var successCallback = function (data) { data = JSON.parse(data); $('#apps-spinner').addClass('hidden'); var viewModel = {}; if(data != null && data.length > 0) { for (var i = 0; i < data.length; i++) { data[i].name = decodeURIComponent(data[i].name); data[i].platform = deviceType; } } viewModel.applications = data; viewModel.deviceType = deviceType; if(data.length > 0){ var content = template(viewModel); $("#applications-list-container").html(content); } }; invokerUtil.get(serviceURL, successCallback, function(message){ $("#applications-list-container").append("<br><p class='fw-warning'>Loading application was not" + " successful please try again in a while<p>"); }); }); } function loadPolicyCompliance() { var policyCompliance = $("#policy-view"); var policySrc = policyCompliance.attr("src"); var deviceId = policyCompliance.data("device-id"); var deviceType = policyCompliance.data("device-type"); var activePolicy = null; $.template("policy-view", policySrc, function (template) { var serviceURLPolicy ="/mdm-admin/policies/"+deviceType+"/"+deviceId+"/active-policy" var serviceURLCompliance = "/mdm-admin/policies/"+deviceType+"/"+deviceId; var successCallbackCompliance = function (data) { var viewModel = {}; viewModel.policy = activePolicy; viewModel.deviceType = deviceType; data = JSON.parse(data); if (data != null && data.complianceFeatures!= null && data.complianceFeatures != undefined && data.complianceFeatures.length > 0) { viewModel.compliance = "NON-COMPLIANT"; viewModel.complianceFeatures = data.complianceFeatures; var content = template(viewModel); $("#policy-list-container").html(content); } else { viewModel.compliance = "COMPLIANT"; var content = template(viewModel); $("#policy-list-container").html(content); $("#policy-compliance-table").addClass("hidden"); } }; var successCallbackPolicy = function (data) { data = JSON.parse(data); $('#policy-spinner').addClass('hidden'); if(data != null && data.active == true){ activePolicy = data; invokerUtil.get(serviceURLCompliance, successCallbackCompliance, function(message){ $("#policy-list-container").append("<br><p class='fw-warning'>Loading policy related data" + " was not successful please try again in a while<p>"); }); } }; invokerUtil.get(serviceURLPolicy, successCallbackPolicy, function(message){ $("#policy-list-container").append("<br><p class='fw-warning'>Loading policy related was not" + " successful please try again in a while<p>"); }); }); } }());
pasindujw/product-mdm
modules/apps/jaggery/emm/src/emm/units/device-detail/public/js/device-detail.js
JavaScript
apache-2.0
11,488
"use strict"; /* This file contains translations between the integer values used in the Zulip API to describe values in dropdowns, radio buttons, and similar widgets and the user-facing strings that should be used to describe them, as well as data details like sort orders that may be useful for some widgets. We plan to eventually transition much of this file to have a more standard format and then to be populated using data sent from the Zulip server in `page_params`, so that the data is available for other parts of the ecosystem to use (including the mobile apps and API documentation) without a ton of copying. */ exports.demote_inactive_streams_values = { automatic: { code: 1, description: i18n.t("Automatic"), }, always: { code: 2, description: i18n.t("Always"), }, never: { code: 3, description: i18n.t("Never"), }, }; exports.color_scheme_values = { automatic: { code: 1, description: i18n.t("Automatic"), }, night: { code: 2, description: i18n.t("Night mode"), }, day: { code: 3, description: i18n.t("Day mode"), }, }; exports.twenty_four_hour_time_values = { twenty_four_hour_clock: { value: true, description: i18n.t("24-hour clock (17:00)"), }, twelve_hour_clock: { value: false, description: i18n.t("12-hour clock (5:00 PM)"), }, }; exports.get_all_display_settings = () => ({ settings: { user_display_settings: [ "dense_mode", "high_contrast_mode", "left_side_userlist", "starred_message_counts", "fluid_layout_width", ], }, render_only: { high_contrast_mode: page_params.development_environment, dense_mode: page_params.development_environment, }, }); exports.email_address_visibility_values = { everyone: { code: 1, description: i18n.t("Admins, members, and guests"), }, //// Backend support for this configuration is not available yet. // admins_and_members: { // code: 2, // description: i18n.t("Members and admins"), // }, admins_only: { code: 3, description: i18n.t("Admins only"), }, nobody: { code: 4, description: i18n.t("Nobody"), }, }; exports.create_stream_policy_values = { by_admins_only: { order: 1, code: 2, description: i18n.t("Admins"), }, by_full_members: { order: 2, code: 3, description: i18n.t("Admins and full members"), }, by_members: { order: 3, code: 1, description: i18n.t("Admins and members"), }, }; exports.invite_to_stream_policy_values = exports.create_stream_policy_values; exports.user_group_edit_policy_values = { by_admins_only: { order: 1, code: 2, description: i18n.t("Admins"), }, by_members: { order: 2, code: 1, description: i18n.t("Admins and members"), }, }; exports.private_message_policy_values = { by_anyone: { order: 1, code: 1, description: i18n.t("Admins, members, and guests"), }, disabled: { order: 2, code: 2, description: i18n.t("Private messages disabled"), }, }; exports.wildcard_mention_policy_values = { by_everyone: { order: 1, code: 1, description: i18n.t("Admins, members and guests"), }, by_members: { order: 2, code: 2, description: i18n.t("Admins and members"), }, by_full_members: { order: 3, code: 3, description: i18n.t("Admins and full members"), }, // Until we add stream administrators, we mislabel this choice // (which we intend to be the long-term default) as "Admins only" // and don't offer the long-term "Admins only" option. by_stream_admins_only: { order: 4, code: 4, // description: i18n.t("Organization and stream admins"), description: i18n.t("Admins only"), }, // by_admins_only: { // order: 5, // code: 5, // description: i18n.t("Admins only"), // }, nobody: { order: 6, code: 6, description: i18n.t("Nobody"), }, }; const time_limit_dropdown_values = new Map([ [ "any_time", { text: i18n.t("Any time"), seconds: 0, }, ], [ "never", { text: i18n.t("Never"), }, ], [ "upto_two_min", { text: i18n.t("Up to __time_limit__ after posting", {time_limit: i18n.t("2 minutes")}), seconds: 2 * 60, }, ], [ "upto_ten_min", { text: i18n.t("Up to __time_limit__ after posting", {time_limit: i18n.t("10 minutes")}), seconds: 10 * 60, }, ], [ "upto_one_hour", { text: i18n.t("Up to __time_limit__ after posting", {time_limit: i18n.t("1 hour")}), seconds: 60 * 60, }, ], [ "upto_one_day", { text: i18n.t("Up to __time_limit__ after posting", {time_limit: i18n.t("1 day")}), seconds: 24 * 60 * 60, }, ], [ "upto_one_week", { text: i18n.t("Up to __time_limit__ after posting", {time_limit: i18n.t("1 week")}), seconds: 7 * 24 * 60 * 60, }, ], [ "custom_limit", { text: i18n.t("Up to N minutes after posting"), }, ], ]); exports.msg_edit_limit_dropdown_values = time_limit_dropdown_values; exports.msg_delete_limit_dropdown_values = time_limit_dropdown_values; exports.retain_message_forever = -1; exports.user_role_values = { guest: { code: 600, description: i18n.t("Guest"), }, member: { code: 400, description: i18n.t("Member"), }, admin: { code: 200, description: i18n.t("Administrator"), }, owner: { code: 100, description: i18n.t("Owner"), }, }; const user_role_array = Object.values(exports.user_role_values); exports.user_role_map = new Map(user_role_array.map((role) => [role.code, role.description])); // NOTIFICATIONS exports.general_notifications_table_labels = { realm: [ /* An array of notification settings of any category like * `stream_notification_settings` which makes a single row of * "Notification triggers" table should follow this order */ "visual", "audio", "mobile", "email", "all_mentions", ], stream: { is_muted: i18n.t("Mute stream"), desktop_notifications: i18n.t("Visual desktop notifications"), audible_notifications: i18n.t("Audible desktop notifications"), push_notifications: i18n.t("Mobile notifications"), email_notifications: i18n.t("Email notifications"), pin_to_top: i18n.t("Pin stream to top of left sidebar"), wildcard_mentions_notify: i18n.t("Notifications for @all/@everyone mentions"), }, }; exports.stream_specific_notification_settings = [ "desktop_notifications", "audible_notifications", "push_notifications", "email_notifications", "wildcard_mentions_notify", ]; exports.stream_notification_settings = [ "enable_stream_desktop_notifications", "enable_stream_audible_notifications", "enable_stream_push_notifications", "enable_stream_email_notifications", "wildcard_mentions_notify", ]; const pm_mention_notification_settings = [ "enable_desktop_notifications", "enable_sounds", "enable_offline_push_notifications", "enable_offline_email_notifications", ]; const desktop_notification_settings = ["pm_content_in_desktop_notifications"]; const mobile_notification_settings = ["enable_online_push_notifications"]; const email_notification_settings = [ "enable_digest_emails", "enable_login_emails", "message_content_in_email_notifications", "realm_name_in_notifications", ]; const presence_notification_settings = ["presence_enabled"]; const other_notification_settings = desktop_notification_settings.concat( ["desktop_icon_count_display"], mobile_notification_settings, email_notification_settings, presence_notification_settings, ["notification_sound"], ); exports.all_notification_settings = other_notification_settings.concat( pm_mention_notification_settings, exports.stream_notification_settings, ); exports.all_notifications = () => ({ general_settings: [ { label: i18n.t("Streams"), notification_settings: settings_notifications.get_notifications_table_row_data( exports.stream_notification_settings, ), }, { label: i18n.t("PMs, mentions, and alerts"), notification_settings: settings_notifications.get_notifications_table_row_data( pm_mention_notification_settings, ), }, ], settings: { desktop_notification_settings, mobile_notification_settings, email_notification_settings, presence_notification_settings, }, show_push_notifications_tooltip: { push_notifications: !page_params.realm_push_notifications_enabled, enable_online_push_notifications: !page_params.realm_push_notifications_enabled, }, }); const map_language_to_playground_info = { // TODO: This is being hardcoded just for the prototype, post which we should // add support for realm admins to configure their own choices. The keys here // are the pygment lexer subclass names for the different language alias it // supports. Rust: [ { name: "Rust playground", url_prefix: "https://play.rust-lang.org/?edition=2018&code=", }, ], Julia: [ { name: "Julia playground", url_prefix: "https://repl.it/languages/julia/?code=", }, ], Python: [ { name: "Python 3 playground", url_prefix: "https://repl.it/languages/python3/?code=", }, ], "Python 2.7": [ { name: "Python 2.7 playground", url_prefix: "https://repl.it/languages/python/?code=", }, ], JavaScript: [ { name: "JavaScript playground", url_prefix: "https://repl.it/languages/javascript/?code=", }, ], Lean: [ { name: "Lean playground", url_prefix: "https://leanprover.github.io/live/latest/#code=", }, { name: "Lean community playground", url_prefix: "https://leanprover-community.github.io/lean-web-editor/#code=", }, ], }; exports.get_playground_info_for_languages = (lang) => map_language_to_playground_info[lang];
showell/zulip
static/js/settings_config.js
JavaScript
apache-2.0
11,095
angular.module('classwhole', ['services', 'utils', 'directives']); angular.module('directives', []); angular.module('services', []);
mikesmayer/classwhole
app/assets/javascripts/angular/app.js
JavaScript
apache-2.0
133
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 (callback) { if (typeof define === 'function' && define.amd) { define(['core/AbstractTextWidget'], callback); } else { callback(); } }(function () { (function ($) { AjaxSolr.AutocompleteWidget = AjaxSolr.AbstractTextWidget.extend({ afterRequest: function () { $(this.target).find('input').unbind().removeData('events').val(''); var self = this; var list = []; for (var i = 0; i < this.fields.length; i++) { var field = this.fields[i]; for (var facet in this.manager.response.facet_counts.facet_fields[field]) { list.push({ field: field, value: facet, label: facet + ' (' + this.manager.response.facet_counts.facet_fields[field][facet] + ') - ' + field }); } } this.requestSent = false; $(this.target).find('input').autocomplete('destroy').autocomplete({ source: list, select: function(event, ui) { if (ui.item) { self.requestSent = true; if (self.manager.store.addByValue('fq', ui.item.field + ':' + AjaxSolr.Parameter.escapeValue(ui.item.value))) { self.doRequest(); } } } }); // This has lower priority so that requestSent is set. $(this.target).find('input').bind('keydown', function(e) { if (self.requestSent === false && e.which == 13) { var value = $(this).val(); if (value && self.set(value)) { self.doRequest(); } } }); } }); })(jQuery); }));
apache/chukwa
core/src/main/web/hicc/ajax-solr/chukwa/widgets/AutocompleteWidget.7.0.js
JavaScript
apache-2.0
2,325
'use strict'; goog.require('grrUi.core.module'); goog.require('grrUi.tests.browserTrigger'); goog.require('grrUi.tests.module'); var browserTrigger = grrUi.tests.browserTrigger; describe('infinite table', function() { var $compile, $rootScope, $interval; beforeEach(module(grrUi.core.module.name)); beforeEach(module(grrUi.tests.module.name)); beforeEach(inject(function($injector) { $compile = $injector.get('$compile'); $rootScope = $injector.get('$rootScope'); $interval = $injector.get('$interval'); })); afterEach(function() { // We have to clean document's body to remove tables we add there. $(document.body).html(''); }); var render = function(items, noDomAppend) { $rootScope.testItems = items; // We render the infinite table with grr-memory-items-provider. // While it means that this unit test actually depends on the working // code of grr-memory-items-provider (which is tested separately), // this seems to be the easiest/most reasonable way to test that // grr-paged-filtered-table is working correctly. Mocking out // items providers would require writing code that's almost // equal to grr-memory-items-provider code. var template = '<div>' + '<table>' + '<tbody>' + '<tr grr-infinite-table grr-memory-items-provider ' + 'items="testItems" page-size="5">' + '<td>{$ item.timestamp $}</td>' + '<td>{$ item.message $}</td>' + '</tr>' + '</tbody' + '</table>' + '</div>'; var element = $compile(template)($rootScope); $rootScope.$apply(); if (!noDomAppend) { $('body').append(element); $interval.flush(1000); } return element; }; it('throws if items provider is not specified', function() { var template = '<table><tbody><tr grr-infinite-table />' + '</tbody></table>'; var compiledTemplate = $compile(template); expect(function() { compiledTemplate($rootScope); }).toThrow( 'Data provider not specified.'); }); it('shows empty table when there are no elements', function() { var element = render([]); expect($('table', element).length).toBe(1); expect($('table tr', element).length).toBe(0); }); it('shows 2 rows for 2 items', function() { var element = render([{timestamp: 42, message: 'foo'}, {timestamp: 43, message: 'bar'}]); expect($('table', element).length).toBe(1); expect($('table tr', element).length).toBe(2); expect($('table tr:eq(0) td:eq(0):contains(42)', element).length). toBe(1); expect($('table tr:eq(0) td:eq(1):contains(foo)', element).length). toBe(1); expect($('table tr:eq(1) td:eq(0):contains(43)', element).length). toBe(1); expect($('table tr:eq(1) td:eq(1):contains(bar)', element).length). toBe(1); }); it('does nothing when "Loading..." row is not seen', function() { var element = render([{timestamp: 42, message: 'foo'}, {timestamp: 43, message: 'bar'}], true); expect($('table', element).length).toBe(1); expect($('table tr', element).length).toBe(1); expect($('table tr:contains("Loading...")', element).length).toBe(1); $interval.flush(1000); expect($('table tr', element).length).toBe(1); expect($('table tr:contains("Loading...")', element).length).toBe(1); $('body').append(element); $interval.flush(1000); expect($('table tr', element).length).toBe(2); expect($('table tr:contains("Loading...")', element).length).toBe(0); expect($('table tr:eq(0) td:eq(0):contains(42)', element).length). toBe(1); expect($('table tr:eq(0) td:eq(1):contains(foo)', element).length). toBe(1); expect($('table tr:eq(1) td:eq(0):contains(43)', element).length). toBe(1); expect($('table tr:eq(1) td:eq(1):contains(bar)', element).length). toBe(1); }); });
wandec/grr
gui/static/angular-components/core/infinite-table-directive_test.js
JavaScript
apache-2.0
3,966
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ function run_test() { // We're testing migration to this version from one version below var targetVersion = 8; // First import the downloads.sqlite file importDatabaseFile("v" + (targetVersion - 1) + ".sqlite"); // Init the download manager which will try migrating to the new version var dm = Cc["@mozilla.org/download-manager;1"]. getService(Ci.nsIDownloadManager); var dbConn = dm.DBConnection; // Check schema version do_check_true(dbConn.schemaVersion >= targetVersion); // Make sure all the columns are there var stmt = dbConn.createStatement( "SELECT name, source, target, tempPath, startTime, endTime, state, " + "referrer, entityID, currBytes, maxBytes, mimeType, " + "preferredApplication, preferredAction, autoResume " + "FROM moz_downloads " + "WHERE id = 28"); stmt.executeStep(); // This data is based on the original values in the table var data = [ "firefox-3.0a9pre.en-US.linux-i686.tar.bz2", "http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/firefox-3.0a9pre.en-US.linux-i686.tar.bz2", "file:///Users/Ed/Desktop/firefox-3.0a9pre.en-US.linux-i686.tar.bz2", "/Users/Ed/Desktop/+EZWafFQ.bz2.part", 1192469856209164, 1192469877017396, Ci.nsIDownloadManager.DOWNLOAD_FINISHED, "http://ftp.mozilla.org/pub/mozilla.org/firefox/nightly/latest-trunk/", "%2210e66c1-8a2d6b-9b33f380%22/9055595/Mon, 15 Oct 2007 11:45:34 GMT", 1210772, 9055595, "application/x-bzip2", "AAAAAAGqAAIAAQxNYWNpbnRvc2ggSEQAAAAAAAAAAAAAAAAAAAC+91IESCsAAAAHc5UUU3R1ZmZJdCBFeHBhbmRlci5hcHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAdzmb3SGI8AAAAAAAAAAP////8AAAkgAAAAAAAAAAAAAAAAAAAAFFN0dWZmSXQgU3RhbmRhcmQgOS4wABAACAAAvveYVAAAABEACAAAvdJs7wAAAAEACAAHc5UAAAAWAAIAQ01hY2ludG9zaCBIRDpBcHBsaWNhdGlvbnM6U3R1ZmZJdCBTdGFuZGFyZCA5LjA6U3R1ZmZJdCBFeHBhbmRlci5hcHAAAA4AKgAUAFMAdAB1AGYAZgBJAHQAIABFAHgAcABhAG4AZABlAHIALgBhAHAAcAAPABoADABNAGEAYwBpAG4AdABvAHMAaAAgAEgARAASADZBcHBsaWNhdGlvbnMvU3R1ZmZJdCBTdGFuZGFyZCA5LjAvU3R1ZmZJdCBFeHBhbmRlci5hcHAAEwABLwD//wAA", 2, // For the new columns added, check for null or default values 0, ]; // Make sure the values are correct after the migration var i = 0; do_check_eq(data[i], stmt.getString(i++)); do_check_eq(data[i], stmt.getUTF8String(i++)); do_check_eq(data[i], stmt.getUTF8String(i++)); do_check_eq(data[i], stmt.getString(i++)); do_check_eq(data[i], stmt.getInt64(i++)); do_check_eq(data[i], stmt.getInt64(i++)); do_check_eq(data[i], stmt.getInt32(i++)); do_check_eq(data[i], stmt.getUTF8String(i++)); do_check_eq(data[i], stmt.getUTF8String(i++)); do_check_eq(data[i], stmt.getInt64(i++)); do_check_eq(data[i], stmt.getInt64(i++)); do_check_eq(data[i], stmt.getUTF8String(i++)); do_check_eq(data[i], stmt.getUTF8String(i++)); do_check_eq(data[i], stmt.getInt32(i++)); do_check_eq(data[i], stmt.getInt32(i++)); stmt.reset(); stmt.finalize(); cleanup(); }
sergecodd/FireFox-OS
B2G/gecko/toolkit/components/downloads/test/schema_migration/test_migration_to_8.js
JavaScript
apache-2.0
3,203
/* * 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 models = require('./index'); /** * Parameters supplied to the Create or Update Event Source operation for an * EventHub event source. * * @extends models['EventSourceCreateOrUpdateParameters'] */ class EventHubEventSourceCreateOrUpdateParameters extends models['EventSourceCreateOrUpdateParameters'] { /** * Create a EventHubEventSourceCreateOrUpdateParameters. * @member {string} [provisioningState] Provisioning state of the resource. * Possible values include: 'Accepted', 'Creating', 'Updating', 'Succeeded', * 'Failed', 'Deleting' * @member {date} [creationTime] The time the resource was created. * @member {string} [timestampPropertyName] The event property that will be * used as the event source's timestamp. If a value isn't specified for * timestampPropertyName, or if null or empty-string is specified, the event * creation time will be used. * @member {string} eventSourceResourceId The resource id of the event source * in Azure Resource Manager. * @member {string} serviceBusNamespace The name of the service bus that * contains the event hub. * @member {string} eventHubName The name of the event hub. * @member {string} consumerGroupName The name of the event hub's consumer * group that holds the partitions from which events will be read. * @member {string} keyName The name of the SAS key that grants the Time * Series Insights service access to the event hub. The shared access * policies for this key must grant 'Listen' permissions to the event hub. * @member {string} sharedAccessKey The value of the shared access key that * grants the Time Series Insights service read access to the event hub. This * property is not shown in event source responses. */ constructor() { super(); } /** * Defines the metadata of EventHubEventSourceCreateOrUpdateParameters * * @returns {object} metadata of EventHubEventSourceCreateOrUpdateParameters * */ mapper() { return { required: false, serializedName: 'Microsoft.EventHub', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'kind', clientName: 'kind' }, uberParent: 'CreateOrUpdateTrackedResourceProperties', className: 'EventHubEventSourceCreateOrUpdateParameters', modelProperties: { location: { required: true, serializedName: 'location', type: { name: 'String' } }, tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, kind: { required: true, serializedName: 'kind', isPolymorphicDiscriminator: true, type: { name: 'String' } }, provisioningState: { required: false, serializedName: 'properties.provisioningState', type: { name: 'Enum', allowedValues: [ 'Accepted', 'Creating', 'Updating', 'Succeeded', 'Failed', 'Deleting' ] } }, creationTime: { required: false, readOnly: true, serializedName: 'properties.creationTime', type: { name: 'DateTime' } }, timestampPropertyName: { required: false, serializedName: 'properties.timestampPropertyName', type: { name: 'String' } }, eventSourceResourceId: { required: true, serializedName: 'properties.eventSourceResourceId', type: { name: 'String' } }, serviceBusNamespace: { required: true, serializedName: 'properties.serviceBusNamespace', type: { name: 'String' } }, eventHubName: { required: true, serializedName: 'properties.eventHubName', type: { name: 'String' } }, consumerGroupName: { required: true, serializedName: 'properties.consumerGroupName', type: { name: 'String' } }, keyName: { required: true, serializedName: 'properties.keyName', type: { name: 'String' } }, sharedAccessKey: { required: true, serializedName: 'properties.sharedAccessKey', type: { name: 'String' } } } } }; } } module.exports = EventHubEventSourceCreateOrUpdateParameters;
xingwu1/azure-sdk-for-node
lib/services/timeseriesinsightsManagement/lib/models/eventHubEventSourceCreateOrUpdateParameters.js
JavaScript
apache-2.0
5,409
/** * @license * Copyright 2015 Google Inc. 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 */ CLASS({ package: 'foam.apps.builder.wizard', name: 'NewOrExistingDAOWizard', extends: 'foam.apps.builder.wizard.NewOrExistingWizard', requires: [ 'foam.apps.builder.wizard.NewDAOWizard', 'foam.apps.builder.dao.DAOFactory', ], imports: [ 'daoConfigDAO as unfilteredExistingDAO', ], exports: [ 'selection$' ], properties: [ { name: 'newViewFactory', label: 'Create a new Data Source', defaultValue: { factory_: 'foam.apps.builder.wizard.NewDAOWizard' }, }, { name: 'existingViewFactory', label: 'Use an existing Data Source', defaultValue: null, }, { name: 'nextViewFactory', lazyFactory: function() { return this.newViewFactory; }, }, { name: 'selection', }, { name: 'unfilteredExistingDAO', postSet: function(old, nu) { if ( this.data ) { this.filterExistingDAO(); } else { this.data$.addListener(EventService.oneTime(this.filterExistingDAO)); } } }, { name: 'existingDAO', view: { factory_: 'foam.ui.md.DAOListView', rowView: 'foam.apps.builder.dao.DAOFactoryView', } } ], listeners: [ { name: 'filterExistingDAO', code: function() { this.existingDAO = this.unfilteredExistingDAO; // .where( // EQ(this.DAOFactory.MODEL_TYPE, this.data.baseModelId) // ); } }, ], methods: [ function onNext() { if ( this.selection && this.nextViewFactory === this.existingViewFactory ) { this.data.getDataConfig().dao = this.selection; } if ( this.nextViewFactory === this.newViewFactory ) { this.data.resetDAO(); } this.SUPER(); }, ], });
mdittmer/foam
js/foam/apps/builder/wizard/NewOrExistingDAOWizard.js
JavaScript
apache-2.0
2,095
/** * @license * Copyright 2014 The Lovefield Project 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. */ goog.provide('lf.proc.Database'); goog.require('lf.Database'); goog.require('lf.Exception'); goog.require('lf.base'); goog.require('lf.proc.ExportTask'); goog.require('lf.proc.ImportTask'); goog.require('lf.proc.Transaction'); goog.require('lf.query.DeleteBuilder'); goog.require('lf.query.InsertBuilder'); goog.require('lf.query.SelectBuilder'); goog.require('lf.query.UpdateBuilder'); goog.require('lf.service'); /** * @implements {lf.Database} * @constructor @struct * @export * * @param {!lf.Global} global */ lf.proc.Database = function(global) { /** @private {!lf.Global} */ this.global_ = global; /** @private {!lf.schema.Database} */ this.schema_ = global.getService(lf.service.SCHEMA); /** * Whether this connection to the database is active. * @private {boolean} */ this.isActive_ = false; /** @private {!lf.proc.Runner} */ this.runner_; }; /** * @param {!lf.schema.ConnectOptions=} opt_options * @return {!IThenable<!lf.proc.Database>} * @export */ lf.proc.Database.prototype.init = function(opt_options) { // The SCHEMA might have been removed from this.global_ in the case where // lf.proc.Database#close() was called, therefore it needs to be re-added. this.global_.registerService(lf.service.SCHEMA, this.schema_); return /** @type {!IThenable<!lf.proc.Database>} */ ( lf.base.init(this.global_, opt_options).then(function() { this.isActive_ = true; this.runner_ = this.global_.getService(lf.service.RUNNER); return this; }.bind(this))); }; /** @override @export */ lf.proc.Database.prototype.getSchema = function() { return this.schema_; }; /** @private */ lf.proc.Database.prototype.checkActive_ = function() { if (!this.isActive_) { // 2: The database connection is not active. throw new lf.Exception(2); } }; /** @override @export */ lf.proc.Database.prototype.select = function(var_args) { this.checkActive_(); var columns = arguments.length == 1 && !goog.isDefAndNotNull(arguments[0]) ? [] : Array.prototype.slice.call(arguments); return new lf.query.SelectBuilder(this.global_, columns); }; /** @override @export */ lf.proc.Database.prototype.insert = function() { this.checkActive_(); return new lf.query.InsertBuilder(this.global_); }; /** @override @export */ lf.proc.Database.prototype.insertOrReplace = function() { this.checkActive_(); return new lf.query.InsertBuilder(this.global_, /* allowReplace */ true); }; /** @override @export */ lf.proc.Database.prototype.update = function(table) { this.checkActive_(); return new lf.query.UpdateBuilder(this.global_, table); }; /** @override @export */ lf.proc.Database.prototype.delete = function() { this.checkActive_(); return new lf.query.DeleteBuilder(this.global_); }; /** @override @export */ lf.proc.Database.prototype.observe = function(query, callback) { this.checkActive_(); var observerRegistry = this.global_.getService( lf.service.OBSERVER_REGISTRY); observerRegistry.addObserver(query, callback); }; /** @override @export */ lf.proc.Database.prototype.unobserve = function(query, callback) { this.checkActive_(); var observerRegistry = this.global_.getService( lf.service.OBSERVER_REGISTRY); observerRegistry.removeObserver(query, callback); }; /** @override @export */ lf.proc.Database.prototype.createTransaction = function(opt_type) { this.checkActive_(); return new lf.proc.Transaction(this.global_); }; /** @override @export */ lf.proc.Database.prototype.close = function() { lf.base.closeDatabase(this.global_); this.global_.clear(); this.isActive_ = false; }; /** @override @export */ lf.proc.Database.prototype.export = function() { this.checkActive_(); var task = new lf.proc.ExportTask(this.global_); return this.runner_.scheduleTask(task).then(function(results) { return results[0].getPayloads()[0]; }); }; /** @override @export */ lf.proc.Database.prototype.import = function(data) { this.checkActive_(); var task = new lf.proc.ImportTask(this.global_, data); return this.runner_.scheduleTask(task).then(function() { return null; }); }; /** @return {boolean} */ lf.proc.Database.prototype.isOpen = function() { return this.isActive_; };
ralic/lovefield
lib/proc/database.js
JavaScript
apache-2.0
4,910
"use strict"; var exec = require( "child_process" ).exec; module.exports = function( grunt ) { grunt.registerTask( "version", "Commit a new version", function( version ) { if ( !/\d\.\d+\.\d+/.test( version ) ) { grunt.fatal( "Version must follow semver release format: " + version ); return; } var done = this.async(), files = grunt.config( "version.files" ), rversion = /("version":\s*")[^"]+/; // Update version in specified files files.forEach(function( filename ) { var text = grunt.file.read( filename ); text = text.replace( rversion, "$1" + version ); grunt.file.write( filename, text ); }); // Add files to git index exec( "git add -A", function( err ) { if ( err ) { grunt.fatal( err ); return; } // Commit next pre version grunt.config( "pkg.version", version ); grunt.task.run([ "build", "bower", "test", "commit:'Update version to " + version + "'" ]); done(); }); }); };
thinq4yourself/labster-landing-material-proto
bower_components/detectizr/tasks/version.js
JavaScript
apache-2.0
956
var overlays = (function () { var exports = {}; var active_overlay; var close_handler; var open_overlay_name; function reset_state() { active_overlay = undefined; close_handler = undefined; open_overlay_name = undefined; } exports.is_active = function () { return !!open_overlay_name; }; exports.is_modal_open = function () { return $(".modal").hasClass("in"); }; exports.info_overlay_open = function () { return open_overlay_name === 'informationalOverlays'; }; exports.settings_open = function () { return open_overlay_name === 'settings'; }; exports.streams_open = function () { return open_overlay_name === 'subscriptions'; }; exports.lightbox_open = function () { return open_overlay_name === 'lightbox'; }; exports.active_modal = function () { if (!exports.is_modal_open()) { blueslip.error("Programming error — Called open_modal when there is no modal open"); return; } return $(".modal.in").attr("id"); }; exports.open_overlay = function (opts) { if (!opts.name || !opts.overlay || !opts.on_close) { blueslip.error('Programming error in open_overlay'); return; } if (active_overlay || open_overlay_name || close_handler) { blueslip.error('Programming error--trying to open ' + opts.name + ' before closing ' + open_overlay_name); return; } blueslip.debug('open overlay: ' + opts.name); // Our overlays are kind of crufty...we have an HTML id // attribute for them and then a data-overlay attribute for // them. Make sure they match. if (opts.overlay.attr('data-overlay') !== opts.name) { blueslip.error('Bad overlay setup for ' + opts.name); return; } open_overlay_name = opts.name; active_overlay = opts.overlay; opts.overlay.addClass('show'); opts.overlay.attr("aria-hidden", "false"); $('.app').attr("aria-hidden", "true"); $('.fixed-app').attr("aria-hidden", "true"); $('.header').attr("aria-hidden", "true"); close_handler = function () { opts.on_close(); reset_state(); }; }; exports.open_modal = function (name) { if (name === undefined) { blueslip.error('Undefined name was passed into open_modal'); return; } if (exports.is_modal_open()) { blueslip.error('open_modal() was called while ' + exports.active_modal() + ' modal was open.'); return; } blueslip.debug('open modal: ' + name); $("#" + name).modal("show").attr("aria-hidden", false); }; exports.close_overlay = function (name) { if (name !== open_overlay_name) { blueslip.error("Trying to close " + name + " when " + open_overlay_name + " is open." ); return; } if (name === undefined) { blueslip.error('Undefined name was passed into close_overlay'); return; } blueslip.debug('close overlay: ' + name); active_overlay.removeClass("show"); active_overlay.attr("aria-hidden", "true"); $('.app').attr("aria-hidden", "false"); $('.fixed-app').attr("aria-hidden", "false"); $('.header').attr("aria-hidden", "false"); if (!close_handler) { blueslip.error("Overlay close handler for " + name + " not properly setup." ); return; } close_handler(); }; exports.close_active = function () { if (!open_overlay_name) { blueslip.warn('close_active() called without checking is_active()'); return; } exports.close_overlay(open_overlay_name); }; exports.close_modal = function (name) { if (name === undefined) { blueslip.error('Undefined name was passed into close_modal'); return; } if (!exports.is_modal_open()) { blueslip.warn('close_active_modal() called without checking is_modal_open()'); return; } if (exports.active_modal() !== name) { blueslip.error("Trying to close " + name + " modal when " + exports.active_modal() + " is open." ); return; } blueslip.debug('close modal: ' + name); $("#" + name).modal("hide").attr("aria-hidden", true); }; exports.close_active_modal = function () { if (!exports.is_modal_open()) { blueslip.warn('close_active_modal() called without checking is_modal_open()'); return; } $(".modal.in").modal("hide").attr("aria-hidden", true); }; exports.close_for_hash_change = function () { $(".overlay.show").removeClass("show"); reset_state(); }; exports.open_settings = function () { overlays.open_overlay({ name: 'settings', overlay: $("#settings_overlay_container"), on_close: function () { hashchange.exit_overlay(); }, }); }; $(function () { $("body").on("click", ".overlay, .overlay .exit", function (e) { var $target = $(e.target); // if the target is not the .overlay element, search up the node tree // until it is found. if ($target.is(".exit, .exit-sign, .overlay-content, .exit span")) { $target = $target.closest("[data-overlay]"); } else if (!$target.is(".overlay")) { // not a valid click target then. return; } var target_name = $target.attr("data-overlay"); exports.close_overlay(target_name); e.preventDefault(); e.stopPropagation(); }); }); return exports; }()); if (typeof module !== 'undefined') { module.exports = overlays; }
verma-varsha/zulip
static/js/overlays.js
JavaScript
apache-2.0
5,509
/** * Copyright 2015 The AMP HTML 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. */ import {AmpAudio} from '../amp-audio'; import {naturalDimensions_} from '../../../../src/static-layout'; describes.realWin( 'amp-audio', { amp: { extensions: ['amp-audio'], }, }, (env) => { let win, doc; let ampAudio; beforeEach(() => { win = env.win; doc = win.document; }); function getAmpAudio(attributes, opt_childNodesAttrs) { ampAudio = doc.createElement('amp-audio'); for (const key in attributes) { ampAudio.setAttribute(key, attributes[key]); } if (opt_childNodesAttrs) { opt_childNodesAttrs.forEach((childNodeAttrs) => { let child; if (childNodeAttrs.tag === 'text') { child = doc.createTextNode(childNodeAttrs.text); } else { child = doc.createElement(childNodeAttrs.tag); for (const key in childNodeAttrs) { if (key !== 'tag') { child.setAttribute(key, childNodeAttrs[key]); } } } ampAudio.appendChild(child); }); } doc.body.appendChild(ampAudio); return ampAudio; } function attachAndRun(attributes, opt_childNodesAttrs) { naturalDimensions_['AMP-AUDIO'] = {width: '300px', height: '30px'}; const ampAudio = getAmpAudio(attributes, opt_childNodesAttrs); return ampAudio .buildInternal() .then(() => ampAudio.layoutCallback()) .then(() => ampAudio) .catch((error) => { // Ignore failed to load errors since sources are fake. if (error.toString().indexOf('Failed to load') > -1) { return ampAudio; } else { throw error; } }); } function attachToAmpStoryAndRun(attributes) { naturalDimensions_['AMP-AUDIO'] = {width: '300px', height: '30px'}; const ampAudio = doc.createElement('amp-audio'); const ampStory = doc.createElement('amp-story'); for (const key in attributes) { ampAudio.setAttribute(key, attributes[key]); } ampStory.appendChild(ampAudio); doc.body.appendChild(ampStory); return ampAudio .buildInternal() .then(() => ampAudio.layoutCallback()) .then(() => ampAudio) .catch((error) => { // Ignore failed to load errors since sources are fake. if (error.toString().indexOf('Failed to load') > -1) { return ampAudio; } else { throw error; } }); } it('should load audio through attribute', () => { return attachAndRun({ src: 'audio.mp3', }).then((a) => { const audio = a.querySelector('audio'); expect(audio.tagName).to.equal('AUDIO'); expect(audio.getAttribute('src')).to.equal('audio.mp3'); expect(audio.hasAttribute('controls')).to.be.true; expect(a.style.width).to.be.equal('300px'); expect(a.style.height).to.be.equal('30px'); }); }); it('should not preload audio', () => { return attachAndRun({ src: 'audio.mp3', preload: 'none', }).then((a) => { const audio = a.querySelector('audio'); expect(audio.getAttribute('preload')).to.be.equal('none'); }); }); it('should only preload audio metadata', () => { return attachAndRun({ src: 'audio.mp3', preload: 'metadata', }).then((a) => { const audio = a.querySelector('audio'); expect(audio.getAttribute('preload')).to.be.equal('metadata'); }); }); it( 'should attach `<audio>` element and execute relevant actions for ' + 'layout="nodisplay"', async () => { const ampAudio = await attachAndRun({ src: 'audio.mp3', preload: 'none', layout: 'nodisplay', }); const impl = await ampAudio.getImpl(); const audio = ampAudio.querySelector('audio'); expect(audio).to.not.be.null; impl.executeAction({method: 'play', satisfiesTrust: () => true}); expect(impl.isPlaying).to.be.true; impl.executeAction({method: 'pause', satisfiesTrust: () => true}); expect(impl.isPlaying).to.be.false; } ); it('should load audio through sources', () => { return attachAndRun( { width: 503, height: 53, autoplay: '', preload: '', muted: '', loop: '', }, [ {tag: 'source', src: 'audio.mp3', type: 'audio/mpeg'}, {tag: 'source', src: 'audio.ogg', type: 'audio/ogg'}, {tag: 'text', text: 'Unsupported.'}, ] ).then((a) => { const audio = a.querySelector('audio'); expect(audio.tagName).to.equal('AUDIO'); expect(a.getAttribute('width')).to.be.equal('503'); expect(a.getAttribute('height')).to.be.equal('53'); expect(audio.offsetWidth).to.be.greaterThan(1); expect(audio.offsetHeight).to.be.greaterThan(1); expect(audio.hasAttribute('controls')).to.be.true; expect(audio.hasAttribute('autoplay')).to.be.true; expect(audio.hasAttribute('muted')).to.be.true; expect(audio.hasAttribute('preload')).to.be.true; expect(audio.hasAttribute('loop')).to.be.true; expect(audio.hasAttribute('src')).to.be.false; expect(audio.childNodes[0].tagName).to.equal('SOURCE'); expect(audio.childNodes[0].getAttribute('src')).to.equal('audio.mp3'); expect(audio.childNodes[1].tagName).to.equal('SOURCE'); expect(audio.childNodes[1].getAttribute('src')).to.equal('audio.ogg'); expect(audio.childNodes[2].nodeType).to.equal(Node.TEXT_NODE); expect(audio.childNodes[2].textContent).to.equal('Unsupported.'); }); }); it('should set its dimensions to the browser natural', () => { return attachAndRun({ src: 'audio.mp3', }).then((a) => { const audio = a.querySelector('audio'); expect(a.style.width).to.be.equal('300px'); expect(a.style.height).to.be.equal('30px'); if (/Safari|Firefox/.test(navigator.userAgent)) { // Safari has default sizes for audio tags that cannot // be overridden. return; } expect(audio.offsetWidth).to.be.equal(300); expect(audio.offsetHeight).to.be.equal(30); }); }); it('should set its natural dimension only if not specified', () => { return attachAndRun({ 'width': '500', src: 'audio.mp3', }).then((a) => { expect(a.style.width).to.be.equal('500px'); expect(a.style.height).to.be.equal('30px'); }); }); it('should fallback when not available', () => { // For this single test, cause audio elements that are // created to lack the necessary feature set, which should trigger // fallback behavior. const {createElement} = doc; doc.createElement = (name) => { if (name === 'audio') { name = 'busted-audio'; } return createElement.call(doc, name); }; const element = doc.createElement('div'); element.toggleFallback = env.sandbox.spy(); const audio = new AmpAudio(element); audio.buildAudioElement(); expect(element.toggleFallback).to.be.calledOnce; }); it('should propagate ARIA attributes', () => { return attachAndRun({ src: 'audio.mp3', 'aria-label': 'Hello', 'aria-labelledby': 'id2', 'aria-describedby': 'id3', }).then((a) => { const audio = a.querySelector('audio'); expect(audio.getAttribute('aria-label')).to.equal('Hello'); expect(audio.getAttribute('aria-labelledby')).to.equal('id2'); expect(audio.getAttribute('aria-describedby')).to.equal('id3'); }); }); it('should play/pause when `play`/`pause` actions are called', async () => { const ampAudio = await attachAndRun({ 'width': '500', src: 'audio.mp3', }); const impl = await ampAudio.getImpl(); impl.executeAction({method: 'play', satisfiesTrust: () => true}); expect(impl.isPlaying).to.be.true; impl.executeAction({method: 'pause', satisfiesTrust: () => true}); expect(impl.isPlaying).to.be.false; }); it( 'should not play/pause when `amp-audio` is a direct descendant ' + 'of `amp-story`', async () => { const ampAudio = await attachToAmpStoryAndRun({ 'width': '500', src: 'audio.mp3', }); const impl = await ampAudio.getImpl(); impl.executeAction({method: 'play', satisfiesTrust: () => true}); expect(impl.isPlaying).to.be.false; impl.executeAction({method: 'pause', satisfiesTrust: () => true}); expect(impl.isPlaying).to.be.false; } ); } );
rsimha-amp/amphtml
extensions/amp-audio/0.1/test/test-amp-audio.js
JavaScript
apache-2.0
9,546
/** * cbpAnimatedHeader.js v1.0.0 * http://www.codrops.com * * Licensed under the MIT license. * http://www.opensource.org/licenses/mit-license.php * * Copyright 2013, Codrops * http://www.codrops.com */ var cbpAnimatedHeader = (function() { var docElem = document.documentElement, header = document.querySelector( '.navbar-fixed-top' ), didScroll = false, changeHeaderOn = 100; function init() { window.addEventListener( 'scroll', function( event ) { if( !didScroll ) { didScroll = true; setTimeout( scrollPage, 50 ); } }, false ); } function scrollPage() { var sy = scrollY(); if ( sy >= changeHeaderOn ) { classie.add( header, 'navbar-shrink' ); } else { classie.remove( header, 'navbar-shrink' ); } didScroll = false; } function scrollY() { return window.pageYOffset || docElem.scrollTop; } init(); })();
ConceptHaus/Maniac
js/cbpAnimatedHeader.js
JavaScript
apache-2.0
876
var indexerLanguage="en"; //Auto generated index for searching. w["-"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["-31011"]="57"; w["-5level"]="69"; w["-day"]="30"; w["-demand"]="112"; w["-djava"]="107"; w["-flight"]="32,97"; w["-integ"]="85"; w["-ip"]="72"; w["-ip_address"]="85"; w["-mac-address"]="112"; w["-memori"]="17,104"; w["-port"]="21,24,58,63,85"; w["-q"]="72"; w["-u"]="100"; w["0"]="2,9,10,11,12,15,18,19,21,23,24,25,32,35,36,40,41,43,44,47,49,50,54,56,57,63,68,75,79,82,85,93,95,99,100,101,103,104,106,110,111"; w["00"]="12,36,75,101,103"; w["0000"]="12,85"; w["01"]="12"; w["0100"]="12"; w["02"]="2,15,47,49,75,93,111"; w["037b382a5706483a822d0f7b3b2a9555"]="111"; w["04"]="107"; w["05"]="103"; w["07"]="41,68,75"; w["08"]="47,49,75,93"; w["0a"]="75"; w["0a1bf57198074c779894776a9d002146"]="111"; w["0b"]="75"; w["0d"]="15,111"; w["0f"]="15,111"; w["1"]="1,2,5,9,12,15,18,21,23,24,25,35,36,39,41,43,46,47,49,50,54,57,58,63,68,75,79,82,85,91,93,96,97,100,101,103,105,106,109,111,112,115"; w["1-192"]="58"; w["10"]="6,23,25,31,36,40,43,47,49,50,54,58,63,75,82,85,93,100,101,106,107,112"; w["100"]="2,5,9,15,21,40,47,49,50,54,58,63,79,82,93,94,111,113"; w["1000"]="85,112"; w["10000"]="112"; w["101"]="5"; w["102"]="5"; w["104"]="94"; w["10a83af63f9342118433c3a43a329528"]="23,43"; w["11"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["111"]="75"; w["112"]="8,11,37,59,92"; w["113"]="15"; w["119"]="8,11,37,59,87,92"; w["12"]="12,32,75,103"; w["120"]="87"; w["122"]="75"; w["123"]="87"; w["12345678-90123456-123456789012"]="75"; w["127"]="36,75,101,103"; w["128"]="49,97"; w["13"]="22,27,91"; w["14"]="72,107"; w["143"]="8,59"; w["144"]="8"; w["15"]="1,8,11,37,39,59,87,92"; w["150"]="54,58,63"; w["1500"]="36,75,101,103,106"; w["15000"]="112"; w["152"]="75"; w["1536m"]="97"; w["16"]="15,21,23,29,40,41,43,57,68,72,79,85,97,103,106,111"; w["161"]="75"; w["16436"]="75"; w["16509"]="98"; w["168"]="5,9,10,15,28,58,75,94,103,106,111"; w["169"]="2,40,50,79,82,111"; w["17"]="28,62,85,97"; w["172"]="15,19,21,40,41,57,68,79,106,111"; w["179"]="114"; w["18"]="84"; w["1800"]="112"; w["19"]="19,41,49,68"; w["192"]="5,9,10,15,58,75,94,103,106"; w["198"]="2,21,54,58,63"; w["1b"]="75"; w["1b89"]="75"; w["1d475afc-d892-4dc7-af72-9bd88e565dd"]="11"; w["1q"]="72"; w["2"]="2,11,12,15,19,21,23,24,25,27,35,36,38,40,41,43,49,50,54,55,56,57,63,68,72,75,79,82,85,97,99,100,101,105,106"; w["2-3"]="25,112"; w["200"]="15,36,101,111"; w["2000"]="75"; w["2014"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["203"]="15"; w["2034"]="75"; w["2048"]="23,24,35,41,43,57,68"; w["2048m"]="97"; w["2054"]="41,68"; w["21"]="2"; w["2181"]="5,48"; w["22"]="8,11,35,37,41,59,75,92"; w["24"]="2,15,21,23,40,43,47,49,54,63,75,79,93,111"; w["24-bit"]="72"; w["250"]="36,101"; w["2500"]="31"; w["254"]="2,40,50,58,79,82,111"; w["255"]="2,50,79,82,111"; w["256"]="97"; w["2606"]="114"; w["27017"]="42"; w["2888"]="48"; w["28c40ac757e746f08747cdb32a83c40b"]="111"; w["2a"]="15,106,111"; w["3"]="2,10,21,24,25,35,36,40,41,43,50,57,68,72,74,79,82,101,103,106,112,115"; w["30"]="2,15,50,82,111,112"; w["30000"]="5,112"; w["32"]="9,15,40,97"; w["32-bit"]="40"; w["3306"]="42"; w["34"]="2,12,75"; w["35"]="36,101"; w["35357"]="42,94"; w["3600"]="112"; w["3888"]="48"; w["3d"]="15,111"; w["3e"]="41,68,103"; w["3eff"]="103"; w["4"]="10,24,35,41,46,49,54,58,63,68,78,97,110,115"; w["40"]="103"; w["400"]="8,87"; w["4096"]="72"; w["41"]="15,111"; w["42"]="75"; w["439"]="11"; w["46"]="15,75,111"; w["47"]="75"; w["48-bit"]="85"; w["49"]="2,15,111"; w["4d"]="36,101"; w["4e"]="75"; w["4f"]="103"; w["5"]="1,10,23,28,39,41,43,56,68,108,112"; w["50"]="13,32,36,101,113"; w["500"]="8,31,85,113"; w["5000"]="42,112"; w["51"]="2,21,54,58,63"; w["5120m"]="97"; w["54"]="75"; w["54ff"]="75"; w["56"]="12,36,101"; w["5672"]="42"; w["56ff"]="36,101"; w["590"]="103"; w["5900"]="35,41,98"; w["5b"]="49"; w["5d"]="47,49,93"; w["5e"]="103"; w["5f"]="49"; w["6"]="4,10,24,35,41,85"; w["6-3ubuntu3"]="115"; w["60"]="36,75,101,112"; w["6000"]="42"; w["6001"]="42"; w["6002"]="42"; w["6080"]="42"; w["6144m"]="97"; w["62"]="2"; w["64"]="97"; w["64512"]="75"; w["64513"]="75"; w["65"]="75"; w["65536"]="36,101,103"; w["6632"]="106"; w["6633"]="37,87"; w["68"]="15,111"; w["6a"]="75"; w["6b"]="15,111"; w["6c"]="75,106"; w["6e"]="103"; w["6f"]="75"; w["7"]="6,70,85,107"; w["70"]="36,101"; w["7000"]="48"; w["7001"]="48"; w["7071b156-5f05-4d8c-8df2-3bb22a9325fc"]="11"; w["7199"]="48,104"; w["72"]="24"; w["7200"]="98,114"; w["75"]="97"; w["765cf657-3cf4-4d79-9621-7d71af38a298"]="106"; w["777"]="11"; w["78"]="12"; w["7a"]="75"; w["7a4937fa604a425e867f085427cc351"]="111"; w["7b"]="103"; w["7b5e"]="103"; w["7c"]="36,101"; w["7c35"]="36,101"; w["7cf9"]="75"; w["7e"]="75"; w["8"]="1,20,39"; w["80"]="9,15,24,35,41,42,58"; w["80-88"]="58"; w["8004"]="42"; w["8005"]="42"; w["8009"]="42"; w["802"]="72"; w["8080"]="9,15,42,64"; w["81"]="47,49,93"; w["85"]="15,111"; w["87"]="15,49,111"; w["8773"]="42"; w["8774"]="42"; w["8775"]="42"; w["8776"]="42"; w["8777"]="42"; w["88"]="75"; w["8842"]="103"; w["89"]="2,15,75,111"; w["8e"]="36,101"; w["8ff"]="75"; w["8th"]="12"; w["9"]="40,110"; w["90"]="12,103"; w["9042"]="48"; w["908"]="11"; w["9082e813-38f1-4795-8844-8fc35ec00000"]="8"; w["9082e813-38f1-4795-8844-8fc35ec0b19b"]="8"; w["91"]="75"; w["9160"]="48"; w["9191"]="42"; w["9199"]="17"; w["9292"]="42"; w["93"]="36,101"; w["9696"]="42"; w["98"]="75"; w["9a"]="103"; w["9aff"]="103"; w["9b"]="49"; w["9e"]="106"; w["9eff"]="106"; w["9f"]="15,111"; w["_mn"]="46"; w["_ns"]="114"; w["a1"]="75"; w["a16f"]="75"; w["a4"]="36,75,101"; w["a6"]="47,49,93"; w["a8"]="15,111"; w["aa"]="106"; w["aa6c"]="106"; w["ab"]="12,47,49,93"; w["abl"]="13,15,32,46,52,57,71,75,106,112"; w["abov"]="0,2,10,21,23,24,32,35,36,41,43,44,47,49,50,54,55,63,69,80,82,83,90,93,100,103,112"; w["abstract"]="49,51,78"; w["accept"]="7,12,16,21,23,24,28,35,41,43,54,57,58,63,64,68,81,85,97,109"; w["accept_src_dst_mynetwork_inbound"]="43"; w["access"]="0,6,16,23,38,43,47,55,64,70,71,77,94,104,105,112"; w["accommod"]="112"; w["accomplish"]="9,23,75"; w["accord"]="17,35,39,41,112"; w["account"]="15,17,24,110"; w["accumul"]="32,97"; w["achiev"]="15"; w["ack"]="104"; w["across"]="13,51,104"; w["act"]="7,15,34,46,102"; w["action"]="0,7,16,18,21,26,40,54,58,63,81,85,95,100,109,112"; w["activ"]="0,9,34,39,75,104"; w["actor"]="97"; w["actual"]="64"; w["ad"]="3,4,8,15,18,23,43,47,49,50,71,78,80,82,86,87,90,93,100,106,111,115"; w["ad-rout"]="75"; w["ad-route0"]="75"; w["add"]="1,6,8,9,12,15,19,23,24,36,39,43,46,47,54,55,57,58,63,71,75,80,82,87,100,101,104,106,110,111"; w["addit"]="0,27,31,34,35,41,46,51,60,73,104,106,110"; w["address"]="2,6,9,10,12,13,15,16,17,19,20,21,24,28,29,32,36,37,39,40,41,47,49,51,52,54,57,58,63,68,75,79,82,85,86,87,88,92,93,100,101,103,106,109,110,111,112"; w["adjust"]="112"; w["admin"]="2,55,64,75,77,94,105,111"; w["admin_state_up"]="65,113"; w["administr"]="40,55,99"; w["admit"]="36,53,74"; w["advanc"]="62,64"; w["advantag"]="51,72"; w["advert"]="96"; w["advertis"]="75"; w["advis"]="56"; w["aff"]="75"; w["affect"]="7,30,97"; w["after"]="5,16,26,34,46,56,71,74,75,95,104,112"; w["afterward"]="0"; w["again"]="8,13,40"; w["against"]="7,15,24,32,85"; w["agent"]="0,22,27,29,30,32,46,56,60,62,74,89,91,95,97,98,99,104,112,114"; w["aggreg"]="104"; w["agnost"]="24"; w["agre"]="17"; w["ahead"]="57"; w["aim"]="0"; w["akka"]="97"; w["algorithm"]="40"; w["alia"]="12,19,24,36,44,45,47,61,80,83,90"; w["alias"]="10,75"; w["aliv"]="34,36,61,75,101,103,106"; w["all"]="0,8,9,11,12,13,16,17,24,28,29,32,34,35,36,38,39,40,41,43,46,50,51,55,56,65,71,74,76,85,94,97,100,104,106,109,110,112,115"; w["allevi"]="0"; w["alloc"]="32,97"; w["allow"]="6,9,11,23,24,31,41,43,46,51,55,57,64,68,71,74,85,96,97,104,105"; w["almost"]="104"; w["along"]="99"; w["alongsid"]="32"; w["alreadi"]="8,16,28,35,41,68,81,85,86,87"; w["also"]="0,17,28,32,38,39,40,51,56,67,70,71,85,97,100,104,112"; w["alt_demo"]="111"; w["altern"]="76,85"; w["although"]="38"; w["alway"]="51"; w["among"]="32,104"; w["amount"]="0,34,97,104,112"; w["and"]="0,1,2,3,4,5,6,7,8,9,10,11,13,15,16,17,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,38,39,40,41,43,45,46,47,49,50,51,52,53,54,55,56,57,58,60,62,63,64,68,70,71,72,73,74,75,78,79,81,83,84,85,86,87,88,90,93,94,95,96,97,99,100,102,104,105,106,108,109,110,111,112,113,115"; w["ani"]="0,2,11,15,16,17,24,35,39,40,41,46,51,67,75,76,79,81,82,85,86,100,105,106,113"; w["anoth"]="0,7,8,16,17,24,32,33,47,49,72,85"; w["anti-entropi"]="104"; w["apach"]="17,107"; w["apart"]="16,71"; w["api"]="6,26,27,29,30,38,55,62,64,71,77,81,89,91,94,105,107,110,112,113"; w["api_1"]="110"; w["appear"]="0,17,56,75,100,104"; w["append"]="46,100"; w["appli"]="0,16,24,32,40,51,55,58,71,78,85,104,109,110,112"; w["applic"]="0,24,38,77,94"; w["appropri"]="1,15,17,38,39"; w["approximatedatas"]="17"; w["architectur"]="102"; w["aren"]="62"; w["argument"]="24,85"; w["arp"]="12,40,41,68,109,112"; w["arp-suppression-t"]="52"; w["arp_expiration_second"]="112"; w["arp_retry_interval_second"]="112"; w["arp_stale_second"]="112"; w["arp_timeout_second"]="112"; w["arptabl"]="112"; w["ask"]="104"; w["assign"]="8,10,11,15,23,34,36,43,44,45,47,49,51,56,71,80,83,88,90,106,110"; w["associ"]="0,13,14,16,18,21,24,26,32,46,86,95,96,110"; w["assum"]="1,13,21,41,43,56,88,100,111"; w["assumpt"]="21,41,54,63,88"; w["asynchron"]="60"; w["attach"]="46,47,110,113"; w["attack"]="32,82"; w["attempt"]="40"; w["attend"]="104"; w["attribut"]="6,7,23,43,81,82,85,92"; w["auth"]="77,94,105"; w["auth-admin-rol"]="55"; w["auth-admin_rol"]="55,94"; w["auth-auth_provid"]="77,94"; w["auth-tenant-admin"]="55"; w["auth-tenant_admin_rol"]="55,64"; w["auth-tenant_user_rol"]="55,64"; w["authent"]="38,64,66,77,94,105"; w["author"]="38,55,105"; w["authrol"]="55"; w["auto-complet"]="28"; w["auto-gener"]="75"; w["autom"]="100,115"; w["automat"]="50,74,110"; w["autonom"]="75,86,96"; w["avail"]="0,15,16,17,22,28,31,32,38,67,74,82,100,104,105,111"; w["averag"]="17"; w["avoid"]="16,60,94"; w["awar"]="37,39,67,112"; w["away"]="9"; w["b"]="0"; w["b0"]="9,15,111"; w["b3"]="75"; w["b7"]="103"; w["back"]="19,32,110,112"; w["back-end"]="15,46,110"; w["bad"]="104"; w["balanc"]="9,14,15,34,40,46,78,110,111"; w["ballpark"]="97"; w["bandwidth"]="40"; w["bang"]="85"; w["base"]="22,34,40,64,77,115"; w["baselin"]="0"; w["basi"]="41"; w["basic"]="22,96,99,100"; w["bb"]="49"; w["bc3afc36-6274-4603-9109-c29f1c12ba33"]="11"; w["be"]="0,24,32,46,104"; w["becaus"]="0,7,14,16,24,29,32,56,75,85,97,104,106,110,112"; w["becom"]="0,14,31,56,104,112"; w["been"]="34,52,71,81,106,112"; w["befor"]="24,31,34,40,67,75,86,97,107,111"; w["behalf"]="86"; w["behavior"]="0,32,39,56,60,91,112"; w["behind"]="106"; w["belong"]="13,16,33,41,68,71,85,110"; w["below"]="0,1,2,5,6,7,9,17,19,21,24,25,30,31,32,39,40,46,54,55,58,63,64,70,73,79,82,85,91,104,105,112,113"; w["best"]="12,17,86,104"; w["better"]="51,72"; w["between"]="0,14,16,26,29,32,34,39,51,57,71,72,85,86,95,96,102,104,105,106,112"; w["beyond"]="17,104"; w["bgp"]="14,18,25,29,75,82,86,96,111,112,114"; w["bgp-enabl"]="86"; w["bgp0"]="75"; w["bgp_connect_retri"]="25,112"; w["bgp_holdtim"]="25,112"; w["bgp_keepal"]="25,112"; w["bgpd"]="25,75,86,112,114"; w["bgpd_binari"]="75"; w["bgpid"]="18"; w["big"]="104"; w["bin"]="107"; w["bind"]="1,3,8,11,18,49,59,73,74,75,78,85,86,93,101,102,103,106"; w["binding0"]="11"; w["binding1"]="11"; w["binding2"]="11"; w["binding3"]="11"; w["binding4"]="11"; w["bit"]="12,40,85"; w["bitmask"]="85"; w["blackhol"]="2,40,82"; w["blank"]="17"; w["block"]="12,13,85"; w["bloom"]="104"; w["border"]="29"; w["both"]="7,13,14,17,24,25,39,56,70,73,86,100,111,112"; w["bound"]="2,8,11,18,39,51,59,75,76,85,86"; w["box"]="100"; w["bpdu"]="13"; w["bpdus"]="13"; w["br0"]="37,92"; w["break"]="60"; w["bridg"]="1,2,8,11,12,13,18,39,40,41,47,51,58,68,70,71,72,78,79,80,85,88,90,93,101,102,106,108,112"; w["bridge-port-"]="112"; w["bridge0"]="1,2,15,41,68,101,103,106,111"; w["bridge1"]="1,49,80,90,93,101"; w["bridge2"]="1,101"; w["bridgebridg"]="68"; w["bridgeid"]="18"; w["brief"]="60"; w["briefli"]="40"; w["bring"]="88"; w["broadcast"]="12"; w["broken"]="24"; w["bucket"]="32,97"; w["buf_size_kb"]="112"; w["buffer"]="0,112"; w["bug"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["built"]="0,17,104"; w["burst"]="32,97"; w["busi"]="104"; w["but"]="0,7,9,15,17,24,27,38,39,40,51,56,60,70,81,91,97,104,105,109,110,112,113"; w["byte"]="104"; w["c1"]="36,101"; w["c2"]="15,111"; w["c4"]="15,111"; w["c6"]="2"; w["c9"]="36,101"; w["c9a4"]="36,101"; w["cach"]="60,62,104,112"; w["cache_typ"]="112"; w["call"]="7,16,46,51,56,71,75,81,86,93,106,109"; w["caller"]="7,16"; w["can"]="0,3,6,11,15,16,17,19,21,22,23,24,25,28,29,30,32,34,35,39,40,41,46,49,50,51,52,55,59,60,64,65,67,70,72,74,75,76,79,83,85,91,93,94,97,99,100,104,106,108,110,111,112,113"; w["candid"]="40"; w["cannot"]="16,39,51,79,110"; w["capabl"]="13"; w["capac"]="32,97,104"; w["captur"]="32"; w["card"]="101"; w["care"]="29"; w["carri"]="32,39"; w["case"]="2,14,34,40,56,57,73,75,79,85,86,104,110"; w["cassandra"]="31,48,56,60,62,73,104,112"; w["cassandra-bas"]="60"; w["cassandra-rel"]="31"; w["cassandra-serv"]="5"; w["catalina"]="107"; w["categori"]="17,30,42,48,89,98,104,114"; w["caus"]="0,16,32,100,104,112"; w["caution"]="29"; w["cb"]="15,111"; w["ceilomet"]="42"; w["ceilometer-api"]="42"; w["central"]="16,58"; w["certain"]="0,29,34,50,97,101,103,104"; w["cf"]="104"; w["cfstat"]="104"; w["ch"]="69,91"; w["chain"]="6,7,12,16,18,20,21,23,24,35,41,43,54,57,58,63,68,70,78,81,85,109"; w["chain0"]="12,15,21,24,35,41,57,79"; w["chain1"]="15,21,35,41,57,79"; w["chain10"]="63"; w["chain11"]="43"; w["chain18"]="24"; w["chain2"]="35,41,68"; w["chain3"]="35,41,68"; w["chain4"]="35,41,68"; w["chain5"]="23,35,41"; w["chain6"]="35,41"; w["chain7"]="35,41,54"; w["chain9"]="58"; w["chainid"]="18"; w["chanc"]="110,112"; w["chang"]="13,17,21,24,25,30,39,46,71,97,104,109,112"; w["channel"]="42,97,112"; w["chapter"]="4,6,20,22,24,29,32,38,39,49,62,70,72,74,78,84,96,108,110"; w["check"]="7,16,26,34,38,46,63,85,95,109,110,112"; w["check_flow_expiration_interv"]="112"; w["checker"]="46"; w["choic"]="16"; w["choos"]="13,17,46,51,109,112"; w["cidr"]="85"; w["cinder-api"]="42"; w["class"]="55,77,91,94"; w["classifi"]="17"; w["clean"]="46"; w["clear"]="0,17"; w["cleart"]="75"; w["cli"]="1,3,6,9,14,15,21,25,28,29,40,41,47,54,57,58,63,72,75,82,85,106,111,113"; w["client"]="5,17,48,56,60,64"; w["client-sid"]="64"; w["clock"]="104"; w["clone"]="100"; w["close"]="0,56,104"; w["cloud"]="29,32,38,51,96,101,110"; w["cloud-control"]="5"; w["cluster"]="26,48,95,104,112"; w["code"]="8,40,87,97"; w["collect"]="0,17,71,104,112"; w["collector"]="0,17"; w["column"]="104"; w["combin"]="8,11,13,51,85"; w["come"]="46,110,112"; w["comma"]="5"; w["command"]="2,3,8,11,14,15,19,21,23,28,35,36,37,41,43,44,45,47,49,50,54,57,58,59,61,63,67,68,72,75,76,79,80,82,83,85,87,90,92,93,100,101,103,104,106,111"; w["comment"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["commit"]="104"; w["communic"]="32,33,48,71,74,75,98,105,106,112,114"; w["compact"]="104"; w["compar"]="51"; w["comparison"]="72"; w["complet"]="0,13,38,76,104"; w["complex"]="16"; w["compon"]="51,97,102"; w["compos"]="22,115"; w["comprehens"]="104"; w["compris"]="78"; w["comput"]="17,32,41,42,48,51,84,97,98,99"; w["compute-1"]="36,101"; w["compute-2"]="36,101"; w["compute1"]="103"; w["compute2"]="103"; w["compute3"]="103"; w["concept"]="62"; w["concern"]="30"; w["concurr"]="0"; w["concurrentmarksweep"]="0"; w["condit"]="7,8,16,21,23,24,41,43,70,85"; w["conf"]="25,31,32,46,75,97,100,112"; w["config"]="46,56,71,99,100"; w["configur"]="0,1,2,5,9,13,14,15,17,20,21,22,24,25,30,31,32,33,34,35,39,41,46,51,52,54,55,56,58,60,62,63,64,68,71,72,73,75,77,82,86,88,91,94,96,97,99,100,102,104,105,106,110,112,113,115"; w["confirm"]="44,45,50,82"; w["conflict"]="104"; w["congratul"]="106"; w["conn_expir"]="26,95"; w["connect"]="1,2,4,5,9,13,14,16,17,25,26,28,30,33,34,37,39,40,41,47,49,51,52,54,56,57,58,60,63,68,71,72,74,75,79,83,85,86,87,88,92,93,95,96,101,103,104,105,106,108,110,112"; w["connection-st"]="37,87,106"; w["connection-track"]="85"; w["consid"]="5,24,32,34,58,85,109,112"; w["consist"]="0,24,55"; w["constant"]="56"; w["constraint"]="0"; w["construct"]="7,16,23"; w["consum"]="0,104"; w["consumpt"]="0"; w["contain"]="0,15,16,17,21,24,27,35,39,41,46,68,75,82,85,97,100,105,115"; w["content"]="0,4,6,16,20,22,24,29,32,38,39,62,70,72,74,78,84,85,96,108,110"; w["content-typ"]="64"; w["context"]="0"; w["context-awar"]="28"; w["context-param"]="5,55,64,71,77,94,105"; w["continu"]="7,13,16,24,26,85,95,109,112"; w["control"]="7,38,42,48,50,57,84,97,98,102,103,112,114"; w["convent"]="67"; w["converg"]="0"; w["convert"]="55"; w["cooki"]="110"; w["coordin"]="51,72,102"; w["correct"]="16,18,24,26,95"; w["correl"]="104"; w["correspond"]="16,24,32,39,51"; w["cors-access_control_allow_head"]="64"; w["cors-access_control_allow_method"]="64"; w["cors-access_control_allow_origin"]="64"; w["cors-access_control_expose_head"]="64"; w["could"]="13"; w["count"]="0,17,104"; w["countephemer"]="17"; w["counter"]="56"; w["coupl"]="6"; w["cover"]="5,30,112"; w["cpu"]="0,17,100,104"; w["cpus"]="0"; w["cql"]="48"; w["crash"]="112"; w["creat"]="1,9,12,14,15,18,23,24,29,33,38,43,45,46,49,51,54,55,60,63,70,71,75,78,83,86,90,93,94,97,102,106,108,111,112,113"; w["creation"]="0,12,24,36,51,85,97"; w["credenti"]="28,38"; w["critic"]="67"; w["cron"]="100"; w["cron-bas"]="115"; w["current"]="0,2,16,21,34,39,49,58,75,79,80,81,83,85,86,93,100,101,103"; w["custom"]="6,15"; w["cycl"]="13"; w["d"]="69"; w["d0"]="103"; w["d2"]="49"; w["d7"]="36,101"; w["daemon"]="30,97"; w["data"]="5,13,17,18,54,67,85,99,100,104,112,115"; w["databas"]="5,17,22,26,30,46,48,60,73,74,84,112,115"; w["datapath"]="0,32,36,75,97,101,103,106,112"; w["datastax"]="104"; w["day"]="9"; w["day-"]="30"; w["dc"]="2"; w["dc40"]="103"; w["dd"]="69"; w["deal"]="17,31"; w["debian"]="32"; w["debug"]="27,97"; w["decid"]="12,13,24,40,109"; w["decis"]="34"; w["decreas"]="112"; w["dedic"]="0,97"; w["default"]="6,16,24,25,32,33,40,46,57,64,69,79,85,91,97,100,104,106,112"; w["default-dispatch"]="97"; w["default_tz"]="19"; w["defin"]="30,32,35,40,41,46,55,72,79,110,112"; w["definit"]="24,104"; w["degrad"]="0,104"; w["delay"]="13,34,113"; w["delet"]="4,18,19,33,38,44,50,51,59,61,64,65,76,95,100,102"; w["delimit"]="5"; w["deliveri"]="4,40"; w["demand"]="75"; w["demo"]="41,111"; w["demo-ext-net"]="2"; w["demo-private-net"]="41,68"; w["demonstr"]="20,88"; w["denial"]="32"; w["denot"]="40"; w["depend"]="0,5,7,13,16,32,40,56,91,112"; w["depict"]="24,39"; w["deploy"]="0,2,15,17,22,51,62,73,100,104,107,115"; w["describ"]="0,2,3,7,16,18,22,24,26,28,30,32,39,45,55,56,58,60,62,64,95,96,99,105"; w["descript"]="0,3,8,11,17,37,55,85,92,104,105,106"; w["design"]="24,38,46"; w["desir"]="17,19,23,36,43,44,46,47,50,61,80,93,101,105"; w["destin"]="2,9,16,21,23,24,35,40,41,43,54,63,79,82,85,109,110"; w["destination_unreach"]="40"; w["detail"]="60,69,73,86,99,107"; w["detect"]="13,16,46,56,95,104"; w["determin"]="9,15,31,40,55,56,87,104,111,112"; w["dev"]="107"; w["develop"]="95,97"; w["devic"]="2,13,15,40,41,47,49,50,54,58,68,75,78,85,93,101,103,108,111,112"; w["df"]="49,75"; w["diagnos"]="56"; w["diagram"]="39"; w["dictat"]="112"; w["did"]="50"; w["didn"]="43,109"; w["differ"]="7,14,23,24,32,33,39,40,43,51,64,85,86,109"; w["differenti"]="85"; w["digit"]="85"; w["direct"]="4,6,16,29,33,40,51,55,79,88,110"; w["directori"]="64,100"; w["disabl"]="9,32,34,65,66,77,105"; w["disallow"]="85"; w["disassoci"]="59,76"; w["discard"]="24"; w["disconnect"]="5,26,37,92,95,112"; w["disconnected_ttl_second"]="112"; w["discrep"]="104"; w["discuss"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["disk"]="100,104"; w["display"]="0,17,21,28,40,41,79"; w["disqus"]="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115"; w["disregard"]="40"; w["distinct"]="7"; w["distinguish"]="16,85"; w["distribut"]="32,86,104"; w["diverg"]="104"; w["divid"]="32"; w["dnat"]="16,20,21,24,58,63,85"; w["dnat-test"]="63"; w["do"]="0,6,14,16,17,24,27,40,41,46,55,65,68,100,112,113"; w["doc"]="38"; w["document"]="5,17,28,38,67,71,99,100,104,110"; w["doe"]="7,16,23,24,38,40,41,46,55,68,75,85,110"; w["doesn"]="16,24,51,85"; w["domain"]="32,64"; w["don"]="6,16,40,58,112"; w["done"]="0"; w["down"]="17,31,46,60,95,112,113"; w["draw"]="24"; w["drop"]="0,2,7,9,12,16,23,24,40,41,43,68,82,85,97,109"; w["drop_not_src_mynetwork_inbound"]="23"; w["dst"]="2,9,15,21,23,24,40,43,50,58,63,79,82,85"; w["dst-port"]="24,35,41,85"; w["due"]="104"; w["durat"]="0"; w["dure"]="0,16,56,70,85,97,104,112"; w["dynam"]="24,36,44,58,82,96"; w["e"]="16,81,106,109"; w["e2"]="75"; w["e5"]="75"; w["each"]="0,2,7,11,15,17,22,32,34,37,39,48,49,56,64,75,79,91,93,97,98,99,100,104,110,112,114,115"; w["earlier"]="43,58"; w["eas"]="85"; w["easiest"]="29"; w["easili"]="17,46,49,93,100"; w["eden"]="0,97";
yantarou/midonet-docs
www/operation-guide/2014-11/content/search/index-1.js
JavaScript
apache-2.0
23,078
import {registerBidder} from 'src/adapters/bidderFactory'; const utils = require('src/utils'); const BIDDER_CODE = 'teads'; const ENDPOINT_URL = '//a.teads.tv/hb/bid-request'; const gdprStatus = { GDPR_APPLIES_PUBLISHER: 12, GDPR_APPLIES_GLOBAL: 11, GDPR_DOESNT_APPLY: 0, CMP_NOT_FOUND_OR_ERROR: 22 } export const spec = { code: BIDDER_CODE, supportedMediaTypes: ['video', 'banner'], /** * Determines whether or not the given bid request is valid. * * @param {BidRequest} bid The bid params to validate. * @return boolean True if this is a valid bid, and false otherwise. */ isBidRequestValid: function(bid) { let isValid = false; if (typeof bid.params !== 'undefined') { let isValidPlacementId = _validateId(utils.getValue(bid.params, 'placementId')); let isValidPageId = _validateId(utils.getValue(bid.params, 'pageId')); isValid = isValidPlacementId && isValidPageId; } if (!isValid) { utils.logError('Teads placementId and pageId parameters are required. Bid aborted.'); } return isValid; }, /** * Make a server request from the list of BidRequests. * * @param {validBidRequests[]} an array of bids * @return ServerRequest Info describing the request to the server. */ buildRequests: function(validBidRequests, bidderRequest) { const bids = validBidRequests.map(buildRequestObject); const payload = { referrer: utils.getTopWindowUrl(), data: bids, deviceWidth: screen.width }; let gdpr = bidderRequest.gdprConsent; if (bidderRequest && gdpr) { let isCmp = (typeof gdpr.gdprApplies === 'boolean') let isConsentString = (typeof gdpr.consentString === 'string') let status = isCmp ? findGdprStatus(gdpr.gdprApplies, gdpr.vendorData) : gdprStatus.CMP_NOT_FOUND_OR_ERROR payload.gdpr_iab = { consent: isConsentString ? gdpr.consentString : '', status: status }; } const payloadString = JSON.stringify(payload); return { method: 'POST', url: ENDPOINT_URL, data: payloadString, }; }, /** * Unpack the response from the server into a list of bids. * * @param {*} serverResponse A successful response from the server. * @return {Bid[]} An array of bids which were nested inside the server. */ interpretResponse: function(serverResponse, bidderRequest) { const bidResponses = []; serverResponse = serverResponse.body; if (serverResponse.responses) { serverResponse.responses.forEach(function (bid) { const bidResponse = { cpm: bid.cpm, width: bid.width, height: bid.height, currency: bid.currency, netRevenue: true, ttl: bid.ttl, ad: bid.ad, requestId: bid.bidId, creativeId: bid.creativeId }; bidResponses.push(bidResponse); }); } return bidResponses; }, getUserSyncs: function(syncOptions, responses, gdprApplies) { if (syncOptions.iframeEnabled) { return [{ type: 'iframe', url: '//sync.teads.tv/iframe' }]; } } }; function findGdprStatus(gdprApplies, gdprData) { let status = gdprStatus.GDPR_APPLIES_PUBLISHER; if (gdprApplies) { if (gdprData.hasGlobalScope || gdprData.hasGlobalConsent) status = gdprStatus.GDPR_APPLIES_GLOBAL } else status = gdprStatus.GDPR_DOESNT_APPLY return status; } function buildRequestObject(bid) { const reqObj = {}; let placementId = utils.getValue(bid.params, 'placementId'); let pageId = utils.getValue(bid.params, 'pageId'); reqObj.sizes = utils.parseSizesInput(bid.sizes); reqObj.bidId = utils.getBidIdParameter('bidId', bid); reqObj.bidderRequestId = utils.getBidIdParameter('bidderRequestId', bid); reqObj.placementId = parseInt(placementId, 10); reqObj.pageId = parseInt(pageId, 10); reqObj.adUnitCode = utils.getBidIdParameter('adUnitCode', bid); reqObj.auctionId = utils.getBidIdParameter('auctionId', bid); reqObj.transactionId = utils.getBidIdParameter('transactionId', bid); return reqObj; } function _validateId(id) { return (parseInt(id) > 0); } registerBidder(spec);
indexexchange/Prebid.js
modules/teadsBidAdapter.js
JavaScript
apache-2.0
4,185
/** * @license * Visual Blocks Editor * * Copyright 2012 Google Inc. * https://developers.google.com/blockly/ * * 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 Utility functions for handling variables. * @author fraser@google.com (Neil Fraser) */ 'use strict'; /** * @name Blockly.Variables * @namespace **/ goog.provide('Blockly.Variables'); goog.require('Blockly.Blocks'); goog.require('Blockly.constants'); goog.require('Blockly.VariableModel'); goog.require('Blockly.Workspace'); goog.require('goog.string'); /** * Constant to separate variable names from procedures and generated functions * when running generators. * @deprecated Use Blockly.VARIABLE_CATEGORY_NAME */ Blockly.Variables.NAME_TYPE = Blockly.VARIABLE_CATEGORY_NAME; /** * Find all user-created variables that are in use in the workspace. * For use by generators. * To get a list of all variables on a workspace, including unused variables, * call Workspace.getAllVariables. * @param {!Blockly.Workspace} ws The workspace to search for variables. * @return {!Array.<!Blockly.VariableModel>} Array of variable models. */ Blockly.Variables.allUsedVarModels = function(ws) { var blocks = ws.getAllBlocks(); var variableHash = Object.create(null); // Iterate through every block and add each variable to the hash. for (var x = 0; x < blocks.length; x++) { var blockVariables = blocks[x].getVarModels(); if (blockVariables) { for (var y = 0; y < blockVariables.length; y++) { var variable = blockVariables[y]; if (variable.getId()) { variableHash[variable.getId()] = variable; } } } } // Flatten the hash into a list. var variableList = []; for (var id in variableHash) { variableList.push(variableHash[id]); } return variableList; }; /** * Find all user-created variables that are in use in the workspace and return * only their names. * For use by generators. * To get a list of all variables on a workspace, including unused variables, * call Workspace.getAllVariables. * @deprecated January 2018 */ Blockly.Variables.allUsedVariables = function() { console.warn('Deprecated call to Blockly.Variables.allUsedVariables. ' + 'Use Blockly.Variables.allUsedVarModels instead.\nIf this is a major ' + 'issue please file a bug on GitHub.'); }; /** * Find all developer variables used by blocks in the workspace. * Developer variables are never shown to the user, but are declared as global * variables in the generated code. * To declare developer variables, define the getDeveloperVariables function on * your block and return a list of variable names. * For use by generators. * @param {!Blockly.Workspace} workspace The workspace to search. * @return {!Array.<string>} A list of non-duplicated variable names. */ Blockly.Variables.allDeveloperVariables = function(workspace) { var blocks = workspace.getAllBlocks(); var hash = {}; for (var i = 0; i < blocks.length; i++) { var block = blocks[i]; if (block.getDeveloperVars) { var devVars = block.getDeveloperVars(); for (var j = 0; j < devVars.length; j++) { hash[devVars[j]] = devVars[j]; } } } // Flatten the hash into a list. var list = []; for (var name in hash) { list.push(hash[name]); } return list; }; /** * Construct the elements (blocks and button) required by the flyout for the * variable category. * @param {!Blockly.Workspace} workspace The workspace containing variables. * @return {!Array.<!Element>} Array of XML elements. */ Blockly.Variables.flyoutCategory = function(workspace) { var xmlList = []; var button = goog.dom.createDom('button'); button.setAttribute('text', Blockly.Msg.NEW_VARIABLE); button.setAttribute('callbackKey', 'CREATE_VARIABLE'); workspace.registerButtonCallback('CREATE_VARIABLE', function(button) { Blockly.Variables.createVariableButtonHandler(button.getTargetWorkspace()); }); xmlList.push(button); var blockList = Blockly.Variables.flyoutCategoryBlocks(workspace); xmlList = xmlList.concat(blockList); return xmlList; }; /** * Construct the blocks required by the flyout for the variable category. * @param {!Blockly.Workspace} workspace The workspace containing variables. * @return {!Array.<!Element>} Array of XML block elements. */ Blockly.Variables.flyoutCategoryBlocks = function(workspace) { var variableModelList = workspace.getVariablesOfType(''); variableModelList.sort(Blockly.VariableModel.compareByName); var xmlList = []; if (variableModelList.length > 0) { var firstVariable = variableModelList[0]; if (Blockly.Blocks['variables_set']) { var gap = Blockly.Blocks['math_change'] ? 8 : 24; var blockText = '<xml>' + '<block type="variables_set" gap="' + gap + '">' + Blockly.Variables.generateVariableFieldXmlString(firstVariable) + '</block>' + '</xml>'; var block = Blockly.Xml.textToDom(blockText).firstChild; xmlList.push(block); } if (Blockly.Blocks['math_change']) { var gap = Blockly.Blocks['variables_get'] ? 20 : 8; var blockText = '<xml>' + '<block type="math_change" gap="' + gap + '">' + Blockly.Variables.generateVariableFieldXmlString(firstVariable) + '<value name="DELTA">' + '<shadow type="math_number">' + '<field name="NUM">1</field>' + '</shadow>' + '</value>' + '</block>' + '</xml>'; var block = Blockly.Xml.textToDom(blockText).firstChild; xmlList.push(block); } for (var i = 0, variable; variable = variableModelList[i]; i++) { if (Blockly.Blocks['variables_get']) { var blockText = '<xml>' + '<block type="variables_get" gap="8">' + Blockly.Variables.generateVariableFieldXmlString(variable) + '</block>' + '</xml>'; var block = Blockly.Xml.textToDom(blockText).firstChild; xmlList.push(block); } } } return xmlList; }; /** * Return a new variable name that is not yet being used. This will try to * generate single letter variable names in the range 'i' to 'z' to start with. * If no unique name is located it will try 'i' to 'z', 'a' to 'h', * then 'i2' to 'z2' etc. Skip 'l'. * @param {!Blockly.Workspace} workspace The workspace to be unique in. * @return {string} New variable name. */ Blockly.Variables.generateUniqueName = function(workspace) { var variableList = workspace.getAllVariables(); var newName = ''; if (variableList.length) { var nameSuffix = 1; var letters = 'ijkmnopqrstuvwxyzabcdefgh'; // No 'l'. var letterIndex = 0; var potName = letters.charAt(letterIndex); while (!newName) { var inUse = false; for (var i = 0; i < variableList.length; i++) { if (variableList[i].name.toLowerCase() == potName) { // This potential name is already used. inUse = true; break; } } if (inUse) { // Try the next potential name. letterIndex++; if (letterIndex == letters.length) { // Reached the end of the character sequence so back to 'i'. // a new suffix. letterIndex = 0; nameSuffix++; } potName = letters.charAt(letterIndex); if (nameSuffix > 1) { potName += nameSuffix; } } else { // We can use the current potential name. newName = potName; } } } else { newName = 'i'; } return newName; }; /** * Handles "Create Variable" button in the default variables toolbox category. * It will prompt the user for a varibale name, including re-prompts if a name * is already in use among the workspace's variables. * * Custom button handlers can delegate to this function, allowing variables * types and after-creation processing. More complex customization (e.g., * prompting for variable type) is beyond the scope of this function. * * @param {!Blockly.Workspace} workspace The workspace on which to create the * variable. * @param {function(?string=)=} opt_callback A callback. It will be passed an * acceptable new variable name, or null if change is to be aborted (cancel * button), or undefined if an existing variable was chosen. * @param {string=} opt_type The type of the variable like 'int', 'string', or * ''. This will default to '', which is a specific type. */ Blockly.Variables.createVariableButtonHandler = function( workspace, opt_callback, opt_type) { var type = opt_type || ''; // This function needs to be named so it can be called recursively. var promptAndCheckWithAlert = function(defaultName) { Blockly.Variables.promptName(Blockly.Msg.NEW_VARIABLE_TITLE, defaultName, function(text) { if (text) { var existing = Blockly.Variables.nameUsedWithAnyType_(text, workspace); if (existing) { var lowerCase = text.toLowerCase(); if (existing.type == type) { var msg = Blockly.Msg.VARIABLE_ALREADY_EXISTS.replace( '%1', lowerCase); } else { var msg = Blockly.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE; msg = msg.replace('%1', lowerCase).replace('%2', existing.type); } Blockly.alert(msg, function() { promptAndCheckWithAlert(text); // Recurse }); } else { // No conflict workspace.createVariable(text, type); if (opt_callback) { opt_callback(text); } } } else { // User canceled prompt. if (opt_callback) { opt_callback(null); } } }); }; promptAndCheckWithAlert(''); }; goog.exportSymbol('Blockly.Variables.createVariableButtonHandler', Blockly.Variables.createVariableButtonHandler); /** * Original name of Blockly.Variables.createVariableButtonHandler(..). * @deprecated Use Blockly.Variables.createVariableButtonHandler(..). * * @param {!Blockly.Workspace} workspace The workspace on which to create the * variable. * @param {function(?string=)=} opt_callback A callback. It will be passed an * acceptable new variable name, or null if change is to be aborted (cancel * button), or undefined if an existing variable was chosen. * @param {string=} opt_type The type of the variable like 'int', 'string', or * ''. This will default to '', which is a specific type. */ Blockly.Variables.createVariable = Blockly.Variables.createVariableButtonHandler; goog.exportSymbol('Blockly.Variables.createVariable', Blockly.Variables.createVariable); /** * Rename a variable with the given workspace, variableType, and oldName. * @param {!Blockly.Workspace} workspace The workspace on which to rename the * variable. * @param {Blockly.VariableModel} variable Variable to rename. * @param {function(?string=)=} opt_callback A callback. It will * be passed an acceptable new variable name, or null if change is to be * aborted (cancel button), or undefined if an existing variable was chosen. */ Blockly.Variables.renameVariable = function(workspace, variable, opt_callback) { // This function needs to be named so it can be called recursively. var promptAndCheckWithAlert = function(defaultName) { var promptText = Blockly.Msg.RENAME_VARIABLE_TITLE.replace('%1', variable.name); Blockly.Variables.promptName(promptText, defaultName, function(newName) { if (newName) { var existing = Blockly.Variables.nameUsedWithOtherType_(newName, variable.type, workspace); if (existing) { var msg = Blockly.Msg.VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE .replace('%1', newName.toLowerCase()) .replace('%2', existing.type); Blockly.alert(msg, function() { promptAndCheckWithAlert(newName); // Recurse }); } else { workspace.renameVariableById(variable.getId(), newName); if (opt_callback) { opt_callback(newName); } } } else { // User canceled prompt. if (opt_callback) { opt_callback(null); } } }); }; promptAndCheckWithAlert(''); }; /** * Prompt the user for a new variable name. * @param {string} promptText The string of the prompt. * @param {string} defaultText The default value to show in the prompt's field. * @param {function(?string)} callback A callback. It will return the new * variable name, or null if the user picked something illegal. */ Blockly.Variables.promptName = function(promptText, defaultText, callback) { Blockly.prompt(promptText, defaultText, function(newVar) { // Merge runs of whitespace. Strip leading and trailing whitespace. // Beyond this, all names are legal. if (newVar) { newVar = newVar.replace(/[\s\xa0]+/g, ' ').replace(/^ | $/g, ''); if (newVar == Blockly.Msg.RENAME_VARIABLE || newVar == Blockly.Msg.NEW_VARIABLE) { // Ok, not ALL names are legal... newVar = null; } } callback(newVar); }); }; /** * Check whether there exists a variable with the given name but a different * type. * @param {string} name The name to search for. * @param {string} type The type to exclude from the search. * @param {!Blockly.Workspace} workspace The workspace to search for the * variable. * @return {?Blockly.VariableModel} The variable with the given name and a * different type, or null if none was found. * @private */ Blockly.Variables.nameUsedWithOtherType_ = function(name, type, workspace) { var allVariables = workspace.getVariableMap().getAllVariables(); name = name.toLowerCase(); for (var i = 0, variable; variable = allVariables[i]; i++) { if (variable.name.toLowerCase() == name && variable.type != type) { return variable; } } return null; }; /** * Check whether there exists a variable with the given name of any type. * @param {string} name The name to search for. * @param {!Blockly.Workspace} workspace The workspace to search for the * variable. * @return {?Blockly.VariableModel} The variable with the given name, or null if * none was found. * @private */ Blockly.Variables.nameUsedWithAnyType_ = function(name, workspace) { var allVariables = workspace.getVariableMap().getAllVariables(); name = name.toLowerCase(); for (var i = 0, variable; variable = allVariables[i]; i++) { if (variable.name.toLowerCase() == name) { return variable; } } return null; }; /** * Generate XML string for variable field. * @param {!Blockly.VariableModel} variableModel The variable model to generate * an XML string from. * @return {string} The generated XML. * @package */ Blockly.Variables.generateVariableFieldXmlString = function(variableModel) { // The variable name may be user input, so it may contain characters that need // to be escaped to create valid XML. var typeString = variableModel.type; if (typeString == '') { typeString = '\'\''; } var text = '<field name="VAR" id="' + variableModel.getId() + '" variabletype="' + goog.string.htmlEscape(typeString) + '">' + goog.string.htmlEscape(variableModel.name) + '</field>'; return text; }; /** * Generate DOM objects representing a variable field. * @param {!Blockly.VariableModel} variableModel The variable model to * represent. * @return {Element} The generated DOM. * @public */ Blockly.Variables.generateVariableFieldDom = function(variableModel) { var xmlFieldString = Blockly.Variables.generateVariableFieldXmlString(variableModel); var text = '<xml>' + xmlFieldString + '</xml>'; var dom = Blockly.Xml.textToDom(text); var fieldDom = dom.firstChild; return fieldDom; }; /** * Helper function to look up or create a variable on the given workspace. * If no variable exists, creates and returns it. * @param {!Blockly.Workspace} workspace The workspace to search for the * variable. It may be a flyout workspace or main workspace. * @param {string} id The ID to use to look up or create the variable, or null. * @param {string=} opt_name The string to use to look up or create the * variable. * @param {string=} opt_type The type to use to look up or create the variable. * @return {!Blockly.VariableModel} The variable corresponding to the given ID * or name + type combination. */ Blockly.Variables.getOrCreateVariablePackage = function(workspace, id, opt_name, opt_type) { var variable = Blockly.Variables.getVariable(workspace, id, opt_name, opt_type); if (!variable) { variable = Blockly.Variables.createVariable_(workspace, id, opt_name, opt_type); } return variable; }; /** * Look up a variable on the given workspace. * Always looks in the main workspace before looking in the flyout workspace. * Always prefers lookup by ID to lookup by name + type. * @param {!Blockly.Workspace} workspace The workspace to search for the * variable. It may be a flyout workspace or main workspace. * @param {string} id The ID to use to look up the variable, or null. * @param {string=} opt_name The string to use to look up the variable. Only * used if lookup by ID fails. * @param {string=} opt_type The type to use to look up the variable. Only used * if lookup by ID fails. * @return {?Blockly.VariableModel} The variable corresponding to the given ID * or name + type combination, or null if not found. * @package */ Blockly.Variables.getVariable = function(workspace, id, opt_name, opt_type) { var potentialVariableMap = workspace.getPotentialVariableMap(); // Try to just get the variable, by ID if possible. if (id) { // Look in the real variable map before checking the potential variable map. var variable = workspace.getVariableById(id); if (!variable && potentialVariableMap) { variable = potentialVariableMap.getVariableById(id); } } else if (opt_name) { if (opt_type == undefined) { throw new Error('Tried to look up a variable by name without a type'); } // Otherwise look up by name and type. var variable = workspace.getVariable(opt_name, opt_type); if (!variable && potentialVariableMap) { variable = potentialVariableMap.getVariable(opt_name, opt_type); } } return variable; }; /** * Helper function to create a variable on the given workspace. * @param {!Blockly.Workspace} workspace The workspace in which to create the * variable. It may be a flyout workspace or main workspace. * @param {string} id The ID to use to create the variable, or null. * @param {string=} opt_name The string to use to create the variable. * @param {string=} opt_type The type to use to create the variable. * @return {!Blockly.VariableModel} The variable corresponding to the given ID * or name + type combination. * @private */ Blockly.Variables.createVariable_ = function(workspace, id, opt_name, opt_type) { var potentialVariableMap = workspace.getPotentialVariableMap(); // Variables without names get uniquely named for this workspace. if (!opt_name) { var ws = workspace.isFlyout ? workspace.targetWorkspace : workspace; opt_name = Blockly.Variables.generateUniqueName(ws); } // Create a potential variable if in the flyout. if (potentialVariableMap) { var variable = potentialVariableMap.createVariable(opt_name, opt_type, id); } else { // In the main workspace, create a real variable. var variable = workspace.createVariable(opt_name, opt_type, id); } return variable; }; /** * Helper function to get the list of variables that have been added to the * workspace after adding a new block, using the given list of variables that * were in the workspace before the new block was added. * @param {!Blockly.Workspace} workspace The workspace to inspect. * @param {!Array.<!Blockly.VariableModel>} originalVariables The array of * variables that existed in the workspace before adding the new block. * @return {!Array.<!Blockly.VariableModel>} The new array of variables that were * freshly added to the workspace after creating the new block, or [] if no * new variables were added to the workspace. * @package */ Blockly.Variables.getAddedVariables = function(workspace, originalVariables) { var allCurrentVariables = workspace.getAllVariables(); var addedVariables = []; if (originalVariables.length != allCurrentVariables.length) { for (var i = 0; i < allCurrentVariables.length; i++) { var variable = allCurrentVariables[i]; // For any variable that is present in allCurrentVariables but not // present in originalVariables, add the variable to addedVariables. if (originalVariables.indexOf(variable) == -1) { addedVariables.push(variable); } } } return addedVariables; };
jstnhuang/blockly
core/variables.js
JavaScript
apache-2.0
21,831
import { dom, text } from '../../commons'; /** * Note: `identical-links-same-purpose-after` fn, helps reconcile the results */ function identicalLinksSamePurposeEvaluate(node, options, virtualNode) { const accText = text.accessibleTextVirtual(virtualNode); const name = text .sanitize( text.removeUnicode(accText, { emoji: true, nonBmp: true, punctuations: true }) ) .toLowerCase(); if (!name) { return undefined; } /** * Set `data` and `relatedNodes` for use in `after` fn */ const afterData = { name, urlProps: dom.urlPropsFromAttribute(node, 'href') }; this.data(afterData); this.relatedNodes([node]); return true; } export default identicalLinksSamePurposeEvaluate;
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/axe-core/lib/checks/navigation/identical-links-same-purpose-evaluate.js
JavaScript
apache-2.0
763
var url = require('url') var fs = require('fs'); var express = require('express'); var _ = require('lodash'); var superagent = require('superagent'); var net = require('net'); var http = require('http'); var https = require('https'); var WS = require('ws'); var WebSocketServer = WS.Server; var indexData; var app = express(); var ms = process.env.MS || 5000; process.env.MS=ms var ctxRoot = process.env.CTX_ROOT || '/'; if ( !ctxRoot.startsWith('/') ) { ctxRoot = '/' + ctxRoot; } if ( !ctxRoot.endsWith('/') ) { ctxRoot = ctxRoot + '/'; } app.use(ctxRoot, express.static('dist')); var server = app.listen(8080, function () { indexData = _.template(fs.readFileSync('index.tpl'))(process.env); }); app.get(ctxRoot, function(req, res) { res.send(indexData); }); if (process.env.DOCKER_HOST) { console.log("Docker Host: " + process.env.DOCKER_HOST) try { dh = process.env.DOCKER_HOST.split(":"); var docker_host = dh[0]; var docker_port = dh[1]; } catch (err) { console.log(err.stack) } } var cert_path; if (process.env.DOCKER_TLS_VERIFY) { if (process.env.DOCKER_CERT_PATH) { cert_path = process.env.DOCKER_CERT_PATH; } else { cert_path = (process.env.HOME || process.env.USERPROFILE) + "/.docker" } } var wss = new WebSocketServer({server: server}); app.get(ctxRoot + 'apis/*', function(req, response) { var path = req.params[0]; var jsonData={}; var options = { path: ('/' + path), method: 'GET' } var request = http.request; if (cert_path) { request = https.request; options.ca = fs.readFileSync(cert_path + '/ca.pem'); options.cert = fs.readFileSync(cert_path + '/cert.pem'); options.key = fs.readFileSync(cert_path + '/key.pem'); } if (docker_host) { options.host = docker_host; options.port = docker_port; } else if (process.platform === 'win32') { options.socketPath = '\\\\.\\pipe\\docker_engine'; } else { options.socketPath = '/var/run/docker.sock'; } var req = request(options, (res) => { var data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { jsonData['objects'] = JSON.parse(data.toString()); response.json(jsonData); }); }); req.on('error', (e) => { console.log(`problem with request: ${e.message}`); console.log(e.stack); }); req.end(); });
dockersamples/docker-swarm-visualizer
server.js
JavaScript
apache-2.0
2,529
"use strict"; import React from "react"; import ReactDOM from "react-dom"; import debugFactory from "debug"; const debug = debugFactory('app:components:RainfallVsYieldChartComponent'); import CropYieldsChart from "../../charts/cropYieldsVersusRainfall"; import {Glyphicon, Button, DropdownButton, MenuItem} from "react-bootstrap"; let RainfallVsYieldChartComponent = React.createClass({ propTypes: { crop: React.PropTypes.string.isRequired, state: React.PropTypes.string.isRequired, lat: React.PropTypes.number.isRequired, lng: React.PropTypes.number.isRequired, zoom: React.PropTypes.number.isRequired, radius: React.PropTypes.number.isRequired }, contextTypes: { cropStore: React.PropTypes.object.isRequired }, render() { return ( <div> <CropYieldsChart radius={this.props.radius} crop={this.context.cropStore.getCropDatum(this.props.crop)} state={this.props.state} lat={this.props.lat} lng={this.props.lng} zoom={this.props.zoom} /> </div> ); } }); module.exports = RainfallVsYieldChartComponent;
atsid/EPA-EDS
src/js/components/panes/cropmetrics/rainfall_vs_yield.js
JavaScript
apache-2.0
1,261
'use strict'; /** * The bot implementation * * Instantiate apssing a connector via * makeBot * */ // var exec = require('child_process').exec // var request2 = require('request-defaults') // var request = request2.globalDefaults({ // 'proxy': 'http://proxy:8080', // 'https-proxy': 'https://proxy:8080' // }) var builder = require('botbuilder'); var dispatcher = require('../match/dispatcher.js').dispatcher; // globalTunnel.initialize({ // host: 'proxy.exxxample.com', // port: 8080 // }) // Create bot and bind to console // var connector = new htmlconnector.HTMLConnector() // connector.setAnswerHook(function (sAnswer) { // console.log('Got answer : ' + sAnswer + '\n') // }) var sensitive = require('../../sensitive/data.js'); var bot; // setTimeout(function () { // connector.processMessage('start unit test ABC ') // }, 5000) /** * Construct a bot * @param connector {Connector} the connector to use * HTMLConnector * or connector = new builder.ConsoleConnector().listen() */ function makeBot(connector) { bot = new builder.UniversalBot(connector); // Create LUIS recognizer that points at our model and add it as the root '/' dialog for our Cortana Bot. var model = sensitive.modelurl; // var model = 'https://api.projectoxford.ai/luis/v2.0/apps/c413b2ef-382c-45bd-8ff0-f76d60e2a821?subscription-key=c21398b5980a4ce09f474bbfee93b892&q=' var recognizer = new builder.LuisRecognizer(model); var dialog = new builder.IntentDialog({ recognizers: [recognizer] }); // dialog.onBegin(function(session,args) { // console.log("beginning ...") // session.dialogData.retryPrompt = args && args.retryPrompt || "I am sorry" // session.send("What do you want?") // // }) bot.dialog('/', dialog); dialog.matches(/builtin.intent.ringPerson/i, [function (session, args, next) { // console.log("Show session : " + JSON.stringify(session)) console.log(JSON.stringify(args)); next(); }, function (session, args, next) { // console.log("Show session : " + JSON.stringify(session)) console.log(JSON.stringify(args)); next(); }]); dialog.matches('ShowEntity', [function (session, args, next) { var isCombinedIndex = {}; var oNewEntity; // fuse entities var combinedEntities = args.entities.map(function (oEntity, iIndex) { if (isCombinedIndex[iIndex]) { return undefined; } var i = iIndex + 1; oNewEntity = Object.assign({}, oEntity); while (i < args.entities.length) { var oNext = args.entities[i]; if (oNext.type === oEntity.type && (oNext.startIndex === oNewEntity.endIndex + 1 || oNext.startIndex === oNewEntity.endIndex + 2)) { var spaced = oNext.startIndex === oNewEntity.endIndex + 2; isCombinedIndex[i] = true; oNewEntity.entity = oNewEntity.entity + (spaced ? ' ' : '') + oNext.entity; oNewEntity.endIndex = oNext.endIndex; i = i + 1; } else { i = args.entities.length; } } // while return oNewEntity; }); combinedEntities = combinedEntities.filter(function (oEntity) { return oEntity !== undefined; }); console.log('raw: ' + JSON.stringify(args.entities), undefined, 2); console.log('combined: ' + JSON.stringify(combinedEntities, undefined, 2)); var systemId = builder.EntityRecognizer.findEntity(combinedEntities, 'SystemId'); var client = builder.EntityRecognizer.findEntity(args.entities, 'client'); var systemObjectId = builder.EntityRecognizer.findEntity(combinedEntities, 'systemObjectId') || builder.EntityRecognizer.findEntity(combinedEntities, 'SystemObject') || builder.EntityRecognizer.findEntity(combinedEntities, 'builtin.number'); var systemObjectCategory = builder.EntityRecognizer.findEntity(args.entities, 'SystemObjectCategory'); session.dialogData.system = { systemId: systemId, client: client }; var sSystemId = systemId && systemId.entity; var sClient = client && client.entity; var ssystemObjectId = systemObjectId && systemObjectId.entity; var sSystemObjectCategory = systemObjectCategory && systemObjectCategory.entity; console.log('Show entities: ' + JSON.stringify(args.entities, undefined, 2)); var sTool = null; // dirty hack: if (sSystemObjectCategory === 'unit' || sSystemObjectCategory === 'unit test') { sTool = null; } if (sSystemId && sSystemId.indexOf('system ') === 0) { sSystemId = sSystemId.substring('system '.length); } if (sSystemObjectCategory === 'catalog') { sTool = 'FLPD'; } if (sSystemObjectCategory === 'group') { sTool = 'FLPD'; } if (!ssystemObjectId && !sSystemObjectCategory) { sTool = 'FLP'; } session.send('Showing entity "%s" of type "%s" in System "%s" client "%s" ', // Creating alarm named "%s" for %d/%d/%d %d:%02d%s', ssystemObjectId, sSystemObjectCategory, sSystemId, sClient); var u = dispatcher.execShowEntity({ systemId: sSystemId, client: sClient, tool: sTool, systemObjectCategory: sSystemObjectCategory, systemObjectId: ssystemObjectId }); if (u) { session.send(u); } // console.log("show entity, Show session : " + JSON.stringify(session)) // console.log("Show entity : " + JSON.stringify(args.entities)) }]); dialog.matches('StartTransaction', [function (session, args, next) { console.log('Start Transaction session : ' + JSON.stringify(session)); console.log('Show entity : ' + JSON.stringify(args.entities)); }]); dialog.matches('ringperson', [function (session, args, next) { console.log('sringperson session : ' + JSON.stringify(session)); console.log('ringperson' + JSON.stringify(args.entities)); }]); // Add intent handlers dialog.matches('builtin.intent.alarm.set_alarm', [function (session, args, next) { console.log('builtin alarm'); // Resolve and store any entities passed from LUIS. var title = builder.EntityRecognizer.findEntity(args.entities, 'builtin.alarm.title'); var time = builder.EntityRecognizer.resolveTime(args.entities); var alarm = session.dialogData.alarm = { title: title ? title.entity : null, timestamp: time ? time.getTime() : null }; // Prompt for title if (!alarm.title) { builder.Prompts.text(session, 'What would you like to call your alarm?'); } else { next(); } }, function (session, results, next) { var alarm = session.dialogData.alarm; if (results.response) { alarm.title = results.response; } // Prompt for time (title will be blank if the user said cancel) if (alarm.title && !alarm.timestamp) { builder.Prompts.time(session, 'What time would you like to set the alarm for?'); } else { next(); } }, function (session, results) { var alarm = session.dialogData.alarm; if (results.response) { var time = builder.EntityRecognizer.resolveTime([results.response]); alarm.timestamp = time ? time.getTime() : null; } // Set the alarm (if title or timestamp is blank the user said cancel) if (alarm.title && alarm.timestamp) { // Save address of who to notify and write to scheduler. alarm.address = session.message.address; alarms[alarm.title] = alarm; // Send confirmation to user var date = new Date(alarm.timestamp); var isAM = date.getHours() < 12; session.send('Creating alarm named "%s" for %d/%d/%d %d:%02d%s', alarm.title, date.getMonth() + 1, date.getDate(), date.getFullYear(), isAM ? date.getHours() : date.getHours() - 12, date.getMinutes(), isAM ? 'am' : 'pm'); } else { session.send('Ok... no problem.'); } }]); dialog.onDefault(builder.DialogAction.send('I\'m sorry I didn\'t understand. I can only show start and ring')); // Very simple alarm scheduler var alarms = {}; setInterval(function () { var now = new Date().getTime(); for (var key in alarms) { var alarm = alarms[key]; if (now >= alarm.timestamp) { var msg = new builder.Message().address(alarm.address).text('Here\'s your \'%s\' alarm.', alarm.title); bot.send(msg); delete alarms[key]; } } }, 15000); } if (module) { module.exports = { makeBot: makeBot }; }
jfseb/fdevstart
gen2/bot/dialog.js
JavaScript
apache-2.0
8,343
/*H-ui.admin.js v2.3.1 date:15:42 2015.08.19 by:guojunhui*/ /*获取顶部选项卡总长度*/ function tabNavallwidth(){ var taballwidth=0, $tabNav = $(".acrossTab"), $tabNavWp = $(".Hui-tabNav-wp"), $tabNavitem = $(".acrossTab li"), $tabNavmore =$(".Hui-tabNav-more"); if (!$tabNav[0]){return} $tabNavitem.each(function(index, element) { taballwidth+=Number(parseFloat($(this).width()+60))}); $tabNav.width(taballwidth+25); var w = $tabNavWp.width(); if(taballwidth+25>w){ $tabNavmore.show()} else{ $tabNavmore.hide(); $tabNav.css({left:0})} } /*左侧菜单响应式*/ function Huiasidedisplay(){ if($(window).width()>=768){ $(".Hui-aside").show() } } function getskincookie(){ var v = getCookie("Huiskin"); if(v==null||v==""){ v="default"; } $("#skin").attr("href","/resources/Jy_admin/skin/"+v+"/skin.css"); } $(function(){ getskincookie(); //layer.config({extend: 'extend/layer.ext.js'}); Huiasidedisplay(); var resizeID; $(window).resize(function(){ clearTimeout(resizeID); resizeID = setTimeout(function(){ Huiasidedisplay(); },500); }); $(".Hui-nav-toggle").click(function(){ $(".Hui-aside").slideToggle(); }); $(".Hui-aside").on("click",".menu_dropdown dd li a",function(){ if($(window).width()<768){ $(".Hui-aside").slideToggle(); } }); /*左侧菜单*/ $.Huifold(".menu_dropdown dl dt",".menu_dropdown dl dd","fast",1,"click"); /*选项卡导航*/ $(".Hui-aside").on("click",".menu_dropdown a",function(){ if($(this).attr('_href')){ var bStop=false; var bStopIndex=0; var _href=$(this).attr('_href'); var _titleName=$(this).html(); var topWindow=$(window.parent.document); var show_navLi=topWindow.find("#min_title_list li"); show_navLi.each(function() { if($(this).find('span').attr("data-href")==_href){ bStop=true; bStopIndex=show_navLi.index($(this)); return false; } }); if(!bStop){ creatIframe(_href,_titleName); min_titleList(); } else{ show_navLi.removeClass("active").eq(bStopIndex).addClass("active"); var iframe_box=topWindow.find("#iframe_box"); iframe_box.find(".show_iframe").hide().eq(bStopIndex).show().find("iframe").attr("src",_href); } } }); function min_titleList(){ var topWindow=$(window.parent.document); var show_nav=topWindow.find("#min_title_list"); var aLi=show_nav.find("li"); }; function creatIframe(href,titleName){ var topWindow=$(window.parent.document); var show_nav=topWindow.find('#min_title_list'); show_nav.find('li').removeClass("active"); var iframe_box=topWindow.find('#iframe_box'); show_nav.append('<li class="active"><span data-href="'+href+'">'+titleName+'</span><i></i><em></em></li>'); tabNavallwidth(); var iframeBox=iframe_box.find('.show_iframe'); iframeBox.hide(); iframe_box.append('<div class="show_iframe"><div class="loading"></div><iframe frameborder="0" src='+href+'></iframe></div>'); var showBox=iframe_box.find('.show_iframe:visible'); showBox.find('iframe').attr("src",href).load(function(){ showBox.find('.loading').hide(); }); } var num=0; var oUl=$("#min_title_list"); var hide_nav=$("#Hui-tabNav"); $(document).on("click","#min_title_list li",function(){ var bStopIndex=$(this).index(); var iframe_box=$("#iframe_box"); $("#min_title_list li").removeClass("active").eq(bStopIndex).addClass("active"); iframe_box.find(".show_iframe").hide().eq(bStopIndex).show(); }); $(document).on("click","#min_title_list li i",function(){ var aCloseIndex=$(this).parents("li").index(); $(this).parent().remove(); $('#iframe_box').find('.show_iframe').eq(aCloseIndex).remove(); num==0?num=0:num--; tabNavallwidth(); }); $(document).on("dblclick","#min_title_list li",function(){ var aCloseIndex=$(this).index(); var iframe_box=$("#iframe_box"); if(aCloseIndex>0){ $(this).remove(); $('#iframe_box').find('.show_iframe').eq(aCloseIndex).remove(); num==0?num=0:num--; $("#min_title_list li").removeClass("active").eq(aCloseIndex-1).addClass("active"); iframe_box.find(".show_iframe").hide().eq(aCloseIndex-1).show(); tabNavallwidth(); }else{ return false; } }); tabNavallwidth(); $('#js-tabNav-next').click(function(){ num==oUl.find('li').length-1?num=oUl.find('li').length-1:num++; toNavPos(); }); $('#js-tabNav-prev').click(function(){ num==0?num=0:num--; toNavPos(); }); function toNavPos(){ oUl.stop().animate({'left':-num*100},100); } /*换肤*/ $("#Hui-skin .dropDown-menu a").click(function(){ var v = $(this).attr("data-val"); setCookie("Huiskin", v); $("#skin").attr("href","/resources/Jy_admin/skin/"+v+"/skin.css"); }); }); /*弹出层*/ /* 参数解释: title 标题 url 请求的url id 需要操作的数据id w 弹出层宽度(缺省调默认值) h 弹出层高度(缺省调默认值) */ function layer_show(title,url,w,h){ if (title == null || title == '') { title=false; }; if (url == null || url == '') { url="404.html"; }; if (w == null || w == '') { w=800; }; if (h == null || h == '') { h=($(window).height() - 50); }; layer.open({ type: 2, area: [w+'px', h +'px'], fix: false, //不固定 maxmin: true, shade:0.4, title: title, content: url }); } /*关闭弹出框口*/ function layer_close(){ var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); }
YeGithubAdmin/JYHD
resources/Jy_admin/js/H-ui.admin.js
JavaScript
apache-2.0
5,403
import React, { Component } from 'react'; import { Text } from 'react-native'; import { connectStyle } from '@shoutem/theme'; import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames'; class Label extends Component { render() { return ( <Text ref={c => this._root = c} {...this.props} /> ); } } Label.propTypes = { ...Text.propTypes, style: React.PropTypes.object, }; const StyledLabel = connectStyle('NativeBase.Label', {}, mapPropsToStyleNames)(Label); export { StyledLabel as Label, };
tausifmuzaffar/bisApp
node_modules/native-base/src/basic/Label.js
JavaScript
apache-2.0
525
/* * Copyright 2010 Comcast Cable Communications Management, LLC * * 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() { DAWGPOUND.reservationHandler(); }); var DAWGPOUND = (function() { var dawgApi = {}; // dawgApi.reservationDialogSetup = function() { // $("#reservation-lock-dialog-date-picker").datepicker(); // $("#reservation-lock-dialog").dialog({ // buttons : [ { // text : "Reserve Device(s).", // click : function() { // var originId = $("#reservation-lock-dialog").data("origin"); // var element = $(originId); // var deviceId = $(element).data("deviceid"); // var token = $(element).data("token"); // var date = $("#datepicker").datepicker( 'getDate' ).getTime(); // dawgApi.reserve(origin, deviceId, token, date); // $(this).dialog("close"); // } // } ] // }); // }; dawgApi.reservationHandler = function() { $('.lockable').click(function(event) { var element = this; var deviceId = $(element).data("deviceid"); var loginUser = $(element).data("loginuser"); var locked = $(element).data("locked"); var expiration = -1; //dialog.data("origin",this.id); if (locked) { dawgApi.unreserve(element, deviceId, loginUser); } else { dawgApi.reserve(element, deviceId, loginUser, expiration); } }); $('#multilock').click(function(event) { var elements = $('.bulk-checkbox:checkbox:checked'); $.each(elements, function(index, element) { var deviceId = $(element).data("deviceid"); var sourceElement = $("#td-"+deviceId); var loginUser = $(sourceElement).data("loginuser"); dawgApi.reserve(sourceElement, deviceId, loginUser, -1); }); }); $('#multiunlock').click(function(event) { var elements = $('.bulk-checkbox:checkbox:checked'); $.each(elements, function(index, element) { var deviceId = $(element).data("deviceid"); var sourceElement = $("#td-"+deviceId); var loginUser = $(sourceElement).data("loginuser"); dawgApi.unreserve(sourceElement, deviceId, loginUser); }); }); }; dawgApi.reserve = function(element, deviceId, token, expiration) { var posturl = DAWG_POUND + "reservations/reserve/" + token + "/" + deviceId + "/" + expiration; $.post(posturl, function(data) { if (data) { $(element).html('<i class="icon-lock"></i> ' + token + " - " + expiration); $(element).data("locked",true); $(element).data("token",token); } else { console.log(data + "\ncould not reserve!"); } }); }; dawgApi.unreserve = function(element, deviceId, token) { var posturl = DAWG_POUND + "reservations/unreserve/" + deviceId; $.post(posturl, function(data) { if (data) { $(element).html('<i class="icon-unlock"></i> old reserver: ' + data); $(element).data("locked",false); console.log(data); } else { console.log(data + "\ncould not unreserve!"); } }); }; return dawgApi; }());
trentontrees/dawg
libraries/dawg-house/src/main/webapp/resources/scripts/dawg-pound.js
JavaScript
apache-2.0
4,060
app.factory('userService', function($http, $auth, $state, $q, $rootScope) { var _identity = undefined; var _authenticated = false; var _authenticate = function(identity) { _identity = identity; if(identity != null) { _authenticated = true; } }; var _isInRole = function(role) { if (!_authenticated || !_identity.roles) return false; return _identity.roles.indexOf(role) != -1; }; var _isInAnyRole= function(roles) { if (!_authenticated || !_identity.roles) return false; for (var i = 0; i < roles.length; i++) { if (this.isInRole(roles[i])) return true; } return false; } return { isIdentityResolved: function() { return angular.isDefined(_identity); }, isAuthenticated: function() { return _authenticated; }, authenticate: function(identity) { _authenticate(identity) }, isInRole: function(role) { return _isInRole(role) }, isInAnyRole: function(roles) { return _isInAnyRole(roles) }, identity: function() { var deferred = $q.defer(); if(this.isIdentityResolved()) { deferred.resolve(_identity); } else { $http.get('/api/user') .success(function (user) { _authenticate(user); deferred.resolve(_identity); }) .error(function (data, status, headers, config) { _authenticate(null); deferred.resolve(data, status, headers, config); }); } return deferred.promise; }, loginWithFacebook: function() { var deferred = $q.defer(); $auth.authenticate("facebook") .then(function(response) { _authenticate(response.data.user); deferred.resolve(_identity, response); }) .catch(function(response) { deferred.reject(response); }); return deferred.promise; }, authorize: function() { return this.identity() .then(function() { console.log("?"); if(($rootScope.toState.data.requiresLogin) && !_authenticated) { console.log("changestate"); $state.go('signin'); } else { if ($rootScope.toState.data.roles && $rootScope.toState.data.roles.length > 0 && !_isInAnyRole($rootScope.toState.data.roles)) { if (_authenticated) { console.log("accessdenied"); $state.go('accessdenied'); } else { console.log("go signin"); $rootScope.returnToState = $rootScope.toState; $rootScope.returnToStateParams = $rootScope.toStateParams; $state.go('signin'); } } } console.log("authorized"); }); } }; });
mehdichamouma/session-montpellier
ui/app/scripts/services/userService.js
JavaScript
apache-2.0
2,865
/** * @license * Copyright 2014 Google Inc. 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 Imports the given keys into the extension. */ goog.provide('e2e.ext.actions.ImportKey'); goog.require('e2e.ext.actions.Action'); goog.require('e2e.ext.actions.GetKeyDescription'); goog.require('e2e.ext.utils.Error'); goog.scope(function() { var actions = e2e.ext.actions; var constants = e2e.ext.constants; var utils = e2e.ext.utils; /** * Constructor for the action. * @constructor * @implements {e2e.ext.actions.Action.<(string|!e2e.ByteArray), !Array.<string>>} */ actions.ImportKey = function() {}; /** @override */ actions.ImportKey.prototype.execute = function(ctx, request, requestor, callback, errorCallback) { if (!goog.isFunction(request.passphraseCallback)) { errorCallback( new utils.Error('Unable to import key.', 'errorUnableToImportKey')); return; } if (typeof request.content === 'string') { var r = /** @type {!e2e.ext.messages.ApiRequest.<string>} */ (request); new actions.GetKeyDescription(). execute(ctx, r, requestor, function(result) { if (goog.isDef(result)) { ctx.importKey( /** @type {!function(string, !function(string))} */ (request.passphraseCallback), request.content). addCallback(callback).addErrback(errorCallback); } }, errorCallback); } else { // TODO(yan): Show a dialog in this case as well. ctx.importKey( /** @type {!function(string, !function(string))} */ (request.passphraseCallback), request.content). addCallback(callback).addErrback(errorCallback); } }; }); // goog.scope
diracdeltas/end-to-end-1
src/javascript/crypto/e2e/extension/actions/importkey.js
JavaScript
apache-2.0
2,245
'use strict'; const express = require('express'); const router = express.Router(); const offset = require('server/middleware/pageoffset.js'); const daterange = require('server/middleware/daterange.js'); const normalizequery = require('server/middleware/normalizequery.js'); const storage = require('server/storage'); const sttclient = require('server/stt/clients/sttclient.js'); const client = sttclient({db: storage.db, models: storage.models}); const dateRange = daterange.dateRangeMiddleware(); const lowerCaseQueryKeys = normalizequery.lowerCaseQueryKeys(); const pageOffset = offset(client.changes.limit); const handleChangesReq = (req, res, next) => { return client.changes.allChangesAndCount({data: { sampleId: req.params.sampleId, facilityKey: req.params.facilityKey, regionKey: req.params.regionKey, afterDate: req.query.afterdate, beforeDate: req.query.beforedate, offset: req.offset }}) .then(results => res.json(results)) .catch(next); }; const handleChangesExport = (req, res, next) => { return client.changes.allChanges({ csvResult: true, unlimited: true, data: { sampleId: req.params.sampleId, facilityKey: req.params.facilityKey, regionKey: req.params.regionKey, afterDate: req.query.afterdate, beforeDate: req.query.beforedate }}) .then(results => res.send(results)) .catch(next); }; const prepCSVRes = (req, res, next) => { res.set({ 'Content-Disposition': `attachment; filename=changes-${Date.now()}.csv`, 'Content-type': 'text/csv' }); next(); }; router.get('/changes.csv', pageOffset, lowerCaseQueryKeys, dateRange, prepCSVRes, handleChangesExport); router.get('/ids/:sampleId/changes.csv', pageOffset, lowerCaseQueryKeys, dateRange, prepCSVRes, handleChangesExport); router.get('/facility/:facilityKey/changes.csv', pageOffset, lowerCaseQueryKeys, dateRange, prepCSVRes, handleChangesExport); router.get('/region/:regionKey/changes.csv', pageOffset, lowerCaseQueryKeys, dateRange, prepCSVRes, handleChangesExport); router.get('/changes', pageOffset, lowerCaseQueryKeys, dateRange, handleChangesReq); router.get('/facility/:facilityKey/changes', pageOffset, lowerCaseQueryKeys, dateRange, handleChangesReq); router.get('/region/:regionKey/changes', pageOffset, lowerCaseQueryKeys, dateRange, handleChangesReq); const handleSampleChangesReq = (req, res, next) => { return client.changes.allChangesAndCount({ unlimited: true, data: {sampleId: req.params.sampleId}}) .then(results => res.json(results)) .catch(next); }; // Always return all the changes for an individual Sample ID router.get('/ids/:sampleId/changes', handleSampleChangesReq); module.exports = router;
Kharatsa/sample-tracking
app/server/stt/routes/changesroutes.js
JavaScript
apache-2.0
2,727
export const compareDateStrings = (a, b) => { a = Date.parse(a) b = Date.parse(b) if (a > b) { return 1 } if (a < b) { return -1 } return 0 } // https://vuejs.org/v2/guide/syntax.html#Filters export const normalize = value => { if (!value) return '' value = value.toString().replace(/_/g, ' ') return value.charAt(0).toUpperCase() + value.slice(1) } export const search = (obj, query) => [obj.description, obj.title, obj.url] .join(' ') .toUpperCase() .includes(query.toUpperCase()) export const maxLength = (value, length) => { if ((value.length + 3) >= length) { return value.slice(0, length) + '...' } return value } export const normalizeUrl = value => value.replace(/^(http?:\/\/)|(https?:\/\/)/g, '') export const formatUrl = value => { const pos = value.search(/^(http?:\/\/)|(https?:\/\/)/g) if (pos !== 0) { return 'http://' + value } return value }
sbdchd/linky
frontend/src/utilities.js
JavaScript
bsd-2-clause
928
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ //In this particular case, we are using this JavaScript in the case where we are employing an external template //And NOT generating fields //For now, we are only using this when creating an entirely new object, but later will incorporate editing functionality as well var hasActivity = { onLoad: function() { this.mixIn(); this.initObjects(); this.initPage(); this.bindEventListeners(); }, mixIn: function() { // Get the custom form data from the page $.extend(this, customFormData); $.extend(this, i18nStrings); }, initObjects:function() { this.searchUrlButton = $("input[name='selectAcUrl']"); this.formSubmit = $("input[name='formSubmit'"); this.actionType = $("input[name='actionType']"); this.agentTypeDiv = $("div#agentTypeDropdown"); this.vocabSource = $("div#vocabSource"); }, // Initial page setup. Called only at page load. initPage: function() { //Make invisible for now this.agentTypeDiv.hide(); }, bindEventListeners:function() { this.searchUrlButton.change(function() { var selectedInput = $("input[name='selectAcUrl']:checked"); var selectedUrl = selectedInput.val(); var agentNameInput = $("#agentName"); agentNameInput.attr("acUrl", selectedUrl); //Also change the value of the agent type dropdown on the basis of what is checked hasActivity.setAgentType(selectedInput.attr("lookupType")); }); //If create new chosen, then show lookupType this.actionType.change(function() { var actionTypeVal = $(this).val(); if(actionTypeVal == "create") { hasActivity.vocabSource.hide(); hasActivity.agentTypeDiv.show(); } else { hasActivity.vocabSource.show(); hasActivity.agentTypeDiv.hide(); } }); this.formSubmit.click(function() { hasActivity.copyActivityLabel(); hasActivity.updateAgentType(); return true; }); }, copyActivityLabel:function() { //Find selected activity label var selectedLabel = $("#activityType option:selected").text(); $("#activityLabel").val(selectedLabel); }, setAgentType:function(lookupType) { $("#agentType").val(lookupType); }, updateAgentType:function() { //if lookup selected, then need to set agent type value var actionTypeVal = hasActivity.actionType.val(); if(actionTypeVal == "lookup") { var lookupType = $("input[name='selectAcUrl']:checked").attr("lookupType"); hasActivity.setAgentType(lookupType); } } }; $(document).ready(function() { hasActivity.onLoad(); });
ld4l-labs/vitrolib
webapp/src/main/webapp/templates/freemarker/edit/forms/js/hasActivity.js
JavaScript
bsd-2-clause
3,169
function foo() { Enter({ name: 'foo', lineNumber: 1, range: [0, 17] }); Exit({ name: 'foo', lineNumber: 1, range: [0, 17] }); } var bar = function() { Enter({ name: 'bar', lineNumber: 3, range: [29, 170] }); console.log('Hello'); function baz() { Enter({ name: 'baz', lineNumber: 7, range: [74, 115] }); alert('baz') Exit({ name: 'baz', lineNumber: 7, range: [74, 115] }); } (function() { Enter({ name: '[Anonymous]', lineNumber: 11, range: [122, 136] }); Exit({ name: '[Anonymous]', lineNumber: 11, range: [122, 136] }); }()); (function abc() { Enter({ name: 'abc', lineNumber: 12, range: [146, 164] }); Exit({ name: 'abc', lineNumber: 12, range: [146, 164] }); }()); Exit({ name: 'bar', lineNumber: 3, range: [29, 170] }); }
ariya/esmorph
test/data/multiple_morphed.js
JavaScript
bsd-2-clause
821
var searchData= [ ['normalize',['normalize',['../classsc_1_1_quat.html#a4fd2ed1eb85f002a730f137054e02f1e',1,'sc::Quat']]], ['numconnectors',['numConnectors',['../classsc_1_1_slave.html#aeb03338c2e663fff7549390ecb99e25d',1,'sc::Slave']]] ];
umitresearchlab/strong-coupling-core
docs/search/functions_a.js
JavaScript
bsd-2-clause
244
(function () { app.validate = { getValidator: function (selector, params) { return $(selector).kendoValidator(_.merge({ validateOnBlur: true, rules: { validateBirthDateRule: function (input) { if (input.is('input[type=date]')) { var selectedDate = new Date(input.val()); var today = new Date(); var selectedDateAfterToday = selectedDate > today; return !selectedDateAfterToday; } return true; }, validateEmailRule: function (input) { if (input.is('input[name=email]') && !!input.val()) { return input.val().indexOf('@') > 0; } return true; } }, messages: { validateBirthDateRule: 'Please set a birth date in the past.', validateEmailRule: 'Not valid email format.', required: function (input) { if (input.is('input[type=password]')) { return 'The specified password is not valid.' } return 'This field is required.'; } } }, params)).data('kendoValidator'); } } }());
gngeorgiev/platform-friends
friends-hybrid/common/validate.js
JavaScript
bsd-2-clause
1,542
/*! * OS.js - JavaScript Cloud/Web Desktop Platform * * Copyright (c) 2011-2016, Anders Evenrud <andersevenrud@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @author Anders Evenrud <andersevenrud@gmail.com> * @licence Simplified BSD License */ (function(WindowManager, GUI, Utils, API, VFS) { 'use strict'; var SETTING_STORAGE_NAME = 'CoreWM'; var PADDING_PANEL_AUTOHIDE = 10; // FIXME: Replace with a constant ?! ///////////////////////////////////////////////////////////////////////////// // SETTINGS ///////////////////////////////////////////////////////////////////////////// function DefaultSettings(defaults) { var compability = Utils.getCompability(); var cfg = { animations : compability.css.animation, fullscreen : true, desktopMargin : 5, wallpaper : 'osjs:///themes/wallpapers/wallpaper.png', icon : 'osjs-white.png', backgroundColor : '#572a79', fontFamily : 'Karla', theme : 'default', icons : 'default', sounds : 'default', background : 'image-fill', windowCornerSnap : 0, windowSnap : 0, useTouchMenu : compability.touch, enableIconView : false, enableSwitcher : true, enableHotkeys : true, enableSounds : true, invertIconViewColor : false, moveOnResize : true, // Move windows into viewport on resize desktopIcons : [], panels : [ { options: { position: 'top', ontop: false, autohide: false, background: '#101010', foreground: '#ffffff', opacity: 85 }, items: [ {name: 'AppMenu', settings: {}}, {name: 'Buttons', settings: {}}, {name: 'WindowList', settings: {}}, {name: 'NotificationArea', settings: {}}, {name: 'Clock', settings: {}} ] } ] }; if ( defaults ) { cfg = Utils.mergeObject(cfg, defaults); } return cfg; } ///////////////////////////////////////////////////////////////////////////// // EXPORTS ///////////////////////////////////////////////////////////////////////////// OSjs.Applications = OSjs.Applications || {}; OSjs.Applications.CoreWM = OSjs.Applications.CoreWM || {}; OSjs.Applications.CoreWM.DefaultSettings = DefaultSettings; })(OSjs.Core.WindowManager, OSjs.GUI, OSjs.Utils, OSjs.API, OSjs.VFS);
arduino-org/OS.js-v2
src/packages/default/CoreWM/settings.js
JavaScript
bsd-2-clause
3,971
/* * Package: xrefs.js * * Namespace: amigo.data.xrefs * * This package was automatically created during an AmiGO 2 installation * from the GO.xrf_abbs file at: "http://www.geneontology.org/doc/GO.xrf_abbs". * * NOTE: This file is generated dynamically at installation time. * Hard to work with unit tests--hope it's not too bad. You have to * occasionally copy back to keep the unit tests sane. */ // All of the server/instance-specific meta-data. if ( typeof amigo == "undefined" ){ var amigo = {}; } if ( typeof amigo.data == "undefined" ){ amigo.data = {}; } /* * Variable: xrefs * * All the external references that we know about. */ amigo.data.xrefs = { "taxon" : { "url_syntax" : "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=[example_id]", "example_id" : "taxon:7227", "datatype" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=3702", "abbreviation" : "taxon", "object" : null, "database" : "NCBI Taxonomy", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "ensembl" : { "entity_type" : "SO:0000673 ! transcript", "local_id_syntax" : "ENS[A-Z0-9]{10,17}", "database" : "Ensembl database of automatically annotated genomic data", "uri_prefix" : null, "generic_url" : "http://www.ensembl.org/", "datatype" : null, "example_id" : "ENSEMBL:ENSP00000265949", "url_syntax" : "http://www.ensembl.org/id/[example_id]", "object" : null, "abbreviation" : "Ensembl", "url_example" : "http://www.ensembl.org/id/ENSP00000265949", "id" : null, "fullname" : null, "name" : null }, "kegg" : { "object" : null, "url_example" : null, "abbreviation" : "KEGG", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.genome.ad.jp/kegg/", "datatype" : null, "example_id" : null, "url_syntax" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Kyoto Encyclopedia of Genes and Genomes" }, "pfam" : { "database" : "Pfam database of protein families", "local_id_syntax" : "PF[0-9]{5}", "entity_type" : "SO:0000839 ! polypeptide region", "uri_prefix" : null, "url_syntax" : "http://www.sanger.ac.uk/cgi-bin/Pfam/getacc?[example_id]", "datatype" : null, "example_id" : "Pfam:PF00046", "generic_url" : "http://www.sanger.ac.uk/Software/Pfam/", "fullname" : null, "id" : null, "name" : null, "description" : "Pfam is a collection of protein families represented by sequence alignments and hidden Markov models (HMMs)", "url_example" : "http://www.sanger.ac.uk/cgi-bin/Pfam/getacc?PF00046", "abbreviation" : "Pfam", "object" : null }, "sgd_ref" : { "object" : null, "abbreviation" : "SGD_REF", "url_example" : "http://www.yeastgenome.org/reference/S000049602/overview", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.yeastgenome.org/", "datatype" : null, "example_id" : "SGD_REF:S000049602", "url_syntax" : "http://www.yeastgenome.org/reference/[example_is]/overview", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Saccharomyces Genome Database" }, "um-bbd_enzymeid" : { "object" : null, "url_example" : "http://umbbd.msi.umn.edu/servlets/pageservlet?ptype=ep&enzymeID=e0230", "abbreviation" : "UM-BBD_enzymeID", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://umbbd.msi.umn.edu/", "example_id" : "UM-BBD_enzymeID:e0413", "datatype" : null, "url_syntax" : "http://umbbd.msi.umn.edu/servlets/pageservlet?ptype=ep&enzymeID=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "University of Minnesota Biocatalysis/Biodegradation Database" }, "ncbi_locus_tag" : { "url_syntax" : null, "datatype" : null, "example_id" : "NCBI_locus_tag:CTN_0547", "generic_url" : "http://www.ncbi.nlm.nih.gov/", "fullname" : null, "name" : null, "id" : null, "url_example" : null, "abbreviation" : "NCBI_locus_tag", "object" : null, "database" : "NCBI locus tag", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "tair" : { "generic_url" : "http://www.arabidopsis.org/", "url_syntax" : "http://arabidopsis.org/servlets/TairObject?accession=[example_id]", "example_id" : "TAIR:locus:2146653", "datatype" : null, "abbreviation" : "TAIR", "url_example" : "http://arabidopsis.org/servlets/TairObject?accession=locus:2146653", "object" : null, "fullname" : null, "id" : null, "name" : null, "entity_type" : "SO:0000185 ! primary transcript", "database" : "The Arabidopsis Information Resource", "local_id_syntax" : "locus:[0-9]{7}", "uri_prefix" : null }, "obo_sf_po" : { "datatype" : null, "example_id" : "OBO_SF_PO:3184921", "url_syntax" : "https://sourceforge.net/tracker/index.php?func=detail&aid=[example_id]&group_id=76834&atid=835555", "generic_url" : "http://sourceforge.net/tracker/?func=browse&group_id=76834&atid=835555", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "https://sourceforge.net/tracker/index.php?func=detail&aid=3184921&group_id=76834&atid=835555", "abbreviation" : "OBO_SF_PO", "database" : "Source Forge OBO Plant Ontology (PO) term request tracker", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "rnacentral" : { "uri_prefix" : null, "local_id_syntax" : "URS[0-9A-F]{10}([_\\/][0-9]+){0,1}", "database" : "RNAcentral", "entity_type" : "CHEBI:33697 ! ribonucleic acid", "fullname" : null, "name" : null, "id" : null, "object" : null, "description" : "An international database of ncRNA sequences", "url_example" : "http://rnacentral.org/rna/URS000047C79B_9606", "abbreviation" : "RNAcentral", "example_id" : "RNAcentral:URS000047C79B_9606", "datatype" : null, "url_syntax" : "http://rnacentral.org/rna/[example_id]", "generic_url" : "http://rnacentral.org" }, "germonline" : { "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.germonline.org/", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "GermOnline", "url_example" : null, "database" : "GermOnline", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "goc" : { "entity_type" : "BET:0000000 ! entity", "database" : "Gene Ontology Consortium", "uri_prefix" : null, "generic_url" : "http://www.geneontology.org/", "example_id" : null, "datatype" : null, "url_syntax" : null, "object" : null, "abbreviation" : "GOC", "url_example" : null, "fullname" : null, "id" : null, "name" : null }, "bhf-ucl" : { "fullname" : null, "name" : null, "id" : null, "object" : null, "description" : "The Cardiovascular Gene Ontology Annotation Initiative is supported by the British Heart Foundation (BHF) and located at University College London (UCL).", "url_example" : null, "abbreviation" : "BHF-UCL", "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.ucl.ac.uk/cardiovasculargeneontology/", "uri_prefix" : null, "database" : "Cardiovascular Gene Ontology Annotation Initiative", "entity_type" : "BET:0000000 ! entity" }, "nif_subcellular" : { "url_example" : "http://www.neurolex.org/wiki/sao1770195789", "abbreviation" : "NIF_Subcellular", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.neurolex.org/wiki", "url_syntax" : "http://www.neurolex.org/wiki/[example_id]", "example_id" : "NIF_Subcellular:sao1186862860", "datatype" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Neuroscience Information Framework standard ontology, subcellular hierarchy" }, "kegg_reaction" : { "generic_url" : "http://www.genome.jp/kegg/reaction/", "url_syntax" : "http://www.genome.jp/dbget-bin/www_bget?rn:[example_id]", "example_id" : "KEGG:R02328", "datatype" : null, "abbreviation" : "KEGG_REACTION", "url_example" : "http://www.genome.jp/dbget-bin/www_bget?rn:R02328", "object" : null, "fullname" : null, "name" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "KEGG Reaction Database", "local_id_syntax" : "R\\d+", "uri_prefix" : null }, "mesh" : { "entity_type" : "BET:0000000 ! entity", "database" : "Medical Subject Headings", "uri_prefix" : null, "generic_url" : "http://www.nlm.nih.gov/mesh/2005/MBrowser.html", "example_id" : "MeSH:mitosis", "datatype" : null, "url_syntax" : "http://www.nlm.nih.gov/cgi/mesh/2005/MB_cgi?mode=&term=[example_id]", "object" : null, "url_example" : "http://www.nlm.nih.gov/cgi/mesh/2005/MB_cgi?mode=&term=mitosis", "abbreviation" : "MeSH", "id" : null, "fullname" : null, "name" : null }, "uniparc" : { "entity_type" : "BET:0000000 ! entity", "database" : "UniProt Archive", "uri_prefix" : null, "generic_url" : "http://www.uniprot.org/uniparc/", "url_syntax" : "http://www.uniprot.org/uniparc/[example_id]", "datatype" : null, "example_id" : "UniParc:UPI000000000A", "abbreviation" : "UniParc", "description" : "A non-redundant archive of protein sequences extracted from Swiss-Prot, TrEMBL, PIR-PSD, EMBL, Ensembl, IPI, PDB, RefSeq, FlyBase, WormBase, European Patent Office, United States Patent and Trademark Office, and Japanese Patent Office", "url_example" : "http://www.uniprot.org/uniparc/UPI000000000A", "object" : null, "name" : null, "fullname" : null, "id" : null }, "fb" : { "url_example" : "http://flybase.org/reports/FBgn0000024.html", "abbreviation" : "FB", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://flybase.org/", "url_syntax" : "http://flybase.org/reports/[example_id].html", "example_id" : "FB:FBgn0000024", "datatype" : null, "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "FlyBase", "local_id_syntax" : "FBgn[0-9]{7}" }, "sgd_locus" : { "object" : null, "url_example" : "http://www.yeastgenome.org/locus/S000006169/overview", "abbreviation" : "SGD_LOCUS", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.yeastgenome.org/", "datatype" : null, "example_id" : "SGD_LOCUS:GAL4", "url_syntax" : "http://www.yeastgenome.org/locus/[example_id]/overview", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Saccharomyces Genome Database" }, "casref" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Catalog of Fishes publications database", "abbreviation" : "CASREF", "url_example" : "http://research.calacademy.org/research/ichthyology/catalog/getref.asp?id=2031", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://research.calacademy.org/research/ichthyology/catalog/fishcatsearch.html", "url_syntax" : "http://research.calacademy.org/research/ichthyology/catalog/getref.asp?id=[example_id]", "datatype" : null, "example_id" : "CASREF:2031" }, "sgdid" : { "local_id_syntax" : "S[0-9]{9}", "database" : "Saccharomyces Genome Database", "entity_type" : "SO:0000704 ! gene", "uri_prefix" : null, "example_id" : "SGD:S000006169", "datatype" : null, "url_syntax" : "http://www.yeastgenome.org/locus/[example_id]/overview", "generic_url" : "http://www.yeastgenome.org/", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://www.yeastgenome.org/locus/S000006169/overview", "abbreviation" : "SGDID" }, "gorel" : { "database" : "GO Extensions to OBO Relation Ontology Ontology", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "datatype" : null, "example_id" : null, "generic_url" : "http://purl.obolibrary.org/obo/ro", "id" : null, "fullname" : null, "name" : null, "abbreviation" : "GOREL", "description" : "Additional relations pending addition into RO", "url_example" : null, "object" : null }, "ncbitaxon" : { "url_syntax" : "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=[example_id]", "datatype" : null, "example_id" : "taxon:7227", "generic_url" : "http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/", "name" : null, "id" : null, "fullname" : null, "abbreviation" : "NCBITaxon", "url_example" : "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=3702", "object" : null, "database" : "NCBI Taxonomy", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "gr" : { "example_id" : "GR:sd1", "datatype" : null, "url_syntax" : "http://www.gramene.org/db/searches/browser?search_type=All&RGN=on&query=[example_id]", "generic_url" : "http://www.gramene.org/", "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://www.gramene.org/db/searches/browser?search_type=All&RGN=on&query=sd1", "abbreviation" : "GR", "local_id_syntax" : "[A-Z][0-9][A-Z0-9]{3}[0-9]", "database" : "Gramene", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null }, "rhea" : { "uri_prefix" : null, "database" : "Rhea, the Annotated Reactions Database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://www.ebi.ac.uk/rhea/reaction.xhtml?id=25811", "description" : "Rhea is a freely available, manually annotated database of chemical reactions created in collaboration with the Swiss Institute of Bioinformatics (SIB).", "abbreviation" : "RHEA", "object" : null, "url_syntax" : "http://www.ebi.ac.uk/rhea/reaction.xhtml?id=[example_id]", "datatype" : null, "example_id" : "RHEA:25811", "generic_url" : "http://www.ebi.ac.uk/rhea/" }, "geo" : { "example_id" : "GEO:GDS2223", "datatype" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/sites/GDSbrowser?acc=[example_id]", "generic_url" : "http://www.ncbi.nlm.nih.gov/geo/", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/sites/GDSbrowser?acc=GDS2223", "abbreviation" : "GEO", "database" : "NCBI Gene Expression Omnibus", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "agricola_id" : { "database" : "AGRICultural OnLine Access", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "example_id" : "AGRICOLA_NAL:TP248.2 P76 v.14", "datatype" : null, "generic_url" : "http://agricola.nal.usda.gov/", "name" : null, "fullname" : null, "id" : null, "url_example" : null, "abbreviation" : "AGRICOLA_ID", "object" : null }, "unigene" : { "database" : "UniGene", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "datatype" : null, "example_id" : "UniGene:Hs.212293", "url_syntax" : "http://www.ncbi.nlm.nih.gov/UniGene/clust.cgi?ORG=[organism_abbreviation]&CID=[cluster_id]", "generic_url" : "http://www.ncbi.nlm.nih.gov/UniGene", "name" : null, "fullname" : null, "id" : null, "object" : null, "description" : "NCBI transcript cluster database, organized by transcriptome. Each UniGene entry is a set of transcript sequences that appear to come from the same transcription locus (gene or expressed pseudogene).", "url_example" : "http://www.ncbi.nlm.nih.gov/UniGene/clust.cgi?ORG=Hs&CID=212293", "abbreviation" : "UniGene" }, "sgn_ref" : { "example_id" : "SGN_ref:861", "datatype" : null, "url_syntax" : "http://www.sgn.cornell.edu/chado/publication.pl?pub_id=[example_id]", "generic_url" : "http://www.sgn.cornell.edu/", "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://www.sgn.cornell.edu/chado/publication.pl?pub_id=861", "abbreviation" : "SGN_ref", "database" : "Sol Genomics Network", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "ecoliwiki" : { "fullname" : null, "name" : null, "id" : null, "description" : "EcoliHub\\'s subsystem for community annotation of E. coli K-12", "abbreviation" : "EcoliWiki", "url_example" : null, "object" : null, "url_syntax" : null, "example_id" : null, "datatype" : null, "generic_url" : "http://ecoliwiki.net/", "uri_prefix" : null, "database" : "EcoliWiki from EcoliHub", "local_id_syntax" : "[A-Za-z]{3,4}", "entity_type" : "SO:0000704 ! gene" }, "smd" : { "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "SMD", "url_example" : null, "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://genome-www.stanford.edu/microarray", "uri_prefix" : null, "database" : "Stanford Microarray Database", "entity_type" : "BET:0000000 ! entity" }, "ncbi" : { "database" : "National Center for Biotechnology Information", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : null, "abbreviation" : "NCBI" }, "ensembl_proteinid" : { "example_id" : "ENSEMBL_ProteinID:ENSP00000361027", "datatype" : null, "url_syntax" : "http://www.ensembl.org/id/[example_id]", "generic_url" : "http://www.ensembl.org/", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : "http://www.ensembl.org/id/ENSP00000361027", "abbreviation" : "ENSEMBL_ProteinID", "local_id_syntax" : "ENSP[0-9]{9,16}", "database" : "Ensembl database of automatically annotated genomic data", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null }, "genedb" : { "local_id_syntax" : "((LmjF|LinJ|LmxM)\\.[0-9]{2}\\.[0-9]{4})|(PF3D7_[0-9]{7})|(Tb[0-9]+\\.[A-Za-z0-9]+\\.[0-9]+)|(TcCLB\\.[0-9]{6}\\.[0-9]+)", "database" : "GeneDB", "entity_type" : "SO:0000704 ! gene", "uri_prefix" : null, "example_id" : "PF3D7_1467300", "datatype" : null, "url_syntax" : "http://www.genedb.org/gene/[example_id]", "generic_url" : "http://www.genedb.org/gene/", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://www.genedb.org/gene/PF3D7_1467300", "abbreviation" : "GeneDB" }, "h-invdb_cdna" : { "uri_prefix" : null, "database" : "H-invitational Database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "H-invDB_cDNA", "url_example" : "http://www.h-invitational.jp/hinv/spsoup/transcript_view?acc_id=AK093149", "example_id" : "H-invDB_cDNA:AK093148", "datatype" : null, "url_syntax" : "http://www.h-invitational.jp/hinv/spsoup/transcript_view?acc_id=[example_id]", "generic_url" : "http://www.h-invitational.jp/" }, "obo_rel" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "OBO relation ontology", "object" : null, "abbreviation" : "OBO_REL", "url_example" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.obofoundry.org/ro/", "example_id" : "OBO_REL:part_of", "datatype" : null, "url_syntax" : null }, "ensemblfungi" : { "entity_type" : "SO:0000704 ! gene", "database" : "Ensembl Fungi, the Ensembl Genomes database for accessing fungal genome data", "uri_prefix" : null, "generic_url" : "http://fungi.ensembl.org/", "url_syntax" : "http://www.ensemblgenomes.org/id/[example_ID]", "datatype" : null, "example_id" : "EnsemblFungi:YOR197W", "abbreviation" : "EnsemblFungi", "url_example" : "http://www.ensemblgenomes.org/id/YOR197W", "object" : null, "name" : null, "fullname" : null, "id" : null }, "enzyme" : { "object" : null, "abbreviation" : "ENZYME", "url_example" : "http://www.expasy.ch/cgi-bin/nicezyme.pl?1.1.1.1", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.expasy.ch/", "datatype" : null, "example_id" : "ENZYME:EC 1.1.1.1", "url_syntax" : "http://www.expasy.ch/cgi-bin/nicezyme.pl?[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Swiss Institute of Bioinformatics enzyme database" }, "ncbi_gene" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "NCBI Gene", "local_id_syntax" : "\\d+", "url_example" : "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids=4771", "abbreviation" : "NCBI_Gene", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids=[example_id]", "datatype" : null, "example_id" : "NCBI_Gene:4771" }, "dbsnp" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/projects/SNP", "datatype" : null, "example_id" : "dbSNP:rs3131969", "url_syntax" : "http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=[example_id]", "object" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=rs3131969", "abbreviation" : "dbSNP", "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "local_id_syntax" : "\\d+", "database" : "NCBI dbSNP", "uri_prefix" : null }, "uniprotkb-subcell" : { "uri_prefix" : null, "database" : "UniProt Knowledgebase Subcellular Location vocabulary", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "UniProtKB-SubCell", "url_example" : "http://www.uniprot.org/locations/SL-0012", "example_id" : "UniProtKB-SubCell:SL-0012", "datatype" : null, "url_syntax" : "http://www.uniprot.org/locations/[example_id]", "generic_url" : "http://www.uniprot.org/locations/" }, "uniprot" : { "example_id" : "UniProtKB:P51587", "datatype" : null, "url_syntax" : "http://www.uniprot.org/uniprot/[example_id]", "generic_url" : "http://www.uniprot.org", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : "http://www.uniprot.org/uniprot/P51587", "description" : "A central repository of protein sequence and function created by joining the information contained in Swiss-Prot, TrEMBL, and PIR database", "abbreviation" : "UniProt", "local_id_syntax" : "([OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z]([0-9][A-Z][A-Z0-9]{2}){1,2}[0-9])((-[0-9]+)|:PRO_[0-9]{10}|:VAR_[0-9]{6}){0,1}", "database" : "Universal Protein Knowledgebase", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null }, "cbs" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Center for Biological Sequence Analysis", "url_example" : "http://www.cbs.dtu.dk/services/[example_id]/", "abbreviation" : "CBS", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.cbs.dtu.dk/", "url_syntax" : null, "datatype" : null, "example_id" : "CBS:TMHMM" }, "sabio-rk" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "SABIO Reaction Kinetics", "url_example" : "http://sabio.villa-bosch.de/reacdetails.jsp?reactid=1858", "description" : "The SABIO-RK (System for the Analysis of Biochemical Pathways - Reaction Kinetics) is a web-based application based on the SABIO relational database that contains information about biochemical reactions, their kinetic equations with their parameters, and the experimental conditions under which these parameters were measured.", "abbreviation" : "SABIO-RK", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://sabio.villa-bosch.de/", "url_syntax" : "http://sabio.villa-bosch.de/reacdetails.jsp?reactid=[example_id]", "datatype" : null, "example_id" : "SABIO-RK:1858" }, "flybase" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "FlyBase", "local_id_syntax" : "FBgn[0-9]{7}", "abbreviation" : "FLYBASE", "url_example" : "http://flybase.org/reports/FBgn0000024.html", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://flybase.org/", "url_syntax" : "http://flybase.org/reports/[example_id].html", "example_id" : "FB:FBgn0000024", "datatype" : null }, "fbbt" : { "database" : "Drosophila gross anatomy", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://flybase.org/cgi-bin/fbcvq.html?query=FBbt:[example_id]", "example_id" : "FBbt:00005177", "datatype" : null, "generic_url" : "http://flybase.org/", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://flybase.org/cgi-bin/fbcvq.html?query=FBbt:00005177", "abbreviation" : "FBbt", "object" : null }, "vmd" : { "uri_prefix" : null, "database" : "Virginia Bioinformatics Institute Microbial Database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://vmd.vbi.vt.edu/cgi-bin/browse/browserDetail_new.cgi?gene_id=109198", "abbreviation" : "VMD", "object" : null, "url_syntax" : "http://vmd.vbi.vt.edu/cgi-bin/browse/browserDetail_new.cgi?gene_id=[example_id]", "datatype" : null, "example_id" : "VMD:109198", "generic_url" : "http://phytophthora.vbi.vt.edu" }, "muscletrait" : { "entity_type" : "BET:0000000 ! entity", "database" : "TRAnscript Integrated Table", "uri_prefix" : null, "generic_url" : "http://muscle.cribi.unipd.it/", "datatype" : null, "example_id" : null, "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "MuscleTRAIT", "description" : "an integrated database of transcripts expressed in human skeletal muscle", "id" : null, "name" : null, "fullname" : null }, "nmpdr" : { "uri_prefix" : null, "database" : "National Microbial Pathogen Data Resource", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://www.nmpdr.org/linkin.cgi?id=fig|306254.1.peg.183", "abbreviation" : "NMPDR", "object" : null, "url_syntax" : "http://www.nmpdr.org/linkin.cgi?id=[example_id]", "example_id" : "NMPDR:fig|306254.1.peg.183", "datatype" : null, "generic_url" : "http://www.nmpdr.org" }, "tgd_ref" : { "url_syntax" : "http://db.ciliate.org/cgi-bin/reference/reference.pl?dbid=[example_id]", "example_id" : "TGD_REF:T000005818", "datatype" : null, "generic_url" : "http://www.ciliate.org/", "name" : null, "fullname" : null, "id" : null, "abbreviation" : "TGD_REF", "url_example" : "http://db.ciliate.org/cgi-bin/reference/reference.pl?dbid=T000005818", "object" : null, "database" : "Tetrahymena Genome Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "pamgo_vmd" : { "url_syntax" : "http://vmd.vbi.vt.edu/cgi-bin/browse/go_detail.cgi?gene_id=[example_id]", "example_id" : "PAMGO_VMD:109198", "datatype" : null, "generic_url" : "http://phytophthora.vbi.vt.edu", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://vmd.vbi.vt.edu/cgi-bin/browse/go_detail.cgi?gene_id=109198", "description" : "Virginia Bioinformatics Institute Microbial Database; member of PAMGO Interest Group", "abbreviation" : "PAMGO_VMD", "object" : null, "database" : "Virginia Bioinformatics Institute Microbial Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "corum" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "CORUM - the Comprehensive Resource of Mammalian protein complexes", "url_example" : "http://mips.gsf.de/genre/proj/corum/complexdetails.html?id=837", "abbreviation" : "CORUM", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://mips.gsf.de/genre/proj/corum/", "url_syntax" : "http://mips.gsf.de/genre/proj/corum/complexdetails.html?id=[example_id]", "datatype" : null, "example_id" : "CORUM:837" }, "tigr_tigrfams" : { "object" : null, "abbreviation" : "TIGR_TIGRFAMS", "url_example" : "http://search.jcvi.org/search?p&q=TIGR00254", "id" : null, "name" : null, "fullname" : null, "generic_url" : "http://search.jcvi.org/", "example_id" : "JCVI_TIGRFAMS:TIGR00254", "datatype" : null, "url_syntax" : "http://search.jcvi.org/search?p&q=[example_id]", "uri_prefix" : null, "entity_type" : "SO:0000839 ! polypeptide region", "database" : "TIGRFAMs HMM collection at the J. Craig Venter Institute" }, "zfin" : { "name" : null, "fullname" : null, "id" : null, "abbreviation" : "ZFIN", "url_example" : "http://zfin.org/cgi-bin/ZFIN_jump?record=ZDB-GENE-990415-103", "object" : null, "url_syntax" : "http://zfin.org/cgi-bin/ZFIN_jump?record=[example_id]", "datatype" : null, "example_id" : "ZFIN:ZDB-GENE-990415-103", "generic_url" : "http://zfin.org/", "uri_prefix" : null, "database" : "Zebrafish Information Network", "local_id_syntax" : "ZDB-(GENE|GENO|MRPHLNO)-[0-9]{6}-[0-9]+", "entity_type" : "VariO:0001 ! variation" }, "seed" : { "database" : "The SEED;", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "datatype" : null, "example_id" : "SEED:fig|83331.1.peg.1", "url_syntax" : "http://www.theseed.org/linkin.cgi?id=[example_id]", "generic_url" : "http://www.theseed.org", "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://www.theseed.org/linkin.cgi?id=fig|83331.1.peg.1", "description" : "Project to annotate the first 1000 sequenced genomes, develop detailed metabolic reconstructions, and construct the corresponding stoichiometric matrices", "abbreviation" : "SEED" }, "go_ref" : { "generic_url" : "http://www.geneontology.org/", "datatype" : null, "example_id" : "GO_REF:0000001", "url_syntax" : "http://www.geneontology.org/cgi-bin/references.cgi#GO_REF:[example_id]", "object" : null, "abbreviation" : "GO_REF", "url_example" : "http://www.geneontology.org/cgi-bin/references.cgi#GO_REF:0000001", "fullname" : null, "name" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "local_id_syntax" : "\\d{7}", "database" : "Gene Ontology Database references", "uri_prefix" : null }, "resid" : { "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "RESID", "url_example" : null, "datatype" : null, "example_id" : "RESID:AA0062", "url_syntax" : null, "generic_url" : "ftp://ftp.ncifcrf.gov/pub/users/residues/", "uri_prefix" : null, "database" : "RESID Database of Protein Modifications", "entity_type" : "BET:0000000 ! entity" }, "modbase" : { "generic_url" : "http://modbase.compbio.ucsf.edu/", "url_syntax" : "http://salilab.org/modbase/searchbyid?databaseID=[example_id]", "example_id" : "ModBase:P10815", "datatype" : null, "url_example" : "http://salilab.org/modbase/searchbyid?databaseID=P04848", "abbreviation" : "ModBase", "object" : null, "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "ModBase comprehensive Database of Comparative Protein Structure Models", "uri_prefix" : null }, "img" : { "object" : null, "url_example" : "http://img.jgi.doe.gov/cgi-bin/pub/main.cgi?section=GeneDetail&page=geneDetail&gene_oid=640008772", "abbreviation" : "IMG", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://img.jgi.doe.gov", "datatype" : null, "example_id" : "IMG:640008772", "url_syntax" : "http://img.jgi.doe.gov/cgi-bin/pub/main.cgi?section=GeneDetail&page=geneDetail&gene_oid=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Integrated Microbial Genomes; JGI web site for genome annotation" }, "gdb" : { "database" : "Human Genome Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "datatype" : null, "example_id" : "GDB:306600", "url_syntax" : "http://www.gdb.org/gdb-bin/genera/accno?accessionNum=GDB:[example_id]", "generic_url" : "http://www.gdb.org/", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "GDB", "url_example" : "http://www.gdb.org/gdb-bin/genera/accno?accessionNum=GDB:306600" }, "doi" : { "uri_prefix" : null, "local_id_syntax" : "10\\.[0-9]+\\/.*", "database" : "Digital Object Identifier", "entity_type" : "BET:0000000 ! entity", "id" : null, "fullname" : null, "name" : null, "object" : null, "url_example" : "http://dx.doi.org/DOI:10.1016/S0963-9969(99)00021-6", "abbreviation" : "DOI", "example_id" : "DOI:10.1016/S0963-9969(99)00021-6", "datatype" : null, "url_syntax" : "http://dx.doi.org/DOI:[example_id]", "generic_url" : "http://dx.doi.org/" }, "aspgd_locus" : { "uri_prefix" : null, "database" : "Aspergillus Genome Database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "AspGD_LOCUS", "url_example" : "http://www.aspergillusgenome.org/cgi-bin/locus.pl?locus=AN10942", "datatype" : null, "example_id" : "AspGD_LOCUS:AN10942", "url_syntax" : "http://www.aspergillusgenome.org/cgi-bin/locus.pl?locus=[example_id]", "generic_url" : "http://www.aspergillusgenome.org/" }, "cgsc" : { "generic_url" : "http://cgsc.biology.yale.edu/", "url_syntax" : null, "example_id" : "CGSC:rbsK", "datatype" : null, "url_example" : "http://cgsc.biology.yale.edu/Site.php?ID=315", "abbreviation" : "CGSC", "object" : null, "id" : null, "fullname" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "CGSC", "uri_prefix" : null }, "broad_neurospora" : { "fullname" : null, "id" : null, "name" : null, "abbreviation" : "Broad_NEUROSPORA", "description" : "Neurospora crassa database at the Broad Institute", "url_example" : "http://www.broadinstitute.org/annotation/genome/neurospora/GeneDetails.html?sp=S7000007580576824", "object" : null, "url_syntax" : "http://www.broadinstitute.org/annotation/genome/neurospora/GeneDetails.html?sp=S[example_id]", "datatype" : null, "example_id" : "BROAD_NEUROSPORA:7000007580576824", "generic_url" : "http://www.broadinstitute.org/annotation/genome/neurospora/MultiHome.html", "uri_prefix" : null, "database" : "Neurospora crassa Database", "entity_type" : "BET:0000000 ! entity" }, "geneid" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids=[example_id]", "example_id" : "NCBI_Gene:4771", "datatype" : null, "abbreviation" : "GeneID", "url_example" : "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids=4771", "object" : null, "name" : null, "id" : null, "fullname" : null, "entity_type" : "SO:0000704 ! gene", "database" : "NCBI Gene", "local_id_syntax" : "\\d+", "uri_prefix" : null }, "ecogene" : { "abbreviation" : "ECOGENE", "url_example" : "http://www.ecogene.org/geneInfo.php?eg_id=EG10818", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.ecogene.org/", "url_syntax" : "http://www.ecogene.org/geneInfo.php?eg_id=[example_id]", "example_id" : "ECOGENE:EG10818", "datatype" : null, "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "EcoGene Database of Escherichia coli Sequence and Function", "local_id_syntax" : "EG[0-9]{5}" }, "cgen" : { "name" : null, "fullname" : null, "id" : null, "object" : null, "abbreviation" : "CGEN", "url_example" : null, "datatype" : null, "example_id" : "CGEN:PrID131022", "url_syntax" : null, "generic_url" : "http://www.cgen.com/", "uri_prefix" : null, "database" : "Compugen Gene Ontology Gene Association Data", "entity_type" : "BET:0000000 ! entity" }, "biocyc" : { "entity_type" : "BET:0000000 ! entity", "database" : "BioCyc collection of metabolic pathway databases", "uri_prefix" : null, "generic_url" : "http://biocyc.org/", "example_id" : "BioCyc:PWY-5271", "datatype" : null, "url_syntax" : "http://biocyc.org/META/NEW-IMAGE?type=PATHWAY&object=[example_id]", "object" : null, "abbreviation" : "BioCyc", "url_example" : "http://biocyc.org/META/NEW-IMAGE?type=PATHWAY&object=PWY-5271", "name" : null, "fullname" : null, "id" : null }, "sp_sl" : { "abbreviation" : "SP_SL", "url_example" : "http://www.uniprot.org/locations/SL-0012", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.uniprot.org/locations/", "url_syntax" : "http://www.uniprot.org/locations/[example_id]", "example_id" : "UniProtKB-SubCell:SL-0012", "datatype" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "UniProt Knowledgebase Subcellular Location vocabulary" }, "ncbi_gi" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val=[example_id]", "example_id" : "NCBI_gi:113194944", "datatype" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val=113194944", "abbreviation" : "NCBI_gi", "object" : null, "fullname" : null, "name" : null, "id" : null, "entity_type" : "SO:0000704 ! gene", "database" : "NCBI databases", "local_id_syntax" : "[0-9]{6,}", "uri_prefix" : null }, "cog_function" : { "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/COG/grace/shokog.cgi?fun=H", "abbreviation" : "COG_Function", "example_id" : "COG_Function:H", "datatype" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/COG/grace/shokog.cgi?fun=[example_id]", "generic_url" : "http://www.ncbi.nlm.nih.gov/COG/", "uri_prefix" : null, "database" : "NCBI COG function", "entity_type" : "BET:0000000 ! entity" }, "subtilistg" : { "entity_type" : "BET:0000000 ! entity", "database" : "Bacillus subtilis Genome Sequence Project", "uri_prefix" : null, "generic_url" : "http://genolist.pasteur.fr/SubtiList/", "url_syntax" : null, "datatype" : null, "example_id" : "SUBTILISTG:accC", "abbreviation" : "SUBTILISTG", "url_example" : null, "object" : null, "name" : null, "fullname" : null, "id" : null }, "genprotec" : { "abbreviation" : "GenProtEC", "url_example" : null, "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://genprotec.mbl.edu/", "url_syntax" : null, "datatype" : null, "example_id" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "GenProtEC E. coli genome and proteome database" }, "pombase" : { "id" : null, "fullname" : null, "name" : null, "url_example" : "http://www.pombase.org/spombe/result/SPBC11B10.09", "abbreviation" : "PomBase", "object" : null, "url_syntax" : "http://www.pombase.org/spombe/result/[example_id]", "example_id" : "PomBase:SPBC11B10.09", "datatype" : null, "generic_url" : "http://www.pombase.org/", "uri_prefix" : null, "database" : "PomBase", "local_id_syntax" : "S\\w+(\\.)?\\w+(\\.)?", "entity_type" : "SO:0000704 ! gene" }, "pinc" : { "generic_url" : "http://www.proteome.com/", "url_syntax" : null, "example_id" : null, "datatype" : null, "abbreviation" : "PINC", "description" : "represents GO annotations created in 2001 for NCBI and extracted into UniProtKB-GOA from EntrezGene", "url_example" : null, "object" : null, "id" : null, "fullname" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Proteome Inc.", "uri_prefix" : null }, "pro" : { "id" : null, "fullname" : null, "name" : null, "object" : null, "url_example" : "http://www.proconsortium.org/cgi-bin/pro/entry_pro?id=PR:000025380", "abbreviation" : "PRO", "example_id" : "PR:000025380", "datatype" : null, "url_syntax" : "http://www.proconsortium.org/cgi-bin/pro/entry_pro?id=PR:[example_id]", "generic_url" : "http://www.proconsortium.org/pro/pro.shtml", "uri_prefix" : null, "local_id_syntax" : "[0-9]{9}", "database" : "Protein Ontology", "entity_type" : "PR:000000001 ! protein" }, "wikipedia" : { "uri_prefix" : null, "database" : "Wikipedia", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "abbreviation" : "Wikipedia", "url_example" : "http://en.wikipedia.org/wiki/Endoplasmic_reticulum", "object" : null, "url_syntax" : "http://en.wikipedia.org/wiki/[example_id]", "example_id" : "Wikipedia:Endoplasmic_reticulum", "datatype" : null, "generic_url" : "http://en.wikipedia.org/" }, "ensemblplants" : { "datatype" : null, "example_id" : "EnsemblPlants:LOC_Os01g22954", "url_syntax" : "http://www.ensemblgenomes.org/id/[example_ID]", "generic_url" : "http://plants.ensembl.org/", "name" : null, "id" : null, "fullname" : null, "object" : null, "abbreviation" : "EnsemblPlants", "url_example" : "http://www.ensemblgenomes.org/id/LOC_Os01g22954", "database" : "Ensembl Plants, the Ensembl Genomes database for accessing plant genome data", "entity_type" : "SO:0000704 ! gene", "uri_prefix" : null }, "merops_fam" : { "uri_prefix" : null, "database" : "MEROPS peptidase database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://merops.sanger.ac.uk/cgi-bin/famsum?family=m18", "abbreviation" : "MEROPS_fam", "datatype" : null, "example_id" : "MEROPS_fam:M18", "url_syntax" : "http://merops.sanger.ac.uk/cgi-bin/famsum?family=[example_id]", "generic_url" : "http://merops.sanger.ac.uk/" }, "dictybase" : { "database" : "dictyBase", "local_id_syntax" : "DDB_G[0-9]{7}", "entity_type" : "SO:0000704 ! gene", "uri_prefix" : null, "url_syntax" : "http://dictybase.org/gene/[example_id]", "datatype" : null, "example_id" : "dictyBase:DDB_G0277859", "generic_url" : "http://dictybase.org", "id" : null, "fullname" : null, "name" : null, "abbreviation" : "DictyBase", "url_example" : "http://dictybase.org/gene/DDB_G0277859", "object" : null }, "ipi" : { "generic_url" : "http://www.ebi.ac.uk/IPI/IPIhelp.html", "datatype" : null, "example_id" : "IPI:IPI00000005.1", "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "IPI", "fullname" : null, "name" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "International Protein Index", "uri_prefix" : null }, "gr_gene" : { "name" : null, "id" : null, "fullname" : null, "abbreviation" : "GR_gene", "url_example" : "http://www.gramene.org/db/genes/search_gene?acc=GR:0060198", "object" : null, "url_syntax" : "http://www.gramene.org/db/genes/search_gene?acc=[example_id]", "datatype" : null, "example_id" : "GR_GENE:GR:0060198", "generic_url" : "http://www.gramene.org/", "uri_prefix" : null, "database" : "Gramene", "entity_type" : "BET:0000000 ! entity" }, "wbbt" : { "url_syntax" : null, "example_id" : "WBbt:0005733", "datatype" : null, "generic_url" : "http://www.wormbase.org/", "id" : null, "fullname" : null, "name" : null, "abbreviation" : "WBbt", "url_example" : null, "object" : null, "database" : "C. elegans gross anatomy", "local_id_syntax" : "[0-9]{7}", "entity_type" : "UBERON:0001062 ! metazoan anatomical entity", "uri_prefix" : null }, "aspgdid" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "local_id_syntax" : "ASPL[0-9]{10}", "database" : "Aspergillus Genome Database", "object" : null, "abbreviation" : "AspGDID", "url_example" : "http://www.aspergillusgenome.org/cgi-bin/locus.pl?dbid=ASPL0000067538", "id" : null, "name" : null, "fullname" : null, "generic_url" : "http://www.aspergillusgenome.org/", "example_id" : "AspGD:ASPL0000067538", "datatype" : null, "url_syntax" : "http://www.aspergillusgenome.org/cgi-bin/locus.pl?dbid=[example_id]" }, "mgd" : { "generic_url" : "http://www.informatics.jax.org/", "datatype" : null, "example_id" : "MGD:Adcy9", "url_syntax" : null, "object" : null, "abbreviation" : "MGD", "url_example" : null, "fullname" : null, "name" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Mouse Genome Database", "uri_prefix" : null }, "smart" : { "uri_prefix" : null, "database" : "Simple Modular Architecture Research Tool", "entity_type" : "SO:0000839 ! polypeptide region", "fullname" : null, "id" : null, "name" : null, "abbreviation" : "SMART", "url_example" : "http://smart.embl-heidelberg.de/smart/do_annotation.pl?BLAST=DUMMY&DOMAIN=SM00005", "object" : null, "url_syntax" : "http://smart.embl-heidelberg.de/smart/do_annotation.pl?BLAST=DUMMY&DOMAIN=[example_id]", "datatype" : null, "example_id" : "SMART:SM00005", "generic_url" : "http://smart.embl-heidelberg.de/" }, "tigr_egad" : { "name" : null, "id" : null, "fullname" : null, "abbreviation" : "TIGR_EGAD", "url_example" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenePage.cgi?locus=VCA0557", "object" : null, "url_syntax" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenePage.cgi?locus=[example_id]", "example_id" : "JCVI_CMR:VCA0557", "datatype" : null, "generic_url" : "http://cmr.jcvi.org/", "uri_prefix" : null, "database" : "EGAD database at the J. Craig Venter Institute", "entity_type" : "PR:000000001 ! protein" }, "iuphar" : { "object" : null, "url_example" : null, "abbreviation" : "IUPHAR", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.iuphar.org/", "example_id" : null, "datatype" : null, "url_syntax" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "International Union of Pharmacology" }, "hpa_antibody" : { "generic_url" : "http://www.proteinatlas.org/", "url_syntax" : "http://www.proteinatlas.org/antibody_info.php?antibody_id=[example_id]", "example_id" : "HPA_antibody:HPA000237", "datatype" : null, "abbreviation" : "HPA_antibody", "url_example" : "http://www.proteinatlas.org/antibody_info.php?antibody_id=HPA000237", "object" : null, "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Human Protein Atlas antibody information", "uri_prefix" : null }, "nc-iubmb" : { "entity_type" : "BET:0000000 ! entity", "database" : "Nomenclature Committee of the International Union of Biochemistry and Molecular Biology", "uri_prefix" : null, "generic_url" : "http://www.chem.qmw.ac.uk/iubmb/", "example_id" : null, "datatype" : null, "url_syntax" : null, "object" : null, "abbreviation" : "NC-IUBMB", "url_example" : null, "fullname" : null, "name" : null, "id" : null }, "ensembl_geneid" : { "generic_url" : "http://www.ensembl.org/", "url_syntax" : "http://www.ensembl.org/id/[example_id]", "example_id" : "ENSEMBL_GeneID:ENSG00000126016", "datatype" : null, "url_example" : "http://www.ensembl.org/id/ENSG00000126016", "abbreviation" : "ENSEMBL_GeneID", "object" : null, "fullname" : null, "id" : null, "name" : null, "entity_type" : "SO:0000704 ! gene", "database" : "Ensembl database of automatically annotated genomic data", "local_id_syntax" : "ENSG[0-9]{9,16}", "uri_prefix" : null }, "pmcid" : { "object" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/sites/entrez?db=pmc&cmd=search&term=PMC201377", "abbreviation" : "PMCID", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.pubmedcentral.nih.gov/", "example_id" : "PMCID:PMC201377", "datatype" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/sites/entrez?db=pmc&cmd=search&term=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Pubmed Central" }, "yeastfunc" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Yeast Function", "object" : null, "abbreviation" : "YeastFunc", "url_example" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://func.med.harvard.edu/yeast/", "example_id" : null, "datatype" : null, "url_syntax" : null }, "ma" : { "id" : null, "fullname" : null, "name" : null, "url_example" : "http://www.informatics.jax.org/searches/AMA.cgi?id=MA:0000003", "description" : "Adult Mouse Anatomical Dictionary; part of Gene Expression Database", "abbreviation" : "MA", "object" : null, "url_syntax" : "http://www.informatics.jax.org/searches/AMA.cgi?id=MA:[example_id]", "datatype" : null, "example_id" : "MA:0000003", "generic_url" : "http://www.informatics.jax.org/", "uri_prefix" : null, "database" : "Adult Mouse Anatomical Dictionary", "entity_type" : "BET:0000000 ! entity" }, "jcvi_tigrfams" : { "uri_prefix" : null, "entity_type" : "SO:0000839 ! polypeptide region", "database" : "TIGRFAMs HMM collection at the J. Craig Venter Institute", "object" : null, "abbreviation" : "JCVI_TIGRFAMS", "url_example" : "http://search.jcvi.org/search?p&q=TIGR00254", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://search.jcvi.org/", "datatype" : null, "example_id" : "JCVI_TIGRFAMS:TIGR00254", "url_syntax" : "http://search.jcvi.org/search?p&q=[example_id]" }, "agricola_ind" : { "entity_type" : "BET:0000000 ! entity", "database" : "AGRICultural OnLine Access", "uri_prefix" : null, "generic_url" : "http://agricola.nal.usda.gov/", "datatype" : null, "example_id" : "AGRICOLA_IND:IND23252955", "url_syntax" : null, "object" : null, "abbreviation" : "AGRICOLA_IND", "url_example" : null, "name" : null, "fullname" : null, "id" : null }, "po_ref" : { "database" : "Plant Ontology custom references", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://wiki.plantontology.org:8080/index.php/PO_REF:[example_id]", "datatype" : null, "example_id" : "PO_REF:00001", "generic_url" : "http://wiki.plantontology.org:8080/index.php/PO_references", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://wiki.plantontology.org:8080/index.php/PO_REF:00001", "abbreviation" : "PO_REF", "object" : null }, "jcvi_medtr" : { "entity_type" : "BET:0000000 ! entity", "database" : "Medicago truncatula genome database at the J. Craig Venter Institute", "uri_prefix" : null, "generic_url" : "http://medicago.jcvi.org/cgi-bin/medicago/overview.cgi", "url_syntax" : "http://medicago.jcvi.org/cgi-bin/medicago/search/shared/ORF_infopage.cgi?orf=[example_id]", "example_id" : "JCVI_Medtr:Medtr5g024510", "datatype" : null, "url_example" : "http://medicago.jcvi.org/cgi-bin/medicago/search/shared/ORF_infopage.cgi?orf=Medtr5g024510", "abbreviation" : "JCVI_Medtr", "object" : null, "name" : null, "fullname" : null, "id" : null }, "hgnc" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "HUGO Gene Nomenclature Committee", "local_id_syntax" : "[0-9]+", "abbreviation" : "HGNC", "url_example" : "http://www.genenames.org/data/hgnc_data.php?hgnc_id=HGNC:29", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.genenames.org/", "url_syntax" : "http://www.genenames.org/data/hgnc_data.php?hgnc_id=HGNC:[example_id]", "example_id" : "HGNC:29", "datatype" : null }, "broad" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Broad Institute", "object" : null, "url_example" : null, "abbreviation" : "Broad", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.broad.mit.edu/", "datatype" : null, "example_id" : null, "url_syntax" : null }, "cazy" : { "entity_type" : "BET:0000000 ! entity", "database" : "Carbohydrate Active EnZYmes", "local_id_syntax" : "(CE|GH|GT|PL)\\d+", "uri_prefix" : null, "generic_url" : "http://www.cazy.org/", "url_syntax" : "http://www.cazy.org/[example_id].html", "datatype" : null, "example_id" : "CAZY:PL11", "url_example" : "http://www.cazy.org/PL11.html", "description" : "The CAZy database describes the families of structurally-related catalytic and carbohydrate-binding modules (or functional domains) of enzymes that degrade, modify, or create glycosidic bonds.", "abbreviation" : "CAZY", "object" : null, "fullname" : null, "id" : null, "name" : null }, "ri" : { "database" : "Roslin Institute", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "example_id" : null, "datatype" : null, "generic_url" : "http://www.roslin.ac.uk/", "name" : null, "id" : null, "fullname" : null, "abbreviation" : "RI", "url_example" : null, "object" : null }, "brenda" : { "uri_prefix" : null, "entity_type" : "GO:0003824 ! catalytic activity", "database" : "BRENDA, The Comprehensive Enzyme Information System", "object" : null, "abbreviation" : "BRENDA", "url_example" : "http://www.brenda-enzymes.info/php/result_flat.php4?ecno=4.2.1.3", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.brenda-enzymes.info", "example_id" : "BRENDA:4.2.1.3", "datatype" : null, "url_syntax" : "http://www.brenda-enzymes.info/php/result_flat.php4?ecno=[example_id]" }, "vbrc" : { "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://vbrc.org/query.asp?web_id=VBRC:F35742", "abbreviation" : "VBRC", "datatype" : null, "example_id" : "VBRC:F35742", "url_syntax" : "http://vbrc.org/query.asp?web_id=VBRC:[example_id]", "generic_url" : "http://vbrc.org", "uri_prefix" : null, "database" : "Viral Bioinformatics Resource Center", "entity_type" : "BET:0000000 ! entity" }, "prow" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/prow/", "url_syntax" : null, "datatype" : null, "example_id" : null, "url_example" : null, "abbreviation" : "PROW", "object" : null, "fullname" : null, "name" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Protein Reviews on the Web", "uri_prefix" : null }, "gb" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/Genbank/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=[example_id]", "datatype" : null, "example_id" : "GB:AA816246", "abbreviation" : "GB", "description" : "The NIH genetic sequence database, an annotated collection of all publicly available DNA sequences.", "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=AA816246", "object" : null, "id" : null, "fullname" : null, "name" : null, "entity_type" : "PR:000000001 ! protein", "database" : "GenBank", "local_id_syntax" : "([A-Z]{2}[0-9]{6})|([A-Z]{1}[0-9]{5})", "uri_prefix" : null }, "tgd_locus" : { "datatype" : null, "example_id" : "TGD_LOCUS:PDD1", "url_syntax" : "http://db.ciliate.org/cgi-bin/locus.pl?locus=[example_id]", "generic_url" : "http://www.ciliate.org/", "name" : null, "fullname" : null, "id" : null, "object" : null, "abbreviation" : "TGD_LOCUS", "url_example" : "http://db.ciliate.org/cgi-bin/locus.pl?locus=PDD1", "database" : "Tetrahymena Genome Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "so" : { "generic_url" : "http://sequenceontology.org/", "example_id" : "SO:0000195", "datatype" : null, "url_syntax" : "http://song.sourceforge.net/SOterm_tables.html#SO:[example_id]", "object" : null, "abbreviation" : "SO", "url_example" : "http://song.sourceforge.net/SOterm_tables.html#SO:0000195", "id" : null, "fullname" : null, "name" : null, "entity_type" : "SO:0000110 ! sequence feature", "local_id_syntax" : "\\d{7}", "database" : "Sequence Ontology", "uri_prefix" : null }, "vega" : { "uri_prefix" : null, "database" : "Vertebrate Genome Annotation database", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://vega.sanger.ac.uk/perl/searchview?species=all&idx=All&q=OTTHUMP00000000661", "abbreviation" : "VEGA", "object" : null, "url_syntax" : "http://vega.sanger.ac.uk/perl/searchview?species=all&idx=All&q=[example_id]", "example_id" : "VEGA:OTTHUMP00000000661", "datatype" : null, "generic_url" : "http://vega.sanger.ac.uk/index.html" }, "ecocyc" : { "url_example" : "http://biocyc.org/ECOLI/NEW-IMAGE?type=PATHWAY&object=P2-PWY", "abbreviation" : "EcoCyc", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://ecocyc.org/", "url_syntax" : "http://biocyc.org/ECOLI/NEW-IMAGE?type=PATHWAY&object=[example_id]", "example_id" : "EcoCyc:P2-PWY", "datatype" : null, "uri_prefix" : null, "entity_type" : "GO:0008150 ! biological_process", "database" : "Encyclopedia of E. coli metabolism", "local_id_syntax" : "EG[0-9]{5}" }, "sanger" : { "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.sanger.ac.uk/", "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : null, "abbreviation" : "Sanger", "database" : "Wellcome Trust Sanger Institute", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "psi-mod" : { "url_example" : "http://www.ebi.ac.uk/ontology-lookup/?termId=MOD:00219", "abbreviation" : "PSI-MOD", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://psidev.sourceforge.net/mod/", "url_syntax" : "http://www.ebi.ac.uk/ontology-lookup/?termId=MOD:[example_id]", "example_id" : "MOD:00219", "datatype" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Proteomics Standards Initiative protein modification ontology" }, "trait" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "TRAnscript Integrated Table", "object" : null, "url_example" : null, "description" : "an integrated database of transcripts expressed in human skeletal muscle", "abbreviation" : "TRAIT", "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://muscle.cribi.unipd.it/", "datatype" : null, "example_id" : null, "url_syntax" : null }, "pir" : { "uri_prefix" : null, "database" : "Protein Information Resource", "local_id_syntax" : "[A-Z]{1}[0-9]{5}", "entity_type" : "PR:000000001 ! protein", "fullname" : null, "name" : null, "id" : null, "abbreviation" : "PIR", "url_example" : "http://pir.georgetown.edu/cgi-bin/pirwww/nbrfget?uid=I49499", "object" : null, "url_syntax" : "http://pir.georgetown.edu/cgi-bin/pirwww/nbrfget?uid=[example_id]", "example_id" : "PIR:I49499", "datatype" : null, "generic_url" : "http://pir.georgetown.edu/" }, "pamgo" : { "database" : "Plant-Associated Microbe Gene Ontology Interest Group", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "datatype" : null, "example_id" : null, "generic_url" : "http://pamgo.vbi.vt.edu/", "name" : null, "fullname" : null, "id" : null, "abbreviation" : "PAMGO", "url_example" : null, "object" : null }, "bfo" : { "database" : "Basic Formal Ontology", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://purl.obolibrary.org/obo/BFO_[example_id]", "example_id" : "BFO:0000066", "datatype" : null, "generic_url" : "http://purl.obolibrary.org/obo/bfo", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://purl.obolibrary.org/obo/BFO_0000066", "description" : "An upper ontology used by Open Bio Ontologies (OBO) Foundry. BFO contains upper-level classes as well as core relations such as part_of (BFO_0000050)", "abbreviation" : "BFO", "object" : null }, "chebi" : { "abbreviation" : "ChEBI", "url_example" : "http://www.ebi.ac.uk/chebi/searchId.do?chebiId=CHEBI:17234", "object" : null, "id" : null, "name" : null, "fullname" : null, "generic_url" : "http://www.ebi.ac.uk/chebi/", "url_syntax" : "http://www.ebi.ac.uk/chebi/searchId.do?chebiId=CHEBI:[example_id]", "datatype" : null, "example_id" : "CHEBI:17234", "uri_prefix" : null, "entity_type" : "CHEBI:24431 ! chemical entity", "database" : "Chemical Entities of Biological Interest", "local_id_syntax" : "[0-9]{1,6}" }, "jcvi_cmr" : { "database" : "EGAD database at the J. Craig Venter Institute", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null, "url_syntax" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenePage.cgi?locus=[example_id]", "datatype" : null, "example_id" : "JCVI_CMR:VCA0557", "generic_url" : "http://cmr.jcvi.org/", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenePage.cgi?locus=VCA0557", "abbreviation" : "JCVI_CMR", "object" : null }, "rfam" : { "uri_prefix" : null, "database" : "Rfam database of RNA families", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://rfam.sanger.ac.uk/family/RF00012", "abbreviation" : "Rfam", "object" : null, "url_syntax" : "http://rfam.sanger.ac.uk/family/[example_id]", "example_id" : "Rfam:RF00012", "datatype" : null, "generic_url" : "http://rfam.sanger.ac.uk/" }, "lifedb" : { "object" : null, "description" : "LifeDB is a database for information on protein localization, interaction, functional assays and expression.", "url_example" : "http://www.dkfz.de/LIFEdb/LIFEdb.aspx?ID=DKFZp564O1716", "abbreviation" : "LIFEdb", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.lifedb.de/", "example_id" : "LIFEdb:DKFZp564O1716", "datatype" : null, "url_syntax" : "http://www.dkfz.de/LIFEdb/LIFEdb.aspx?ID=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "LifeDB" }, "issn" : { "url_example" : null, "abbreviation" : "ISSN", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.issn.org/", "url_syntax" : null, "datatype" : null, "example_id" : "ISSN:1234-1231", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "International Standard Serial Number" }, "h-invdb_locus" : { "name" : null, "fullname" : null, "id" : null, "object" : null, "abbreviation" : "H-invDB_locus", "url_example" : "http://www.h-invitational.jp/hinv/spsoup/locus_view?hix_id=HIX0014446", "datatype" : null, "example_id" : "H-invDB_locus:HIX0014446", "url_syntax" : "http://www.h-invitational.jp/hinv/spsoup/locus_view?hix_id=[example_id]", "generic_url" : "http://www.h-invitational.jp/", "uri_prefix" : null, "database" : "H-invitational Database", "entity_type" : "BET:0000000 ! entity" }, "ec" : { "database" : "Enzyme Commission", "entity_type" : "GO:0003824 ! catalytic activity", "uri_prefix" : null, "url_syntax" : "http://www.expasy.org/enzyme/[example_id]", "example_id" : "EC:1.4.3.6", "datatype" : null, "generic_url" : "http://www.chem.qmul.ac.uk/iubmb/enzyme/", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://www.expasy.org/enzyme/1.4.3.6", "abbreviation" : "EC", "object" : null }, "apidb_plasmodb" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "PlasmoDB Plasmodium Genome Resource", "abbreviation" : "ApiDB_PlasmoDB", "url_example" : "http://www.plasmodb.org/gene/PF11_0344", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://plasmodb.org/", "url_syntax" : "http://www.plasmodb.org/gene/[example_id]", "example_id" : "ApiDB_PlasmoDB:PF11_0344", "datatype" : null }, "ntnu_sb" : { "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : null, "abbreviation" : "NTNU_SB", "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.ntnu.edu/nt/systemsbiology", "uri_prefix" : null, "database" : "Norwegian University of Science and Technology, Systems Biology team", "entity_type" : "BET:0000000 ! entity" }, "rnamdb" : { "url_syntax" : "http://s59.cas.albany.edu/RNAmods/cgi-bin/rnashow.cgi?[example_id]", "datatype" : null, "example_id" : "RNAmods:037", "generic_url" : "http://s59.cas.albany.edu/RNAmods/", "fullname" : null, "name" : null, "id" : null, "abbreviation" : "RNAMDB", "url_example" : "http://s59.cas.albany.edu/RNAmods/cgi-bin/rnashow.cgi?091", "object" : null, "database" : "RNA Modification Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "maizegdb_locus" : { "object" : null, "url_example" : "http://www.maizegdb.org/cgi-bin/displaylocusresults.cgi?term=ZmPK1", "abbreviation" : "MaizeGDB_Locus", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.maizegdb.org", "example_id" : "MaizeGDB_Locus:ZmPK1", "datatype" : null, "url_syntax" : "http://www.maizegdb.org/cgi-bin/displaylocusresults.cgi?term=[example_id]", "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "local_id_syntax" : "[A-Za-z][A-Za-z0-9]*", "database" : "MaizeGDB" }, "ena" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "European Nucleotide Archive", "local_id_syntax" : "([A-Z]{1}[0-9]{5})|([A-Z]{2}[0-9]{6})|([A-Z]{4}[0-9]{8,9})", "abbreviation" : "ENA", "description" : "ENA is made up of a number of distinct databases that includes EMBL-Bank, the newly established Sequence Read Archive (SRA) and the Trace Archive. International nucleotide sequence database collaboration, comprising ENA-EBI nucleotide sequence data library (EMBL-Bank), DNA DataBank of Japan (DDBJ), and NCBI GenBank", "url_example" : "http://www.ebi.ac.uk/ena/data/view/AA816246", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.ebi.ac.uk/ena/", "url_syntax" : "http://www.ebi.ac.uk/ena/data/view/[example_id]", "example_id" : "ENA:AA816246", "datatype" : null }, "pmid" : { "url_syntax" : "http://www.ncbi.nlm.nih.gov/pubmed/[example_id]", "example_id" : "PMID:4208797", "datatype" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/PubMed/", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/pubmed/4208797", "abbreviation" : "PMID", "object" : null, "database" : "PubMed", "local_id_syntax" : "[0-9]+", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "metacyc" : { "entity_type" : "BET:0000000 ! entity", "database" : "Metabolic Encyclopedia of metabolic and other pathways", "uri_prefix" : null, "generic_url" : "http://metacyc.org/", "url_syntax" : "http://biocyc.org/META/NEW-IMAGE?type=NIL&object=[example_id]", "example_id" : "MetaCyc:GLUTDEG-PWY", "datatype" : null, "abbreviation" : "MetaCyc", "url_example" : "http://biocyc.org/META/NEW-IMAGE?type=NIL&object=GLUTDEG-PWY", "object" : null, "id" : null, "fullname" : null, "name" : null }, "panther" : { "uri_prefix" : null, "local_id_syntax" : "PTN[0-9]{9}|PTHR[0-9]{5}_[A-Z0-9]+", "database" : "Protein ANalysis THrough Evolutionary Relationships Classification System", "entity_type" : "NCIT:C20130 ! protein family", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "PANTHER", "url_example" : "http://www.pantherdb.org/panther/lookupId.jsp?id=PTHR10000", "example_id" : "PANTHER:PTHR11455", "datatype" : null, "url_syntax" : "http://www.pantherdb.org/panther/lookupId.jsp?id=[example_id]", "generic_url" : "http://www.pantherdb.org/" }, "casgen" : { "database" : "Catalog of Fishes genus database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Genus&id=[example_id]", "example_id" : "CASGEN:1040", "datatype" : null, "generic_url" : "http://research.calacademy.org/research/ichthyology/catalog/fishcatsearch.html", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Genus&id=1040", "abbreviation" : "CASGEN", "object" : null }, "rgdid" : { "uri_prefix" : null, "database" : "Rat Genome Database", "local_id_syntax" : "[0-9]{4,7}", "entity_type" : "SO:0000704 ! gene", "id" : null, "fullname" : null, "name" : null, "url_example" : "http://rgd.mcw.edu/generalSearch/RgdSearch.jsp?quickSearch=1&searchKeyword=2004", "abbreviation" : "RGDID", "object" : null, "url_syntax" : "http://rgd.mcw.edu/generalSearch/RgdSearch.jsp?quickSearch=1&searchKeyword=[example_id]", "datatype" : null, "example_id" : "RGD:2004", "generic_url" : "http://rgd.mcw.edu/" }, "tc" : { "uri_prefix" : null, "entity_type" : "PR:000000001 ! protein", "database" : "Transport Protein Database", "url_example" : "http://www.tcdb.org/tcdb/index.php?tc=9.A.4.1.1", "abbreviation" : "TC", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.tcdb.org/", "url_syntax" : "http://www.tcdb.org/tcdb/index.php?tc=[example_id]", "datatype" : null, "example_id" : "TC:9.A.4.1.1" }, "protein_id" : { "uri_prefix" : null, "local_id_syntax" : "[A-Z]{3}[0-9]{5}(\\.[0-9]+)?", "database" : "DDBJ / ENA / GenBank", "entity_type" : "PR:000000001 ! protein", "name" : null, "fullname" : null, "id" : null, "object" : null, "abbreviation" : "protein_id", "description" : "protein identifier shared by DDBJ/EMBL-bank/GenBank nucleotide sequence databases", "url_example" : null, "example_id" : "protein_id:CAA71991", "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/Genbank/" }, "cgd_ref" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Candida Genome Database", "url_example" : "http://www.candidagenome.org/cgi-bin/reference/reference.pl?dbid=1490", "abbreviation" : "CGD_REF", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.candidagenome.org/", "url_syntax" : "http://www.candidagenome.org/cgi-bin/reference/reference.pl?dbid=[example_id]", "datatype" : null, "example_id" : "CGD_REF:1490" }, "pubchem_compound" : { "uri_prefix" : null, "entity_type" : "CHEBI:24431 ! chemical entity", "database" : "NCBI PubChem database of chemical structures", "local_id_syntax" : "[0-9]+", "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pccompound&term=2244", "abbreviation" : "PubChem_Compound", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://pubchem.ncbi.nlm.nih.gov/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pccompound&term=[example_id]", "datatype" : null, "example_id" : "PubChem_Compound:2244" }, "imgt_hla" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "IMGT/HLA human major histocompatibility complex sequence database", "object" : null, "abbreviation" : "IMGT_HLA", "url_example" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.ebi.ac.uk/imgt/hla", "example_id" : "IMGT_HLA:HLA00031", "datatype" : null, "url_syntax" : null }, "pirsf" : { "database" : "PIR Superfamily Classification System", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "datatype" : null, "example_id" : "PIRSF:SF002327", "url_syntax" : "http://pir.georgetown.edu/cgi-bin/ipcSF?id=[example_id]", "generic_url" : "http://pir.georgetown.edu/pirsf/", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "PIRSF", "url_example" : "http://pir.georgetown.edu/cgi-bin/ipcSF?id=SF002327" }, "ddanat" : { "uri_prefix" : null, "local_id_syntax" : "[0-9]{7}", "database" : "Dictyostelium discoideum anatomy", "entity_type" : "CARO:0000000 ! anatomical entity", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : null, "abbreviation" : "DDANAT", "datatype" : null, "example_id" : "DDANAT:0000068", "url_syntax" : null, "generic_url" : "http://dictybase.org/Dicty_Info/dicty_anatomy_ontology.html" }, "um-bbd" : { "database" : "University of Minnesota Biocatalysis/Biodegradation Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://umbbd.msi.umn.edu/", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "UM-BBD", "url_example" : null }, "ddbj" : { "entity_type" : "BET:0000000 ! entity", "database" : "DNA Databank of Japan", "uri_prefix" : null, "generic_url" : "http://www.ddbj.nig.ac.jp/", "example_id" : "DDBJ:AA816246", "datatype" : null, "url_syntax" : "http://arsa.ddbj.nig.ac.jp/arsa/ddbjSplSearch?KeyWord=[example_id]", "object" : null, "url_example" : "http://arsa.ddbj.nig.ac.jp/arsa/ddbjSplSearch?KeyWord=AA816246", "abbreviation" : "DDBJ", "fullname" : null, "id" : null, "name" : null }, "ro" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "OBO Relation Ontology Ontology", "object" : null, "abbreviation" : "RO", "description" : "A collection of relations used across OBO ontologies", "url_example" : "http://purl.obolibrary.org/obo/RO_0002211", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://purl.obolibrary.org/obo/ro", "example_id" : "RO:0002211", "datatype" : null, "url_syntax" : "http://purl.obolibrary.org/obo/RO_[example_id]" }, "alzheimers_university_of_toronto" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Alzheimers Project at University of Toronto", "abbreviation" : "Alzheimers_University_of_Toronto", "url_example" : null, "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.ims.utoronto.ca/", "url_syntax" : null, "example_id" : null, "datatype" : null }, "pubchem_bioassay" : { "abbreviation" : "PubChem_BioAssay", "url_example" : "http://pubchem.ncbi.nlm.nih.gov/assay/assay.cgi?aid=177", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://pubchem.ncbi.nlm.nih.gov/", "url_syntax" : "http://pubchem.ncbi.nlm.nih.gov/assay/assay.cgi?aid=[example_id]", "datatype" : null, "example_id" : "PubChem_BioAssay:177", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "NCBI PubChem database of bioassay records" }, "cog_pathway" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "NCBI COG pathway", "url_example" : "http://www.ncbi.nlm.nih.gov/COG/new/release/coglist.cgi?pathw=14", "abbreviation" : "COG_Pathway", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/COG/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/COG/new/release/coglist.cgi?pathw=[example_id]", "datatype" : null, "example_id" : "COG_Pathway:14" }, "aracyc" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "AraCyc metabolic pathway database for Arabidopsis thaliana", "url_example" : "http://www.arabidopsis.org:1555/ARA/NEW-IMAGE?type=NIL&object=PWYQT-62", "abbreviation" : "AraCyc", "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.arabidopsis.org/biocyc/index.jsp", "url_syntax" : "http://www.arabidopsis.org:1555/ARA/NEW-IMAGE?type=NIL&object=[example_id]", "example_id" : "AraCyc:PWYQT-62", "datatype" : null }, "um-bbd_reactionid" : { "entity_type" : "BET:0000000 ! entity", "database" : "University of Minnesota Biocatalysis/Biodegradation Database", "uri_prefix" : null, "generic_url" : "http://umbbd.msi.umn.edu/", "url_syntax" : "http://umbbd.msi.umn.edu/servlets/pageservlet?ptype=r&reacID=[example_id]", "example_id" : "UM-BBD_reactionID:r0129", "datatype" : null, "url_example" : "http://umbbd.msi.umn.edu/servlets/pageservlet?ptype=r&reacID=r0129", "abbreviation" : "UM-BBD_reactionID", "object" : null, "name" : null, "fullname" : null, "id" : null }, "mod" : { "database" : "Proteomics Standards Initiative protein modification ontology", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : "MOD:00219", "datatype" : null, "url_syntax" : "http://www.ebi.ac.uk/ontology-lookup/?termId=MOD:[example_id]", "generic_url" : "http://psidev.sourceforge.net/mod/", "name" : null, "id" : null, "fullname" : null, "object" : null, "abbreviation" : "MOD", "url_example" : "http://www.ebi.ac.uk/ontology-lookup/?termId=MOD:00219" }, "hugo" : { "uri_prefix" : null, "database" : "Human Genome Organisation", "entity_type" : "BET:0000000 ! entity", "id" : null, "fullname" : null, "name" : null, "abbreviation" : "HUGO", "url_example" : null, "object" : null, "url_syntax" : null, "example_id" : null, "datatype" : null, "generic_url" : "http://www.hugo-international.org/" }, "mips_funcat" : { "uri_prefix" : null, "database" : "MIPS Functional Catalogue", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "MIPS_funcat", "url_example" : "http://mips.gsf.de/cgi-bin/proj/funcatDB/search_advanced.pl?action=2&wert=11.02", "datatype" : null, "example_id" : "MIPS_funcat:11.02", "url_syntax" : "http://mips.gsf.de/cgi-bin/proj/funcatDB/search_advanced.pl?action=2&wert=[example_id]", "generic_url" : "http://mips.gsf.de/proj/funcatDB/" }, "pfamb" : { "entity_type" : "BET:0000000 ! entity", "database" : "Pfam-B supplement to Pfam", "uri_prefix" : null, "generic_url" : "http://www.sanger.ac.uk/Software/Pfam/", "datatype" : null, "example_id" : "PfamB:PB014624", "url_syntax" : null, "object" : null, "abbreviation" : "PfamB", "url_example" : null, "id" : null, "fullname" : null, "name" : null }, "pamgo_mgg" : { "uri_prefix" : null, "database" : "Magnaporthe grisea database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "object" : null, "description" : "Magnaporthe grisea database at North Carolina State University; member of PAMGO Interest Group", "abbreviation" : "PAMGO_MGG", "url_example" : "http://scotland.fgl.ncsu.edu/cgi-bin/adHocQuery.cgi?adHocQuery_dbName=smeng_goannotation&Action=Data&QueryName=Functional+Categorization+of+MGG+GO+Annotation&P_KeyWord=MGG_05132", "example_id" : "PAMGO_MGG:MGG_05132", "datatype" : null, "url_syntax" : "http://scotland.fgl.ncsu.edu/cgi-bin/adHocQuery.cgi?adHocQuery_dbName=smeng_goannotation&Action=Data&QueryName=Functional+Categorization+of+MGG+GO+Annotation&P_KeyWord=[example_id]", "generic_url" : "http://scotland.fgl.ncsu.edu/smeng/GoAnnotationMagnaporthegrisea.html" }, "prodom" : { "fullname" : null, "name" : null, "id" : null, "description" : "ProDom protein domain families automatically generated from UniProtKB", "url_example" : "http://prodom.prabi.fr/prodom/current/cgi-bin/request.pl?question=DBEN&query=PD000001", "abbreviation" : "ProDom", "object" : null, "url_syntax" : "http://prodom.prabi.fr/prodom/current/cgi-bin/request.pl?question=DBEN&query=[example_id]", "example_id" : "ProDom:PD000001", "datatype" : null, "generic_url" : "http://prodom.prabi.fr/prodom/current/html/home.php", "uri_prefix" : null, "database" : "ProDom protein domain families", "entity_type" : "BET:0000000 ! entity" }, "aspgd_ref" : { "uri_prefix" : null, "database" : "Aspergillus Genome Database", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://www.aspergillusgenome.org/cgi-bin/reference/reference.pl?dbid=90", "abbreviation" : "AspGD_REF", "object" : null, "url_syntax" : "http://www.aspergillusgenome.org/cgi-bin/reference/reference.pl?dbid=[example_id]", "datatype" : null, "example_id" : "AspGD_REF:90", "generic_url" : "http://www.aspergillusgenome.org/" }, "reactome" : { "entity_type" : "BET:0000000 ! entity", "local_id_syntax" : "REACT_[0-9]+", "database" : "Reactome - a curated knowledgebase of biological pathways", "uri_prefix" : null, "generic_url" : "http://www.reactome.org/", "datatype" : null, "example_id" : "Reactome:REACT_604", "url_syntax" : "http://www.reactome.org/cgi-bin/eventbrowser_st_id?ST_ID=[example_id]", "object" : null, "url_example" : "http://www.reactome.org/cgi-bin/eventbrowser_st_id?ST_ID=REACT_604", "abbreviation" : "Reactome", "fullname" : null, "name" : null, "id" : null }, "cl" : { "entity_type" : "GO:0005623 ! cell", "database" : "Cell Type Ontology", "local_id_syntax" : "[0-9]{7}", "uri_prefix" : null, "generic_url" : "http://cellontology.org", "url_syntax" : "http://purl.obolibrary.org/obo/CL_[example_id]", "datatype" : null, "example_id" : "CL:0000041", "url_example" : "http://purl.obolibrary.org/obo/CL_0000041", "abbreviation" : "CL", "object" : null, "fullname" : null, "id" : null, "name" : null }, "ppi" : { "abbreviation" : "PPI", "url_example" : null, "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://genome.pseudomonas-syringae.org/", "url_syntax" : null, "datatype" : null, "example_id" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Pseudomonas syringae community annotation project" }, "spd" : { "local_id_syntax" : "[0-9]{2}/[0-9]{2}[A-Z][0-9]{2}", "database" : "Schizosaccharomyces pombe Postgenome Database at RIKEN; includes Orfeome Localisation data", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : "SPD:05/05F01", "datatype" : null, "url_syntax" : "http://www.riken.jp/SPD/[example_id].html", "generic_url" : "http://www.riken.jp/SPD/", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "SPD", "url_example" : "http://www.riken.jp/SPD/05/05F01.html" }, "merops" : { "uri_prefix" : null, "database" : "MEROPS peptidase database", "entity_type" : "PR:000000001 ! protein", "id" : null, "fullname" : null, "name" : null, "url_example" : "http://merops.sanger.ac.uk/cgi-bin/pepsum?mid=A08.001", "abbreviation" : "MEROPS", "object" : null, "url_syntax" : "http://merops.sanger.ac.uk/cgi-bin/pepsum?mid=[example_id]", "datatype" : null, "example_id" : "MEROPS:A08.001", "generic_url" : "http://merops.sanger.ac.uk/" }, "cdd" : { "datatype" : null, "example_id" : "CDD:34222", "url_syntax" : "http://www.ncbi.nlm.nih.gov/Structure/cdd/cddsrv.cgi?uid=[example_id]", "generic_url" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=cdd", "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/Structure/cdd/cddsrv.cgi?uid=34222", "abbreviation" : "CDD", "database" : "Conserved Domain Database at NCBI", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "tigr_cmr" : { "uri_prefix" : null, "database" : "EGAD database at the J. Craig Venter Institute", "entity_type" : "PR:000000001 ! protein", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenePage.cgi?locus=VCA0557", "abbreviation" : "TIGR_CMR", "object" : null, "url_syntax" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenePage.cgi?locus=[example_id]", "datatype" : null, "example_id" : "JCVI_CMR:VCA0557", "generic_url" : "http://cmr.jcvi.org/" }, "biomd" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "BioModels Database", "object" : null, "abbreviation" : "BIOMD", "url_example" : "http://www.ebi.ac.uk/compneur-srv/biomodels-main/publ-model.do?mid=BIOMD0000000045", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.ebi.ac.uk/biomodels/", "example_id" : "BIOMD:BIOMD0000000045", "datatype" : null, "url_syntax" : "http://www.ebi.ac.uk/compneur-srv/biomodels-main/publ-model.do?mid=[example_id]" }, "mgi" : { "url_example" : "http://www.informatics.jax.org/accession/MGI:80863", "abbreviation" : "MGI", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.informatics.jax.org/", "url_syntax" : "http://www.informatics.jax.org/accession/[example_id]", "example_id" : "MGI:MGI:80863", "datatype" : null, "uri_prefix" : null, "entity_type" : "VariO:0001 ! variation", "database" : "Mouse Genome Informatics", "local_id_syntax" : "MGI:[0-9]{5,}" }, "pamgo_gat" : { "generic_url" : "http://agro.vbi.vt.edu/public/", "example_id" : "PAMGO_GAT:Atu0001", "datatype" : null, "url_syntax" : "http://agro.vbi.vt.edu/public/servlet/GeneEdit?&Search=Search&level=2&genename=[example_id]", "object" : null, "url_example" : "http://agro.vbi.vt.edu/public/servlet/GeneEdit?&Search=Search&level=2&genename=atu0001", "abbreviation" : "PAMGO_GAT", "fullname" : null, "id" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Genome Annotation Tool (Agrobacterium tumefaciens C58); PAMGO Interest Group", "uri_prefix" : null }, "dictybase_ref" : { "uri_prefix" : null, "database" : "dictyBase literature references", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : "http://dictybase.org/db/cgi-bin/dictyBase/reference/reference.pl?refNo=10157", "abbreviation" : "dictyBase_REF", "datatype" : null, "example_id" : "dictyBase_REF:10157", "url_syntax" : "http://dictybase.org/db/cgi-bin/dictyBase/reference/reference.pl?refNo=[example_id]", "generic_url" : "http://dictybase.org" }, "refgenome" : { "object" : null, "url_example" : null, "abbreviation" : "RefGenome", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.geneontology.org/GO.refgenome.shtml", "datatype" : null, "example_id" : null, "url_syntax" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "GO Reference Genomes" }, "mo" : { "uri_prefix" : null, "database" : "MGED Ontology", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://mged.sourceforge.net/ontologies/MGEDontology.php#Action", "abbreviation" : "MO", "object" : null, "url_syntax" : "http://mged.sourceforge.net/ontologies/MGEDontology.php#[example_id]", "datatype" : null, "example_id" : "MO:Action", "generic_url" : "http://mged.sourceforge.net/ontologies/MGEDontology.php" }, "omssa" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Open Mass Spectrometry Search Algorithm", "object" : null, "abbreviation" : "OMSSA", "url_example" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://pubchem.ncbi.nlm.nih.gov/omssa/", "example_id" : null, "datatype" : null, "url_syntax" : null }, "cas" : { "description" : "CAS REGISTRY is the most authoritative collection of disclosed chemical substance information, containing more than 54 million organic and inorganic substances and 62 million sequences. CAS REGISTRY covers substances identified from the scientific literature from 1957 to the present, with additional substances going back to the early 1900s.", "abbreviation" : "CAS", "url_example" : null, "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.cas.org/expertise/cascontent/registry/index.html", "url_syntax" : null, "datatype" : null, "example_id" : "CAS:58-08-2", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "CAS Chemical Registry" }, "gonuts" : { "uri_prefix" : null, "database" : "Gene Ontology Normal Usage Tracking System (GONUTS)", "entity_type" : "BET:0000000 ! entity", "id" : null, "fullname" : null, "name" : null, "object" : null, "description" : "Third party documentation for GO and community annotation system.", "abbreviation" : "GONUTS", "url_example" : "http://gowiki.tamu.edu/wiki/index.php/MOUSE:CD28", "example_id" : "GONUTS:MOUSE:CD28", "datatype" : null, "url_syntax" : "http://gowiki.tamu.edu/wiki/index.php/[example_id]", "generic_url" : "http://gowiki.tamu.edu" }, "cas_spc" : { "entity_type" : "BET:0000000 ! entity", "database" : "Catalog of Fishes species database", "uri_prefix" : null, "generic_url" : "http://research.calacademy.org/research/ichthyology/catalog/fishcatsearch.html", "example_id" : null, "datatype" : null, "url_syntax" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Species&id=[example_id]", "object" : null, "abbreviation" : "CAS_SPC", "url_example" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Species&id=1979", "fullname" : null, "name" : null, "id" : null }, "rebase" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "REBASE restriction enzyme database", "object" : null, "url_example" : "http://rebase.neb.com/rebase/enz/EcoRI.html", "abbreviation" : "REBASE", "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://rebase.neb.com/rebase/rebase.html", "datatype" : null, "example_id" : "REBASE:EcoRI", "url_syntax" : "http://rebase.neb.com/rebase/enz/[example_id].html" }, "uniprotkb-kw" : { "url_syntax" : "http://www.uniprot.org/keywords/[example_id]", "datatype" : null, "example_id" : "UniProtKB-KW:KW-0812", "generic_url" : "http://www.uniprot.org/keywords/", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://www.uniprot.org/keywords/KW-0812", "abbreviation" : "UniProtKB-KW", "object" : null, "database" : "UniProt Knowledgebase keywords", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "fma" : { "database" : "Foundational Model of Anatomy", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "example_id" : "FMA:61905", "datatype" : null, "generic_url" : "http://sig.biostr.washington.edu/projects/fm/index.html", "fullname" : null, "id" : null, "name" : null, "url_example" : null, "abbreviation" : "FMA", "object" : null }, "pubmed" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/PubMed/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/pubmed/[example_id]", "example_id" : "PMID:4208797", "datatype" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/pubmed/4208797", "abbreviation" : "PubMed", "object" : null, "fullname" : null, "id" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "PubMed", "local_id_syntax" : "[0-9]+", "uri_prefix" : null }, "ncbi_gp" : { "database" : "NCBI GenPept", "local_id_syntax" : "[A-Z]{3}[0-9]{5}(\\.[0-9]+)?", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=protein&val=[example_id]", "example_id" : "NCBI_GP:EAL72968", "datatype" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/", "fullname" : null, "name" : null, "id" : null, "abbreviation" : "NCBI_GP", "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=protein&val=EAL72968", "object" : null }, "jstor" : { "uri_prefix" : null, "database" : "Digital archive of scholarly articles", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : "http://www.jstor.org/stable/3093870", "abbreviation" : "JSTOR", "datatype" : null, "example_id" : "JSTOR:3093870", "url_syntax" : "http://www.jstor.org/stable/[example_id]", "generic_url" : "http://www.jstor.org/" }, "medline" : { "database" : "Medline literature database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "datatype" : null, "example_id" : "MEDLINE:20572430", "url_syntax" : null, "generic_url" : "http://www.nlm.nih.gov/databases/databases_medline.html", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : null, "abbreviation" : "MEDLINE" }, "intact" : { "uri_prefix" : null, "entity_type" : "GO:0043234 ! protein complex", "local_id_syntax" : "EBI-[0-9]+", "database" : "IntAct protein interaction database", "object" : null, "url_example" : "http://www.ebi.ac.uk/intact/search/do/search?searchString=EBI-17086", "abbreviation" : "IntAct", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.ebi.ac.uk/intact/", "example_id" : "IntAct:EBI-17086", "datatype" : null, "url_syntax" : "http://www.ebi.ac.uk/intact/search/do/search?searchString=[example_id]" }, "cgd_locus" : { "object" : null, "abbreviation" : "CGD_LOCUS", "url_example" : "http://www.candidagenome.org/cgi-bin/locus.pl?locus=HWP1", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.candidagenome.org/", "datatype" : null, "example_id" : "CGD_LOCUS:HWP1", "url_syntax" : "http://www.candidagenome.org/cgi-bin/locus.pl?locus=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Candida Genome Database" }, "pr" : { "database" : "Protein Ontology", "local_id_syntax" : "[0-9]{9}", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null, "url_syntax" : "http://www.proconsortium.org/cgi-bin/pro/entry_pro?id=PR:[example_id]", "datatype" : null, "example_id" : "PR:000025380", "generic_url" : "http://www.proconsortium.org/pro/pro.shtml", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://www.proconsortium.org/cgi-bin/pro/entry_pro?id=PR:000025380", "abbreviation" : "PR", "object" : null }, "cog" : { "generic_url" : "http://www.ncbi.nlm.nih.gov/COG/", "example_id" : null, "datatype" : null, "url_syntax" : null, "object" : null, "abbreviation" : "COG", "url_example" : null, "fullname" : null, "id" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "NCBI Clusters of Orthologous Groups", "uri_prefix" : null }, "coriell" : { "description" : "The Coriell Cell Repositories provide essential research reagents to the scientific community by establishing, verifying, maintaining, and distributing cell cultures and DNA derived from cell cultures. These collections, supported by funds from the National Institutes of Health (NIH) and several foundations, are extensively utilized by research scientists around the world.", "url_example" : "http://ccr.coriell.org/Sections/Search/Sample_Detail.aspx?Ref=GM07892", "abbreviation" : "CORIELL", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://ccr.coriell.org/", "url_syntax" : "http://ccr.coriell.org/Sections/Search/Sample_Detail.aspx?Ref=[example_id]", "datatype" : null, "example_id" : "GM07892", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Coriell Institute for Medical Research" }, "ipr" : { "local_id_syntax" : "IPR\\d{6}", "database" : "InterPro database of protein domains and motifs", "entity_type" : "SO:0000839 ! polypeptide region", "uri_prefix" : null, "datatype" : null, "example_id" : "InterPro:IPR000001", "url_syntax" : "http://www.ebi.ac.uk/interpro/entry/[example_id]", "generic_url" : "http://www.ebi.ac.uk/interpro/", "id" : null, "fullname" : null, "name" : null, "object" : null, "abbreviation" : "IPR", "url_example" : "http://www.ebi.ac.uk/interpro/entry/IPR015421" }, "cgdid" : { "fullname" : null, "id" : null, "name" : null, "abbreviation" : "CGDID", "url_example" : "http://www.candidagenome.org/cgi-bin/locus.pl?dbid=CAL0005516", "object" : null, "url_syntax" : "http://www.candidagenome.org/cgi-bin/locus.pl?dbid=[example_id]", "example_id" : "CGD:CAL0005516", "datatype" : null, "generic_url" : "http://www.candidagenome.org/", "uri_prefix" : null, "database" : "Candida Genome Database", "local_id_syntax" : "(CAL|CAF)[0-9]{7}", "entity_type" : "SO:0000704 ! gene" }, "rgd" : { "local_id_syntax" : "[0-9]{4,7}", "database" : "Rat Genome Database", "entity_type" : "SO:0000704 ! gene", "uri_prefix" : null, "example_id" : "RGD:2004", "datatype" : null, "url_syntax" : "http://rgd.mcw.edu/generalSearch/RgdSearch.jsp?quickSearch=1&searchKeyword=[example_id]", "generic_url" : "http://rgd.mcw.edu/", "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://rgd.mcw.edu/generalSearch/RgdSearch.jsp?quickSearch=1&searchKeyword=2004", "abbreviation" : "RGD" }, "wb" : { "generic_url" : "http://www.wormbase.org/", "url_syntax" : "http://www.wormbase.org/db/gene/gene?name=[example_id]", "datatype" : null, "example_id" : "WB:WBGene00003001", "abbreviation" : "WB", "url_example" : "http://www.wormbase.org/db/get?class=Gene;name=WBGene00003001", "object" : null, "fullname" : null, "id" : null, "name" : null, "entity_type" : "PR:000000001 ! protein", "database" : "WormBase database of nematode biology", "local_id_syntax" : "(WP:CE[0-9]{5})|(WB(Gene|Var|RNAi|Transgene)[0-9]{8})", "uri_prefix" : null }, "roslin_institute" : { "datatype" : null, "example_id" : null, "url_syntax" : null, "generic_url" : "http://www.roslin.ac.uk/", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : null, "abbreviation" : "Roslin_Institute", "database" : "Roslin Institute", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "locusid" : { "uri_prefix" : null, "database" : "NCBI Gene", "local_id_syntax" : "\\d+", "entity_type" : "SO:0000704 ! gene", "fullname" : null, "name" : null, "id" : null, "abbreviation" : "LocusID", "url_example" : "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids=4771", "object" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=gene&list_uids=[example_id]", "example_id" : "NCBI_Gene:4771", "datatype" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/" }, "hpa" : { "object" : null, "url_example" : "http://www.proteinatlas.org/tissue_profile.php?antibody_id=HPA000237", "abbreviation" : "HPA", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.proteinatlas.org/", "example_id" : "HPA:HPA000237", "datatype" : null, "url_syntax" : "http://www.proteinatlas.org/tissue_profile.php?antibody_id=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Human Protein Atlas tissue profile information" }, "sgn" : { "entity_type" : "SO:0000704 ! gene", "database" : "Sol Genomics Network", "uri_prefix" : null, "generic_url" : "http://www.sgn.cornell.edu/", "datatype" : null, "example_id" : "SGN:4476", "url_syntax" : "http://www.sgn.cornell.edu/phenome/locus_display.pl?locus_id=[example_id]", "object" : null, "abbreviation" : "SGN", "url_example" : "http://www.sgn.cornell.edu/phenome/locus_display.pl?locus_id=4476", "fullname" : null, "id" : null, "name" : null }, "casspc" : { "database" : "Catalog of Fishes species database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : null, "datatype" : null, "url_syntax" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Species&id=[example_id]", "generic_url" : "http://research.calacademy.org/research/ichthyology/catalog/fishcatsearch.html", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Species&id=1979", "abbreviation" : "CASSPC" }, "sp_kw" : { "entity_type" : "BET:0000000 ! entity", "database" : "UniProt Knowledgebase keywords", "uri_prefix" : null, "generic_url" : "http://www.uniprot.org/keywords/", "datatype" : null, "example_id" : "UniProtKB-KW:KW-0812", "url_syntax" : "http://www.uniprot.org/keywords/[example_id]", "object" : null, "url_example" : "http://www.uniprot.org/keywords/KW-0812", "abbreviation" : "SP_KW", "id" : null, "fullname" : null, "name" : null }, "imgt_ligm" : { "uri_prefix" : null, "database" : "ImMunoGeneTics database covering immunoglobulins and T-cell receptors", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : null, "description" : "Database of immunoglobulins and T cell receptors from human and other vertebrates, with translation for fully annotated sequences.", "abbreviation" : "IMGT_LIGM", "datatype" : null, "example_id" : "IMGT_LIGM:U03895", "url_syntax" : null, "generic_url" : "http://imgt.cines.fr" }, "agbase" : { "abbreviation" : "AgBase", "url_example" : null, "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.agbase.msstate.edu/", "url_syntax" : "http://www.agbase.msstate.edu/cgi-bin/getEntry.pl?db_pick=[ChickGO/MaizeGO]&uid=[example_id]", "example_id" : null, "datatype" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "AgBase resource for functional analysis of agricultural plant and animal gene products" }, "reac" : { "example_id" : "Reactome:REACT_604", "datatype" : null, "url_syntax" : "http://www.reactome.org/cgi-bin/eventbrowser_st_id?ST_ID=[example_id]", "generic_url" : "http://www.reactome.org/", "name" : null, "id" : null, "fullname" : null, "object" : null, "abbreviation" : "REAC", "url_example" : "http://www.reactome.org/cgi-bin/eventbrowser_st_id?ST_ID=REACT_604", "local_id_syntax" : "REACT_[0-9]+", "database" : "Reactome - a curated knowledgebase of biological pathways", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "uniprotkb" : { "url_syntax" : "http://www.uniprot.org/uniprot/[example_id]", "example_id" : "UniProtKB:P51587", "datatype" : null, "generic_url" : "http://www.uniprot.org", "id" : null, "fullname" : null, "name" : null, "abbreviation" : "UniProtKB", "description" : "A central repository of protein sequence and function created by joining the information contained in Swiss-Prot, TrEMBL, and PIR database", "url_example" : "http://www.uniprot.org/uniprot/P51587", "object" : null, "database" : "Universal Protein Knowledgebase", "local_id_syntax" : "([OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z]([0-9][A-Z][A-Z0-9]{2}){1,2}[0-9])((-[0-9]+)|:PRO_[0-9]{10}|:VAR_[0-9]{6}){0,1}", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null }, "po" : { "object" : null, "url_example" : "http://www.plantontology.org/amigo/go.cgi?action=query&view=query&search_constraint=terms&query=PO:0009004", "abbreviation" : "PO", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.plantontology.org/", "datatype" : null, "example_id" : "PO:0009004", "url_syntax" : "http://www.plantontology.org/amigo/go.cgi?action=query&view=query&search_constraint=terms&query=PO:[example_id]", "uri_prefix" : null, "entity_type" : "PO:0009012 ! plant structure development stage", "local_id_syntax" : "[0-9]{7}", "database" : "Plant Ontology Consortium Database" }, "gr_qtl" : { "url_syntax" : "http://www.gramene.org/db/qtl/qtl_display?qtl_accession_id=[example_id]", "example_id" : "GR_QTL:CQU7", "datatype" : null, "generic_url" : "http://www.gramene.org/", "fullname" : null, "name" : null, "id" : null, "abbreviation" : "GR_QTL", "url_example" : "http://www.gramene.org/db/qtl/qtl_display?qtl_accession_id=CQU7", "object" : null, "database" : "Gramene", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "multifun" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "MultiFun cell function assignment schema", "object" : null, "abbreviation" : "MultiFun", "url_example" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://genprotec.mbl.edu/files/MultiFun.html", "example_id" : null, "datatype" : null, "url_syntax" : null }, "cas_gen" : { "entity_type" : "BET:0000000 ! entity", "database" : "Catalog of Fishes genus database", "uri_prefix" : null, "generic_url" : "http://research.calacademy.org/research/ichthyology/catalog/fishcatsearch.html", "url_syntax" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Genus&id=[example_id]", "example_id" : "CASGEN:1040", "datatype" : null, "url_example" : "http://research.calacademy.org/research/ichthyology/catalog/getname.asp?rank=Genus&id=1040", "abbreviation" : "CAS_GEN", "object" : null, "name" : null, "id" : null, "fullname" : null }, "kegg_ligand" : { "entity_type" : "CHEBI:24431 ! chemical entity", "database" : "KEGG LIGAND Database", "local_id_syntax" : "C\\d{5}", "uri_prefix" : null, "generic_url" : "http://www.genome.ad.jp/kegg/docs/upd_ligand.html", "url_syntax" : "http://www.genome.jp/dbget-bin/www_bget?cpd:[example_id]", "example_id" : "KEGG_LIGAND:C00577", "datatype" : null, "abbreviation" : "KEGG_LIGAND", "url_example" : "http://www.genome.jp/dbget-bin/www_bget?cpd:C00577", "object" : null, "id" : null, "fullname" : null, "name" : null }, "gr_protein" : { "name" : null, "fullname" : null, "id" : null, "abbreviation" : "GR_protein", "url_example" : "http://www.gramene.org/db/protein/protein_search?acc=Q6VSV0", "object" : null, "url_syntax" : "http://www.gramene.org/db/protein/protein_search?acc=[example_id]", "example_id" : "GR_PROTEIN:Q6VSV0", "datatype" : null, "generic_url" : "http://www.gramene.org/", "uri_prefix" : null, "database" : "Gramene", "local_id_syntax" : "[A-Z][0-9][A-Z0-9]{3}[0-9]", "entity_type" : "PR:000000001 ! protein" }, "locsvmpsi" : { "entity_type" : "BET:0000000 ! entity", "database" : "LOCSVMPSI", "uri_prefix" : null, "generic_url" : "http://bioinformatics.ustc.edu.cn/locsvmpsi/locsvmpsi.php", "datatype" : null, "example_id" : null, "url_syntax" : null, "object" : null, "description" : "Subcellular localization for eukayotic proteins based on SVM and PSI-BLAST", "url_example" : null, "abbreviation" : "LOCSVMpsi", "name" : null, "fullname" : null, "id" : null }, "ensemblplants/gramene" : { "generic_url" : "http://plants.ensembl.org/", "url_syntax" : "http://www.ensemblgenomes.org/id/[example_ID]", "example_id" : "EnsemblPlants:LOC_Os01g22954", "datatype" : null, "abbreviation" : "EnsemblPlants/Gramene", "url_example" : "http://www.ensemblgenomes.org/id/LOC_Os01g22954", "object" : null, "fullname" : null, "name" : null, "id" : null, "entity_type" : "SO:0000704 ! gene", "database" : "Ensembl Plants, the Ensembl Genomes database for accessing plant genome data", "uri_prefix" : null }, "broad_mgg" : { "generic_url" : "http://www.broad.mit.edu/annotation/genome/magnaporthe_grisea/Home.html", "url_syntax" : "http://www.broad.mit.edu/annotation/genome/magnaporthe_grisea/GeneLocus.html?sp=S[example_id]", "example_id" : "Broad_MGG:MGG_05132.5", "datatype" : null, "description" : "Magnaporthe grisea Database at the Broad Institute", "abbreviation" : "Broad_MGG", "url_example" : "http://www.broad.mit.edu/annotation/genome/magnaporthe_grisea/GeneLocus.html?sp=SMGG_05132", "object" : null, "id" : null, "fullname" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Magnaporthe grisea Database", "uri_prefix" : null }, "fypo" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "local_id_syntax" : "\\d{7}", "database" : "Fission Yeast Phenotype Ontology", "object" : null, "abbreviation" : "FYPO", "url_example" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.pombase.org/", "datatype" : null, "example_id" : "FYPO:0000001", "url_syntax" : null }, "pharmgkb" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Pharmacogenetics and Pharmacogenomics Knowledge Base", "url_example" : "http://www.pharmgkb.org/do/serve?objId=PA267", "abbreviation" : "PharmGKB", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.pharmgkb.org", "url_syntax" : "http://www.pharmgkb.org/do/serve?objId=[example_id]", "example_id" : "PharmGKB:PA267", "datatype" : null }, "jcvi_ref" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "J. Craig Venter Institute", "abbreviation" : "JCVI_REF", "url_example" : "http://cmr.jcvi.org/CMR/AnnotationSops.shtml", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://cmr.jcvi.org/", "url_syntax" : null, "datatype" : null, "example_id" : "JCVI_REF:GO_ref" }, "jcvi_egad" : { "entity_type" : "BET:0000000 ! entity", "database" : "JCVI CMR Egad", "uri_prefix" : null, "generic_url" : "http://cmr.jcvi.org/", "example_id" : "JCVI_EGAD:74462", "datatype" : null, "url_syntax" : "http://cmr.jcvi.org/cgi-bin/CMR/EgadSearch.cgi?search_string=[example_id]", "object" : null, "url_example" : "http://cmr.jcvi.org/cgi-bin/CMR/EgadSearch.cgi?search_string=74462", "abbreviation" : "JCVI_EGAD", "fullname" : null, "name" : null, "id" : null }, "patric" : { "database" : "PathoSystems Resource Integration Center", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://patric.vbi.vt.edu/gene/overview.php?fid=[example_id]", "example_id" : "PATRIC:cds.000002.436951", "datatype" : null, "generic_url" : "http://patric.vbi.vt.edu", "name" : null, "fullname" : null, "id" : null, "description" : "PathoSystems Resource Integration Center at the Virginia Bioinformatics Institute", "abbreviation" : "PATRIC", "url_example" : "http://patric.vbi.vt.edu/gene/overview.php?fid=cds.000002.436951", "object" : null }, "ptarget" : { "database" : "pTARGET Prediction server for protein subcellular localization", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "datatype" : null, "example_id" : null, "generic_url" : "http://bioinformatics.albany.edu/~ptarget/", "fullname" : null, "name" : null, "id" : null, "abbreviation" : "pTARGET", "url_example" : null, "object" : null }, "h-invdb" : { "database" : "H-invitational Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : null, "example_id" : null, "datatype" : null, "generic_url" : "http://www.h-invitational.jp/", "fullname" : null, "name" : null, "id" : null, "url_example" : null, "abbreviation" : "H-invDB", "object" : null }, "tigr_ref" : { "generic_url" : "http://cmr.jcvi.org/", "datatype" : null, "example_id" : "JCVI_REF:GO_ref", "url_syntax" : null, "object" : null, "url_example" : "http://cmr.jcvi.org/CMR/AnnotationSops.shtml", "abbreviation" : "TIGR_REF", "fullname" : null, "id" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "J. Craig Venter Institute", "uri_prefix" : null }, "isbn" : { "generic_url" : "http://isbntools.com/", "example_id" : "ISBN:0781702534", "datatype" : null, "url_syntax" : "https://en.wikipedia.org/w/index.php?title=Special%3ABookSources&isbn=[example_id]", "object" : null, "abbreviation" : "ISBN", "url_example" : "https://en.wikipedia.org/w/index.php?title=Special%3ABookSources&isbn=0123456789", "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "International Standard Book Number", "uri_prefix" : null }, "prints" : { "url_example" : "http://www.bioinf.manchester.ac.uk/cgi-bin/dbbrowser/sprint/searchprintss.cgi?display_opts=Prints&category=None&queryform=false&regexpr=off&prints_accn=PR00025", "abbreviation" : "PRINTS", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.bioinf.manchester.ac.uk/dbbrowser/PRINTS/", "url_syntax" : "http://www.bioinf.manchester.ac.uk/cgi-bin/dbbrowser/sprint/searchprintss.cgi?display_opts=Prints&category=None&queryform=false&regexpr=off&prints_accn=[example_id]", "example_id" : "PRINTS:PR00025", "datatype" : null, "uri_prefix" : null, "entity_type" : "SO:0000839 ! polypeptide region", "database" : "PRINTS compendium of protein fingerprints" }, "tigr_genprop" : { "id" : null, "name" : null, "fullname" : null, "object" : null, "abbreviation" : "TIGR_GenProp", "url_example" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenomePropDefinition.cgi?prop_acc=GenProp0120", "example_id" : "JCVI_GenProp:GenProp0120", "datatype" : null, "url_syntax" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenomePropDefinition.cgi?prop_acc=[example_id]", "generic_url" : "http://cmr.jcvi.org/", "uri_prefix" : null, "local_id_syntax" : "GenProp[0-9]{4}", "database" : "Genome Properties database at the J. Craig Venter Institute", "entity_type" : "GO:0008150 ! biological_process" }, "refseq" : { "database" : "RefSeq", "local_id_syntax" : "(NC|AC|NG|NT|NW|NZ|NM|NR|XM|XR|NP|AP|XP|YP|ZP)_[0-9]+(\\.[0-9]+){0,1}", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val=[example_id]", "example_id" : "RefSeq:XP_001068954", "datatype" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/RefSeq/", "fullname" : null, "id" : null, "name" : null, "abbreviation" : "RefSeq", "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val=XP_001068954", "object" : null }, "iuphar_gpcr" : { "entity_type" : "BET:0000000 ! entity", "database" : "International Union of Pharmacology", "uri_prefix" : null, "generic_url" : "http://www.iuphar.org/", "datatype" : null, "example_id" : "IUPHAR_GPCR:1279", "url_syntax" : "http://www.iuphar-db.org/DATABASE/FamilyMenuForward?familyId=[example_id]", "object" : null, "abbreviation" : "IUPHAR_GPCR", "url_example" : "http://www.iuphar-db.org/DATABASE/FamilyMenuForward?familyId=13", "name" : null, "fullname" : null, "id" : null }, "ecocyc_ref" : { "database" : "Encyclopedia of E. coli metabolism", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://biocyc.org/ECOLI/reference.html?type=CITATION-FRAME&object=[example_id]", "datatype" : null, "example_id" : "EcoCyc_REF:COLISALII", "generic_url" : "http://ecocyc.org/", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://biocyc.org/ECOLI/reference.html?type=CITATION-FRAME&object=COLISALII", "abbreviation" : "ECOCYC_REF", "object" : null }, "echobase" : { "url_syntax" : "http://www.biolws1.york.ac.uk/echobase/Gene.cfm?recordID=[example_id]", "example_id" : "EchoBASE:EB0231", "datatype" : null, "generic_url" : "http://www.ecoli-york.org/", "name" : null, "fullname" : null, "id" : null, "abbreviation" : "EchoBASE", "url_example" : "http://www.biolws1.york.ac.uk/echobase/Gene.cfm?recordID=EB0231", "object" : null, "database" : "EchoBASE post-genomic database for Escherichia coli", "local_id_syntax" : "EB[0-9]{4}", "entity_type" : "SO:0000704 ! gene", "uri_prefix" : null }, "nasc_code" : { "entity_type" : "BET:0000000 ! entity", "database" : "Nottingham Arabidopsis Stock Centre Seeds Database", "uri_prefix" : null, "generic_url" : "http://arabidopsis.info", "url_syntax" : "http://seeds.nottingham.ac.uk/NASC/stockatidb.lasso?code=[example_id]", "datatype" : null, "example_id" : "NASC_code:N3371", "abbreviation" : "NASC_code", "url_example" : "http://seeds.nottingham.ac.uk/NASC/stockatidb.lasso?code=N3371", "object" : null, "name" : null, "fullname" : null, "id" : null }, "cog_cluster" : { "uri_prefix" : null, "database" : "NCBI COG cluster", "entity_type" : "BET:0000000 ! entity", "id" : null, "fullname" : null, "name" : null, "object" : null, "abbreviation" : "COG_Cluster", "url_example" : "http://www.ncbi.nlm.nih.gov/COG/new/release/cow.cgi?cog=COG0001", "datatype" : null, "example_id" : "COG_Cluster:COG0001", "url_syntax" : "http://www.ncbi.nlm.nih.gov/COG/new/release/cow.cgi?cog=[example_id]", "generic_url" : "http://www.ncbi.nlm.nih.gov/COG/" }, "maizegdb" : { "uri_prefix" : null, "database" : "MaizeGDB", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://www.maizegdb.org/cgi-bin/id_search.cgi?id=881225", "abbreviation" : "MaizeGDB", "object" : null, "url_syntax" : "http://www.maizegdb.org/cgi-bin/id_search.cgi?id=[example_id]", "datatype" : null, "example_id" : "MaizeGDB:881225", "generic_url" : "http://www.maizegdb.org" }, "dflat" : { "database" : "Developmental FunctionaL Annotation at Tufts", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://bcb.cs.tufts.edu/dflat/", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : null, "abbreviation" : "DFLAT" }, "mitre" : { "generic_url" : "http://www.mitre.org/", "datatype" : null, "example_id" : null, "url_syntax" : null, "object" : null, "abbreviation" : "MITRE", "url_example" : null, "fullname" : null, "id" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "The MITRE Corporation", "uri_prefix" : null }, "dictybase_gene_name" : { "object" : null, "abbreviation" : "dictyBase_gene_name", "url_example" : "http://dictybase.org/gene/mlcE", "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://dictybase.org", "datatype" : null, "example_id" : "dictyBase_gene_name:mlcE", "url_syntax" : "http://dictybase.org/gene/[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "dictyBase" }, "ncbi_taxid" : { "object" : null, "abbreviation" : "ncbi_taxid", "url_example" : "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=3702", "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/", "example_id" : "taxon:7227", "datatype" : null, "url_syntax" : "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=[example_id]", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "NCBI Taxonomy" }, "wbphenotype" : { "entity_type" : "PATO:0000001 ! quality", "database" : "WormBase phenotype ontology", "local_id_syntax" : "[0-9]{7}", "uri_prefix" : null, "generic_url" : "http://www.wormbase.org/", "url_syntax" : "http://www.wormbase.org/species/c_elegans/phenotype/WBPhenotype:[example_id]", "datatype" : null, "example_id" : "WBPhenotype:0002117", "abbreviation" : "WBPhenotype", "url_example" : "http://www.wormbase.org/species/c_elegans/phenotype/WBPhenotype:0000154", "object" : null, "id" : null, "fullname" : null, "name" : null }, "vida" : { "entity_type" : "BET:0000000 ! entity", "database" : "Virus Database at University College London", "uri_prefix" : null, "generic_url" : "http://www.biochem.ucl.ac.uk/bsm/virus_database/VIDA.html", "datatype" : null, "example_id" : null, "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "VIDA", "fullname" : null, "id" : null, "name" : null }, "um-bbd_pathwayid" : { "object" : null, "url_example" : "http://umbbd.msi.umn.edu/acr/acr_map.html", "abbreviation" : "UM-BBD_pathwayID", "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://umbbd.msi.umn.edu/", "example_id" : "UM-BBD_pathwayID:acr", "datatype" : null, "url_syntax" : "http://umbbd.msi.umn.edu/[example_id]/[example_id]_map.html", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "University of Minnesota Biocatalysis/Biodegradation Database" }, "parkinsonsuk-ucl" : { "generic_url" : "http://www.ucl.ac.uk/functional-gene-annotation/neurological", "url_syntax" : null, "example_id" : null, "datatype" : null, "abbreviation" : "ParkinsonsUK-UCL", "url_example" : null, "object" : null, "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Parkinsons Disease Gene Ontology Initiative", "uri_prefix" : null }, "kegg_enzyme" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "KEGG Enzyme Database", "local_id_syntax" : "\\d(\\.\\d{1,2}){2}\\.\\d{1,3}", "url_example" : "http://www.genome.jp/dbget-bin/www_bget?ec:2.1.1.4", "abbreviation" : "KEGG_ENZYME", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.genome.jp/dbget-bin/www_bfind?enzyme", "url_syntax" : "http://www.genome.jp/dbget-bin/www_bget?ec:[example_id]", "example_id" : "KEGG_ENZYME:2.1.1.4", "datatype" : null }, "wormbase" : { "local_id_syntax" : "(WP:CE[0-9]{5})|(WB(Gene|Var|RNAi|Transgene)[0-9]{8})", "database" : "WormBase database of nematode biology", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null, "datatype" : null, "example_id" : "WB:WBGene00003001", "url_syntax" : "http://www.wormbase.org/db/gene/gene?name=[example_id]", "generic_url" : "http://www.wormbase.org/", "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : "http://www.wormbase.org/db/get?class=Gene;name=WBGene00003001", "abbreviation" : "WormBase" }, "transfac" : { "name" : null, "fullname" : null, "id" : null, "object" : null, "url_example" : null, "abbreviation" : "TRANSFAC", "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.gene-regulation.com/pub/databases.html#transfac", "uri_prefix" : null, "database" : "TRANSFAC database of eukaryotic transcription factors", "entity_type" : "BET:0000000 ! entity" }, "unipathway" : { "uri_prefix" : null, "entity_type" : "GO:0008150 ! biological_process", "database" : "UniPathway", "abbreviation" : "UniPathway", "description" : "UniPathway is a a metabolic door to UniProtKB/Swiss-Prot, a curated resource of metabolic pathways for the UniProtKB/Swiss-Prot knowledgebase.", "url_example" : "http://www.grenoble.prabi.fr/obiwarehouse/unipathway/upa?upid=UPA00155", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.grenoble.prabi.fr/obiwarehouse/unipathway", "url_syntax" : "http://www.grenoble.prabi.fr/obiwarehouse/unipathway/upa?upid=[example_id]", "example_id" : "UniPathway:UPA00155", "datatype" : null }, "rnamods" : { "uri_prefix" : null, "database" : "RNA Modification Database", "entity_type" : "BET:0000000 ! entity", "id" : null, "fullname" : null, "name" : null, "url_example" : "http://s59.cas.albany.edu/RNAmods/cgi-bin/rnashow.cgi?091", "abbreviation" : "RNAmods", "object" : null, "url_syntax" : "http://s59.cas.albany.edu/RNAmods/cgi-bin/rnashow.cgi?[example_id]", "example_id" : "RNAmods:037", "datatype" : null, "generic_url" : "http://s59.cas.albany.edu/RNAmods/" }, "jcvi" : { "entity_type" : "BET:0000000 ! entity", "database" : "J. Craig Venter Institute", "uri_prefix" : null, "generic_url" : "http://www.jcvi.org/", "datatype" : null, "example_id" : null, "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "JCVI", "id" : null, "fullname" : null, "name" : null }, "vz" : { "abbreviation" : "VZ", "url_example" : "http://viralzone.expasy.org/all_by_protein/957.html", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://viralzone.expasy.org/", "url_syntax" : "http://viralzone.expasy.org/all_by_protein/[example_id].html", "example_id" : "VZ:957", "datatype" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "ViralZone" }, "go_central" : { "database" : "GO Central", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.geneontology.org/GO.refgenome.shtml", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "GO_Central", "description" : "Manual annotation from PAINT curators into the UniProt Protein2GO curation tool.", "url_example" : null }, "eco" : { "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : null, "abbreviation" : "ECO", "datatype" : null, "example_id" : "ECO:0000002", "url_syntax" : null, "generic_url" : "http://www.geneontology.org/", "uri_prefix" : null, "local_id_syntax" : "\\d{7}", "database" : "Evidence Code ontology", "entity_type" : "BET:0000000 ! entity" }, "superfamily" : { "database" : "SUPERFAMILY protein annotation database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://supfam.cs.bris.ac.uk/SUPERFAMILY/cgi-bin/scop.cgi?ipid=SSF[example_id]", "datatype" : null, "example_id" : "SUPERFAMILY:51905", "generic_url" : "http://supfam.cs.bris.ac.uk/SUPERFAMILY/index.html", "name" : null, "fullname" : null, "id" : null, "description" : "A database of structural and functional protein annotations for completely sequenced genomes", "abbreviation" : "SUPERFAMILY", "url_example" : "http://supfam.cs.bris.ac.uk/SUPERFAMILY/cgi-bin/scop.cgi?ipid=SSF51905", "object" : null }, "embl" : { "entity_type" : "SO:0000704 ! gene", "database" : "EMBL Nucleotide Sequence Database", "local_id_syntax" : "([A-Z]{1}[0-9]{5})|([A-Z]{2}[0-9]{6})|([A-Z]{4}[0-9]{8,9})", "uri_prefix" : null, "generic_url" : "http://www.ebi.ac.uk/embl/", "url_syntax" : "http://www.ebi.ac.uk/cgi-bin/emblfetch?style=html&Submit=Go&id=[example_id]", "datatype" : null, "example_id" : "EMBL:AA816246", "description" : "International nucleotide sequence database collaboration, comprising EMBL-EBI nucleotide sequence data library (EMBL-Bank), DNA DataBank of Japan (DDBJ), and NCBI GenBank", "abbreviation" : "EMBL", "url_example" : "http://www.ebi.ac.uk/cgi-bin/emblfetch?style=html&Submit=Go&id=AA816246", "object" : null, "fullname" : null, "name" : null, "id" : null }, "pubchem_substance" : { "datatype" : null, "example_id" : "PubChem_Substance:4594", "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pcsubstance&term=[example_id]", "generic_url" : "http://pubchem.ncbi.nlm.nih.gov/", "fullname" : null, "id" : null, "name" : null, "object" : null, "abbreviation" : "PubChem_Substance", "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?CMD=search&DB=pcsubstance&term=4594", "local_id_syntax" : "[0-9]{4,}", "database" : "NCBI PubChem database of chemical substances", "entity_type" : "CHEBI:24431 ! chemical entity", "uri_prefix" : null }, "go" : { "name" : null, "fullname" : null, "id" : null, "abbreviation" : "GO", "url_example" : "http://amigo.geneontology.org/amigo/term/GO:0004352", "object" : null, "url_syntax" : "http://amigo.geneontology.org/amigo/term/GO:[example_id]", "example_id" : "GO:0004352", "datatype" : null, "generic_url" : "http://amigo.geneontology.org/", "uri_prefix" : null, "database" : "Gene Ontology Database", "local_id_syntax" : "\\d{7}", "entity_type" : "GO:0032991 ! macromolecular complex" }, "iuphar_receptor" : { "uri_prefix" : null, "database" : "International Union of Pharmacology", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://www.iuphar-db.org/DATABASE/ObjectDisplayForward?objectId=56", "abbreviation" : "IUPHAR_RECEPTOR", "object" : null, "url_syntax" : "http://www.iuphar-db.org/DATABASE/ObjectDisplayForward?objectId=[example_id]", "example_id" : "IUPHAR_RECEPTOR:2205", "datatype" : null, "generic_url" : "http://www.iuphar.org/" }, "ddb" : { "generic_url" : "http://dictybase.org", "example_id" : "dictyBase:DDB_G0277859", "datatype" : null, "url_syntax" : "http://dictybase.org/gene/[example_id]", "object" : null, "abbreviation" : "DDB", "url_example" : "http://dictybase.org/gene/DDB_G0277859", "id" : null, "fullname" : null, "name" : null, "entity_type" : "SO:0000704 ! gene", "local_id_syntax" : "DDB_G[0-9]{7}", "database" : "dictyBase", "uri_prefix" : null }, "hgnc_gene" : { "uri_prefix" : null, "database" : "HUGO Gene Nomenclature Committee", "entity_type" : "BET:0000000 ! entity", "name" : null, "fullname" : null, "id" : null, "url_example" : "http://www.genenames.org/data/hgnc_data.php?app_sym=ABCA1", "abbreviation" : "HGNC_gene", "object" : null, "url_syntax" : "http://www.genenames.org/data/hgnc_data.php?app_sym=[example_id]", "datatype" : null, "example_id" : "HGNC_gene:ABCA1", "generic_url" : "http://www.genenames.org/" }, "pdb" : { "local_id_syntax" : "[A-Za-z0-9]{4}", "database" : "Protein Data Bank", "entity_type" : "PR:000000001 ! protein", "uri_prefix" : null, "example_id" : "PDB:1A4U", "datatype" : null, "url_syntax" : "http://www.rcsb.org/pdb/cgi/explore.cgi?pdbId=[example_id]", "generic_url" : "http://www.rcsb.org/pdb/", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://www.rcsb.org/pdb/cgi/explore.cgi?pdbId=1A4U", "abbreviation" : "PDB" }, "paint_ref" : { "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "PAINT_REF", "url_example" : "http://www.geneontology.org/gene-associations/submission/paint/PTHR10046/PTHR10046.txt", "datatype" : null, "example_id" : "PAINT_REF:PTHR10046", "url_syntax" : "http://www.geneontology.org/gene-associations/submission/paint/[example_id]/[example_id].txt", "generic_url" : "http://www.pantherdb.org/", "uri_prefix" : null, "database" : "Phylogenetic Annotation INference Tool References", "entity_type" : "BET:0000000 ! entity" }, "subtilist" : { "generic_url" : "http://genolist.pasteur.fr/SubtiList/", "example_id" : "SUBTILISTG:BG11384", "datatype" : null, "url_syntax" : null, "object" : null, "abbreviation" : "SUBTILIST", "url_example" : null, "name" : null, "fullname" : null, "id" : null, "entity_type" : "PR:000000001 ! protein", "database" : "Bacillus subtilis Genome Sequence Project", "uri_prefix" : null }, "mengo" : { "uri_prefix" : null, "database" : "Microbial ENergy processes Gene Ontology Project", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "MENGO", "url_example" : null, "example_id" : null, "datatype" : null, "url_syntax" : null, "generic_url" : "http://mengo.vbi.vt.edu/" }, "ddb_ref" : { "url_example" : "http://dictybase.org/db/cgi-bin/dictyBase/reference/reference.pl?refNo=10157", "abbreviation" : "DDB_REF", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://dictybase.org", "url_syntax" : "http://dictybase.org/db/cgi-bin/dictyBase/reference/reference.pl?refNo=[example_id]", "datatype" : null, "example_id" : "dictyBase_REF:10157", "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "dictyBase literature references" }, "obi" : { "uri_prefix" : null, "database" : "Ontology for Biomedical Investigations", "local_id_syntax" : "\\d{7}", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "url_example" : null, "abbreviation" : "OBI", "object" : null, "url_syntax" : null, "example_id" : "OBI:0000038", "datatype" : null, "generic_url" : "http://obi-ontology.org/page/Main_Page" }, "mim" : { "database" : "Mendelian Inheritance in Man", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "url_syntax" : "http://omim.org/entry/[example_id]", "datatype" : null, "example_id" : "OMIM:190198", "generic_url" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=OMIM", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://omim.org/entry/190198", "abbreviation" : "MIM", "object" : null }, "agi_locuscode" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "local_id_syntax" : "A[Tt][MmCc0-5][Gg][0-9]{5}(\\.[0-9]{1})?", "database" : "Arabidopsis Genome Initiative", "object" : null, "url_example" : "http://arabidopsis.org/servlets/TairObject?type=locus&name=At2g17950", "description" : "Comprises TAIR, TIGR and MIPS", "abbreviation" : "AGI_LocusCode", "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.arabidopsis.org", "datatype" : null, "example_id" : "AGI_LocusCode:At2g17950", "url_syntax" : "http://arabidopsis.org/servlets/TairObject?type=locus&name=[example_id]" }, "aspgd" : { "uri_prefix" : null, "local_id_syntax" : "ASPL[0-9]{10}", "database" : "Aspergillus Genome Database", "entity_type" : "SO:0000704 ! gene", "id" : null, "fullname" : null, "name" : null, "object" : null, "abbreviation" : "AspGD", "url_example" : "http://www.aspergillusgenome.org/cgi-bin/locus.pl?dbid=ASPL0000067538", "example_id" : "AspGD:ASPL0000067538", "datatype" : null, "url_syntax" : "http://www.aspergillusgenome.org/cgi-bin/locus.pl?dbid=[example_id]", "generic_url" : "http://www.aspergillusgenome.org/" }, "tgd" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Tetrahymena Genome Database", "url_example" : null, "abbreviation" : "TGD", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.ciliate.org/", "url_syntax" : null, "datatype" : null, "example_id" : null }, "uberon" : { "id" : null, "fullname" : null, "name" : null, "object" : null, "url_example" : "http://purl.obolibrary.org/obo/UBERON_0002398", "description" : "A multi-species anatomy ontology", "abbreviation" : "UBERON", "datatype" : null, "example_id" : "URBERON:0002398", "url_syntax" : "http://purl.obolibrary.org/obo/UBERON_[example_id]", "generic_url" : "http://uberon.org", "uri_prefix" : null, "local_id_syntax" : "[0-9]{7}", "database" : "Uber-anatomy ontology", "entity_type" : "CARO:0000000 ! anatomical entity" }, "biomdid" : { "generic_url" : "http://www.ebi.ac.uk/biomodels/", "url_syntax" : "http://www.ebi.ac.uk/compneur-srv/biomodels-main/publ-model.do?mid=[example_id]", "datatype" : null, "example_id" : "BIOMD:BIOMD0000000045", "url_example" : "http://www.ebi.ac.uk/compneur-srv/biomodels-main/publ-model.do?mid=BIOMD0000000045", "abbreviation" : "BIOMDID", "object" : null, "name" : null, "id" : null, "fullname" : null, "entity_type" : "BET:0000000 ! entity", "database" : "BioModels Database", "uri_prefix" : null }, "wbls" : { "id" : null, "fullname" : null, "name" : null, "url_example" : null, "abbreviation" : "WBls", "object" : null, "url_syntax" : null, "datatype" : null, "example_id" : "WBls:0000010", "generic_url" : "http://www.wormbase.org/", "uri_prefix" : null, "database" : "C. elegans development", "local_id_syntax" : "[0-9]{7}", "entity_type" : "WBls:0000075 ! nematoda life stage" }, "cgd" : { "name" : null, "fullname" : null, "id" : null, "object" : null, "abbreviation" : "CGD", "url_example" : "http://www.candidagenome.org/cgi-bin/locus.pl?dbid=CAL0005516", "datatype" : null, "example_id" : "CGD:CAL0005516", "url_syntax" : "http://www.candidagenome.org/cgi-bin/locus.pl?dbid=[example_id]", "generic_url" : "http://www.candidagenome.org/", "uri_prefix" : null, "local_id_syntax" : "(CAL|CAF)[0-9]{7}", "database" : "Candida Genome Database", "entity_type" : "SO:0000704 ! gene" }, "ensembl_transcriptid" : { "uri_prefix" : null, "entity_type" : "SO:0000673 ! transcript", "database" : "Ensembl database of automatically annotated genomic data", "local_id_syntax" : "ENST[0-9]{9,16}", "abbreviation" : "ENSEMBL_TranscriptID", "url_example" : "http://www.ensembl.org/id/ENST00000371959", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.ensembl.org/", "url_syntax" : "http://www.ensembl.org/id/[example_id]", "datatype" : null, "example_id" : "ENSEMBL_TranscriptID:ENST00000371959" }, "mtbbase" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Collection and Refinement of Physiological Data on Mycobacterium tuberculosis", "abbreviation" : "MTBBASE", "url_example" : null, "object" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "http://www.ark.in-berlin.de/Site/MTBbase.html", "url_syntax" : null, "example_id" : null, "datatype" : null }, "pompep" : { "object" : null, "abbreviation" : "Pompep", "url_example" : null, "id" : null, "fullname" : null, "name" : null, "generic_url" : "ftp://ftp.sanger.ac.uk/pub/yeast/pombe/Protein_data/", "example_id" : "Pompep:SPAC890.04C", "datatype" : null, "url_syntax" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Schizosaccharomyces pombe protein data" }, "interpro" : { "database" : "InterPro database of protein domains and motifs", "local_id_syntax" : "IPR\\d{6}", "entity_type" : "SO:0000839 ! polypeptide region", "uri_prefix" : null, "url_syntax" : "http://www.ebi.ac.uk/interpro/entry/[example_id]", "datatype" : null, "example_id" : "InterPro:IPR000001", "generic_url" : "http://www.ebi.ac.uk/interpro/", "id" : null, "name" : null, "fullname" : null, "url_example" : "http://www.ebi.ac.uk/interpro/entry/IPR015421", "abbreviation" : "INTERPRO", "object" : null }, "prosite" : { "fullname" : null, "id" : null, "name" : null, "url_example" : "http://www.expasy.ch/cgi-bin/prosite-search-ac?PS00365", "abbreviation" : "Prosite", "object" : null, "url_syntax" : "http://www.expasy.ch/cgi-bin/prosite-search-ac?[example_id]", "example_id" : "Prosite:PS00365", "datatype" : null, "generic_url" : "http://www.expasy.ch/prosite/", "uri_prefix" : null, "database" : "Prosite database of protein families and domains", "entity_type" : "SO:0000839 ! polypeptide region" }, "cacao" : { "entity_type" : "BET:0000000 ! entity", "database" : "Community Assessment of Community Annotation with Ontologies", "uri_prefix" : null, "generic_url" : "http://gowiki.tamu.edu/wiki/index.php/Category:CACAO", "example_id" : "MYCS2:A0QNF5", "datatype" : null, "url_syntax" : "http://gowiki.tamu.edu/wiki/index.php/[example_id]", "object" : null, "description" : "The Community Assessment of Community Annotation with Ontologies (CACAO) is a project to do large-scale manual community annotation of gene function using the Gene Ontology as a multi-institution student competition.", "abbreviation" : "CACAO", "url_example" : "http://gowiki.tamu.edu/wiki/index.php/MYCS2:A0QNF5", "id" : null, "fullname" : null, "name" : null }, "hamap" : { "url_syntax" : "http://hamap.expasy.org/unirule/[example_id]", "example_id" : "HAMAP:MF_00031", "datatype" : null, "generic_url" : "http://hamap.expasy.org/", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://hamap.expasy.org/unirule/MF_00131", "abbreviation" : "HAMAP", "object" : null, "database" : "High-quality Automated and Manual Annotation of microbial Proteomes", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "wb_ref" : { "datatype" : null, "example_id" : "WB_REF:WBPaper00004823", "url_syntax" : "http://www.wormbase.org/db/misc/paper?name=[example_id]", "generic_url" : "http://www.wormbase.org/", "fullname" : null, "id" : null, "name" : null, "object" : null, "url_example" : "http://www.wormbase.org/db/misc/paper?name=WBPaper00004823", "abbreviation" : "WB_REF", "database" : "WormBase database of nematode biology", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "genbank" : { "entity_type" : "PR:000000001 ! protein", "database" : "GenBank", "local_id_syntax" : "([A-Z]{2}[0-9]{6})|([A-Z]{1}[0-9]{5})", "uri_prefix" : null, "generic_url" : "http://www.ncbi.nlm.nih.gov/Genbank/", "url_syntax" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=[example_id]", "example_id" : "GB:AA816246", "datatype" : null, "url_example" : "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&val=AA816246", "description" : "The NIH genetic sequence database, an annotated collection of all publicly available DNA sequences.", "abbreviation" : "GenBank", "object" : null, "fullname" : null, "name" : null, "id" : null }, "psort" : { "fullname" : null, "name" : null, "id" : null, "url_example" : null, "abbreviation" : "PSORT", "object" : null, "url_syntax" : null, "example_id" : null, "datatype" : null, "generic_url" : "http://www.psort.org/", "uri_prefix" : null, "database" : "PSORT protein subcellular localization databases and prediction tools for bacteria", "entity_type" : "BET:0000000 ! entity" }, "psi-mi" : { "generic_url" : "http://psidev.sourceforge.net/mi/xml/doc/user/index.html", "url_syntax" : null, "example_id" : "MI:0018", "datatype" : null, "url_example" : null, "abbreviation" : "PSI-MI", "object" : null, "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Proteomic Standard Initiative for Molecular Interaction", "uri_prefix" : null }, "gene3d" : { "uri_prefix" : null, "database" : "Domain Architecture Classification", "entity_type" : "BET:0000000 ! entity", "fullname" : null, "id" : null, "name" : null, "url_example" : "http://gene3d.biochem.ucl.ac.uk/superfamily/?accession=G3DSA%3A3.30.390.30", "abbreviation" : "Gene3D", "object" : null, "url_syntax" : "http://gene3d.biochem.ucl.ac.uk/superfamily/?accession=[example_id]", "datatype" : null, "example_id" : "Gene3D:G3DSA:3.30.390.30", "generic_url" : "http://gene3d.biochem.ucl.ac.uk/Gene3D/" }, "poc" : { "url_example" : null, "abbreviation" : "POC", "object" : null, "fullname" : null, "name" : null, "id" : null, "generic_url" : "http://www.plantontology.org/", "url_syntax" : null, "datatype" : null, "example_id" : null, "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Plant Ontology Consortium" }, "phi" : { "entity_type" : "BET:0000000 ! entity", "database" : "MeGO (Phage and Mobile Element Ontology)", "uri_prefix" : null, "generic_url" : "http://aclame.ulb.ac.be/Classification/mego.html", "datatype" : null, "example_id" : "PHI:0000055", "url_syntax" : null, "object" : null, "abbreviation" : "PHI", "url_example" : null, "fullname" : null, "id" : null, "name" : null }, "tigr" : { "entity_type" : "BET:0000000 ! entity", "database" : "J. Craig Venter Institute", "uri_prefix" : null, "generic_url" : "http://www.jcvi.org/", "datatype" : null, "example_id" : null, "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "TIGR", "id" : null, "name" : null, "fullname" : null }, "biosis" : { "entity_type" : "BET:0000000 ! entity", "database" : "BIOSIS previews", "uri_prefix" : null, "generic_url" : "http://www.biosis.org/", "url_syntax" : null, "example_id" : "BIOSIS:200200247281", "datatype" : null, "abbreviation" : "BIOSIS", "url_example" : null, "object" : null, "fullname" : null, "name" : null, "id" : null }, "jcvi_genprop" : { "uri_prefix" : null, "entity_type" : "GO:0008150 ! biological_process", "local_id_syntax" : "GenProp[0-9]{4}", "database" : "Genome Properties database at the J. Craig Venter Institute", "object" : null, "abbreviation" : "JCVI_GenProp", "url_example" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenomePropDefinition.cgi?prop_acc=GenProp0120", "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://cmr.jcvi.org/", "datatype" : null, "example_id" : "JCVI_GenProp:GenProp0120", "url_syntax" : "http://cmr.jcvi.org/cgi-bin/CMR/shared/GenomePropDefinition.cgi?prop_acc=[example_id]" }, "biopixie_mefit" : { "generic_url" : "http://pixie.princeton.edu/pixie/", "example_id" : null, "datatype" : null, "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "bioPIXIE_MEFIT", "fullname" : null, "name" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "biological Process Inference from eXperimental Interaction Evidence/Microarray Experiment Functional Integration Technology", "uri_prefix" : null }, "mi" : { "generic_url" : "http://psidev.sourceforge.net/mi/xml/doc/user/index.html", "url_syntax" : null, "datatype" : null, "example_id" : "MI:0018", "url_example" : null, "abbreviation" : "MI", "object" : null, "id" : null, "name" : null, "fullname" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Proteomic Standard Initiative for Molecular Interaction", "uri_prefix" : null }, "pato" : { "entity_type" : "BET:0000000 ! entity", "database" : "Phenotypic quality ontology", "uri_prefix" : null, "generic_url" : "http://www.bioontology.org/wiki/index.php/PATO:Main_Page", "url_syntax" : null, "example_id" : "PATO:0001420", "datatype" : null, "url_example" : null, "abbreviation" : "PATO", "object" : null, "id" : null, "fullname" : null, "name" : null }, "kegg_pathway" : { "generic_url" : "http://www.genome.jp/kegg/pathway.html", "url_syntax" : "http://www.genome.jp/dbget-bin/www_bget?path:[example_id]", "example_id" : "KEGG_PATHWAY:ot00020", "datatype" : null, "abbreviation" : "KEGG_PATHWAY", "url_example" : "http://www.genome.jp/dbget-bin/www_bget?path:ot00020", "object" : null, "name" : null, "fullname" : null, "id" : null, "entity_type" : "BET:0000000 ! entity", "database" : "KEGG Pathways Database", "uri_prefix" : null }, "ecogene_g" : { "database" : "EcoGene Database of Escherichia coli Sequence and Function", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null, "example_id" : "ECOGENE_G:deoC", "datatype" : null, "url_syntax" : null, "generic_url" : "http://www.ecogene.org/", "fullname" : null, "name" : null, "id" : null, "object" : null, "abbreviation" : "ECOGENE_G", "url_example" : null }, "eck" : { "uri_prefix" : null, "local_id_syntax" : "ECK[0-9]{4}", "database" : "EcoGene Database of Escherichia coli Sequence and Function", "entity_type" : "SO:0000704 ! gene", "id" : null, "fullname" : null, "name" : null, "object" : null, "abbreviation" : "ECK", "url_example" : "http://www.ecogene.org/geneInfo.php?eck_id=ECK3746", "example_id" : "ECK:ECK3746", "datatype" : null, "url_syntax" : "http://www.ecogene.org/geneInfo.php?eck_id=[example_id]", "generic_url" : "http://www.ecogene.org/" }, "um-bbd_ruleid" : { "url_syntax" : "http://umbbd.msi.umn.edu/servlets/rule.jsp?rule=[example_id]", "datatype" : null, "example_id" : "UM-BBD_ruleID:bt0330", "generic_url" : "http://umbbd.msi.umn.edu/", "name" : null, "fullname" : null, "id" : null, "abbreviation" : "UM-BBD_ruleID", "url_example" : "http://umbbd.msi.umn.edu/servlets/rule.jsp?rule=bt0330", "object" : null, "database" : "University of Minnesota Biocatalysis/Biodegradation Database", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "eurofung" : { "uri_prefix" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Eurofungbase community annotation", "url_example" : null, "abbreviation" : "Eurofung", "object" : null, "fullname" : null, "id" : null, "name" : null, "generic_url" : "http://www.eurofung.net/option=com_content&task=section&id=3&Itemid=4", "url_syntax" : null, "datatype" : null, "example_id" : null }, "phenoscape" : { "entity_type" : "BET:0000000 ! entity", "database" : "PhenoScape Knowledgebase", "uri_prefix" : null, "generic_url" : "http://phenoscape.org/", "example_id" : null, "datatype" : null, "url_syntax" : null, "object" : null, "url_example" : null, "abbreviation" : "PhenoScape", "name" : null, "fullname" : null, "id" : null }, "unimod" : { "entity_type" : "BET:0000000 ! entity", "database" : "UniMod", "uri_prefix" : null, "generic_url" : "http://www.unimod.org/", "url_syntax" : "http://www.unimod.org/modifications_view.php?editid1=[example_id]", "datatype" : null, "example_id" : "UniMod:1287", "description" : "protein modifications for mass spectrometry", "abbreviation" : "UniMod", "url_example" : "http://www.unimod.org/modifications_view.php?editid1=1287", "object" : null, "name" : null, "fullname" : null, "id" : null }, "syscilia_ccnet" : { "entity_type" : "BET:0000000 ! entity", "database" : "Syscilia", "uri_prefix" : null, "generic_url" : "http://syscilia.org/", "url_syntax" : null, "datatype" : null, "example_id" : null, "url_example" : null, "description" : "A systems biology approach to dissect cilia function and its disruption in human genetic disease", "abbreviation" : "SYSCILIA_CCNET", "object" : null, "id" : null, "fullname" : null, "name" : null }, "omim" : { "fullname" : null, "name" : null, "id" : null, "object" : null, "url_example" : "http://omim.org/entry/190198", "abbreviation" : "OMIM", "datatype" : null, "example_id" : "OMIM:190198", "url_syntax" : "http://omim.org/entry/[example_id]", "generic_url" : "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=OMIM", "uri_prefix" : null, "database" : "Mendelian Inheritance in Man", "entity_type" : "BET:0000000 ! entity" }, "pseudocap" : { "url_syntax" : "http://v2.pseudomonas.com/getAnnotation.do?locusID=[example_id]", "datatype" : null, "example_id" : "PseudoCAP:PA4756", "generic_url" : "http://v2.pseudomonas.com/", "fullname" : null, "name" : null, "id" : null, "url_example" : "http://v2.pseudomonas.com/getAnnotation.do?locusID=PA4756", "abbreviation" : "PseudoCAP", "object" : null, "database" : "Pseudomonas Genome Project", "entity_type" : "BET:0000000 ! entity", "uri_prefix" : null }, "asap" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "A Systematic Annotation Package for Community Analysis of Genomes", "object" : null, "abbreviation" : "ASAP", "url_example" : "https://asap.ahabs.wisc.edu/annotation/php/feature_info.php?FeatureID=ABE-0000008", "id" : null, "fullname" : null, "name" : null, "generic_url" : "https://asap.ahabs.wisc.edu/annotation/php/ASAP1.htm", "example_id" : "ASAP:ABE-0000008", "datatype" : null, "url_syntax" : "https://asap.ahabs.wisc.edu/annotation/php/feature_info.php?FeatureID=[example_id]" }, "gr_ref" : { "generic_url" : "http://www.gramene.org/", "url_syntax" : "http://www.gramene.org/db/literature/pub_search?ref_id=[example_id]", "example_id" : "GR_REF:659", "datatype" : null, "url_example" : "http://www.gramene.org/db/literature/pub_search?ref_id=659", "abbreviation" : "GR_REF", "object" : null, "id" : null, "fullname" : null, "name" : null, "entity_type" : "BET:0000000 ! entity", "database" : "Gramene", "uri_prefix" : null }, "sgd" : { "uri_prefix" : null, "entity_type" : "SO:0000704 ! gene", "database" : "Saccharomyces Genome Database", "local_id_syntax" : "S[0-9]{9}", "url_example" : "http://www.yeastgenome.org/locus/S000006169/overview", "abbreviation" : "SGD", "object" : null, "name" : null, "fullname" : null, "id" : null, "generic_url" : "http://www.yeastgenome.org/", "url_syntax" : "http://www.yeastgenome.org/locus/[example_id]/overview", "datatype" : null, "example_id" : "SGD:S000006169" } };
mugitty/bbop-js
_data/xrefs.js
JavaScript
bsd-3-clause
170,836
// d3.tip // Copyright (c) 2013 Justin Palmer // // Tooltips for d3.js SVG visualizations (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module with d3 as a dependency. define(['d3'], factory) } else if (typeof module === 'object' && module.exports) { // CommonJS module.exports = function(d3) { d3.tip = factory(d3) return d3.tip } } else { // Browser global. root.d3.tip = factory(root.d3) } }(this, function (d3) { // Public - contructs a new tooltip // // Returns a tip return function() { var direction = d3_tip_direction, offset = d3_tip_offset, html = d3_tip_html, node = initNode(), svg = null, point = null, target = null, parent = null, fixed_el = null function tip(vis) { svg = getSVGNode(vis) point = svg.createSVGPoint() } // Public - show the tooltip on the screen // // Returns a tip tip.show = function() { if(!parent) tip.parent(document.body); var args = Array.prototype.slice.call(arguments) if(args[args.length - 1] instanceof SVGElement) target = args.pop() var content = html.apply(this, args), poffset = offset.apply(this, args), dir = direction.apply(this, args), nodel = getNodeEl(), i = directions.length, coords, parentCoords = node.offsetParent.getBoundingClientRect() nodel.html(content) .style({ visibility: 'visible', opacity: 1, 'pointer-events': 'all' }) while(i--) nodel.classed(directions[i], false) coords = direction_callbacks.get(dir).apply(this) nodel.classed(dir, true).style({ top: (coords.top + poffset[0]) - parentCoords.top + 'px', left: (coords.left + poffset[1]) - parentCoords.left + 'px' }) return tip } // Public - hide the tooltip // // Returns a tip tip.hide = function() { var nodel = getNodeEl() nodel.style({ visibility: 'hidden', opacity: 0, 'pointer-events': 'none' }) return tip } // Public: Proxy attr calls to the d3 tip container. Sets or gets attribute value. // // n - name of the attribute // v - value of the attribute // // Returns tip or attribute value tip.attr = function(n, v) { if (arguments.length < 2 && typeof n === 'string') { return getNodeEl().attr(n) } else { var args = Array.prototype.slice.call(arguments) d3.selection.prototype.attr.apply(getNodeEl(), args) } return tip } // Public: Proxy style calls to the d3 tip container. Sets or gets a style value. // // n - name of the property // v - value of the property // // Returns tip or style property value tip.style = function(n, v) { if (arguments.length < 2 && typeof n === 'string') { return getNodeEl().style(n) } else { var args = Array.prototype.slice.call(arguments) d3.selection.prototype.style.apply(getNodeEl(), args) } return tip } // Public: Set or get the direction or fixed position of the tooltip // // v - One of n(north), s(south), e(east), or w(west), nw(northwest), // sw(southwest), ne(northeast) or se(southeast). May also be set // to 'fixed', which requires a seconds parameter: the id of an // SVG element on the page to which the tip will be fixed in its // position. It will be fixed to the nw corner of the element. Use // the offset call when creating the tip to adjust position relative // to the nw corner of the fixed element. Example call: // .direction('fixed', '#choropleth') // // // Returns tip or direction tip.direction = function(v) { if (!arguments.length) { return direction; } else if (arguments.length == 2) { fixed_el = arguments[1]; } direction = v == null ? v : d3.functor(v); return tip; } // Public: Sets or gets the offset of the tip // // v - Array of [x, y] offset // // Returns offset or tip.offset = function(v) { if (!arguments.length) return offset offset = v == null ? v : d3.functor(v) return tip } // Public: sets or gets the html value of the tooltip // // v - String value of the tip // // Returns html value or tip tip.html = function(v) { if (!arguments.length) return html html = v == null ? v : d3.functor(v) return tip } // Public: Sets or gets the parent of the tooltip element // // v - New parent for the tip // // Returns parent element or tip tip.parent = function(v) { if (!arguments.length) return parent parent = v || document.body parent.appendChild(node) // Make sure offsetParent has a position so the tip can be // based from it. Mainly a concern with <body>. var offsetParent = d3.select(node.offsetParent) if (offsetParent.style('position') === 'static') { offsetParent.style('position', 'relative') } return tip } // Public: destroys the tooltip and removes it from the DOM // // Returns a tip tip.destroy = function() { if(node) { getNodeEl().remove(); node = null; } return tip; } function d3_tip_direction() { return 'n' } function d3_tip_offset() { return [0, 0] } function d3_tip_html() { return ' ' } var direction_callbacks = d3.map({ fixed: direction_fixed, n: direction_n, s: direction_s, e: direction_e, w: direction_w, nw: direction_nw, ne: direction_ne, sw: direction_sw, se: direction_se }), directions = direction_callbacks.keys() function direction_fixed() { var bbox = getScreenBBox(fixed_el); return { top: bbox.nw.y, left: bbox.nw.x } } function direction_n() { var bbox = getScreenBBox() return { top: bbox.n.y - node.offsetHeight, left: bbox.n.x - node.offsetWidth / 2 } } function direction_s() { var bbox = getScreenBBox() return { top: bbox.s.y, left: bbox.s.x - node.offsetWidth / 2 } } function direction_e() { var bbox = getScreenBBox() return { top: bbox.e.y - node.offsetHeight / 2, left: bbox.e.x } } function direction_w() { var bbox = getScreenBBox() return { top: bbox.w.y - node.offsetHeight / 2, left: bbox.w.x - node.offsetWidth } } function direction_nw() { var bbox = getScreenBBox() return { top: bbox.nw.y - node.offsetHeight, left: bbox.nw.x - node.offsetWidth } } function direction_ne() { var bbox = getScreenBBox() return { top: bbox.ne.y - node.offsetHeight, left: bbox.ne.x } } function direction_sw() { var bbox = getScreenBBox() return { top: bbox.sw.y, left: bbox.sw.x - node.offsetWidth } } function direction_se() { var bbox = getScreenBBox() return { top: bbox.se.y, left: bbox.e.x } } function initNode() { var node = d3.select(document.createElement('div')) node.style({ position: 'absolute', top: 0, opacity: 0, 'pointer-events': 'none', 'box-sizing': 'border-box' }) return node.node() } function getSVGNode(el) { el = el.node() if(el.tagName.toLowerCase() === 'svg') return el return el.ownerSVGElement } function getNodeEl() { if(node === null) { node = initNode(); // re-add node to DOM document.body.appendChild(node); }; return d3.select(node); } // Private - gets the screen coordinates of a shape // // Given a shape on the screen, will return an SVGPoint for the directions // n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest), // sw(southwest). // // +-+-+ // | | // + + // | | // +-+-+ // // Returns an Object {n, s, e, w, nw, sw, ne, se} function getScreenBBox(fixed_element) { var targetel; if (fixed_element){ targetel = d3.select(fixed_element)[0][0]; } else { targetel = target || d3.event.target; } while ('undefined' === typeof targetel.getScreenCTM && 'undefined' === targetel.parentNode) { targetel = targetel.parentNode; } var bbox = {}, matrix = targetel.getScreenCTM(), tbbox = targetel.getBBox(), width = tbbox.width, height = tbbox.height, x = tbbox.x, y = tbbox.y point.x = x point.y = y bbox.nw = point.matrixTransform(matrix) point.x += width bbox.ne = point.matrixTransform(matrix) point.y += height bbox.se = point.matrixTransform(matrix) point.x -= width bbox.sw = point.matrixTransform(matrix) point.y -= height / 2 bbox.w = point.matrixTransform(matrix) point.x += width bbox.e = point.matrixTransform(matrix) point.x -= width / 2 point.y -= height / 2 bbox.n = point.matrixTransform(matrix) point.y += height bbox.s = point.matrixTransform(matrix) return bbox } return tip }; }));
carnby/matta
datagramas/libs/d3-tip/index.js
JavaScript
bsd-3-clause
9,759
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Polymer element for displaying a summary of network states * by type: Ethernet, WiFi, Cellular, WiMAX, and VPN. */ (function() { /** @typedef {chrome.networkingPrivate.DeviceStateProperties} */ var DeviceStateProperties; /** * @typedef {{ * Ethernet: (DeviceStateProperties|undefined), * WiFi: (DeviceStateProperties|undefined), * Cellular: (DeviceStateProperties|undefined), * WiMAX: (DeviceStateProperties|undefined), * VPN: (DeviceStateProperties|undefined) * }} */ var DeviceStateObject; /** * @typedef {{ * Ethernet: (?CrOnc.NetworkStateProperties|undefined), * WiFi: (?CrOnc.NetworkStateProperties|undefined), * Cellular: (?CrOnc.NetworkStateProperties|undefined), * WiMAX: (?CrOnc.NetworkStateProperties|undefined), * VPN: (?CrOnc.NetworkStateProperties|undefined) * }} */ var NetworkStateObject; /** * @typedef {{ * Ethernet: (Array<CrOnc.NetworkStateProperties>|undefined), * WiFi: (Array<CrOnc.NetworkStateProperties>|undefined), * Cellular: (Array<CrOnc.NetworkStateProperties>|undefined), * WiMAX: (Array<CrOnc.NetworkStateProperties>|undefined), * VPN: (Array<CrOnc.NetworkStateProperties>|undefined) * }} */ var NetworkStateListObject; /** @const {!Array<string>} */ var NETWORK_TYPES = [ CrOnc.Type.ETHERNET, CrOnc.Type.WI_FI, CrOnc.Type.CELLULAR, CrOnc.Type.WI_MAX, CrOnc.Type.VPN ]; Polymer({ is: 'network-summary', properties: { /** * The device state for each network device type. * @type {DeviceStateObject} */ deviceStates: { type: Object, value: function() { return {}; }, }, /** * Network state data for each network type. * @type {NetworkStateObject} */ networkStates: { type: Object, value: function() { return {}; }, }, /** * List of network state data for each network type. * @type {NetworkStateListObject} */ networkStateLists: { type: Object, value: function() { return {}; }, } }, /** * Listener function for chrome.networkingPrivate.onNetworkListChanged event. * @type {?function(!Array<string>)} * @private */ networkListChangedListener_: null, /** * Listener function for chrome.networkingPrivate.onDeviceStateListChanged * event. * @type {?function(!Array<string>)} * @private */ deviceStateListChangedListener_: null, /** * Listener function for chrome.networkingPrivate.onNetworksChanged event. * @type {?function(!Array<string>)} * @private */ networksChangedListener_: null, /** * Dictionary of GUIDs identifying primary (active) networks for each type. * @type {?Object} * @private */ networkIds_: null, /** @override */ attached: function() { this.networkIds_ = {}; this.getNetworkLists_(); this.networkListChangedListener_ = this.onNetworkListChangedEvent_.bind(this); chrome.networkingPrivate.onNetworkListChanged.addListener( this.networkListChangedListener_); this.deviceStateListChangedListener_ = this.onDeviceStateListChangedEvent_.bind(this); chrome.networkingPrivate.onDeviceStateListChanged.addListener( this.deviceStateListChangedListener_); this.networksChangedListener_ = this.onNetworksChangedEvent_.bind(this); chrome.networkingPrivate.onNetworksChanged.addListener( this.networksChangedListener_); }, /** @override */ detached: function() { chrome.networkingPrivate.onNetworkListChanged.removeListener( this.networkListChangedListener_); chrome.networkingPrivate.onDeviceStateListChanged.removeListener( this.deviceStateListChangedListener_); chrome.networkingPrivate.onNetworksChanged.removeListener( this.networksChangedListener_); }, /** * Event triggered when the WiFi network-summary-item is expanded. * @param {!{detail: {expanded: boolean, type: string}}} event * @private */ onWiFiExpanded_: function(event) { this.getNetworkStates_(); // Get the latest network states (only). if (event.detail.expanded) chrome.networkingPrivate.requestNetworkScan(); }, /** * Event triggered when a network-summary-item is selected. * @param {!{detail: !CrOnc.NetworkStateProperties}} event * @private */ onSelected_: function(event) { var state = event.detail; if (state.ConnectionState == CrOnc.ConnectionState.NOT_CONNECTED) { this.connectToNetwork_(state); return; } MoreRouting.navigateTo('internet-detail', {guid: state.GUID}); }, /** * Event triggered when the enabled state of a network-summary-item is * toggled. * @param {!{detail: {enabled: boolean, type: string}}} event * @private */ onDeviceEnabledToggled_: function(event) { if (event.detail.enabled) chrome.networkingPrivate.enableNetworkType(event.detail.type); else chrome.networkingPrivate.disableNetworkType(event.detail.type); }, /** * networkingPrivate.onNetworkListChanged event callback. * @private */ onNetworkListChangedEvent_: function() { this.getNetworkLists_(); }, /** * networkingPrivate.onDeviceStateListChanged event callback. * @private */ onDeviceStateListChangedEvent_: function() { this.getNetworkLists_(); }, /** * networkingPrivate.onNetworksChanged event callback. * @param {!Array<string>} networkIds The list of changed network GUIDs. * @private */ onNetworksChangedEvent_: function(networkIds) { networkIds.forEach(function(id) { if (id in this.networkIds_) { chrome.networkingPrivate.getState( id, function(state) { if (chrome.runtime.lastError) { if (chrome.runtime.lastError != 'Error.NetworkUnavailable') { console.error('Unexpected networkingPrivate.getState error:', chrome.runtime.lastError); } return; } // Async call, ensure id still exists. if (!this.networkIds_[id]) return; if (!state) { this.networkIds_[id] = undefined; return; } this.updateNetworkState_(state.Type, state); }.bind(this)); } }, this); }, /** * Handles UI requests to connect to a network. * TODO(stevenjb): Handle Cellular activation, etc. * @param {!CrOnc.NetworkStateProperties} state The network state. * @private */ connectToNetwork_: function(state) { chrome.networkingPrivate.startConnect(state.GUID, function() { if (chrome.runtime.lastError && chrome.runtime.lastError != 'connecting') { console.error('Unexpected networkingPrivate.startConnect error:', chrome.runtime.lastError); } }); }, /** * Requests the list of device states and network states from Chrome. * Updates deviceStates, networkStates, and networkStateLists once the * results are returned from Chrome. * @private */ getNetworkLists_: function() { // First get the device states. chrome.networkingPrivate.getDeviceStates( function(states) { this.getDeviceStatesCallback_(states); // Second get the network states. this.getNetworkStates_(); }.bind(this)); }, /** * Requests the list of network states from Chrome. Updates networkStates and * networkStateLists once the results are returned from Chrome. * @private */ getNetworkStates_: function() { var filter = { networkType: 'All', visible: true, configured: false }; chrome.networkingPrivate.getNetworks( filter, this.getNetworksCallback_.bind(this)); }, /** * networkingPrivate.getDeviceStates callback. * @param {!Array<!DeviceStateProperties>} states The state properties for all * available devices. * @private */ getDeviceStatesCallback_: function(states) { /** @type {!DeviceStateObject} */ var newStates = {}; states.forEach(function(state) { newStates[state.Type] = state; }); this.deviceStates = newStates; }, /** * networkingPrivate.getNetworksState callback. * @param {!Array<!CrOnc.NetworkStateProperties>} states The state properties * for all visible networks. * @private */ getNetworksCallback_: function(states) { // Clear any current networks. this.networkIds_ = {}; // Track the first (active) state for each type. var foundTypes = {}; // Complete list of states by type. /** @type {!NetworkStateListObject} */ var networkStateLists = { Ethernet: [], WiFi: [], Cellular: [], WiMAX: [], VPN: [] }; states.forEach(function(state) { var type = state.Type; if (!foundTypes[type]) { foundTypes[type] = true; this.updateNetworkState_(type, state); } networkStateLists[type].push(state); }, this); // Set any types with a deviceState and no network to a default state, // and any types not found to null. NETWORK_TYPES.forEach(function(type) { if (!foundTypes[type]) { /** @type {CrOnc.NetworkStateProperties} */ var defaultState = null; if (this.deviceStates[type]) defaultState = { GUID: '', Type: type }; this.updateNetworkState_(type, defaultState); } }, this); this.networkStateLists = networkStateLists; // Create a VPN entry in deviceStates if there are any VPN networks. if (networkStateLists.VPN && networkStateLists.VPN.length > 0) { var vpn = { Type: CrOnc.Type.VPN, State: 'Enabled' }; this.set('deviceStates.VPN', vpn); } }, /** * Sets 'networkStates[type]' which will update the cr-network-list-item * associated with 'type'. * @param {string} type The network type. * @param {?CrOnc.NetworkStateProperties} state The state properties for the * network to associate with |type|. May be null if there are no networks * matching |type|. * @private */ updateNetworkState_: function(type, state) { this.set('networkStates.' + type, state); if (state) this.networkIds_[state.GUID] = true; }, }); })();
vadimtk/chrome4sdp
chrome/browser/resources/settings/internet_page/network_summary.js
JavaScript
bsd-3-clause
10,457
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const getInverseDependencies = require('./getInverseDependencies'); const querystring = require('querystring'); const url = require('url'); import type {ResolutionResponse} from './getInverseDependencies'; import type {Server as HTTPServer} from 'http'; import type {Server as HTTPSServer} from 'https'; import type {Client as WebSocketClient} from 'ws'; const blacklist = [ 'Libraries/Utilities/HMRClient.js', ]; type HMRBundle = { getModulesIdsAndCode(): Array<{id: string, code: string}>, getSourceMappingURLs(): Array<mixed>, getSourceURLs(): Array<mixed>, isEmpty(): boolean, }; type DependencyOptions = {| +dev: boolean, +entryFile: string, +hot: boolean, +minify: boolean, +platform: ?string, +recursive: boolean, +rootEntryFile: string, +bundlingOptions?: Object, |}; /** * This is a subset of the actual `metro-bundler`'s `Server` class, * without all the stuff we don't need to know about. This allows us to use * `attachHMRServer` with different versions of `metro-bundler` as long as * this specific contract is maintained. */ type PackagerServer<TModule> = { buildBundleForHMR( options: {platform: ?string}, host: string, port: number, ): Promise<HMRBundle>, getDependencies(options: DependencyOptions): Promise<ResolutionResponse<TModule>>, getModuleForPath(entryFile: string): Promise<TModule>, getShallowDependencies(options: DependencyOptions): Promise<Array<string>>, setHMRFileChangeListener(listener: ?(type: string, filePath: string) => mixed): void, }; type HMROptions<TModule> = { httpServer: HTTPServer | HTTPSServer, packagerServer: PackagerServer<TModule>, path: string, }; type Moduleish = { getName(): string, isAsset(): boolean, isJSON(): boolean, path: string, }; /** * Attaches a WebSocket based connection to the Packager to expose * Hot Module Replacement updates to the simulator. */ function attachHMRServer<TModule: Moduleish>( {httpServer, path, packagerServer}: HMROptions<TModule>, ) { type Client = {| ws: WebSocketClient, platform: string, bundleEntry: string, dependenciesCache: Array<string>, dependenciesModulesCache: {[mixed]: TModule}, shallowDependencies: {[string]: Array<string>}, inverseDependenciesCache: mixed, |}; const clients: Set<Client> = new Set(); function disconnect(client: Client) { clients.delete(client); // If there are no clients connected, stop listenig for file changes if (clients.size === 0) { packagerServer.setHMRFileChangeListener(null); } } // For the give platform and entry file, returns a promise with: // - The full list of dependencies. // - The shallow dependencies each file on the dependency list has // - Inverse shallow dependencies map async function getDependencies(platform: string, bundleEntry: string): Promise<{ dependenciesCache: Array<string>, dependenciesModulesCache: {[mixed]: TModule}, shallowDependencies: {[string]: Array<string>}, inverseDependenciesCache: mixed, /* $FlowFixMe(>=0.54.0 site=react_native_fb,react_native_oss) This comment * suppresses an error found when Flow v0.54 was deployed. To see the error * delete this comment and run Flow. */ resolutionResponse: ResolutionResponse<TModule>, }> { const response = await packagerServer.getDependencies({ dev: true, entryFile: bundleEntry, rootEntryFile: bundleEntry, hot: true, minify: false, platform: platform, recursive: true, }); /* $FlowFixMe: getModuleId might be null */ const {getModuleId}: {getModuleId: () => number} = response; // for each dependency builds the object: // `{path: '/a/b/c.js', deps: ['modA', 'modB', ...]}` const deps: Array<{ path: string, name?: string, deps: Array<string>, }> = await Promise.all(response.dependencies.map(async (dep: TModule) => { const depName = dep.getName(); if (dep.isAsset() || dep.isJSON()) { return {path: dep.path, deps: []}; } const dependencies = await packagerServer.getShallowDependencies({ dev: true, entryFile: dep.path, rootEntryFile: bundleEntry, hot: true, minify: false, platform: platform, recursive: true, bundlingOptions: response.options, }); return { path: dep.path, name: depName, deps: dependencies, }; })); // list with all the dependencies' filenames the bundle entry has const dependenciesCache = response.dependencies.map(dep => dep.path); // map from module name to path const moduleToFilenameCache = Object.create(null); deps.forEach(dep => { /* $FlowFixMe: `name` could be null, but `deps` would be as well. */ moduleToFilenameCache[dep.name] = dep.path; }); // map that indicates the shallow dependency each file included on the // bundle has const shallowDependencies = Object.create(null); deps.forEach(dep => { shallowDependencies[dep.path] = dep.deps; }); // map from module name to the modules' dependencies the bundle entry // has const dependenciesModulesCache = Object.create(null); response.dependencies.forEach(dep => { dependenciesModulesCache[getModuleId(dep)] = dep; }); const inverseDependenciesCache = Object.create(null); const inverseDependencies = getInverseDependencies(response); for (const [module, dependents] of inverseDependencies) { inverseDependenciesCache[getModuleId(module)] = Array.from(dependents).map(getModuleId); } /* $FlowFixMe(>=0.56.0 site=react_native_oss) This comment suppresses an * error found when Flow v0.56 was deployed. To see the error delete this * comment and run Flow. */ /* $FlowFixMe(>=0.56.0 site=react_native_fb,react_native_oss) This comment * suppresses an error found when Flow v0.56 was deployed. To see the error * delete this comment and run Flow. */ return { dependenciesCache, dependenciesModulesCache, shallowDependencies, inverseDependenciesCache, resolutionResponse: response, }; } async function prepareResponse( client: Client, filename: string, ): Promise<?Object> { try { const bundle = await generateBundle(client, filename); if (!bundle || bundle.isEmpty()) { return; } return { type: 'update', body: { modules: bundle.getModulesIdsAndCode(), inverseDependencies: client.inverseDependenciesCache, sourceURLs: bundle.getSourceURLs(), sourceMappingURLs: bundle.getSourceMappingURLs(), }, }; } catch (error) { // send errors to the client instead of killing packager server let body; if (error.type === 'TransformError' || error.type === 'NotFoundError' || error.type === 'UnableToResolveError') { body = { type: error.type, description: error.description, filename: error.filename, lineNumber: error.lineNumber, }; } else { console.error(error.stack || error); body = { type: 'InternalError', description: 'react-packager has encountered an internal error, ' + 'please check your terminal error output for more details', }; } return {type: 'error', body}; } } async function generateBundle( client: Client, filename: string, ): Promise<?HMRBundle> { // If the main file is an asset, do not generate a bundle. const moduleToUpdate = await packagerServer.getModuleForPath(filename); if (moduleToUpdate.isAsset()) { return; } const deps = await packagerServer.getShallowDependencies({ dev: true, minify: false, entryFile: filename, rootEntryFile: client.bundleEntry, hot: true, platform: client.platform, recursive: true, }); // if the file dependencies have change we need to invalidate the // dependencies caches because the list of files we need to send // to the client may have changed const oldDependencies = client.shallowDependencies[filename]; let resolutionResponse; if (arrayEquals(deps, oldDependencies)) { // Need to create a resolution response to pass to the bundler // to process requires after transform. By providing a // specific response we can compute a non recursive one which // is the least we need and improve performance. const response = await packagerServer.getDependencies({ dev: true, entryFile: filename, rootEntryFile: client.bundleEntry, hot: true, minify: false, platform: client.platform, recursive: true, }); resolutionResponse = await response.copy({ dependencies: [moduleToUpdate]}, ); } else { // if there're new dependencies compare the full list of // dependencies we used to have with the one we now have const { dependenciesCache: depsCache, dependenciesModulesCache: depsModulesCache, shallowDependencies: shallowDeps, inverseDependenciesCache: inverseDepsCache, resolutionResponse: myResolutionReponse, } = await getDependencies(client.platform, client.bundleEntry); // build list of modules for which we'll send HMR updates const modulesToUpdate = [moduleToUpdate]; Object.keys(depsModulesCache).forEach(module => { if (!client.dependenciesModulesCache[module]) { modulesToUpdate.push(depsModulesCache[module]); } }); // Need to send modules to the client in an order it can // process them: if a new dependency graph was uncovered // because a new dependency was added, the file that was // changed, which is the root of the dependency tree that // will be sent, needs to be the last module that gets // processed. Reversing the new modules makes sense // because we get them through the resolver which returns // a BFS ordered list. modulesToUpdate.reverse(); // invalidate caches client.dependenciesCache = depsCache; client.dependenciesModulesCache = depsModulesCache; client.shallowDependencies = shallowDeps; client.inverseDependenciesCache = inverseDepsCache; resolutionResponse = await myResolutionReponse.copy({ dependencies: modulesToUpdate, }); } // make sure the file was modified is part of the bundle if (!client.shallowDependencies[filename]) { return; } const httpServerAddress = httpServer.address(); // Sanitize the value from the HTTP server let packagerHost = 'localhost'; if (httpServer.address().address && httpServer.address().address !== '::' && httpServer.address().address !== '') { packagerHost = httpServerAddress.address; } const bundle: HMRBundle = await packagerServer.buildBundleForHMR( { entryFile: client.bundleEntry, platform: client.platform, resolutionResponse, }, packagerHost, httpServerAddress.port, ); return bundle; } function handleFileChange( type: string, filename: string, ): void { clients.forEach( client => sendFileChangeToClient(client, type, filename), ); } async function sendFileChangeToClient( client: Client, type: string, filename: string, ): Promise<mixed> { const blacklisted = blacklist.find( blacklistedPath => filename.indexOf(blacklistedPath) !== -1, ); if (blacklisted) { return; } if (clients.has(client)) { client.ws.send(JSON.stringify({type: 'update-start'})); } if (type !== 'delete') { const response = await prepareResponse(client, filename); if (response && clients.has(client)) { client.ws.send(JSON.stringify(response)); } } if (clients.has(client)) { client.ws.send(JSON.stringify({type: 'update-done'})); } } /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an * error found when Flow v0.54 was deployed. To see the error delete this * comment and run Flow. */ const WebSocketServer = require('ws').Server; const wss = new WebSocketServer({ server: httpServer, path: path, }); wss.on('connection', async ws => { /* $FlowFixMe: url might be null */ const params = querystring.parse(url.parse(ws.upgradeReq.url).query); const { dependenciesCache, dependenciesModulesCache, shallowDependencies, inverseDependenciesCache, } = await getDependencies(params.platform, params.bundleEntry); const client = { ws, platform: params.platform, bundleEntry: params.bundleEntry, dependenciesCache, dependenciesModulesCache, shallowDependencies, inverseDependenciesCache, }; clients.add(client); // If this is the first client connecting, start listening to file changes if (clients.size === 1) { packagerServer.setHMRFileChangeListener(handleFileChange); } client.ws.on('error', e => { console.error('[Hot Module Replacement] Unexpected error', e); disconnect(client); }); client.ws.on('close', () => disconnect(client)); }); } function arrayEquals<T>(arrayA: Array<T>, arrayB: Array<T>): boolean { arrayA = arrayA || []; arrayB = arrayB || []; return ( arrayA.length === arrayB.length && arrayA.every((element, index) => { return element === arrayB[index]; }) ); } module.exports = attachHMRServer;
frantic/react-native
local-cli/server/util/attachHMRServer.js
JavaScript
bsd-3-clause
14,119
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PushNotificationIOS * @flow */ 'use strict'; var Map = require('Map'); var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var RCTPushNotificationManager = require('NativeModules').PushNotificationManager; var invariant = require('invariant'); var _notifHandlers = new Map(); var _initialNotification = RCTPushNotificationManager && RCTPushNotificationManager.initialNotification; var DEVICE_NOTIF_EVENT = 'remoteNotificationReceived'; var NOTIF_REGISTER_EVENT = 'remoteNotificationsRegistered'; /** * Handle push notifications for your app, including permission handling and * icon badge number. * * To get up and running, [configure your notifications with Apple](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringPushNotifications/ConfiguringPushNotifications.html) * and your server-side system. To get an idea, [this is the Parse guide](https://parse.com/tutorials/ios-push-notifications). */ class PushNotificationIOS { _data: Object; _alert: string | Object; _sound: string; _badgeCount: number; /** * Sets the badge number for the app icon on the home screen */ static setApplicationIconBadgeNumber(number: number) { RCTPushNotificationManager.setApplicationIconBadgeNumber(number); } /** * Gets the current badge number for the app icon on the home screen */ static getApplicationIconBadgeNumber(callback: Function) { RCTPushNotificationManager.getApplicationIconBadgeNumber(callback); } /** * Attaches a listener to remote notification events while the app is running * in the foreground or the background. * * Valid events are: * * - `notification` : Fired when a remote notification is received. The * handler will be invoked with an instance of `PushNotificationIOS`. * - `register`: Fired when the user registers for remote notifications. The * handler will be invoked with a hex string representing the deviceToken. */ static addEventListener(type: string, handler: Function) { invariant( type === 'notification' || type === 'register', 'PushNotificationIOS only supports `notification` and `register` events' ); var listener; if (type === 'notification') { listener = RCTDeviceEventEmitter.addListener( DEVICE_NOTIF_EVENT, (notifData) => { handler(new PushNotificationIOS(notifData)); } ); } else if (type === 'register') { listener = RCTDeviceEventEmitter.addListener( NOTIF_REGISTER_EVENT, (registrationInfo) => { handler(registrationInfo.deviceToken); } ); } _notifHandlers.set(handler, listener); } /** * Requests notification permissions from iOS, prompting the user's * dialog box. By default, it will request all notification permissions, but * a subset of these can be requested by passing a map of requested * permissions. * The following permissions are supported: * * - `alert` * - `badge` * - `sound` * * If a map is provided to the method, only the permissions with truthy values * will be requested. */ static requestPermissions(permissions?: { alert?: boolean, badge?: boolean, sound?: boolean }) { var requestedPermissions = {}; if (permissions) { requestedPermissions = { alert: !!permissions.alert, badge: !!permissions.badge, sound: !!permissions.sound }; } else { requestedPermissions = { alert: true, badge: true, sound: true }; } RCTPushNotificationManager.requestPermissions(requestedPermissions); } /** * See what push permissions are currently enabled. `callback` will be * invoked with a `permissions` object: * * - `alert` :boolean * - `badge` :boolean * - `sound` :boolean */ static checkPermissions(callback: Function) { invariant( typeof callback === 'function', 'Must provide a valid callback' ); RCTPushNotificationManager.checkPermissions(callback); } /** * Removes the event listener. Do this in `componentWillUnmount` to prevent * memory leaks */ static removeEventListener(type: string, handler: Function) { invariant( type === 'notification' || type === 'register', 'PushNotificationIOS only supports `notification` and `register` events' ); var listener = _notifHandlers.get(handler); if (!listener) { return; } listener.remove(); _notifHandlers.delete(handler); } /** * An initial notification will be available if the app was cold-launched * from a notification. * * The first caller of `popInitialNotification` will get the initial * notification object, or `null`. Subsequent invocations will return null. */ static popInitialNotification() { var initialNotification = _initialNotification && new PushNotificationIOS(_initialNotification); _initialNotification = null; return initialNotification; } /** * You will never need to instansiate `PushNotificationIOS` yourself. * Listening to the `notification` event and invoking * `popInitialNotification` is sufficient */ constructor(nativeNotif) { this._data = {}; // Extract data from Apple's `aps` dict as defined: // https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html Object.keys(nativeNotif).forEach((notifKey) => { var notifVal = nativeNotif[notifKey]; if (notifKey === 'aps') { this._alert = notifVal.alert; this._sound = notifVal.sound; this._badgeCount = notifVal.badge; } else { this._data[notifKey] = notifVal; } }); } /** * An alias for `getAlert` to get the notification's main message string */ getMessage(): ?string | ?Object { // alias because "alert" is an ambiguous name return this._alert; } /** * Gets the sound string from the `aps` object */ getSound(): ?string { return this._sound; } /** * Gets the notification's main message from the `aps` object */ getAlert(): ?string | ?Object { return this._alert; } /** * Gets the badge count number from the `aps` object */ getBadgeCount(): ?number { return this._badgeCount; } /** * Gets the data object on the notif */ getData(): ?Object { return this._data; } } module.exports = PushNotificationIOS;
JoeStanton/react-native
Libraries/PushNotificationIOS/PushNotificationIOS.js
JavaScript
bsd-3-clause
6,885
/** * Norbert Laposa, 2012/05/13 */ /*revealPrimaryNavigation*/ function revealPrimaryNavigation() { if ($('#primaryNavigation').hasClass('open')) { $('#primaryNavigation').slideUp().removeClass('open'); } else { $('#primaryNavigation').slideDown().addClass('open'); } } $(function() { /** * mobile navigation */ $('#revealNavigationButton a').click(function() { revealPrimaryNavigation(); return false; }); }
1nv4d3r5/onxshop
share/js/reveal_navigation.js
JavaScript
bsd-3-clause
441
/* * Copyright (C) 2012 Google Inc. All rights reserved. * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @param {string} name * @param {string} title * @param {!WebInspector.ResourceCategory} category * @param {boolean} isTextType */ WebInspector.ResourceType = function(name, title, category, isTextType) { this._name = name; this._title = title; this._category = category; this._isTextType = isTextType; } WebInspector.ResourceType.prototype = { /** * @return {string} */ name: function() { return this._name; }, /** * @return {string} */ title: function() { return this._title; }, /** * @return {!WebInspector.ResourceCategory} */ category: function() { return this._category; }, /** * @return {boolean} */ isTextType: function() { return this._isTextType; }, /** * @return {boolean} */ isScript: function() { return this._name === "script" || this._name === "sm-script"; }, /** * @return {boolean} */ hasScripts: function() { return this.isScript() || this.isDocument(); }, /** * @return {boolean} */ isStyleSheet: function() { return this._name === "stylesheet" || this._name === "sm-stylesheet"; }, /** * @return {boolean} */ isDocument: function() { return this._name === "document"; }, /** * @return {boolean} */ isDocumentOrScriptOrStyleSheet: function() { return this.isDocument() || this.isScript() || this.isStyleSheet(); }, /** * @return {boolean} */ isFromSourceMap: function() { return this._name.startsWith("sm-"); }, /** * @override * @return {string} */ toString: function() { return this._name; }, /** * @return {string} */ canonicalMimeType: function() { if (this.isDocument()) return "text/html"; if (this.isScript()) return "text/javascript"; if (this.isStyleSheet()) return "text/css"; return ""; } } /** * @constructor * @param {string} title * @param {string} shortTitle */ WebInspector.ResourceCategory = function(title, shortTitle) { this.title = title; this.shortTitle = shortTitle; } WebInspector.resourceCategories = { XHR: new WebInspector.ResourceCategory("XHR and Fetch", "XHR"), Script: new WebInspector.ResourceCategory("Scripts", "JS"), Stylesheet: new WebInspector.ResourceCategory("Stylesheets", "CSS"), Image: new WebInspector.ResourceCategory("Images", "Img"), Media: new WebInspector.ResourceCategory("Media", "Media"), Font: new WebInspector.ResourceCategory("Fonts", "Font"), Document: new WebInspector.ResourceCategory("Documents", "Doc"), WebSocket: new WebInspector.ResourceCategory("WebSockets", "WS"), Manifest: new WebInspector.ResourceCategory("Manifest", "Manifest"), Other: new WebInspector.ResourceCategory("Other", "Other") } /** * Keep these in sync with WebCore::InspectorPageAgent::resourceTypeJson * @enum {!WebInspector.ResourceType} */ WebInspector.resourceTypes = { XHR: new WebInspector.ResourceType("xhr", "XHR", WebInspector.resourceCategories.XHR, true), Fetch: new WebInspector.ResourceType("fetch", "Fetch", WebInspector.resourceCategories.XHR, true), EventSource: new WebInspector.ResourceType("eventsource", "EventSource", WebInspector.resourceCategories.XHR, true), Script: new WebInspector.ResourceType("script", "Script", WebInspector.resourceCategories.Script, true), Stylesheet: new WebInspector.ResourceType("stylesheet", "Stylesheet", WebInspector.resourceCategories.Stylesheet, true), Image: new WebInspector.ResourceType("image", "Image", WebInspector.resourceCategories.Image, false), Media: new WebInspector.ResourceType("media", "Media", WebInspector.resourceCategories.Media, false), Font: new WebInspector.ResourceType("font", "Font", WebInspector.resourceCategories.Font, false), Document: new WebInspector.ResourceType("document", "Document", WebInspector.resourceCategories.Document, true), TextTrack: new WebInspector.ResourceType("texttrack", "TextTrack", WebInspector.resourceCategories.Other, true), WebSocket: new WebInspector.ResourceType("websocket", "WebSocket", WebInspector.resourceCategories.WebSocket, false), Other: new WebInspector.ResourceType("other", "Other", WebInspector.resourceCategories.Other, false), SourceMapScript: new WebInspector.ResourceType("sm-script", "Script", WebInspector.resourceCategories.Script, false), SourceMapStyleSheet: new WebInspector.ResourceType("sm-stylesheet", "Stylesheet", WebInspector.resourceCategories.Stylesheet, false), Manifest: new WebInspector.ResourceType("manifest", "Manifest", WebInspector.resourceCategories.Manifest, true), } /** * @param {string} url * @return {string} */ WebInspector.ResourceType.mimeFromURL = function(url) { var name = WebInspector.TextUtils.fileName(url); if (WebInspector.ResourceType.mimeTypeByName[name]) { return WebInspector.ResourceType.mimeTypeByName[name]; } var ext = WebInspector.TextUtils.extension(url).toLowerCase(); return WebInspector.ResourceType.mimeTypeByExtension[ext]; } WebInspector.ResourceType.mimeTypeByName = { // CoffeeScript "Cakefile": "text/x-coffeescript" } WebInspector.ResourceType.mimeTypeByExtension = { // Web extensions "js": "text/javascript", "css": "text/css", "html": "text/html", "htm": "text/html", "xml": "application/xml", "xsl": "application/xml", // HTML Embedded Scripts: ASP, JSP "asp": "application/x-aspx", "aspx": "application/x-aspx", "jsp": "application/x-jsp", // C/C++ "c": "text/x-c++src", "cc": "text/x-c++src", "cpp": "text/x-c++src", "h": "text/x-c++src", "m": "text/x-c++src", "mm": "text/x-c++src", // CoffeeScript "coffee": "text/x-coffeescript", // Dart "dart": "text/javascript", // TypeScript "ts": "text/typescript", "tsx": "text/typescript", // JSON "json": "application/json", "gyp": "application/json", "gypi": "application/json", // C# "cs": "text/x-csharp", // Java "java": "text/x-java", // Less "less": "text/x-less", // PHP "php": "text/x-php", "phtml": "application/x-httpd-php", // Python "py": "text/x-python", // Shell "sh": "text/x-sh", // SCSS "scss": "text/x-scss", // Video Text Tracks. "vtt": "text/vtt", // LiveScript "ls": "text/x-livescript", // ClojureScript "cljs": "text/x-clojure", "cljc": "text/x-clojure", "cljx": "text/x-clojure", // Stylus "styl": "text/x-styl", // JSX "jsx": "text/jsx", // Image "jpeg": "image/jpeg", "jpg": "image/jpeg", "svg": "image/svg", "gif": "image/gif", "webp": "image/webp", "png": "image/png", "ico": "image/ico", "tiff": "image/tiff", "tif": "image/tif", "bmp": "image/bmp", // Font "ttf": "font/opentype", "otf": "font/opentype", "ttc": "font/opentype", "woff": "application/font-woff" }
was4444/chromium.src
third_party/WebKit/Source/devtools/front_end/common/ResourceType.js
JavaScript
bsd-3-clause
8,909
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A class that can auto-select aircraft based on a set of criteria. */ (function(VRS, $, undefined) { //region Global settings VRS.globalOptions = VRS.globalOptions || {}; VRS.globalOptions.aircraftAutoSelectEnabled = VRS.globalOptions.aircraftAutoSelectEnabled !== undefined ? VRS.globalOptions.aircraftAutoSelectEnabled : true; // True if auto-select is enabled by default. VRS.globalOptions.aircraftAutoSelectClosest = VRS.globalOptions.aircraftAutoSelectClosest !== undefined ? VRS.globalOptions.aircraftAutoSelectClosest : true; // True if the closest matching aircraft should be auto-selected, false if the furthest matching aircraft should be auto-selected. VRS.globalOptions.aircraftAutoSelectOffRadarAction = VRS.globalOptions.aircraftAutoSelectOffRadarAction || VRS.OffRadarAction.EnableAutoSelect; // What to do when an aircraft goes out of range of the radar. VRS.globalOptions.aircraftAutoSelectFilters = VRS.globalOptions.aircraftAutoSelectFilters || []; // The list of filters that auto-select starts off with. VRS.globalOptions.aircraftAutoSelectFiltersLimit = VRS.globalOptions.aircraftAutoSelectFiltersLimit !== undefined ? VRS.globalOptions.aircraftAutoSelectFiltersLimit : 2; // The maximum number of auto-select filters that we're going to allow. //endregion //region AircraftAutoSelect /** * A class that can auto-select aircraft on each refresh. * @param {VRS.AircraftList} aircraftList * @param {string=} name * @constructor */ VRS.AircraftAutoSelect = function(aircraftList, name) { //region -- Fields var that = this; var _AircraftList = aircraftList; var _Dispatcher = new VRS.EventHandler({ name: 'VRS.AircraftAutoSelect' }); var _Events = { enabledChanged: 'enabledChanged' }; /** * @type {VRS.Aircraft} * The last aircraft selected by the object. */ var _LastAircraftSelected; //endregion //region -- Events subscribed, dispose var _AircraftListUpdatedHook = _AircraftList.hookUpdated(aircraftListUpdated, this); var _SelectedAircraftChangedHook = _AircraftList.hookSelectedAircraftChanged(selectedAircraftChanged, this); /** * Releases all of the resources held by the object. */ this.dispose = function() { if(_AircraftListUpdatedHook) _AircraftList.unhook(_AircraftListUpdatedHook); if(_SelectedAircraftChangedHook) _AircraftList.unhook(_SelectedAircraftChangedHook); _AircraftListUpdatedHook = _SelectedAircraftChangedHook = null; }; //endregion //region -- Properties var _Name = name || 'default'; /** * Gets the name of the object. This is used when storing and loading settings. * @returns {string} */ this.getName = function() { return _Name; }; /** * Determines whether the object is actively setting selected aircraft. * @type {bool} * @private */ var _Enabled = VRS.globalOptions.aircraftAutoSelectEnabled; /** * Gets a value indicating whether the object is actively setting the selected aircraft. * @returns {bool} */ this.getEnabled = function() { return _Enabled; }; /** * Sets a value indicating whether the object is to auto-select aircraft or not. * @param {bool} value */ this.setEnabled = function(value) { if(_Enabled !== value) { _Enabled = value; _Dispatcher.raise(_Events.enabledChanged); if(_Enabled && _AircraftList) { var closestAircraft = that.closestAircraft(_AircraftList); if(closestAircraft && closestAircraft !== _AircraftList.getSelectedAircraft()) { _AircraftList.setSelectedAircraft(closestAircraft, false); } } } }; /** * True if the closest aircraft is to be selected, false otherwise. * @type {bool} * @private */ var _SelectClosest = VRS.globalOptions.aircraftAutoSelectClosest; /** * Gets a value indicating that the closest aircraft is to be selected. * @returns {boolean} */ this.getSelectClosest = function() { return _SelectClosest; }; /** * Sets a value indicating that the closest aircraft is to be selected. * @param value */ this.setSelectClosest = function(value) { _SelectClosest = value; }; /** @type {VRS.OffRadarAction} @private */ var _OffRadarAction = VRS.globalOptions.aircraftAutoSelectOffRadarAction; /** Gets a value that describes what to do when an aircraft goes off the radar. * @type {VRS.OffRadarAction} */ this.getOffRadarAction = function() { return _OffRadarAction; }; this.setOffRadarAction = function(/** VRS.OffRadarAction */ value) { _OffRadarAction = value; }; /** * An array of the different aircraft filters to use when determining which aircraft to auto-select. * @type {VRS.AircraftFilter[]} * @private */ var _Filters = VRS.globalOptions.aircraftAutoSelectFilters; //noinspection JSUnusedGlobalSymbols /** * Returns a clone of the filter at the specified index. * @param {number} index * @returns {VRS.AircraftFilter} */ this.getFilter = function(index) { return /** @type {VRS.AircraftFilter} */ _Filters[index].clone(); }; //noinspection JSUnusedGlobalSymbols /** * Sets the property filter at the specified index. * @param {number} index * @param {VRS.AircraftFilter} aircraftFilter */ this.setFilter = function(index, aircraftFilter) { if(_Filters.length < VRS.globalOptions.aircraftListFiltersLimit) { var existing = index < _Filters.length ? _Filters[index] : null; if(existing && !existing.equals(aircraftFilter)) _Filters[index] = aircraftFilter; } }; //endregion //region -- Events exposed /** * Raised after the Enabled property value has changed. * @param {function} callback * @param {object} forceThis * @returns {object} */ this.hookEnabledChanged = function(callback, forceThis) { return _Dispatcher.hook(_Events.enabledChanged, callback, forceThis); }; /** * Unhooks an event hooked on this object. * @param {object} hookResult * @returns {*} */ this.unhook = function(hookResult) { return _Dispatcher.unhook(hookResult); }; //endregion //region -- State persistence - saveState, loadState, applyState, loadAndApplyState /** * Saves the current state of the object. */ this.saveState = function() { VRS.configStorage.save(persistenceKey(), createSettings()); }; /** * Returns the saved state of the object. * @returns {VRS_STATE_AIRCRAFTAUTOSELECT} */ this.loadState = function() { var savedSettings = VRS.configStorage.load(persistenceKey(), {}); var result = $.extend(createSettings(), savedSettings); result.filters = VRS.aircraftFilterHelper.buildValidFiltersList(result.filters, VRS.globalOptions.aircraftAutoSelectFiltersLimit); return result; }; /** * Applies a saved state to the object. * @param {VRS_STATE_AIRCRAFTAUTOSELECT} settings */ this.applyState = function(settings) { that.setEnabled(settings.enabled); that.setSelectClosest(settings.selectClosest); that.setOffRadarAction(settings.offRadarAction); _Filters = []; $.each(settings.filters, function(idx, serialisedFilter) { var aircraftFilter = VRS.aircraftFilterHelper.createFilter(serialisedFilter.property); aircraftFilter.applySerialisedObject(serialisedFilter); _Filters.push(aircraftFilter); }); }; /** * Loads and applies the saved state to the object. */ this.loadAndApplyState = function() { that.applyState(that.loadState()); }; /** * Returns the key under which the object's settings are saved. * @returns {string} */ function persistenceKey() { return 'vrsAircraftAutoSelect-' + _Name; } /** * Creates the state object. * @returns {VRS_STATE_AIRCRAFTAUTOSELECT} */ function createSettings() { var filters = VRS.aircraftFilterHelper.serialiseFiltersList(_Filters); return { enabled: _Enabled, selectClosest: _SelectClosest, offRadarAction: _OffRadarAction, filters: filters }; } //endregion //region -- createOptionPane /** * Creates the option pane that allows configuration of the object. * @param {number} displayOrder * @returns {VRS.OptionPane[]} */ this.createOptionPane = function(displayOrder) { var result = []; var pane = new VRS.OptionPane({ name: 'vrsAircraftAutoSelectPane1', titleKey: 'PaneAutoSelect', displayOrder: displayOrder }); result.push(pane); pane.addField(new VRS.OptionFieldCheckBox({ name: 'enable', labelKey: 'AutoSelectAircraft', getValue: that.getEnabled, setValue: that.setEnabled, saveState: that.saveState, hookChanged: that.hookEnabledChanged, unhook: that.unhook })); pane.addField(new VRS.OptionFieldRadioButton({ name: 'closest', labelKey: 'Select', getValue: that.getSelectClosest, setValue: that.setSelectClosest, saveState: that.saveState, values: [ new VRS.ValueText({ value: true, textKey: 'ClosestToCurrentLocation' }), new VRS.ValueText({ value: false, textKey: 'FurthestFromCurrentLocation' }) ] })); if(VRS.aircraftListFiltersLimit !== 0) { var panesTypeSettings = VRS.aircraftFilterHelper.addConfigureFiltersListToPane({ pane: pane, filters: _Filters, saveState: function() { that.saveState(); }, maxFilters: VRS.globalOptions.aircraftAutoSelectFiltersLimit, allowableProperties: [ VRS.AircraftFilterProperty.Altitude, VRS.AircraftFilterProperty.Distance ], addFilter: function(newComparer, paneField) { var aircraftFilter = that.addFilter(newComparer); paneField.addPane(aircraftFilter.createOptionPane(that.saveState)); that.saveState(); }, addFilterButtonLabel: 'AddCondition' }); panesTypeSettings.hookPaneRemoved(filterPaneRemoved, this); } pane = new VRS.OptionPane({ name: 'vrsAircraftAutoSelectPane2', displayOrder: displayOrder + 1 }); result.push(pane); pane.addField(new VRS.OptionFieldLabel({ name: 'offRadarActionLabel', labelKey: 'OffRadarAction' })); pane.addField(new VRS.OptionFieldRadioButton({ name: 'offRadarAction', getValue: that.getOffRadarAction, setValue: that.setOffRadarAction, saveState: that.saveState, values: [ new VRS.ValueText({ value: VRS.OffRadarAction.WaitForReturn, textKey: 'OffRadarActionWait' }), new VRS.ValueText({ value: VRS.OffRadarAction.EnableAutoSelect, textKey: 'OffRadarActionEnableAutoSelect' }), new VRS.ValueText({ value: VRS.OffRadarAction.Nothing, textKey: 'OffRadarActionNothing' }) ] })); return result; }; //endregion //region --addFilter, comparerPaneRemoved, removeFilterAt /** * Adds a new filter to the auto-select settings. * @param {VRS.AircraftFilter|VRS.AircraftFilterProperty} filterOrFilterProperty * @returns {VRS.AircraftFilter} */ this.addFilter = function(filterOrFilterProperty) { var filter = filterOrFilterProperty; if(!(filter instanceof VRS.AircraftFilter)) { filter = VRS.aircraftFilterHelper.createFilter(filterOrFilterProperty); } _Filters.push(filter); return filter; }; //noinspection JSUnusedLocalSymbols /** * Removes an existing filter from the auto-select settings. * @param {VRS.OptionPane} [pane] Unused. * @param {number} index */ function filterPaneRemoved(pane, index) { that.removeFilterAt(index); that.saveState(); } /** * Removes an existing filter from the auto-select settings. * @param {number} index */ this.removeFilterAt = function(index) { _Filters.splice(index, 1); }; //endregion //region -- closestAircraft, aircraftListUpdated, selectedAircraftChanged /** * Returns the closest aircraft from the aircraft list passed across. * @param {VRS.AircraftList} aircraftList * @returns {VRS.Aircraft} */ this.closestAircraft = function(aircraftList) { var result = null; if(this.getEnabled()) { var useClosest = this.getSelectClosest(); var useFilters = _Filters.length > 0; var selectedDistance = useClosest ? Number.MAX_VALUE : Number.MIN_VALUE; aircraftList.foreachAircraft(function(aircraft) { if(aircraft.distanceFromHereKm.val !== undefined) { var isCandidate = useClosest ? aircraft.distanceFromHereKm.val < selectedDistance : aircraft.distanceFromHereKm.val > selectedDistance; if(isCandidate) { if(useFilters && !VRS.aircraftFilterHelper.aircraftPasses(aircraft, _Filters, {})) isCandidate = false; if(isCandidate) { result = aircraft; selectedDistance = aircraft.distanceFromHereKm.val; } } } }); } return result; }; //noinspection JSUnusedLocalSymbols /** * Called when the aircraft list is updated. * @param {VRS.AircraftCollection} newAircraft * @param {VRS.AircraftCollection} offRadar */ function aircraftListUpdated(newAircraft, offRadar) { var selectedAircraft = _AircraftList.getSelectedAircraft(); var autoSelectAircraft = that.closestAircraft(_AircraftList); var useAutoSelectedAircraft = function() { if(autoSelectAircraft !== selectedAircraft) { _AircraftList.setSelectedAircraft(autoSelectAircraft, false); selectedAircraft = autoSelectAircraft; } }; if(autoSelectAircraft) { useAutoSelectedAircraft(); } else if(selectedAircraft) { var isOffRadar = offRadar.findAircraftById(selectedAircraft.id); if(isOffRadar) { switch(that.getOffRadarAction()) { case VRS.OffRadarAction.Nothing: break; case VRS.OffRadarAction.EnableAutoSelect: if(!that.getEnabled()) { that.setEnabled(true); autoSelectAircraft = that.closestAircraft(_AircraftList); if(autoSelectAircraft) useAutoSelectedAircraft(); } break; case VRS.OffRadarAction.WaitForReturn: _AircraftList.setSelectedAircraft(undefined, false); break; } } } if(!selectedAircraft && _LastAircraftSelected) { var reselectAircraft = newAircraft.findAircraftById(_LastAircraftSelected.id); if(reselectAircraft) _AircraftList.setSelectedAircraft(reselectAircraft, false); } } /** * Called when the aircraft list changes the selected aircraft. //* @param {VRS.Aircraft} oldSelectedAircraft */ function selectedAircraftChanged() { var selectedAircraft = _AircraftList.getSelectedAircraft(); if(selectedAircraft) _LastAircraftSelected = selectedAircraft; if(_AircraftList.getWasAircraftSelectedByUser()) that.setEnabled(false); } //endregion }; //endregion }(window.VRS = window.VRS || {}, jQuery));
VincentFortuneDeng/VirtualRadarSource2.0.2
VirtualRadar.WebSite/Site/Web/script/vrs/aircraftAutoSelect.js
JavaScript
bsd-3-clause
19,911
//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com //** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/ //** Menu created: Nov 12, 2008 //** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth //** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items. //** May 1st, 09" (v1.3): //** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v' //** 2) In IE6, shadows are now always disabled //** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired. //** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below var ddsmoothmenu={ //Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs): arrowimages: {down:['downarrowclass', 'images/down.gif', 10], right:['rightarrowclass', 'images/right.gif']}, transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds shadow: {enable:true, offsetx:4, offsety:5}, //enable shadow? showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively ///////Stop configuring beyond here/////////////////////////// detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc) detectie6: document.all && !window.XMLHttpRequest, getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs var $menucontainer=$('#'+setting.contentsource[0]) //reference empty div on page that will hold menu $menucontainer.html("Loading Menu...") $.ajax({ url: setting.contentsource[1], //path to external menu file async: true, error:function(ajaxrequest){ $menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText) }, success:function(content){ $menucontainer.html(content) ddsmoothmenu.buildmenu($, setting) } }) }, buildmenu:function($, setting){ var smoothmenu=ddsmoothmenu var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL $mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu" var $headers=$mainmenu.find("ul").parent() $headers.hover( function(e){ $(this).children('a:eq(0)').addClass('selected') }, function(e){ $(this).children('a:eq(0)').removeClass('selected') } ) $headers.each(function(i){ //loop through each LI header var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header var $subul=$(this).find('ul:eq(0)').css({display:'block'}) $subul.data('timers', {}) this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()} this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header? $subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0}) $curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images '<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1]) +'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0]) + '" style="border:0;" />' ) if (smoothmenu.shadow.enable){ this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets if (this.istopheader) $parentshadow=$(document.body) else{ var $parentLi=$curobj.parents("li:eq(0)") $parentshadow=$parentLi.get(0).$shadow } this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'}) //insert shadow DIV and set it to parent node for the next shadow div } $curobj.hover( function(e){ var $targetul=$subul //reference UL to reveal var header=$curobj.get(0) //reference header LI as DOM object clearTimeout($targetul.data('timers').hidetimer) $targetul.data('timers').showtimer=setTimeout(function(){ header._offsets={left:$curobj.offset().left, top:$curobj.offset().top} var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent if ($targetul.queue().length<=1){ //if 1 or less queued animations $targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime) if (smoothmenu.shadow.enable){ var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full header.$shadow.css({opacity:1}) } header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime) } } }, ddsmoothmenu.showhidedelay.showdelay) }, function(e){ var $targetul=$subul var header=$curobj.get(0) clearTimeout($targetul.data('timers').showtimer) $targetul.data('timers').hidetimer=setTimeout(function(){ $targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime) if (smoothmenu.shadow.enable){ if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them header.$shadow.children('div:eq(0)').css({opacity:0}) } header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime) } }, ddsmoothmenu.showhidedelay.hidedelay) } ) //end hover }) //end $headers.each() $mainmenu.find("ul").css({display:'none', visibility:'visible'}) }, init:function(setting){ if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set? var mainmenuid='#'+setting.mainmenuid var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid document.write('<style type="text/css">\n' +mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n' +mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n' +'</style>') } this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow jQuery(document).ready(function($){ //ajax menu? if (typeof setting.contentsource=="object"){ //if external ajax menu ddsmoothmenu.getajaxmenu($, setting) } else{ //else if markup menu ddsmoothmenu.buildmenu($, setting) } }) } } //end ddsmoothmenu variable
liqi328/rjrepaircompany
static/scripts/ddsmoothmenu.js
JavaScript
bsd-3-clause
7,627
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (module) { function Bridge() { } var eventHandlers = {}; Bridge.prototype.handleMessage = function( type, payload ) { var that = this; if ( eventHandlers.hasOwnProperty( type ) ) { eventHandlers[type].forEach( function( callback ) { callback.call( that, payload ); } ); } }; Bridge.prototype.registerListener = function( messageType, callback ) { if ( eventHandlers.hasOwnProperty( messageType ) ) { eventHandlers[messageType].push( callback ); } else { eventHandlers[messageType] = [ callback ]; } }; Bridge.prototype.sendMessage = function( messageType, payload ) { setTimeout(function() { // See: https://phabricator.wikimedia.org/T96822 and http://stackoverflow.com/a/9782220/135557 var messagePack = { type: messageType, payload: payload }; var url = "x-wikipedia-bridge:" + encodeURIComponent( JSON.stringify( messagePack ) ); // quick iframe version based on http://stackoverflow.com/a/6508343/82439 // fixme can this be an XHR instead? check Cordova current state var iframe = document.createElement('iframe'); iframe.setAttribute("src", url); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; }, 0); }; module.exports = new Bridge(); })(module); },{}],2:[function(require,module,exports){ // Created by Monte Hurd on 12/28/13. // Used by methods in "UIWebView+ElementLocation.h" category. // Copyright (c) 2013 Wikimedia Foundation. Provided under MIT-style license; please copy and modify! function stringEndsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } function getZoomLevel() { // From: http://stackoverflow.com/a/5078596/135557 var deviceWidth = (Math.abs(window.orientation) === 90) ? screen.height : screen.width; var zoom = deviceWidth / window.innerWidth; return zoom; } exports.getImageWithSrc = function(src) { var images = document.getElementsByTagName('img'); for (var i = 0; i < images.length; ++i) { if (stringEndsWith(images[i].src, src)) { return images[i]; } } return null; }; exports.getElementRect = function(element) { var rect = element.getBoundingClientRect(); var zoom = getZoomLevel(); var zoomedRect = { top: rect.top * zoom, left: rect.left * zoom, width: rect.width * zoom, height: rect.height * zoom }; return zoomedRect; }; exports.getElementRectAsJson = function(element) { return JSON.stringify(this.getElementRect(element)); }; exports.getIndexOfFirstOnScreenElementWithTopGreaterThanY = function(elementPrefix, elementCount){ for (var i = 0; i < elementCount; ++i) { var div = document.getElementById(elementPrefix + i); if (div === null) { continue; } var rect = this.getElementRect(div); if ( (rect.top >= 0) || ((rect.top + rect.height) >= 0)) { return i; } } return -1; }; },{}],3:[function(require,module,exports){ (function () { var bridge = require("./bridge"); var transformer = require("./transformer"); var refs = require("./refs"); var issuesAndDisambig = require("./transforms/collapsePageIssuesAndDisambig"); var utilities = require("./utilities"); // DOMContentLoaded fires before window.onload! That's good! // See: http://stackoverflow.com/a/3698214/135557 document.addEventListener("DOMContentLoaded", function() { transformer.transform( "moveFirstGoodParagraphUp", document ); transformer.transform( "hideRedlinks", document ); transformer.transform( "addImageOverflowXContainers", document ); // Needs to happen before "widenImages" transform. transformer.transform( "widenImages", document ); transformer.transform( "hideTables", document ); transformer.transform( "collapsePageIssuesAndDisambig", document.getElementById( "section_heading_and_content_block_0" ) ); bridge.sendMessage( "DOMContentLoaded", {} ); }); bridge.registerListener( "setLanguage", function( payload ){ var html = document.querySelector( "html" ); html.lang = payload.lang; html.dir = payload.dir; html.classList.add( 'content-' + payload.dir ); html.classList.add( 'ui-' + payload.uidir ); document.querySelector('base').href = 'https://' + payload.lang + '.wikipedia.org/'; } ); bridge.registerListener( "setPageProtected", function() { document.getElementsByTagName( "html" )[0].classList.add( "page-protected" ); } ); document.onclick = function() { // Reminder: resist adding any click/tap handling here - they can // "fight" with items in the touchEndedWithoutDragging handler. // Add click/tap handling to touchEndedWithoutDragging instead. event.preventDefault(); // <-- Do not remove! }; // track where initial touches start var touchDownY = 0.0; document.addEventListener( "touchstart", function (event) { touchDownY = parseInt(event.changedTouches[0].clientY); }, false); function handleTouchEnded(event){ var touchobj = event.changedTouches[0]; var touchEndY = parseInt(touchobj.clientY); if (((touchDownY - touchEndY) === 0) && (event.changedTouches.length === 1)) { // None of our tap events should fire if the user dragged vertically. touchEndedWithoutDragging(event); } } function touchEndedWithoutDragging(event){ /* there are certain elements which don't have an <a> ancestor, so if we fail to find it, specify the event's target instead */ var didSendMessage = maybeSendMessageForTarget(event, utilities.findClosest(event.target, 'A') || event.target); var hasSelectedText = window.getSelection().rangeCount > 0; if (!didSendMessage && !hasSelectedText) { // Do NOT prevent default behavior -- this is needed to for instance // handle deselection of text. bridge.sendMessage('nonAnchorTouchEndedWithoutDragging', { id: event.target.getAttribute( "id" ), tagName: event.target.tagName }); } } /** * Attempts to send a bridge message which corresponds to `hrefTarget`, based on various attributes. * @return `true` if a message was sent, otherwise `false`. */ function maybeSendMessageForTarget(event, hrefTarget){ if (!hrefTarget) { return false; } var href = hrefTarget.getAttribute( "href" ); var hrefClass = hrefTarget.getAttribute('class'); if (href && refs.isReference(href)) { // Handle reference links with a popup view instead of scrolling about! refs.sendNearbyReferences( hrefTarget ); } else if (href && href[0] === "#") { var targetId = href.slice(1); if ( "issues" === targetId ) { var issuesPayload = issuesAndDisambig.issuesClicked( hrefTarget ); bridge.sendMessage( 'issuesClicked', issuesPayload ); } else if ( "disambig" === targetId ) { var disambigPayload = issuesAndDisambig.disambigClicked( hrefTarget ); bridge.sendMessage( 'disambigClicked', disambigPayload ); } else if ( "issues_container_close_button" === targetId ) { issuesAndDisambig.closeClicked(); } else { // If it is a link to an anchor in the current page, use existing link handling // so top floating native header height can be taken into account by the regular // fragment handling logic. bridge.sendMessage( 'linkClicked', { 'href': href }); } } else if (typeof hrefClass === 'string' && hrefClass.indexOf('image') !== -1) { var url = event.target.getAttribute('src'); bridge.sendMessage('imageClicked', { 'url': url }); } else if (href) { bridge.sendMessage( 'linkClicked', { 'href': href }); } else { return false; } return true; } document.addEventListener("touchend", handleTouchEnded, false); })(); },{"./bridge":1,"./refs":5,"./transformer":8,"./transforms/collapsePageIssuesAndDisambig":11,"./utilities":16}],4:[function(require,module,exports){ var bridge = require("./bridge"); var elementLocation = require("./elementLocation"); window.bridge = bridge; window.elementLocation = elementLocation; },{"./bridge":1,"./elementLocation":2}],5:[function(require,module,exports){ var bridge = require("./bridge"); function isReference( href ) { return ( href.slice( 0, 10 ) === "#cite_note" ); } function goDown( element ) { return element.getElementsByTagName( "A" )[0]; } /** * Skip over whitespace but not other elements */ function skipOverWhitespace( skipFunc ) { return (function(element) { do { element = skipFunc( element ); if (element && element.nodeType == Node.TEXT_NODE) { if (element.textContent.match(/^\s+$/)) { // Ignore empty whitespace continue; } else { break; } } else { // found an element or ran out break; } } while (true); return element; }); } var goLeft = skipOverWhitespace( function( element ) { return element.previousSibling; }); var goRight = skipOverWhitespace( function( element ) { return element.nextSibling; }); function hasReferenceLink( element ) { try { return isReference( goDown( element ).getAttribute( "href" ) ); } catch (e) { return false; } } function collectRefText( sourceNode ) { var href = sourceNode.getAttribute( "href" ); var targetId = href.slice(1); var targetNode = document.getElementById( targetId ); if ( targetNode === null ) { /*global console */ console.log("reference target not found: " + targetId); return ""; } // preferably without the back link var refTexts = targetNode.getElementsByClassName( "reference-text" ); if ( refTexts.length > 0 ) { targetNode = refTexts[0]; } return targetNode.innerHTML; } function collectRefLink( sourceNode ) { var node = sourceNode; while (!node.classList || !node.classList.contains('reference')) { node = node.parentNode; if (!node) { return ''; } } return node.id; } function sendNearbyReferences( sourceNode ) { var refsIndex = 0; var refs = []; var linkId = []; var linkText = []; var curNode = sourceNode; // handle clicked ref: refs.push( collectRefText( curNode ) ); linkId.push( collectRefLink( curNode ) ); linkText.push( curNode.textContent ); // go left: curNode = sourceNode.parentElement; while ( hasReferenceLink( goLeft( curNode ) ) ) { refsIndex += 1; curNode = goLeft( curNode ); refs.unshift( collectRefText( goDown ( curNode ) ) ); linkId.unshift( collectRefLink( curNode ) ); linkText.unshift( curNode.textContent ); } // go right: curNode = sourceNode.parentElement; while ( hasReferenceLink( goRight( curNode ) ) ) { curNode = goRight( curNode ); refs.push( collectRefText( goDown ( curNode ) ) ); linkId.push( collectRefLink( curNode ) ); linkText.push( curNode.textContent ); } // Special handling for references bridge.sendMessage( 'referenceClicked', { "refs": refs, "refsIndex": refsIndex, "linkId": linkId, "linkText": linkText } ); } exports.isReference = isReference; exports.sendNearbyReferences = sendNearbyReferences; },{"./bridge":1}],6:[function(require,module,exports){ (function (global){ var sectionHeaders = require("./sectionHeaders"); function scrollDownByTopMostSectionHeaderHeightIfNecessary(fragmentId){ var header = sectionHeaders.getSectionHeaderForId(fragmentId); if (header.id != fragmentId){ window.scrollBy(0, -header.getBoundingClientRect().height); } } function scrollToFragment(fragmentId){ location.hash = ''; location.hash = fragmentId; /* Setting location.hash scrolls the element to very top of screen. If this element is not a section header it will be positioned *under* the top static section header, so shift it down by the static section header height in these cases. */ scrollDownByTopMostSectionHeaderHeightIfNecessary(fragmentId); } global.scrollToFragment = scrollToFragment; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./sectionHeaders":7}],7:[function(require,module,exports){ (function (global){ var utilities = require("./utilities"); var querySelectorForHeadingsToNativize = 'h1.section_heading, h2.section_heading, h3.section_heading'; function getSectionHeadersArray(){ var nodeList = document.querySelectorAll(querySelectorForHeadingsToNativize); var nodeArray = Array.prototype.slice.call(nodeList); nodeArray = nodeArray.map(function(n){ return { anchor:n.getAttribute('id'), sectionId:n.getAttribute('sectionId'), text:n.textContent }; }); return nodeArray; } function getSectionHeaderLocationsArray(){ var nodeList = document.querySelectorAll(querySelectorForHeadingsToNativize); var nodeArray = Array.prototype.slice.call(nodeList); nodeArray = nodeArray.map(function(n){ return n.getBoundingClientRect().top; }); return nodeArray; } function getSectionHeaderForId(id){ var sectionHeadingParent = utilities.findClosest(document.getElementById(id), 'div[id^="section_heading_and_content_block_"]'); var sectionHeading = sectionHeadingParent.querySelector(querySelectorForHeadingsToNativize); return sectionHeading; } exports.getSectionHeaderForId = getSectionHeaderForId; global.getSectionHeadersArray = getSectionHeadersArray; global.getSectionHeaderLocationsArray = getSectionHeaderLocationsArray; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./utilities":16}],8:[function(require,module,exports){ function Transformer() { } var transforms = {}; Transformer.prototype.register = function( transform, fun ) { if ( transform in transforms ) { transforms[transform].push( fun ); } else { transforms[transform] = [ fun ]; } }; Transformer.prototype.transform = function( transform, element ) { var functions = transforms[transform]; for ( var i = 0; i < functions.length; i++ ) { functions[i](element); } }; module.exports = new Transformer(); },{}],9:[function(require,module,exports){ require("./transforms/collapseTables"); require("./transforms/relocateFirstParagraph"); require("./transforms/hideRedLinks"); require("./transforms/addImageOverflowContainers"); require("./transforms/collapsePageIssuesAndDisambig"); },{"./transforms/addImageOverflowContainers":10,"./transforms/collapsePageIssuesAndDisambig":11,"./transforms/collapseTables":12,"./transforms/hideRedLinks":13,"./transforms/relocateFirstParagraph":14}],10:[function(require,module,exports){ var transformer = require("../transformer"); var utilities = require("../utilities"); function shouldAddImageOverflowXContainer(image) { if ((image.width > (window.screen.width * 0.8)) && !utilities.isNestedInTable(image)){ return true; }else{ return false; } } function addImageOverflowXContainer(image, ancestor) { image.setAttribute('hasOverflowXContainer', 'true'); // So "widenImages" transform knows instantly not to widen this one. var div = document.createElement( 'div' ); div.className = 'image_overflow_x_container'; ancestor.parentElement.insertBefore( div, ancestor ); div.appendChild( ancestor ); } function maybeAddImageOverflowXContainer() { var image = this; if (shouldAddImageOverflowXContainer(image)){ var ancestor = utilities.firstAncestorWithMultipleChildren (image); if(ancestor){ addImageOverflowXContainer(image, ancestor); } } } transformer.register( "addImageOverflowXContainers", function( content ) { // Wrap wide images in a <div style="overflow-x:auto">...</div> so they can scroll // side to side if needed without causing the entire section to scroll side to side. var images = content.getElementsByTagName('img'); for (var i = 0; i < images.length; ++i) { // Load event used so images w/o style or inline width/height // attributes can still have their size determined reliably. images[i].addEventListener('load', maybeAddImageOverflowXContainer, false); } } ); },{"../transformer":8,"../utilities":16}],11:[function(require,module,exports){ var transformer = require("../transformer"); var utilities = require("../utilities"); transformer.register( 'collapsePageIssuesAndDisambig', function( content ) { transformer.transform( "displayDisambigLink", content); transformer.transform( "displayIssuesLink", content); var issuesContainer = document.getElementById('issues_container'); if(!issuesContainer){ return; } issuesContainer.setAttribute( "dir", window.directionality ); // If we have both issues and disambiguation, then insert the separator. var disambigBtn = document.getElementById( "disambig_button" ); var issuesBtn = document.getElementById( "issues_button" ); if (issuesBtn !== null && disambigBtn !== null) { var separator = document.createElement( 'span' ); separator.innerText = '|'; separator.className = 'issues_separator'; issuesContainer.insertBefore(separator, issuesBtn.parentNode); } // Hide the container if there were no page issues or disambiguation. issuesContainer.style.display = (disambigBtn || issuesBtn) ? 'inherit' : 'none'; } ); transformer.register( 'displayDisambigLink', function( content ) { var hatnotes = content.querySelectorAll( "div.hatnote" ); if ( hatnotes.length > 0 ) { var container = document.getElementById( "issues_container" ); var wrapper = document.createElement( 'div' ); var link = document.createElement( 'a' ); link.setAttribute( 'href', '#disambig' ); link.className = 'disambig_button'; link.innerHTML = utilities.httpGetSync('wmf://localize/page-similar-titles'); link.id = 'disambig_button'; wrapper.appendChild( link ); var i = 0, len = hatnotes.length; for (; i < len; i++) { wrapper.appendChild( hatnotes[i] ); } container.appendChild( wrapper ); } } ); transformer.register( 'displayIssuesLink', function( content ) { var issues = content.querySelectorAll( "table.ambox:not([class*='ambox-multiple_issues']):not([class*='ambox-notice'])" ); if ( issues.length > 0 ) { var el = issues[0]; var container = document.getElementById( "issues_container" ); var wrapper = document.createElement( 'div' ); var link = document.createElement( 'a' ); link.setAttribute( 'href', '#issues' ); link.className = 'issues_button'; link.innerHTML = utilities.httpGetSync('wmf://localize/page-issues'); link.id = 'issues_button'; wrapper.appendChild( link ); el.parentNode.replaceChild( wrapper, el ); var i = 0, len = issues.length; for (; i < len; i++) { wrapper.appendChild( issues[i] ); } container.appendChild( wrapper ); } } ); function collectDisambig( sourceNode ) { var res = []; var links = sourceNode.querySelectorAll( 'div.hatnote a' ); var i = 0, len = links.length; for (; i < len; i++) { // Pass the href; we'll decode it into a proper page title in Obj-C if(links[i].getAttribute( 'href' ).indexOf("redlink=1") === -1){ res.push( links[i] ); } } return res; } function collectIssues( sourceNode ) { var res = []; var issues = sourceNode.querySelectorAll( 'table.ambox' ); var i = 0, len = issues.length; for (; i < len; i++) { // .ambox- is used e.g. on eswiki res.push( issues[i].querySelector( '.mbox-text, .ambox-text' ).innerHTML ); } return res; } function anchorForAnchor(anchor) { var url = anchor.getAttribute( 'href' ); var titleForDisplay = anchor.text.substring(0,1).toUpperCase() + anchor.text.substring(1); return '<a class="ios-disambiguation-item-anchor" href="' + url + '" >' + titleForDisplay + '</a>'; } function divForIssue(issue) { return '<div class="ios-issue-item">' + issue + '</div>'; } function insertAfter(newNode, referenceNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } function setIsSelected(el, isSelected) { if(isSelected){ el.style.borderBottom = "1px dotted #bbb;"; el.style.color = '#000'; }else{ el.style.borderBottom = "none"; el.style.color = '#777'; } } function toggleSubContainerButtons( activeSubContainerId, focusButtonId, blurButtonId ){ var buttonToBlur = document.getElementById( blurButtonId ); if(buttonToBlur) { setIsSelected(buttonToBlur, false); } var buttonToActivate = document.getElementById( focusButtonId ); var isActiveSubContainerPresent = document.getElementById( activeSubContainerId ) ? true : false; setIsSelected(buttonToActivate, isActiveSubContainerPresent); } function toggleSubContainers( activeSubContainerId, inactiveSubContainerId, activeSubContainerContents ){ var containerToRemove = document.getElementById( inactiveSubContainerId ); var closeButton = document.getElementById('issues_container_close_button'); if(containerToRemove){ containerToRemove.parentNode.removeChild(containerToRemove); } var containerToAddOrToggle = document.getElementById( activeSubContainerId ); if(containerToAddOrToggle){ containerToAddOrToggle.parentNode.removeChild(containerToAddOrToggle); closeButton.style.display = 'none'; }else{ containerToAddOrToggle = document.createElement( 'div' ); containerToAddOrToggle.id = activeSubContainerId; containerToAddOrToggle.innerHTML = activeSubContainerContents; insertAfter(containerToAddOrToggle, document.getElementById('issues_container')); closeButton.style.display = 'inherit'; } } function closeClicked() { if(document.getElementById( 'disambig_sub_container' )){ toggleSubContainers('disambig_sub_container', 'issues_sub_container', null); toggleSubContainerButtons('disambig_sub_container', 'disambig_button', 'issues_button'); }else if(document.getElementById( 'issues_sub_container' )){ toggleSubContainers('issues_sub_container', 'disambig_sub_container', null); toggleSubContainerButtons('issues_sub_container', 'issues_button', 'disambig_button'); } } function issuesClicked( sourceNode ) { var issues = collectIssues( sourceNode.parentNode ); var disambig = collectDisambig( sourceNode.parentNode.parentNode ); // not clicked node toggleSubContainers('issues_sub_container', 'disambig_sub_container', issues.map(divForIssue).join( "" )); toggleSubContainerButtons('issues_sub_container', 'issues_button', 'disambig_button'); return { "hatnotes": disambig, "issues": issues }; } function disambigClicked( sourceNode ) { var disambig = collectDisambig( sourceNode.parentNode ); var issues = collectIssues( sourceNode.parentNode.parentNode ); // not clicked node toggleSubContainers('disambig_sub_container', 'issues_sub_container', disambig.map(anchorForAnchor).sort().join( "" )); toggleSubContainerButtons('disambig_sub_container', 'disambig_button', 'issues_button'); return { "hatnotes": disambig, "issues": issues }; } exports.issuesClicked = issuesClicked; exports.disambigClicked = disambigClicked; exports.closeClicked = closeClicked; },{"../transformer":8,"../utilities":16}],12:[function(require,module,exports){ var transformer = require("../transformer"); var utilities = require("../utilities"); /* Tries to get an array of table header (TH) contents from a given table. If there are no TH elements in the table, an empty array is returned. */ function getTableHeader( element ) { var thArray = []; if (element.children === undefined || element.children === null) { return thArray; } for (var i = 0; i < element.children.length; i++) { var el = element.children[i]; if (el.tagName === "TH") { // ok, we have a TH element! // However, if it contains more than two links, then ignore it, because // it will probably appear weird when rendered as plain text. var aNodes = el.querySelectorAll( "a" ); if (aNodes.length < 3) { // Also ignore it if it's identical to the page title. if (el.innerText.length > 0 && el.innerText !== window.pageTitle && el.innerHTML !== window.pageTitle) { thArray.push(el.innerText); } } } //if it's a table within a table, don't worry about it if (el.tagName === "TABLE") { continue; } //recurse into children of this element var ret = getTableHeader(el); //did we get a list of TH from this child? if (ret.length > 0) { thArray = thArray.concat(ret); } } return thArray; } /* OnClick handler function for expanding/collapsing tables and infoboxes. */ function tableCollapseClickHandler() { var container = this.parentNode; var divCollapsed = container.children[0]; var tableFull = container.children[1]; var divBottom = container.children[2]; if (tableFull.style.display !== 'none') { tableFull.style.display = 'none'; divCollapsed.classList.remove('app_table_collapse_close'); divCollapsed.classList.remove('app_table_collapse_icon'); divCollapsed.classList.add('app_table_collapsed_open'); divBottom.style.display = 'none'; //if they clicked the bottom div, then scroll back up to the top of the table. if (this === divBottom) { window.scrollTo( 0, container.offsetTop - 48 ); } } else { tableFull.style.display = 'block'; divCollapsed.classList.remove('app_table_collapsed_open'); divCollapsed.classList.add('app_table_collapse_close'); divCollapsed.classList.add('app_table_collapse_icon'); divBottom.style.display = 'block'; } } function shouldTableBeCollapsed( table ) { if (table.style.display === 'none' || table.classList.contains( 'navbox' ) || table.classList.contains( 'vertical-navbox' ) || table.classList.contains( 'navbox-inner' ) || table.classList.contains( 'metadata' ) || table.classList.contains( 'mbox-small' )) { return false; } return true; } transformer.register( "hideTables", function( content ) { var isMainPage = utilities.httpGetSync('wmf://article/is-main-page'); if (isMainPage == "1") return; var tables = content.querySelectorAll( "table" ); for (var i = 0; i < tables.length; i++) { var table = tables[i]; if (utilities.findClosest (table, '.app_table_container')) continue; if (!shouldTableBeCollapsed(table)) { continue; } var isInfobox = table.classList.contains( 'infobox' ); var parent = table.parentElement; // If parent contains only this table it's safe to reset its styling if (parent.childElementCount === 1){ parent.removeAttribute("class"); parent.removeAttribute("style"); } // Remove max width restriction table.style.maxWidth = 'none'; var headerText = getTableHeader(table); var caption = "<strong>" + (isInfobox ? utilities.httpGetSync('wmf://localize/info-box-title') : utilities.httpGetSync('wmf://localize/table-title-other')) + "</strong>"; caption += "<span class='app_span_collapse_text'>"; if (headerText.length > 0) { caption += ": " + headerText[0]; } if (headerText.length > 1) { caption += ", " + headerText[1]; } if (headerText.length > 0) { caption += " ..."; } caption += "</span>"; //create the container div that will contain both the original table //and the collapsed version. var containerDiv = document.createElement( 'div' ); containerDiv.className = 'app_table_container'; table.parentNode.insertBefore(containerDiv, table); table.parentNode.removeChild(table); //remove top and bottom margin from the table, so that it's flush with //our expand/collapse buttons table.style.marginTop = "0px"; table.style.marginBottom = "0px"; //create the collapsed div var collapsedDiv = document.createElement( 'div' ); collapsedDiv.classList.add('app_table_collapsed_container'); collapsedDiv.classList.add('app_table_collapsed_open'); collapsedDiv.innerHTML = caption; //create the bottom collapsed div var bottomDiv = document.createElement( 'div' ); bottomDiv.classList.add('app_table_collapsed_bottom'); bottomDiv.classList.add('app_table_collapse_icon'); bottomDiv.innerHTML = utilities.httpGetSync('wmf://localize/info-box-close-text'); //add our stuff to the container containerDiv.appendChild(collapsedDiv); containerDiv.appendChild(table); containerDiv.appendChild(bottomDiv); //set initial visibility table.style.display = 'none'; collapsedDiv.style.display = 'block'; bottomDiv.style.display = 'none'; //assign click handler to the collapsed divs collapsedDiv.onclick = tableCollapseClickHandler; bottomDiv.onclick = tableCollapseClickHandler; } } ); },{"../transformer":8,"../utilities":16}],13:[function(require,module,exports){ var transformer = require("../transformer"); transformer.register( "hideRedlinks", function( content ) { var redLinks = content.querySelectorAll( 'a.new' ); for ( var i = 0; i < redLinks.length; i++ ) { var redLink = redLinks[i]; redLink.style.color = 'inherit'; } } ); },{"../transformer":8}],14:[function(require,module,exports){ var transformer = require("../transformer"); transformer.register( "moveFirstGoodParagraphUp", function( content ) { /* Instead of moving the infobox down beneath the first P tag, move the first good looking P tag *up* (as the first child of the first section div). That way the first P text will appear not only above infoboxes, but above other tables/images etc too! */ if(content.getElementById( "mainpage" ))return; var block_0 = content.getElementById( "content_block_0" ); if(!block_0) return; var allPs = block_0.getElementsByTagName( "p" ); if(!allPs) return; for ( var i = 0; i < allPs.length; i++ ) { var p = allPs[i]; // Narrow down to first P which is direct child of content_block_0 DIV. // (Don't want to yank P from somewhere in the middle of a table!) if (p.parentNode != block_0) continue; // Ensure the P being pulled up has at least a couple lines of text. // Otherwise silly things like a empty P or P which only contains a // BR tag will get pulled up (see articles on "Chemical Reaction" and // "Hawaii"). // Trick for quickly determining element height: // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetHeight // http://stackoverflow.com/a/1343350/135557 var minHeight = 40; var pIsTooSmall = (p.offsetHeight < minHeight); if(pIsTooSmall) continue; // Move the P! Place it just after the lead section edit button. block_0.insertBefore(p, block_0.firstChild); // But only move one P! break; } }); },{"../transformer":8}],15:[function(require,module,exports){ var transformer = require("../transformer"); var utilities = require("../utilities"); var maxStretchRatioAllowedBeforeRequestingHigherResolution = 1.3; // If enabled, widened images will have thin red dashed border and // and widened images for which a higher resolution version was // requested will have thick red dashed border. var enableDebugBorders = false; function widenAncestors (el) { while ((el = el.parentElement) && !el.classList.contains('content_block')){ // Only widen if there was a width setting. Keeps changes minimal. if(el.style.width){ el.style.width = '100%'; } if(el.style.maxWidth){ el.style.maxWidth = '100%'; } if(el.style.float){ el.style.float = 'none'; } } } function shouldWidenImage(image) { if ( image.width >= 64 && image.hasAttribute('srcset') && !image.hasAttribute('hasOverflowXContainer') && !utilities.isNestedInTable(image) ) { return true; }else{ return false; } } function makeRoomForImageWidening(image) { // Expand containment so css wideImageOverride width percentages can take effect. widenAncestors (image); // Remove width and height attributes so wideImageOverride width percentages can take effect. image.removeAttribute("width"); image.removeAttribute("height"); } function getStretchRatio(image){ var widthControllingDiv = utilities.firstDivAncestor(image); if (widthControllingDiv){ return (widthControllingDiv.offsetWidth / image.naturalWidth); } return 1.0; } function useHigherResolutionImageSrcFromSrcsetIfNecessary(image) { if (image.getAttribute('srcset')){ var stretchRatio = getStretchRatio(image); if (stretchRatio > maxStretchRatioAllowedBeforeRequestingHigherResolution) { var srcsetDict = utilities.getDictionaryFromSrcset(image.getAttribute('srcset')); /* Grab the highest res url from srcset - avoids the complexity of parsing urls to retrieve variants - which can get tricky - canonicals have different paths than size variants */ var largestSrcsetDictKey = Object.keys(srcsetDict).reduce(function(a, b) { return a > b ? a : b; }); image.src = srcsetDict[largestSrcsetDictKey]; if(enableDebugBorders){ image.style.borderWidth = '10px'; } } } } function widenImage(image) { makeRoomForImageWidening (image); image.classList.add("wideImageOverride"); if(enableDebugBorders){ image.style.borderStyle = 'dashed'; image.style.borderWidth = '1px'; image.style.borderColor = '#f00'; } useHigherResolutionImageSrcFromSrcsetIfNecessary(image); } function maybeWidenImage() { var image = this; if (shouldWidenImage(image)) { widenImage(image); } } transformer.register( "widenImages", function( content ) { var images = content.querySelectorAll( 'img' ); for ( var i = 0; i < images.length; i++ ) { // Load event used so images w/o style or inline width/height // attributes can still have their size determined reliably. images[i].addEventListener('load', maybeWidenImage, false); } } ); },{"../transformer":8,"../utilities":16}],16:[function(require,module,exports){ function getDictionaryFromSrcset(srcset) { /* Returns dictionary with density (without "x") as keys and urls as values. Parameter 'srcset' string: '//image1.jpg 1.5x, //image2.jpg 2x, //image3.jpg 3x' Returns dictionary: {1.5: '//image1.jpg', 2: '//image2.jpg', 3: '//image3.jpg'} */ var sets = srcset.split(',').map(function(set) { return set.trim().split(' '); }); var output = {}; sets.forEach(function(set) { output[set[1].replace('x', '')] = set[0]; }); return output; } function firstDivAncestor (el) { while ((el = el.parentElement)){ if(el.tagName === 'DIV'){ return el; } } return null; } function firstAncestorWithMultipleChildren (el) { while ((el = el.parentElement) && (el.childElementCount == 1)); return el; } // Implementation of https://developer.mozilla.org/en-US/docs/Web/API/Element/closest function findClosest (el, selector) { while ((el = el.parentElement) && !el.matches(selector)); return el; } function httpGetSync(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); xmlHttp.send( null ); return xmlHttp.responseText; } function isNestedInTable(el) { while ((el = el.parentElement)){ if(el.tagName === 'TD'){ return true; } } return false; } exports.getDictionaryFromSrcset = getDictionaryFromSrcset; exports.firstDivAncestor = firstDivAncestor; exports.firstAncestorWithMultipleChildren = firstAncestorWithMultipleChildren; exports.findClosest = findClosest; exports.httpGetSync = httpGetSync; exports.isNestedInTable = isNestedInTable; },{}],17:[function(require,module,exports){ (function (global){ var _topElement = null; var _preRotationOffsetY = null; function setPreRotationRelativeScrollOffset() { _topElement = document.elementFromPoint( window.innerWidth / 2, 0 ); if (_topElement) { var rect = _topElement.getBoundingClientRect(); _preRotationOffsetY = rect.top / rect.height; } else { _preRotationOffsetY = null; } } function getPostRotationScrollOffset() { if (_topElement && (_preRotationOffsetY !== null)) { var rect = _topElement.getBoundingClientRect(); _topElement = null; return (window.scrollY + rect.top) - (_preRotationOffsetY * rect.height); } else { _topElement = null; return 0; } } global.setPreRotationRelativeScrollOffset = setPreRotationRelativeScrollOffset; global.getPostRotationScrollOffset = getPostRotationScrollOffset; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17])
soppysonny/wikipedia-ios
Wikipedia/assets/bundle.js
JavaScript
mit
39,250
const DrawCard = require('../../drawcard.js'); class PaxterRedwyne extends DrawCard { setupCardAbilities(ability) { this.plotModifiers({ gold: 1 }); this.persistentEffect({ targetController: 'current', effect: ability.effects.reduceFirstPlayedCardCostEachRound(1, card => card.getType() === 'event') }); } } PaxterRedwyne.code = '01182'; module.exports = PaxterRedwyne;
ystros/throneteki
server/game/cards/01-Core/PaxterRedwyne.js
JavaScript
mit
449
OC.L10N.register( "federatedfilesharing", { "Federated sharing" : "Federated sharing", "Add to your ownCloud" : "Ajouter à votre ownCloud", "Invalid Federated Cloud ID" : "ID Federated Cloud incorrect", "Sharing %s failed, because this item is already shared with %s" : "Le partage de %s a échoué car cet élément est déjà partagé avec %s", "Not allowed to create a federated share with the same user" : "Non autorisé à créer un partage fédéré avec le même utilisateur", "File is already shared with %s" : "Le fichier est déjà partagé avec %s", "Sharing %s failed, could not find %s, maybe the server is currently unreachable." : "Le partage de %s a échoué : impossible de trouver %s. Peut-être le serveur est-il momentanément injoignable.", "Accept" : "Accepter", "Decline" : "Refuser", "Share with me through my #ownCloud Federated Cloud ID, see %s" : "Partagez avec moi grâce à mon identifiant Federated Cloud #owncloud %s", "Share with me through my #ownCloud Federated Cloud ID" : "Partagez avec moi grâce à mon identifiant Federated Cloud #owncloud", "Federated Cloud Sharing" : "Federated Cloud Sharing", "Open documentation" : "Voir la documentation", "Allow users on this server to send shares to other servers" : "Autoriser les utilisateurs de ce serveur à envoyer des partages vers d'autres serveurs", "Allow users on this server to receive shares from other servers" : "Autoriser les utilisateurs de ce serveur à recevoir des partages d'autres serveurs", "Federated Cloud" : "Federated Cloud", "Your Federated Cloud ID:" : "Votre identifiant Federated Cloud :", "Share it:" : "Partager :", "Add to your website" : "Ajouter à votre site web", "Share with me via ownCloud" : "Partagez avec moi via ownCloud", "HTML Code:" : "Code HTML :" }, "nplurals=2; plural=(n > 1);");
phil-davis/core
apps/federatedfilesharing/l10n/fr.js
JavaScript
mit
1,903
import expect from 'expect'; import { showNotification, } from '../actions'; import { SHOW_NOTIFICATION, } from '../constants'; describe('NotificationProvider actions', () => { describe('Default Action', () => { it('has a type of SHOW_NOTIFICATION', () => { const message = 'Well done!'; const status = 'success'; const expected = { type: SHOW_NOTIFICATION, message, status, id: 1, }; expect(showNotification(expected.message, expected.status)).toEqual(expected); }); }); });
skelpook/strapi
packages/strapi-admin/files/public/app/containers/NotificationProvider/tests/actions.test.js
JavaScript
mit
556
/** * Node 版静态资源文件服务器 * 功能:实现了缓存、gzip压缩等 * * @author liufeng.clf * @date 2014/12/1 */ // 设置端口号 var PORT = 8000 || process.env.PORT; // 引入模块 var http = require('http'); var url = require('url'); var fs = require('fs'); var path = require('path'); var zlib = require('zlib'); // 引入文件 var mime = require('./mime').types; var config = require('./config'); var server = http.createServer(function (req, res) { res.setHeader("Server","Node/V8"); // 获取文件路径 var pathName = url.parse(req.url).pathname; if(pathName.slice(-1) === "/"){ pathName = pathName + "index.html"; //默认取当前默认下的index.html } // 安全处理(当使用Linux 的 curl命令访问时,存在安全隐患) var realPath = path.join("assert", path.normalize(pathName.replace(/\.\./g, ""))); // 检查文件路径是否存在 fs.exists(realPath, function(exists) { // 当文件不存在时的情况, 输出一个404错误 if (!exists) { res.writeHead(404, "Not Found", {'Content-Type': 'text/plain'}); res.write("The request url" + pathName +" is not found!"); res.end(); } else { // 当文件存在时的处理逻辑 fs.stat(realPath, function(err, stat) { // 获取文件扩展名 var ext = path.extname(realPath); ext = ext ? ext.slice(1) : "unknown"; var contentType = mime[ext] || "text/plain"; // 设置 Content-Type res.setHeader("Content-Type", contentType); var lastModified = stat.mtime.toUTCString(); var ifModifiedSince = "If-Modified-Since".toLowerCase(); res.setHeader("Last-Modified", lastModified); if (ext.match(config.Expires.fileMatch)) { var expires = new Date(); expires.setTime(expires.getTime() + config.Expires.maxAge * 1000); res.setHeader("Expires", expires.toUTCString()); res.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge); } if (req.headers[ifModifiedSince] && lastModified == req.headers[ifModifiedSince]) { res.writeHead(304, "Not Modified"); res.end(); } else { // 使用流的方式去读取文件 var raw = fs.createReadStream(realPath); var acceptEncoding = req.headers['accept-encoding'] || ""; var matched = ext.match(config.Compress.match); if (matched && acceptEncoding.match(/\bgzip\b/)) { res.writeHead(200, "Ok", {'Content-Encoding': 'gzip'}); raw.pipe(zlib.createGzip()).pipe(res); } else if (matched && acceptEncoding.match(/\bdeflate\b/)) { res.writeHead(200, "Ok", {'Content-Encoding': 'deflate'}); raw.pipe(zlib.createDeflate()).pipe(res); } else { res.writeHead(200, "Ok"); raw.pipe(res); } //下面是普通的读取文件的方式,不推荐 // fs.readFile(realPath, "binary", function(err, data) { // if(err) { // // file exists, but have some error while read // res.writeHead(500, {'Content-Type': 'text/plain'}); // res.end(err); // } else { // // file exists, can success return // res.writeHead(200, {'Content-Type': contentType}); // res.write(data, "binary"); // res.end(); // } // }); } }); } }); }); //监听端口,提供静态资源服务 server.listen(PORT, function() { console.log("Server is listening on port " + PORT + "!"); });
node-funs/static-server
server.js
JavaScript
mit
3,837
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { if (n === 1) return 1; return 5; } global.ng.common.locales['or'] = [ 'or', [['ପୂ', 'ଅ'], ['AM', 'PM'], u], [['AM', 'ଅପରାହ୍ନ'], ['ପୂର୍ବାହ୍ନ', 'ଅପରାହ୍ନ'], u], [ ['ର', 'ସୋ', 'ମ', 'ବୁ', 'ଗୁ', 'ଶୁ', 'ଶ'], [ 'ରବି', 'ସୋମ', 'ମଙ୍ଗଳ', 'ବୁଧ', 'ଗୁରୁ', 'ଶୁକ୍ର', 'ଶନି' ], [ 'ରବିବାର', 'ସୋମବାର', 'ମଙ୍ଗଳବାର', 'ବୁଧବାର', 'ଗୁରୁବାର', 'ଶୁକ୍ରବାର', 'ଶନିବାର' ], [ 'ରବି', 'ସୋମ', 'ମଙ୍ଗଳ', 'ବୁଧ', 'ଗୁରୁ', 'ଶୁକ୍ର', 'ଶନି' ] ], u, [ [ 'ଜା', 'ଫେ', 'ମା', 'ଅ', 'ମଇ', 'ଜୁ', 'ଜୁ', 'ଅ', 'ସେ', 'ଅ', 'ନ', 'ଡି' ], [ 'ଜାନୁଆରୀ', 'ଫେବୃଆରୀ', 'ମାର୍ଚ୍ଚ', 'ଅପ୍ରେଲ', 'ମଇ', 'ଜୁନ', 'ଜୁଲାଇ', 'ଅଗଷ୍ଟ', 'ସେପ୍ଟେମ୍ବର', 'ଅକ୍ଟୋବର', 'ନଭେମ୍ବର', 'ଡିସେମ୍ବର' ], u ], u, [ ['BC', 'AD'], u, ['ଖ୍ରୀଷ୍ଟପୂର୍ବ', 'ଖ୍ରୀଷ୍ଟାବ୍ଦ'] ], 0, [0, 0], ['M/d/yy', 'MMM d, y', 'MMMM d, y', 'EEEE, MMMM d, y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{0} ଠାରେ {1}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'INR', '₹', 'ଭାରତୀୟ ଟଙ୍କା', {}, 'ltr', plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
Toxicable/angular
packages/common/locales/global/or.js
JavaScript
mit
2,475
(function() { 'use strict'; app.controller('dashboardCtrl', ['commonFactory','$state',function(commonFactory,$state){ var dashboard = this; dashboard.user = commonFactory.getUser(); if(!dashboard.user){ $state.go('login'); } }]); })();
colorgap/bowyer
themes/bootstrap/dashboard/app/modules/dashboard/dashboardController.js
JavaScript
mit
275
(function($) { 'use strict'; var DOCUMENT_SELECTOR = '.course-experience-points-disbursement.new '; var COPY_BUTTON_SELECTOR = '#experience-points-disbursement-copy-button'; function copyExperiencePoints(event) { event.preventDefault(); var valueToCopy = $('.course_user:first').find('.points_awarded:first').val(); $('.points_awarded').val(valueToCopy); } $(document).on('click', DOCUMENT_SELECTOR + COPY_BUTTON_SELECTOR, copyExperiencePoints); })(jQuery);
cysjonathan/coursemology2
app/assets/javascripts/course/experience_points/disbursement.js
JavaScript
mit
484
import React from "react"; import { Link, Route } from "react-router-dom"; import { Block, Row, Inline, Col } from "jsxstyle"; import PropTypes from "prop-types"; import { LIGHT_GRAY, RED } from "../Theme.js"; import Logo from "./Logo.js"; function Tab({ to, ...rest }) { return ( <Route path={to} children={({ match }) => ( <Block component={Link} props={{ to }} flex="1" textAlign="center" textTransform="uppercase" fontWeight="bold" fontSize="90%" padding="5px" background={match ? RED : "white"} color={match ? "white" : ""} {...rest} /> )} /> ); } Tab.propTypes = { to: PropTypes.string }; function Tabs() { return ( <Row boxShadow="0px 1px 1px hsla(0, 0%, 0%, 0.15)" margin="10px"> <Tab to="/core" borderTopLeftRadius="3px" borderBottomLeftRadius="3px"> Core </Tab> <Tab to="/web" marginLeft="-1px"> Web </Tab> <Tab to="/native" marginLeft="-1px" borderTopRightRadius="3px" borderBottomRightRadius="3px" > Native </Tab> </Row> ); } function Branding() { return ( <Col alignItems="center" padding="15px 0"> <Logo size={36} shadow={false} /> <Block marginTop="10px" flex="1" textTransform="uppercase" fontWeight="bold" fontSize="90%" > <Inline component="a" props={{ href: "https://reacttraining.com" }}> React Training </Inline> <Inline> / </Inline> <Inline component="a" props={{ href: "https://github.com/ReactTraining/react-router" }} color={LIGHT_GRAY} > React Router </Inline> </Block> </Col> ); } export default function EnvironmentHeader() { return ( <Block> <Branding /> <Tabs /> </Block> ); }
rackt/react-router
website/modules/components/EnvironmentHeader.js
JavaScript
mit
1,977
/* global kity: true */ /* global window: true */ var Vector = kity.Vector; var ForceChart = kity.createClass( "ForceChart", { base: kity.Group, constructor: function ( nodes, links ) { this.callBase(); this.nodes = nodes; this.links = links; }, start: function () { var nodes = this.nodes; var links = this.links; var color = kity.Color.createHSL( 0, 100, 50 ); for ( var i = 0; i < links.length; i++ ) { var link = links[ i ]; var sourceNode = nodes[ link.source ]; var targetNode = nodes[ link.target ]; var sdf = sourceNode.distanceInfo = sourceNode.distanceInfo || {}; var tdf = targetNode.distanceInfo = targetNode.distanceInfo || {}; sdf[ link.target ] = { node: targetNode, distance: link.distance }; tdf[ link.source ] = { node: sourceNode, distance: link.distance }; var line = new kity.Path().stroke( '#AAA' ); line.source = sourceNode; line.target = targetNode; this.addShape( link.shape = line ); } for ( var id in nodes ) { var node = nodes[ id ]; this.addShape( node.shape = new kity.Circle( 10 ).fill( color = color.inc( 'h', 360 / 6 ) ) ); node.s = new Vector( 100 + Math.random() * 600, 100 + Math.random() * 400 ); node.a = new Vector(); node.v = new Vector(); node.shape.chartNode = node; } this.frame = kity.Timeline.requestFrame( this.tick.bind( this ) ); }, tick: function ( frame ) { var k = 20, dt = frame.dur / 1000, name, node, distanceInfo, din, di, dir, d; for ( name in this.nodes ) { node = this.nodes[ name ]; node.a = new kity.Vector(); distanceInfo = node.distanceInfo; for ( din in distanceInfo ) { di = distanceInfo[ din ]; dir = Vector.fromPoints( node.s, di.node.s ); d = dir.length() - di.distance; node.a = node.a.add( dir.normalize( k * d ) ); } } for ( name in this.nodes ) { node = this.nodes[ name ]; node.v = node.v.add( node.a.multipy( dt ) ); node.v = node.v.multipy( 0.9 ); if ( !node.locked ) { node.s = node.s.add( node.v.multipy( dt ) ); } node.shape.setTranslate( node.s ); } for ( var i = 0; i < this.links.length; i++ ) { var line = this.links[ i ].shape; var src = line.source.s, tgt = line.target.s; line.setPathData( [ 'M', src.x, src.y, 'L', tgt.x, tgt.y ] ); } frame.next(); } } ); var data = { "nodes": { "A": {}, "B": {}, "C": {}, "D": {}, "E": {}, "F": {} }, "links": [ { "source": "A", "target": "B", "distance": 200 }, { "source": "A", "target": "C", "distance": 200 }, { "source": "A", "target": "D", "distance": 200 }, { "source": "A", "target": "E", "distance": 200 }, { "source": "A", "target": "F", "distance": 200 }, { "source": "B", "target": "C", "distance": 200 }, { "source": "B", "target": "D", "distance": 200 }, { "source": "B", "target": "E", "distance": 200 }, { "source": "B", "target": "F", "distance": 200 }, { "source": "C", "target": "D", "distance": 200 }, { "source": "C", "target": "E", "distance": 200 }, { "source": "C", "target": "F", "distance": 200 },{ "source": "D", "target": "E", "distance": 200 }, { "source": "D", "target": "F", "distance": 200 }, { "source": "E", "target": "F", "distance": 200 } ] }; var paper = new kity.Paper( window.document.body ); var fc = new ForceChart( data.nodes, data.links ); paper.addShape( fc ); fc.start(); var dragTarget = null; fc.on( 'mousedown', function ( e ) { if ( e.targetShape.chartNode ) { dragTarget = e.targetShape.chartNode; dragTarget.locked = true; } } ); paper.on( 'mousemove', function ( e ) { if ( dragTarget ) { dragTarget.s = e.getPosition().asVector(); } } ); paper.on( 'mouseup', function ( e ) { if ( dragTarget ) { dragTarget.locked = false; dragTarget = null; } } );
AlloyTeam/Nuclear
packages/admin/mind-map/bower_components/kity/demo/force-chart/force-chart.js
JavaScript
mit
4,904
import React, { PropTypes } from 'react' import muiThemeable from 'material-ui/styles/muiThemeable' import IconButton from 'material-ui/IconButton' import ArrowDropUp from 'material-ui/svg-icons/navigation/arrow-drop-up' import { Toolbar, ToolbarGroup, ToolbarTitle } from 'material-ui/Toolbar' import { white } from 'material-ui/styles/colors' import TwitchChatEmbed from './TwitchChatEmbed' import ChatSelector from './ChatSelector' import { chatPropType } from '../utils/PropTypes' class ChatSidebar extends React.Component { static propTypes = { enabled: PropTypes.bool.isRequired, hasBeenVisible: PropTypes.bool.isRequired, chats: PropTypes.objectOf(chatPropType).isRequired, displayOrderChats: PropTypes.arrayOf(chatPropType).isRequired, renderedChats: PropTypes.arrayOf(PropTypes.string).isRequired, currentChat: PropTypes.string.isRequired, setTwitchChat: PropTypes.func.isRequired, muiTheme: PropTypes.object.isRequired, } constructor(props) { super(props) this.state = { chatSelectorOpen: false, } } onRequestOpenChatSelector() { this.setState({ chatSelectorOpen: true, }) } onRequestCloseChatSelector() { this.setState({ chatSelectorOpen: false, }) } render() { const metrics = { switcherHeight: 36, } const panelContainerStyle = { position: 'absolute', top: this.props.muiTheme.layout.appBarHeight, right: 0, bottom: 0, width: this.props.muiTheme.layout.chatPanelWidth, background: '#EFEEF1', display: this.props.enabled ? null : 'none', zIndex: 1000, } const chatEmbedContainerStyle = { position: 'absolute', top: 0, bottom: metrics.switcherHeight, width: '100%', } const switcherToolbarStyle = { position: 'absolute', bottom: 0, height: metrics.switcherHeight, width: '100%', background: this.props.muiTheme.palette.primary1Color, } const toolbarTitleStyle = { color: white, fontSize: 16, } const toolbarButtonStyle = { width: metrics.switcherHeight, height: metrics.switcherHeight, padding: 8, } const toolbarButtonIconStyle = { width: (metrics.switcherHeight - 16), height: (metrics.switcherHeight - 16), } const renderedChats = [] this.props.renderedChats.forEach((chat) => { const visible = (chat === this.props.currentChat) renderedChats.push( <TwitchChatEmbed channel={chat} key={chat} visible={visible} /> ) }) const currentChat = this.props.chats[this.props.currentChat] let currentChatName = 'UNKNOWN' if (currentChat) { currentChatName = `${currentChat.name} Chat` } let content if (this.props.hasBeenVisible) { content = ( <div style={panelContainerStyle}> <div style={chatEmbedContainerStyle}> {renderedChats} </div> <Toolbar style={switcherToolbarStyle}> <ToolbarGroup> <ToolbarTitle text={currentChatName} style={toolbarTitleStyle} /> </ToolbarGroup> <ToolbarGroup lastChild> <IconButton style={toolbarButtonStyle} iconStyle={toolbarButtonIconStyle} onTouchTap={() => this.onRequestOpenChatSelector()} > <ArrowDropUp color={white} /> </IconButton> </ToolbarGroup> </Toolbar> <ChatSelector chats={this.props.displayOrderChats} currentChat={this.props.currentChat} setTwitchChat={this.props.setTwitchChat} open={this.state.chatSelectorOpen} onRequestClose={() => this.onRequestCloseChatSelector()} /> </div> ) } else { content = (<div />) } return content } } export default muiThemeable()(ChatSidebar)
verycumbersome/the-blue-alliance
react/gameday2/components/ChatSidebar.js
JavaScript
mit
4,048
/** @jsxImportSource baz */ var x = (<div><span /></div>);
jridgewell/babel
packages/babel-plugin-transform-react-jsx/test/fixtures/nextAutoImport/import-source-pragma/input.js
JavaScript
mit
58
//textarea angular.module('xeditable').directive('editableTextarea', ['editableDirectiveFactory', function(editableDirectiveFactory) { return editableDirectiveFactory({ directiveName: 'editableTextarea', inputTpl: '<textarea></textarea>', render: function() { this.parent.render.call(this); // Add classes to the form if (this.attrs.eFormclass) { this.editorEl.addClass(this.attrs.eFormclass); this.inputEl.removeAttr('formclass'); } }, addListeners: function() { var self = this; self.parent.addListeners.call(self); // submit textarea by ctrl+enter even with buttons if (self.single && self.buttons !== 'no') { self.autosubmit(); } }, autosubmit: function() { var self = this; self.inputEl.bind('keydown', function(e) { if (self.attrs.submitOnEnter) { if (e.keyCode === 13 && !e.shiftKey) { self.scope.$apply(function() { self.scope.$form.$submit(); }); } } else if ((e.ctrlKey || e.metaKey) && (e.keyCode === 13) || (e.keyCode === 9 && self.editorEl.attr('blur') === 'submit')) { self.scope.$apply(function() { self.scope.$form.$submit(); }); } }); } }); }]);
HS2-SOLUTIONS/angular-xeditable
src/js/directives/textarea.js
JavaScript
mit
1,417
System.register(["github:aurelia/event-aggregator@0.3.0/index"], function($__export) { return { setters: [function(m) { for (var p in m) $__export(p, m[p]); }], execute: function() {} }; });
taylorzane/aurelia-firebase
jspm_packages/github/aurelia/event-aggregator@0.3.0.js
JavaScript
mit
195
const debug = require('ghost-ignition').debug('web:api:default:app'); const express = require('express'); const urlUtils = require('../../lib/url-utils'); const errorHandler = require('../shared/middlewares/error-handler'); module.exports = function setupApiApp() { debug('Parent API setup start'); const apiApp = express(); // Mount different API versions apiApp.use(urlUtils.getVersionPath({version: 'v2', type: 'content'}), require('./v2/content/app')()); apiApp.use(urlUtils.getVersionPath({version: 'v2', type: 'admin'}), require('./v2/admin/app')()); apiApp.use(urlUtils.getVersionPath({version: 'v3', type: 'content'}), require('./canary/content/app')()); apiApp.use(urlUtils.getVersionPath({version: 'v3', type: 'admin'}), require('./canary/admin/app')()); apiApp.use(urlUtils.getVersionPath({version: 'v3', type: 'members'}), require('./canary/members/app')()); apiApp.use(urlUtils.getVersionPath({version: 'canary', type: 'content'}), require('./canary/content/app')()); apiApp.use(urlUtils.getVersionPath({version: 'canary', type: 'admin'}), require('./canary/admin/app')()); apiApp.use(urlUtils.getVersionPath({version: 'canary', type: 'members'}), require('./canary/members/app')()); // Error handling for requests to non-existent API versions apiApp.use(errorHandler.resourceNotFound); apiApp.use(errorHandler.handleJSONResponse); debug('Parent API setup end'); return apiApp; };
dingotiles/ghost-for-cloudfoundry
versions/3.3.0/core/server/web/api/index.js
JavaScript
mit
1,464
export default function SuccessMessage({ children }) { return ( <p className="flex items-center text-sm font-bold text-green-700 dark:text-green-400"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="mr-2 h-4 w-4" > <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" /> </svg> {children} </p> ) }
zeit/next.js
examples/with-fauna/components/SuccessMessage.js
JavaScript
mit
584
/** * Fill metadataStore with metadata, crafted by hand using * Breeze Labs: breeze.metadata.helper.js * @see http://www.breezejs.com/documentation/metadata-by-hand */ (function(angular) { 'use strict'; angular.module("app").factory( 'metadata', ['breeze', factory] ); function factory(breeze) { setNamingConvention(); return { fillStore: fillStore }; ///////////////////// function setNamingConvention() { // Translate certain zza property names between MongoDb names and client names var convention = new breeze.NamingConvention({ serverPropertyNameToClient: function(serverPropertyName) { switch (serverPropertyName) { case '_id': return 'id'; case 'qty': return 'quantity'; case 'optionId': return 'productOptionId'; case 'sizeId': return 'productSizeId'; case 'items': return 'orderItems'; case 'options': return 'orderItemOptions'; default: return serverPropertyName; } }, clientPropertyNameToServer: function(clientPropertyName) { switch (clientPropertyName) { case 'id': return '_id'; case 'quantity': return 'qty'; case 'productOptionId': return 'optionId'; case 'productSizeId': return 'sizeId'; case 'orderItems': return 'items'; case 'orderItemOptions': return 'options'; default: return clientPropertyName; } } }); convention.setAsDefault(); } function fillStore(store){ // Using Breeze Labs: breeze.metadata.helper.js // https://github.com/IdeaBlade/Breeze/blob/master/Breeze.Client/Scripts/Labs/breeze.metadata-helper.js // The helper reduces data entry by applying common conventions // and converting common abbreviations (e.g., 'type' -> 'dataType') // 'None' (client-generated) is the default key generation strategy for this app var keyGen = breeze.AutoGeneratedKeyType.None; // namespace of the corresponding classes on the server var namespace = 'Zza.Model'; var helper = new breeze.config.MetadataHelper(namespace, keyGen); /*** Convenience fns and vars ***/ // addType - make it easy to add the type to the store using the helper var addType = function (type) { helper.addTypeToStore(store, type); }; // DataTypes var DT = breeze.DataType; var BOOL = DT.Boolean; var DATE = DT.DateTime; var DECIMAL = DT.Decimal; var LUID = DT.Int32; // "Lookup" Id var ID = DT.MongoObjectId; // Root entity Id addAddress(); addCustomer(); addOrder(); addOrderItem(); addOrderItemOption(); addOrderStatus(); addProduct(); addProductOption(); addProductSize(); function addAddress() { addType({ name: 'Address', isComplexType: true, dataProperties: { street: { max: 100 }, city: { max: 100 }, state: { max: 2 }, zip: { max: 10 } } }); } function addCustomer() { addType({ name: 'Customer', dataProperties: { id: { type: ID }, firstName: { max: 50 }, lastName: { max: 50 }, phone: { max: 100 }, email: { max: 255 }, address: { complex: 'Address'} }, navigationProperties: { orders: {type: 'Order', hasMany: true } // nav in cache; not in Mongo! } }); } function addOrder() { addType({ name: 'Order', dataProperties: { id: { type: ID }, customerId:{ type: ID, required: true }, name: { max: 50, required: true }, statusId: { type: LUID, required: true, default: 1 },//default is 'Ordered' status: { max: 20, required: true }, ordered: { type: DATE, required: true, default: "2014-01-01T08:00:00Z"}, phone: { max: 100 }, delivered: { type: DATE }, deliveryCharge: { type: DECIMAL, required: true, default: 0 }, deliveryAddress:{ complex: 'Address'}, itemsTotal: { type: DECIMAL, required: true, default: 0 }, orderItems: { complex: 'OrderItem', hasMany: true } }, navigationProperties: { customer: 'Customer', orderStatus: {type: 'OrderStatus', fk: 'statusId'} } }); } function addOrderItem() { addType({ name: 'OrderItem', isComplexType: true, dataProperties: { productId: { type: LUID, required: true, default: 0 }, name: { max: 50, required: true }, type: { max: 50, required: true }, productSizeId: { type: LUID, required: true, default: 0 }, size: { max: 50, required: true }, quantity: { type: DT.Int32, required: true, default: 1 }, unitPrice: { type: DECIMAL, required: true, default: 0 }, totalPrice: { type: DECIMAL, required: true, default: 0 }, instructions: { max: 255 }, orderItemOptions: { complex: 'OrderItemOption', hasMany: true } } }); } function addOrderItemOption() { addType({ name: 'OrderItemOption', isComplexType: true, dataProperties: { productOptionId: { type: LUID, required: true, default: 0 }, name: { max: 50, required: true }, quantity: { type: DT.Int32, required: true, default: 1 }, price: { type: DECIMAL, required: true, default: 0 } } }); } function addOrderStatus() { addType({ name: 'OrderStatus', dataProperties: { id: { type: LUID }, name: { max: 50, required: true } } }); } function addProduct() { addType({ name: 'Product', dataProperties: { id: { type: LUID }, type: { max: 20, required: true }, name: { max: 50, required: true }, description: { max: 255 }, image: { max: 50 }, // image name hasOptions: { type: BOOL, required: true }, isPremium: { type: BOOL, required: true }, isVegetarian: { type: BOOL, required: true }, withTomatoSauce:{ type: BOOL, required: true }, sizeIds: { type: LUID, hasMany: true } } }); } function addProductOption() { addType({ name: 'ProductOption', dataProperties: { id: { type: LUID }, type: { max: 20, required: true }, name: { max: 50, required: true }, factor: { max: 255 }, productTypes: { hasMany: true } } }); } function addProductSize() { addType({ name: 'ProductSize', dataProperties: { id: { type: LUID }, type: { max: 20, required: true }, name: { max: 50, required: true }, price: { type: DECIMAL, required: true, default: 0 }, premiumPrice: { type: DECIMAL }, toppingPrice: { type: DECIMAL }, isGlutenFree: { type: BOOL } } }); } } } }( this.angular ));
johnpapa/ng-demos
zza-node-mongo/client/app/services/metadata.js
JavaScript
mit
9,612
'use strict'; import Vue from 'vue'; import Vuex from 'vuex'; import * as actions from './actions' import * as getters from './getters' import mutations from './mutations' Vue.use(Vuex); const state = { articleList: [], article: {} }; export default new Vuex.Store({ state, actions, getters, mutations });
Eric-Zhong/iphone2
app/web/store/app/index.js
JavaScript
mit
321
// Based upon the excellent jsx-transpiler by Ingvar Stepanyan (RReverser) // https://github.com/RReverser/jsx-transpiler // jsx import isString from "lodash/lang/isString"; import * as messages from "../../messages"; import esutils from "esutils"; import * as react from "./react"; import * as t from "../../types"; export default function (exports, opts) { exports.check = function (node) { if (t.isJSX(node)) return true; if (react.isCreateClass(node)) return true; return false; }; exports.JSXIdentifier = function (node, parent) { if (node.name === "this" && t.isReferenced(node, parent)) { return t.thisExpression(); } else if (esutils.keyword.isIdentifierNameES6(node.name)) { node.type = "Identifier"; } else { return t.literal(node.name); } }; exports.JSXNamespacedName = function (node, parent, scope, file) { throw this.errorWithNode(messages.get("JSXNamespacedTags")); }; exports.JSXMemberExpression = { exit(node) { node.computed = t.isLiteral(node.property); node.type = "MemberExpression"; } }; exports.JSXExpressionContainer = function (node) { return node.expression; }; exports.JSXAttribute = { enter(node) { var value = node.value; if (t.isLiteral(value) && isString(value.value)) { value.value = value.value.replace(/\n\s+/g, " "); } }, exit(node) { var value = node.value || t.literal(true); return t.inherits(t.property("init", node.name, value), node); } }; exports.JSXOpeningElement = { exit(node, parent, scope, file) { parent.children = react.buildChildren(parent); var tagExpr = node.name; var args = []; var tagName; if (t.isIdentifier(tagExpr)) { tagName = tagExpr.name; } else if (t.isLiteral(tagExpr)) { tagName = tagExpr.value; } var state = { tagExpr: tagExpr, tagName: tagName, args: args }; if (opts.pre) { opts.pre(state, file); } var attribs = node.attributes; if (attribs.length) { attribs = buildJSXOpeningElementAttributes(attribs, file); } else { attribs = t.literal(null); } args.push(attribs); if (opts.post) { opts.post(state, file); } return state.call || t.callExpression(state.callee, args); } }; /** * The logic for this is quite terse. It's because we need to * support spread elements. We loop over all attributes, * breaking on spreads, we then push a new object containg * all prior attributes to an array for later processing. */ var buildJSXOpeningElementAttributes = function (attribs, file) { var _props = []; var objs = []; var pushProps = function () { if (!_props.length) return; objs.push(t.objectExpression(_props)); _props = []; }; while (attribs.length) { var prop = attribs.shift(); if (t.isJSXSpreadAttribute(prop)) { pushProps(); objs.push(prop.argument); } else { _props.push(prop); } } pushProps(); if (objs.length === 1) { // only one object attribs = objs[0]; } else { // looks like we have multiple objects if (!t.isObjectExpression(objs[0])) { objs.unshift(t.objectExpression([])); } // spread it attribs = t.callExpression( file.addHelper("extends"), objs ); } return attribs; }; exports.JSXElement = { exit(node) { var callExpr = node.openingElement; callExpr.arguments = callExpr.arguments.concat(node.children); if (callExpr.arguments.length >= 3) { callExpr._prettyCall = true; } return t.inherits(callExpr, node); } }; // display names var addDisplayName = function (id, call) { var props = call.arguments[0].properties; var safe = true; for (var i = 0; i < props.length; i++) { var prop = props[i]; if (t.isIdentifier(prop.key, { name: "displayName" })) { safe = false; break; } } if (safe) { props.unshift(t.property("init", t.identifier("displayName"), t.literal(id))); } }; exports.ExportDefaultDeclaration = function (node, parent, scope, file) { if (react.isCreateClass(node.declaration)) { addDisplayName(file.opts.basename, node.declaration); } }; exports.AssignmentExpression = exports.Property = exports.VariableDeclarator = function (node) { var left, right; if (t.isAssignmentExpression(node)) { left = node.left; right = node.right; } else if (t.isProperty(node)) { left = node.key; right = node.value; } else if (t.isVariableDeclarator(node)) { left = node.id; right = node.init; } if (t.isMemberExpression(left)) { left = left.property; } if (t.isIdentifier(left) && react.isCreateClass(right)) { addDisplayName(left.name, right); } }; };
hryniu555/babel
src/babel/transformation/helpers/build-react-transformer.js
JavaScript
mit
5,058
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import Button from './button'; import * as SharedStyle from '../../shared-style'; var STYLE = { borderColor: "#c12e2a", backgroundColor: "#c9302c", color: SharedStyle.COLORS.white }; var STYLE_HOVER = { backgroundColor: "#972726", borderColor: "#c12e2a", color: SharedStyle.COLORS.white }; export default function FormDeleteButton(_ref) { var children = _ref.children, rest = _objectWithoutProperties(_ref, ['children']); return React.createElement( Button, _extends({ style: STYLE, styleHover: STYLE_HOVER }, rest), children ); }
vovance/3d-demo
es/components/style/delete-button.js
JavaScript
mit
1,078
import SWAGGER_CONFIG from './SWAGGER_CONFIG'; import swaggerToApiDoc from './swagger-to-api-doc'; Object.keys(SWAGGER_CONFIG).forEach((file) => { swaggerToApiDoc(file, SWAGGER_CONFIG[file].name, SWAGGER_CONFIG[file].path, SWAGGER_CONFIG[file].product); });
JeremyCraigMartinez/developer-dot
dynamic/build-all-pages.js
JavaScript
mit
263
/** @license React v16.10.1 * react-dom-unstable-native-dependencies.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var aa=require("react-dom"),h=require("object-assign");function k(a){for(var b=a.message,c="https://reactjs.org/docs/error-decoder.html?invariant="+b,d=1;d<arguments.length;d++)c+="&args[]="+encodeURIComponent(arguments[d]);a.message="Minified React error #"+b+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ";return a}var l=null,n=null,p=null; function r(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))throw k(Error(103));a.currentTarget=b?p(c):null;b=b?b(a):null;a.currentTarget=null;a._dispatchListeners=null;a._dispatchInstances=null;return b}function t(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}function u(a,b,c){for(var d=[];a;)d.push(a),a=t(a);for(a=d.length;0<a--;)b(d[a],"captured",c);for(a=0;a<d.length;a++)b(d[a],"bubbled",c)} function v(a,b){if(null==b)throw k(Error(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function w(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)} function x(a,b){var c=a.stateNode;if(!c)return null;var d=l(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw k(Error(231),b,typeof c); return c}function y(a,b,c){if(b=x(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=v(c._dispatchListeners,b),c._dispatchInstances=v(c._dispatchInstances,a)}function ba(a){a&&a.dispatchConfig.phasedRegistrationNames&&u(a._targetInst,y,a)}function ca(a){if(a&&a.dispatchConfig.phasedRegistrationNames){var b=a._targetInst;b=b?t(b):null;u(b,y,a)}} function z(a){if(a&&a.dispatchConfig.registrationName){var b=a._targetInst;if(b&&a&&a.dispatchConfig.registrationName){var c=x(b,a.dispatchConfig.registrationName);c&&(a._dispatchListeners=v(a._dispatchListeners,c),a._dispatchInstances=v(a._dispatchInstances,b))}}}function A(){return!0}function B(){return!1} function C(a,b,c,d){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var g in a)a.hasOwnProperty(g)&&((b=a[g])?this[g]=b(c):"target"===g?this.target=d:this[g]=c[g]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?A:B;this.isPropagationStopped=B;return this} h(C.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=A)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=A)},persist:function(){this.isPersistent=A},isPersistent:B,destructor:function(){var a=this.constructor.Interface,b;for(b in a)this[b]= null;this.nativeEvent=this._targetInst=this.dispatchConfig=null;this.isPropagationStopped=this.isDefaultPrevented=B;this._dispatchInstances=this._dispatchListeners=null}});C.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null}; C.extend=function(a){function b(){}function c(){return d.apply(this,arguments)}var d=this;b.prototype=d.prototype;var g=new b;h(g,c.prototype);c.prototype=g;c.prototype.constructor=c;c.Interface=h({},d.Interface,a);c.extend=d.extend;D(c);return c};D(C);function da(a,b,c,d){if(this.eventPool.length){var g=this.eventPool.pop();this.call(g,a,b,c,d);return g}return new this(a,b,c,d)} function ea(a){if(!(a instanceof this))throw k(Error(279));a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function D(a){a.eventPool=[];a.getPooled=da;a.release=ea}var E=C.extend({touchHistory:function(){return null}});function F(a){return"touchstart"===a||"mousedown"===a}function G(a){return"touchmove"===a||"mousemove"===a}function H(a){return"touchend"===a||"touchcancel"===a||"mouseup"===a} var I=["touchstart","mousedown"],J=["touchmove","mousemove"],K=["touchcancel","touchend","mouseup"],L=[],N={touchBank:L,numberActiveTouches:0,indexOfSingleActiveTouch:-1,mostRecentTimeStamp:0};function O(a){return a.timeStamp||a.timestamp}function P(a){a=a.identifier;if(null==a)throw k(Error(138));return a} function fa(a){var b=P(a),c=L[b];c?(c.touchActive=!0,c.startPageX=a.pageX,c.startPageY=a.pageY,c.startTimeStamp=O(a),c.currentPageX=a.pageX,c.currentPageY=a.pageY,c.currentTimeStamp=O(a),c.previousPageX=a.pageX,c.previousPageY=a.pageY,c.previousTimeStamp=O(a)):(c={touchActive:!0,startPageX:a.pageX,startPageY:a.pageY,startTimeStamp:O(a),currentPageX:a.pageX,currentPageY:a.pageY,currentTimeStamp:O(a),previousPageX:a.pageX,previousPageY:a.pageY,previousTimeStamp:O(a)},L[b]=c);N.mostRecentTimeStamp=O(a)} function ha(a){var b=L[P(a)];b?(b.touchActive=!0,b.previousPageX=b.currentPageX,b.previousPageY=b.currentPageY,b.previousTimeStamp=b.currentTimeStamp,b.currentPageX=a.pageX,b.currentPageY=a.pageY,b.currentTimeStamp=O(a),N.mostRecentTimeStamp=O(a)):console.warn("Cannot record touch move without a touch start.\nTouch Move: %s\n","Touch Bank: %s",Q(a),R())} function ia(a){var b=L[P(a)];b?(b.touchActive=!1,b.previousPageX=b.currentPageX,b.previousPageY=b.currentPageY,b.previousTimeStamp=b.currentTimeStamp,b.currentPageX=a.pageX,b.currentPageY=a.pageY,b.currentTimeStamp=O(a),N.mostRecentTimeStamp=O(a)):console.warn("Cannot record touch end without a touch start.\nTouch End: %s\n","Touch Bank: %s",Q(a),R())}function Q(a){return JSON.stringify({identifier:a.identifier,pageX:a.pageX,pageY:a.pageY,timestamp:O(a)})} function R(){var a=JSON.stringify(L.slice(0,20));20<L.length&&(a+=" (original size: "+L.length+")");return a} var S={recordTouchTrack:function(a,b){if(G(a))b.changedTouches.forEach(ha);else if(F(a))b.changedTouches.forEach(fa),N.numberActiveTouches=b.touches.length,1===N.numberActiveTouches&&(N.indexOfSingleActiveTouch=b.touches[0].identifier);else if(H(a)&&(b.changedTouches.forEach(ia),N.numberActiveTouches=b.touches.length,1===N.numberActiveTouches))for(a=0;a<L.length;a++)if(b=L[a],null!=b&&b.touchActive){N.indexOfSingleActiveTouch=a;break}},touchHistory:N}; function T(a,b){if(null==b)throw k(Error(334));return null==a?b:Array.isArray(a)?a.concat(b):Array.isArray(b)?[a].concat(b):[a,b]}var U=null,V=0;function W(a,b){var c=U;U=a;if(null!==X.GlobalResponderHandler)X.GlobalResponderHandler.onChange(c,a,b)} var Y={startShouldSetResponder:{phasedRegistrationNames:{bubbled:"onStartShouldSetResponder",captured:"onStartShouldSetResponderCapture"},dependencies:I},scrollShouldSetResponder:{phasedRegistrationNames:{bubbled:"onScrollShouldSetResponder",captured:"onScrollShouldSetResponderCapture"},dependencies:["scroll"]},selectionChangeShouldSetResponder:{phasedRegistrationNames:{bubbled:"onSelectionChangeShouldSetResponder",captured:"onSelectionChangeShouldSetResponderCapture"},dependencies:["selectionchange"]}, moveShouldSetResponder:{phasedRegistrationNames:{bubbled:"onMoveShouldSetResponder",captured:"onMoveShouldSetResponderCapture"},dependencies:J},responderStart:{registrationName:"onResponderStart",dependencies:I},responderMove:{registrationName:"onResponderMove",dependencies:J},responderEnd:{registrationName:"onResponderEnd",dependencies:K},responderRelease:{registrationName:"onResponderRelease",dependencies:K},responderTerminationRequest:{registrationName:"onResponderTerminationRequest",dependencies:[]}, responderGrant:{registrationName:"onResponderGrant",dependencies:[]},responderReject:{registrationName:"onResponderReject",dependencies:[]},responderTerminate:{registrationName:"onResponderTerminate",dependencies:[]}},X={_getResponder:function(){return U},eventTypes:Y,extractEvents:function(a,b,c,d,g){if(F(a))V+=1;else if(H(a))if(0<=V)--V;else return console.warn("Ended a touch event which was not counted in `trackedTouchCount`."),null;S.recordTouchTrack(a,d);if(c&&("scroll"===a&&!d.responderIgnoreScroll|| 0<V&&"selectionchange"===a||F(a)||G(a))){b=F(a)?Y.startShouldSetResponder:G(a)?Y.moveShouldSetResponder:"selectionchange"===a?Y.selectionChangeShouldSetResponder:Y.scrollShouldSetResponder;if(U)b:{var e=U;for(var f=0,q=e;q;q=t(q))f++;q=0;for(var M=c;M;M=t(M))q++;for(;0<f-q;)e=t(e),f--;for(;0<q-f;)c=t(c),q--;for(;f--;){if(e===c||e===c.alternate)break b;e=t(e);c=t(c)}e=null}else e=c;c=e===U;e=E.getPooled(b,e,d,g);e.touchHistory=S.touchHistory;c?w(e,ca):w(e,ba);b:{b=e._dispatchListeners;c=e._dispatchInstances; if(Array.isArray(b))for(f=0;f<b.length&&!e.isPropagationStopped();f++){if(b[f](e,c[f])){b=c[f];break b}}else if(b&&b(e,c)){b=c;break b}b=null}e._dispatchInstances=null;e._dispatchListeners=null;e.isPersistent()||e.constructor.release(e);if(b&&b!==U)if(e=E.getPooled(Y.responderGrant,b,d,g),e.touchHistory=S.touchHistory,w(e,z),c=!0===r(e),U)if(f=E.getPooled(Y.responderTerminationRequest,U,d,g),f.touchHistory=S.touchHistory,w(f,z),q=!f._dispatchListeners||r(f),f.isPersistent()||f.constructor.release(f), q){f=E.getPooled(Y.responderTerminate,U,d,g);f.touchHistory=S.touchHistory;w(f,z);var m=T(m,[e,f]);W(b,c)}else b=E.getPooled(Y.responderReject,b,d,g),b.touchHistory=S.touchHistory,w(b,z),m=T(m,b);else m=T(m,e),W(b,c);else m=null}else m=null;b=U&&F(a);e=U&&G(a);c=U&&H(a);if(b=b?Y.responderStart:e?Y.responderMove:c?Y.responderEnd:null)b=E.getPooled(b,U,d,g),b.touchHistory=S.touchHistory,w(b,z),m=T(m,b);b=U&&"touchcancel"===a;if(a=U&&!b&&H(a))a:{if((a=d.touches)&&0!==a.length)for(e=0;e<a.length;e++)if(c= a[e].target,null!==c&&void 0!==c&&0!==c){f=n(c);b:{for(c=U;f;){if(c===f||c===f.alternate){c=!0;break b}f=t(f)}c=!1}if(c){a=!1;break a}}a=!0}if(a=b?Y.responderTerminate:a?Y.responderRelease:null)d=E.getPooled(a,U,d,g),d.touchHistory=S.touchHistory,w(d,z),m=T(m,d),W(null);return m},GlobalResponderHandler:null,injection:{injectGlobalResponderHandler:function(a){X.GlobalResponderHandler=a}}},Z=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events,ja=Z[3],ka=Z[0],la=Z[1];l=Z[2];n=ka;p=la; module.exports={ResponderEventPlugin:X,ResponderTouchHistoryStore:S,injectEventPluginsByName:ja};
extend1994/cdnjs
ajax/libs/react-dom/16.10.1/cjs/react-dom-unstable-native-dependencies.production.min.js
JavaScript
mit
10,730
#!/usr/bin/env node // Based on CoffeeScript by andrewschaaf on github // // TODO: // - past and future dates, especially < 1900 and > 2100 // - locales // - look for edge cases var assert = require('assert') , libFilename = process.argv[2] || '../strftime.js' , lib = require(libFilename) // Tue, 07 Jun 2011 18:51:45 GMT , Time = new Date(1307472705067) assert.fn = function(value, msg) { assert.equal('function', typeof value, msg) } assert.format = function(format, expected, expectedUTC, time) { time = time || Time function _assertFmt(expected, name) { name = name || 'strftime' var actual = lib[name](format, time) assert.equal(expected, actual, name + '("' + format + '", ' + time + ') is ' + JSON.stringify(actual) + ', expected ' + JSON.stringify(expected)) } if (expected) _assertFmt(expected, 'strftime') _assertFmt(expectedUTC || expected, 'strftimeUTC') } /// check exports assert.fn(lib.strftime) assert.fn(lib.strftimeUTC) assert.fn(lib.localizedStrftime) ok('Exports') /// time zones if (process.env.TZ == 'America/Vancouver') { testTimezone('P[DS]T') assert.format('%C', '01', '01', new Date(100, 0, 1)) assert.format('%j', '097', '098', new Date(1365390736236)) ok('Time zones (' + process.env.TZ + ')') } else if (process.env.TZ == 'CET') { testTimezone('CES?T') assert.format('%C', '01', '00', new Date(100, 0, 1)) assert.format('%j', '098', '098', new Date(1365390736236)) ok('Time zones (' + process.env.TZ + ')') } else { console.log('(Current timezone has no tests: ' + (process.env.TZ || 'none') + ')') } /// check all formats in GMT, most coverage assert.format('%A', 'Tuesday') assert.format('%a', 'Tue') assert.format('%B', 'June') assert.format('%b', 'Jun') assert.format('%C', '20') assert.format('%D', '06/07/11') assert.format('%d', '07') assert.format('%-d', '7') assert.format('%_d', ' 7') assert.format('%0d', '07') assert.format('%e', '7') assert.format('%F', '2011-06-07') assert.format('%H', null, '18') assert.format('%h', 'Jun') assert.format('%I', null, '06') assert.format('%-I', null, '6') assert.format('%_I', null, ' 6') assert.format('%0I', null, '06') assert.format('%j', null, '158') assert.format('%k', null, '18') assert.format('%L', '067') assert.format('%l', null, ' 6') assert.format('%-l', null, '6') assert.format('%_l', null, ' 6') assert.format('%0l', null, '06') assert.format('%M', null, '51') assert.format('%m', '06') assert.format('%n', '\n') assert.format('%o', '7th') assert.format('%P', null, 'pm') assert.format('%p', null, 'PM') assert.format('%R', null, '18:51') assert.format('%r', null, '06:51:45 PM') assert.format('%S', '45') assert.format('%s', '1307472705') assert.format('%T', null, '18:51:45') assert.format('%t', '\t') assert.format('%U', '23') assert.format('%U', '24', null, new Date(+Time + 5 * 86400000)) assert.format('%u', '2') assert.format('%v', '7-Jun-2011') assert.format('%W', '23') assert.format('%W', '23', null, new Date(+Time + 5 * 86400000)) assert.format('%w', '2') assert.format('%Y', '2011') assert.format('%y', '11') assert.format('%Z', null, 'GMT') assert.format('%z', null, '+0000') assert.format('%%', '%') // any other char ok('GMT') /// locales var it_IT = { days: words('domenica lunedi martedi mercoledi giovedi venerdi sabato') , shortDays: words('dom lun mar mer gio ven sab') , months: words('gennaio febbraio marzo aprile maggio giugno luglio agosto settembre ottobre novembre dicembre') , shortMonths: words('gen feb mar apr mag giu lug ago set ott nov dic') , AM: 'it$AM' , PM: 'it$PM' , am: 'it$am' , pm: 'it$pm' , formats: { D: 'it$%m/%d/%y' , F: 'it$%Y-%m-%d' , R: 'it$%H:%M' , r: 'it$%I:%M:%S %p' , T: 'it$%H:%M:%S' , v: 'it$%e-%b-%Y' } } assert.format_it = function(format, expected, expectedUTC) { function _assertFmt(expected, name) { name = name || 'strftime' var actual = lib[name](format, Time, it_IT) assert.equal(expected, actual, name + '("' + format + '", Time) is ' + JSON.stringify(actual) + ', expected ' + JSON.stringify(expected)) } if (expected) _assertFmt(expected, 'strftime') _assertFmt(expectedUTC || expected, 'strftimeUTC') } assert.format_it('%A', 'martedi') assert.format_it('%a', 'mar') assert.format_it('%B', 'giugno') assert.format_it('%b', 'giu') assert.format_it('%D', 'it$06/07/11') assert.format_it('%F', 'it$2011-06-07') assert.format_it('%p', null, 'it$PM') assert.format_it('%P', null, 'it$pm') assert.format_it('%R', null, 'it$18:51') assert.format_it('%r', null, 'it$06:51:45 it$PM') assert.format_it('%T', null, 'it$18:51:45') assert.format_it('%v', 'it$7-giu-2011') ok('Localization') /// timezones assert.formatTZ = function(format, expected, tz, time) { time = time || Time; var actual = lib.strftimeTZ(format, time, tz) assert.equal( expected, actual, ('strftime("' + format + '", ' + time + ') is ' + JSON.stringify(actual) + ', expected ' + JSON.stringify(expected)) ) } assert.formatTZ('%F %r %z', '2011-06-07 06:51:45 PM +0000', 0) assert.formatTZ('%F %r %z', '2011-06-07 06:51:45 PM +0000', '+0000') assert.formatTZ('%F %r %z', '2011-06-07 08:51:45 PM +0200', 120) assert.formatTZ('%F %r %z', '2011-06-07 08:51:45 PM +0200', '+0200') assert.formatTZ('%F %r %z', '2011-06-07 11:51:45 AM -0700', -420) assert.formatTZ('%F %r %z', '2011-06-07 11:51:45 AM -0700', '-0700') ok('Time zone offset') /// helpers function words(s) { return (s || '').split(' '); } function ok(s) { console.log('[ \033[32mOK\033[0m ] ' + s) } // Pass a regex or string that matches the timezone abbrev, e.g. %Z above. // Don't pass GMT! Every date includes it and it will fail. // Be careful if you pass a regex, it has to quack like the default one. function testTimezone(regex) { regex = typeof regex === 'string' ? RegExp('\\((' + regex + ')\\)$') : regex var match = Time.toString().match(regex) if (match) { var off = Time.getTimezoneOffset() , hourOff = off / 60 , hourDiff = Math.floor(hourOff) , hours = 18 - hourDiff , padSpace24 = hours < 10 ? ' ' : '' , padZero24 = hours < 10 ? '0' : '' , hour24 = String(hours) , padSpace12 = (hours % 12) < 10 ? ' ' : '' , padZero12 = (hours % 12) < 10 ? '0' : '' , hour12 = String(hours % 12) , sign = hourDiff < 0 ? '+' : '-' , minDiff = Time.getTimezoneOffset() - (hourDiff * 60) , mins = String(51 - minDiff) , tz = match[1] , ampm = hour12 == hour24 ? 'AM' : 'PM' , R = hour24 + ':' + mins , r = padZero12 + hour12 + ':' + mins + ':45 ' + ampm , T = R + ':45' assert.format('%H', padZero24 + hour24, '18') assert.format('%I', padZero12 + hour12, '06') assert.format('%k', padSpace24 + hour24, '18') assert.format('%l', padSpace12 + hour12, ' 6') assert.format('%M', mins) assert.format('%P', ampm.toLowerCase(), 'pm') assert.format('%p', ampm, 'PM') assert.format('%R', R, '18:51') assert.format('%r', r, '06:51:45 PM') assert.format('%T', T, '18:51:45') assert.format('%Z', tz, 'GMT') assert.format('%z', sign + '0' + Math.abs(hourDiff) + '00', '+0000') } }
SimonWallner/space-walk
tools/recorder/node_modules/strftime/test/test.js
JavaScript
mit
7,203
import Checkbox from './src/checkbox.vue'; export default Checkbox;
xiayuxiaoyan/xcui
src/components/checkbox/index.js
JavaScript
mit
68
import React from 'react'; import FontAwesomeIcon from '@fortawesome/react-fontawesome'; import faCheck from '@fortawesome/fontawesome-free-solid/faCheck'; import LinkButton from 'shared/components/linkButton/linkButton'; import Section from 'shared/components/section/section'; import styles from '../getInvolved.css'; const Volunteer = () => ( <Section title="Become a Volunteer"> <div className={styles.wrapper}> <div className={styles.half}> <ul className={styles.list}> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> Join our community on Slack, and work with new software developers to help grow and mentor them in learning to code and enter the tech industry. Answer questions, participate in mock interviews, and review resumes. </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> Lead a squad of new developers in learning new skills in Linux, Python, cloud infrastructure, web development, and more. </p> </li> <li className={styles.listItem}> <FontAwesomeIcon icon={faCheck} size="2x" /> <p className={styles.itemText}> Meet up with a local chapter (or start your own!) and network with other new developers eager to build cool apps and code the future! </p> </li> </ul> </div> <div className={styles.halfPhotoWrapper}> <img src="https://s3.amazonaws.com/operationcode-assets/page-get_involved/hackathon1.jpg" alt="Operation Code Members at Operation Spark" className={styles.photo} /> </div> </div> <div className={styles.button}> <LinkButton text="Volunteer" theme="red" link="/signup" /> </div> </Section> ); export default Volunteer;
sethbergman/operationcode_frontend
src/scenes/home/getInvolved/volunteer/volunteer.js
JavaScript
mit
2,077
const getFiltersOnStringList = require('./getFiltersOnStringList') const getCausesFilters = causes => getFiltersOnStringList( 'causes.id', causes, ) module.exports = getCausesFilters
tithebarn/charity-base
graphql/resolvers/query/CHC/getCharities/elastic-query/causes.js
JavaScript
mit
189
'use strict'; /** * @ngdoc directive * @name ng.directive:ngSwitch * @restrict EA * * @description * Conditionally change the DOM structure. * * @usageContent * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * ... * <ANY ng-switch-default>...</ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elments add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. * * `ngSwitchDefault`: the default case when no other casses match. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </script> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div ng-switch on="selection" > <div ng-switch-when="settings">Settings Div</div> <span ng-switch-when="home">Home Span</span> <span ng-switch-default>default</span> </div> </div> </doc:source> <doc:scenario> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select deafault', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </doc:scenario> </doc:example> */ var NG_SWITCH = 'ng-switch'; var ngSwitchDirective = valueFn({ restrict: 'EA', compile: function(element, attr) { var watchExpr = attr.ngSwitch || attr.on, cases = {}; element.data(NG_SWITCH, cases); return function(scope, element){ var selectedTransclude, selectedElement, selectedScope; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { if (selectedElement) { selectedScope.$destroy(); selectedElement.remove(); selectedElement = selectedScope = null; } if ((selectedTransclude = cases['!' + value] || cases['?'])) { scope.$eval(attr.change); selectedScope = scope.$new(); selectedTransclude(selectedScope, function(caseElement) { selectedElement = caseElement; element.append(caseElement); }); } }); }; } }); var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['!' + attrs.ngSwitchWhen] = transclude; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, compile: function(element, attrs, transclude) { var cases = element.inheritedData(NG_SWITCH); assertArg(cases); cases['?'] = transclude; } });
christianv/angular.js
src/ng/directive/ngSwitch.js
JavaScript
mit
3,358
const kelda = require('kelda'); const hap = require('@kelda/haproxy'); const infrastructure = require('../../config/infrastructure.js'); const indexPath = '/usr/share/nginx/html/index.html'; /** * Returns a new Container whose index file contains the given content. * @param {string} content - The contents to put in the container's index file. * @returns {Container} - A container with given content in its index file. */ function containerWithContent(content) { return new kelda.Container({ name: 'web', image: 'nginx', filepathToContent: { [indexPath]: content }, }); } const serviceA = [ containerWithContent('a1'), containerWithContent('a2'), ]; const serviceB = [ containerWithContent('b1'), containerWithContent('b2'), containerWithContent('b3'), ]; const proxy = hap.withURLrouting({ 'serviceB.com': serviceB, 'serviceA.com': serviceA, }); kelda.allowTraffic(kelda.publicInternet, proxy, 80); const inf = infrastructure.createTestInfrastructure(); serviceA.forEach(container => container.deploy(inf)); serviceB.forEach(container => container.deploy(inf)); proxy.deploy(inf);
kelda/kelda
integration-tester/tests/haproxy/haproxy.js
JavaScript
mit
1,124
var expect = require('chai').expect, sinon = require('sinon'), inherits = require('util').inherits, NodeInspectorWrapper = require('../../../../lib/daemon/inspector/NodeInspectorWrapper') describe('NodeInspectorWrapper', function () { var wrapper beforeEach(function () { wrapper = new NodeInspectorWrapper() wrapper._child_process = { fork: sinon.stub() } wrapper._config = { remote: { inspector: { enabled: true } } } wrapper._logger = { info: function () { }, warn: function () { }, error: function () { }, debug: function () { } } }) it('should not start node-inspector when it is not enabled', function (done) { wrapper._config.remote.inspector.enabled = false wrapper.afterPropertiesSet(function () { expect(wrapper._child_process.fork.callCount).to.equal(0) done() }) }) it('should start node-inspector and inform the callback of the port', function (done) { var debugPort = 5 var child = { on: sinon.stub(), removeAllListeners: sinon.stub(), kill: sinon.stub() } wrapper._child_process.fork.returns(child) wrapper.afterPropertiesSet(function (error) { expect(error).to.not.exist expect(wrapper.debuggerPort).to.equal(debugPort) expect(child.on.callCount).to.equal(3) expect(child.on.getCall(0).args[0]).to.equal('message') done() }) child.on.getCall(0).args[1]({ event: 'node-inspector:ready', args: [debugPort] }) }) it('should report error when starting node-inspector', function (done) { var child = { on: sinon.stub(), removeAllListeners: sinon.stub(), kill: sinon.stub() } wrapper._child_process.fork.returns(child) var startupError = new Error() wrapper.afterPropertiesSet(function (error) { expect(error.message).to.equal(startupError.message) expect(error.stack).to.equal(startupError.stack) expect(child.on.callCount).to.equal(3) expect(child.on.getCall(0).args[0]).to.equal('message') done() }) child.on.getCall(0).args[1]({ event: 'node-inspector:failed', args: [startupError] }) }) it('should report error when starting node-inspector fails', function (done) { var child = { on: sinon.stub(), removeAllListeners: sinon.stub(), kill: sinon.stub() } wrapper._child_process.fork.returns(child) var startupError = new Error() wrapper.afterPropertiesSet(function (error) { expect(error.message).to.equal(startupError.message) expect(error.stack).to.equal(startupError.stack) expect(child.on.callCount).to.equal(3) expect(child.on.getCall(1).args[0]).to.equal('error') done() }) child.on.getCall(1).args[1](startupError) }) it('should report error when starting node-inspector exits before starting', function (done) { var child = { on: sinon.stub(), removeAllListeners: sinon.stub(), kill: sinon.stub() } wrapper._child_process.fork.returns(child) wrapper.afterPropertiesSet(function (error) { expect(error.message).to.contain('1') expect(child.on.callCount).to.equal(3) expect(child.on.getCall(2).args[0]).to.equal('exit') done() }) child.on.getCall(2).args[1](1) }) it('should restart node-inspector when it fails', function (done) { var child = { on: sinon.stub(), removeAllListeners: sinon.stub(), kill: sinon.stub() } wrapper._child_process.fork.returns(child) wrapper._startNodeInspector() expect(child.on.callCount).to.equal(3) expect(child.on.getCall(0).args[0]).to.equal('message') expect(child.on.getCall(1).args[0]).to.equal('error') expect(child.on.getCall(2).args[0]).to.equal('exit') expect(wrapper._child_process.fork.callCount).to.equal(1) // invoke exit callback child.on.getCall(2).args[1](5) process.nextTick(function () { expect(wrapper._child_process.fork.callCount).to.equal(2) done() }) }) it('should restart node-inspector only once when it errors and exits', function (done) { var child = { on: sinon.stub(), removeAllListeners: sinon.stub(), kill: sinon.stub() } wrapper._child_process.fork.returns(child) wrapper._startNodeInspector() expect(child.on.callCount).to.equal(3) expect(child.on.getCall(0).args[0]).to.equal('message') expect(child.on.getCall(1).args[0]).to.equal('error') expect(child.on.getCall(2).args[0]).to.equal('exit') expect(wrapper._child_process.fork.callCount).to.equal(1) // invoke error callback child.on.getCall(1).args[1](new Error('Aargh!')) // invoke exit callback child.on.getCall(2).args[1](5) process.nextTick(function () { expect(wrapper._child_process.fork.callCount).to.equal(2) done() }) }) it('should stop node-inspector', function () { var child = { removeAllListeners: sinon.stub(), kill: sinon.stub() } var wrapper = new NodeInspectorWrapper() wrapper._child = child wrapper.stopNodeInspector() expect(child.removeAllListeners.withArgs('error').called).to.be.true expect(child.removeAllListeners.withArgs('exit').called).to.be.true expect(child.kill.called).to.be.true expect(wrapper._child).to.not.exist }) it('should suvive stop node-inspector when not started', function () { var wrapper = new NodeInspectorWrapper() wrapper.stopNodeInspector() }) })
tableflip/guvnor
test/lib/daemon/inspector/NodeInspectorWrapperTest.js
JavaScript
mit
5,633
/** * General-purpose jQuery wrapper. Simply pass the plugin name as the expression. * * It is possible to specify a default set of parameters for each jQuery plugin. * Under the jq key, namespace each plugin by that which will be passed to ui-jq. * Unfortunately, at this time you can only pre-define the first parameter. * @example { jq : { datepicker : { showOn:'click' } } } * * @param ui-jq {string} The $elm.[pluginName]() to call. * @param [ui-options] {mixed} Expression to be evaluated and passed as options to the function * Multiple parameters can be separated by commas * @param [ui-refresh] {expression} Watch expression and refire plugin on changes * * @example <input ui-jq="datepicker" ui-options="{showOn:'click'},secondParameter,thirdParameter" ui-refresh="iChange"> */ angular.module('ui.jq',[]). value('uiJqConfig',{}). directive('uiJq', ['uiJqConfig', '$timeout', function uiJqInjectingFunction(uiJqConfig, $timeout) { 'use strict'; return { restrict: 'A', compile: function uiJqCompilingFunction(tElm, tAttrs) { if (!angular.isFunction(tElm[tAttrs.uiJq])) { throw new Error('ui-jq: The "' + tAttrs.uiJq + '" function does not exist'); } var options = uiJqConfig && uiJqConfig[tAttrs.uiJq]; return function uiJqLinkingFunction(scope, elm, attrs) { var linkOptions = []; // If ui-options are passed, merge (or override) them onto global defaults and pass to the jQuery method if (attrs.uiOptions) { linkOptions = scope.$eval('[' + attrs.uiOptions + ']'); if (angular.isObject(options) && angular.isObject(linkOptions[0])) { linkOptions[0] = angular.extend({}, options, linkOptions[0]); } } else if (options) { linkOptions = [options]; } // If change compatibility is enabled, the form input's "change" event will trigger an "input" event if (attrs.ngModel && elm.is('select,input,textarea')) { elm.bind('change', function() { elm.trigger('input'); }); } // Call jQuery method and pass relevant options function callPlugin() { $timeout(function() { elm[attrs.uiJq].apply(elm, linkOptions); }, 0, false); } // If ui-refresh is used, re-fire the the method upon every change if (attrs.uiRefresh) { scope.$watch(attrs.uiRefresh, function() { callPlugin(); }); } callPlugin(); }; } }; }]);
mithundas79/angularTemplateSample
vendor/ui-utils/jq/jq.js
JavaScript
mit
2,559
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require("@angular/core"); var http_1 = require("@angular/http"); var Observable_1 = require("rxjs/Observable"); require("rxjs/add/observable/fromPromise"); require("rxjs/add/operator/mergeMap"); var AuthConfigConsts = (function () { function AuthConfigConsts() { } return AuthConfigConsts; }()); AuthConfigConsts.DEFAULT_TOKEN_NAME = 'id_token'; AuthConfigConsts.DEFAULT_HEADER_NAME = 'Authorization'; AuthConfigConsts.HEADER_PREFIX_BEARER = 'Bearer '; exports.AuthConfigConsts = AuthConfigConsts; var AuthConfigDefaults = { headerName: AuthConfigConsts.DEFAULT_HEADER_NAME, headerPrefix: null, tokenName: AuthConfigConsts.DEFAULT_TOKEN_NAME, tokenGetter: function () { return localStorage.getItem(AuthConfigDefaults.tokenName); }, noJwtError: false, noClientCheck: false, globalHeaders: [], noTokenScheme: false }; /** * Sets up the authentication configuration. */ var AuthConfig = (function () { function AuthConfig(config) { config = config || {}; this._config = objectAssign({}, AuthConfigDefaults, config); if (this._config.headerPrefix) { this._config.headerPrefix += ' '; } else if (this._config.noTokenScheme) { this._config.headerPrefix = ''; } else { this._config.headerPrefix = AuthConfigConsts.HEADER_PREFIX_BEARER; } if (config.tokenName && !config.tokenGetter) { this._config.tokenGetter = function () { return localStorage.getItem(config.tokenName); }; } } AuthConfig.prototype.getConfig = function () { return this._config; }; return AuthConfig; }()); exports.AuthConfig = AuthConfig; var AuthHttpError = (function (_super) { __extends(AuthHttpError, _super); function AuthHttpError() { return _super.apply(this, arguments) || this; } return AuthHttpError; }(Error)); exports.AuthHttpError = AuthHttpError; /** * Allows for explicit authenticated HTTP requests. */ var AuthHttp = (function () { function AuthHttp(options, http, defOpts) { var _this = this; this.http = http; this.defOpts = defOpts; this.config = options.getConfig(); this.tokenStream = new Observable_1.Observable(function (obs) { obs.next(_this.config.tokenGetter()); }); } AuthHttp.prototype.mergeOptions = function (providedOpts, defaultOpts) { var newOptions = defaultOpts || new http_1.RequestOptions(); if (this.config.globalHeaders) { this.setGlobalHeaders(this.config.globalHeaders, providedOpts); } newOptions = newOptions.merge(new http_1.RequestOptions(providedOpts)); return newOptions; }; AuthHttp.prototype.requestHelper = function (requestArgs, additionalOptions) { var options = new http_1.RequestOptions(requestArgs); if (additionalOptions) { options = options.merge(additionalOptions); } return this.request(new http_1.Request(this.mergeOptions(options, this.defOpts))); }; AuthHttp.prototype.requestWithToken = function (req, token) { if (!this.config.noClientCheck && !tokenNotExpired(undefined, token)) { if (!this.config.noJwtError) { return new Observable_1.Observable(function (obs) { obs.error(new AuthHttpError('No JWT present or has expired')); }); } } else { req.headers.set(this.config.headerName, this.config.headerPrefix + token); } return this.http.request(req); }; AuthHttp.prototype.setGlobalHeaders = function (headers, request) { if (!request.headers) { request.headers = new http_1.Headers(); } headers.forEach(function (header) { var key = Object.keys(header)[0]; var headerValue = header[key]; request.headers.set(key, headerValue); }); }; AuthHttp.prototype.request = function (url, options) { var _this = this; if (typeof url === 'string') { return this.get(url, options); // Recursion: transform url from String to Request } // else if ( ! url instanceof Request ) { // throw new Error('First argument must be a url string or Request instance.'); // } // from this point url is always an instance of Request; var req = url; var token = this.config.tokenGetter(); if (token instanceof Promise) { return Observable_1.Observable.fromPromise(token).mergeMap(function (jwtToken) { return _this.requestWithToken(req, jwtToken); }); } else { return this.requestWithToken(req, token); } }; AuthHttp.prototype.get = function (url, options) { return this.requestHelper({ body: '', method: http_1.RequestMethod.Get, url: url }, options); }; AuthHttp.prototype.post = function (url, body, options) { return this.requestHelper({ body: body, method: http_1.RequestMethod.Post, url: url }, options); }; AuthHttp.prototype.put = function (url, body, options) { return this.requestHelper({ body: body, method: http_1.RequestMethod.Put, url: url }, options); }; AuthHttp.prototype.delete = function (url, options) { return this.requestHelper({ body: '', method: http_1.RequestMethod.Delete, url: url }, options); }; AuthHttp.prototype.patch = function (url, body, options) { return this.requestHelper({ body: body, method: http_1.RequestMethod.Patch, url: url }, options); }; AuthHttp.prototype.head = function (url, options) { return this.requestHelper({ body: '', method: http_1.RequestMethod.Head, url: url }, options); }; AuthHttp.prototype.options = function (url, options) { return this.requestHelper({ body: '', method: http_1.RequestMethod.Options, url: url }, options); }; return AuthHttp; }()); AuthHttp = __decorate([ core_1.Injectable(), __metadata("design:paramtypes", [AuthConfig, http_1.Http, http_1.RequestOptions]) ], AuthHttp); exports.AuthHttp = AuthHttp; /** * Helper class to decode and find JWT expiration. */ var JwtHelper = (function () { function JwtHelper() { } JwtHelper.prototype.urlBase64Decode = function (str) { var output = str.replace(/-/g, '+').replace(/_/g, '/'); switch (output.length % 4) { case 0: { break; } case 2: { output += '=='; break; } case 3: { output += '='; break; } default: { throw 'Illegal base64url string!'; } } return this.b64DecodeUnicode(output); }; // credits for decoder goes to https://github.com/atk JwtHelper.prototype.b64decode = function (str) { var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; var output = ''; str = String(str).replace(/=+$/, ''); if (str.length % 4 == 1) { throw new Error("'atob' failed: The string to be decoded is not correctly encoded."); } for ( // initialize result and counters var bc = 0, bs = void 0, buffer = void 0, idx = 0; // get next character buffer = str.charAt(idx++); // character found in table? initialize bit storage and add its ascii value; ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, // and if not first of each 4 characters, // convert the first 8 bits to one ascii character bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) { // try to find character in table (0-63, not found => -1) buffer = chars.indexOf(buffer); } return output; }; // https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem JwtHelper.prototype.b64DecodeUnicode = function (str) { return decodeURIComponent(Array.prototype.map.call(this.b64decode(str), function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); }; JwtHelper.prototype.decodeToken = function (token) { var parts = token.split('.'); if (parts.length !== 3) { throw new Error('JWT must have 3 parts'); } var decoded = this.urlBase64Decode(parts[1]); if (!decoded) { throw new Error('Cannot decode the token'); } return JSON.parse(decoded); }; JwtHelper.prototype.getTokenExpirationDate = function (token) { var decoded; decoded = this.decodeToken(token); if (!decoded.hasOwnProperty('exp')) { return null; } var date = new Date(0); // The 0 here is the key, which sets the date to the epoch date.setUTCSeconds(decoded.exp); return date; }; JwtHelper.prototype.isTokenExpired = function (token, offsetSeconds) { var date = this.getTokenExpirationDate(token); offsetSeconds = offsetSeconds || 0; if (date == null) { return false; } // Token expired? return !(date.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000))); }; return JwtHelper; }()); exports.JwtHelper = JwtHelper; /** * Checks for presence of token and that token hasn't expired. * For use with the @CanActivate router decorator and NgIf */ function tokenNotExpired(tokenName, jwt) { if (tokenName === void 0) { tokenName = AuthConfigConsts.DEFAULT_TOKEN_NAME; } var token = jwt || localStorage.getItem(tokenName); var jwtHelper = new JwtHelper(); return token != null && !jwtHelper.isTokenExpired(token); } exports.tokenNotExpired = tokenNotExpired; exports.AUTH_PROVIDERS = [ { provide: AuthHttp, deps: [http_1.Http, http_1.RequestOptions], useFactory: function (http, options) { return new AuthHttp(new AuthConfig(), http, options); } } ]; function provideAuth(config) { return [ { provide: AuthHttp, deps: [http_1.Http, http_1.RequestOptions], useFactory: function (http, options) { return new AuthHttp(new AuthConfig(config), http, options); } } ]; } exports.provideAuth = provideAuth; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function objectAssign(target) { var source = []; for (var _i = 1; _i < arguments.length; _i++) { source[_i - 1] = arguments[_i]; } var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; } //# sourceMappingURL=angular2-jwt.js.map
k3ralas/it-network-app
node_modules/angular2-jwt/angular2-jwt.js
JavaScript
mit
12,701
/* * WellCommerce Open-Source E-Commerce Platform * * This file is part of the WellCommerce package. * * (c) Adam Piotrowski <adam@wellcommerce.org> * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ var GFormDependency = function(sType, sFieldSource, mCondition, mArgument) { var gThis = this; gThis.m_iId; gThis.m_sType = sType; gThis.m_gForm; gThis.m_sFieldSource = sFieldSource; gThis.m_sFieldTarget; gThis.m_mArgument = mArgument; if (mCondition instanceof GFormCondition) { gThis.m_gCondition = mCondition; } else { gThis.m_fSource = mCondition; } gThis.Constructor = function(gForm, sFieldTarget) { gThis.m_iId = GFormDependency.s_iNextId++; gThis.m_gForm = gForm; gThis.m_sFieldTarget = sFieldTarget; gThis._InitializeEvents(); }; gThis._InitializeEvents = function() { var gFieldTarget = gThis.m_gForm.GetField(gThis.m_sFieldTarget); var fHandler; switch (gThis.m_sType) { case GFormDependency.HIDE: fHandler = gThis.EvaluateHide; break; case GFormDependency.SHOW: fHandler = gThis.EvaluateShow; break; case GFormDependency.IGNORE: fHandler = gThis.EvaluateIgnore; break; case GFormDependency.SUGGEST: fHandler = gThis.EvaluateSuggest; break; case GFormDependency.INVOKE_CUSTOM_FUNCTION: fHandler = gThis.EvaluateInvoke; break; case GFormDependency.EXCHANGE_OPTIONS: fHandler = gThis.EvaluateExchangeOptions; break; default: return; } var bAlreadyInitialised = false; if (!gFieldTarget.m_oInitializedDependencies[gThis.m_iId]) { var gField = gThis.m_gForm.GetFieldForForm(gThis.m_sFieldSource); gField.BindChangeHandler(fHandler, { gNode: gField, }); gField.m_afDependencyTriggers.push(fHandler); gFieldTarget.m_oInitializedDependencies[gThis.m_iId] = true; bAlreadyInitialised = true; } if (!bAlreadyInitialised || (gThis.m_sType !== GFormDependency.EXCHANGE_OPTIONS)) { fHandler.apply(gThis.m_gForm.GetFieldForForm(gThis.m_sFieldSource).m_jField); } if (gThis.m_sType === GFormDependency.EXCHANGE_OPTIONS) { gField.TriggerChangeHandler(); } }; gThis.EvaluateShow = function(eEvent) { var gCurrentField, gDependentField; if (eEvent === undefined) { eEvent = {data: {gNode: $(this).closest('.GFormNode').get(0).gNode}}; } gCurrentField = eEvent.data.gNode; gDependentField = gThis._FindFieldInCurrentRepetition(gCurrentField, gThis.m_gForm.GetFieldForForm(gThis.m_sFieldTarget)); if ((gCurrentField.m_gParent instanceof GFormRepeatableFieldset) && (gCurrentField.m_gParent === gDependentField.m_gParent)) { gDependentField = gDependentField; } if (gThis.Evaluate(gCurrentField.GetValue())) { gDependentField.Show(); } else { gDependentField.Hide(); } }; gThis.EvaluateHide = function(eEvent) { var gCurrentField, gDependentField; if (eEvent === undefined) { eEvent = {data: {gNode: $(this).closest('.GFormNode').get(0).gNode}}; } gCurrentField = eEvent.data.gNode; gDependentField = gThis._FindFieldInCurrentRepetition(gCurrentField, gThis.m_gForm.GetFieldForForm(gThis.m_sFieldTarget)); if (gThis.Evaluate(gCurrentField.GetValue())) { gDependentField.Hide(); } else { gDependentField.Show(); } }; gThis._FindFieldInCurrentRepetition = function(gCurrentField, gDependentField) { if ((gCurrentField.m_gParent instanceof GFormRepetition) && (gCurrentField.m_gParent.m_gParent === gDependentField.m_gParent.m_gParent)) { for (var i in gCurrentField.m_gParent.m_agFields) { var gField = gCurrentField.m_gParent.m_agFields[i]; if (gField.m_oOptions.sName === gThis.m_sFieldTarget) { return gField; } } } return gDependentField; }; gThis.EvaluateIgnore = function(eEvent) { var gCurrentField, gDependentField; if (eEvent === undefined) { eEvent = {data: {gNode: $(this).closest('.GFormNode').get(0).gNode}}; } gCurrentField = eEvent.data.gNode; gDependentField = gThis._FindFieldInCurrentRepetition(gCurrentField, gThis.m_gForm.GetFieldForForm(gThis.m_sFieldTarget)); if (gThis.Evaluate(gCurrentField.GetValue())) { gDependentField.Ignore(); } else { gDependentField.Unignore(); } }; gThis.EvaluateInvoke = function(eEvent) { if (eEvent === undefined) { eEvent = { data: { gNode: $(this).closest('.GFormNode').get(0).gNode, mArgument: gThis.m_mArgument, }, }; } gThis.m_fSource({ sValue: eEvent.data.gNode.GetValue(), gForm: gThis.m_gForm, sFieldTarget: gThis.m_sFieldTarget, mArgument: gThis.m_mArgument, }); }; gThis.EvaluateSuggest = function(eEvent) { var gCurrentField, gDependentField; if (eEvent === undefined) { eEvent = {data: {gNode: $(this).closest('.GFormNode').get(0).gNode}}; } gCurrentField = eEvent.data.gNode; gDependentField = gThis._FindFieldInCurrentRepetition(gCurrentField, gThis.m_gForm.GetFieldForForm(gThis.m_sFieldTarget)); gThis.m_fSource({ value: eEvent.data.gNode.GetValue(), }, GCallback(function(oData) { gDependentField.SetValue(oData.suggestion); }, { gForm: gThis.m_gForm, sFieldTarget: gThis.m_sFieldTarget, })); }; gThis.EvaluateExchangeOptions = function(eEvent) { if (eEvent === undefined) { eEvent = { data: { gNode: $(this).closest('.GFormNode').get(0).gNode, mArgument: gThis.m_mArgument, }, }; } GF_Ajax_Request(Routing.generate(gThis.m_fSource), { value: eEvent.data.gNode.GetValue(), }, function(oData) { gThis.m_gForm.GetField(gThis.m_sFieldTarget).ExchangeOptions(oData); }); }; gThis.Evaluate = function(mValue) { return gThis.m_gCondition.Evaluate(mValue); }; }; GFormDependency.HIDE = 'hide'; GFormDependency.SHOW = 'show'; GFormDependency.IGNORE = 'ignore'; GFormDependency.SUGGEST = 'suggest'; GFormDependency.INVOKE_CUSTOM_FUNCTION = 'invoke'; GFormDependency.EXCHANGE_OPTIONS = 'exchangeOptions'; GFormDependency.s_iNextId = 0;
diversantvlz/WellCommerce
src/WellCommerce/Bundle/AppBundle/Resources/public/js/core/form/01.dependency.js
JavaScript
mit
6,401
import stateType from './State'; import actionType from './Action'; export const initialChildWindowState = { window: null, state: stateType.INITIAL }; export default (state, action) => { switch (action.type) { case actionType.CHANGE_STATE: if (!Object.keys(stateType).includes(action.payload)) throw new Error(`Invalid window state: ${action.payload}.`); else if (action.payload === stateType.ERROR) throw new Error( `Error occured while window was in this state: ${action.payload}.` ); return { ...state, state: action.payload }; case actionType.SET_WINDOW: return { ...state, window: action.payload }; case actionType.RESET: return initialChildWindowState; default: throw new Error(`Invalid action type: ${action.type}.`); } };
owennw/OpenFinD3FC
packages/stockflux-launcher/src/reducers/child-window/ChildWindow.js
JavaScript
mit
826
/** * @license * (c) 2009-2016 Michael Leibman * michael{dot}leibman{at}gmail{dot}com * http://github.com/mleibman/slickgrid * * Distributed under MIT license. * All rights reserved. * * SlickGrid v2.4 * * NOTES: * Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods. * This increases the speed dramatically, but can only be done safely because there are no event handlers * or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy() * and do proper cleanup. */ // make sure required JavaScript modules are loaded if (typeof jQuery === "undefined") { throw new Error("SlickGrid requires jquery module to be loaded"); } if (!jQuery.fn.drag) { throw new Error("SlickGrid requires jquery.event.drag module to be loaded"); } if (typeof Slick === "undefined") { throw new Error("slick.core.js not loaded"); } (function ($) { "use strict"; // Slick.Grid $.extend(true, window, { Slick: { Grid: SlickGrid } }); // shared across all grids on the page var scrollbarDimensions; var maxSupportedCssHeight; // browser's breaking point ////////////////////////////////////////////////////////////////////////////////////////////// // SlickGrid class implementation (available as Slick.Grid) /** * Creates a new instance of the grid. * @class SlickGrid * @constructor * @param {Node} container Container node to create the grid in. * @param {Array,Object} data An array of objects for databinding. * @param {Array} columns An array of column definitions. * @param {Object} options Grid options. **/ function SlickGrid(container, data, columns, options) { // settings var defaults = { alwaysShowVerticalScroll: false, alwaysAllowHorizontalScroll: false, explicitInitialization: false, rowHeight: 25, defaultColumnWidth: 80, enableAddRow: false, leaveSpaceForNewRows: false, editable: false, autoEdit: true, suppressActiveCellChangeOnEdit: false, enableCellNavigation: true, enableColumnReorder: true, asyncEditorLoading: false, asyncEditorLoadDelay: 100, forceFitColumns: false, enableAsyncPostRender: false, asyncPostRenderDelay: 50, enableAsyncPostRenderCleanup: false, asyncPostRenderCleanupDelay: 40, autoHeight: false, editorLock: Slick.GlobalEditorLock, showColumnHeader: true, showHeaderRow: false, headerRowHeight: 25, createFooterRow: false, showFooterRow: false, footerRowHeight: 25, createPreHeaderPanel: false, showPreHeaderPanel: false, preHeaderPanelHeight: 25, showTopPanel: false, topPanelHeight: 25, formatterFactory: null, editorFactory: null, cellFlashingCssClass: "flashing", selectedCellCssClass: "selected", multiSelect: true, enableTextSelectionOnCells: false, dataItemColumnValueExtractor: null, frozenBottom: false, frozenColumn: -1, frozenRow: -1, fullWidthRows: false, multiColumnSort: false, numberedMultiColumnSort: false, tristateMultiColumnSort: false, sortColNumberInSeparateSpan: false, defaultFormatter: defaultFormatter, forceSyncScrolling: false, addNewRowCssClass: "new-row", preserveCopiedSelectionOnPaste: false, showCellSelection: true, viewportClass: null, minRowBuffer: 3, emulatePagingWhenScrolling: true, // when scrolling off bottom of viewport, place new row at top of viewport editorCellNavOnLRKeys: false, doPaging: true, autosizeColsMode: Slick.GridAutosizeColsMode.LegacyOff, autosizeColPaddingPx: 4, autosizeTextAvgToMWidthRatio: 0.75, viewportSwitchToScrollModeWidthPercent: undefined, viewportMinWidthPx: undefined, viewportMaxWidthPx: undefined }; var columnDefaults = { name: "", resizable: true, sortable: false, minWidth: 30, maxWidth: undefined, rerenderOnResize: false, headerCssClass: null, defaultSortAsc: true, focusable: true, selectable: true, }; var columnAutosizeDefaults = { ignoreHeaderText: false, colValueArray: undefined, allowAddlPercent: undefined, formatterOverride: undefined, autosizeMode: Slick.ColAutosizeMode.ContentIntelligent, rowSelectionModeOnInit: undefined, rowSelectionMode: Slick.RowSelectionMode.FirstNRows, rowSelectionCount: 100, valueFilterMode: Slick.ValueFilterMode.None, widthEvalMode: Slick.WidthEvalMode.CanvasTextSize, sizeToRemaining: undefined, widthPx: undefined, colDataTypeOf: undefined }; // scroller var th; // virtual height var h; // real scrollable height var ph; // page height var n; // number of pages var cj; // "jumpiness" coefficient var page = 0; // current page var offset = 0; // current page offset var vScrollDir = 1; // private var initialized = false; var $container; var uid = "slickgrid_" + Math.round(1000000 * Math.random()); var self = this; var $focusSink, $focusSink2; var $groupHeaders = $(); var $headerScroller; var $headers; var $headerRow, $headerRowScroller, $headerRowSpacerL, $headerRowSpacerR; var $footerRow, $footerRowScroller, $footerRowSpacerL, $footerRowSpacerR; var $preHeaderPanel, $preHeaderPanelScroller, $preHeaderPanelSpacer; var $preHeaderPanelR, $preHeaderPanelScrollerR, $preHeaderPanelSpacerR; var $topPanelScroller; var $topPanel; var $viewport; var $canvas; var $style; var $boundAncestors; var treeColumns; var stylesheet, columnCssRulesL, columnCssRulesR; var viewportH, viewportW; var canvasWidth, canvasWidthL, canvasWidthR; var headersWidth, headersWidthL, headersWidthR; var viewportHasHScroll, viewportHasVScroll; var headerColumnWidthDiff = 0, headerColumnHeightDiff = 0, // border+padding cellWidthDiff = 0, cellHeightDiff = 0, jQueryNewWidthBehaviour = false; var absoluteColumnMinWidth; var hasFrozenRows = false; var frozenRowsHeight = 0; var actualFrozenRow = -1; var paneTopH = 0; var paneBottomH = 0; var viewportTopH = 0; var viewportBottomH = 0; var topPanelH = 0; var headerRowH = 0; var footerRowH = 0; var tabbingDirection = 1; var $activeCanvasNode; var $activeViewportNode; var activePosX; var activeRow, activeCell; var activeCellNode = null; var currentEditor = null; var serializedEditorValue; var editController; var rowsCache = {}; var renderedRows = 0; var numVisibleRows = 0; var prevScrollTop = 0; var scrollTop = 0; var lastRenderedScrollTop = 0; var lastRenderedScrollLeft = 0; var prevScrollLeft = 0; var scrollLeft = 0; var selectionModel; var selectedRows = []; var plugins = []; var cellCssClasses = {}; var columnsById = {}; var sortColumns = []; var columnPosLeft = []; var columnPosRight = []; var pagingActive = false; var pagingIsLastPage = false; var scrollThrottle = ActionThrottle(render, 50); // async call handles var h_editorLoader = null; var h_render = null; var h_postrender = null; var h_postrenderCleanup = null; var postProcessedRows = {}; var postProcessToRow = null; var postProcessFromRow = null; var postProcessedCleanupQueue = []; var postProcessgroupId = 0; // perf counters var counter_rows_rendered = 0; var counter_rows_removed = 0; // These two variables work around a bug with inertial scrolling in Webkit/Blink on Mac. // See http://crbug.com/312427. var rowNodeFromLastMouseWheelEvent; // this node must not be deleted while inertial scrolling var zombieRowNodeFromLastMouseWheelEvent; // node that was hidden instead of getting deleted var zombieRowCacheFromLastMouseWheelEvent; // row cache for above node var zombieRowPostProcessedFromLastMouseWheelEvent; // post processing references for above node var $paneHeaderL; var $paneHeaderR; var $paneTopL; var $paneTopR; var $paneBottomL; var $paneBottomR; var $headerScrollerL; var $headerScrollerR; var $headerL; var $headerR; var $groupHeadersL; var $groupHeadersR; var $headerRowScrollerL; var $headerRowScrollerR; var $footerRowScrollerL; var $footerRowScrollerR; var $headerRowL; var $headerRowR; var $footerRowL; var $footerRowR; var $topPanelScrollerL; var $topPanelScrollerR; var $topPanelL; var $topPanelR; var $viewportTopL; var $viewportTopR; var $viewportBottomL; var $viewportBottomR; var $canvasTopL; var $canvasTopR; var $canvasBottomL; var $canvasBottomR; var $viewportScrollContainerX; var $viewportScrollContainerY; var $headerScrollContainer; var $headerRowScrollContainer; var $footerRowScrollContainer; // store css attributes if display:none is active in container or parent var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' }; var $hiddenParents; var oldProps = []; var columnResizeDragging = false; ////////////////////////////////////////////////////////////////////////////////////////////// // Initialization function init() { if (container instanceof jQuery) { $container = container; } else { $container = $(container); } if ($container.length < 1) { throw new Error("SlickGrid requires a valid container, " + container + " does not exist in the DOM."); } cacheCssForHiddenInit(); // calculate these only once and share between grid instances maxSupportedCssHeight = maxSupportedCssHeight || getMaxSupportedCssHeight(); options = $.extend({}, defaults, options); validateAndEnforceOptions(); columnDefaults.width = options.defaultColumnWidth; treeColumns = new Slick.TreeColumns(columns); columns = treeColumns.extractColumns(); updateColumnProps(); // validate loaded JavaScript modules against requested options if (options.enableColumnReorder && !$.fn.sortable) { throw new Error("SlickGrid's 'enableColumnReorder = true' option requires jquery-ui.sortable module to be loaded"); } editController = { "commitCurrentEdit": commitCurrentEdit, "cancelCurrentEdit": cancelCurrentEdit }; $container .empty() .css("overflow", "hidden") .css("outline", 0) .addClass(uid) .addClass("ui-widget"); // set up a positioning container if needed if (!(/relative|absolute|fixed/).test($container.css("position"))) { $container.css("position", "relative"); } $focusSink = $("<div tabIndex='0' hideFocus style='position:fixed;width:0;height:0;top:0;left:0;outline:0;'></div>").appendTo($container); // Containers used for scrolling frozen columns and rows $paneHeaderL = $("<div class='slick-pane slick-pane-header slick-pane-left' tabIndex='0' />").appendTo($container); $paneHeaderR = $("<div class='slick-pane slick-pane-header slick-pane-right' tabIndex='0' />").appendTo($container); $paneTopL = $("<div class='slick-pane slick-pane-top slick-pane-left' tabIndex='0' />").appendTo($container); $paneTopR = $("<div class='slick-pane slick-pane-top slick-pane-right' tabIndex='0' />").appendTo($container); $paneBottomL = $("<div class='slick-pane slick-pane-bottom slick-pane-left' tabIndex='0' />").appendTo($container); $paneBottomR = $("<div class='slick-pane slick-pane-bottom slick-pane-right' tabIndex='0' />").appendTo($container); if (options.createPreHeaderPanel) { $preHeaderPanelScroller = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderL); $preHeaderPanel = $("<div />").appendTo($preHeaderPanelScroller); $preHeaderPanelSpacer = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScroller); $preHeaderPanelScrollerR = $("<div class='slick-preheader-panel ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($paneHeaderR); $preHeaderPanelR = $("<div />").appendTo($preHeaderPanelScrollerR); $preHeaderPanelSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($preHeaderPanelScrollerR); if (!options.showPreHeaderPanel) { $preHeaderPanelScroller.hide(); $preHeaderPanelScrollerR.hide(); } } // Append the header scroller containers $headerScrollerL = $("<div class='slick-header ui-state-default slick-header-left' />").appendTo($paneHeaderL); $headerScrollerR = $("<div class='slick-header ui-state-default slick-header-right' />").appendTo($paneHeaderR); // Cache the header scroller containers $headerScroller = $().add($headerScrollerL).add($headerScrollerR); if (treeColumns.hasDepth()) { $groupHeadersL = []; $groupHeadersR = []; for (var index = 0; index < treeColumns.getDepth() - 1; index++) { $groupHeadersL[index] = $("<div class='slick-group-header-columns slick-group-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $groupHeadersR[index] = $("<div class='slick-group-header-columns slick-group-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); } $groupHeaders = $().add($groupHeadersL).add($groupHeadersR); } // Append the columnn containers to the headers $headerL = $("<div class='slick-header-columns slick-header-columns-left' style='left:-1000px' />").appendTo($headerScrollerL); $headerR = $("<div class='slick-header-columns slick-header-columns-right' style='left:-1000px' />").appendTo($headerScrollerR); // Cache the header columns $headers = $().add($headerL).add($headerR); $headerRowScrollerL = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopL); $headerRowScrollerR = $("<div class='slick-headerrow ui-state-default' />").appendTo($paneTopR); $headerRowScroller = $().add($headerRowScrollerL).add($headerRowScrollerR); $headerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerL); $headerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .appendTo($headerRowScrollerR); $headerRowL = $("<div class='slick-headerrow-columns slick-headerrow-columns-left' />").appendTo($headerRowScrollerL); $headerRowR = $("<div class='slick-headerrow-columns slick-headerrow-columns-right' />").appendTo($headerRowScrollerR); $headerRow = $().add($headerRowL).add($headerRowR); // Append the top panel scroller $topPanelScrollerL = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopL); $topPanelScrollerR = $("<div class='slick-top-panel-scroller ui-state-default' />").appendTo($paneTopR); $topPanelScroller = $().add($topPanelScrollerL).add($topPanelScrollerR); // Append the top panel $topPanelL = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerL); $topPanelR = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScrollerR); $topPanel = $().add($topPanelL).add($topPanelR); if (!options.showColumnHeader) { $headerScroller.hide(); } if (!options.showTopPanel) { $topPanelScroller.hide(); } if (!options.showHeaderRow) { $headerRowScroller.hide(); } // Append the viewport containers $viewportTopL = $("<div class='slick-viewport slick-viewport-top slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneTopL); $viewportTopR = $("<div class='slick-viewport slick-viewport-top slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneTopR); $viewportBottomL = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-left' tabIndex='0' hideFocus />").appendTo($paneBottomL); $viewportBottomR = $("<div class='slick-viewport slick-viewport-bottom slick-viewport-right' tabIndex='0' hideFocus />").appendTo($paneBottomR); // Cache the viewports $viewport = $().add($viewportTopL).add($viewportTopR).add($viewportBottomL).add($viewportBottomR); // Default the active viewport to the top left $activeViewportNode = $viewportTopL; // Append the canvas containers $canvasTopL = $("<div class='grid-canvas grid-canvas-top grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportTopL); $canvasTopR = $("<div class='grid-canvas grid-canvas-top grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportTopR); $canvasBottomL = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-left' tabIndex='0' hideFocus />").appendTo($viewportBottomL); $canvasBottomR = $("<div class='grid-canvas grid-canvas-bottom grid-canvas-right' tabIndex='0' hideFocus />").appendTo($viewportBottomR); if (options.viewportClass) $viewport.toggleClass(options.viewportClass, true); // Cache the canvases $canvas = $().add($canvasTopL).add($canvasTopR).add($canvasBottomL).add($canvasBottomR); scrollbarDimensions = scrollbarDimensions || measureScrollbar(); // Default the active canvas to the top left $activeCanvasNode = $canvasTopL; // pre-header if ($preHeaderPanelSpacer) $preHeaderPanelSpacer.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headers.width(getHeadersWidth()); $headerRowSpacerL.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); $headerRowSpacerR.css("width", getCanvasWidth() + scrollbarDimensions.width + "px"); // footer Row if (options.createFooterRow) { $footerRowScrollerR = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopR); $footerRowScrollerL = $("<div class='slick-footerrow ui-state-default' />").appendTo($paneTopL); $footerRowScroller = $().add($footerRowScrollerL).add($footerRowScrollerR); $footerRowSpacerL = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerL); $footerRowSpacerR = $("<div style='display:block;height:1px;position:absolute;top:0;left:0;'></div>") .css("width", getCanvasWidth() + scrollbarDimensions.width + "px") .appendTo($footerRowScrollerR); $footerRowL = $("<div class='slick-footerrow-columns slick-footerrow-columns-left' />").appendTo($footerRowScrollerL); $footerRowR = $("<div class='slick-footerrow-columns slick-footerrow-columns-right' />").appendTo($footerRowScrollerR); $footerRow = $().add($footerRowL).add($footerRowR); if (!options.showFooterRow) { $footerRowScroller.hide(); } } $focusSink2 = $focusSink.clone().appendTo($container); if (!options.explicitInitialization) { finishInitialization(); } } function finishInitialization() { if (!initialized) { initialized = true; getViewportWidth(); getViewportHeight(); // header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?) // calculate the diff so we can set consistent sizes measureCellPaddingAndBorder(); // for usability reasons, all text selection in SlickGrid is disabled // with the exception of input and textarea elements (selection must // be enabled there so that editors work as expected); note that // selection in grid cells (grid body) is already unavailable in // all browsers except IE disableSelection($headers); // disable all text selection in header (including input and textarea) if (!options.enableTextSelectionOnCells) { // disable text selection in grid cells except in input and textarea elements // (this is IE-specific, because selectstart event will only fire in IE) $viewport.on("selectstart.ui", function (event) { return $(event.target).is("input,textarea"); }); } setFrozenOptions(); setPaneVisibility(); setScroller(); setOverflow(); updateColumnCaches(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); setupColumnSort(); createCssRules(); resizeCanvas(); bindAncestorScrollEvents(); $container .on("resize.slickgrid", resizeCanvas); $viewport .on("scroll", handleScroll); if (jQuery.fn.mousewheel) { $viewport.on("mousewheel", handleMouseWheel); } $headerScroller //.on("scroll", handleHeaderScroll) .on("contextmenu", handleHeaderContextMenu) .on("click", handleHeaderClick) .on("mouseenter", ".slick-header-column", handleHeaderMouseEnter) .on("mouseleave", ".slick-header-column", handleHeaderMouseLeave); $headerRowScroller .on("scroll", handleHeaderRowScroll); if (options.createFooterRow) { $footerRow .on("contextmenu", handleFooterContextMenu) .on("click", handleFooterClick); $footerRowScroller .on("scroll", handleFooterRowScroll); } if (options.createPreHeaderPanel) { $preHeaderPanelScroller .on("scroll", handlePreHeaderPanelScroll); } $focusSink.add($focusSink2) .on("keydown", handleKeyDown); $canvas .on("keydown", handleKeyDown) .on("click", handleClick) .on("dblclick", handleDblClick) .on("contextmenu", handleContextMenu) .on("draginit", handleDragInit) .on("dragstart", {distance: 3}, handleDragStart) .on("drag", handleDrag) .on("dragend", handleDragEnd) .on("mouseenter", ".slick-cell", handleMouseEnter) .on("mouseleave", ".slick-cell", handleMouseLeave); restoreCssFromHiddenInit(); } } function cacheCssForHiddenInit() { // handle display:none on container or container parents $hiddenParents = $container.parents().addBack().not(':visible'); $hiddenParents.each(function() { var old = {}; for ( var name in cssShow ) { old[ name ] = this.style[ name ]; this.style[ name ] = cssShow[ name ]; } oldProps.push(old); }); } function restoreCssFromHiddenInit() { // finish handle display:none on container or container parents // - put values back the way they were $hiddenParents.each(function(i) { var old = oldProps[i]; for ( var name in cssShow ) { this.style[ name ] = old[ name ]; } }); } function hasFrozenColumns() { return options.frozenColumn > -1; } function registerPlugin(plugin) { plugins.unshift(plugin); plugin.init(self); } function unregisterPlugin(plugin) { for (var i = plugins.length; i >= 0; i--) { if (plugins[i] === plugin) { if (plugins[i].destroy) { plugins[i].destroy(); } plugins.splice(i, 1); break; } } } function getPluginByName(name) { for (var i = plugins.length-1; i >= 0; i--) { if (plugins[i].pluginName === name) { return plugins[i]; } } return undefined; } function setSelectionModel(model) { if (selectionModel) { selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged); if (selectionModel.destroy) { selectionModel.destroy(); } } selectionModel = model; if (selectionModel) { selectionModel.init(self); selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged); } } function getSelectionModel() { return selectionModel; } function getCanvasNode(columnIdOrIdx, rowIndex) { if (!columnIdOrIdx) { columnIdOrIdx = 0; } if (!rowIndex) { rowIndex = 0; } var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); return (hasFrozenRows && rowIndex >= actualFrozenRow + (options.frozenBottom ? 0 : 1) ) ? ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasBottomR[0] : $canvasBottomL[0]) : ((hasFrozenColumns() && idx > options.frozenColumn) ? $canvasTopR[0] : $canvasTopL[0]) ; } function getActiveCanvasNode(element) { setActiveCanvasNode(element); return $activeCanvasNode[0]; } function getCanvases() { return $canvas; } function setActiveCanvasNode(element) { if (element) { $activeCanvasNode = $(element.target).closest('.grid-canvas'); } } function getViewportNode() { return $viewport[0]; } function getActiveViewportNode(element) { setActiveViewPortNode(element); return $activeViewportNode[0]; } function setActiveViewportNode(element) { if (element) { $activeViewportNode = $(element.target).closest('.slick-viewport'); } } function measureScrollbar() { var $outerdiv = $('<div class="' + $viewport.className + '" style="position:absolute; top:-10000px; left:-10000px; overflow:auto; width:100px; height:100px;"></div>').appendTo($viewport); var $innerdiv = $('<div style="width:200px; height:200px; overflow:auto;"></div>').appendTo($outerdiv); var dim = { width: $outerdiv[0].offsetWidth - $outerdiv[0].clientWidth, height: $outerdiv[0].offsetHeight - $outerdiv[0].clientHeight }; $innerdiv.remove(); $outerdiv.remove(); return dim; } function getHeadersWidth() { headersWidth = headersWidthL = headersWidthR = 0; var includeScrollbar = !options.autoHeight; for (var i = 0, ii = columns.length; i < ii; i++) { var width = columns[ i ].width; if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += width; } else { headersWidthL += width; } } if (includeScrollbar) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) { headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; } } if (hasFrozenColumns()) { headersWidthL = headersWidthL + 1000; headersWidthR = Math.max(headersWidthR, viewportW) + headersWidthL; headersWidthR += scrollbarDimensions.width; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } headersWidth = headersWidthL + headersWidthR; return Math.max(headersWidth, viewportW) + 1000; } function getHeadersWidthL() { headersWidthL =0; columns.forEach(function(column, i) { if (!(( options.frozenColumn ) > -1 && ( i > options.frozenColumn ))) headersWidthL += column.width; }); if (hasFrozenColumns()) { headersWidthL += 1000; } else { headersWidthL += scrollbarDimensions.width; headersWidthL = Math.max(headersWidthL, viewportW) + 1000; } return headersWidthL; } function getHeadersWidthR() { headersWidthR =0; columns.forEach(function(column, i) { if (( options.frozenColumn ) > -1 && ( i > options.frozenColumn )) headersWidthR += column.width; }); if (hasFrozenColumns()) { headersWidthR = Math.max(headersWidthR, viewportW) + getHeadersWidthL(); headersWidthR += scrollbarDimensions.width; } return headersWidthR; } function getCanvasWidth() { var availableWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; var i = columns.length; canvasWidthL = canvasWidthR = 0; while (i--) { if (hasFrozenColumns() && (i > options.frozenColumn)) { canvasWidthR += columns[i].width; } else { canvasWidthL += columns[i].width; } } var totalRowWidth = canvasWidthL + canvasWidthR; return options.fullWidthRows ? Math.max(totalRowWidth, availableWidth) : totalRowWidth; } function updateCanvasWidth(forceColumnWidthsUpdate) { var oldCanvasWidth = canvasWidth; var oldCanvasWidthL = canvasWidthL; var oldCanvasWidthR = canvasWidthR; var widthChanged; canvasWidth = getCanvasWidth(); widthChanged = canvasWidth !== oldCanvasWidth || canvasWidthL !== oldCanvasWidthL || canvasWidthR !== oldCanvasWidthR; if (widthChanged || hasFrozenColumns() || hasFrozenRows) { $canvasTopL.width(canvasWidthL); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); if (hasFrozenColumns()) { $canvasTopR.width(canvasWidthR); $paneHeaderL.width(canvasWidthL); $paneHeaderR.css('left', canvasWidthL); $paneHeaderR.css('width', viewportW - canvasWidthL); $paneTopL.width(canvasWidthL); $paneTopR.css('left', canvasWidthL); $paneTopR.css('width', viewportW - canvasWidthL); $headerRowScrollerL.width(canvasWidthL); $headerRowScrollerR.width(viewportW - canvasWidthL); $headerRowL.width(canvasWidthL); $headerRowR.width(canvasWidthR); if (options.createFooterRow) { $footerRowScrollerL.width(canvasWidthL); $footerRowScrollerR.width(viewportW - canvasWidthL); $footerRowL.width(canvasWidthL); $footerRowR.width(canvasWidthR); } if (options.createPreHeaderPanel) { $preHeaderPanel.width(canvasWidth); } $viewportTopL.width(canvasWidthL); $viewportTopR.width(viewportW - canvasWidthL); if (hasFrozenRows) { $paneBottomL.width(canvasWidthL); $paneBottomR.css('left', canvasWidthL); $viewportBottomL.width(canvasWidthL); $viewportBottomR.width(viewportW - canvasWidthL); $canvasBottomL.width(canvasWidthL); $canvasBottomR.width(canvasWidthR); } } else { $paneHeaderL.width('100%'); $paneTopL.width('100%'); $headerRowScrollerL.width('100%'); $headerRowL.width(canvasWidth); if (options.createFooterRow) { $footerRowScrollerL.width('100%'); $footerRowL.width(canvasWidth); } if (options.createPreHeaderPanel) { $preHeaderPanel.width('100%'); $preHeaderPanel.width(canvasWidth); } $viewportTopL.width('100%'); if (hasFrozenRows) { $viewportBottomL.width('100%'); $canvasBottomL.width(canvasWidthL); } } viewportHasHScroll = (canvasWidth > viewportW - scrollbarDimensions.width); } $headerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $headerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); if (options.createFooterRow) { $footerRowSpacerL.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); $footerRowSpacerR.width(canvasWidth + (viewportHasVScroll ? scrollbarDimensions.width : 0)); } if (widthChanged || forceColumnWidthsUpdate) { applyColumnWidths(); } } function disableSelection($target) { if ($target && $target.jquery) { $target .attr("unselectable", "on") .css("MozUserSelect", "none") .on("selectstart.ui", function () { return false; }); // from jquery:ui.core.js 1.7.2 } } function getMaxSupportedCssHeight() { var supportedHeight = 1000000; // FF reports the height back but still renders blank after ~6M px var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000; var div = $("<div style='display:none' />").appendTo(document.body); while (true) { var test = supportedHeight * 2; div.css("height", test); if (test > testUpTo || div.height() !== test) { break; } else { supportedHeight = test; } } div.remove(); return supportedHeight; } function getUID() { return uid; } function getHeaderColumnWidthDiff() { return headerColumnWidthDiff; } function getScrollbarDimensions() { return scrollbarDimensions; } // TODO: this is static. need to handle page mutation. function bindAncestorScrollEvents() { var elem = (hasFrozenRows && !options.frozenBottom) ? $canvasBottomL[0] : $canvasTopL[0]; while ((elem = elem.parentNode) != document.body && elem != null) { // bind to scroll containers only if (elem == $viewportTopL[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight) { var $elem = $(elem); if (!$boundAncestors) { $boundAncestors = $elem; } else { $boundAncestors = $boundAncestors.add($elem); } $elem.on("scroll." + uid, handleActiveCellPositionChange); } } } function unbindAncestorScrollEvents() { if (!$boundAncestors) { return; } $boundAncestors.off("scroll." + uid); $boundAncestors = null; } function updateColumnHeader(columnId, title, toolTip) { if (!initialized) { return; } var idx = getColumnIndex(columnId); if (idx == null) { return; } var columnDef = columns[idx]; var $header = $headers.children().eq(idx); if ($header) { if (title !== undefined) { columns[idx].name = title; } if (toolTip !== undefined) { columns[idx].toolTip = toolTip; } trigger(self.onBeforeHeaderCellDestroy, { "node": $header[0], "column": columnDef, "grid": self }); $header .attr("title", toolTip || "") .children().eq(0).html(title); trigger(self.onHeaderCellRendered, { "node": $header[0], "column": columnDef, "grid": self }); } } function getHeader(columnDef) { if (!columnDef) { return hasFrozenColumns() ? $headers : $headerL; } var idx = getColumnIndex(columnDef.id); return hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; } function getHeaderColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var targetHeader = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var targetIndex = hasFrozenColumns() ? ((idx <= options.frozenColumn) ? idx : idx - options.frozenColumn - 1) : idx; var $rtn = targetHeader.children().eq(targetIndex); return $rtn && $rtn[0]; } function getHeaderRow() { return hasFrozenColumns() ? $headerRow : $headerRow[0]; } function getFooterRow() { return hasFrozenColumns() ? $footerRow : $footerRow[0]; } function getPreHeaderPanel() { return $preHeaderPanel[0]; } function getPreHeaderPanelRight() { return $preHeaderPanelR[0]; } function getHeaderRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $headerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $headerRowTarget = $headerRowL; } else { $headerRowTarget = $headerRowR; idx -= options.frozenColumn + 1; } } else { $headerRowTarget = $headerRowL; } var $header = $headerRowTarget.children().eq(idx); return $header && $header[0]; } function getFooterRowColumn(columnIdOrIdx) { var idx = (typeof columnIdOrIdx === "number" ? columnIdOrIdx : getColumnIndex(columnIdOrIdx)); var $footerRowTarget; if (hasFrozenColumns()) { if (idx <= options.frozenColumn) { $footerRowTarget = $footerRowL; } else { $footerRowTarget = $footerRowR; idx -= options.frozenColumn + 1; } } else { $footerRowTarget = $footerRowL; } var $footer = $footerRowTarget && $footerRowTarget.children().eq(idx); return $footer && $footer[0]; } function createColumnFooter() { if (options.createFooterRow) { $footerRow.find(".slick-footerrow-column") .each(function () { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); $footerRowR.empty(); for (var i = 0; i < columns.length; i++) { var m = columns[i]; var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (i > options.frozenColumn)? $footerRowR: $footerRowL); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } } function createColumnGroupHeaders() { var columnsLength = 0; var frozenColumnsValid = false; if (!treeColumns.hasDepth()) return; for (var index = 0; index < $groupHeadersL.length; index++) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); var groupColumns = treeColumns.getColumnsInDepth(index); for (var indexGroup in groupColumns) { var m = groupColumns[indexGroup]; columnsLength += m.extractColumns().length; if (hasFrozenColumns() && index === 0 && (columnsLength-1) === options.frozenColumn) frozenColumnsValid = true; $("<div class='ui-state-default slick-group-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? 'frozen': '') .appendTo(hasFrozenColumns() && (columnsLength - 1) > options.frozenColumn? $groupHeadersR[index]: $groupHeadersL[index]); } if (hasFrozenColumns() && index === 0 && !frozenColumnsValid) { $groupHeadersL[index].empty(); $groupHeadersR[index].empty(); alert("All columns of group should to be grouped!"); break; } } applyColumnGroupHeaderWidths(); } function createColumnHeaders() { function onMouseEnter() { $(this).addClass("ui-state-hover"); } function onMouseLeave() { $(this).removeClass("ui-state-hover"); } $headers.find(".slick-header-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerL.empty(); $headerR.empty(); getHeadersWidth(); $headerL.width(headersWidthL); $headerR.width(headersWidthR); $headerRow.find(".slick-headerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeHeaderRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $headerRowL.empty(); $headerRowR.empty(); if (options.createFooterRow) { $footerRowL.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowL.empty(); if (hasFrozenColumns()) { $footerRowR.find(".slick-footerrow-column") .each(function() { var columnDef = $(this).data("column"); if (columnDef) { trigger(self.onBeforeFooterRowCellDestroy, { "node": this, "column": columnDef, "grid": self }); } }); $footerRowR.empty(); } } for (var i = 0; i < columns.length; i++) { var m = columns[i]; var $headerTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerL : $headerR) : $headerL; var $headerRowTarget = hasFrozenColumns() ? ((i <= options.frozenColumn) ? $headerRowL : $headerRowR) : $headerRowL; var header = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + m.name + "</span>") .width(m.width - headerColumnWidthDiff) .attr("id", "" + uid + m.id) .attr("title", m.toolTip || "") .data("column", m) .addClass(m.headerCssClass || "") .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerTarget); if (options.enableColumnReorder || m.sortable) { header .on('mouseenter', onMouseEnter) .on('mouseleave', onMouseLeave); } if(m.hasOwnProperty('headerCellAttrs') && m.headerCellAttrs instanceof Object) { for (var key in m.headerCellAttrs) { if (m.headerCellAttrs.hasOwnProperty(key)) { header.attr(key, m.headerCellAttrs[key]); } } } if (m.sortable) { header.addClass("slick-header-sortable"); header.append("<span class='slick-sort-indicator" + (options.numberedMultiColumnSort && !options.sortColNumberInSeparateSpan ? " slick-sort-indicator-numbered" : "" ) + "' />"); if (options.numberedMultiColumnSort && options.sortColNumberInSeparateSpan) { header.append("<span class='slick-sort-indicator-numbered' />"); } } trigger(self.onHeaderCellRendered, { "node": header[0], "column": m, "grid": self }); if (options.showHeaderRow) { var headerRowCell = $("<div class='ui-state-default slick-headerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .addClass(hasFrozenColumns() && i <= options.frozenColumn? 'frozen': '') .appendTo($headerRowTarget); trigger(self.onHeaderRowCellRendered, { "node": headerRowCell[0], "column": m, "grid": self }); } if (options.createFooterRow && options.showFooterRow) { var footerRowCell = $("<div class='ui-state-default slick-footerrow-column l" + i + " r" + i + "'></div>") .data("column", m) .appendTo($footerRow); trigger(self.onFooterRowCellRendered, { "node": footerRowCell[0], "column": m, "grid": self }); } } setSortColumns(sortColumns); setupColumnResize(); if (options.enableColumnReorder) { if (typeof options.enableColumnReorder == 'function') { options.enableColumnReorder(self, $headers, headerColumnWidthDiff, setColumns, setupColumnResize, columns, getColumnIndex, uid, trigger); } else { setupColumnReorder(); } } } function setupColumnSort() { $headers.click(function (e) { if (columnResizeDragging) return; // temporary workaround for a bug in jQuery 1.7.1 (http://bugs.jquery.com/ticket/11328) e.metaKey = e.metaKey || e.ctrlKey; if ($(e.target).hasClass("slick-resizable-handle")) { return; } var $col = $(e.target).closest(".slick-header-column"); if (!$col.length) { return; } var column = $col.data("column"); if (column.sortable) { if (!getEditorLock().commitCurrentEdit()) { return; } var sortColumn = null; var i = 0; for (; i < sortColumns.length; i++) { if (sortColumns[i].columnId == column.id) { sortColumn = sortColumns[i]; sortColumn.sortAsc = !sortColumn.sortAsc; break; } } var hadSortCol = !!sortColumn; if (options.tristateMultiColumnSort) { if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; } if (hadSortCol && sortColumn.sortAsc) { // three state: remove sort rather than go back to ASC sortColumns.splice(i, 1); sortColumn = null; } if (!options.multiColumnSort) { sortColumns = []; } if (sortColumn && (!hadSortCol || !options.multiColumnSort)) { sortColumns.push(sortColumn); } } else { // legacy behaviour if (e.metaKey && options.multiColumnSort) { if (sortColumn) { sortColumns.splice(i, 1); } } else { if ((!e.shiftKey && !e.metaKey) || !options.multiColumnSort) { sortColumns = []; } if (!sortColumn) { sortColumn = { columnId: column.id, sortAsc: column.defaultSortAsc }; sortColumns.push(sortColumn); } else if (sortColumns.length === 0) { sortColumns.push(sortColumn); } } } setSortColumns(sortColumns); if (!options.multiColumnSort) { trigger(self.onSort, { multiColumnSort: false, columnId: (sortColumns.length > 0 ? column.id : null), sortCol: (sortColumns.length > 0 ? column : null), sortAsc: (sortColumns.length > 0 ? sortColumns[0].sortAsc : true) }, e); } else { trigger(self.onSort, { multiColumnSort: true, sortCols: $.map(sortColumns, function(col) { return {columnId: columns[getColumnIndex(col.columnId)].id, sortCol: columns[getColumnIndex(col.columnId)], sortAsc: col.sortAsc }; }) }, e); } } }); } function currentPositionInHeader(id) { var currentPosition = 0; $headers.find('.slick-header-column').each(function (i) { if (this.id == id) { currentPosition = i; return false; } }); return currentPosition; } function limitPositionInGroup(idColumn) { var groupColumnOfPreviousPosition, startLimit = 0, endLimit = 0; treeColumns .getColumnsInDepth($groupHeadersL.length - 1) .some(function (groupColumn) { startLimit = endLimit; endLimit += groupColumn.columns.length; groupColumn.columns.some(function (column) { if (column.id === idColumn) groupColumnOfPreviousPosition = groupColumn; return groupColumnOfPreviousPosition; }); return groupColumnOfPreviousPosition; }); endLimit--; return { start: startLimit, end: endLimit, group: groupColumnOfPreviousPosition }; } function remove(arr, elem) { var index = arr.lastIndexOf(elem); if(index > -1) { arr.splice(index, 1); remove(arr, elem); } } function columnPositionValidInGroup($item) { var currentPosition = currentPositionInHeader($item[0].id); var limit = limitPositionInGroup($item.data('column').id); var positionValid = limit.start <= currentPosition && currentPosition <= limit.end; return { limit: limit, valid: positionValid, message: positionValid? '': 'Column "'.concat($item.text(), '" can be reordered only within the "', limit.group.name, '" group!') }; } function setupColumnReorder() { $headers.filter(":ui-sortable").sortable("destroy"); var columnScrollTimer = null; function scrollColumnsRight() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft + 10; } function scrollColumnsLeft() { $viewportScrollContainerX[0].scrollLeft = $viewportScrollContainerX[0].scrollLeft - 10; } var canDragScroll; $headers.sortable({ containment: "parent", distance: 3, axis: "x", cursor: "default", tolerance: "intersection", helper: "clone", placeholder: "slick-sortable-placeholder ui-state-default slick-header-column", start: function (e, ui) { ui.placeholder.width(ui.helper.outerWidth() - headerColumnWidthDiff); canDragScroll = !hasFrozenColumns() || (ui.placeholder.offset().left + ui.placeholder.width()) > $viewportScrollContainerX.offset().left; $(ui.helper).addClass("slick-header-column-active"); }, beforeStop: function (e, ui) { $(ui.helper).removeClass("slick-header-column-active"); }, sort: function (e, ui) { if (canDragScroll && e.originalEvent.pageX > $container[0].clientWidth) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsRight, 100); } } else if (canDragScroll && e.originalEvent.pageX < $viewportScrollContainerX.offset().left) { if (!(columnScrollTimer)) { columnScrollTimer = setInterval( scrollColumnsLeft, 100); } } else { clearInterval(columnScrollTimer); columnScrollTimer = null; } }, stop: function (e, ui) { var cancel = false; clearInterval(columnScrollTimer); columnScrollTimer = null; var limit = null; if (treeColumns.hasDepth()) { var validPositionInGroup = columnPositionValidInGroup(ui.item); limit = validPositionInGroup.limit; cancel = !validPositionInGroup.valid; if (cancel) alert(validPositionInGroup.message); } if (cancel || !getEditorLock().commitCurrentEdit()) { $(this).sortable("cancel"); return; } var reorderedIds = $headerL.sortable("toArray"); reorderedIds = reorderedIds.concat($headerR.sortable("toArray")); var reorderedColumns = []; for (var i = 0; i < reorderedIds.length; i++) { reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid, ""))]); } setColumns(reorderedColumns); trigger(self.onColumnsReordered, { impactedColumns : getImpactedColumns( limit ) }); e.stopPropagation(); setupColumnResize(); } }); } function getImpactedColumns( limit ) { var impactedColumns = []; if( limit ) { for( var i = limit.start; i <= limit.end; i++ ) { impactedColumns.push( columns[i] ); } } else { impactedColumns = columns; } return impactedColumns; } function setupColumnResize() { var $col, j, k, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable; columnElements = $headers.children(); columnElements.find(".slick-resizable-handle").remove(); columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (columns[i].resizable) { if (firstResizable === undefined) { firstResizable = i; } lastResizable = i; } }); if (firstResizable === undefined) { return; } columnElements.each(function (i, e) { if (i >= columns.length) { return; } if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) { return; } $col = $(e); $("<div class='slick-resizable-handle' />") .appendTo(e) .on("dragstart", function (e, dd) { if (!getEditorLock().commitCurrentEdit()) { return false; } pageX = e.pageX; $(this).parent().addClass("slick-header-column-active"); var shrinkLeewayOnRight = null, stretchLeewayOnRight = null; // lock each column's width option to current width columnElements.each(function (i, e) { if (i >= columns.length) { return; } columns[i].previousWidth = $(e).outerWidth(); }); if (options.forceFitColumns) { shrinkLeewayOnRight = 0; stretchLeewayOnRight = 0; // colums on right affect maxPageX/minPageX for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (stretchLeewayOnRight !== null) { if (c.maxWidth) { stretchLeewayOnRight += c.maxWidth - c.previousWidth; } else { stretchLeewayOnRight = null; } } shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } } var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0; for (j = 0; j <= i; j++) { // columns on left only affect minPageX c = columns[j]; if (c.resizable) { if (stretchLeewayOnLeft !== null) { if (c.maxWidth) { stretchLeewayOnLeft += c.maxWidth - c.previousWidth; } else { stretchLeewayOnLeft = null; } } shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth); } } if (shrinkLeewayOnRight === null) { shrinkLeewayOnRight = 100000; } if (shrinkLeewayOnLeft === null) { shrinkLeewayOnLeft = 100000; } if (stretchLeewayOnRight === null) { stretchLeewayOnRight = 100000; } if (stretchLeewayOnLeft === null) { stretchLeewayOnLeft = 100000; } maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft); minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight); }) .on("drag", function (e, dd) { columnResizeDragging = true; var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x; var newCanvasWidthL = 0, newCanvasWidthR = 0; if (d < 0) { // shrink column x = d; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } } } else { // stretch column x = d; newCanvasWidthL = 0; newCanvasWidthR = 0; for (j = i; j >= 0; j--) { c = columns[j]; if (c.resizable) { if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) { x -= c.maxWidth - c.previousWidth; c.width = c.maxWidth; } else { c.width = c.previousWidth + x; x = 0; } } } for (k = 0; k <= i; k++) { c = columns[k]; if (hasFrozenColumns() && (k > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } if (options.forceFitColumns) { x = -d; for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (c.resizable) { actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth); if (x && c.previousWidth + x < actualMinWidth) { x += c.previousWidth - actualMinWidth; c.width = actualMinWidth; } else { c.width = c.previousWidth + x; x = 0; } if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } else { for (j = i + 1; j < columns.length; j++) { c = columns[j]; if (hasFrozenColumns() && (j > options.frozenColumn)) { newCanvasWidthR += c.width; } else { newCanvasWidthL += c.width; } } } } if (hasFrozenColumns() && newCanvasWidthL != canvasWidthL) { $headerL.width(newCanvasWidthL + 1000); $paneHeaderR.css('left', newCanvasWidthL); } applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); if (options.syncColumnCellResize) { applyColumnWidths(); } }) .on("dragend", function (e, dd) { var newWidth; $(this).parent().removeClass("slick-header-column-active"); for (j = 0; j < columns.length; j++) { c = columns[j]; newWidth = $(columnElements[j]).outerWidth(); if (c.previousWidth !== newWidth && c.rerenderOnResize) { invalidateAllRows(); } } updateCanvasWidth(true); render(); trigger(self.onColumnsResized, {triggeredByColumn: $(this).parent().attr("id").replace(uid, "")}); setTimeout(function () { columnResizeDragging = false; }, 300); }); }); } function getVBoxDelta($el) { var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; var delta = 0; $.each(p, function (n, val) { delta += parseFloat($el.css(val)) || 0; }); return delta; } function setFrozenOptions() { options.frozenColumn = (options.frozenColumn >= 0 && options.frozenColumn < columns.length) ? parseInt(options.frozenColumn) : -1; if (options.frozenRow > -1) { hasFrozenRows = true; frozenRowsHeight = ( options.frozenRow ) * options.rowHeight; var dataLength = getDataLength(); actualFrozenRow = ( options.frozenBottom ) ? ( dataLength - options.frozenRow ) : options.frozenRow; } else { hasFrozenRows = false; } } function setPaneVisibility() { if (hasFrozenColumns()) { $paneHeaderR.show(); $paneTopR.show(); if (hasFrozenRows) { $paneBottomL.show(); $paneBottomR.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } else { $paneHeaderR.hide(); $paneTopR.hide(); $paneBottomR.hide(); if (hasFrozenRows) { $paneBottomL.show(); } else { $paneBottomR.hide(); $paneBottomL.hide(); } } } function setOverflow() { $viewportTopL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportTopR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'scroll' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'hidden' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'scroll' : 'auto' ) : ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomL.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ): ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'hidden' : 'hidden' ): ( hasFrozenRows ? 'scroll' : 'auto' )) }); $viewportBottomR.css({ 'overflow-x': ( hasFrozenColumns() ) ? ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'scroll' : 'auto' ) : ( hasFrozenRows && !options.alwaysAllowHorizontalScroll ? 'auto' : 'auto' ), 'overflow-y': options.alwaysShowVerticalScroll ? "scroll" : (( hasFrozenColumns() ) ? ( hasFrozenRows ? 'auto' : 'auto' ) : ( hasFrozenRows ? 'auto' : 'auto' )) }); if (options.viewportClass) { $viewportTopL.toggleClass(options.viewportClass, true); $viewportTopR.toggleClass(options.viewportClass, true); $viewportBottomL.toggleClass(options.viewportClass, true); $viewportBottomR.toggleClass(options.viewportClass, true); } } function setScroller() { if (hasFrozenColumns()) { $headerScrollContainer = $headerScrollerR; $headerRowScrollContainer = $headerRowScrollerR; $footerRowScrollContainer = $footerRowScrollerR; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomR; $viewportScrollContainerY = $viewportTopR; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomR; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopR; } } else { $headerScrollContainer = $headerScrollerL; $headerRowScrollContainer = $headerRowScrollerL; $footerRowScrollContainer = $footerRowScrollerL; if (hasFrozenRows) { if (options.frozenBottom) { $viewportScrollContainerX = $viewportBottomL; $viewportScrollContainerY = $viewportTopL; } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportBottomL; } } else { $viewportScrollContainerX = $viewportScrollContainerY = $viewportTopL; } } } function measureCellPaddingAndBorder() { var el; var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"]; var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"]; // jquery prior to version 1.8 handles .width setter/getter as a direct css write/read // jquery 1.8 changed .width to read the true inner element width if box-sizing is set to border-box, and introduced a setter for .outerWidth // so for equivalent functionality, prior to 1.8 use .width, and after use .outerWidth var verArray = $.fn.jquery.split('.'); jQueryNewWidthBehaviour = (verArray[0]==1 && verArray[1]>=8) || verArray[0] >=2; el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers); headerColumnWidthDiff = headerColumnHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { headerColumnWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { headerColumnHeightDiff += parseFloat(el.css(val)) || 0; }); } el.remove(); var r = $("<div class='slick-row' />").appendTo($canvas); el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r); cellWidthDiff = cellHeightDiff = 0; if (el.css("box-sizing") != "border-box" && el.css("-moz-box-sizing") != "border-box" && el.css("-webkit-box-sizing") != "border-box") { $.each(h, function (n, val) { cellWidthDiff += parseFloat(el.css(val)) || 0; }); $.each(v, function (n, val) { cellHeightDiff += parseFloat(el.css(val)) || 0; }); } r.remove(); absoluteColumnMinWidth = Math.max(headerColumnWidthDiff, cellWidthDiff); } function createCssRules() { $style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head")); var rowHeight = (options.rowHeight - cellHeightDiff); var rules = [ "." + uid + " .slick-group-header-column { left: 1000px; }", "." + uid + " .slick-header-column { left: 1000px; }", "." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }", "." + uid + " .slick-preheader-panel { height:" + options.preHeaderPanelHeight + "px; }", "." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }", "." + uid + " .slick-footerrow-columns { height:" + options.footerRowHeight + "px; }", "." + uid + " .slick-cell { height:" + rowHeight + "px; }", "." + uid + " .slick-row { height:" + options.rowHeight + "px; }" ]; for (var i = 0; i < columns.length; i++) { rules.push("." + uid + " .l" + i + " { }"); rules.push("." + uid + " .r" + i + " { }"); } if ($style[0].styleSheet) { // IE $style[0].styleSheet.cssText = rules.join(" "); } else { $style[0].appendChild(document.createTextNode(rules.join(" "))); } } function getColumnCssRules(idx) { var i; if (!stylesheet) { var sheets = document.styleSheets; for (i = 0; i < sheets.length; i++) { if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) { stylesheet = sheets[i]; break; } } if (!stylesheet) { throw new Error("Cannot find stylesheet."); } // find and cache column CSS rules columnCssRulesL = []; columnCssRulesR = []; var cssRules = (stylesheet.cssRules || stylesheet.rules); var matches, columnIdx; for (i = 0; i < cssRules.length; i++) { var selector = cssRules[i].selectorText; if (matches = /\.l\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesL[columnIdx] = cssRules[i]; } else if (matches = /\.r\d+/.exec(selector)) { columnIdx = parseInt(matches[0].substr(2, matches[0].length - 2), 10); columnCssRulesR[columnIdx] = cssRules[i]; } } } return { "left": columnCssRulesL[idx], "right": columnCssRulesR[idx] }; } function removeCssRules() { $style.remove(); stylesheet = null; } function destroy() { getEditorLock().cancelCurrentEdit(); trigger(self.onBeforeDestroy, {}); var i = plugins.length; while(i--) { unregisterPlugin(plugins[i]); } if (options.enableColumnReorder) { $headers.filter(":ui-sortable").sortable("destroy"); } unbindAncestorScrollEvents(); $container.off(".slickgrid"); removeCssRules(); $canvas.off("draginit dragstart dragend drag"); $container.empty().removeClass(uid); } ////////////////////////////////////////////////////////////////////////////////////////////// // Column Autosizing ////////////////////////////////////////////////////////////////////////////////////////////// var canvas = null; var canvas_context = null; function autosizeColumn(columnOrIndexOrId, isInit) { var c = columnOrIndexOrId; if (typeof columnOrIndexOrId === 'number') { c = columns[columnOrIndexOrId]; } else if (typeof columnOrIndexOrId === 'string') { for (i = 0; i < columns.length; i++) { if (columns[i].Id === columnOrIndexOrId) { c = columns[i]; } } } var $gridCanvas = $(getCanvasNode(0, 0)); getColAutosizeWidth(c, $gridCanvas, isInit); } function autosizeColumns(autosizeMode, isInit) { //LogColWidths(); autosizeMode = autosizeMode || options.autosizeColsMode; if (autosizeMode === Slick.GridAutosizeColsMode.LegacyForceFit || autosizeMode === Slick.GridAutosizeColsMode.LegacyOff) { legacyAutosizeColumns(); return; } if (autosizeMode === Slick.GridAutosizeColsMode.None) { return; } // test for brower canvas support, canvas_context!=null if supported canvas = document.createElement("canvas"); if (canvas && canvas.getContext) { canvas_context = canvas.getContext("2d"); } // pass in the grid canvas var $gridCanvas = $(getCanvasNode(0, 0)); var viewportWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; // iterate columns to get autosizes var i, c, colWidth, reRender, totalWidth = 0, totalWidthLessSTR = 0, strColsMinWidth = 0, totalMinWidth = 0, totalLockedColWidth = 0; for (i = 0; i < columns.length; i++) { c = columns[i]; getColAutosizeWidth(c, $gridCanvas, isInit); totalLockedColWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : 0); totalMinWidth += (c.autoSize.autosizeMode === Slick.ColAutosizeMode.Locked ? c.width : c.minWidth); totalWidth += c.autoSize.widthPx; totalWidthLessSTR += (c.autoSize.sizeToRemaining ? 0 : c.autoSize.widthPx); strColsMinWidth += (c.autoSize.sizeToRemaining ? c.minWidth || 0 : 0); } var strColTotalGuideWidth = totalWidth - totalWidthLessSTR; if (autosizeMode === Slick.GridAutosizeColsMode.FitViewportToCols) { // - if viewport with is outside MinViewportWidthPx and MaxViewportWidthPx, then the viewport is set to // MinViewportWidthPx or MaxViewportWidthPx and the FitColsToViewport algorithm is used // - viewport is resized to fit columns var setWidth = totalWidth + scrollbarDimensions.width; autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport; if (options.viewportMaxWidthPx && setWidth > options.viewportMaxWidthPx) { setWidth = options.viewportMaxWidthPx; autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport; } else if (options.viewportMinWidthPx && setWidth < options.viewportMinWidthPx) { setWidth = options.viewportMinWidthPx; autosizeMode = Slick.GridAutosizeColsMode.FitColsToViewport; } else { // falling back to IgnoreViewport will size the columns as-is, with render checking //for (i = 0; i < columns.length; i++) { columns[i].width = columns[i].autoSize.widthPx; } } $container.width(setWidth); } if (autosizeMode === Slick.GridAutosizeColsMode.FitColsToViewport) { if (strColTotalGuideWidth > 0 && totalWidthLessSTR < viewportWidth - strColsMinWidth) { // if addl space remains in the viewport and there are SizeToRemaining cols, just the SizeToRemaining cols expand proportionally to fill viewport for (i = 0; i < columns.length; i++) { c = columns[i]; var totalSTRViewportWidth = viewportWidth - totalWidthLessSTR; if (c.autoSize.sizeToRemaining) { colWidth = totalSTRViewportWidth * c.autoSize.widthPx / strColTotalGuideWidth; } else { colWidth = c.autoSize.widthPx; } if (c.rerenderOnResize && c.width != colWidth) { reRender = true; } c.width = colWidth; } } else if ((options.viewportSwitchToScrollModeWidthPercent && totalWidthLessSTR + strColsMinWidth > viewportWidth * options.viewportSwitchToScrollModeWidthPercent / 100) || (totalMinWidth > viewportWidth)) { // if the total columns width is wider than the viewport by switchToScrollModeWidthPercent, switch to IgnoreViewport mode autosizeMode = Slick.GridAutosizeColsMode.IgnoreViewport; } else { // otherwise (ie. no SizeToRemaining cols or viewport smaller than columns) all cols other than 'Locked' scale in proportion to fill viewport // and SizeToRemaining get minWidth var unallocatedColWidth = totalWidthLessSTR - totalLockedColWidth; var unallocatedViewportWidth = viewportWidth - totalLockedColWidth - strColsMinWidth; for (i = 0; i < columns.length; i++) { c = columns[i]; colWidth = c.width; if (c.autoSize.autosizeMode !== Slick.ColAutosizeMode.Locked) { if (c.autoSize.sizeToRemaining) { colWidth = c.minWidth; } else { // size width proportionally to free space (we know we have enough room due to the earlier calculations) colWidth = unallocatedViewportWidth / unallocatedColWidth * c.autoSize.widthPx; if (colWidth < c.minWidth) { colWidth = c.minWidth; } // remove the just allocated widths from the allocation pool unallocatedColWidth -= c.autoSize.widthPx; unallocatedViewportWidth -= colWidth; } } if (c.rerenderOnResize && c.width != colWidth) { reRender = true; } c.width = colWidth; } } } if (autosizeMode === Slick.GridAutosizeColsMode.IgnoreViewport) { // just size columns as-is for (i = 0; i < columns.length; i++) { colWidth = columns[i].autoSize.widthPx; if (columns[i].rerenderOnResize && columns[i].width != colWidth) { reRender = true; } columns[i].width = colWidth; } } //LogColWidths(); reRenderColumns(reRender); } function LogColWidths () { var s = "Col Widths:"; for (i = 0; i < columns.length; i++) { s += ' ' + columns[i].width; } console.log(s); } function getColAutosizeWidth(columnDef, $gridCanvas, isInit) { var autoSize = columnDef.autoSize; // set to width as default autoSize.widthPx = columnDef.width; if (autoSize.autosizeMode === Slick.ColAutosizeMode.Locked || autoSize.autosizeMode === Slick.ColAutosizeMode.Guide) { return; } var dl = getDataLength(); //getDataItem(); // ContentIntelligent takes settings from column data type if (autoSize.autosizeMode === Slick.ColAutosizeMode.ContentIntelligent) { // default to column colDataTypeOf (can be used if initially there are no data rows) var colDataTypeOf = autoSize.colDataTypeOf; var colDataItem; if (dl > 0) { var tempRow = getDataItem(0); if (tempRow) { colDataItem = tempRow[columnDef.field]; colDataTypeOf = typeof colDataItem; if (colDataTypeOf === 'object') { if (colDataItem instanceof Date) { colDataTypeOf = "date"; } if (typeof moment!=='undefined' && colDataItem instanceof moment) { colDataTypeOf = "moment"; } } } } if (colDataTypeOf === 'boolean') { autoSize.colValueArray = [ true, false ]; } if (colDataTypeOf === 'number') { autoSize.valueFilterMode = Slick.ValueFilterMode.GetGreatestAndSub; autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows; } if (colDataTypeOf === 'string') { autoSize.valueFilterMode = Slick.ValueFilterMode.GetLongestText; autoSize.rowSelectionMode = Slick.RowSelectionMode.AllRows; autoSize.allowAddlPercent = 5; } if (colDataTypeOf === 'date') { autoSize.colValueArray = [ new Date(2009, 8, 30, 12, 20, 20) ]; // Sep 30th 2009, 12:20:20 AM } if (colDataTypeOf === 'moment' && typeof moment!=='undefined') { autoSize.colValueArray = [ moment([2009, 8, 30, 12, 20, 20]) ]; // Sep 30th 2009, 12:20:20 AM } } // at this point, the autosizeMode is effectively 'Content', so proceed to get size var colWidth = getColContentSize(columnDef, $gridCanvas, isInit); var addlPercentMultiplier = (autoSize.allowAddlPercent ? (1 + autoSize.allowAddlPercent/100) : 1); colWidth = colWidth * addlPercentMultiplier + options.autosizeColPaddingPx; if (columnDef.minWidth && colWidth < columnDef.minWidth) { colWidth = columnDef.minWidth; } if (columnDef.maxWidth && colWidth > columnDef.maxWidth) { colWidth = columnDef.maxWidth; } autoSize.widthPx = colWidth; } function getColContentSize(columnDef, $gridCanvas, isInit) { var autoSize = columnDef.autoSize; var widthAdjustRatio = 1; // at this point, the autosizeMode is effectively 'Content', so proceed to get size // get header width, if we are taking notice of it var i, ii; var maxColWidth = 0; var headerWidth = 0; if (!autoSize.ignoreHeaderText) { headerWidth = getColHeaderWidth(columnDef); } if (autoSize.colValueArray) { // if an array of values are specified, just pass them in instead of data maxColWidth = getColWidth(columnDef, $gridCanvas, autoSize.colValueArray); return Math.max(headerWidth, maxColWidth); } // select rows to evaluate using rowSelectionMode and rowSelectionCount var rows = getData(); if (rows.getItems) { rows = rows.getItems(); } var rowSelectionMode = (isInit ? autoSize.rowSelectionModeOnInit : undefined) || autoSize.rowSelectionMode; if (rowSelectionMode === Slick.RowSelectionMode.FirstRow) { rows = rows.slice(0,1); } if (rowSelectionMode === Slick.RowSelectionMode.LastRow) { rows = rows.slice(rows.length -1, rows.length); } if (rowSelectionMode === Slick.RowSelectionMode.FirstNRows) { rows = rows.slice(0, autoSize.rowSelectionCount); } // now use valueFilterMode to further filter selected rows if (autoSize.valueFilterMode === Slick.ValueFilterMode.DeDuplicate) { var rowsDict = {}; for (i = 0, ii = rows.length; i < ii; i++) { rowsDict[rows[i][columnDef.field]] = true; } if (Object.keys) { rows = Object.keys(rowsDict); } else { rows = []; for (var i in rowsDict) rows.push(i); } } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetGreatestAndSub) { // get greatest abs value in data var tempVal, maxVal, maxAbsVal = 0; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if (Math.abs(tempVal) > maxAbsVal) { maxVal = tempVal; maxAbsVal = Math.abs(tempVal); } } // now substitute a '9' for all characters (to get widest width) and convert back to a number maxVal = '' + maxVal; maxVal = Array(maxVal.length + 1).join("9"); maxVal = +maxVal; rows = [ maxVal ]; } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestTextAndSub) { // get greatest abs value in data var tempVal, maxLen = 0, maxIndex; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; maxIndex = i; } } // now substitute a 'c' for all characters tempVal = Array(maxLen + 1).join("m"); widthAdjustRatio = options.autosizeTextAvgToMWidthRatio; rows = [ tempVal ]; } if (autoSize.valueFilterMode === Slick.ValueFilterMode.GetLongestText) { // get greatest abs value in data var tempVal, maxLen = 0, maxIndex; for (i = 0, ii = rows.length; i < ii; i++) { tempVal = rows[i][columnDef.field]; if ((tempVal || '').length > maxLen) { maxLen = tempVal.length; maxIndex = i; } } // now substitute a 'c' for all characters tempVal = rows[maxIndex][columnDef.field]; rows = [ tempVal ]; } maxColWidth = getColWidth(columnDef, $gridCanvas, rows) * widthAdjustRatio; return Math.max(headerWidth, maxColWidth); } function getColWidth(columnDef, $gridCanvas, data) { var colIndex = getColumnIndex(columnDef.id); var $rowEl = $('<div class="slick-row ui-widget-content"></div>'); var $cellEl = $('<div class="slick-cell"></div>'); $cellEl.css({ "position": "absolute", "visibility": "hidden", "text-overflow": "initial", "white-space": "nowrap" }); $rowEl.append($cellEl); $gridCanvas.append($rowEl); var len, max = 0, text, maxText, formatterResult, maxWidth = 0, val; // use canvas - very fast, but text-only if (canvas_context && columnDef.autoSize.widthEvalMode === Slick.WidthEvalMode.CanvasTextSize) { canvas_context.font = $cellEl.css("font-size") + " " + $cellEl.css("font-family"); $(data).each(function (index, row) { // row is either an array or values or a single value val = (Array.isArray(row) ? row[columnDef.field] : row); text = '' + val; len = text ? canvas_context.measureText(text).width : 0; if (len > max) { max = len; maxText = text; } }); $cellEl.html(maxText); len = $cellEl.outerWidth(); $rowEl.remove(); return len; } $(data).each(function (index, row) { val = (Array.isArray(row) ? row[columnDef.field] : row); if (columnDef.formatterOverride) { // use formatterOverride as first preference formatterResult = columnDef.formatterOverride(index, colIndex, val, columnDef, row); } else if (columnDef.formatter) { // otherwise, use formatter formatterResult = columnDef.formatter(index, colIndex, val, columnDef, row); } else { // otherwise, use plain text formatterResult = '' + val; } applyFormatResultToCellNode(formatterResult, $cellEl[0]); len = $cellEl.outerWidth(); if (len > max) { max = len; } }); $rowEl.remove(); return max; } function getColHeaderWidth(columnDef) { var width = 0; //if (columnDef && (!columnDef.resizable || columnDef._autoCalcWidth === true)) return; var headerColElId = getUID() + columnDef.id; var headerColEl = document.getElementById(headerColElId); var dummyHeaderColElId = headerColElId + "_"; if (headerColEl) { // headers have been created, use clone technique var clone = headerColEl.cloneNode(true); clone.id = dummyHeaderColElId; clone.style.cssText = 'position: absolute; visibility: hidden;right: auto;text-overflow: initial;white-space: nowrap;'; headerColEl.parentNode.insertBefore(clone, headerColEl); width = clone.offsetWidth; clone.parentNode.removeChild(clone); } else { // headers have not yet been created, create a new node var header = getHeader(columnDef); headerColEl = $("<div class='ui-state-default slick-header-column' />") .html("<span class='slick-column-name'>" + columnDef.name + "</span>") .attr("id", dummyHeaderColElId) .css({ "position": "absolute", "visibility": "hidden", "right": "auto", "text-overflow:": "initial", "white-space": "nowrap" }) .addClass(columnDef.headerCssClass || "") .appendTo(header); width = headerColEl[0].offsetWidth; header[0].removeChild(headerColEl[0]); } return width; } function legacyAutosizeColumns() { var i, c, widths = [], shrinkLeeway = 0, total = 0, prevTotal, availWidth = viewportHasVScroll ? viewportW - scrollbarDimensions.width : viewportW; for (i = 0; i < columns.length; i++) { c = columns[i]; widths.push(c.width); total += c.width; if (c.resizable) { shrinkLeeway += c.width - Math.max(c.minWidth, absoluteColumnMinWidth); } } // shrink prevTotal = total; while (total > availWidth && shrinkLeeway) { var shrinkProportion = (total - availWidth) / shrinkLeeway; for (i = 0; i < columns.length && total > availWidth; i++) { c = columns[i]; var width = widths[i]; if (!c.resizable || width <= c.minWidth || width <= absoluteColumnMinWidth) { continue; } var absMinWidth = Math.max(c.minWidth, absoluteColumnMinWidth); var shrinkSize = Math.floor(shrinkProportion * (width - absMinWidth)) || 1; shrinkSize = Math.min(shrinkSize, width - absMinWidth); total -= shrinkSize; shrinkLeeway -= shrinkSize; widths[i] -= shrinkSize; } if (prevTotal <= total) { // avoid infinite loop break; } prevTotal = total; } // grow prevTotal = total; while (total < availWidth) { var growProportion = availWidth / total; for (i = 0; i < columns.length && total < availWidth; i++) { c = columns[i]; var currentWidth = widths[i]; var growSize; if (!c.resizable || c.maxWidth <= currentWidth) { growSize = 0; } else { growSize = Math.min(Math.floor(growProportion * currentWidth) - currentWidth, (c.maxWidth - currentWidth) || 1000000) || 1; } total += growSize; widths[i] += (total <= availWidth ? growSize : 0); } if (prevTotal >= total) { // avoid infinite loop break; } prevTotal = total; } var reRender = false; for (i = 0; i < columns.length; i++) { if (columns[i].rerenderOnResize && columns[i].width != widths[i]) { reRender = true; } columns[i].width = widths[i]; } reRenderColumns(reRender); } function reRenderColumns(reRender) { applyColumnHeaderWidths(); applyColumnGroupHeaderWidths(); updateCanvasWidth(true); trigger(self.onAutosizeColumns, { "columns": columns}); if (reRender) { invalidateAllRows(); render(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // General ////////////////////////////////////////////////////////////////////////////////////////////// function trigger(evt, args, e) { e = e || new Slick.EventData(); args = args || {}; args.grid = self; return evt.notify(args, e, self); } function getEditorLock() { return options.editorLock; } function getEditController() { return editController; } function getColumnIndex(id) { return columnsById[id]; } function applyColumnGroupHeaderWidths() { if (!treeColumns.hasDepth()) return; for (var depth = $groupHeadersL.length - 1; depth >= 0; depth--) { var groupColumns = treeColumns.getColumnsInDepth(depth); $().add($groupHeadersL[depth]).add($groupHeadersR[depth]).each(function(i) { var $groupHeader = $(this), currentColumnIndex = 0; $groupHeader.width(i === 0? getHeadersWidthL(): getHeadersWidthR()); $groupHeader.children().each(function() { var $groupHeaderColumn = $(this); var m = $(this).data('column'); m.width = 0; m.columns.forEach(function() { var $headerColumn = $groupHeader.next().children(':eq(' + (currentColumnIndex++) + ')'); m.width += $headerColumn.outerWidth(); }); $groupHeaderColumn.width(m.width - headerColumnWidthDiff); }); }); } } function applyColumnHeaderWidths() { if (!initialized) { return; } var h; for (var i = 0, headers = $headers.children(), ii = columns.length; i < ii; i++) { h = $(headers[i]); if (jQueryNewWidthBehaviour) { if (h.outerWidth() !== columns[i].width) { h.outerWidth(columns[i].width); } } else { if (h.width() !== columns[i].width - headerColumnWidthDiff) { h.width(columns[i].width - headerColumnWidthDiff); } } } updateColumnCaches(); } function applyColumnWidths() { var x = 0, w, rule; for (var i = 0; i < columns.length; i++) { w = columns[i].width; rule = getColumnCssRules(i); rule.left.style.left = x + "px"; rule.right.style.right = (((options.frozenColumn != -1 && i > options.frozenColumn) ? canvasWidthR : canvasWidthL) - x - w) + "px"; // If this column is frozen, reset the css left value since the // column starts in a new viewport. if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function setSortColumn(columnId, ascending) { setSortColumns([{ columnId: columnId, sortAsc: ascending}]); } function setSortColumns(cols) { sortColumns = cols; var numberCols = options.numberedMultiColumnSort && sortColumns.length > 1; var headerColumnEls = $headers.children(); headerColumnEls .removeClass("slick-header-column-sorted") .find(".slick-sort-indicator") .removeClass("slick-sort-indicator-asc slick-sort-indicator-desc"); headerColumnEls .find(".slick-sort-indicator-numbered") .text(''); $.each(sortColumns, function(i, col) { if (col.sortAsc == null) { col.sortAsc = true; } var columnIndex = getColumnIndex(col.columnId); if (columnIndex != null) { headerColumnEls.eq(columnIndex) .addClass("slick-header-column-sorted") .find(".slick-sort-indicator") .addClass(col.sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc"); if (numberCols) { headerColumnEls.eq(columnIndex) .find(".slick-sort-indicator-numbered") .text(i+1); } } }); } function getSortColumns() { return sortColumns; } function handleSelectedRangesChanged(e, ranges) { var previousSelectedRows = selectedRows.slice(0); // shallow copy previously selected rows for later comparison selectedRows = []; var hash = {}; for (var i = 0; i < ranges.length; i++) { for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) { if (!hash[j]) { // prevent duplicates selectedRows.push(j); hash[j] = {}; } for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) { if (canCellBeSelected(j, k)) { hash[j][columns[k].id] = options.selectedCellCssClass; } } } } setCellCssStyles(options.selectedCellCssClass, hash); if (simpleArrayEquals(previousSelectedRows, selectedRows)) { trigger(self.onSelectedRowsChanged, {rows: getSelectedRows()}, e); } } // compare 2 simple arrays (integers or strings only, do not use to compare object arrays) function simpleArrayEquals(arr1, arr2) { return Array.isArray(arr1) && Array.isArray(arr2) && arr2.sort().toString() !== arr1.sort().toString(); } function getColumns() { return columns; } function updateColumnCaches() { // Pre-calculate cell boundaries. columnPosLeft = []; columnPosRight = []; var x = 0; for (var i = 0, ii = columns.length; i < ii; i++) { columnPosLeft[i] = x; columnPosRight[i] = x + columns[i].width; if (options.frozenColumn == i) { x = 0; } else { x += columns[i].width; } } } function updateColumnProps() { columnsById = {}; for (var i = 0; i < columns.length; i++) { if (columns[i].width) { columns[i].widthRequest = columns[i].width; } var m = columns[i] = $.extend({}, columnDefaults, columns[i]); m.autoSize = $.extend({}, columnAutosizeDefaults, m.autoSize); columnsById[m.id] = i; if (m.minWidth && m.width < m.minWidth) { m.width = m.minWidth; } if (m.maxWidth && m.width > m.maxWidth) { m.width = m.maxWidth; } if (!m.resizable) { // there is difference between user resizable and autoWidth resizable //m.autoSize.autosizeMode = Slick.ColAutosizeMode.Locked; } } } function setColumns(columnDefinitions) { var _treeColumns = new Slick.TreeColumns(columnDefinitions); if (_treeColumns.hasDepth()) { treeColumns = _treeColumns; columns = treeColumns.extractColumns(); } else { columns = columnDefinitions; } updateColumnProps(); updateColumnCaches(); if (initialized) { setPaneVisibility(); setOverflow(); invalidateAllRows(); createColumnHeaders(); createColumnGroupHeaders(); createColumnFooter(); removeCssRules(); createCssRules(); resizeCanvas(); updateCanvasWidth(); applyColumnHeaderWidths(); applyColumnWidths(); handleScroll(); } } function getOptions() { return options; } function setOptions(args, suppressRender) { if (!getEditorLock().commitCurrentEdit()) { return; } makeActiveCellNormal(); if (args.showColumnHeader !== undefined) { setColumnHeaderVisibility(args.showColumnHeader); } if (options.enableAddRow !== args.enableAddRow) { invalidateRow(getDataLength()); } options = $.extend(options, args); validateAndEnforceOptions(); $viewport.css("overflow-y", options.autoHeight ? "hidden" : "auto"); if (!suppressRender) { render(); } setFrozenOptions(); setScroller(); zombieRowNodeFromLastMouseWheelEvent = null; setColumns(treeColumns.extractColumns()); } function validateAndEnforceOptions() { if (options.autoHeight) { options.leaveSpaceForNewRows = false; } if (options.forceFitColumns) { options.autosizeColsMode = Slick.GridAutosizeColsMode.LegacyForceFit; console.log("forceFitColumns option is deprecated - use autosizeColsMode"); } } function setData(newData, scrollToTop) { data = newData; invalidateAllRows(); updateRowCount(); if (scrollToTop) { scrollTo(0); } } function getData() { return data; } function getDataLength() { if (data.getLength) { return data.getLength(); } else { return data && data.length || 0; } } function getDataLengthIncludingAddNew() { return getDataLength() + (!options.enableAddRow ? 0 : (!pagingActive || pagingIsLastPage ? 1 : 0) ); } function getDataItem(i) { if (data.getItem) { return data.getItem(i); } else { return data[i]; } } function getTopPanel() { return $topPanel[0]; } function setTopPanelVisibility(visible) { if (options.showTopPanel != visible) { options.showTopPanel = visible; if (visible) { $topPanelScroller.slideDown("fast", resizeCanvas); } else { $topPanelScroller.slideUp("fast", resizeCanvas); } } } function setHeaderRowVisibility(visible) { if (options.showHeaderRow != visible) { options.showHeaderRow = visible; if (visible) { $headerRowScroller.slideDown("fast", resizeCanvas); } else { $headerRowScroller.slideUp("fast", resizeCanvas); } } } function setColumnHeaderVisibility(visible, animate) { if (options.showColumnHeader != visible) { options.showColumnHeader = visible; if (visible) { if (animate) { $headerScroller.slideDown("fast", resizeCanvas); } else { $headerScroller.show(); resizeCanvas(); } } else { if (animate) { $headerScroller.slideUp("fast", resizeCanvas); } else { $headerScroller.hide(); resizeCanvas(); } } } } function setFooterRowVisibility(visible) { if (options.showFooterRow != visible) { options.showFooterRow = visible; if (visible) { $footerRowScroller.slideDown("fast", resizeCanvas); } else { $footerRowScroller.slideUp("fast", resizeCanvas); } } } function setPreHeaderPanelVisibility(visible) { if (options.showPreHeaderPanel != visible) { options.showPreHeaderPanel = visible; if (visible) { $preHeaderPanelScroller.slideDown("fast", resizeCanvas); } else { $preHeaderPanelScroller.slideUp("fast", resizeCanvas); } } } function getContainerNode() { return $container.get(0); } ////////////////////////////////////////////////////////////////////////////////////////////// // Rendering / Scrolling function getRowTop(row) { return options.rowHeight * row - offset; } function getRowFromPosition(y) { return Math.floor((y + offset) / options.rowHeight); } function scrollTo(y) { y = Math.max(y, 0); y = Math.min(y, th - $viewportScrollContainerY.height() + ((viewportHasHScroll || hasFrozenColumns()) ? scrollbarDimensions.height : 0)); var oldOffset = offset; page = Math.min(n - 1, Math.floor(y / ph)); offset = Math.round(page * cj); var newScrollTop = y - offset; if (offset != oldOffset) { var range = getVisibleRange(newScrollTop); cleanupRows(range); updateRowPositions(); } if (prevScrollTop != newScrollTop) { vScrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1; lastRenderedScrollTop = ( scrollTop = prevScrollTop = newScrollTop ); if (hasFrozenColumns()) { $viewportTopL[0].scrollTop = newScrollTop; } if (hasFrozenRows) { $viewportBottomL[0].scrollTop = $viewportBottomR[0].scrollTop = newScrollTop; } $viewportScrollContainerY[0].scrollTop = newScrollTop; trigger(self.onViewportChanged, {}); } } function defaultFormatter(row, cell, value, columnDef, dataContext, grid) { if (value == null) { return ""; } else { return (value + "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); } } function getFormatter(row, column) { var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); // look up by id, then index var columnOverrides = rowMetadata && rowMetadata.columns && (rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]); return (columnOverrides && columnOverrides.formatter) || (rowMetadata && rowMetadata.formatter) || column.formatter || (options.formatterFactory && options.formatterFactory.getFormatter(column)) || options.defaultFormatter; } function callFormatter( row, cell, value, m, item, grid ) { var result; // pass metadata to formatter var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; if( metadata ) { var columnData = metadata[m.id] || metadata[cell]; result = getFormatter(row, m)(row, cell, value, m, item, columnData ); } else { result = getFormatter(row, m)(row, cell, value, m, item); } return result; } function getEditor(row, cell) { var column = columns[cell]; var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) { return columnMetadata[column.id].editor; } if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) { return columnMetadata[cell].editor; } return column.editor || (options.editorFactory && options.editorFactory.getEditor(column)); } function getDataItemValueForColumn(item, columnDef) { if (options.dataItemColumnValueExtractor) { return options.dataItemColumnValueExtractor(item, columnDef); } return item[columnDef.field]; } function appendRowHtml(stringArrayL, stringArrayR, row, range, dataLength) { var d = getDataItem(row); var dataLoading = row < dataLength && !d; var rowCss = "slick-row" + (hasFrozenRows && row <= options.frozenRow? ' frozen': '') + (dataLoading ? " loading" : "") + (row === activeRow && options.showCellSelection ? " active" : "") + (row % 2 == 1 ? " odd" : " even"); if (!d) { rowCss += " " + options.addNewRowCssClass; } var metadata = data.getItemMetadata && data.getItemMetadata(row); if (metadata && metadata.cssClasses) { rowCss += " " + metadata.cssClasses; } var frozenRowOffset = getFrozenRowOffset(row); var rowHtml = "<div class='ui-widget-content " + rowCss + "' style='top:" + (getRowTop(row) - frozenRowOffset ) + "px'>"; stringArrayL.push(rowHtml); if (hasFrozenColumns()) { stringArrayR.push(rowHtml); } var colspan, m; for (var i = 0, ii = columns.length; i < ii; i++) { m = columns[i]; colspan = 1; if (metadata && metadata.columns) { var columnData = metadata.columns[m.id] || metadata.columns[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } // Do not render cells outside of the viewport. if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { if (!m.alwaysRenderColumn && columnPosLeft[i] > range.rightPx) { // All columns to the right are outside the range. break; } if (hasFrozenColumns() && ( i > options.frozenColumn )) { appendCellHtml(stringArrayR, row, i, colspan, d); } else { appendCellHtml(stringArrayL, row, i, colspan, d); } } else if (m.alwaysRenderColumn || (hasFrozenColumns() && i <= options.frozenColumn)) { appendCellHtml(stringArrayL, row, i, colspan, d); } if (colspan > 1) { i += (colspan - 1); } } stringArrayL.push("</div>"); if (hasFrozenColumns()) { stringArrayR.push("</div>"); } } function appendCellHtml(stringArray, row, cell, colspan, item) { // stringArray: stringBuilder containing the HTML parts // row, cell: row and column index // colspan: HTML colspan // item: grid data for row var m = columns[cell]; var cellCss = "slick-cell l" + cell + " r" + Math.min(columns.length - 1, cell + colspan - 1) + (m.cssClass ? " " + m.cssClass : ""); if (hasFrozenColumns() && cell <= options.frozenColumn) { cellCss += (" frozen"); } if (row === activeRow && cell === activeCell && options.showCellSelection) { cellCss += (" active"); } // TODO: merge them together in the setter for (var key in cellCssClasses) { if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) { cellCss += (" " + cellCssClasses[key][row][m.id]); } } var value = null, formatterResult = ''; if (item) { value = getDataItemValueForColumn(item, m); formatterResult = getFormatter(row, m)(row, cell, value, m, item, self); if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } } // get addl css class names from object type formatter return and from string type return of onBeforeAppendCell var addlCssClasses = trigger(self.onBeforeAppendCell, { row: row, cell: cell, value: value, dataContext: item }) || ''; addlCssClasses += (formatterResult && formatterResult.addClasses ? (addlCssClasses ? ' ' : '') + formatterResult.addClasses : ''); var toolTip = formatterResult && formatterResult.toolTip ? "title='" + formatterResult.toolTip + "'" : ''; var customAttrStr = ''; if(m.hasOwnProperty('cellAttrs') && m.cellAttrs instanceof Object) { for (var key in m.cellAttrs) { if (m.cellAttrs.hasOwnProperty(key)) { customAttrStr += ' ' + key + '="' + m.cellAttrs[key] + '" '; } } } stringArray.push("<div class='" + cellCss + (addlCssClasses ? ' ' + addlCssClasses : '') + "' " + toolTip + customAttrStr + ">"); // if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet) if (item) { stringArray.push(Object.prototype.toString.call(formatterResult) !== '[object Object]' ? formatterResult : formatterResult.text); } stringArray.push("</div>"); rowsCache[row].cellRenderQueue.push(cell); rowsCache[row].cellColSpans[cell] = colspan; } function cleanupRows(rangeToKeep) { for (var i in rowsCache) { var removeFrozenRow = true; if (hasFrozenRows && ( ( options.frozenBottom && i >= actualFrozenRow ) // Frozen bottom rows || ( !options.frozenBottom && i <= actualFrozenRow ) // Frozen top rows ) ) { removeFrozenRow = false; } if (( ( i = parseInt(i, 10)) !== activeRow ) && ( i < rangeToKeep.top || i > rangeToKeep.bottom ) && ( removeFrozenRow ) ) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidate() { updateRowCount(); invalidateAllRows(); render(); } function invalidateAllRows() { if (currentEditor) { makeActiveCellNormal(); } for (var row in rowsCache) { removeRowFromCache(row); } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function queuePostProcessedRowForCleanup(cacheEntry, postProcessedRow, rowIdx) { postProcessgroupId++; // store and detach node for later async cleanup for (var columnIdx in postProcessedRow) { if (postProcessedRow.hasOwnProperty(columnIdx)) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cacheEntry.cellNodesByColumnIdx[ columnIdx | 0], columnIdx: columnIdx | 0, rowIdx: rowIdx }); } } postProcessedCleanupQueue.push({ actionType: 'R', groupId: postProcessgroupId, node: cacheEntry.rowNode }); $(cacheEntry.rowNode).detach(); } function queuePostProcessedCellForCleanup(cellnode, columnIdx, rowIdx) { postProcessedCleanupQueue.push({ actionType: 'C', groupId: postProcessgroupId, node: cellnode, columnIdx: columnIdx, rowIdx: rowIdx }); $(cellnode).detach(); } function removeRowFromCache(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } if (rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[0] || (hasFrozenColumns() && rowNodeFromLastMouseWheelEvent == cacheEntry.rowNode[1])) { cacheEntry.rowNode.hide(); zombieRowNodeFromLastMouseWheelEvent = cacheEntry.rowNode; } else { cacheEntry.rowNode.each(function() { this.parentElement.removeChild(this); }); } delete rowsCache[row]; delete postProcessedRows[row]; renderedRows--; counter_rows_removed++; } function invalidateRows(rows) { var i, rl; if (!rows || !rows.length) { return; } vScrollDir = 0; rl = rows.length; for (i = 0; i < rl; i++) { if (currentEditor && activeRow === rows[i]) { makeActiveCellNormal(); } if (rowsCache[rows[i]]) { removeRowFromCache(rows[i]); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } } function invalidateRow(row) { if (!row && row !== 0) { return; } invalidateRows([row]); } function applyFormatResultToCellNode(formatterResult, cellNode, suppressRemove) { if (formatterResult === null || formatterResult === undefined) { formatterResult = ''; } if (Object.prototype.toString.call(formatterResult) !== '[object Object]') { cellNode.innerHTML = formatterResult; return; } cellNode.innerHTML = formatterResult.text; if (formatterResult.removeClasses && !suppressRemove) { $(cellNode).removeClass(formatterResult.removeClasses); } if (formatterResult.addClasses) { $(cellNode).addClass(formatterResult.addClasses); } if (formatterResult.toolTip) { $(cellNode).attr("title", formatterResult.toolTip); } } function updateCell(row, cell) { var cellNode = getCellNode(row, cell); if (!cellNode) { return; } var m = columns[cell], d = getDataItem(row); if (currentEditor && activeRow === row && activeCell === cell) { currentEditor.loadValue(d); } else { var formatterResult = d ? getFormatter(row, m)(row, cell, getDataItemValueForColumn(d, m), m, d, self) : ""; applyFormatResultToCellNode(formatterResult, cellNode); invalidatePostProcessingResults(row); } } function updateRow(row) { var cacheEntry = rowsCache[row]; if (!cacheEntry) { return; } ensureCellNodesInRowsCache(row); var formatterResult, d = getDataItem(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx], node = cacheEntry.cellNodesByColumnIdx[columnIdx][0]; if (row === activeRow && columnIdx === activeCell && currentEditor) { currentEditor.loadValue(d); } else if (d) { formatterResult = getFormatter(row, m)(row, columnIdx, getDataItemValueForColumn(d, m), m, d, self); applyFormatResultToCellNode(formatterResult, node); } else { node.innerHTML = ""; } } invalidatePostProcessingResults(row); } function getViewportHeight() { if (options.autoHeight) { var fullHeight = $paneHeaderL.outerHeight(); fullHeight += ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; fullHeight += ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; fullHeight += (getCanvasWidth() > viewportW) ? scrollbarDimensions.height : 0; viewportH = options.rowHeight * getDataLengthIncludingAddNew() + ( ( options.frozenColumn == -1 ) ? fullHeight : 0 ); } else { var columnNamesH = ( options.showColumnHeader ) ? parseFloat($.css($headerScroller[0], "height")) + getVBoxDelta($headerScroller) : 0; topPanelH = ( options.showTopPanel ) ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0; headerRowH = ( options.showHeaderRow ) ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0; footerRowH = ( options.showFooterRow ) ? options.footerRowHeight + getVBoxDelta($footerRowScroller) : 0; var preHeaderH = (options.createPreHeaderPanel && options.showPreHeaderPanel) ? options.preHeaderPanelHeight + getVBoxDelta($preHeaderPanelScroller) : 0; viewportH = parseFloat($.css($container[0], "height", true)) - parseFloat($.css($container[0], "paddingTop", true)) - parseFloat($.css($container[0], "paddingBottom", true)) - columnNamesH - topPanelH - headerRowH - footerRowH - preHeaderH; } numVisibleRows = Math.ceil(viewportH / options.rowHeight); return viewportH; } function getViewportWidth() { viewportW = parseFloat($container.width()); } function resizeCanvas() { if (!initialized) { return; } paneTopH = 0; paneBottomH = 0; viewportTopH = 0; viewportBottomH = 0; getViewportWidth(); getViewportHeight(); // Account for Frozen Rows if (hasFrozenRows) { if (options.frozenBottom) { paneTopH = viewportH - frozenRowsHeight - scrollbarDimensions.height; paneBottomH = frozenRowsHeight + scrollbarDimensions.height; } else { paneTopH = frozenRowsHeight; paneBottomH = viewportH - frozenRowsHeight; } } else { paneTopH = viewportH; } // The top pane includes the top panel and the header row paneTopH += topPanelH + headerRowH + footerRowH; if (hasFrozenColumns() && options.autoHeight) { paneTopH += scrollbarDimensions.height; } // The top viewport does not contain the top panel or header row viewportTopH = paneTopH - topPanelH - headerRowH - footerRowH; if (options.autoHeight) { if (hasFrozenColumns()) { $container.height( paneTopH + parseFloat($.css($headerScrollerL[0], "height")) ); } $paneTopL.css('position', 'relative'); } $paneTopL.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); var paneBottomTop = $paneTopL.position().top + paneTopH; if (!options.autoHeight) { $viewportTopL.height(viewportTopH); } if (hasFrozenColumns()) { $paneTopR.css({ 'top': $paneHeaderL.height(), 'height': paneTopH }); $viewportTopR.height(viewportTopH); if (hasFrozenRows) { $paneBottomL.css({ 'top': paneBottomTop, 'height': paneBottomH }); $paneBottomR.css({ 'top': paneBottomTop, 'height': paneBottomH }); $viewportBottomR.height(paneBottomH); } } else { if (hasFrozenRows) { $paneBottomL.css({ 'width': '100%', 'height': paneBottomH }); $paneBottomL.css('top', paneBottomTop); } } if (hasFrozenRows) { $viewportBottomL.height(paneBottomH); if (options.frozenBottom) { $canvasBottomL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasBottomR.height(frozenRowsHeight); } } else { $canvasTopL.height(frozenRowsHeight); if (hasFrozenColumns()) { $canvasTopR.height(frozenRowsHeight); } } } else { $viewportTopR.height(viewportTopH); } if (!scrollbarDimensions || !scrollbarDimensions.width) { scrollbarDimensions = measureScrollbar(); } if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit) { autosizeColumns(); } updateRowCount(); handleScroll(); // Since the width has changed, force the render() to reevaluate virtually rendered cells. lastRenderedScrollLeft = -1; render(); } function updatePagingStatusFromView( pagingInfo ) { pagingActive = (pagingInfo.pageSize !== 0); pagingIsLastPage = (pagingInfo.pageNum == pagingInfo.totalPages - 1); } function updateRowCount() { if (!initialized) { return; } var dataLength = getDataLength(); var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); var numberOfRows = 0; var oldH = ( hasFrozenRows && !options.frozenBottom ) ? $canvasBottomL.height() : $canvasTopL.height(); if (hasFrozenRows ) { var numberOfRows = getDataLength() - options.frozenRow; } else { var numberOfRows = dataLengthIncludingAddNew + (options.leaveSpaceForNewRows ? numVisibleRows - 1 : 0); } var tempViewportH = $viewportScrollContainerY.height(); var oldViewportHasVScroll = viewportHasVScroll; // with autoHeight, we do not need to accommodate the vertical scroll bar viewportHasVScroll = options.alwaysShowVerticalScroll || !options.autoHeight && (numberOfRows * options.rowHeight > tempViewportH); makeActiveCellNormal(); // remove the rows that are now outside of the data range // this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows var r1 = dataLength - 1; for (var i in rowsCache) { if (i > r1) { removeRowFromCache(i); } } if (options.enableAsyncPostRenderCleanup) { startPostProcessingCleanup(); } if (activeCellNode && activeRow > r1) { resetActiveCell(); } var oldH = h; if (options.autoHeight) { h = options.rowHeight * numberOfRows; } else { th = Math.max(options.rowHeight * numberOfRows, tempViewportH - scrollbarDimensions.height); if (th < maxSupportedCssHeight) { // just one page h = ph = th; n = 1; cj = 0; } else { // break into pages h = maxSupportedCssHeight; ph = h / 100; n = Math.floor(th / ph); cj = (th - h) / (n - 1); } } if (h !== oldH) { if (hasFrozenRows && !options.frozenBottom) { $canvasBottomL.css("height", h); if (hasFrozenColumns()) { $canvasBottomR.css("height", h); } } else { $canvasTopL.css("height", h); $canvasTopR.css("height", h); } scrollTop = $viewportScrollContainerY[0].scrollTop; } var oldScrollTopInRange = (scrollTop + offset <= th - tempViewportH); if (th == 0 || scrollTop == 0) { page = offset = 0; } else if (oldScrollTopInRange) { // maintain virtual position scrollTo(scrollTop + offset); } else { // scroll to bottom scrollTo(th - tempViewportH); } if (h != oldH && options.autoHeight) { resizeCanvas(); } if (options.autosizeColsMode === Slick.GridAutosizeColsMode.LegacyForceFit && oldViewportHasVScroll != viewportHasVScroll) { autosizeColumns(); } updateCanvasWidth(false); } function getVisibleRange(viewportTop, viewportLeft) { if (viewportTop == null) { viewportTop = scrollTop; } if (viewportLeft == null) { viewportLeft = scrollLeft; } return { top: getRowFromPosition(viewportTop), bottom: getRowFromPosition(viewportTop + viewportH) + 1, leftPx: viewportLeft, rightPx: viewportLeft + viewportW }; } function getRenderedRange(viewportTop, viewportLeft) { var range = getVisibleRange(viewportTop, viewportLeft); var buffer = Math.round(viewportH / options.rowHeight); var minBuffer = options.minRowBuffer; if (vScrollDir == -1) { range.top -= buffer; range.bottom += minBuffer; } else if (vScrollDir == 1) { range.top -= minBuffer; range.bottom += buffer; } else { range.top -= minBuffer; range.bottom += minBuffer; } range.top = Math.max(0, range.top); range.bottom = Math.min(getDataLengthIncludingAddNew() - 1, range.bottom); range.leftPx -= viewportW; range.rightPx += viewportW; range.leftPx = Math.max(0, range.leftPx); range.rightPx = Math.min(canvasWidth, range.rightPx); return range; } function ensureCellNodesInRowsCache(row) { var cacheEntry = rowsCache[row]; if (cacheEntry) { if (cacheEntry.cellRenderQueue.length) { var $lastNode = cacheEntry.rowNode.children().last(); while (cacheEntry.cellRenderQueue.length) { var columnIdx = cacheEntry.cellRenderQueue.pop(); cacheEntry.cellNodesByColumnIdx[columnIdx] = $lastNode; $lastNode = $lastNode.prev(); // Hack to retrieve the frozen columns because if ($lastNode.length === 0) { $lastNode = $(cacheEntry.rowNode[0]).children().last(); } } } } } function cleanUpCells(range, row) { // Ignore frozen rows if (hasFrozenRows && ( ( options.frozenBottom && row > actualFrozenRow ) // Frozen bottom rows || ( row <= actualFrozenRow ) // Frozen top rows ) ) { return; } var totalCellsRemoved = 0; var cacheEntry = rowsCache[row]; // Remove cells outside the range. var cellsToRemove = []; for (var i in cacheEntry.cellNodesByColumnIdx) { // I really hate it when people mess with Array.prototype. if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(i)) { continue; } // This is a string, so it needs to be cast back to a number. i = i | 0; // Ignore frozen columns if (i <= options.frozenColumn) { continue; } // Ignore alwaysRenderedColumns if (Array.isArray(columns) && columns[i] && columns[i].alwaysRenderColumn){ continue; } var colspan = cacheEntry.cellColSpans[i]; if (columnPosLeft[i] > range.rightPx || columnPosRight[Math.min(columns.length - 1, i + colspan - 1)] < range.leftPx) { if (!(row == activeRow && i == activeCell)) { cellsToRemove.push(i); } } } var cellToRemove; while ((cellToRemove = cellsToRemove.pop()) != null) { cacheEntry.cellNodesByColumnIdx[cellToRemove][0].parentElement.removeChild(cacheEntry.cellNodesByColumnIdx[cellToRemove][0]); delete cacheEntry.cellColSpans[cellToRemove]; delete cacheEntry.cellNodesByColumnIdx[cellToRemove]; if (postProcessedRows[row]) { delete postProcessedRows[row][cellToRemove]; } totalCellsRemoved++; } } function cleanUpAndRenderCells(range) { var cacheEntry; var stringArray = []; var processedRows = []; var cellsAdded; var totalCellsAdded = 0; var colspan; for (var row = range.top, btm = range.bottom; row <= btm; row++) { cacheEntry = rowsCache[row]; if (!cacheEntry) { continue; } // cellRenderQueue populated in renderRows() needs to be cleared first ensureCellNodesInRowsCache(row); cleanUpCells(range, row); // Render missing cells. cellsAdded = 0; var metadata = data.getItemMetadata && data.getItemMetadata(row); metadata = metadata && metadata.columns; var d = getDataItem(row); // TODO: shorten this loop (index? heuristics? binary search?) for (var i = 0, ii = columns.length; i < ii; i++) { // Cells to the right are outside the range. if (columnPosLeft[i] > range.rightPx) { break; } // Already rendered. if ((colspan = cacheEntry.cellColSpans[i]) != null) { i += (colspan > 1 ? colspan - 1 : 0); continue; } colspan = 1; if (metadata) { var columnData = metadata[columns[i].id] || metadata[i]; colspan = (columnData && columnData.colspan) || 1; if (colspan === "*") { colspan = ii - i; } } if (columnPosRight[Math.min(ii - 1, i + colspan - 1)] > range.leftPx) { appendCellHtml(stringArray, row, i, colspan, d); cellsAdded++; } i += (colspan > 1 ? colspan - 1 : 0); } if (cellsAdded) { totalCellsAdded += cellsAdded; processedRows.push(row); } } if (!stringArray.length) { return; } var x = document.createElement("div"); x.innerHTML = stringArray.join(""); var processedRow; var node; while ((processedRow = processedRows.pop()) != null) { cacheEntry = rowsCache[processedRow]; var columnIdx; while ((columnIdx = cacheEntry.cellRenderQueue.pop()) != null) { node = x.lastChild; if (hasFrozenColumns() && (columnIdx > options.frozenColumn)) { cacheEntry.rowNode[1].appendChild(node); } else { cacheEntry.rowNode[0].appendChild(node); } cacheEntry.cellNodesByColumnIdx[columnIdx] = $(node); } } } function renderRows(range) { var stringArrayL = [], stringArrayR = [], rows = [], needToReselectCell = false, dataLength = getDataLength(); for (var i = range.top, ii = range.bottom; i <= ii; i++) { if (rowsCache[i] || ( hasFrozenRows && options.frozenBottom && i == getDataLength() )) { continue; } renderedRows++; rows.push(i); // Create an entry right away so that appendRowHtml() can // start populatating it. rowsCache[i] = { "rowNode": null, // ColSpans of rendered cells (by column idx). // Can also be used for checking whether a cell has been rendered. "cellColSpans": [], // Cell nodes (by column idx). Lazy-populated by ensureCellNodesInRowsCache(). "cellNodesByColumnIdx": [], // Column indices of cell nodes that have been rendered, but not yet indexed in // cellNodesByColumnIdx. These are in the same order as cell nodes added at the // end of the row. "cellRenderQueue": [] }; appendRowHtml(stringArrayL, stringArrayR, i, range, dataLength); if (activeCellNode && activeRow === i) { needToReselectCell = true; } counter_rows_rendered++; } if (!rows.length) { return; } var x = document.createElement("div"), xRight = document.createElement("div"); x.innerHTML = stringArrayL.join(""); xRight.innerHTML = stringArrayR.join(""); for (var i = 0, ii = rows.length; i < ii; i++) { if (( hasFrozenRows ) && ( rows[i] >= actualFrozenRow )) { if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)) .add($(xRight.firstChild).appendTo($canvasBottomR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasBottomL)); } } else if (hasFrozenColumns()) { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)) .add($(xRight.firstChild).appendTo($canvasTopR)); } else { rowsCache[rows[i]].rowNode = $() .add($(x.firstChild).appendTo($canvasTopL)); } } if (needToReselectCell) { activeCellNode = getCellNode(activeRow, activeCell); } } function startPostProcessing() { if (!options.enableAsyncPostRender) { return; } clearTimeout(h_postrender); h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); } function startPostProcessingCleanup() { if (!options.enableAsyncPostRenderCleanup) { return; } clearTimeout(h_postrenderCleanup); h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } function invalidatePostProcessingResults(row) { // change status of columns to be re-rendered for (var columnIdx in postProcessedRows[row]) { if (postProcessedRows[row].hasOwnProperty(columnIdx)) { postProcessedRows[row][columnIdx] = 'C'; } } postProcessFromRow = Math.min(postProcessFromRow, row); postProcessToRow = Math.max(postProcessToRow, row); startPostProcessing(); } function updateRowPositions() { for (var row in rowsCache) { var rowNumber = row ? parseInt(row) : 0; rowsCache[rowNumber].rowNode[0].style.top = getRowTop(rowNumber) + "px"; } } function render() { if (!initialized) { return; } scrollThrottle.dequeue(); var visible = getVisibleRange(); var rendered = getRenderedRange(); // remove rows no longer in the viewport cleanupRows(rendered); // add new rows & missing cells in existing rows if (lastRenderedScrollLeft != scrollLeft) { if ( hasFrozenRows ) { var renderedFrozenRows = jQuery.extend(true, {}, rendered); if (options.frozenBottom) { renderedFrozenRows.top=actualFrozenRow; renderedFrozenRows.bottom=getDataLength(); } else { renderedFrozenRows.top=0; renderedFrozenRows.bottom=options.frozenRow; } cleanUpAndRenderCells(renderedFrozenRows); } cleanUpAndRenderCells(rendered); } // render missing rows renderRows(rendered); // Render frozen rows if (hasFrozenRows) { if (options.frozenBottom) { renderRows({ top: actualFrozenRow, bottom: getDataLength() - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } else { renderRows({ top: 0, bottom: options.frozenRow - 1, leftPx: rendered.leftPx, rightPx: rendered.rightPx }); } } postProcessFromRow = visible.top; postProcessToRow = Math.min(getDataLengthIncludingAddNew() - 1, visible.bottom); startPostProcessing(); lastRenderedScrollTop = scrollTop; lastRenderedScrollLeft = scrollLeft; h_render = null; trigger(self.onRendered, { startRow: visible.top, endRow: visible.bottom, grid: self }); } function handleHeaderScroll() { handleElementScroll($headerScrollContainer[0]); } function handleHeaderRowScroll() { var scrollLeft = $headerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleFooterRowScroll() { var scrollLeft = $footerRowScrollContainer[0].scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handlePreHeaderPanelScroll() { handleElementScroll($preHeaderPanelScroller[0]); } function handleElementScroll(element) { var scrollLeft = element.scrollLeft; if (scrollLeft != $viewportScrollContainerX[0].scrollLeft) { $viewportScrollContainerX[0].scrollLeft = scrollLeft; } } function handleScroll() { scrollTop = $viewportScrollContainerY[0].scrollTop; scrollLeft = $viewportScrollContainerX[0].scrollLeft; return _handleScroll(false); } function _handleScroll(isMouseWheel) { var maxScrollDistanceY = $viewportScrollContainerY[0].scrollHeight - $viewportScrollContainerY[0].clientHeight; var maxScrollDistanceX = $viewportScrollContainerY[0].scrollWidth - $viewportScrollContainerY[0].clientWidth; // Ceiling the max scroll values if (scrollTop > maxScrollDistanceY) { scrollTop = maxScrollDistanceY; } if (scrollLeft > maxScrollDistanceX) { scrollLeft = maxScrollDistanceX; } var vScrollDist = Math.abs(scrollTop - prevScrollTop); var hScrollDist = Math.abs(scrollLeft - prevScrollLeft); if (hScrollDist) { prevScrollLeft = scrollLeft; $viewportScrollContainerX[0].scrollLeft = scrollLeft; $headerScrollContainer[0].scrollLeft = scrollLeft; $topPanelScroller[0].scrollLeft = scrollLeft; $headerRowScrollContainer[0].scrollLeft = scrollLeft; if (options.createFooterRow) { $footerRowScrollContainer[0].scrollLeft = scrollLeft; } if (options.createPreHeaderPanel) { if (hasFrozenColumns()) { $preHeaderPanelScrollerR[0].scrollLeft = scrollLeft; } else { $preHeaderPanelScroller[0].scrollLeft = scrollLeft; } } if (hasFrozenColumns()) { if (hasFrozenRows) { $viewportTopR[0].scrollLeft = scrollLeft; } } else { if (hasFrozenRows) { $viewportTopL[0].scrollLeft = scrollLeft; } } } if (vScrollDist) { vScrollDir = prevScrollTop < scrollTop ? 1 : -1; prevScrollTop = scrollTop; if (isMouseWheel) { $viewportScrollContainerY[0].scrollTop = scrollTop; } if (hasFrozenColumns()) { if (hasFrozenRows && !options.frozenBottom) { $viewportBottomL[0].scrollTop = scrollTop; } else { $viewportTopL[0].scrollTop = scrollTop; } } // switch virtual pages if needed if (vScrollDist < viewportH) { scrollTo(scrollTop + offset); } else { var oldOffset = offset; if (h == viewportH) { page = 0; } else { page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph))); } offset = Math.round(page * cj); if (oldOffset != offset) { invalidateAllRows(); } } } if (hScrollDist || vScrollDist) { var dx = Math.abs(lastRenderedScrollLeft - scrollLeft); var dy = Math.abs(lastRenderedScrollTop - scrollTop); if (dx > 20 || dy > 20) { // if rendering is forced or scrolling is small enough to be "easy", just render if (options.forceSyncScrolling || (dy < viewportH && dx < viewportW)) { render(); } else { // otherwise, perform "difficult" renders at a capped frequency scrollThrottle.enqueue(); } trigger(self.onViewportChanged, {}); } } trigger(self.onScroll, {scrollLeft: scrollLeft, scrollTop: scrollTop}); if (hScrollDist || vScrollDist) return true; return false; } /* limits the frequency at which the provided action is executed. call enqueue to execute the action - it will execute either immediately or, if it was executed less than minPeriod_ms in the past, as soon as minPeriod_ms has expired. call dequeue to cancel any pending action. */ function ActionThrottle(action, minPeriod_ms) { var blocked = false; var queued = false; function enqueue() { if (!blocked) { blockAndExecute(); } else { queued = true; } } function dequeue() { queued = false; } function blockAndExecute() { blocked = true; setTimeout(unblock, minPeriod_ms); action(); } function unblock() { if (queued) { dequeue(); blockAndExecute(); } else { blocked = false; } } return { enqueue: enqueue, dequeue: dequeue }; } function asyncPostProcessRows() { var dataLength = getDataLength(); while (postProcessFromRow <= postProcessToRow) { var row = (vScrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--; var cacheEntry = rowsCache[row]; if (!cacheEntry || row >= dataLength) { continue; } if (!postProcessedRows[row]) { postProcessedRows[row] = {}; } ensureCellNodesInRowsCache(row); for (var columnIdx in cacheEntry.cellNodesByColumnIdx) { if (!cacheEntry.cellNodesByColumnIdx.hasOwnProperty(columnIdx)) { continue; } columnIdx = columnIdx | 0; var m = columns[columnIdx]; var processedStatus = postProcessedRows[row][columnIdx]; // C=cleanup and re-render, R=rendered if (m.asyncPostRender && processedStatus !== 'R') { var node = cacheEntry.cellNodesByColumnIdx[columnIdx]; if (node) { m.asyncPostRender(node, row, getDataItem(row), m, (processedStatus === 'C')); } postProcessedRows[row][columnIdx] = 'R'; } } h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay); return; } } function asyncPostProcessCleanupRows() { if (postProcessedCleanupQueue.length > 0) { var groupId = postProcessedCleanupQueue[0].groupId; // loop through all queue members with this groupID while (postProcessedCleanupQueue.length > 0 && postProcessedCleanupQueue[0].groupId == groupId) { var entry = postProcessedCleanupQueue.shift(); if (entry.actionType == 'R') { $(entry.node).remove(); } if (entry.actionType == 'C') { var column = columns[entry.columnIdx]; if (column.asyncPostRenderCleanup && entry.node) { // cleanup must also remove element column.asyncPostRenderCleanup(entry.node, entry.rowIdx, column); } } } // call this function again after the specified delay h_postrenderCleanup = setTimeout(asyncPostProcessCleanupRows, options.asyncPostRenderCleanupDelay); } } function updateCellCssStylesOnRenderedRows(addedHash, removedHash) { var node, columnId, addedRowHash, removedRowHash; for (var row in rowsCache) { removedRowHash = removedHash && removedHash[row]; addedRowHash = addedHash && addedHash[row]; if (removedRowHash) { for (columnId in removedRowHash) { if (!addedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).removeClass(removedRowHash[columnId]); } } } } if (addedRowHash) { for (columnId in addedRowHash) { if (!removedRowHash || removedRowHash[columnId] != addedRowHash[columnId]) { node = getCellNode(row, getColumnIndex(columnId)); if (node) { $(node).addClass(addedRowHash[columnId]); } } } } } } function addCellCssStyles(key, hash) { if (cellCssClasses[key]) { throw new Error("addCellCssStyles: cell CSS hash with key '" + key + "' already exists."); } cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, null); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function removeCellCssStyles(key) { if (!cellCssClasses[key]) { return; } updateCellCssStylesOnRenderedRows(null, cellCssClasses[key]); delete cellCssClasses[key]; trigger(self.onCellCssStylesChanged, { "key": key, "hash": null, "grid": self }); } function setCellCssStyles(key, hash) { var prevHash = cellCssClasses[key]; cellCssClasses[key] = hash; updateCellCssStylesOnRenderedRows(hash, prevHash); trigger(self.onCellCssStylesChanged, { "key": key, "hash": hash, "grid": self }); } function getCellCssStyles(key) { return cellCssClasses[key]; } function flashCell(row, cell, speed) { speed = speed || 100; function toggleCellClass($cell, times) { if (!times) { return; } setTimeout(function () { $cell.queue(function () { $cell.toggleClass(options.cellFlashingCssClass).dequeue(); toggleCellClass($cell, times - 1); }); }, speed); } if (rowsCache[row]) { var $cell = $(getCellNode(row, cell)); toggleCellClass($cell, 4); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Interactivity function handleMouseWheel(e, delta, deltaX, deltaY) { var $rowNode = $(e.target).closest(".slick-row"); var rowNode = $rowNode[0]; if (rowNode != rowNodeFromLastMouseWheelEvent) { var $gridCanvas = $rowNode.parents('.grid-canvas'); var left = $gridCanvas.hasClass('grid-canvas-left'); if (zombieRowNodeFromLastMouseWheelEvent && zombieRowNodeFromLastMouseWheelEvent[left? 0:1] != rowNode) { var zombieRow = zombieRowNodeFromLastMouseWheelEvent[left || zombieRowNodeFromLastMouseWheelEvent.length == 1? 0:1]; zombieRow.parentElement.removeChild(zombieRow); zombieRowNodeFromLastMouseWheelEvent = null; } rowNodeFromLastMouseWheelEvent = rowNode; } scrollTop = Math.max(0, $viewportScrollContainerY[0].scrollTop - (deltaY * options.rowHeight)); scrollLeft = $viewportScrollContainerX[0].scrollLeft + (deltaX * 10); var handled = _handleScroll(true); if (handled) e.preventDefault(); } function handleDragInit(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragInit, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } // if nobody claims to be handling drag'n'drop by stopping immediate propagation, // cancel out of it return false; } function handleDragStart(e, dd) { var cell = getCellFromEvent(e); if (!cell || !cellExists(cell.row, cell.cell)) { return false; } var retval = trigger(self.onDragStart, dd, e); if (e.isImmediatePropagationStopped()) { return retval; } return false; } function handleDrag(e, dd) { return trigger(self.onDrag, dd, e); } function handleDragEnd(e, dd) { trigger(self.onDragEnd, dd, e); } function handleKeyDown(e) { trigger(self.onKeyDown, {row: activeRow, cell: activeCell}, e); var handled = e.isImmediatePropagationStopped(); var keyCode = Slick.keyCode; if (!handled) { if (!e.shiftKey && !e.altKey) { if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf(e.which) > -1) { return; } } if (e.which == keyCode.HOME) { handled = (e.ctrlKey) ? navigateTop() : navigateRowStart(); } else if (e.which == keyCode.END) { handled = (e.ctrlKey) ? navigateBottom() : navigateRowEnd(); } } } if (!handled) { if (!e.shiftKey && !e.altKey && !e.ctrlKey) { // editor may specify an array of keys to bubble if (options.editable && currentEditor && currentEditor.keyCaptureList) { if (currentEditor.keyCaptureList.indexOf( e.which ) > -1) { return; } } if (e.which == keyCode.ESCAPE) { if (!getEditorLock().isActive()) { return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event) } cancelEditAndSetFocus(); } else if (e.which == keyCode.PAGE_DOWN) { navigatePageDown(); handled = true; } else if (e.which == keyCode.PAGE_UP) { navigatePageUp(); handled = true; } else if (e.which == keyCode.LEFT) { handled = navigateLeft(); } else if (e.which == keyCode.RIGHT) { handled = navigateRight(); } else if (e.which == keyCode.UP) { handled = navigateUp(); } else if (e.which == keyCode.DOWN) { handled = navigateDown(); } else if (e.which == keyCode.TAB) { handled = navigateNext(); } else if (e.which == keyCode.ENTER) { if (options.editable) { if (currentEditor) { // adding new row if (activeRow === getDataLength()) { navigateDown(); } else { commitEditAndSetFocus(); } } else { if (getEditorLock().commitCurrentEdit()) { makeActiveCellEditable(undefined, undefined, e); } } } handled = true; } } else if (e.which == keyCode.TAB && e.shiftKey && !e.ctrlKey && !e.altKey) { handled = navigatePrev(); } } if (handled) { // the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it e.stopPropagation(); e.preventDefault(); try { e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.) } // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl" // (hitting control key only, nothing else), "Shift" (maybe others) catch (error) { } } } function handleClick(e) { if (!currentEditor) { // if this click resulted in some cell child node getting focus, // don't steal it back - keyboard events will still bubble up // IE9+ seems to default DIVs to tabIndex=0 instead of -1, so check for cell clicks directly. if (e.target != document.activeElement || $(e.target).hasClass("slick-cell")) { setFocus(); } } var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } // this optimisation causes trouble - MLeibman #329 //if ((activeCell != cell.cell || activeRow != cell.row) && canCellBeActive(cell.row, cell.cell)) { if (canCellBeActive(cell.row, cell.cell)) { if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) { scrollRowIntoView(cell.row, false); var preClickModeOn = (e.target && e.target.className === Slick.preClickClassName); var column = columns[cell.cell]; var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit); setActiveCellInternal(getCellNode(cell.row, cell.cell), null, preClickModeOn, suppressActiveCellChangedEvent, e); } } } function handleContextMenu(e) { var $cell = $(e.target).closest(".slick-cell", $canvas); if ($cell.length === 0) { return; } // are we editing this cell? if (activeCellNode === $cell[0] && currentEditor !== null) { return; } trigger(self.onContextMenu, {}, e); } function handleDblClick(e) { var cell = getCellFromEvent(e); if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) { return; } trigger(self.onDblClick, {row: cell.row, cell: cell.cell}, e); if (e.isImmediatePropagationStopped()) { return; } if (options.editable) { gotoCell(cell.row, cell.cell, true, e); } } function handleHeaderMouseEnter(e) { trigger(self.onHeaderMouseEnter, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderMouseLeave(e) { trigger(self.onHeaderMouseLeave, { "column": $(this).data("column"), "grid": self }, e); } function handleHeaderContextMenu(e) { var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); trigger(self.onHeaderContextMenu, {column: column}, e); } function handleHeaderClick(e) { if (columnResizeDragging) return; var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns"); var column = $header && $header.data("column"); if (column) { trigger(self.onHeaderClick, {column: column}, e); } } function handleFooterContextMenu(e) { var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns"); var column = $footer && $footer.data("column"); trigger(self.onFooterContextMenu, {column: column}, e); } function handleFooterClick(e) { var $footer = $(e.target).closest(".slick-footerrow-column", ".slick-footerrow-columns"); var column = $footer && $footer.data("column"); trigger(self.onFooterClick, {column: column}, e); } function handleMouseEnter(e) { trigger(self.onMouseEnter, {}, e); } function handleMouseLeave(e) { trigger(self.onMouseLeave, {}, e); } function cellExists(row, cell) { return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length); } function getCellFromPoint(x, y) { var row = getRowFromPosition(y); var cell = 0; var w = 0; for (var i = 0; i < columns.length && w < x; i++) { w += columns[i].width; cell++; } if (cell < 0) { cell = 0; } return {row: row, cell: cell - 1}; } function getCellFromNode(cellNode) { // read column number from .l<columnNumber> CSS class var cls = /l\d+/.exec(cellNode.className); if (!cls) { throw new Error("getCellFromNode: cannot get cell - " + cellNode.className); } return parseInt(cls[0].substr(1, cls[0].length - 1), 10); } function getRowFromNode(rowNode) { for (var row in rowsCache) { for (var i in rowsCache[row].rowNode) { if (rowsCache[row].rowNode[i] === rowNode) return (row ? parseInt(row) : 0); } } return null; } function getFrozenRowOffset(row) { var offset = ( hasFrozenRows ) ? ( options.frozenBottom ) ? ( row >= actualFrozenRow ) ? ( h < viewportTopH ) ? ( actualFrozenRow * options.rowHeight ) : h : 0 : ( row >= actualFrozenRow ) ? frozenRowsHeight : 0 : 0; return offset; } function getCellFromEvent(e) { var row, cell; var $cell = $(e.target).closest(".slick-cell", $canvas); if (!$cell.length) { return null; } row = getRowFromNode($cell[0].parentNode); if (hasFrozenRows) { var c = $cell.parents('.grid-canvas').offset(); var rowOffset = 0; var isBottom = $cell.parents('.grid-canvas-bottom').length; if (isBottom) { rowOffset = ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } row = getCellFromPoint(e.clientX - c.left, e.clientY - c.top + rowOffset + $(document).scrollTop()).row; } cell = getCellFromNode($cell[0]); if (row == null || cell == null) { return null; } else { return { "row": row, "cell": cell }; } } function getCellNodeBox(row, cell) { if (!cellExists(row, cell)) { return null; } var frozenRowOffset = getFrozenRowOffset(row); var y1 = getRowTop(row) - frozenRowOffset; var y2 = y1 + options.rowHeight - 1; var x1 = 0; for (var i = 0; i < cell; i++) { x1 += columns[i].width; if (options.frozenColumn == i) { x1 = 0; } } var x2 = x1 + columns[cell].width; return { top: y1, left: x1, bottom: y2, right: x2 }; } ////////////////////////////////////////////////////////////////////////////////////////////// // Cell switching function resetActiveCell() { setActiveCellInternal(null, false); } function setFocus() { if (tabbingDirection == -1) { $focusSink[0].focus(); } else { $focusSink2[0].focus(); } } function scrollCellIntoView(row, cell, doPaging) { scrollRowIntoView(row, doPaging); if (cell <= options.frozenColumn) { return; } var colspan = getColspan(row, cell); internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell + (colspan > 1 ? colspan - 1 : 0)]); } function internalScrollColumnIntoView(left, right) { var scrollRight = scrollLeft + $viewportScrollContainerX.width(); if (left < scrollLeft) { $viewportScrollContainerX.scrollLeft(left); handleScroll(); render(); } else if (right > scrollRight) { $viewportScrollContainerX.scrollLeft(Math.min(left, right - $viewportScrollContainerX[0].clientWidth)); handleScroll(); render(); } } function scrollColumnIntoView(cell) { internalScrollColumnIntoView(columnPosLeft[cell], columnPosRight[cell]); } function setActiveCellInternal(newCell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent, e) { if (activeCellNode !== null) { makeActiveCellNormal(); $(activeCellNode).removeClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).removeClass("active"); } } var activeCellChanged = (activeCellNode !== newCell); activeCellNode = newCell; if (activeCellNode != null) { var $activeCellNode = $(activeCellNode); var $activeCellOffset = $activeCellNode.offset(); var rowOffset = Math.floor($activeCellNode.parents('.grid-canvas').offset().top); var isBottom = $activeCellNode.parents('.grid-canvas-bottom').length; if (hasFrozenRows && isBottom) { rowOffset -= ( options.frozenBottom ) ? $canvasTopL.height() : frozenRowsHeight; } var cell = getCellFromPoint($activeCellOffset.left, Math.ceil($activeCellOffset.top) - rowOffset); activeRow = cell.row; activeCell = activePosX = activeCell = activePosX = getCellFromNode(activeCellNode); $activeCellNode.addClass("active"); if (rowsCache[activeRow]) { $(rowsCache[activeRow].rowNode).addClass('active'); } if (opt_editMode == null) { opt_editMode = (activeRow == getDataLength()) || options.autoEdit; } if (options.showCellSelection) { $(activeCellNode).addClass("active"); $(rowsCache[activeRow].rowNode).addClass("active"); } if (options.editable && opt_editMode && isCellPotentiallyEditable(activeRow, activeCell)) { clearTimeout(h_editorLoader); if (options.asyncEditorLoading) { h_editorLoader = setTimeout(function () { makeActiveCellEditable(undefined, preClickModeOn, e); }, options.asyncEditorLoadDelay); } else { makeActiveCellEditable(undefined, preClickModeOn, e); } } } else { activeRow = activeCell = null; } // this optimisation causes trouble - MLeibman #329 //if (activeCellChanged) { if (!suppressActiveCellChangedEvent) { trigger(self.onActiveCellChanged, getActiveCell()); } //} } function clearTextSelection() { if (document.selection && document.selection.empty) { try { //IE fails here if selected element is not in dom document.selection.empty(); } catch (e) { } } else if (window.getSelection) { var sel = window.getSelection(); if (sel && sel.removeAllRanges) { sel.removeAllRanges(); } } } function isCellPotentiallyEditable(row, cell) { var dataLength = getDataLength(); // is the data for this row loaded? if (row < dataLength && !getDataItem(row)) { return false; } // are we in the Add New row? can we create new from this cell? if (columns[cell].cannotTriggerInsert && row >= dataLength) { return false; } // does this cell have an editor? if (!getEditor(row, cell)) { return false; } return true; } function makeActiveCellNormal() { if (!currentEditor) { return; } trigger(self.onBeforeCellEditorDestroy, {editor: currentEditor}); currentEditor.destroy(); currentEditor = null; if (activeCellNode) { var d = getDataItem(activeRow); $(activeCellNode).removeClass("editable invalid"); if (d) { var column = columns[activeCell]; var formatter = getFormatter(activeRow, column); var formatterResult = formatter(activeRow, activeCell, getDataItemValueForColumn(d, column), column, d, self); applyFormatResultToCellNode(formatterResult, activeCellNode); invalidatePostProcessingResults(activeRow); } } // if there previously was text selected on a page (such as selected text in the edit cell just removed), // IE can't set focus to anything else correctly if (navigator.userAgent.toLowerCase().match(/msie/)) { clearTextSelection(); } getEditorLock().deactivate(editController); } function makeActiveCellEditable(editor, preClickModeOn, e) { if (!activeCellNode) { return; } if (!options.editable) { throw new Error("Grid : makeActiveCellEditable : should never get called when options.editable is false"); } // cancel pending async call if there is one clearTimeout(h_editorLoader); if (!isCellPotentiallyEditable(activeRow, activeCell)) { return; } var columnDef = columns[activeCell]; var item = getDataItem(activeRow); if (trigger(self.onBeforeEditCell, {row: activeRow, cell: activeCell, item: item, column: columnDef}) === false) { setFocus(); return; } getEditorLock().activate(editController); $(activeCellNode).addClass("editable"); var useEditor = editor || getEditor(activeRow, activeCell); // don't clear the cell if a custom editor is passed through if (!editor && !useEditor.suppressClearOnEdit) { activeCellNode.innerHTML = ""; } var metadata = data.getItemMetadata && data.getItemMetadata(activeRow); metadata = metadata && metadata.columns; var columnMetaData = metadata && ( metadata[columnDef.id] || metadata[activeCell] ); currentEditor = new useEditor({ grid: self, gridPosition: absBox($container[0]), position: absBox(activeCellNode), container: activeCellNode, column: columnDef, columnMetaData: columnMetaData, item: item || {}, event: e, commitChanges: commitEditAndSetFocus, cancelChanges: cancelEditAndSetFocus }); if (item) { currentEditor.loadValue(item); if (preClickModeOn && currentEditor.preClick) { currentEditor.preClick(); } } serializedEditorValue = currentEditor.serializeValue(); if (currentEditor.position) { handleActiveCellPositionChange(); } } function commitEditAndSetFocus() { // if the commit fails, it would do so due to a validation error // if so, do not steal the focus from the editor if (getEditorLock().commitCurrentEdit()) { setFocus(); if (options.autoEdit) { navigateDown(); } } } function cancelEditAndSetFocus() { if (getEditorLock().cancelCurrentEdit()) { setFocus(); } } function absBox(elem) { var box = { top: elem.offsetTop, left: elem.offsetLeft, bottom: 0, right: 0, width: $(elem).outerWidth(), height: $(elem).outerHeight(), visible: true }; box.bottom = box.top + box.height; box.right = box.left + box.width; // walk up the tree var offsetParent = elem.offsetParent; while ((elem = elem.parentNode) != document.body) { if (elem == null) break; if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible") { box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight; } if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible") { box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth; } box.left -= elem.scrollLeft; box.top -= elem.scrollTop; if (elem === offsetParent) { box.left += elem.offsetLeft; box.top += elem.offsetTop; offsetParent = elem.offsetParent; } box.bottom = box.top + box.height; box.right = box.left + box.width; } return box; } function getActiveCellPosition() { return absBox(activeCellNode); } function getGridPosition() { return absBox($container[0]); } function handleActiveCellPositionChange() { if (!activeCellNode) { return; } trigger(self.onActiveCellPositionChanged, {}); if (currentEditor) { var cellBox = getActiveCellPosition(); if (currentEditor.show && currentEditor.hide) { if (!cellBox.visible) { currentEditor.hide(); } else { currentEditor.show(); } } if (currentEditor.position) { currentEditor.position(cellBox); } } } function getCellEditor() { return currentEditor; } function getActiveCell() { if (!activeCellNode) { return null; } else { return {row: activeRow, cell: activeCell}; } } function getActiveCellNode() { return activeCellNode; } function scrollRowIntoView(row, doPaging) { if (!hasFrozenRows || ( !options.frozenBottom && row > actualFrozenRow - 1 ) || ( options.frozenBottom && row < actualFrozenRow - 1 ) ) { var viewportScrollH = $viewportScrollContainerY.height(); // if frozen row on top // subtract number of frozen row var rowNumber = ( hasFrozenRows && !options.frozenBottom ? row - options.frozenRow : row ); var rowAtTop = rowNumber * options.rowHeight; var rowAtBottom = (rowNumber + 1) * options.rowHeight - viewportScrollH + (viewportHasHScroll ? scrollbarDimensions.height : 0); // need to page down? if ((rowNumber + 1) * options.rowHeight > scrollTop + viewportScrollH + offset) { scrollTo(doPaging ? rowAtTop : rowAtBottom); render(); } // or page up? else if (rowNumber * options.rowHeight < scrollTop + offset) { scrollTo(doPaging ? rowAtBottom : rowAtTop); render(); } } } function scrollRowToTop(row) { scrollTo(row * options.rowHeight); render(); } function scrollPage(dir) { var deltaRows = dir * numVisibleRows; /// First fully visible row crosses the line with /// y == bottomOfTopmostFullyVisibleRow var bottomOfTopmostFullyVisibleRow = scrollTop + options.rowHeight - 1; scrollTo((getRowFromPosition(bottomOfTopmostFullyVisibleRow) + deltaRows) * options.rowHeight); render(); if (options.enableCellNavigation && activeRow != null) { var row = activeRow + deltaRows; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); if (row >= dataLengthIncludingAddNew) { row = dataLengthIncludingAddNew - 1; } if (row < 0) { row = 0; } var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } } function navigatePageDown() { scrollPage(1); } function navigatePageUp() { scrollPage(-1); } function navigateTop() { navigateToRow(0); } function navigateBottom() { navigateToRow(getDataLength()-1); } function navigateToRow(row) { var num_rows = getDataLength(); if (!num_rows) return true; if (row < 0) row = 0; else if (row >= num_rows) row = num_rows - 1; scrollCellIntoView(row, 0, true); if (options.enableCellNavigation && activeRow != null) { var cell = 0, prevCell = null; var prevActivePosX = activePosX; while (cell <= activePosX) { if (canCellBeActive(row, cell)) { prevCell = cell; } cell += getColspan(row, cell); } if (prevCell !== null) { setActiveCellInternal(getCellNode(row, prevCell)); activePosX = prevActivePosX; } else { resetActiveCell(); } } return true; } function getColspan(row, cell) { var metadata = data.getItemMetadata && data.getItemMetadata(row); if (!metadata || !metadata.columns) { return 1; } var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell]; var colspan = (columnData && columnData.colspan); if (colspan === "*") { colspan = columns.length - cell; } else { colspan = colspan || 1; } return colspan; } function findFirstFocusableCell(row) { var cell = 0; while (cell < columns.length) { if (canCellBeActive(row, cell)) { return cell; } cell += getColspan(row, cell); } return null; } function findLastFocusableCell(row) { var cell = 0; var lastFocusableCell = null; while (cell < columns.length) { if (canCellBeActive(row, cell)) { lastFocusableCell = cell; } cell += getColspan(row, cell); } return lastFocusableCell; } function gotoRight(row, cell, posX) { if (cell >= columns.length) { return null; } do { cell += getColspan(row, cell); } while (cell < columns.length && !canCellBeActive(row, cell)); if (cell < columns.length) { return { "row": row, "cell": cell, "posX": cell }; } return null; } function gotoLeft(row, cell, posX) { if (cell <= 0) { return null; } var firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell === null || firstFocusableCell >= cell) { return null; } var prev = { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; var pos; while (true) { pos = gotoRight(prev.row, prev.cell, prev.posX); if (!pos) { return null; } if (pos.cell >= cell) { return prev; } prev = pos; } } function gotoDown(row, cell, posX) { var prevCell; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); while (true) { if (++row >= dataLengthIncludingAddNew) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoUp(row, cell, posX) { var prevCell; while (true) { if (--row < 0) { return null; } prevCell = cell = 0; while (cell <= posX) { prevCell = cell; cell += getColspan(row, cell); } if (canCellBeActive(row, prevCell)) { return { "row": row, "cell": prevCell, "posX": posX }; } } } function gotoNext(row, cell, posX) { if (row == null && cell == null) { row = cell = posX = 0; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos = gotoRight(row, cell, posX); if (pos) { return pos; } var firstFocusableCell = null; var dataLengthIncludingAddNew = getDataLengthIncludingAddNew(); // if at last row, cycle through columns rather than get stuck in the last one if (row === dataLengthIncludingAddNew - 1) { row--; } while (++row < dataLengthIncludingAddNew) { firstFocusableCell = findFirstFocusableCell(row); if (firstFocusableCell !== null) { return { "row": row, "cell": firstFocusableCell, "posX": firstFocusableCell }; } } return null; } function gotoPrev(row, cell, posX) { if (row == null && cell == null) { row = getDataLengthIncludingAddNew() - 1; cell = posX = columns.length - 1; if (canCellBeActive(row, cell)) { return { "row": row, "cell": cell, "posX": cell }; } } var pos; var lastSelectableCell; while (!pos) { pos = gotoLeft(row, cell, posX); if (pos) { break; } if (--row < 0) { return null; } cell = 0; lastSelectableCell = findLastFocusableCell(row); if (lastSelectableCell !== null) { pos = { "row": row, "cell": lastSelectableCell, "posX": lastSelectableCell }; } } return pos; } function gotoRowStart(row, cell, posX) { var newCell = findFirstFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function gotoRowEnd(row, cell, posX) { var newCell = findLastFocusableCell(row); if (newCell === null) return null; return { "row": row, "cell": newCell, "posX": newCell }; } function navigateRight() { return navigate("right"); } function navigateLeft() { return navigate("left"); } function navigateDown() { return navigate("down"); } function navigateUp() { return navigate("up"); } function navigateNext() { return navigate("next"); } function navigatePrev() { return navigate("prev"); } function navigateRowStart() { return navigate("home"); } function navigateRowEnd() { return navigate("end"); } /** * @param {string} dir Navigation direction. * @return {boolean} Whether navigation resulted in a change of active cell. */ function navigate(dir) { if (!options.enableCellNavigation) { return false; } if (!activeCellNode && dir != "prev" && dir != "next") { return false; } if (!getEditorLock().commitCurrentEdit()) { return true; } setFocus(); var tabbingDirections = { "up": -1, "down": 1, "left": -1, "right": 1, "prev": -1, "next": 1, "home": -1, "end": 1 }; tabbingDirection = tabbingDirections[dir]; var stepFunctions = { "up": gotoUp, "down": gotoDown, "left": gotoLeft, "right": gotoRight, "prev": gotoPrev, "next": gotoNext, "home": gotoRowStart, "end": gotoRowEnd }; var stepFn = stepFunctions[dir]; var pos = stepFn(activeRow, activeCell, activePosX); if (pos) { if (hasFrozenRows && options.frozenBottom & pos.row == getDataLength()) { return; } var isAddNewRow = (pos.row == getDataLength()); if (( !options.frozenBottom && pos.row >= actualFrozenRow ) || ( options.frozenBottom && pos.row < actualFrozenRow ) ) { scrollCellIntoView(pos.row, pos.cell, !isAddNewRow && options.emulatePagingWhenScrolling); } setActiveCellInternal(getCellNode(pos.row, pos.cell)); activePosX = pos.posX; return true; } else { setActiveCellInternal(getCellNode(activeRow, activeCell)); return false; } } function getCellNode(row, cell) { if (rowsCache[row]) { ensureCellNodesInRowsCache(row); try { if (rowsCache[row].cellNodesByColumnIdx.length > cell) { return rowsCache[row].cellNodesByColumnIdx[cell][0]; } else { return null; } } catch (e) { return rowsCache[row].cellNodesByColumnIdx[cell]; } } return null; } function setActiveCell(row, cell, opt_editMode, preClickModeOn, suppressActiveCellChangedEvent) { if (!initialized) { return; } if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return; } if (!options.enableCellNavigation) { return; } scrollCellIntoView(row, cell, false); setActiveCellInternal(getCellNode(row, cell), opt_editMode, preClickModeOn, suppressActiveCellChangedEvent); } function canCellBeActive(row, cell) { if (!options.enableCellNavigation || row >= getDataLengthIncludingAddNew() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.focusable !== "undefined") { return !!rowMetadata.focusable; } var columnMetadata = rowMetadata && rowMetadata.columns; if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable !== "undefined") { return !!columnMetadata[columns[cell].id].focusable; } if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable !== "undefined") { return !!columnMetadata[cell].focusable; } return !!columns[cell].focusable; } function canCellBeSelected(row, cell) { if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) { return false; } var rowMetadata = data.getItemMetadata && data.getItemMetadata(row); if (rowMetadata && typeof rowMetadata.selectable !== "undefined") { return !!rowMetadata.selectable; } var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]); if (columnMetadata && typeof columnMetadata.selectable !== "undefined") { return !!columnMetadata.selectable; } return !!columns[cell].selectable; } function gotoCell(row, cell, forceEdit, e) { if (!initialized) { return; } if (!canCellBeActive(row, cell)) { return; } if (!getEditorLock().commitCurrentEdit()) { return; } scrollCellIntoView(row, cell, false); var newCell = getCellNode(row, cell); // if selecting the 'add new' row, start editing right away var column = columns[cell]; var suppressActiveCellChangedEvent = !!(options.editable && column && column.editor && options.suppressActiveCellChangeOnEdit); setActiveCellInternal(newCell, (forceEdit || (row === getDataLength()) || options.autoEdit), null, suppressActiveCellChangedEvent, e); // if no editor was created, set the focus back on the grid if (!currentEditor) { setFocus(); } } ////////////////////////////////////////////////////////////////////////////////////////////// // IEditor implementation for the editor lock function commitCurrentEdit() { var item = getDataItem(activeRow); var column = columns[activeCell]; if (currentEditor) { if (currentEditor.isValueChanged()) { var validationResults = currentEditor.validate(); if (validationResults.valid) { if (activeRow < getDataLength()) { var editCommand = { row: activeRow, cell: activeCell, editor: currentEditor, serializedValue: currentEditor.serializeValue(), prevSerializedValue: serializedEditorValue, execute: function () { this.editor.applyValue(item, this.serializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item }); }, undo: function () { this.editor.applyValue(item, this.prevSerializedValue); updateRow(this.row); trigger(self.onCellChange, { row: this.row, cell: this.cell, item: item }); } }; if (options.editCommandHandler) { makeActiveCellNormal(); options.editCommandHandler(item, column, editCommand); } else { editCommand.execute(); makeActiveCellNormal(); } } else { var newItem = {}; currentEditor.applyValue(newItem, currentEditor.serializeValue()); makeActiveCellNormal(); trigger(self.onAddNewRow, {item: newItem, column: column}); } // check whether the lock has been re-acquired by event handlers return !getEditorLock().isActive(); } else { // Re-add the CSS class to trigger transitions, if any. $(activeCellNode).removeClass("invalid"); $(activeCellNode).width(); // force layout $(activeCellNode).addClass("invalid"); trigger(self.onValidationError, { editor: currentEditor, cellNode: activeCellNode, validationResults: validationResults, row: activeRow, cell: activeCell, column: column }); currentEditor.focus(); return false; } } makeActiveCellNormal(); } return true; } function cancelCurrentEdit() { makeActiveCellNormal(); return true; } function rowsToRanges(rows) { var ranges = []; var lastCell = columns.length - 1; for (var i = 0; i < rows.length; i++) { ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell)); } return ranges; } function getSelectedRows() { if (!selectionModel) { throw new Error("Selection model is not set"); } return selectedRows; } function setSelectedRows(rows) { if (!selectionModel) { throw new Error("Selection model is not set"); } if (self && self.getEditorLock && !self.getEditorLock().isActive()) { selectionModel.setSelectedRanges(rowsToRanges(rows)); } } ////////////////////////////////////////////////////////////////////////////////////////////// // Debug this.debug = function () { var s = ""; s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered); s += ("\n" + "counter_rows_removed: " + counter_rows_removed); s += ("\n" + "renderedRows: " + renderedRows); s += ("\n" + "numVisibleRows: " + numVisibleRows); s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight); s += ("\n" + "n(umber of pages): " + n); s += ("\n" + "(current) page: " + page); s += ("\n" + "page height (ph): " + ph); s += ("\n" + "vScrollDir: " + vScrollDir); alert(s); }; // a debug helper to be able to access private members this.eval = function (expr) { return eval(expr); }; ////////////////////////////////////////////////////////////////////////////////////////////// // Public API $.extend(this, { "slickGridVersion": "2.4.14", // Events "onScroll": new Slick.Event(), "onSort": new Slick.Event(), "onHeaderMouseEnter": new Slick.Event(), "onHeaderMouseLeave": new Slick.Event(), "onHeaderContextMenu": new Slick.Event(), "onHeaderClick": new Slick.Event(), "onHeaderCellRendered": new Slick.Event(), "onBeforeHeaderCellDestroy": new Slick.Event(), "onHeaderRowCellRendered": new Slick.Event(), "onFooterRowCellRendered": new Slick.Event(), "onFooterContextMenu": new Slick.Event(), "onFooterClick": new Slick.Event(), "onBeforeHeaderRowCellDestroy": new Slick.Event(), "onBeforeFooterRowCellDestroy": new Slick.Event(), "onMouseEnter": new Slick.Event(), "onMouseLeave": new Slick.Event(), "onClick": new Slick.Event(), "onDblClick": new Slick.Event(), "onContextMenu": new Slick.Event(), "onKeyDown": new Slick.Event(), "onAddNewRow": new Slick.Event(), "onBeforeAppendCell": new Slick.Event(), "onValidationError": new Slick.Event(), "onViewportChanged": new Slick.Event(), "onColumnsReordered": new Slick.Event(), "onColumnsResized": new Slick.Event(), "onCellChange": new Slick.Event(), "onBeforeEditCell": new Slick.Event(), "onBeforeCellEditorDestroy": new Slick.Event(), "onBeforeDestroy": new Slick.Event(), "onActiveCellChanged": new Slick.Event(), "onActiveCellPositionChanged": new Slick.Event(), "onDragInit": new Slick.Event(), "onDragStart": new Slick.Event(), "onDrag": new Slick.Event(), "onDragEnd": new Slick.Event(), "onSelectedRowsChanged": new Slick.Event(), "onCellCssStylesChanged": new Slick.Event(), "onAutosizeColumns": new Slick.Event(), "onRendered": new Slick.Event(), // Methods "registerPlugin": registerPlugin, "unregisterPlugin": unregisterPlugin, "getPluginByName": getPluginByName, "getColumns": getColumns, "setColumns": setColumns, "getColumnIndex": getColumnIndex, "updateColumnHeader": updateColumnHeader, "setSortColumn": setSortColumn, "setSortColumns": setSortColumns, "getSortColumns": getSortColumns, "autosizeColumns": autosizeColumns, "autosizeColumn": autosizeColumn, "getOptions": getOptions, "setOptions": setOptions, "getData": getData, "getDataLength": getDataLength, "getDataItem": getDataItem, "setData": setData, "getSelectionModel": getSelectionModel, "setSelectionModel": setSelectionModel, "getSelectedRows": getSelectedRows, "setSelectedRows": setSelectedRows, "getContainerNode": getContainerNode, "updatePagingStatusFromView": updatePagingStatusFromView, "applyFormatResultToCellNode": applyFormatResultToCellNode, "render": render, "invalidate": invalidate, "invalidateRow": invalidateRow, "invalidateRows": invalidateRows, "invalidateAllRows": invalidateAllRows, "updateCell": updateCell, "updateRow": updateRow, "getViewport": getVisibleRange, "getRenderedRange": getRenderedRange, "resizeCanvas": resizeCanvas, "updateRowCount": updateRowCount, "scrollRowIntoView": scrollRowIntoView, "scrollRowToTop": scrollRowToTop, "scrollCellIntoView": scrollCellIntoView, "scrollColumnIntoView": scrollColumnIntoView, "getCanvasNode": getCanvasNode, "getUID": getUID, "getHeaderColumnWidthDiff": getHeaderColumnWidthDiff, "getScrollbarDimensions": getScrollbarDimensions, "getHeadersWidth": getHeadersWidth, "getCanvasWidth": getCanvasWidth, "getCanvases": getCanvases, "getActiveCanvasNode": getActiveCanvasNode, "setActiveCanvasNode": setActiveCanvasNode, "getViewportNode": getViewportNode, "getActiveViewportNode": getActiveViewportNode, "setActiveViewportNode": setActiveViewportNode, "focus": setFocus, "scrollTo": scrollTo, "getCellFromPoint": getCellFromPoint, "getCellFromEvent": getCellFromEvent, "getActiveCell": getActiveCell, "setActiveCell": setActiveCell, "getActiveCellNode": getActiveCellNode, "getActiveCellPosition": getActiveCellPosition, "resetActiveCell": resetActiveCell, "editActiveCell": makeActiveCellEditable, "getCellEditor": getCellEditor, "getCellNode": getCellNode, "getCellNodeBox": getCellNodeBox, "canCellBeSelected": canCellBeSelected, "canCellBeActive": canCellBeActive, "navigatePrev": navigatePrev, "navigateNext": navigateNext, "navigateUp": navigateUp, "navigateDown": navigateDown, "navigateLeft": navigateLeft, "navigateRight": navigateRight, "navigatePageUp": navigatePageUp, "navigatePageDown": navigatePageDown, "navigateTop": navigateTop, "navigateBottom": navigateBottom, "navigateRowStart": navigateRowStart, "navigateRowEnd": navigateRowEnd, "gotoCell": gotoCell, "getTopPanel": getTopPanel, "setTopPanelVisibility": setTopPanelVisibility, "getPreHeaderPanel": getPreHeaderPanel, "getPreHeaderPanelLeft": getPreHeaderPanel, "getPreHeaderPanelRight": getPreHeaderPanelRight, "setPreHeaderPanelVisibility": setPreHeaderPanelVisibility, "getHeader": getHeader, "getHeaderColumn": getHeaderColumn, "setHeaderRowVisibility": setHeaderRowVisibility, "getHeaderRow": getHeaderRow, "getHeaderRowColumn": getHeaderRowColumn, "setFooterRowVisibility": setFooterRowVisibility, "getFooterRow": getFooterRow, "getFooterRowColumn": getFooterRowColumn, "getGridPosition": getGridPosition, "flashCell": flashCell, "addCellCssStyles": addCellCssStyles, "setCellCssStyles": setCellCssStyles, "removeCellCssStyles": removeCellCssStyles, "getCellCssStyles": getCellCssStyles, "getFrozenRowOffset": getFrozenRowOffset, "setColumnHeaderVisibility": setColumnHeaderVisibility, "init": finishInitialization, "destroy": destroy, // IEditor implementation "getEditorLock": getEditorLock, "getEditController": getEditController }); init(); } }(jQuery));
extend1994/cdnjs
ajax/libs/6pac-slickgrid/2.4.14/slick.grid.js
JavaScript
mit
194,952
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); var path = require('path'); var buildDir = 'build'; var installDir = 'install'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { concat_debug: { files: ['<%= concat.debug.src %>'], tasks: ['concat:debug'] }, ts_debug: { files: ['<%= ts.debug.src %>'], tasks: ['ts:debug'] }, ts_test: { files: ['<%= ts.test.src %>'], tasks: ['ts:test'] }, less: { files: ['src/assets/less/listcontrol.less'], tasks: ['less:debug'] }, copy: { files: [ 'src/htmls/**/*', 'lib/**/*', 'build/js/**/*.js', 'build/assets/css/**/*.css', 'src/demo/**/*', ], tasks: ['copy:install', 'jasmine_node'] }, configFiles: { files: ['Gruntfile.js'], options: { reload: true, }, }, }, copy: { install: { files: [ { expand: true, cwd: 'src/htmls', src: ['**/*'], dest: path.join(installDir), filter: 'isFile' }, { expand: true, cwd: 'lib', src: ['*'], dest: path.join(installDir, 'lib'), filter: 'isFile' }, { expand: true, cwd: 'lib/bower', src: ['**/*'], dest: path.join(installDir, 'lib'), filter: 'isFile' }, { expand: true, cwd: 'lib/bootstrap', src: ['**/*'], dest: path.join(installDir, 'lib/bootstrap'), filter: 'isFile' }, { expand: true, src: ['test/**/*.js'], dest: path.join(installDir, 'js'), filter: 'isFile' }, { expand: true, cwd: 'build', src: ['js/**/*.js', 'assets/css/**/*.css'], dest: path.join(installDir), filter: 'isFile' }, { expand: true, cwd: 'src/demo', src: ['**/*.html'], dest: path.join(installDir), filter: 'isFile' }, { expand: true, cwd: 'src/demo', src: ['js/**/*', 'css/**/*'], dest: path.join(installDir, 'demo'), filter: 'isFile' }, ] } }, bower: { install: { options: { targetDir: './lib/bower', cleanup: true, }, }, }, clean: ['build', 'install'], karma: { unit: { configFile: 'karma.config.js', singleRun: true, browsers: ['Chrome', 'IE', 'FireFox'] } }, jasmine_node: { options: { forceExit: true, match: '.', matchall: false, extensions: 'js', specNameMatcher: 'jasmine.spec', jUnit: { report: true, savePath : "reports/jasmine/", useDotNotation: true, consolidate: true } }, all: ['install/js/test/'] }, less: { debug: { options: { paths: ['src/assets/css'], }, files: { 'build/assets/css/listcontrol.css' : 'src/assets/less/listcontrol.less', } }, }, concat: { debug: { src: [ 'src/scripts/copyright.p.ts', 'src/scripts/fundamental/head.p.ts', 'src/scripts/fundamental/lifecycle/IDisposable.p.ts', 'src/scripts/fundamental/lifecycle/Disposer.p.ts', 'src/scripts/fundamental/tail.p.ts', 'src/scripts/head.p.ts', 'src/scripts/support.p.ts', 'src/scripts/definitions.p.ts', 'src/scripts/TableViewEditOperation.p.ts', 'src/scripts/TableViewKeySelectOperation.p.ts', 'src/scripts/TableViewMouseSelectOperation.p.ts', 'src/scripts/TableViewEditOperation.p.ts', 'src/scripts/TableViewReorderColumnOperation.p.ts', 'src/scripts/TableViewResizeColumnOperation.p.ts', 'src/scripts/TableView.p.ts', 'src/scripts/StackView.p.ts', 'src/scripts/Operator.p.ts', 'src/scripts/Theme.p.ts', 'src/scripts/RenderAndEditor.p.ts', 'src/scripts/Range.p.ts', 'src/scripts/Position.p.ts', 'src/scripts/Selection.p.ts', 'src/scripts/listcontrol.p.ts', 'src/scripts/tail.p.ts', ], dest: 'build/ts/listcontrol.ts' }, }, ts: { debug: { src: ['build/ts/listcontrol.ts', 'inc/*.d.ts'], outDir: ['build/js'], options: { target: 'es5', // module: 'amd', declaration: false, removeComments: false, }, }, test: { src: ['test/*.ts', 'inc/*.d.ts'], outDir: ['build/js/test'], options: { target: 'es5', // module: 'amd', declaration: false, removeComments: false, }, }, }, uglify: { ship: { files: { 'build/js/listcontrol.min.js': ['build/js/listcontrol.js'], }, }, }, jsdoc: { dist: { src: ['build/js/listcontrol.js'], options: { destination: 'doc', readme: 'README.md', configure: 'jsdoc.config.js', } }, }, }); grunt.registerTask('prepare', ['bower:install']); grunt.registerTask('install', ['copy:install']); grunt.registerTask('build:debug', ['less:debug', 'concat:debug', 'ts:debug', 'install']); grunt.registerTask('build:ship', ['less:debug', 'concat:debug', 'ts:debug', 'uglify', 'install']); grunt.registerTask('build', 'build:debug'); grunt.registerTask('test:karma', ['ts:test', 'install', 'karma']); grunt.registerTask('test:jasmine', ['ts:test', 'install', 'jasmine_node']); grunt.registerTask('test', ['ts:test', 'install', 'jasmine_node', 'karma']); grunt.registerTask('all:debug', ['clean', 'prepare', 'less:debug', 'concat:debug', 'ts:debug', 'ts:test', 'install', 'jasmine_node', 'karma']); grunt.registerTask('all:ship', ['clean', 'prepare', 'less:debug', 'concat:debug', 'ts:debug', 'uglify', 'ts:test', 'install', 'jasmine_node', 'karma']); grunt.registerTask('all', 'all:debug'); grunt.registerTask('default', function () { console.log('Use grunt build to build'); }); };
ksimple/kGrid
Gruntfile.js
JavaScript
mit
8,441
const SET_PROJECT_FIELDS_MODAL_STATE = "obs-show/project_fields_model/SET_PROJECT_FIELDS_MODAL_STATE"; export default function reducer( state = { show: false }, action ) { switch ( action.type ) { case SET_PROJECT_FIELDS_MODAL_STATE: return Object.assign( { }, action.newState ); default: // nothing to see here } return state; } export function setProjectFieldsModalState( newState ) { return { type: SET_PROJECT_FIELDS_MODAL_STATE, newState }; }
calonso-conabio/inaturalist
app/webpack/observations/show/ducks/project_fields_modal.js
JavaScript
mit
490
var dest = './build', src = './src', mui = '../src'; module.exports = { browserSync: { server: { // We're serving the src folder as well // for sass sourcemap linking baseDir: [dest, src] }, files: [ dest + '/**' ] }, less: { src: src + '/less/main.less', watch: [ src + '/less/**', mui + '/less/**' ], dest: dest }, markup: { src: src + "/www/**", dest: dest }, fontIcons: { src: src + "/less/font-icons/**", dest: dest + '/font-icons' }, browserify: { // Enable source maps debug: true, extensions: [ '.jsx' ], // A separate bundle will be generated for each // bundle config in the list below bundleConfigs: [{ entries: src + '/app/app.jsx', dest: dest, outputName: 'app.js' }] } };
121nexus/material-ui
docs/gulp/config.js
JavaScript
mit
841
export {default} from 'ember-frost-bunsen/components/detail'
sandersky/ember-frost-bunsen
app/components/frost-bunsen-detail.js
JavaScript
mit
61
/** * 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.16 (2019-09-24) */ (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); var isValidId = function (id) { return /^[A-Za-z][A-Za-z0-9\-:._]*$/.test(id); }; var getId = function (editor) { var selectedNode = editor.selection.getNode(); var isAnchor = selectedNode.tagName === 'A' && editor.dom.getAttrib(selectedNode, 'href') === ''; return isAnchor ? selectedNode.getAttribute('id') || selectedNode.getAttribute('name') : ''; }; var insert = function (editor, id) { var selectedNode = editor.selection.getNode(); var isAnchor = selectedNode.tagName === 'A' && editor.dom.getAttrib(selectedNode, 'href') === ''; if (isAnchor) { selectedNode.removeAttribute('name'); selectedNode.id = id; editor.undoManager.add(); } else { editor.focus(); editor.selection.collapse(true); editor.execCommand('mceInsertContent', false, editor.dom.createHTML('a', { id: id })); } }; var Anchor = { isValidId: isValidId, getId: getId, insert: insert }; var insertAnchor = function (editor, newId) { if (!Anchor.isValidId(newId)) { editor.windowManager.alert('Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.'); return true; } else { Anchor.insert(editor, newId); return false; } }; var open = function (editor) { var currentId = Anchor.getId(editor); editor.windowManager.open({ title: 'Anchor', size: 'normal', body: { type: 'panel', items: [{ name: 'id', type: 'input', label: 'ID', placeholder: 'example' }] }, buttons: [ { type: 'cancel', name: 'cancel', text: 'Cancel' }, { type: 'submit', name: 'save', text: 'Save', primary: true } ], initialData: { id: currentId }, onSubmit: function (api) { if (!insertAnchor(editor, api.getData().id)) { api.close(); } } }); }; var Dialog = { open: open }; var register = function (editor) { editor.addCommand('mceAnchor', function () { Dialog.open(editor); }); }; var Commands = { register: register }; var isAnchorNode = function (node) { return !node.attr('href') && (node.attr('id') || node.attr('name')) && !node.firstChild; }; var setContentEditable = function (state) { return function (nodes) { for (var i = 0; i < nodes.length; i++) { if (isAnchorNode(nodes[i])) { nodes[i].attr('contenteditable', state); } } }; }; var setup = function (editor) { editor.on('PreInit', function () { editor.parser.addNodeFilter('a', setContentEditable('false')); editor.serializer.addNodeFilter('a', setContentEditable(null)); }); }; var FilterContent = { setup: setup }; var register$1 = function (editor) { editor.ui.registry.addToggleButton('anchor', { icon: 'bookmark', tooltip: 'Anchor', onAction: function () { return editor.execCommand('mceAnchor'); }, onSetup: function (buttonApi) { return editor.selection.selectorChangedWithUnbind('a:not([href])', buttonApi.setActive).unbind; } }); editor.ui.registry.addMenuItem('anchor', { icon: 'bookmark', text: 'Anchor...', onAction: function () { return editor.execCommand('mceAnchor'); } }); }; var Buttons = { register: register$1 }; function Plugin () { global.add('anchor', function (editor) { FilterContent.setup(editor); Commands.register(editor); Buttons.register(editor); }); } Plugin(); }());
cdnjs/cdnjs
ajax/libs/tinymce/5.0.16/plugins/anchor/plugin.js
JavaScript
mit
4,349