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
const log = require('app/lib/core/log') module.exports = config => props => { const [ pluginName, pluginPath, pluginExports ] = props log.trace(`Initialzing includer: ${log.ul(pluginPath)}.`) const exports = {} exports.name = pluginExports.name || pluginName exports.options = pluginExports.options exports.setOptions = newOpts => { log.trace(`Setting options for modifier: ${log.ul(pluginPath)} ${log.hl(pluginName)}.`) exports.options = newOpts } exports.configure = conf => new Promise(resolve => { log.trace(`Configuring includer ${log.hl(pluginName)}.`) config = conf exports.htmlCommentIncluder = pluginExports.plugin(pluginExports, config) if (!exports.htmlCommentIncluder) { const msg = `Could not configure includer: ${pluginName}.` log.error(msg) // return reject(msg) resolve(exports) } resolve(exports) }) return exports }
F1LT3R/markserv-cli
lib/plugin/includer.js
JavaScript
gpl-3.0
890
/** * @author lnaef */ dojo.provide("cs.util.tests.controller.testModelController"); dojo.require("cs.controller.ModelController"); dojo.require("cs.util.tests.controller.testLibraryController"); doh.register("cs.util.tests.controller.testModelController", [ function constructorModelController(){ new cs.controller.ModelController(); }, function addComponent(){ var controller = new cs.controller.ModelController(); controller.addComponent("cs.module.string.concat",{x:200,y:100}); var module = controller._rootStatement.getBlock(0).getComponentContainer().get(0); doh.is("cs.module.string.concat",module.getMetaData().getName()); }, function moveComponentToBlock(){ //init var controller = new cs.controller.ModelController(); var fromBlock = new cs.model.program.Block(); var toBlock = new cs.model.program.Block(); //prepare var module = cs.library.getNewModule("cs.module.string.concat"); fromBlock.addComponent(module); doh.t(fromBlock.hasComponent(module)); //move module from FROMBlock to TOBlock controller.moveComponentToBlock(module,toBlock); doh.f(fromBlock.hasComponent(module)); doh.t(toBlock.hasComponent(module)); }, function connectSockets(){ var controller = new cs.controller.ModelController(); var module1 = cs.library.getNewModule("cs.module.string.concat"); var module2 = cs.library.getNewModule("cs.module.string.concat"); var s1 = module1.getOutputSockets().get(0); var s2 = module2.getInputSockets().get(0); var wire = controller.connectSockets(s1,s2); doh.t(wire.getFROM(),s1); doh.t(wire.getTO(),s2); doh.t(s1.hasWire(wire)); doh.t(s2.hasWire(wire)); }, function deleteComponent(){ var controller = new cs.controller.ModelController(); var module1 = cs.library.getNewModule("cs.module.string.concat"); var module2 = cs.library.getNewModule("cs.module.string.concat"); var block = new cs.model.program.Block(); // add both modules to the block block.addComponent(module1); block.addComponent(module2); doh.t(block.hasComponent(module1)); doh.t(block.hasComponent(module2)); // connect the two modules through a wire var s1 = module1.getOutputSockets().get(0); var s2 = module2.getInputSockets().get(0); var wire = controller.connectSockets(s1,s2); doh.t(wire.getFROM(),s1); doh.t(wire.getTO(),s2); // delete module1 and all its connected wires controller.deleteComponent(module1); doh.f(block.hasComponent(module1)); doh.t(block.hasComponent(module2)); doh.f(wire.getFROM(),s1); doh.f(wire.getTO(),s2); }, function updatePosition(){ var controller = new cs.controller.ModelController(); var module = cs.library.getNewModule("cs.module.string.concat"); doh.is(0,module.getPositionProg().x); doh.is(0,module.getPositionExec().x); controller.updatePositionProg(module,100,200); controller.updatePositionExec(module,300,400); doh.is(100,module.getPositionProg().x); doh.is(200,module.getPositionProg().y); doh.is(300,module.getPositionExec().x); doh.is(400,module.getPositionExec().y); } ]);
lnaef/ClickScript
cs/util/tests/controller/testModelController.js
JavaScript
gpl-3.0
3,185
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ // #ifdef __AMLTEXTBOX || __AMLSECRET || __AMLTEXTAREA || __AMLINPUT || __INC_ALL //@todo DOCUMENT the modules too /** * Element displaying a rectangular area wich allows a * user to type information. The information typed can be * restricted by using this.$masking. The information can also * be hidden from view when used in password mode. By adding an * {@link element.autocomplete autocomplete element} as a child the * value for the textbox can be looked up as you type. By setting the * {@link element.textbox.attribute.mask mask atribute}, complex data input * validation is done while the users types. * * @constructor * @define input, secret, textarea, textbox * @allowchild autocomplete, {smartbinding} * @addnode elements * * @inherits apf.StandardBinding * @inherits apf.XForms * * @author Ruben Daniels (ruben AT ajax DOT org) * @version %I%, %G% * @since 0.1 * * @binding value Determines the way the value for the element is retrieved * from the bound data. * Example: * Sets the value based on data loaded into this component. * <code> * <a:model id="mdlTextbox"> * <data name="Lukasz"></data> * </a:model> * <a:textbox model="mdlTextbox" value="[@name]" /> * </code> * Example: * A shorter way to write this is: * <code> * <a:model id="mdlTextbox"> * <data name="Lukasz"></data> * </a:model> * <a:textbox value="[mdlTextbox::@name]" /> * </code> * * @event click Fires when the user presses a mousebutton while over this element and then let's the mousebutton go. * @event mouseup Fires when the user lets go of a mousebutton while over this element. * @event mousedown Fires when the user presses a mousebutton while over this element. * @event keyup Fires when the user lets go of a keyboard button while this element is focussed. * object: * {Number} keyCode which key was pressed. This is an ascii number. * @event clear Fires when the content of this element is cleared. */ apf.input = function(struct, tagName){ this.$init(tagName || "input", apf.NODE_VISIBLE, struct); }; apf.secret = function(struct, tagName){ this.$init(tagName || "secret", apf.NODE_VISIBLE, struct); }; apf.password = function(struct, tagName){ this.$init(tagName || "password", apf.NODE_VISIBLE, struct); }; apf.textarea = function(struct, tagName){ this.$init(tagName || "textarea", apf.NODE_VISIBLE, struct); this.multiline = true; }; // HTML5 email element apf.email = function(struct, tagName){ this.$init(tagName || "email", apf.NODE_VISIBLE, struct); }; apf.textbox = function(struct, tagName){ this.$init(tagName || "textbox", apf.NODE_VISIBLE, struct); }; (function(){ this.implement( //#ifdef __WITH_DATAACTION apf.DataAction //#endif //#ifdef __WITH_XFORMS //,apf.XForms //#endif ); this.$focussable = true; // This object can get the focus this.$masking = false; this.$autoComplete = false; this.$childProperty = "value"; //this.realtime = false; this.value = ""; this.$isTextInput = true; this.multiline = false; /** * @attribute {Boolean} realtime whether the value of the bound data is * updated as the user types it, or only when this element looses focus or * the user presses enter. */ this.$booleanProperties["focusselect"] = true; this.$booleanProperties["realtime"] = true; this.$supportedProperties.push("value", "mask", "initial-message", "focusselect", "realtime", "type"); /** * @attribute {String} value the text of this element * @todo apf3.0 check use of this.$propHandlers["value"].call */ this.$propHandlers["value"] = function(value, prop, force, initial){ if (!this.$input || !initial && this.getValue() == value) return; // Set Value if (!initial && !value && !this.hasFocus()) //@todo apf3.x research the use of clear return this.$clear(); else if (this.isHTMLBox) { if (this.$input.innerHTML != value) this.$input.innerHTML = value; } else if (this.$input.value != value) this.$input.value = value; if (!initial) apf.setStyleClass(this.$ext, "", [this.$baseCSSname + "Initial"]); if (this.$button) this.$button.style.display = value && !initial ? "block" : "none"; }; //See validation //var oldPropHandler = this.$propHandlers["maxlength"]; this.addEventListener("prop.maxlength", function(e){ //Special validation support using nativate max-length browser support if (this.$input.tagName.toLowerCase().match(/input|textarea/)) this.$input.maxLength = parseInt(e.value) || null; }); this.addEventListener("prop.editable", function(e){ if (apf.isIE) this.$input.unselectable = e.value ? "On" : "Off"; else { if (e.value) apf.addListener(this.$input, "mousedown", apf.preventDefault); else apf.removeListener(this.$input, "mousedown", apf.preventDefault); } }); /** * @attribute {String} mask a complex input pattern that the user should * adhere to. This is a string which is a combination of special and normal * characters. Then comma seperated it has two options. The first option * specifies whether the non input characters (the chars not typed by the * user) are in the value of this element. The second option specifies the * character that is displayed when the user hasn't yet filled in a * character. * Characters: * 0 Any digit * 1 The number 1 or 2. * 9 Any digit or a space. * # User can enter a digit, space, plus or minus sign. * L Any alpha character, case insensitive. * ? Any alpha character, case insensitive or space. * A Any alphanumeric character. * a Any alphanumeric character or space. * X Hexadecimal character, case insensitive. * x Hexadecimal character, case insensitive or space. * & Any whitespace. * C Any character. * ! Causes the input mask to fill from left to right instead of from right to left. * ' The start or end of a literal part. * " The start or end of a literal part. * > Converts all characters that follow to uppercase. * < Converts all characters that follow to lowercase. * \ Cancel the special meaning of a character. * Example: * An american style phone number. * <code> * <a:textbox mask="(000)0000-0000;;_" /> * </code> * Example: * A dutch postal code * <code> * <a:textbox mask="0000 AA;;_" /> * </code> * Example: * A date * <code> * <a:textbox mask="00-00-0000;;_" datatype="xsd:date" /> * </code> * Example: * A serial number * <code> * <a:textbox mask="'WCS74'0000-00000;1;_" /> * </code> * Example: * A MAC address * <code> * <a:textbox mask="XX-XX-XX-XX-XX-XX;;_" /> * </code> */ this.$propHandlers["mask"] = function(value){ if (this.mask.toLowerCase() == "password")// || !apf.hasMsRangeObject) return; if (!value) { throw new Error("Not Implemented"); } if (!this.$masking) { this.$masking = true; this.implement(apf.textbox.masking); this.focusselect = false; //this.realtime = false; } this.setMask(this.mask); }; //this.$propHandlers["ref"] = function(value) { // this.$input.setAttribute("name", value.split("/").pop().split("::").pop() // .replace(/[\@\.\(\)]*/g, "")); //}; /** * @attribute {String} initial-message the message displayed by this element * when it doesn't have a value set. This property is inherited from parent * nodes. When none is found it is looked for on the appsettings element. */ this.$propHandlers["initial-message"] = function(value){ if (value) { //#ifdef __WITH_WINDOW_FOCUS if (apf.hasFocusBug) this.$input.onblur(); //#endif //this.$propHandlers["value"].call(this, value, null, true); } if (!this.value) this.$clear(true); if (this.type == "password" && this.$inputInitFix) { this.$inputInitFix.innerHTML = value; apf.setStyleClass(this.$inputInitFix, "initFxEnabled"); } }; /** * @attribute {Boolean} focusselect whether the text in this element is * selected when this element receives focus. */ this.$propHandlers["focusselect"] = function(value){ var _self = this; this.$input.onmousedown = function(){ _self.focusselect = false; }; this.$input.onmouseup = this.$input.onmouseout = function(){ _self.focusselect = value; }; }; /** * @attribute {String} type the type or function this element represents. * This can be any arbitrary name. Although there are some special values. * Possible values: * username this element is used to type in the name part of login credentials. * password this element is used to type in the password part of login credentials. */ this.$propHandlers["type"] = function(value){ if (value && "password|username".indexOf(value) > -1 && typeof this.focusselect == "undefined") { this.focusselect = true; this.$propHandlers["focusselect"].call(this, true); } }; this.$isTextInput = function(e){ return true; }; /**** Public Methods ****/ //#ifdef __WITH_CONVENIENCE_API /** * Sets the value of this element. This should be one of the values * specified in the values attribute. * @param {String} value the new value of this element */ this.setValue = function(value){ return this.setProperty("value", value, false, true); }; this.clear = function(){ this.setProperty("value", ""); } //@todo cleanup and put initial-message behaviour in one location this.$clear = function(noEvent){ if (this["initial-message"]) { apf.setStyleClass(this.$ext, this.$baseCSSname + "Initial"); this.$propHandlers["value"].call(this, this["initial-message"], null, null, true); } else { this.$propHandlers["value"].call(this, "", null, null, true); } if (!noEvent) this.dispatchEvent("clear");//@todo this should work via value change } /** * Returns the current value of this element. * @return {String} */ this.getValue = function(){ var v = this.isHTMLBox ? this.$input.innerHTML : this.$input.value; return v == this["initial-message"] ? "" : v.replace(/\r/g, ""); }; //#endif /** * Selects the text in this element. */ this.select = function(){ try { this.$input.select(); } catch(e){} }; /** * Deselects the text in this element. */ this.deselect = function(){this.$input.deselect();}; /**** Private Methods *****/ this.$enable = function(){this.$input.disabled = false;}; this.$disable = function(){this.$input.disabled = true;}; this.$insertData = function(str){ return this.setValue(str); }; /** * @private */ this.insert = function(text){ if (apf.hasMsRangeObject) { try { this.$input.focus(); } catch(e) {} var range = document.selection.createRange(); if (this.oninsert) text = this.oninsert(text); range.pasteHTML(text); range.collapse(true); range.select(); } else { this.$input.value += text; } }; this.addEventListener("$clear", function(){ this.value = "";//@todo what about property binding? if (this["initial-message"] && apf.document.activeElement != this) { this.$propHandlers["value"].call(this, this["initial-message"], null, null, true); apf.setStyleClass(this.$ext, this.$baseCSSname + "Initial"); } else { this.$propHandlers["value"].call(this, ""); } if (!this.$input.tagName.toLowerCase().match(/input|textarea/i)) { if (apf.hasMsRangeObject) { try { var range = document.selection.createRange(); range.moveStart("sentence", -1); //range.text = ""; range.select(); } catch(e) {} } } this.dispatchEvent("clear"); //@todo apf3.0 }); this.$keyHandler = function(key, ctrlKey, shiftKey, altKey, e){ if (this.$button && key == 27) { //this.$clear(); if (this.value) { this.change(""); e.stopPropagation(); } //this.focus({mouse:true}); } /*if (this.dispatchEvent("keydown", { keyCode : key, ctrlKey : ctrlKey, shiftKey : shiftKey, altKey : altKey, htmlEvent : e}) === false) return false; // @todo: revisit this IF statement - dead code? if (false && apf.isIE && (key == 86 && ctrlKey || key == 45 && shiftKey)) { var text = window.clipboardData.getData("Text"); if ((text = this.dispatchEvent("keydown", { text : this.onpaste(text)}) === false)) return false; if (!text) text = window.clipboardData.getData("Text"); this.$input.focus(); var range = document.selection.createRange(); range.text = ""; range.collapse(); range.pasteHTML(text.replace(/\n/g, "<br />").replace(/\t/g, "&nbsp;&nbsp;&nbsp;")); return false; }*/ }; this.$registerElement = function(oNode) { if (!oNode) return; if (oNode.localName == "autocomplete") this.$autoComplete = oNode; }; var fTimer; this.$focus = function(e){ if (!this.$ext || this.$ext.disabled) return; this.$setStyleClass(this.$ext, this.$baseCSSname + "Focus"); if (this["initial-message"] && this.$input.value == this["initial-message"]) { this.$propHandlers["value"].call(this, "", null, null, true); apf.setStyleClass(this.$ext, "", [this.$baseCSSname + "Initial"]); } var _self = this; function delay(){ try { if (!fTimer || document.activeElement != _self.$input) { _self.$input.focus(); } else { clearInterval(fTimer); return; } } catch(e) {} if (_self.$masking) _self.setPosition(); if (_self.focusselect) _self.select(); }; if ((!e || e.mouse) && apf.isIE) { clearInterval(fTimer); fTimer = setInterval(delay, 1); } else delay(); }; this.$blur = function(e){ if (!this.$ext) return; if (!this.realtime) this.change(this.getValue()); this.$setStyleClass(this.$ext, "", [this.$baseCSSname + "Focus", "capsLock"]); if (this["initial-message"] && this.$input.value == "") { this.$propHandlers["value"].call(this, this["initial-message"], null, null, true); apf.setStyleClass(this.$ext, this.$baseCSSname + "Initial"); } /*if (apf.hasMsRangeObject) { var r = this.$input.createTextRange(); r.collapse(); r.select(); }*/ try { if (apf.isIE || !e || e.srcElement != apf.window) this.$input.blur(); } catch(e) {} // check if we clicked on the oContainer. ifso dont hide it if (this.oContainer) { $setTimeout("var o = apf.lookup(" + this.$uniqueId + ");\ o.oContainer.style.display = 'none'", 100); } clearInterval(fTimer); }; /**** Init ****/ this.$draw = function(){ var _self = this, typedBefore = false; //#ifdef __AMLCODEEDITOR if (this.localName == "codeeditor") { this.skin = "textarea"; this.$loadSkin(); } //#endif //Build Main Skin this.$ext = this.$getExternal(null, null, function(oExt){ var mask = this.getAttribute("mask"); if ((typeof mask == "string" && mask.toLowerCase() == "password") || "secret|password".indexOf(this.localName) > -1) { this.type = "password"; this.$getLayoutNode("main", "input").setAttribute("type", "password"); } //#ifdef __WITH_HTML5 else if (this.localName == "email") { this.datatype = (this.prefix ? this.prefix + ":" : "") + "email"; this.$propHandlers["datatype"].call(this, this.datatype, "datatype"); } else if (this.localName == "url") { this.datatype = (this.prefix ? this.prefix + ":" : "") + "url"; this.$propHandlers["datatype"].call(this, this.datatype, "datatype"); } //#endif oExt.setAttribute("onmousedown", "if (!this.host.disabled) \ this.host.dispatchEvent('mousedown', {htmlEvent : event});"); oExt.setAttribute("onmouseup", "if (!this.host.disabled) \ this.host.dispatchEvent('mouseup', {htmlEvent : event});"); oExt.setAttribute("onclick", "if (!this.host.disabled) \ this.host.dispatchEvent('click', {htmlEvent : event});"); }); this.$input = this.$getLayoutNode("main", "input", this.$ext); this.$button = this.$getLayoutNode("main", "button", this.$ext); this.$inputInitFix = this.$getLayoutNode("main", "initialfix", this.$ext); if (this.type == "password") this.$propHandlers["type"].call(this, "password"); if (!apf.hasContentEditable && "input|textarea".indexOf(this.$input.tagName.toLowerCase()) == -1) { var node = this.$input; this.$input = node.parentNode.insertBefore(document.createElement("textarea"), node); node.parentNode.removeChild(node); this.$input.className = node.className; if (this.$ext == node) this.$ext = this.$input; } if (this.$button) { this.$button.onmousedown = function(){ _self.$clear(); //@todo why are both needed for doc filter _self.change(""); //@todo only this one should be needed _self.focus({mouse:true}); } } //@todo for skin switching this should be removed if (this.$input.tagName.toLowerCase() == "textarea") { this.addEventListener("focus", function(e){ //if (this.multiline != "optional") //e.returnValue = false }); } this.$input.onselectstart = function(e){ if (!e) e = event; e.cancelBubble = true; } this.$input.host = this; this.$input.onkeydown = function(e){ e = e || window.event; if (this.host.disabled) { e.returnValue = false; return false; } //Change if (!_self.realtime) { var value = _self.getValue(); if (e.keyCode == 13 && value != _self.value) _self.change(value); } else if (apf.isWebkit && _self.xmlRoot && _self.getValue() != _self.value) //safari issue (only old??) $setTimeout("var o = apf.lookup(" + _self.$uniqueId + ");\ o.change(o.getValue())"); if (_self.multiline == "optional" && e.keyCode == 13 && !e.shiftKey || e.ctrlKey && (e.keyCode == 66 || e.keyCode == 73 || e.keyCode == 85)) { e.returnValue = false; return false; } if (typedBefore && this.getAttribute("type") == "password" && this.value != "") { var hasClass = (_self.$ext.className.indexOf("capsLock") > -1), capsKey = (e.keyCode === 20); if (capsKey) // caps off apf.setStyleClass(_self.$ext, hasClass ? null : "capsLock", hasClass ? ["capsLock"] : null); } //Autocomplete if (_self.$autoComplete || _self.oContainer) { var keyCode = e.keyCode; $setTimeout(function(){ if (_self.$autoComplete) _self.$autoComplete.fillAutocomplete(keyCode); else _self.fillAutocomplete(keyCode); }); } //Non this.$masking if (!_self.mask) { return _self.$keyHandler(e.keyCode, e.ctrlKey, e.shiftKey, e.altKey, e); } }; this.$input.onkeyup = function(e){ if (!e) e = event; if (this.host.disabled) return false; var keyCode = e.keyCode; if (_self.$button) _self.$button.style.display = this.value ? "block" : "none"; if (_self.realtime) { $setTimeout(function(){ var v; if (!_self.mask && (v = _self.getValue()) != _self.value) _self.change(v); _self.dispatchEvent("keyup", {keyCode : keyCode});//@todo }); } else { _self.dispatchEvent("keyup", {keyCode : keyCode});//@todo } //#ifdef __WITH_VALIDATION if (_self.isValid && _self.isValid() && e.keyCode != 13 && e.keyCode != 17) _self.clearError(); //#endif }; //#ifdef __WITH_WINDOW_FOCUS if (apf.hasFocusBug) apf.sanitizeTextbox(this.$input); //#endif if (apf.hasAutocompleteXulBug) this.$input.setAttribute("autocomplete", "off"); if ("INPUT|TEXTAREA".indexOf(this.$input.tagName) == -1) { this.isHTMLBox = true; this.$input.unselectable = "Off"; this.$input.contentEditable = true; this.$input.style.width = "1px"; this.$input.select = function(){ var r = document.selection.createRange(); r.moveToElementText(this); r.select(); } }; this.$input.deselect = function(){ if (!document.selection) return; var r = document.selection.createRange(); r.collapse(); r.select(); }; var f; apf.addListener(this.$input, "keypress", f = function(e) { if (_self.$input.getAttribute("type") != "password") return apf.removeListener(_self.$input, "keypress", f); e = e || window.event; // get key pressed var which = -1; if (e.which) which = e.which; else if (e.keyCode) which = e.keyCode; // get shift status var shift_status = false; if (e.shiftKey) shift_status = e.shiftKey; else if (e.modifiers) shift_status = !!(e.modifiers & 4); if (((which >= 65 && which <= 90) && !shift_status) || ((which >= 97 && which <= 122) && shift_status)) { // uppercase, no shift key apf.setStyleClass(_self.$ext, "capsLock"); } else { apf.setStyleClass(_self.$ext, null, ["capsLock"]); } typedBefore = true; }); }; this.$loadAml = function() { if (typeof this["initial-message"] == "undefined") this.$setInheritedAttribute("initial-message"); if (typeof this.realtime == "undefined") this.$setInheritedAttribute("realtime"); } this.addEventListener("DOMNodeRemovedFromDocument", function(){ if (this.$button) this.$button.onmousedown = null; if (this.$input) { this.$input.onkeypress = this.$input.onmouseup = this.$input.onmouseout = this.$input.onmousedown = this.$input.onkeydown = this.$input.onkeyup = this.$input.onselectstart = null; } }); // #ifdef __WITH_DATABINDING }).call(apf.textbox.prototype = new apf.StandardBinding()); /* #else }).call(apf.textbox.prototype = new apf.Presentation()); #endif*/ apf.config.$inheritProperties["initial-message"] = 1; apf.config.$inheritProperties["realtime"] = 1; apf.input.prototype = apf.secret.prototype = apf.password.prototype = apf.textarea.prototype = apf.email.prototype = apf.textbox.prototype; apf.aml.setElement("input", apf.input); apf.aml.setElement("secret", apf.secret); apf.aml.setElement("password", apf.password); apf.aml.setElement("textarea", apf.textarea); apf.aml.setElement("textbox", apf.textbox); // #endif
tfe/cloud9
support/apf/elements/textbox.js
JavaScript
gpl-3.0
27,330
import accounting from "accounting-js"; import _ from "lodash"; import { Meteor } from "meteor/meteor"; import $ from "jquery"; import { Template } from "meteor/templating"; import { ReactiveVar } from "meteor/reactive-var"; import { i18next, Logger, formatNumber, Reaction } from "/client/api"; import { NumericInput } from "/imports/plugins/core/ui/client/components"; import { Orders, Shops, Packages } from "/lib/collections"; import { ButtonSelect } from "../../../../ui/client/components/button"; import DiscountList from "/imports/plugins/core/discounts/client/components/list"; import InvoiceContainer from "../../containers/invoiceContainer.js"; import LineItemsContainer from "../../containers/lineItemsContainer.js"; import TotalActionsContainer from "../../containers/totalActionsContainer.js"; // helper to return the order payment object // the first credit paymentMethod on the order // returns entire payment method function orderCreditMethod(order) { return order.billing.filter(value => value.paymentMethod.method === "credit")[0]; } // // core order shipping invoice templates // Template.coreOrderShippingInvoice.onCreated(function () { this.state = new ReactiveDict(); this.refunds = new ReactiveVar([]); this.refundAmount = new ReactiveVar(0.00); this.state.setDefault({ isCapturing: false, isRefunding: false, isFetching: true }); this.autorun(() => { const currentData = Template.currentData(); const order = Orders.findOne(currentData.orderId); const shop = Shops.findOne({}); this.state.set("order", order); this.state.set("currency", shop.currencies[shop.currency]); if (order) { Meteor.call("orders/refunds/list", order, (error, result) => { if (error) Logger.warn(error); this.refunds.set(result); this.state.set("isFetching", false); }); } }); }); Template.coreOrderShippingInvoice.helpers({ isCapturing() { const instance = Template.instance(); if (instance.state.get("isCapturing")) { instance.$(":input").attr("disabled", true); instance.$("#btn-capture-payment").text("Capturing"); return true; } return false; }, isRefunding() { const instance = Template.instance(); if (instance.state.get("isRefunding")) { instance.$("#btn-refund-payment").text(i18next.t("order.refunding")); return true; } return false; }, isFetching() { const instance = Template.instance(); if (instance.state.get("isFetching")) { return true; } return false; }, DiscountList() { return DiscountList; }, InvoiceContainer() { return InvoiceContainer; }, buttonSelectComponent() { return { component: ButtonSelect, buttons: [ { name: "Approve", i18nKeyLabel: "order.approveInvoice", active: true, status: "info", eventAction: "approveInvoice", bgColor: "bg-info", buttonType: "submit" }, { name: "Cancel", i18nKeyLabel: "order.cancelInvoice", active: false, status: "danger", eventAction: "cancelOrder", bgColor: "bg-danger", buttonType: "button" } ] }; }, LineItemsContainer() { return LineItemsContainer; }, TotalActionsContainer() { return TotalActionsContainer; }, orderId() { const instance = Template.instance(); const state = instance.state; const order = state.get("order"); return order._id; } }); /** * coreOrderAdjustments events */ Template.coreOrderShippingInvoice.events({ /** * Click Start Cancel Order * @param {Event} event - Event Object * @param {Template} instance - Blaze Template * @return {void} */ "click [data-event-action=cancelOrder]": (event, instance) => { event.preventDefault(); const order = instance.state.get("order"); const invoiceTotal = order.billing[0].invoice.total; const currencySymbol = instance.state.get("currency").symbol; Meteor.subscribe("Packages"); const packageId = order.billing[0].paymentMethod.paymentPackageId; const settingsKey = order.billing[0].paymentMethod.paymentSettingsKey; // check if payment provider supports de-authorize const checkSupportedMethods = Packages.findOne({ _id: packageId, shopId: Reaction.getShopId() }).settings[settingsKey].support; const orderStatus = order.billing[0].paymentMethod.status; const orderMode = order.billing[0].paymentMethod.mode; let alertText; if (_.includes(checkSupportedMethods, "de-authorize") || (orderStatus === "completed" && orderMode === "capture")) { alertText = i18next.t("order.applyRefundDuringCancelOrder", { currencySymbol, invoiceTotal }); } Alerts.alert({ title: i18next.t("order.cancelOrder"), text: alertText, type: "warning", showCancelButton: true, showCloseButton: true, confirmButtonColor: "#98afbc", cancelButtonColor: "#98afbc", confirmButtonText: i18next.t("order.cancelOrderNoRestock"), cancelButtonText: i18next.t("order.cancelOrderThenRestock") }, (isConfirm, cancel)=> { let returnToStock; if (isConfirm) { returnToStock = false; return Meteor.call("orders/cancelOrder", order, returnToStock, err => { if (err) { $(".alert").removeClass("hidden").text(err.message); } }); } if (cancel === "cancel") { returnToStock = true; return Meteor.call("orders/cancelOrder", order, returnToStock, err => { if (err) { $(".alert").removeClass("hidden").text(err.message); } }); } }); }, /** * Submit form * @param {Event} event - Event object * @param {Template} instance - Blaze Template * @return {void} */ "submit form[name=capture]": (event, instance) => { event.preventDefault(); const state = instance.state; const order = state.get("order"); const paymentMethod = orderCreditMethod(order); const orderTotal = accounting.toFixed( paymentMethod.invoice.subtotal + paymentMethod.invoice.shipping + paymentMethod.invoice.taxes , 2); const discount = state.get("field-discount") || order.discount; // TODO: review Discount cannot be greater than original total price // logic is probably not valid any more. Discounts aren't valid below 0 order. if (discount > orderTotal) { Alerts.inline("Discount cannot be greater than original total price", "error", { placement: "coreOrderShippingInvoice", i18nKey: "order.invalidDiscount", autoHide: 10000 }); } else if (orderTotal === accounting.toFixed(discount, 2)) { Alerts.alert({ title: i18next.t("order.fullDiscountWarning"), showCancelButton: true, confirmButtonText: i18next.t("order.applyDiscount") }, (isConfirm) => { if (isConfirm) { Meteor.call("orders/approvePayment", order, (error) => { if (error) { Logger.warn(error); } }); } }); } else { Meteor.call("orders/approvePayment", order, (error) => { if (error) { Logger.warn(error); if (error.error === "orders/approvePayment.discount-amount") { Alerts.inline("Discount cannot be greater than original total price", "error", { placement: "coreOrderShippingInvoice", i18nKey: "order.invalidDiscount", autoHide: 10000 }); } } }); } }, /** * Submit form * @param {Event} event - Event object * @param {Template} instance - Blaze Template * @return {void} */ "click [data-event-action=applyRefund]": (event, instance) => { event.preventDefault(); const { state } = Template.instance(); const currencySymbol = state.get("currency").symbol; const order = instance.state.get("order"); const paymentMethod = orderCreditMethod(order).paymentMethod; const orderTotal = paymentMethod.amount; const discounts = paymentMethod.discounts; const refund = state.get("field-refund") || 0; const refunds = Template.instance().refunds.get(); let refundTotal = 0; _.each(refunds, function (item) { refundTotal += parseFloat(item.amount); }); let adjustedTotal; // TODO extract Stripe specific fullfilment payment handling out of core. // Stripe counts discounts as refunds, so we need to re-add the discount to not "double discount" in the adjustedTotal if (paymentMethod.processor === "Stripe") { adjustedTotal = accounting.toFixed(orderTotal + discounts - refundTotal, 2); } else { adjustedTotal = accounting.toFixed(orderTotal - refundTotal, 2); } if (refund > adjustedTotal) { Alerts.inline("Refund(s) total cannot be greater than adjusted total", "error", { placement: "coreOrderRefund", i18nKey: "order.invalidRefund", autoHide: 10000 }); } else { Alerts.alert({ title: i18next.t("order.applyRefundToThisOrder", { refund: refund, currencySymbol: currencySymbol }), showCancelButton: true, confirmButtonText: i18next.t("order.applyRefund") }, (isConfirm) => { if (isConfirm) { state.set("isRefunding", true); Meteor.call("orders/refunds/create", order._id, paymentMethod, refund, (error, result) => { if (error) { Alerts.alert(error.reason); } if (result) { Alerts.toast(i18next.t("mail.alerts.emailSent"), "success"); } $("#btn-refund-payment").text(i18next.t("order.applyRefund")); state.set("field-refund", 0); state.set("isRefunding", false); }); } }); } }, "click [data-event-action=makeAdjustments]": (event, instance) => { event.preventDefault(); Meteor.call("orders/makeAdjustmentsToInvoice", instance.state.get("order")); }, "click [data-event-action=capturePayment]": (event, instance) => { event.preventDefault(); instance.state.set("isCapturing", true); const order = instance.state.get("order"); Meteor.call("orders/capturePayments", order._id); if (order.workflow.status === "new") { Meteor.call("workflow/pushOrderWorkflow", "coreOrderWorkflow", "processing", order); Reaction.Router.setQueryParams({ filter: "processing", _id: order._id }); } }, "change input[name=refund_amount], keyup input[name=refund_amount]": (event, instance) => { instance.refundAmount.set(accounting.unformat(event.target.value)); } }); /** * coreOrderShippingInvoice helpers */ Template.coreOrderShippingInvoice.helpers({ NumericInput() { return NumericInput; }, numericInputProps(fieldName, value = 0, enabled = true) { const { state } = Template.instance(); const order = state.get("order"); const paymentMethod = orderCreditMethod(order); const status = paymentMethod.status; const isApprovedAmount = (status === "approved" || status === "completed"); return { component: NumericInput, numericType: "currency", value: value, disabled: !enabled, isEditing: !isApprovedAmount, // Dont allow editing if its approved format: state.get("currency"), classNames: { input: { amount: true }, text: { "text-success": status === "completed" } }, onChange(event, data) { state.set(`field-${fieldName}`, data.numberValue); } }; }, refundInputProps() { const { state } = Template.instance(); const order = state.get("order"); const paymentMethod = orderCreditMethod(order).paymentMethod; const refunds = Template.instance().refunds.get(); let refundTotal = 0; _.each(refunds, function (item) { refundTotal += parseFloat(item.amount); }); const adjustedTotal = paymentMethod.amount - refundTotal; return { component: NumericInput, numericType: "currency", value: state.get("field-refund") || 0, maxValue: adjustedTotal, format: state.get("currency"), classNames: { input: { amount: true } }, onChange(event, data) { state.set("field-refund", data.numberValue); } }; }, refundAmount() { return Template.instance().refundAmount; }, invoice() { const instance = Template.instance(); const order = instance.state.get("order"); const invoice = Object.assign({}, order.billing[0].invoice, { totalItems: _.sumBy(order.items, (o) => o.quantity) }); return invoice; }, money(amount) { return formatNumber(amount); }, disabled() { const instance = Template.instance(); const order = instance.state.get("order"); const status = orderCreditMethod(order).paymentMethod.status; if (status === "approved" || status === "completed") { return "disabled"; } return ""; }, paymentPendingApproval() { const instance = Template.instance(); const order = instance.state.get("order"); const status = orderCreditMethod(order).paymentMethod.status; return status === "created" || status === "adjustments" || status === "error"; }, canMakeAdjustments() { const instance = Template.instance(); const order = instance.state.get("order"); const status = orderCreditMethod(order).paymentMethod.status; if (status === "approved" || status === "completed") { return false; } return true; }, showAfterPaymentCaptured() { const instance = Template.instance(); const order = instance.state.get("order"); const orderStatus = orderCreditMethod(order).paymentMethod.status; return orderStatus === "completed"; }, paymentApproved() { const instance = Template.instance(); const order = instance.state.get("order"); return order.billing[0].paymentMethod.status === "approved"; }, paymentCaptured() { const instance = Template.instance(); const order = instance.state.get("order"); const orderStatus = orderCreditMethod(order).paymentMethod.status; const orderMode = orderCreditMethod(order).paymentMethod.mode; return orderStatus === "completed" || (orderStatus === "refunded" && orderMode === "capture"); }, refundTransactions() { const instance = Template.instance(); const order = instance.state.get("order"); const transactions = orderCreditMethod(order).paymentMethod.transactions; return _.filter(transactions, (transaction) => { return transaction.type === "refund"; }); }, refunds() { const refunds = Template.instance().refunds.get(); if (_.isArray(refunds)) { return refunds.reverse(); } return refunds; }, /** * Get the total after all refunds * @return {Number} the amount after all refunds */ adjustedTotal() { const instance = Template.instance(); const order = instance.state.get("order"); const paymentMethod = orderCreditMethod(order).paymentMethod; const discounts = orderCreditMethod(order).invoice.discounts; const refunds = Template.instance().refunds.get(); let refundTotal = 0; _.each(refunds, function (item) { refundTotal += parseFloat(item.amount); }); if (paymentMethod.processor === "Stripe") { return Math.abs(paymentMethod.amount + discounts - refundTotal); } return Math.abs(paymentMethod.amount - refundTotal); }, capturedDisabled() { const isLoading = Template.instance().state.get("isCapturing"); if (isLoading) { return "disabled"; } return null; }, refundSubmitDisabled() { const amount = Template.instance().state.get("field-refund") || 0; const isLoading = Template.instance().state.get("isRefunding"); if (amount === 0 || isLoading) { return "disabled"; } return null; }, /** * Order * @summary find a single order using the order id spplied with the template * data context * @return {Object} A single order */ order() { const instance = Template.instance(); const order = instance.state.get("order"); return order; }, shipment() { const instance = Template.instance(); const order = instance.state.get("order"); const shipment = _.filter(order.shipping, { _id: currentData.fulfillment._id })[0]; return shipment; }, discounts() { const enabledPaymentsArr = []; const apps = Reaction.Apps({ provides: "paymentMethod", enabled: true }); for (app of apps) { if (app.enabled === true) enabledPaymentsArr.push(app); } let discount = false; for (enabled of enabledPaymentsArr) { if (enabled.packageName === "discount-codes") { discount = true; break; } } return discount; }, items() { const instance = Template.instance(); const order = instance.state.get("order"); const currentData = Template.currentData(); const shipment = currentData.fulfillment; // returns order items with shipping detail const returnItems = _.map(order.items, (item) => { const shipping = shipment.shipmentMethod; return _.extend(item, { shipping }); }); let items; // if avalara tax has been enabled it adds a "taxDetail" field for every item if (order.taxes !== undefined) { const taxes = order.taxes.slice(0, -1); items = _.map(returnItems, (item) => { const taxDetail = _.find(taxes, { lineNumber: item._id }); return _.extend(item, { taxDetail }); }); } else { items = returnItems; } return items; } });
Sweetgrassbuffalo/ReactionSweeGrass-v2
imports/plugins/core/orders/client/templates/workflow/shippingInvoice.js
JavaScript
gpl-3.0
17,911
import { Map, Set, OrderedSet, List } from 'immutable' import * as constants from '../constants/files.js' import { ls, searchFiles, rangeSelect } from '../sagas/helpers.js' const initialState = Map({ files: List(), workingDirectoryFiles: null, searchResults: List(), uploading: List(), downloading: List(), selected: OrderedSet(), path: '', searchText: '', uploadSource: '', showAllowanceDialog: false, showUploadDialog: false, showSearchField: false, showFileTransfers: false, showDeleteDialog: false, showRenameDialog: false, settingAllowance: false, dragging: false, contractCount: 0, allowance: '0', spending: '0', showDownloadsSince: Date.now(), unreadUploads: Set(), unreadDownloads: Set(), }) export default function filesReducer(state = initialState, action) { switch (action.type) { case constants.SET_ALLOWANCE_COMPLETED: return state.set('settingAllowance', false) case constants.RECEIVE_ALLOWANCE: return state.set('allowance', action.allowance) case constants.RECEIVE_SPENDING: return state.set('spending', action.spending) case constants.DOWNLOAD_FILE: return state.set('unreadDownloads', state.get('unreadDownloads').add(action.file.siapath)) case constants.UPLOAD_FILE: return state.set('unreadUploads', state.get('unreadUploads').add(action.siapath)) case constants.RECEIVE_FILES: { const workingDirectoryFiles = ls(action.files, state.get('path')) const workingDirectorySiapaths = workingDirectoryFiles.map((file) => file.siapath) // filter out selected files that are no longer in the working directory const selected = state.get('selected').filter((file) => workingDirectorySiapaths.includes(file.siapath)) return state.set('files', action.files) .set('workingDirectoryFiles', workingDirectoryFiles) .set('selected', selected) } case constants.SET_ALLOWANCE: return state.set('allowance', action.funds) .set('settingAllowance', true) case constants.CLEAR_DOWNLOADS: return state.set('showDownloadsSince', Date.now()) case constants.SET_SEARCH_TEXT: { const results = searchFiles(state.get('workingDirectoryFiles'), action.text, state.get('path')) return state.set('searchResults', results) .set('searchText', action.text) } case constants.SET_PATH: return state.set('path', action.path) .set('selected', OrderedSet()) .set('workingDirectoryFiles', ls(state.get('files'), action.path)) .set('searchResults', searchFiles(state.get('workingDirectoryFiles'), state.get('searchText', state.get('path')))) case constants.DESELECT_FILE: return state.set('selected', state.get('selected').filter((file) => file.siapath !== action.file.siapath)) case constants.SELECT_FILE: return state.set('selected', state.get('selected').add(action.file)) case constants.DESELECT_ALL: return state.set('selected', OrderedSet()) case constants.SELECT_UP_TO: return state.set('selected', rangeSelect(action.file, state.get('workingDirectoryFiles'), state.get('selected'))) case constants.SHOW_ALLOWANCE_DIALOG: return state.set('showAllowanceDialog', true) case constants.CLOSE_ALLOWANCE_DIALOG: return state.set('showAllowanceDialog', false) case constants.TOGGLE_SEARCH_FIELD: return state.set('showSearchField', !state.get('showSearchField')) case constants.SET_DRAGGING: return state.set('dragging', true) case constants.SET_NOT_DRAGGING: return state.set('dragging', false) case constants.SHOW_DELETE_DIALOG: return state.set('showDeleteDialog', true) case constants.HIDE_DELETE_DIALOG: return state.set('showDeleteDialog', false) case constants.SHOW_UPLOAD_DIALOG: return state.set('showUploadDialog', true) .set('uploadSource', action.source) case constants.HIDE_UPLOAD_DIALOG: return state.set('showUploadDialog', false) case constants.RECEIVE_UPLOADS: return state.set('uploading', action.uploads) case constants.RECEIVE_DOWNLOADS: return state.set('downloading', action.downloads.filter((download) => Date.parse(download.starttime) > state.get('showDownloadsSince'))) case constants.SHOW_FILE_TRANSFERS: return state.set('showFileTransfers', true) case constants.HIDE_FILE_TRANSFERS: return state.set('showFileTransfers', false) case constants.TOGGLE_FILE_TRANSFERS: return state.set('showFileTransfers', !state.get('showFileTransfers')) .set('unreadDownloads', Set()) .set('unreadUploads', Set()) case constants.SET_CONTRACT_COUNT: return state.set('contractCount', action.count) case constants.SHOW_RENAME_DIALOG: return state.set('showRenameDialog', true) case constants.HIDE_RENAME_DIALOG: return state.set('showRenameDialog', false) default: return state } }
patel344/Mr.Miner
Mr.Mining/MikeTheMiner/dist/Santas_helpers/Sia_wallet/resources/app/plugins/Files/js/reducers/files.js
JavaScript
gpl-3.0
4,745
'use strict'; /** @namespace chas2.test * Тесты */ chas2.test = { /** @namespace chas2.test._ * Функционал, используемый только внутри модуля chas2.test * @private */ _ : {}, /** @function chas2.test.testTemplates * Проверить шаблоны в текущем наборе * @param {Number} triesCount кол-во прогонов каждого шаблона * @param {Function} infoFunc функция вывода информационной строки * @param {Function} warnFunc функция вывода предупреждающей строки * @param {Function} errFunc функция вывода строки об ошибке */ testTemplates : function(p) { var infoFunc = p.infoFunc || chas2.Linfo; var warnFunc = p.warnFunc || chas2.Lwarn; var errFunc = p.errFunc || chas2.Lerr; infoFunc('Проверка шаблонов в наборе "' + nabor.adres + '"'); var errCount = 0; for (var category in nabor.upak) { infoFunc('\tПроверка категории ' + category); var errCountPerCat = 0; for (var templ in nabor.upak[category]) { if (templ != 'main') { infoFunc('\t\tПроверка шаблона B1/' + templ); for (var i = p.triesCount || 10; i; i--) { try { nabor.upak[category][templ](); var checkResult = dvig.validateVopr(); if (checkResult != '') { warnFunc('\t\t\t' + checkResult); } } catch (e) { errFunc('\t\t\tОшибка :' + e); errCountPerCat++; } } } } infoFunc('\tПроверка категории ' + category + ' закончена c ' + errCountPerCat + ' ошибками'); } infoFunc('Проверка шаблонов в наборе "' + nabor.adres + '" закончена с ' + errCount + ' ошибками'); } };
DrMGC/chas-ege
src/chas2/test.js
JavaScript
gpl-3.0
1,897
window.nomer=sl(1,4); window.comment='Элементарные бытовые задачи.';
DrMGC/chas-ege
zdn/mat2014gia/B9/main.js
JavaScript
gpl-3.0
94
'use strict'; // Gulp & plugins var gulp = require('gulp'); var autoprefixer = require('gulp-autoprefixer'); var sass = require('gulp-sass'); // BrowerSync var browserSync = require('browser-sync'); // Utilities var handleErrors = require('../util/handleErrors'); // Configs var config = require('../config').sass; gulp.task('sass', function () { return gulp.src(config.src) .pipe(sass(config.settings)) .on('error', handleErrors) .pipe(autoprefixer({browsers: ['last 2 version']})) .pipe(gulp.dest(config.dest)) .pipe(browserSync.reload({stream: true})); });
SteveTan86/react-app-starter
gulp/tasks/sass.js
JavaScript
gpl-3.0
609
$(document).ready(function(){$('.ajaxPopup, .ajax-form').on('click',function(a){a.preventDefault();$.ajax({url:$(this).attr('href'),context:document.body}).done(function(a){$(this).addClass("done");$('#ajaxPopup > div.content').html(a);$('#ajaxPopup').show();});});$('.closePopup').on('click',function(a){a.preventDefault();$('#ajaxPopup').hide();});$(document).ready(function(){$('select').material_select();});});
olymk2/maidstone-hackspace
website/static/js/default.js
JavaScript
gpl-3.0
415
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 __()); }; (function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core', '@angular/forms', '../app/app', '../../util/dom', '../../config/config', '../content/content', '../../util/dom-controller', '../../util/form', '../ion', '../../util/util', '../item/item', '../../navigation/nav-controller', '../../platform/platform'], factory); } })(function (require, exports) { "use strict"; var core_1 = require('@angular/core'); var forms_1 = require('@angular/forms'); var app_1 = require('../app/app'); var dom_1 = require('../../util/dom'); var config_1 = require('../../config/config'); var content_1 = require('../content/content'); var dom_controller_1 = require('../../util/dom-controller'); var form_1 = require('../../util/form'); var ion_1 = require('../ion'); var util_1 = require('../../util/util'); var item_1 = require('../item/item'); var nav_controller_1 = require('../../navigation/nav-controller'); var platform_1 = require('../../platform/platform'); /** * @private * Hopefully someday a majority of the auto-scrolling tricks can get removed. */ var InputBase = (function (_super) { __extends(InputBase, _super); function InputBase(config, _form, _item, _app, _platform, elementRef, renderer, _content, nav, ngControl, _dom) { var _this = this; _super.call(this, config, elementRef, renderer, 'input'); this._form = _form; this._item = _item; this._app = _app; this._platform = _platform; this._content = _content; this._dom = _dom; this._disabled = false; this._type = 'text'; this._value = ''; this._nav = nav; this._useAssist = config.getBoolean('scrollAssist', false); this._usePadding = config.getBoolean('scrollPadding', this._useAssist); this._keyboardHeight = config.getNumber('keyboardHeight'); this._autoFocusAssist = config.get('autoFocusAssist', 'delay'); this._autoComplete = config.get('autocomplete', 'off'); this._autoCorrect = config.get('autocorrect', 'off'); if (ngControl) { ngControl.valueAccessor = this; this.inputControl = ngControl; } _form.register(this); // only listen to content scroll events if there is content if (_content) { this._scrollStart = _content.ionScrollStart.subscribe(function (ev) { _this.scrollHideFocus(ev, true); }); this._scrollEnd = _content.ionScrollEnd.subscribe(function (ev) { _this.scrollHideFocus(ev, false); }); } } InputBase.prototype.scrollHideFocus = function (ev, shouldHideFocus) { var _this = this; // do not continue if there's no nav, or it's transitioning if (!this._nav) return; // DOM READ: check if this input has focus if (this.hasFocus()) { // if it does have focus, then do the dom write this._dom.write(function () { _this._native.hideFocus(shouldHideFocus); }); } }; InputBase.prototype.setItemInputControlCss = function () { var item = this._item; var nativeInput = this._native; var inputControl = this.inputControl; // Set the control classes on the item if (item && inputControl) { this.setControlCss(item, inputControl); } // Set the control classes on the native input if (nativeInput && inputControl) { this.setControlCss(nativeInput, inputControl); } }; InputBase.prototype.setControlCss = function (element, control) { element.setElementClass('ng-untouched', control.untouched); element.setElementClass('ng-touched', control.touched); element.setElementClass('ng-pristine', control.pristine); element.setElementClass('ng-dirty', control.dirty); element.setElementClass('ng-valid', control.valid); element.setElementClass('ng-invalid', !control.valid); }; InputBase.prototype.setValue = function (val) { this._value = val; this.checkHasValue(val); }; InputBase.prototype.setType = function (val) { this._type = 'text'; if (val) { val = val.toLowerCase(); if (/password|email|number|search|tel|url|date|month|time|week/.test(val)) { this._type = val; } } }; InputBase.prototype.setDisabled = function (val) { this._disabled = util_1.isTrueProperty(val); this._item && this._item.setElementClass('item-input-disabled', this._disabled); this._native && this._native.isDisabled(this._disabled); }; InputBase.prototype.setClearOnEdit = function (val) { this._clearOnEdit = util_1.isTrueProperty(val); }; /** * Check if we need to clear the text input if clearOnEdit is enabled * @private */ InputBase.prototype.checkClearOnEdit = function (inputValue) { if (!this._clearOnEdit) { return; } // Did the input value change after it was blurred and edited? if (this._didBlurAfterEdit && this.hasValue()) { // Clear the input this.clearTextInput(); } // Reset the flag this._didBlurAfterEdit = false; }; /** * Overriden in child input * @private */ InputBase.prototype.clearTextInput = function () { }; /** * @private */ InputBase.prototype.setNativeInput = function (nativeInput) { var _this = this; this._native = nativeInput; if (this._item && this._item.labelId !== null) { nativeInput.labelledBy(this._item.labelId); } nativeInput.valueChange.subscribe(function (inputValue) { _this.onChange(inputValue); }); nativeInput.keydown.subscribe(function (inputValue) { _this.onKeydown(inputValue); }); this.focusChange(this.hasFocus()); nativeInput.focusChange.subscribe(function (textInputHasFocus) { _this.focusChange(textInputHasFocus); _this.checkHasValue(nativeInput.getValue()); if (!textInputHasFocus) { _this.onTouched(textInputHasFocus); } }); this.checkHasValue(nativeInput.getValue()); this.setDisabled(this._disabled); var ionInputEle = this._elementRef.nativeElement; var nativeInputEle = nativeInput.element(); // copy ion-input attributes to the native input element dom_1.copyInputAttributes(ionInputEle, nativeInputEle); if (ionInputEle.hasAttribute('autofocus')) { // the ion-input element has the autofocus attributes ionInputEle.removeAttribute('autofocus'); if (this._autoFocusAssist === 'immediate') { // config says to immediate focus on the input // works best on android devices nativeInputEle.focus(); } else if (this._autoFocusAssist === 'delay') { // config says to chill out a bit and focus on the input after transitions // works best on desktop setTimeout(function () { nativeInputEle.focus(); }, 650); } } // by default set autocomplete="off" unless specified by the input if (ionInputEle.hasAttribute('autocomplete')) { this._autoComplete = ionInputEle.getAttribute('autocomplete'); } nativeInputEle.setAttribute('autocomplete', this._autoComplete); // by default set autocorrect="off" unless specified by the input if (ionInputEle.hasAttribute('autocorrect')) { this._autoCorrect = ionInputEle.getAttribute('autocorrect'); } nativeInputEle.setAttribute('autocorrect', this._autoCorrect); }; /** * @private */ InputBase.prototype.setNextInput = function (nextInput) { var _this = this; if (nextInput) { nextInput.focused.subscribe(function () { _this._form.tabFocus(_this); }); } }; /** * @private * Angular2 Forms API method called by the model (Control) on change to update * the checked value. * https://github.com/angular/angular/blob/master/modules/angular2/src/forms/directives/shared.ts#L34 */ InputBase.prototype.writeValue = function (val) { this._value = val; this.checkHasValue(val); }; /** * @private */ InputBase.prototype.onChange = function (val) { this.checkHasValue(val); }; /** * onKeydown handler for clearOnEdit * @private */ InputBase.prototype.onKeydown = function (val) { if (this._clearOnEdit) { this.checkClearOnEdit(val); } }; /** * @private */ InputBase.prototype.onTouched = function (val) { }; /** * @private */ InputBase.prototype.hasFocus = function () { // check if an input has focus or not return this._native.hasFocus(); }; /** * @private */ InputBase.prototype.hasValue = function () { var inputValue = this._value; return (inputValue !== null && inputValue !== undefined && inputValue !== ''); }; /** * @private */ InputBase.prototype.checkHasValue = function (inputValue) { if (this._item) { var hasValue = (inputValue !== null && inputValue !== undefined && inputValue !== ''); this._item.setElementClass('input-has-value', hasValue); } }; /** * @private */ InputBase.prototype.focusChange = function (inputHasFocus) { if (this._item) { (void 0) /* console.debug */; this._item.setElementClass('input-has-focus', inputHasFocus); } // If clearOnEdit is enabled and the input blurred but has a value, set a flag if (this._clearOnEdit && !inputHasFocus && this.hasValue()) { this._didBlurAfterEdit = true; } }; InputBase.prototype.pointerStart = function (ev) { // input cover touchstart if (ev.type === 'touchstart') { this._isTouch = true; } if ((this._isTouch || (!this._isTouch && ev.type === 'mousedown')) && this._app.isEnabled()) { // remember where the touchstart/mousedown started this._coord = dom_1.pointerCoord(ev); } (void 0) /* console.debug */; }; InputBase.prototype.pointerEnd = function (ev) { // input cover touchend/mouseup (void 0) /* console.debug */; if ((this._isTouch && ev.type === 'mouseup') || !this._app.isEnabled()) { // the app is actively doing something right now // don't try to scroll in the input ev.preventDefault(); ev.stopPropagation(); } else if (this._coord) { // get where the touchend/mouseup ended var endCoord = dom_1.pointerCoord(ev); // focus this input if the pointer hasn't moved XX pixels // and the input doesn't already have focus if (!dom_1.hasPointerMoved(8, this._coord, endCoord) && !this.hasFocus()) { ev.preventDefault(); ev.stopPropagation(); // begin the input focus process this.initFocus(); } } this._coord = null; }; /** * @private */ InputBase.prototype.initFocus = function () { var _this = this; // begin the process of setting focus to the inner input element var content = this._content; (void 0) /* console.debug */; if (content) { // this input is inside of a scroll view // find out if text input should be manually scrolled into view // get container of this input, probably an ion-item a few nodes up var ele = this._elementRef.nativeElement; ele = ele.closest('ion-item,[ion-item]') || ele; var scrollData = getScrollData(ele.offsetTop, ele.offsetHeight, content.getContentDimensions(), this._keyboardHeight, this._platform.height()); if (Math.abs(scrollData.scrollAmount) < 4) { // the text input is in a safe position that doesn't // require it to be scrolled into view, just set focus now this.setFocus(); // all good, allow clicks again this._app.setEnabled(true); this._nav && this._nav.setTransitioning(false); if (this._usePadding) { content.clearScrollPaddingFocusOut(); } return; } if (this._usePadding) { // add padding to the bottom of the scroll view (if needed) content.addScrollPadding(scrollData.scrollPadding); } // manually scroll the text input to the top // do not allow any clicks while it's scrolling var scrollDuration = getScrollAssistDuration(scrollData.scrollAmount); this._app.setEnabled(false, scrollDuration); this._nav && this._nav.setTransitioning(true); // temporarily move the focus to the focus holder so the browser // doesn't freak out while it's trying to get the input in place // at this point the native text input still does not have focus this._native.beginFocus(true, scrollData.inputSafeY); // scroll the input into place content.scrollTo(0, scrollData.scrollTo, scrollDuration, function () { (void 0) /* console.debug */; // the scroll view is in the correct position now // give the native text input focus _this._native.beginFocus(false, 0); // ensure this is the focused input _this.setFocus(); // all good, allow clicks again _this._app.setEnabled(true); _this._nav && _this._nav.setTransitioning(false); if (_this._usePadding) { content.clearScrollPaddingFocusOut(); } }); } else { // not inside of a scroll view, just focus it this.setFocus(); } }; /** * @private */ InputBase.prototype.setFocus = function () { // immediately set focus this._form.setAsFocused(this); // set focus on the actual input element (void 0) /* console.debug */; this._native.setFocus(); // ensure the body hasn't scrolled down document.body.scrollTop = 0; }; /** * @private * Angular2 Forms API method called by the view (formControlName) to register the * onChange event handler that updates the model (Control). * @param {Function} fn the onChange event handler. */ InputBase.prototype.registerOnChange = function (fn) { this.onChange = fn; }; /** * @private * Angular2 Forms API method called by the view (formControlName) to register * the onTouched event handler that marks model (Control) as touched. * @param {Function} fn onTouched event handler. */ InputBase.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; InputBase.prototype.focusNext = function () { this._form.tabFocus(this); }; /** @nocollapse */ InputBase.ctorParameters = [ { type: config_1.Config, }, { type: form_1.Form, }, { type: item_1.Item, }, { type: app_1.App, }, { type: platform_1.Platform, }, { type: core_1.ElementRef, }, { type: core_1.Renderer, }, { type: content_1.Content, decorators: [{ type: core_1.Optional },] }, { type: nav_controller_1.NavController, }, { type: forms_1.NgControl, }, { type: dom_controller_1.DomController, }, ]; return InputBase; }(ion_1.Ion)); exports.InputBase = InputBase; /** * @private */ function getScrollData(inputOffsetTop, inputOffsetHeight, scrollViewDimensions, keyboardHeight, plaformHeight) { // compute input's Y values relative to the body var inputTop = (inputOffsetTop + scrollViewDimensions.contentTop - scrollViewDimensions.scrollTop); var inputBottom = (inputTop + inputOffsetHeight); // compute the safe area which is the viewable content area when the soft keyboard is up var safeAreaTop = scrollViewDimensions.contentTop; var safeAreaHeight = (plaformHeight - keyboardHeight - safeAreaTop) / 2; var safeAreaBottom = safeAreaTop + safeAreaHeight; // figure out if each edge of teh input is within the safe area var inputTopWithinSafeArea = (inputTop >= safeAreaTop && inputTop <= safeAreaBottom); var inputTopAboveSafeArea = (inputTop < safeAreaTop); var inputTopBelowSafeArea = (inputTop > safeAreaBottom); var inputBottomWithinSafeArea = (inputBottom >= safeAreaTop && inputBottom <= safeAreaBottom); var inputBottomBelowSafeArea = (inputBottom > safeAreaBottom); /* Text Input Scroll To Scenarios --------------------------------------- 1) Input top within safe area, bottom within safe area 2) Input top within safe area, bottom below safe area, room to scroll 3) Input top above safe area, bottom within safe area, room to scroll 4) Input top below safe area, no room to scroll, input smaller than safe area 5) Input top within safe area, bottom below safe area, no room to scroll, input smaller than safe area 6) Input top within safe area, bottom below safe area, no room to scroll, input larger than safe area 7) Input top below safe area, no room to scroll, input larger than safe area */ var scrollData = { scrollAmount: 0, scrollTo: 0, scrollPadding: 0, inputSafeY: 0 }; if (inputTopWithinSafeArea && inputBottomWithinSafeArea) { // Input top within safe area, bottom within safe area // no need to scroll to a position, it's good as-is return scrollData; } // looks like we'll have to do some auto-scrolling if (inputTopBelowSafeArea || inputBottomBelowSafeArea || inputTopAboveSafeArea) { // Input top or bottom below safe area // auto scroll the input up so at least the top of it shows if (safeAreaHeight > inputOffsetHeight) { // safe area height is taller than the input height, so we // can bring up the input just enough to show the input bottom scrollData.scrollAmount = Math.round(safeAreaBottom - inputBottom); } else { // safe area height is smaller than the input height, so we can // only scroll it up so the input top is at the top of the safe area // however the input bottom will be below the safe area scrollData.scrollAmount = Math.round(safeAreaTop - inputTop); } scrollData.inputSafeY = -(inputTop - safeAreaTop) + 4; if (inputTopAboveSafeArea && scrollData.scrollAmount > inputOffsetHeight) { // the input top is above the safe area and we're already scrolling it into place // don't let it scroll more than the height of the input scrollData.scrollAmount = inputOffsetHeight; } } // figure out where it should scroll to for the best position to the input scrollData.scrollTo = (scrollViewDimensions.scrollTop - scrollData.scrollAmount); // when auto-scrolling, there also needs to be enough // content padding at the bottom of the scroll view // always add scroll padding when a text input has focus // this allows for the content to scroll above of the keyboard // content behind the keyboard would be blank // some cases may not need it, but when jumping around it's best // to have the padding already rendered so there's no jank scrollData.scrollPadding = keyboardHeight; // var safeAreaEle: HTMLElement = (<any>window).safeAreaEle; // if (!safeAreaEle) { // safeAreaEle = (<any>window).safeAreaEle = document.createElement('div'); // safeAreaEle.style.cssText = 'position:absolute; padding:1px 5px; left:0; right:0; font-weight:bold; font-size:10px; font-family:Courier; text-align:right; background:rgba(0, 128, 0, 0.8); text-shadow:1px 1px white; pointer-events:none;'; // document.body.appendChild(safeAreaEle); // } // safeAreaEle.style.top = safeAreaTop + 'px'; // safeAreaEle.style.height = safeAreaHeight + 'px'; // safeAreaEle.innerHTML = ` // <div>scrollTo: ${scrollData.scrollTo}</div> // <div>scrollAmount: ${scrollData.scrollAmount}</div> // <div>scrollPadding: ${scrollData.scrollPadding}</div> // <div>inputSafeY: ${scrollData.inputSafeY}</div> // <div>scrollHeight: ${scrollViewDimensions.scrollHeight}</div> // <div>scrollTop: ${scrollViewDimensions.scrollTop}</div> // <div>contentHeight: ${scrollViewDimensions.contentHeight}</div> // <div>plaformHeight: ${plaformHeight}</div> // `; return scrollData; } exports.getScrollData = getScrollData; var SCROLL_ASSIST_SPEED = 0.3; function getScrollAssistDuration(distanceToScroll) { distanceToScroll = Math.abs(distanceToScroll); var duration = distanceToScroll / SCROLL_ASSIST_SPEED; return Math.min(400, Math.max(150, duration)); } }); //# sourceMappingURL=input-base.js.map
kfrerichs/roleplay
node_modules/ionic-angular/umd/components/input/input-base.js
JavaScript
gpl-3.0
24,204
'use strict'; // Users service used for communicating with the users REST endpoint angular.module('users').factory('Users', [ '$resource', function ($resource) { return $resource('users', {}, { update: { method: 'PUT' } }); } ]);
ogarling/targets-io
public/modules/users/services/users.client.service.js
JavaScript
gpl-3.0
239
"use strict"; tutao.provide('tutao.entity.sys.ChangePasswordData'); /** * @constructor * @param {Object=} data The json data to store in this entity. */ tutao.entity.sys.ChangePasswordData = function(data) { if (data) { this.updateData(data); } else { this.__format = "0"; this._code = null; this._pwEncUserGroupKey = null; this._salt = null; this._verifier = null; } this._entityHelper = new tutao.entity.EntityHelper(this); this.prototype = tutao.entity.sys.ChangePasswordData.prototype; }; /** * Updates the data of this entity. * @param {Object=} data The json data to store in this entity. */ tutao.entity.sys.ChangePasswordData.prototype.updateData = function(data) { this.__format = data._format; this._code = data.code; this._pwEncUserGroupKey = data.pwEncUserGroupKey; this._salt = data.salt; this._verifier = data.verifier; }; /** * The version of the model this type belongs to. * @const */ tutao.entity.sys.ChangePasswordData.MODEL_VERSION = '10'; /** * The url path to the resource. * @const */ tutao.entity.sys.ChangePasswordData.PATH = '/rest/sys/changepasswordservice'; /** * The encrypted flag. * @const */ tutao.entity.sys.ChangePasswordData.prototype.ENCRYPTED = false; /** * Provides the data of this instances as an object that can be converted to json. * @return {Object} The json object. */ tutao.entity.sys.ChangePasswordData.prototype.toJsonData = function() { return { _format: this.__format, code: this._code, pwEncUserGroupKey: this._pwEncUserGroupKey, salt: this._salt, verifier: this._verifier }; }; /** * The id of the ChangePasswordData type. */ tutao.entity.sys.ChangePasswordData.prototype.TYPE_ID = 534; /** * The id of the code attribute. */ tutao.entity.sys.ChangePasswordData.prototype.CODE_ATTRIBUTE_ID = 539; /** * The id of the pwEncUserGroupKey attribute. */ tutao.entity.sys.ChangePasswordData.prototype.PWENCUSERGROUPKEY_ATTRIBUTE_ID = 538; /** * The id of the salt attribute. */ tutao.entity.sys.ChangePasswordData.prototype.SALT_ATTRIBUTE_ID = 537; /** * The id of the verifier attribute. */ tutao.entity.sys.ChangePasswordData.prototype.VERIFIER_ATTRIBUTE_ID = 536; /** * Sets the format of this ChangePasswordData. * @param {string} format The format of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setFormat = function(format) { this.__format = format; return this; }; /** * Provides the format of this ChangePasswordData. * @return {string} The format of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getFormat = function() { return this.__format; }; /** * Sets the code of this ChangePasswordData. * @param {string} code The code of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setCode = function(code) { this._code = code; return this; }; /** * Provides the code of this ChangePasswordData. * @return {string} The code of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getCode = function() { return this._code; }; /** * Sets the pwEncUserGroupKey of this ChangePasswordData. * @param {string} pwEncUserGroupKey The pwEncUserGroupKey of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setPwEncUserGroupKey = function(pwEncUserGroupKey) { this._pwEncUserGroupKey = pwEncUserGroupKey; return this; }; /** * Provides the pwEncUserGroupKey of this ChangePasswordData. * @return {string} The pwEncUserGroupKey of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getPwEncUserGroupKey = function() { return this._pwEncUserGroupKey; }; /** * Sets the salt of this ChangePasswordData. * @param {string} salt The salt of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setSalt = function(salt) { this._salt = salt; return this; }; /** * Provides the salt of this ChangePasswordData. * @return {string} The salt of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getSalt = function() { return this._salt; }; /** * Sets the verifier of this ChangePasswordData. * @param {string} verifier The verifier of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.setVerifier = function(verifier) { this._verifier = verifier; return this; }; /** * Provides the verifier of this ChangePasswordData. * @return {string} The verifier of this ChangePasswordData. */ tutao.entity.sys.ChangePasswordData.prototype.getVerifier = function() { return this._verifier; }; /** * Posts to a service. * @param {Object.<string, string>} parameters The parameters to send to the service. * @param {?Object.<string, string>} headers The headers to send to the service. If null, the default authentication data is used. * @return {Promise.<null=>} Resolves to the string result of the server or rejects with an exception if the post failed. */ tutao.entity.sys.ChangePasswordData.prototype.setup = function(parameters, headers) { if (!headers) { headers = tutao.entity.EntityHelper.createAuthHeaders(); } parameters["v"] = 10; this._entityHelper.notifyObservers(false); return tutao.locator.entityRestClient.postService(tutao.entity.sys.ChangePasswordData.PATH, this, parameters, headers, null); }; /** * Provides the entity helper of this entity. * @return {tutao.entity.EntityHelper} The entity helper. */ tutao.entity.sys.ChangePasswordData.prototype.getEntityHelper = function() { return this._entityHelper; };
bartuspan/tutanota
web/js/generated/entity/sys/ChangePasswordData.js
JavaScript
gpl-3.0
5,572
import emotion from 'preact-emotion'; import remcalc from 'remcalc'; import { Category } from './service'; export const Place = emotion(Category)` margin-bottom: ${remcalc(10)}; `; export const Region = emotion('h6')` margin: ${remcalc(6)} 0; font-size: ${remcalc(13)}; line-height: ${remcalc(18)}; font-weight: ${props => props.theme.font.weight.normal}; color: #494949; `; export { Name as default } from './service';
geek/joyent-portal
packages/my-joy-navigation/src/components/datacenter.js
JavaScript
mpl-2.0
437
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import EnemyInstances from 'parser/shared/modules/EnemyInstances'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import Statistic from 'interface/statistics/Statistic'; import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText'; import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER'; const debug = false; const HARDCAST_HITS = [ SPELLS.FROSTBOLT_DAMAGE.id, SPELLS.EBONBOLT_DAMAGE.id, SPELLS.GLACIAL_SPIKE_DAMAGE.id, ]; class WintersChill extends Analyzer { static dependencies = { enemies: EnemyInstances, }; hasGlacialSpike; totalProcs = 0; hardcastHits = 0; missedHardcasts = 0; singleHardcasts = 0; iceLanceHits = 0; missedIceLanceCasts = 0; singleIceLanceCasts = 0; doubleIceLanceCasts = 0; on_byPlayer_damage(event) { const spellId = event.ability.guid; const enemy = this.enemies.getEntity(event); if (!enemy || !enemy.hasBuff(SPELLS.WINTERS_CHILL.id)) { return; } if (spellId === SPELLS.ICE_LANCE_DAMAGE.id) { this.iceLanceHits += 1; debug && console.log("Ice Lance into Winter's Chill"); } else if(HARDCAST_HITS.includes(spellId)) { this.hardcastHits += 1; debug && console.log(`${event.ability.name} into Winter's Chill`); } } on_byPlayer_applydebuff(event) { const spellId = event.ability.guid; if(spellId !== SPELLS.WINTERS_CHILL.id) { return; } this.iceLanceHits = 0; this.hardcastHits = 0; } on_byPlayer_removedebuff(event) { const spellId = event.ability.guid; if(spellId !== SPELLS.WINTERS_CHILL.id) { return; } this.totalProcs += 1; if (this.iceLanceHits === 0) { this.missedIceLanceCasts += 1; } else if (this.iceLanceHits === 1) { this.singleIceLanceCasts += 1; } else if (this.iceLanceHits === 2) { this.doubleIceLanceCasts += 1; } else { this.error(`Unexpected number of Ice Lances inside Winter's Chill -> ${this.iceLanceHits}`); } if (this.hardcastHits === 0) { this.missedHardcasts += 1; } else if (this.hardcastHits === 1) { this.singleHardcasts += 1; } else { this.error(`Unexpected number of Frostbolt hits inside Winter's Chill -> ${this.hardcastHits}`); } } get iceLanceMissedPercent() { return (this.missedIceLanceCasts / this.totalProcs) || 0; } get iceLanceUtil() { return 1 - this.iceLanceMissedPercent; } get iceLanceUtilSuggestionThresholds() { return { actual: this.iceLanceUtil, isLessThan: { minor: 0.95, average: 0.85, major: 0.75, }, style: 'percentage', }; } get hardcastMissedPercent() { return (this.missedHardcasts / this.totalProcs) || 0; } get hardcastUtil() { return 1 - this.hardcastMissedPercent; } // less strict than the ice lance suggestion both because it's less important, // and also because using a Brain Freeze after being forced to move is a good excuse for missing the hardcast. get hardcastUtilSuggestionThresholds() { return { actual: this.hardcastUtil, isLessThan: { minor: 0.90, average: 0.80, major: 0.60, }, style: 'percentage', }; } get doubleIceLancePercentage() { return this.doubleIceLanceCasts / this.totalProcs || 0; } suggestions(when) { when(this.iceLanceUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You failed to Ice Lance into <SpellLink id={SPELLS.WINTERS_CHILL.id} /> {this.missedIceLanceCasts} times ({formatPercentage(this.iceLanceMissedPercent)}%). Make sure you cast <SpellLink id={SPELLS.ICE_LANCE.id} /> after each <SpellLink id={SPELLS.FLURRY.id} /> to benefit from <SpellLink id={SPELLS.SHATTER.id} />.</>) .icon(SPELLS.ICE_LANCE.icon) .actual(`${formatPercentage(this.iceLanceMissedPercent)}% Winter's Chill not shattered with Ice Lance`) .recommended(`<${formatPercentage(1 - this.iceLanceUtilSuggestionThresholds.isLessThan.minor)}% is recommended`); }); when(this.hardcastUtilSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You failed to <SpellLink id={SPELLS.FROSTBOLT.id} />, <SpellLink id={SPELLS.GLACIAL_SPIKE_TALENT.id} /> or <SpellLink id={SPELLS.EBONBOLT_TALENT.id} /> into <SpellLink id={SPELLS.WINTERS_CHILL.id} /> {this.missedHardcasts} times ({formatPercentage(this.hardcastMissedPercent)}%). Make sure you hard cast just before each instant <SpellLink id={SPELLS.FLURRY.id} /> to benefit from <SpellLink id={SPELLS.SHATTER.id} />.</>) .icon(SPELLS.FROSTBOLT.icon) .actual(`${formatPercentage(this.hardcastMissedPercent)}% Winter's Chill not shattered with Frostbolt, Glacial Spike, or Ebonbolt`) .recommended(`${formatPercentage(1 - recommended)}% is recommended`); }); } statistic() { return ( <Statistic position={STATISTIC_ORDER.CORE(30)} size="flexible" tooltip={( <> Every Brain Freeze Flurry should be preceded by a Frostbolt, Glacial Spike, or Ebonbolt and followed by an Ice Lance, so that both the preceding and following spells benefit from Shatter. <br /><br /> You double Ice Lance'd into Winter's Chill {this.doubleIceLanceCasts} times ({formatPercentage(this.doubleIceLancePercentage, 1)}%). Note this is usually impossible, it can only be done with strong Haste buffs active and by moving towards the target while casting. It should mostly be considered 'extra credit' </> )} > <BoringSpellValueText spell={SPELLS.WINTERS_CHILL}> <SpellIcon id={SPELLS.ICE_LANCE.id} /> {formatPercentage(this.iceLanceUtil, 0)}% <small>Ice Lances shattered</small><br /> <SpellIcon id={SPELLS.FROSTBOLT.id} /> {formatPercentage(this.hardcastUtil, 0)}% <small>Pre-casts shattered</small> </BoringSpellValueText> </Statistic> ); } } export default WintersChill;
fyruna/WoWAnalyzer
src/parser/mage/frost/modules/features/WintersChill.js
JavaScript
agpl-3.0
6,255
#!/usr/bin/env node 'use strict'; /** * Documents RPC Prototype * * - TIU CREATE RECORD (MAKE^TIUSRVP) * - TIU UPDATE RECORD (UPDATE^TIUSRVP) * - TIU DELETE RECORD (DELETE^TIUSRVP) * - TIU SIGN RECORD * ... and locks * ... key file, TIUSRVP * * REM: HMP set * "TIU AUTHORIZATION", * "TIU CREATE ADDENDUM RECORD", * "TIU CREATE RECORD", * "TIU DELETE RECORD", * "TIU DOCUMENTS BY CONTEXT", * "TIU GET DOCUMENT TITLE", * "TIU GET RECORD TEXT", * "TIU GET REQUEST", * "TIU IS THIS A CONSULT?", # manually added ? * "TIU IS THIS A SURGERY?", # manually added ? * "TIU ISPRF", * "TIU LOCK RECORD", * "TIU LONG LIST OF TITLES", * "TIU REQUIRES COSIGNATURE", * "TIU SET DOCUMENT TEXT", * "TIU SIGN RECORD", * "TIU UNLOCK RECORD", * "TIU UPDATE RECORD", * * but CPRS has more: http://vistadataproject.info/artifacts/cprsRPCs * * NOTE: year 1 (2016) has NO locking for TIU RPCs so this wasn't coded for dual pass (facade) * * Scope: initially for Allergy (Progress notes) generated automatically * from Allergy code ... * GMRAGUI1 -> EN1^GMRAPET0 (for S and E cases) -> NEW^TIUPNAPI (turns text in TMP into pass by ref) -> MAKE^TIUSRVP (same as RPC) * and note SPNJRPPN and other VISTA note makers. * * (c) 2016 VISTA Data Project */ /* * Basic setup */ const util = require('util'); const fs = require('fs'); const nodem = require('nodem'); const os = require('os'); const _ = require('lodash'); const fileman = require('../fileman'); const RPCRunner = require('../rpcRunner').RPCRunner; const vdmUtils = require('../vdmUtils'); const VDM = require('../vdm'); // using VDM read to test results const vdmModel = require('./vdmDocumentsModel').vdmModel; // for initial dump of required properties const testUtils = require('../testUtils'); // Convenience function to form the text function formatTextLines(lines) { const tlines = []; lines.forEach((line) => { tlines.push({ 0: line }); }); return tlines; } describe('testDocumentRPCs', () => { let db; // for afterAll let DUZ; // play with 55 to 56 ie/ different DUZ to see what defaults ... let DUZSIG; // AUTHORSIG ie/ signature used for signing let patientIEN; let rpcRunner; // "id": "8925_1-17", "label": "ADVERSE REACTION_ALLERGY" const araDocTypeIEN = '17'; beforeAll(() => { db = new nodem.Gtm(); db.open(); const userId = testUtils.lookupUserIdByName(db, 'ALEXANDER,ROBERT'); DUZ = parseInt(userId.split('-')[1], 10); DUZSIG = 'ROBA123'; // Robert's e sig patientIEN = testUtils.lookupPatientIdByName(db, 'CARTER,DAVID').split('-')[1]; VDM.setDBAndModel(db, vdmModel); // empty both TIU docs (8925) and VISITs (created by side effect) ['8925', '9000010'].forEach((value) => { fileman.emptyFile(db, value); }); rpcRunner = new RPCRunner(db); rpcRunner.initializeUser(DUZ); }); // Leads to error (exception) if don't define patient properly // NEW^TIUPNAPI used by Allergy Doc creation does stop bad Patient properly but MAKE, which is called directly by RPC, doesn't it('Error - patient-less/bad Create S Progress Note', () => { const rpcDefn = { name: 'TIU CREATE RECORD', args: [ '', araDocTypeIEN, '', '', '', { 1202: DUZ, TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; // errorMessage: 'EVENT+2^TIUSRVP1,%GTM-E-NULSUBSC, Null subscripts are not allowed for region: DEFAULT,%GTM-I-GVIS, \t\tGlobal variable: ^DPT("",.105)' expect(() => { rpcRunner.run(rpcDefn.name, rpcDefn.args); }).toThrowError(/EVENT\+2\^TIUSRVP1,%GTM-E-NULSUBSC, Null subscripts/); rpcDefn.args[0] = '111111111'; // errorMessage: 'PATVADPT+4^TIULV,%GTM-E-UNDEF, Undefined local variable: VA(BID)' expect(() => { rpcRunner.run(rpcDefn.name, rpcDefn.args); }).toThrowError('PATVADPT+4^TIULV,%GTM-E-UNDEF, Undefined local variable: VA(BID)'); }); // Leads to error (0/msg) if don't define document_type properly // NEW^TIUPNAPI used by Allergy doc creation stops this before the MAKE even sees it but RPC uses MAKE directly so MAKE check is needed it('Error - document type-less/bad Create S Progress Note', () => { // lot's missing const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, '', '', '', '', { 1202: DUZ, TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; let res = rpcRunner.run(rpcDefn.name, rpcDefn.args); // '0^Invalid TITLE Selected.', expect(res.result).toMatch(/0\^Invalid TITLE Selected./); rpcDefn.args[1] = '111111111'; // nonsense document type res = rpcRunner.run(rpcDefn.name, rpcDefn.args); // '0^Invalid TITLE Selected.' - expect same error expect(res.result).toMatch(/0\^Invalid TITLE Selected./); }); // Correct full note - that largely matches the input VDM // ... only three explicit values needed // - note doesn't show in VPR (as unsigned?) // - does show (so does report_text-less note) in CPRS it('Create S Progress Note', () => { // explicitly removing division and (reference) date and even author (defaults to duz) // SO ONLY THREE VALUES: patient, document title, report_text ... dates and duz defaulted elsewhere. const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, araDocTypeIEN, '', '', '', { 1202: DUZ, TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; const res = rpcRunner.run(rpcDefn.name, rpcDefn.args); expect(res.result).not.toEqual(0); // get result const tiuIEN = res.result; const descr = VDM.describe(`8925-${tiuIEN}`); descr.type = 'Tiu_Document-8925'; // TMP Fix til FMQL fills JLD type 'properly' expect(descr.report_text).toBeDefined(); }); // Allowed a text-less note! Another short coming - shows in CPRS too. // // Note: path of create allergy note through NEW^TIUNAPI does stop text-less (I $D(^TMP("TIUP",$J))'>9 Q ; If no text, quit) // but RPC goes straight to MAKE which has no check (ditto for author which is explicit and not just DUZ!) it('Not error but - text-less Create S Progress Note', () => { const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, araDocTypeIEN, '', '', '', '', ], }; const res = rpcRunner.run(rpcDefn.name, rpcDefn.args); expect(res.result[0]).not.toEqual(0); // get result const tiuIEN = res.result; const descr = VDM.describe(`8925-${tiuIEN}`); expect(descr.report_text).toBeUndefined(); expect(parseInt(descr.line_count, 10)).toEqual(0); }); // create bad explicit author (ie/ leave in but make bad) - leave invalid ref in Doc it('Not error but - bad explicit author (not DUZ) Create S Progress Note', () => { const bad200 = '200-111111'; const rpcDefn = { name: 'TIU CREATE RECORD', args: [ patientIEN, araDocTypeIEN, '', '', '', { 1202: bad200.split('-')[1], // bad author_dictator TEXT: formatTextLines(['This patient has had the following reactions ', 'signed-off on Mar 05, 2016@01:16:21.', '', 'CHOCOLATE', '', "Author's comments:", '', 'unfortunate fellow ', '']), }, ], }; const res = rpcRunner.run(rpcDefn.name, rpcDefn.args); expect(res.result).not.toMatch(/0/); // get result const tiuIEN = res.result; const descr = VDM.describe(`8925-${tiuIEN}`); expect(descr.author_dictator.id).toEqual(bad200); }); // RPC TIU SIGN RECORD (SIGN^TIUSRVP) it('Sign/complete proper Progress Note', () => { // must encrypt the sig! const encryptedSig = db.function({ function: 'ENCRYP^XUSRB1', arguments: [DUZSIG] }).result; const goodNoteIEN = '1'; // not the one with the bad Author but Robert so should work const rpcArgs = [goodNoteIEN, encryptedSig]; // tried in clear too but also fails // if fails: '89250005^You have entered an incorrect Electronic Signature Code...Try again!' const res = rpcRunner.run('TIU SIGN RECORD', rpcArgs); // but want 0! expect(parseInt(res.result, 10)).toEqual(89250005); // TODO: try TIU WHICH SIGNATURE ACTION // TODO: try AUTHSIGN^TIUSRVA (TIU HAS AUTHOR SIGNED) // TODO: ? need LOCK^TIUSRVP (TIU LOCK RECORD) }); /* * Automatic Visit Creation - note: it happens to be queued. Logic is ... */ it('Create E Progress Note', () => { // ..D EN1^GMRAPET0(GMRADFN,.GMRAIEN,"S",.GMRAOUT) ;21 File progress note ... update }); // TIU UPDATE RECORD - UPDATE^TIUSRVP // - updates the record named in the TIUDA parameter, with theinformation contained in the TIUX(Field #) array // ... if can edit in place ... // - err passed by reference /* NOTE: the ability to merge text ... { "id": "8994_02-2_92", "type": "vs:Input_Parameter-8994_02", "input_parameter-8994_02": "TIUDA", "parameter_type-8994_02": "LITERAL", "required-8994_02": true, "description-8994_02": "This is the record # (IEN) of the TIU Document in file #8925." }, { "id": "8994_02-3_92", "type": "vs:Input_Parameter-8994_02", "input_parameter-8994_02": "TIUX", "parameter_type-8994_02": "LIST", "required-8994_02": true, "description-8994_02": "This is the input array which contains the data to be filed in themodified document. It should look something like this: TIUX(.02)=45678TIUX(1301)=2960703.104556TIUX(1302)=293764TIUX(\"TEXT\",1,0)=\"The patient is a 70 year old WHITE MALE, who presentedto the ONCOLOGY CLINIC\"TIUX(\"TEXT\",2,0)=\"On JULY 3, 1996@10:00 AM, with the chief complaint ofNECK PAIN...\"" }, and This API updates the record named in the TIUDA parameter, with theinformation contained in the TIUX(Field #) array. The body of themodified TIU document should be passed in the TIUX(\"TEXT\",i,0) subscript,where i is the line number (i.e., the \"TEXT\" node should be ready to MERGEwith a word processing field). Any filing errors which may occur will bereturned in the single valued ERR parameter (which is passed byreference). */ // Circumstances of DELETE RECORD (see CPRS) ... if EIE Allergy before signing? - really need clones. afterAll(() => { db.close(); }); });
vistadataproject/VDM
prototypes/tiuDocuments/rpcDocuments-spec.js
JavaScript
agpl-3.0
11,813
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {bool, func, number, shape, string} from 'prop-types' import {FormFieldGroup} from '@instructure/ui-form-field' import SubmissionTrayRadioInput from './SubmissionTrayRadioInput' import {statusesTitleMap} from '../constants/statuses' import I18n from 'i18n!gradebook' function checkedValue(submission) { if (submission.excused) { return 'excused' } else if (submission.missing) { return 'missing' } else if (submission.late) { return 'late' } return 'none' } export default class SubmissionTrayRadioInputGroup extends React.Component { state = {pendingUpdateData: null} componentWillReceiveProps(nextProps) { if ( this.props.submissionUpdating && !nextProps.submissionUpdating && this.state.pendingUpdateData ) { this.props.updateSubmission(this.state.pendingUpdateData) this.setState({pendingUpdateData: null}) } } handleRadioInputChanged = ({target: {value}}) => { const alreadyChecked = checkedValue(this.props.submission) === value if (alreadyChecked && !this.props.submissionUpdating) { return } const data = value === 'excused' ? {excuse: true} : {latePolicyStatus: value} if (value === 'late') { data.secondsLateOverride = this.props.submission.secondsLate } if (this.props.submissionUpdating) { this.setState({pendingUpdateData: data}) } else { this.props.updateSubmission(data) } } render() { const radioOptions = ['none', 'late', 'missing', 'excused'].map(status => ( <SubmissionTrayRadioInput key={status} checked={checkedValue(this.props.submission) === status} color={this.props.colors[status]} disabled={this.props.disabled} latePolicy={this.props.latePolicy} locale={this.props.locale} onChange={this.handleRadioInputChanged} updateSubmission={this.props.updateSubmission} submission={this.props.submission} text={statusesTitleMap[status] || I18n.t('None')} value={status} /> )) return ( <FormFieldGroup description={I18n.t('Status')} disabled={this.props.disabled} layout="stacked" rowSpacing="none" > {radioOptions} </FormFieldGroup> ) } } SubmissionTrayRadioInputGroup.propTypes = { colors: shape({ late: string.isRequired, missing: string.isRequired, excused: string.isRequired }).isRequired, disabled: bool.isRequired, latePolicy: shape({ lateSubmissionInterval: string.isRequired }).isRequired, locale: string.isRequired, submission: shape({ excused: bool.isRequired, late: bool.isRequired, missing: bool.isRequired, secondsLate: number.isRequired }).isRequired, submissionUpdating: bool.isRequired, updateSubmission: func.isRequired }
djbender/canvas-lms
app/jsx/gradebook/default_gradebook/components/SubmissionTrayRadioInputGroup.js
JavaScript
agpl-3.0
3,563
// -- // Copyright (C) 2001-2016 OTRS AG, http://otrs.com/ // -- // This software comes with ABSOLUTELY NO WARRANTY. For details, see // the enclosed file COPYING for license information (AGPL). If you // did not receive this file, see http://www.gnu.org/licenses/agpl.txt. // -- "use strict"; var Core = Core || {}; Core.UI = Core.UI || {}; /** * @namespace Core.UI.Datepicker * @memberof Core.UI * @author OTRS AG * @description * This namespace contains the datepicker functions. */ Core.UI.Datepicker = (function (TargetNS) { /** * @private * @name VacationDays * @memberof Core.UI.Datepicker * @member {Object} * @description * Vacation days, defined in SysConfig. */ var VacationDays, /** * @private * @name VacationDaysOneTime * @memberof Core.UI.Datepicker * @member {Object} * @description * One time vacations, defined in SysConfig. */ VacationDaysOneTime, /** * @private * @name LocalizationData * @memberof Core.UI.Datepicker * @member {Object} * @description * Translations. */ LocalizationData, /** * @private * @name DatepickerCount * @memberof Core.UI.Datepicker * @member {Number} * @description * Number of initialized datepicker. */ DatepickerCount = 0; if (!Core.Debug.CheckDependency('Core.UI.Datepicker', '$([]).datepicker', 'jQuery UI datepicker')) { return false; } /** * @private * @name CheckDate * @memberof Core.UI.Datepicker * @function * @returns {Array} First element is always true, second element contains the name of a CSS class, third element a description for the date. * @param {DateObject} DateObject - A JS date object to check. * @description * Check if date is on of the defined vacation days. */ function CheckDate(DateObject) { var DayDescription = '', DayClass = ''; // Get defined days from Config, if not done already if (typeof VacationDays === 'undefined') { VacationDays = Core.Config.Get('Datepicker.VacationDays').TimeVacationDays; } if (typeof VacationDaysOneTime === 'undefined') { VacationDaysOneTime = Core.Config.Get('Datepicker.VacationDays').TimeVacationDaysOneTime; } // Check if date is one of the vacation days if (typeof VacationDays[DateObject.getMonth() + 1] !== 'undefined' && typeof VacationDays[DateObject.getMonth() + 1][DateObject.getDate()] !== 'undefined') { DayDescription += VacationDays[DateObject.getMonth() + 1][DateObject.getDate()]; DayClass = 'Highlight '; } // Check if date is one of the one time vacation days if (typeof VacationDaysOneTime[DateObject.getFullYear()] !== 'undefined' && typeof VacationDaysOneTime[DateObject.getFullYear()][DateObject.getMonth() + 1] !== 'undefined' && typeof VacationDaysOneTime[DateObject.getFullYear()][DateObject.getMonth() + 1][DateObject.getDate()] !== 'undefined') { DayDescription += VacationDaysOneTime[DateObject.getFullYear()][DateObject.getMonth() + 1][DateObject.getDate()]; DayClass = 'Highlight '; } if (DayClass.length) { return [true, DayClass, DayDescription]; } else { return [true, '']; } } /** * @name Init * @memberof Core.UI.Datepicker * @function * @returns {Boolean} false, if Parameter Element is not of the correct type. * @param {jQueryObject|Object} Element - The jQuery object of a text input field which should get a datepicker. * Or a hash with the Keys 'Year', 'Month' and 'Day' and as values the jQueryObjects of the select drop downs. * @description * This function initializes the datepicker on the defined elements. */ TargetNS.Init = function (Element) { var $DatepickerElement, HasDateSelectBoxes = false, Options, ErrorMessage; if (typeof Element.VacationDays === 'object') { Core.Config.Set('Datepicker.VacationDays', Element.VacationDays); } /** * @private * @name LeadingZero * @memberof Core.UI.Datepicker.Init * @function * @returns {String} A number with leading zero, if needed. * @param {Number} Number - A number to convert. * @description * Converts a one digit number to a string with leading zero. */ function LeadingZero(Number) { if (Number.toString().length === 1) { return '0' + Number; } else { return Number; } } if (typeof LocalizationData === 'undefined') { LocalizationData = Core.Config.Get('Datepicker.Localization'); if (typeof LocalizationData === 'undefined') { throw new Core.Exception.ApplicationError('Datepicker localization data could not be found!', 'InternalError'); } } // Increment number of initialized datepickers on this site DatepickerCount++; // Check, if datepicker is used with three input element or with three select boxes if (typeof Element === 'object' && typeof Element.Day !== 'undefined' && typeof Element.Month !== 'undefined' && typeof Element.Year !== 'undefined' && isJQueryObject(Element.Day, Element.Month, Element.Year) && // Sometimes it can happen that BuildDateSelection was called without placing the full date selection. // Ignore in this case. Element.Day.length ) { $DatepickerElement = $('<input>').attr('type', 'hidden').attr('id', 'Datepicker' + DatepickerCount); Element.Year.after($DatepickerElement); if (Element.Day.is('select') && Element.Month.is('select') && Element.Year.is('select')) { HasDateSelectBoxes = true; } } else { return false; } // Define options hash Options = { beforeShowDay: function (DateObject) { return CheckDate(DateObject); }, showOn: 'focus', prevText: LocalizationData.PrevText, nextText: LocalizationData.NextText, firstDay: Element.WeekDayStart, showMonthAfterYear: 0, monthNames: LocalizationData.MonthNames, monthNamesShort: LocalizationData.MonthNamesShort, dayNames: LocalizationData.DayNames, dayNamesShort: LocalizationData.DayNamesShort, dayNamesMin: LocalizationData.DayNamesMin, isRTL: LocalizationData.IsRTL }; Options.onSelect = function (DateText, Instance) { var Year = Instance.selectedYear, Month = Instance.selectedMonth + 1, Day = Instance.selectedDay; // Update the three select boxes if (HasDateSelectBoxes) { Element.Year.find('option[value=' + Year + ']').prop('selected', true); Element.Month.find('option[value=' + Month + ']').prop('selected', true); Element.Day.find('option[value=' + Day + ']').prop('selected', true); } else { Element.Year.val(Year); Element.Month.val(LeadingZero(Month)); Element.Day.val(LeadingZero(Day)); } }; Options.beforeShow = function (Input) { $(Input).val(''); return { defaultDate: new Date(Element.Year.val(), Element.Month.val() - 1, Element.Day.val()) }; }; $DatepickerElement.datepicker(Options); // Add some DOM notes to the datepicker, but only if it was not initialized previously. // Check if one additional DOM node is already present. if (!$('#' + Core.App.EscapeSelector(Element.Day.attr('id')) + 'DatepickerIcon').length) { // add datepicker icon and click event $DatepickerElement.after('<a href="#" class="DatepickerIcon" id="' + Element.Day.attr('id') + 'DatepickerIcon" title="' + LocalizationData.IconText + '"><i class="fa fa-calendar"></i></a>'); if (Element.DateInFuture) { ErrorMessage = Core.Config.Get('Datepicker.ErrorMessageDateInFuture'); } else if (Element.DateNotInFuture) { ErrorMessage = Core.Config.Get('Datepicker.ErrorMessageDateNotInFuture'); } else { ErrorMessage = Core.Config.Get('Datepicker.ErrorMessage'); } // Add validation error messages for all dateselection elements Element.Year .after('<div id="' + Element.Day.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>') .after('<div id="' + Element.Month.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>') .after('<div id="' + Element.Year.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>'); // only insert time element error messages if time elements are present if (Element.Hour && Element.Hour.length) { Element.Hour .after('<div id="' + Element.Hour.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>') .after('<div id="' + Element.Minute.attr('id') + 'Error" class="TooltipErrorMessage"><p>' + ErrorMessage + '</p></div>'); } } $('#' + Core.App.EscapeSelector(Element.Day.attr('id')) + 'DatepickerIcon').unbind('click.Datepicker').bind('click.Datepicker', function () { $DatepickerElement.datepicker('show'); return false; }); // do not show the datepicker container div. $('#ui-datepicker-div').hide(); }; return TargetNS; }(Core.UI.Datepicker || {}));
nilei/otrs
var/httpd/htdocs/js/Core.UI.Datepicker.js
JavaScript
agpl-3.0
10,316
function initializeDataTable(formId, tableId, storageKey, pageNumber, itemsPerPage, ajaxUrl, columnDefs, extra){ let domTable = $('#' + tableId); let options = { 'createdRow': function (row, data, dataIndex) { let url = ""; if (data['osis_url']) { url = data['osis_url']; } else { url = data['url']; } $(row).attr('data-id', url); $(row).attr('data-value', data['acronym']); }, columnDefs: columnDefs, "stateSave": true, "paging" : false, "ordering" : true, "orderMulti": false, "order": [[1, 'asc']], "serverSide": true, "ajax" : { "url": ajaxUrl, "accepts": { json: 'application/json' }, "type": "GET", "dataSrc": "object_list", "data": function (d){ let querystring = getDataAjaxTable(formId, domTable, d, pageNumber); querystring["paginator_size"] = itemsPerPage; return querystring; }, "traditional": true }, "info" : false, "searching" : false, 'processing': false, "language": { "oAria": { "sSortAscending": gettext("activate to sort column ascending"), "sSortDescending": gettext("activate to sort column descending") } } }; return domTable.DataTable($.extend(true, {}, options, extra)); } function outputAnchorOuterHtml(urlPath, textContent){ const anchor = document.createElement("a"); anchor.setAttribute("href", urlPath); anchor.textContent = textContent; return anchor.outerHTML; }
uclouvain/OSIS-Louvain
base/static/js/osis_datatable.js
JavaScript
agpl-3.0
1,779
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var tb_pathToImage = "images/loadingAnimation.gif"; /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init $(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ $(domChunk).click(function(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; }); } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 $("body","html").css({height: "100%", width: "100%"}); $("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); $("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page $('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = $("a[@rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar'>Cerrar</a></div>"); $("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);} $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } $("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ $("#TB_window").remove(); $("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } $("#TB_next").click(goNext); } document.onkeydown = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } else if(keycode == 190){ // display previous image if(!(TB_NextHTML == "")){ document.onkeydown = ""; goNext(); } } else if(keycode == 188){ // display next image if(!(TB_PrevHTML == "")){ document.onkeydown = ""; goPrev(); } } }; tb_position(); $("#TB_load").remove(); $("#TB_ImageOff").click(tb_remove); $("#TB_window").css({display:"block"}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); $("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Cerrar'>Cerrar</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>"); }else{//iframe modal $("#TB_overlay").unbind(); $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>"); } }else{// not an iframe, ajax if($("#TB_window").css("display") != "block"){ if(params['modal'] != "true"){//ajax no modal $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>Cerrar</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal $("#TB_overlay").unbind(); $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; $("#TB_ajaxContent")[0].scrollTop = 0; $("#TB_ajaxWindowTitle").html(caption); } } $("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ $("#TB_ajaxContent").append($('#' + params['inlineId']).children()); $("#TB_window").unload(function () { $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); $("#TB_load").remove(); $("#TB_window").css({display:"block"}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if($.browser.safari){//safari needs help because it will not fire iframe onload $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } }else{ $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); $("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); $("#TB_window").css({display:"block"}); }); } } if(!params['modal']){ document.onkeyup = function(e){ if (e == null) { // ie keycode = event.keyCode; } else { // mozilla keycode = e.which; } if(keycode == 27){ // close tb_remove(); } }; } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ $("#TB_load").remove(); $("#TB_window").css({display:"block"}); } function tb_remove() { $("#TB_imageOff").unbind("click"); $("#TB_closeWindowButton").unbind("click"); $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}); $("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 $("body","html").css({height: "auto", width: "auto"}); $("html").css("overflow",""); } document.onkeydown = ""; document.onkeyup = ""; return false; } function tb_position() { $("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6 $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
manuchis/10.000-ideas
admin/js/jquery.thickbox.js
JavaScript
agpl-3.0
11,601
// // Copyright (C) 2017 - present Instructure, Inc. // // This file is part of Canvas. // // Canvas is free software: you can redistribute it and/or modify it under // the terms of the GNU Affero General Public License as published by the Free // Software Foundation, version 3 of the License. // // Canvas is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR // A PARTICULAR PURPOSE. See the GNU Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. import $ from 'jquery' import I18n from 'i18n!broken_images' export function attachErrorHandler(imgElement) { $(imgElement).on('error', e => { if (e.currentTarget.src) { $.get(e.currentTarget.src).fail(response => { if (response.status === 403) { // Replace the image with a lock image $(e.currentTarget).attr({ src: '/images/svg-icons/icon_lock.svg', alt: I18n.t('Locked image'), width: 100, height: 100 }) } else { // Add the broken-image class $(e.currentTarget).addClass('broken-image') } }) } else { // Add the broken-image class (if there is no source) $(e.currentTarget).addClass('broken-image') } }) } export function getImagesAndAttach() { Array.from(document.querySelectorAll('img:not([src=""])')).forEach(attachErrorHandler) } // this behavior will set up all broken images on the page with an error handler that // can apply the broken-image class if there is an error loading the image. $(document).ready(() => getImagesAndAttach())
djbender/canvas-lms
app/coffeescripts/behaviors/broken-images.js
JavaScript
agpl-3.0
1,809
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.ui.form.on("Supplier", { before_load: function(frm) { frappe.setup_language_field(frm); }, refresh: function(frm) { if(frappe.defaults.get_default("supp_master_name")!="Naming Series") { frm.toggle_display("naming_series", false); } else { erpnext.toggle_naming_series(); } if(frm.doc.__islocal){ hide_field(['address_html','contact_html']); erpnext.utils.clear_address_and_contact(frm); } else { unhide_field(['address_html','contact_html']); erpnext.utils.render_address_and_contact(frm); } }, }); cur_frm.fields_dict['default_price_list'].get_query = function(doc, cdt, cdn) { return{ filters:{'buying': 1} } } cur_frm.fields_dict['accounts'].grid.get_field('account').get_query = function(doc, cdt, cdn) { var d = locals[cdt][cdn]; return { filters: { 'account_type': 'Payable', 'company': d.company, "is_group": 0 } } }
anandpdoshi/erpnext
erpnext/buying/doctype/supplier/supplier.js
JavaScript
agpl-3.0
1,029
/* * Javascript terminal * * Copyright (c) 2011 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ "use strict"; function Term(width, height, handler) { this.w = width; this.h = height; this.cur_h = height; /* current height of the scroll back buffer */ this.tot_h = 1000; /* total height of the scroll back buffer */ this.y_base = 0; /* position of the current top screen line in the * scroll back buffer */ this.y_disp = 0; /* position of the top displayed line in the * scroll back buffer */ /* cursor position */ this.x = 0; this.y = 0; this.cursorstate = 0; this.handler = handler; this.convert_lf_to_crlf = false; this.state = 0; this.output_queue = ""; this.bg_colors = [ "#000000", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff", "#00ffff", "#ffffff" ]; this.fg_colors = [ "#000000", "#ff0000", "#00ff00", "#ffff00", "#0000ff", "#ff00ff", "#00ffff", "#ffffff" ]; this.def_attr = (7 << 3) | 0; this.cur_attr = this.def_attr; this.is_mac = (navigator.userAgent.indexOf("Mac") >=0 ) ? true : false; this.key_rep_state = 0; this.key_rep_str = ""; } Term.prototype.open = function() { var y, line, i, term, c; /* set initial content */ this.lines = new Array(); c = 32 | (this.def_attr << 16); for(y = 0; y < this.cur_h;y++) { line = new Array(); for(i=0;i<this.w;i++) line[i] = c; this.lines[y] = line; } /* create terminal window */ document.writeln('<table border="0" cellspacing="0" cellpadding="0">'); for(y=0;y<this.h;y++) { document.writeln('<tr><td class="term" id="tline' + y + '"></td></tr>'); } document.writeln('</table>'); this.refresh(0, this.h - 1); // key handler document.addEventListener("keydown", this.keyDownHandler.bind(this), true); document.addEventListener("keypress", this.keyPressHandler.bind(this), true); // cursor blinking term = this; setInterval(function() { term.cursor_timer_cb(); }, 1000); }; Term.prototype.refresh = function(ymin, ymax) { var el, y, line, outline, c, w, i, cx, attr, last_attr, fg, bg, y1; for(y = ymin; y <= ymax; y++) { /* convert to HTML string */ y1 = y + this.y_disp; if (y1 >= this.cur_h) y1 -= this.cur_h; line = this.lines[y1]; outline = ""; w = this.w; if (y == this.y && this.cursor_state && this.y_disp == this.y_base) { cx = this.x; } else { cx = -1; } last_attr = this.def_attr; for(i = 0; i < w; i++) { c = line[i]; attr = c >> 16; c &= 0xffff; if (i == cx) { attr = -1; /* cursor */ } if (attr != last_attr) { if (last_attr != this.def_attr) outline += '</span>'; if (attr != this.def_attr) { if (attr == -1) { /* cursor */ outline += '<span class="termReverse">'; } else { outline += '<span style="'; fg = (attr >> 3) & 7; bg = attr & 7; if (fg != 7) { outline += 'color:' + this.fg_colors[fg] + ';'; } if (bg != 0) { outline += 'background-color:' + this.bg_colors[bg] + ';'; } outline += '">'; } } } switch(c) { case 32: outline += "&nbsp;"; break; case 38: // '&' outline += "&amp;"; break; case 60: // '<' outline += "&lt;"; break; case 62: // '>' outline += "&gt;"; break; default: if (c < 32) { outline += "&nbsp;"; } else { outline += String.fromCharCode(c); } break; } last_attr = attr; } if (last_attr != this.def_attr) { outline += '</span>'; } el = document.getElementById("tline" + y); el.innerHTML = outline; } }; Term.prototype.cursor_timer_cb = function() { this.cursor_state ^= 1; this.refresh(this.y, this.y); }; Term.prototype.show_cursor = function() { if (!this.cursor_state) { this.cursor_state = 1; this.refresh(this.y, this.y); } }; Term.prototype.scroll = function() { var y, line, x, c, y1; /* increase height of buffer if possible */ if (this.cur_h < this.tot_h) { this.cur_h++; } /* move down one line */ if (++this.y_base == this.cur_h) this.y_base = 0; this.y_disp = this.y_base; c = 32 | (this.def_attr << 16); line = new Array(); for(x=0;x<this.w;x++) line[x] = c; y1 = this.y_base + this.h - 1; if (y1 >= this.cur_h) y1 -= this.cur_h; this.lines[y1] = line; }; /* scroll down or up in the scroll back buffer by n lines */ Term.prototype.scroll_disp = function(n) { var i, y1; /* slow but it does not really matters */ if (n >= 0) { for(i = 0; i < n; i++) { if (this.y_disp == this.y_base) break; if (++this.y_disp == this.cur_h) this.y_disp = 0; } } else { n = -n; y1 = this.y_base + this.h; if (y1 >= this.cur_h) y1 -= this.cur_h; for(i = 0; i < n; i++) { if (this.y_disp == y1) break; if (--this.y_disp < 0) this.y_disp = this.cur_h - 1; } } this.refresh(0, this.h - 1); }; Term.prototype.write = function(str) { function update(y) { ymin = Math.min(ymin, y); ymax = Math.max(ymax, y); } function erase_to_eol(s, x, y) { var l, i, c, y1; y1 = s.y_base + y; if (y1 >= s.cur_h) y1 -= s.cur_h; l = s.lines[y1]; c = 32 | (s.def_attr << 16); for(i = x; i < s.w; i++) l[i] = c; update(y); } function csi_colors(s, esc_params) { var j, n; if (esc_params.length == 0) { s.cur_attr= s.def_attr; } else { for(j = 0; j < esc_params.length; j++) { n = esc_params[j]; if (n >= 30 && n <= 37) { /* foreground */ s.cur_attr = (s.cur_attr & ~(7 << 3)) | ((n - 30) << 3); } else if (n >= 40 && n <= 47) { /* background */ s.cur_attr = (s.cur_attr & ~7) | (n - 40); } else if (n == 0) { /* default attr */ s.cur_attr = s.def_attr; } } } } var TTY_STATE_NORM = 0; var TTY_STATE_ESC = 1; var TTY_STATE_CSI = 2; var i, c, ymin, ymax, l, n, j, y1; /* update region is in ymin ymax */ ymin = this.h; ymax = -1; update(this.y); // remove the cursor /* reset top of displayed screen to top of real screen */ if (this.y_base != this.y_disp) { this.y_disp = this.y_base; /* force redraw */ ymin = 0; ymax = this.h - 1; } for(i = 0; i < str.length; i++) { c = str.charCodeAt(i); switch(this.state) { case TTY_STATE_NORM: switch(c) { case 10: if (this.convert_lf_to_crlf) { this.x = 0; // emulates '\r' } this.y++; if (this.y >= this.h) { this.y--; this.scroll(); ymin = 0; ymax = this.h - 1; } break; case 13: this.x = 0; break; case 8: if (this.x > 0) { this.x--; } break; case 9: /* tab */ n = (this.x + 8) & ~7; if (n <= this.w) { this.x = n; } break; case 27: this.state = TTY_STATE_ESC; break; default: if (c >= 32) { if (this.x >= this.w) { this.x = 0; this.y++; if (this.y >= this.h) { this.y--; this.scroll(); ymin = 0; ymax = this.h - 1; } } y1 = this.y + this.y_base; if (y1 >= this.cur_h) y1 -= this.cur_h; this.lines[y1][this.x] = (c & 0xffff) | (this.cur_attr << 16); this.x++; update(this.y); } break; } break; case TTY_STATE_ESC: if (c == 91) { // '[' this.esc_params = new Array(); this.cur_param = 0; this.state = TTY_STATE_CSI; } else { this.state = TTY_STATE_NORM; } break; case TTY_STATE_CSI: if (c >= 48 && c <= 57) { // '0' '9' /* numeric */ this.cur_param = this.cur_param * 10 + c - 48; } else { /* add parsed parameter */ this.esc_params[this.esc_params.length] = this.cur_param; this.cur_param = 0; if (c == 59) // ; break; this.state = TTY_STATE_NORM; // console.log("term: csi=" + this.esc_params + " cmd="+c); switch(c) { case 65: // 'A' up n = this.esc_params[0]; if (n < 1) n = 1; this.y -= n; if (this.y < 0) this.y = 0; break; case 66: // 'B' down n = this.esc_params[0]; if (n < 1) n = 1; this.y += n; if (this.y >= this.h) this.y = this.h - 1; break; case 67: // 'C' right n = this.esc_params[0]; if (n < 1) n = 1; this.x += n; if (this.x >= this.w - 1) this.x = this.w - 1; break; case 68: // 'D' left n = this.esc_params[0]; if (n < 1) n = 1; this.x -= n; if (this.x < 0) this.x = 0; break; case 72: // 'H' goto xy { var x1, y1; y1 = this.esc_params[0] - 1; if (this.esc_params.length >= 2) x1 = this.esc_params[1] - 1; else x1 = 0; if (y1 < 0) y1 = 0; else if (y1 >= this.h) y1 = this.h - 1; if (x1 < 0) x1 = 0; else if (x1 >= this.w) x1 = this.w - 1; this.x = x1; this.y = y1; } break; case 74: // 'J' erase to end of screen erase_to_eol(this, this.x, this.y); for(j = this.y + 1; j < this.h; j++) erase_to_eol(this, 0, j); break; case 75: // 'K' erase to end of line erase_to_eol(this, this.x, this.y); break; case 109: // 'm': set color csi_colors(this, this.esc_params); break; case 110: // 'n' return the cursor position this.queue_chars("\x1b[" + (this.y + 1) + ";" + (this.x + 1) + "R"); break; default: break; } } break; } } update(this.y); // show the cursor if (ymax >= ymin) this.refresh(ymin, ymax); }; Term.prototype.writeln = function (str) { this.write(str + '\r\n'); }; Term.prototype.keyDownHandler = function (ev) { var str; str=""; switch(ev.keyCode) { case 8: /* backspace */ str = "\x7f"; break; case 9: /* tab */ str = "\x09"; break; case 13: /* enter */ str = "\x0d"; break; case 27: /* escape */ str = "\x1b"; break; case 37: /* left */ str = "\x1b[D"; break; case 39: /* right */ str = "\x1b[C"; break; case 38: /* up */ if (ev.ctrlKey) { this.scroll_disp(-1); } else { str = "\x1b[A"; } break; case 40: /* down */ if (ev.ctrlKey) { this.scroll_disp(1); } else { str = "\x1b[B"; } break; case 46: /* delete */ str = "\x1b[3~"; break; case 45: /* insert */ str = "\x1b[2~"; break; case 36: /* home */ str = "\x1bOH"; break; case 35: /* end */ str = "\x1bOF"; break; case 33: /* page up */ if (ev.ctrlKey) { this.scroll_disp(-(this.h - 1)); } else { str = "\x1b[5~"; } break; case 34: /* page down */ if (ev.ctrlKey) { this.scroll_disp(this.h - 1); } else { str = "\x1b[6~"; } break; default: if (ev.ctrlKey) { /* ctrl + key */ if (ev.keyCode >= 65 && ev.keyCode <= 90) { str = String.fromCharCode(ev.keyCode - 64); } else if (ev.keyCode == 32) { str = String.fromCharCode(0); } } else if ((!this.is_mac && ev.altKey) || (this.is_mac && ev.metaKey)) { /* meta + key (Note: we only send lower case) */ if (ev.keyCode >= 65 && ev.keyCode <= 90) { str = "\x1b" + String.fromCharCode(ev.keyCode + 32); } } break; } // console.log("keydown: keycode=" + ev.keyCode + " charcode=" + ev.charCode + " str=" + str + " ctrl=" + ev.ctrlKey + " alt=" + ev.altKey + " meta=" + ev.metaKey); if (str) { if (ev.stopPropagation) ev.stopPropagation(); if (ev.preventDefault) ev.preventDefault(); this.show_cursor(); this.key_rep_state = 1; this.key_rep_str = str; this.handler(str); return false; } else { this.key_rep_state = 0; return true; } }; Term.prototype.keyPressHandler = function (ev) { var str, char_code; if (ev.stopPropagation) ev.stopPropagation(); if (ev.preventDefault) ev.preventDefault(); str=""; if (!("charCode" in ev)) { /* on Opera charCode is not defined and keypress is sent for system keys. Moreover, only keupress is repeated which is a problem for system keys. */ char_code = ev.keyCode; if (this.key_rep_state == 1) { this.key_rep_state = 2; return false; } else if (this.key_rep_state == 2) { /* repetition */ this.show_cursor(); this.handler(this.key_rep_str); return false; } } else { char_code = ev.charCode; } if (char_code != 0) { if (!ev.ctrlKey && ((!this.is_mac && !ev.altKey) || (this.is_mac && !ev.metaKey))) { str = String.fromCharCode(char_code); } } // console.log("keypress: keycode=" + ev.keyCode + " charcode=" + ev.charCode + " str=" + str + " ctrl=" + ev.ctrlKey + " alt=" + ev.altKey + " meta=" + ev.metaKey); if (str) { this.show_cursor(); this.handler(str); return false; } else { return true; } }; /* output queue to send back asynchronous responses */ Term.prototype.queue_chars = function (str) { this.output_queue += str; if (this.output_queue) setTimeout(this.outputHandler.bind(this), 0); }; Term.prototype.outputHandler = function () { if (this.output_queue) { this.handler(this.output_queue); this.output_queue = ""; } };
ubercomp/jslm32
third_party/bellard/term.js
JavaScript
lgpl-2.1
18,674
YUI.add('event-simulate', function (Y, NAME) { (function() { /** * Simulate user interaction by generating native DOM events. * * @module event-simulate * @requires event */ //shortcuts var L = Y.Lang, isFunction = L.isFunction, isString = L.isString, isBoolean = L.isBoolean, isObject = L.isObject, isNumber = L.isNumber, //mouse events supported mouseEvents = { click: 1, dblclick: 1, mouseover: 1, mouseout: 1, mousedown: 1, mouseup: 1, mousemove: 1, contextmenu:1 }, msPointerEvents = { MSPointerOver: 1, MSPointerOut: 1, MSPointerDown: 1, MSPointerUp: 1, MSPointerMove: 1 }, //key events supported keyEvents = { keydown: 1, keyup: 1, keypress: 1 }, //HTML events supported uiEvents = { submit: 1, blur: 1, change: 1, focus: 1, resize: 1, scroll: 1, select: 1 }, //events that bubble by default bubbleEvents = { scroll: 1, resize: 1, reset: 1, submit: 1, change: 1, select: 1, error: 1, abort: 1 }, //touch events supported touchEvents = { touchstart: 1, touchmove: 1, touchend: 1, touchcancel: 1 }, gestureEvents = { gesturestart: 1, gesturechange: 1, gestureend: 1 }; //all key, mouse and touch events bubble Y.mix(bubbleEvents, mouseEvents); Y.mix(bubbleEvents, keyEvents); Y.mix(bubbleEvents, touchEvents); /* * Note: Intentionally not for YUIDoc generation. * Simulates a key event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. Note: keydown causes Safari 2.x to * crash. * @method simulateKeyEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: keyup, keydown, and keypress. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 3 specifies that all key events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 3 specifies that all * key events can be cancelled. The default * is true. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {int} keyCode (Optional) The code for the key that is in use. * The default is 0. * @param {int} charCode (Optional) The Unicode code for the character * associated with the key being used. The default is 0. */ function simulateKeyEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, ctrlKey /*:Boolean*/, altKey /*:Boolean*/, shiftKey /*:Boolean*/, metaKey /*:Boolean*/, keyCode /*:int*/, charCode /*:int*/) /*:Void*/ { //check target if (!target){ Y.error("simulateKeyEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); switch(type){ case "textevent": //DOM Level 3 type = "keypress"; break; case "keyup": case "keydown": case "keypress": break; default: Y.error("simulateKeyEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateKeyEvent(): Event type must be a string."); } //setup default values if (!isBoolean(bubbles)){ bubbles = true; //all key events bubble } if (!isBoolean(cancelable)){ cancelable = true; //all key events can be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isBoolean(ctrlKey)){ ctrlKey = false; } if (!isBoolean(altKey)){ altKey = false; } if (!isBoolean(shiftKey)){ shiftKey = false; } if (!isBoolean(metaKey)){ metaKey = false; } if (!isNumber(keyCode)){ keyCode = 0; } if (!isNumber(charCode)){ charCode = 0; } //try to create a mouse event var customEvent /*:MouseEvent*/ = null; //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ try { //try to create key event customEvent = Y.config.doc.createEvent("KeyEvents"); /* * Interesting problem: Firefox implemented a non-standard * version of initKeyEvent() based on DOM Level 2 specs. * Key event was removed from DOM Level 2 and re-introduced * in DOM Level 3 with a different interface. Firefox is the * only browser with any implementation of Key Events, so for * now, assume it's Firefox if the above line doesn't error. */ // @TODO: Decipher between Firefox's implementation and a correct one. customEvent.initKeyEvent(type, bubbles, cancelable, view, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode); } catch (ex /*:Error*/){ /* * If it got here, that means key events aren't officially supported. * Safari/WebKit is a real problem now. WebKit 522 won't let you * set keyCode, charCode, or other properties if you use a * UIEvent, so we first must try to create a generic event. The * fun part is that this will throw an error on Safari 2.x. The * end result is that we need another try...catch statement just to * deal with this mess. */ try { //try to create generic event - will fail in Safari 2.x customEvent = Y.config.doc.createEvent("Events"); } catch (uierror /*:Error*/){ //the above failed, so create a UIEvent for Safari 2.x customEvent = Y.config.doc.createEvent("UIEvents"); } finally { customEvent.initEvent(type, bubbles, cancelable); //initialize customEvent.view = view; customEvent.altKey = altKey; customEvent.ctrlKey = ctrlKey; customEvent.shiftKey = shiftKey; customEvent.metaKey = metaKey; customEvent.keyCode = keyCode; customEvent.charCode = charCode; } } //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.shiftKey = shiftKey; customEvent.metaKey = metaKey; /* * IE doesn't support charCode explicitly. CharCode should * take precedence over any keyCode value for accurate * representation. */ customEvent.keyCode = (charCode > 0) ? charCode : keyCode; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateKeyEvent(): No event simulation framework present."); } } /* * Note: Intentionally not for YUIDoc generation. * Simulates a mouse event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. * @method simulateMouseEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: click, dblclick, mousedown, mouseup, mouseout, * mouseover, and mousemove. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * mouse events except mousemove can be cancelled. The default * is true for all events except mousemove, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) The number of times the mouse button has * been used. The default value is 1. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {int} button (Optional) The button being pressed while the event * is executing. The value should be 0 for the primary mouse button * (typically the left button), 1 for the terciary mouse button * (typically the middle button), and 2 for the secondary mouse button * (typically the right button). The default is 0. * @param {HTMLElement} relatedTarget (Optional) For mouseout events, * this is the element that the mouse has moved to. For mouseover * events, this is the element that the mouse has moved from. This * argument is ignored for all other events. The default is null. */ function simulateMouseEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, detail /*:int*/, screenX /*:int*/, screenY /*:int*/, clientX /*:int*/, clientY /*:int*/, ctrlKey /*:Boolean*/, altKey /*:Boolean*/, shiftKey /*:Boolean*/, metaKey /*:Boolean*/, button /*:int*/, relatedTarget /*:HTMLElement*/) /*:Void*/ { //check target if (!target){ Y.error("simulateMouseEvent(): Invalid target."); } if (isString(type)){ //make sure it's a supported mouse event or an msPointerEvent. if (!mouseEvents[type.toLowerCase()] && !msPointerEvents[type]){ Y.error("simulateMouseEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateMouseEvent(): Event type must be a string."); } //setup default values if (!isBoolean(bubbles)){ bubbles = true; //all mouse events bubble } if (!isBoolean(cancelable)){ cancelable = (type !== "mousemove"); //mousemove is the only one that can't be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isNumber(detail)){ detail = 1; //number of mouse clicks must be at least one } if (!isNumber(screenX)){ screenX = 0; } if (!isNumber(screenY)){ screenY = 0; } if (!isNumber(clientX)){ clientX = 0; } if (!isNumber(clientY)){ clientY = 0; } if (!isBoolean(ctrlKey)){ ctrlKey = false; } if (!isBoolean(altKey)){ altKey = false; } if (!isBoolean(shiftKey)){ shiftKey = false; } if (!isBoolean(metaKey)){ metaKey = false; } if (!isNumber(button)){ button = 0; } relatedTarget = relatedTarget || null; //try to create a mouse event var customEvent /*:MouseEvent*/ = null; //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ customEvent = Y.config.doc.createEvent("MouseEvents"); //Safari 2.x (WebKit 418) still doesn't implement initMouseEvent() if (customEvent.initMouseEvent){ customEvent.initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget); } else { //Safari //the closest thing available in Safari 2.x is UIEvents customEvent = Y.config.doc.createEvent("UIEvents"); customEvent.initEvent(type, bubbles, cancelable); customEvent.view = view; customEvent.detail = detail; customEvent.screenX = screenX; customEvent.screenY = screenY; customEvent.clientX = clientX; customEvent.clientY = clientY; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.metaKey = metaKey; customEvent.shiftKey = shiftKey; customEvent.button = button; customEvent.relatedTarget = relatedTarget; } /* * Check to see if relatedTarget has been assigned. Firefox * versions less than 2.0 don't allow it to be assigned via * initMouseEvent() and the property is readonly after event * creation, so in order to keep YAHOO.util.getRelatedTarget() * working, assign to the IE proprietary toElement property * for mouseout event and fromElement property for mouseover * event. */ if (relatedTarget && !customEvent.relatedTarget){ if (type === "mouseout"){ customEvent.toElement = relatedTarget; } else if (type === "mouseover"){ customEvent.fromElement = relatedTarget; } } //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.detail = detail; customEvent.screenX = screenX; customEvent.screenY = screenY; customEvent.clientX = clientX; customEvent.clientY = clientY; customEvent.ctrlKey = ctrlKey; customEvent.altKey = altKey; customEvent.metaKey = metaKey; customEvent.shiftKey = shiftKey; //fix button property for IE's wacky implementation switch(button){ case 0: customEvent.button = 1; break; case 1: customEvent.button = 4; break; case 2: //leave as is break; default: customEvent.button = 0; } /* * Have to use relatedTarget because IE won't allow assignment * to toElement or fromElement on generic events. This keeps * YAHOO.util.customEvent.getRelatedTarget() functional. */ customEvent.relatedTarget = relatedTarget; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateMouseEvent(): No event simulation framework present."); } } /* * Note: Intentionally not for YUIDoc generation. * Simulates a UI event using the given event information to populate * the generated event object. This method does browser-equalizing * calculations to account for differences in the DOM and IE event models * as well as different browser quirks. * @method simulateHTMLEvent * @private * @static * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: click, dblclick, mousedown, mouseup, mouseout, * mouseover, and mousemove. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * mouse events except mousemove can be cancelled. The default * is true for all events except mousemove, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) The number of times the mouse button has * been used. The default value is 1. */ function simulateUIEvent(target /*:HTMLElement*/, type /*:String*/, bubbles /*:Boolean*/, cancelable /*:Boolean*/, view /*:Window*/, detail /*:int*/) /*:Void*/ { //check target if (!target){ Y.error("simulateUIEvent(): Invalid target."); } //check event type if (isString(type)){ type = type.toLowerCase(); //make sure it's a supported mouse event if (!uiEvents[type]){ Y.error("simulateUIEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateUIEvent(): Event type must be a string."); } //try to create a mouse event var customEvent = null; //setup default values if (!isBoolean(bubbles)){ bubbles = (type in bubbleEvents); //not all events bubble } if (!isBoolean(cancelable)){ cancelable = (type === "submit"); //submit is the only one that can be cancelled } if (!isObject(view)){ view = Y.config.win; //view is typically window } if (!isNumber(detail)){ detail = 1; //usually not used but defaulted to this } //check for DOM-compliant browsers first if (isFunction(Y.config.doc.createEvent)){ //just a generic UI Event object is needed customEvent = Y.config.doc.createEvent("UIEvents"); customEvent.initUIEvent(type, bubbles, cancelable, view, detail); //fire the event target.dispatchEvent(customEvent); } else if (isObject(Y.config.doc.createEventObject)){ //IE //create an IE event object customEvent = Y.config.doc.createEventObject(); //assign available properties customEvent.bubbles = bubbles; customEvent.cancelable = cancelable; customEvent.view = view; customEvent.detail = detail; //fire the event target.fireEvent("on" + type, customEvent); } else { Y.error("simulateUIEvent(): No event simulation framework present."); } } /* * (iOS only) This is for creating native DOM gesture events which only iOS * v2.0+ is supporting. * * @method simulateGestureEvent * @private * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: touchstart, touchmove, touchend, touchcancel. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * touch events except touchcancel can be cancelled. The default * is true for all events except touchcancel, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) Specifies some detail information about * the event depending on the type of event. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {float} scale (iOS v2+ only) The distance between two fingers * since the start of an event as a multiplier of the initial distance. * The default value is 1.0. * @param {float} rotation (iOS v2+ only) The delta rotation since the start * of an event, in degrees, where clockwise is positive and * counter-clockwise is negative. The default value is 0.0. */ function simulateGestureEvent(target, type, bubbles, // boolean cancelable, // boolean view, // DOMWindow detail, // long screenX, screenY, // long clientX, clientY, // long ctrlKey, altKey, shiftKey, metaKey, // boolean scale, // float rotation // float ) { var customEvent; if(!Y.UA.ios || Y.UA.ios<2.0) { Y.error("simulateGestureEvent(): Native gesture DOM eventframe is not available in this platform."); } // check taget if (!target){ Y.error("simulateGestureEvent(): Invalid target."); } //check event type if (Y.Lang.isString(type)) { type = type.toLowerCase(); //make sure it's a supported touch event if (!gestureEvents[type]){ Y.error("simulateTouchEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateGestureEvent(): Event type must be a string."); } // setup default values if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default if (!Y.Lang.isBoolean(cancelable)) { cancelable = true; } if (!Y.Lang.isObject(view)) { view = Y.config.win; } if (!Y.Lang.isNumber(detail)) { detail = 2; } // usually not used. if (!Y.Lang.isNumber(screenX)) { screenX = 0; } if (!Y.Lang.isNumber(screenY)) { screenY = 0; } if (!Y.Lang.isNumber(clientX)) { clientX = 0; } if (!Y.Lang.isNumber(clientY)) { clientY = 0; } if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; } if (!Y.Lang.isBoolean(altKey)) { altKey = false; } if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; } if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; } if (!Y.Lang.isNumber(scale)){ scale = 1.0; } if (!Y.Lang.isNumber(rotation)){ rotation = 0.0; } customEvent = Y.config.doc.createEvent("GestureEvent"); customEvent.initGestureEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, target, scale, rotation); target.dispatchEvent(customEvent); } /* * @method simulateTouchEvent * @private * @param {HTMLElement} target The target of the given event. * @param {String} type The type of event to fire. This can be any one of * the following: touchstart, touchmove, touchend, touchcancel. * @param {Boolean} bubbles (Optional) Indicates if the event can be * bubbled up. DOM Level 2 specifies that all mouse events bubble by * default. The default is true. * @param {Boolean} cancelable (Optional) Indicates if the event can be * canceled using preventDefault(). DOM Level 2 specifies that all * touch events except touchcancel can be cancelled. The default * is true for all events except touchcancel, for which the default * is false. * @param {Window} view (Optional) The view containing the target. This is * typically the window object. The default is window. * @param {int} detail (Optional) Specifies some detail information about * the event depending on the type of event. * @param {int} screenX (Optional) The x-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} screenY (Optional) The y-coordinate on the screen at which * point the event occured. The default is 0. * @param {int} clientX (Optional) The x-coordinate on the client at which * point the event occured. The default is 0. * @param {int} clientY (Optional) The y-coordinate on the client at which * point the event occured. The default is 0. * @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys * is pressed while the event is firing. The default is false. * @param {Boolean} altKey (Optional) Indicates if one of the ALT keys * is pressed while the event is firing. The default is false. * @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys * is pressed while the event is firing. The default is false. * @param {Boolean} metaKey (Optional) Indicates if one of the META keys * is pressed while the event is firing. The default is false. * @param {TouchList} touches A collection of Touch objects representing * all touches associated with this event. * @param {TouchList} targetTouches A collection of Touch objects * representing all touches associated with this target. * @param {TouchList} changedTouches A collection of Touch objects * representing all touches that changed in this event. * @param {float} scale (iOS v2+ only) The distance between two fingers * since the start of an event as a multiplier of the initial distance. * The default value is 1.0. * @param {float} rotation (iOS v2+ only) The delta rotation since the start * of an event, in degrees, where clockwise is positive and * counter-clockwise is negative. The default value is 0.0. */ function simulateTouchEvent(target, type, bubbles, // boolean cancelable, // boolean view, // DOMWindow detail, // long screenX, screenY, // long clientX, clientY, // long ctrlKey, altKey, shiftKey, metaKey, // boolean touches, // TouchList targetTouches, // TouchList changedTouches, // TouchList scale, // float rotation // float ) { var customEvent; // check taget if (!target){ Y.error("simulateTouchEvent(): Invalid target."); } //check event type if (Y.Lang.isString(type)) { type = type.toLowerCase(); //make sure it's a supported touch event if (!touchEvents[type]){ Y.error("simulateTouchEvent(): Event type '" + type + "' not supported."); } } else { Y.error("simulateTouchEvent(): Event type must be a string."); } // note that the caller is responsible to pass appropriate touch objects. // check touch objects // Android(even 4.0) doesn't define TouchList yet /*if(type === 'touchstart' || type === 'touchmove') { if(!touches instanceof TouchList) { Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList'); } else { if(touches.length === 0) { Y.error('simulateTouchEvent(): No touch object found.'); } } } else if(type === 'touchend') { if(!changedTouches instanceof TouchList) { Y.error('simulateTouchEvent(): Invalid touches. It must be a TouchList'); } else { if(changedTouches.length === 0) { Y.error('simulateTouchEvent(): No touch object found.'); } } }*/ if(type === 'touchstart' || type === 'touchmove') { if(touches.length === 0) { Y.error('simulateTouchEvent(): No touch object in touches'); } } else if(type === 'touchend') { if(changedTouches.length === 0) { Y.error('simulateTouchEvent(): No touch object in changedTouches'); } } // setup default values if (!Y.Lang.isBoolean(bubbles)) { bubbles = true; } // bubble by default. if (!Y.Lang.isBoolean(cancelable)) { cancelable = (type !== "touchcancel"); // touchcancel is not cancelled } if (!Y.Lang.isObject(view)) { view = Y.config.win; } if (!Y.Lang.isNumber(detail)) { detail = 1; } // usually not used. defaulted to # of touch objects. if (!Y.Lang.isNumber(screenX)) { screenX = 0; } if (!Y.Lang.isNumber(screenY)) { screenY = 0; } if (!Y.Lang.isNumber(clientX)) { clientX = 0; } if (!Y.Lang.isNumber(clientY)) { clientY = 0; } if (!Y.Lang.isBoolean(ctrlKey)) { ctrlKey = false; } if (!Y.Lang.isBoolean(altKey)) { altKey = false; } if (!Y.Lang.isBoolean(shiftKey)){ shiftKey = false; } if (!Y.Lang.isBoolean(metaKey)) { metaKey = false; } if (!Y.Lang.isNumber(scale)) { scale = 1.0; } if (!Y.Lang.isNumber(rotation)) { rotation = 0.0; } //check for DOM-compliant browsers first if (Y.Lang.isFunction(Y.config.doc.createEvent)) { if (Y.UA.android) { /* * Couldn't find android start version that supports touch event. * Assumed supported(btw APIs broken till icecream sandwitch) * from the beginning. */ if(Y.UA.android < 4.0) { /* * Touch APIs are broken in androids older than 4.0. We will use * simulated touch apis for these versions. * App developer still can listen for touch events. This events * will be dispatched with touch event types. * * (Note) Used target for the relatedTarget. Need to verify if * it has a side effect. */ customEvent = Y.config.doc.createEvent("MouseEvents"); customEvent.initMouseEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, 0, target); customEvent.touches = touches; customEvent.targetTouches = targetTouches; customEvent.changedTouches = changedTouches; } else { customEvent = Y.config.doc.createEvent("TouchEvent"); // Andoroid isn't compliant W3C initTouchEvent method signature. customEvent.initTouchEvent(touches, targetTouches, changedTouches, type, view, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey); } } else if (Y.UA.ios) { if(Y.UA.ios >= 2.0) { customEvent = Y.config.doc.createEvent("TouchEvent"); // Available iOS 2.0 and later customEvent.initTouchEvent(type, bubbles, cancelable, view, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, touches, targetTouches, changedTouches, scale, rotation); } else { Y.error('simulateTouchEvent(): No touch event simulation framework present for iOS, '+Y.UA.ios+'.'); } } else { Y.error('simulateTouchEvent(): Not supported agent yet, '+Y.UA.userAgent); } //fire the event target.dispatchEvent(customEvent); //} else if (Y.Lang.isObject(doc.createEventObject)){ // Windows Mobile/IE, support later } else { Y.error('simulateTouchEvent(): No event simulation framework present.'); } } /** * Simulates the event or gesture with the given name on a target. * @param {HTMLElement} target The DOM element that's the target of the event. * @param {String} type The type of event or name of the supported gesture to simulate * (i.e., "click", "doubletap", "flick"). * @param {Object} options (Optional) Extra options to copy onto the event object. * For gestures, options are used to refine the gesture behavior. * @return {void} * @for Event * @method simulate * @static */ Y.Event.simulate = function(target, type, options){ options = options || {}; if (mouseEvents[type] || msPointerEvents[type]){ simulateMouseEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, options.relatedTarget); } else if (keyEvents[type]){ simulateKeyEvent(target, type, options.bubbles, options.cancelable, options.view, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode); } else if (uiEvents[type]){ simulateUIEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail); // touch low-level event simulation } else if (touchEvents[type]) { if((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.phantomjs) && !(Y.UA.chrome && Y.UA.chrome < 6)) { simulateTouchEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.touches, options.targetTouches, options.changedTouches, options.scale, options.rotation); } else { Y.error("simulate(): Event '" + type + "' can't be simulated. Use gesture-simulate module instead."); } // ios gesture low-level event simulation (iOS v2+ only) } else if(Y.UA.ios && Y.UA.ios >= 2.0 && gestureEvents[type]) { simulateGestureEvent(target, type, options.bubbles, options.cancelable, options.view, options.detail, options.screenX, options.screenY, options.clientX, options.clientY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.scale, options.rotation); // anything else } else { Y.error("simulate(): Event '" + type + "' can't be simulated."); } }; })(); }, 'patched-v3.11.0', {"requires": ["event-base"]});
FuadEfendi/lpotal
tomcat-7.0.57/webapps/ROOT/html/js/aui/event-simulate/event-simulate.js
JavaScript
lgpl-2.1
37,238
var searchData= [ ['takeoff',['takeOff',['../class_flight_controller.html#a514f2619b98216e9fca0ad876d000966',1,'FlightController']]] ];
cranktec/EasyCopter
documentation/html/search/functions_a.js
JavaScript
lgpl-2.1
138
"use strict"; var Activity = require("./activity"); var util = require("util"); function Falsy() { Activity.call(this); this.value = false; this.is = true; this.isNot = false; } util.inherits(Falsy, Activity); Falsy.prototype.run = function (callContext, args) { callContext.schedule(this.value, "_valueGot"); }; Falsy.prototype._valueGot = function (callContext, reason, result) { if (reason !== Activity.states.complete) { callContext.end(reason, result); return; } if (result) { callContext.schedule(this.isNot, "_done"); } else { callContext.schedule(this.is, "_done"); } }; Falsy.prototype._done = function (callContext, reason, result) { callContext.end(reason, result); }; module.exports = Falsy; //# sourceMappingURL=falsy.js.map
unbornchikken/workflow-4-node
lib/es5/activities/falsy.js
JavaScript
lgpl-3.0
823
var dir_68267d1309a1af8e8297ef4c3efbcdba = [ [ "BeagleGoo.cpp", "_beagle_goo_8cpp.html", [ [ "BeagleGoo", "struct_beagle_goo.html", "struct_beagle_goo" ] ] ], [ "BeagleGooP.cpp", "_beagle_goo_p_8cpp.html", "_beagle_goo_p_8cpp" ], [ "GPIOoo.cpp", "_g_p_i_ooo_8cpp.html", null ], [ "gpiotest.c", "gpiotest_8c.html", "gpiotest_8c" ], [ "HD44780.cpp", "_h_d44780_8cpp.html", null ], [ "HD44780gpioPhy.cpp", "_h_d44780gpio_phy_8cpp.html", "_h_d44780gpio_phy_8cpp" ], [ "SPI.cpp", "_s_p_i_8cpp.html", "_s_p_i_8cpp" ], [ "TLC5946chain.cpp", "_t_l_c5946chain_8cpp.html", null ], [ "TLC5946phy.cpp", "_t_l_c5946phy_8cpp.html", null ], [ "TLC5946PRUSSphy.cpp", "_t_l_c5946_p_r_u_s_sphy_8cpp.html", null ] ];
piranha32/IOoo
doc/doxygen/html/dir_68267d1309a1af8e8297ef4c3efbcdba.js
JavaScript
lgpl-3.0
747
// These are concatenated md5 and sha1 fingerprints for the Firefox and // Microsoft root CAs as of Aug 2010 var root_ca_hashes = { '00531D1D7201D423C820D00B6088C5D143DDB1FFF3B49B73831407F6BC8B975023D07C50' : true, '015A99C3D64FA94B3C3BB1A3AB274CBFFC219A76112F76C1C508833C9A2FA2BA84AC087A' : true, '019408DE857F8D806CE602CA89522848750251B2C632536F9D917279543C137CD721C6E0' : true, '0208EE8CAAB8387A6824DCB4E26A52337E206939CC5FA883635F64C750EBF5FDA9AEE653' : true, '0226C3015E08303743A9D07DCF37E6BF323C118E1BF7B8B65254E2E2100DD6029037F096' : true, '034287D7C1167D18AFA4703CB8312C3E4EF2E6670AC9B5091FE06BE0E5483EAAD6BA32D9' : true, '03DC08EEC4703FFA20E5E179E81AE7C59ED18028FB1E8A9701480A7890A59ACD73DFF871' : true, '044BFDC96CDA2A32857C598461468A64BEB5A995746B9EDF738B56E6DF437A77BE106B81' : true, '0468E9247E41CED76C441630703DDDB9AB16DD144ECDC0FC4BAAB62ECF0408896FDE52B7' : true, '068690F2195471FDDD3DE6EEA161CAFF7030AABF8432A800666CCCC42A887E42B7553E2B' : true, '069F6979166690021B8C8CA2C3076F3A627F8D7827656399D27D7F9044C9FEB3F33EFA9A' : true, '06F0171EB1E961ED7A363CA594A1374AFAAA27B8CAF5FDF5CDA98AC3378572E04CE8F2E0' : true, '06F9EBECCC569D88BA90F5BAB01AE00216D424FE9610E17519AF232BB68774E24144BE6E' : true, '076192047EA6B9CD5E6B007AE3BF1D0434D499426F9FC2BB27B075BAB682AAE5EFFCBA74' : true, '087C581F522B44B43B79CD01F8C5C3C995E6ADF8D77146024DD56A21B2E73FCDF23B35FF' : true, '0B092C1CD721866F94376FE6A7F3224D0409565B77DA582E6495AC0060A72354E64B0192' : true, '0C412F135BA054F596662D7ECD0E03F4DA79C1711150C23439AA2B0B0C62FD55B2F9F580' : true, '0C5ADD5AAE29F7A77679FA4151FEF035B865130BEDCA38D27F69929420770BED86EFBC10' : true, '0C7FDD6AF42AB9C89BBD207EA9DB5C3760D68974B5C2659E8A0FC1887C88D246691B182C' : true, '0CF89E17FCD403BDE68D9B3C0587FE8433A335C23CE8034B04E13DE5C48E791AEB8C3204' : true, '0E40A76CDE035D8FD10FE4D18DF96CA9A9E9780814375888F20519B06D2B0D2B6016907D' : true, '0EFA4BF7D760CD65F7A7068857986239D29F6C98BEFC6D986521543EE8BE56CEBC288CF3' : true, '0FA01300C3558AB7D37E2D04739EDE3C8B1A1106B8E26B232980FD652E6181376441FD11' : true, '100EADF35C841D8E035F2DC93937F552742CDF1594049CBF17A2046CC639BB3888E02E33' : true, '10FC635DF6263E0DF325BE5F79CD6767742C3192E607E424EB4549542BE1BBC53E6174E2' : true, '119279403CB18340E5AB664A679280DFA9628F4B98A91B4835BAD2C1463286BB66646A8C' : true, '14F108AD9DFA64E289E71CCFA8AD7D5E3921C115C15D0ECA5CCB5BC4F07D21D8050B566A' : true, '155EF5117AA2C1150E927E66FE3B84C3B38FECEC0B148AA686C3D00F01ECC8848E8085EB' : true, '15ACA5C2922D79BCE87FCB67ED02CF36E7B4F69D61EC9069DB7E90A7401A3CF47D4FE8EE' : true, '15B298A354704048703A375582C45AFA0048F8D37B153F6EA2798C323EF4F318A5624A9E' : true, '15EE9F5AA08528DF6BDD34A3A056D8307F8A77836BDC6D068F8B0737FCC5725413068CA4' : true, '160A1613C17FF01D887EE3D9E71261CCF88015D3F98479E1DA553D24FD42BA3F43886AEF' : true, '173574AF7B611CEBF4F93CE2EE40F9A2925A8F8D2C6D04E0665F596AFF22D863E8256F3F' : true, '1802B00127036A191B323B83DE9AA985D6BF7994F42BE5FA29DA0BD7587B591F47A44F22' : true, '1898C0D6E93AFCF9B0F50CF74B014417FAB7EE36972662FB2DB02AF6BF03FDE87C4B2F9B' : true, '18AE695D15CAB917673267D597B260C04BA7B9DDD68788E12FF852E1A024204BF286A8F6' : true, '1AD00CB9A6E68A3B6E95860C5B8CD8195A4D0E8B5FDCFDF64E7299A36C060DB222CA78E4' : true, '1B2E00CA2606903DADFE6F1568D36BB367650DF17E8E7E5B8240A4F4564BCFE23D69C6F0' : true, '1BD75F76734CC0DC98CA442BCC0F78DD31E2C52CE1089BEFFDDADB26DD7C782EBC4037BD' : true, '1C4BE2C62DB9AC3114F4400769CB1F4011C5B5F75552B011669C2E9717DE6D9BFF5FA810' : true, '1D3554048578B03F42424DBF20730A3F02FAF3E291435468607857694DF5E45B68851868' : true, '1D6496AF2D821A300BA0620D76BC53AA7FBB6ACD7E0AB438DAAF6FD50210D007C6C0829C' : true, '1E240EA0F876D785A3F5F8A1493D2EBAFD1ED1E2021B0B9F73E8EB75CE23436BBCC746EB' : true, '1E42950233926BB95FC07FDAD6B24BFCCCAB0EA04C2301D6697BDD379FCD12EB24E3949D' : true, '1E74C3863C0C35C53EC27FEF3CAA3CD9209900B63D955728140CD13622D8C687A4EB0085' : true, '200B4A7A88A7A942868A5F74567B880593E6AB220303B52328DCDA569EBAE4D1D1CCFB65' : true, '206BD68B4A8F48ABE488090DE5651A500CFD83DBAE44B9A0C8F676F3B570650B94B69DBF' : true, '2124A681C1D8F219AF4998E39DFE0BF46A174570A916FBE84453EED3D070A1D8DA442829' : true, '21BC82AB49C4133B4BB22B5C6B909C198BAF4C9B1DF02A92F7DA128EB91BACF498604B6F' : true, '21D84C822B990933A2EB14248D8E5FE84054DA6F1C3F4074ACED0FECCDDB79D153FB901D' : true, '21EFB85040393F756F27FEE3EA5870EBA59C9B10EC7357515ABB660C4D94F73B9E6E9272' : true, '222DA601EA7C0AF7F06C56433F7776D3FEB8C432DCF9769ACEAE3DD8908FFD288665647D' : true, '224D8F8AFCF735C2BB5734907B8B22163E2BF7F2031B96F38CE6C4D8A85D3E2D58476A0F' : true, '246DABD2F2EA4A66AE5BBCAE50AD6E56F9DD19266B2043F1FE4B3DCB0190AFF11F31A69D' : true, '2477D9A891D13BFA882DC2FFF8CD3393D8C5388AB7301B1B6ED47AE645253A6F9F1A2761' : true, '252AC6C5896839F9557202165EA39ED23C71D70E35A5DAA8B2E3812DC3677417F5990DF3' : true, '255BA669B87BF8780DC18FA6EAE47063FA0882595F9CA6A11ECCBEAF65C764C0CCC311D0' : true, '257ABA832EB6A20BDAFEF5020F08D7AD81968B3AEF1CDC70F5FA3269C292A3635BD123D3' : true, '259DCF5EB3259D95B93F00865F47943D43F9B110D5BAFD48225231B0D0082B372FEF9A54' : true, '266D2C1998B6706838505419EC9034600B77BEBBCB7AA24705DECC0FBD6A02FC7ABD9B52' : true, '27DE36FE72B70003009DF4F01E6C0424DE3F40BD5093D39B6C60F6DABC076201008976C9' : true, '27EC3947CDDA5AAFE29A016521A94CBB4D2378EC919539B5007F758F033B211EC54D8BCF' : true, '2A5D003739469475397B11A6F29341E13F85F2BB4A62B0B58BE1614ABB0D4631B4BEF8BA' : true, '2A954ECA79B2874573D92D90BAF99FB6A43489159A520F0D93D032CCAF37E7FE20A8B419' : true, '2B508718392D3BFFC3917F2D7DC08A97B19DD096DCD4E3E0FD676885505A672C438D4E9C' : true, '2B7020568682A018C807531228702172F17F6FB631DC99E3A3C87FFE1CF1811088D96033' : true, '2C20269DCB1A4A0085B5B75AAEC201378C96BAEBDD2B070748EE303266A0F3986E7CAE58' : true, '2C6F17A39562012065D2076EFCB83F6DB1EAC3E5B82476E9D50B1EC67D2CC11E12E0B491' : true, '2C8C175EB154AB9317B5365ADBD1C6F2A073E5C5BD43610D864C21130A855857CC9CEA46' : true, '2C8F9F661D1890B147269D8E86828CA96252DC40F71143A22FDE9EF7348E064251B18118' : true, '2CC2B0D5D622C52E901EF4633F0FBB324A058FDFD761DB21B0C2EE48579BE27F42A4DA1C' : true, '2DBBE525D3D165823AB70EFAE6EBE2E1B3EAC44776C9C81CEAF29D95B6CCA0081B67EC9D' : true, '2E03FDC5F5D72B9464C1BE8931F1169B96995C7711E8E52DF9E34BECEC67D3CBF1B6C4D2' : true, '30C908DDD73E63A4092814C74EB97E2CCFE4313DBA05B8A7C30063995A9EB7C247AD8FD5' : true, '30C9E71E6BE614EB65B216692031674D3BC0380B33C3F6A60C86152293D9DFF54B81C004' : true, '31853C62949763B9AAFD894EAF6FE0CF1F4914F7D874951DDDAE02C0BEFD3A2D82755185' : true, '324A4BBBC863699BBE749AC6DD1D4624AD7E1C28B064EF8F6003402014C3D0E3370EB58A' : true, '3327D16CFC9185FC8C7E98FA854EF305E70715F6F728365B5190E271DEE4C65EBEEACAF3' : true, '33B784F55F27D76827DE14DE122AED6F0747220199CE74B97CB03D79B264A2C855E933FF' : true, '343339FC6D033A8FA25385443270DEC45E5A168867BFFF00987D0B1DC2AB466C4264F956' : true, '34FCB8D036DB9E14B3C2F2DB8FE494C7379A197B418545350CA60369F33C2EAF474F2079' : true, '354895364A545A72968EE064CCEF2C8CC90D1BEA883DA7D117BE3B79F4210E1A5894A72D' : true, '370971C4AFEB7501AE636C3016BFD1E5A399F76F0CBF4C9DA55E4AC24E8960984B2905B6' : true, '3741491B18569A26F5ADC266FB40A54C4313BB96F1D5869BC14E6A92F6CFF63469878237' : true, '3785445332451F20F0F395E125C4434EF48B11BFDEABBE94542071E641DE6BBE882B40B9' : true, '37A56ED4B1258497B7FD56157AF9A200B435D4E1119D1C6690A749EBB394BD637BA782B7' : true, '3916AAB96A41E11469DF9E6C3B72DCB6879F4BEE05DF98583BE360D633E70D3FFE9871AF' : true, '3AB2DE229A209349F9EDC8D28AE7680D36863563FD5128C7BEA6F005CFE9B43668086CCE' : true, '3AE550B039BEC7463633A1FE823E8D943CBB5DE0FCD6397C0588E56697BD462ABDF95C76' : true, '3B0AE4BB416A84B39D2C575E6542BE478E1032E9245944F84791983EC9E829CB1059B4D3' : true, '3C4C25CC0A19CAEE6AEB55160086725F23E833233E7D0CC92B7C4279AC19C2F474D604CA' : true, '3D4129CB1EAA1174CD5DB062AFB0435BDDE1D2A901802E1D875E84B3807E4BB1FD994134' : true, '3E455215095192E1B75D379FB187298AB1BC968BD4F49D622AA89A81F2150152A41D829C' : true, '3E80175BADD77C104BF941B0CF1642B000EA522C8A9C06AA3ECCE0B4FA6CDC21D92E8099' : true, '3F459639E25087F7BBFE980C3C2098E62AC8D58B57CEBF2F49AFF2FC768F511462907A41' : true, '400125068D21436A0E43009CE743F3D5F9CD0E2CDA7624C18FBDF0F0ABB645B8F7FED57A' : true, '410352DC0FF7501B16F0028EBA6F45C5DAC9024F54D8F6DF94935FB1732638CA6AD77C13' : true, '41B807F7A8D109EEB49A8E704DFC1B787A74410FB0CD5C972A364B71BF031D88A6510E9E' : true, '4265CABE019A9A4CA98C4149CDC0D57F293621028B20ED02F566C532D1D6ED909F45002F' : true, '42769768CFA6B43824AAA11BF267DECA4178AB4CBFCE7B4102ACDAC4933E6FF50DCF715C' : true, '4281A0E21CE35510DE558942659622E6E0B4322EB2F6A568B654538448184A5036874384' : true, '429BD669C6D445AD2E81511D355A89624F555CE20DCD3364E0DC7C41EFDD40F50356C122' : true, '45E1A572C5A93664409EF5E45884678C6B2F34AD8958BE62FDB06B5CCEBB9DD94F4E39F3' : true, '45F750114EC5ADBD53688663EC7B6AE1C09AB0C8AD7114714ED5E21A5A276ADCD5E7EFCB' : true, '468C210EAB92214659DBA6DB0061DE265A5A4DAF7861267C4B1F1E67586BAE6ED4FEB93F' : true, '48D11E627801C26E4369A42CEE130AB564902AD7277AF3E32CD8CC1DC79DE1FD7F8069EA' : true, '4963AE27F4D5953DD8DB2486B89C0753D3C063F219ED073E34AD5D750B327629FFD59AF2' : true, '497904B0EB8719AC47B0BC11519B74D0D1EB23A46D17D68FD92564C2F1F1601764D8E349' : true, '49EFA6A1F0DE8EA76AEE5B7D1E5FC4463E42A18706BD0C9CCF594750D2E4D6AB0048FDC4' : true, '4B1C568CA0E8C79E1EF5EE32939965FE4C95A9902ABE0777CED18D6ACCC3372D2748381E' : true, '4B6771BE33B90DB64B3A400187F08B1F7AC5FFF8DCBC5583176877073BF751735E9BD358' : true, '4B798DD41D0392AA51EE04E5906F474954F9C163759F19045121A319F64C2D0555B7E073' : true, '4BE2C99196650CF40E5A9392A00AFEB28CF427FD790C3AD166068DE81E57EFBB932272D4' : true, '4C5641E50DBB2BE8CAA3ED1808AD43390483ED3399AC3608058722EDBC5E4600E3BEF9D7' : true, '4D56677ECCE6457259B74F511172E169C0DB578157E9EE82B5917DF0DD6D82EE9039C4E2' : true, '4FEBF1F070C280635D589FDA123CA9C4E392512F0ACFF505DFF6DE067F7537E165EA574B' : true, '50193E2FE8B6F4055449F3AEC98B3E1947AFB915CDA26D82467B97FA42914468726138DD' : true, '5186E81FBCB1C371B51810DB5FDCF62078E9DD0650624DB9CB36B50767F209B843BE15B3' : true, '556EBEF54C1D7C0360C43418BC9649C1245C97DF7514E7CF2DF8BE72AE957B9E04741E85' : true, '565FAA80611217F66721E62B6D61568E8025EFF46E70C8D472246584FE403B8A8D6ADBF5' : true, '58EB470764D62CBAE29B96552B9700B56A6F2A8B6E2615088DF59CD24C402418AE42A3F1' : true, '59736628512B98B410FF7D06FA22D6C8A0F8DB3F0BF417693B282EB74A6AD86DF9D448A3' : true, '5A11B922850289E1C3F22CE14EC101844B421F7515F6AE8A6ECEF97F6982A400A4D9224E' : true, '5B6F532CBB8188FA6C042C325DA56B967CA04FD8064C1CAA32A37AA94375038E8DF8DDC0' : true, '5B9EFD3B6035EA688E52FE1319144AA36B81446A5CDDF474A0F800FFBE69FD0DB6287516' : true, '5C48DCF74272EC56946D1CCC713580756631BF9EF74F9EB6C9D5A60CBA6ABED1F7BDEF7B' : true, '5E397BDDF8BAEC82E9AC62BA0C54002BCA3AFBCF1240364B44B216208880483919937CF7' : true, '5E809E845A0E650B1702F355182A3ED7786A74AC76AB147F9C6A3050BA9EA87EFE9ACE3C' : true, '5F944A7322B8F7D131EC5939F78EFE6E9FC796E8F8524F863AE1496D381242105F1B78F5' : true, '60847C5ACEDB0CD4CBA7E9FE02C6A9C0101DFA3FD50BCBBB9BB5600C1955A41AF4733A04' : true, '649CEF2E44FCC68F5207D051738FCB3DDA40188B9189A3EDEEAEDA97FE2F9DF5B7D18A41' : true, '65295911BB8F5166890D47824002C5AFC4674DDC6CE2967FF9C92E072EF8E8A7FBD6A131' : true, '6558AB15AD576C1EA8A7B569ACBFFFEBE5DF743CB601C49B9843DCAB8CE86A81109FE48E' : true, '67AC0D773011DED143AE7B737190BCA9ED8DC8386C4886AEEE079158AAC3BFE658E394B4' : true, '67CB9DC013248A829BB2171ED11BECD4D23209AD23D314232174E40D7F9D62139786633A' : true, '689B17C654E0E0E099551642F75A86D8027268293E5F5D17AAA4B3C3E6361E1F92575EAA' : true, '6960ECBE8C94D76E6F2EC4782F55F08397226AAE4A7A64A59BD16787F27F841C0A001FD0' : true, '6C397DA40E5559B23FD641B11250DE435F3B8CF2F810B37D78B4CEEC1919C37334B9C774' : true, '6CC9A76E47F10CE3533B784C4DC26AC5B72FFF92D2CE43DE0A8D4C548C503726A81E2B93' : true, '6D38C49B22244CA3A8B3A09345E157FA89C32E6B524E4D65388B9ECEDC637134ED4193A3' : true, '70B57C4881953E80DC289BBAEF1EE4854072BA31FEC351438480F62E6CB95508461EAB2F' : true, '711F0E21E7AAEA323A6623D3AB50D66996974CD6B663A7184526B1D648AD815CF51E801A' : true, '71AA6AAF1FA5C0D50E90D40BF6AADFCC55C86F7414AC8BDD6814F4D86AF15F3710E104D0' : true, '71E265FBCD7B0B845BE3BCD76320C598CFF810FB2C4FFC0156BFE1E1FABCB418C68D31C5' : true, '72E44A87E369408077EABCE3F4FFF0E15F43E5B1BFF8788CAC1CC7CA4A9AC6222BCC34C6' : true, '733A747AECBBA396A6C2E4E2C89BC0C3AEC5FB3FC8E1BFC4E54F03075A9AE800B7F7B6FA' : true, '739DD35FC63C95FEC6ED89E58208DD897FB9E2C995C97A939F9E81A07AEA9B4D70463496' : true, '74014A91B108C458CE47CDF0DD11530885A408C09C193E5D51587DCDD61330FD8CDE37BF' : true, '747B820343F0009E6BB3EC47BF85A5934463C531D7CCC1006794612BB656D3BF8257846F' : true, '74A82C81432B35609B78056B58F36582CFF360F524CB20F1FEAD89006F7F586A285B2D5B' : true, '770D19B121FD00429C3E0CA5DD0B028E25019019CFFBD9991CB76825748D945F30939542' : true, '774AF42C9DB027B747B515E4C762F0FCDF646DCB7B0FD3A96AEE88C64E2D676711FF9D5F' : true, '782A02DFDB2E14D5A75F0ADFB68E9C5D4F65566336DB6598581D584A596C87934D5F2AB4' : true, '78A5FB104BE4632ED26BFBF2B6C24B8EEC0C3716EA9EDFADD35DFBD55608E60A05D3CBF3' : true, '79E4A9840D7D3A96D7C04FE2434C892EA8985D3A65E5E5C4B2D7D66D40C6DD2FB19C5436' : true, '7A79544D07923B5BFF41F00EC739A298C060ED44CBD881BD0EF86C0BA287DDCF8167478C' : true, '7BB508999A8C18BF85277D0EAEDAB2AB24BA6D6C8A5B5837A48DB5FAE919EA675C94D217' : true, '7C62FF749D31535E684AD578AA1EBF239F744E9F2B4DBAEC0F312C50B6563B8E2D93C311' : true, '7CA50FF85B9A7D6D30AE545AE342A28A59AF82799186C7B47507CBCF035746EB04DDB716' : true, '7D86908F5BF1F240C0F73D62B5A4A93B72997913EC9B0DAE65D1B6D7B24A76A3AEC2EE16' : true, '7E234E5BA7A5B425E90007741162AED67F8AB0CFD051876A66F3360F47C88D8CD335FC74' : true, '7F667A71D3EB6978209A51149D83DA20BE36A4562FB2EE05DBB3D32323ADF445084ED656' : true, '803ABC22C1E6FB8D9B3B274A321B9A0147BEABC922EAE80E78783462A79F45C254FDE68B' : true, '8135B9FBFB12CA186936EBAE6978A1F1DCBB9EB7194BC47205C111752986835B53CAE4F8' : true, '81D6ED354F1F26D031D040DD8AE5810DE0925E18C7765E22DABD9427529DA6AF4E066428' : true, '8212F789E10B9160A4B6229F9468119268ED18B309CD5291C0D3357C1D1141BF883866B1' : true, '824AD493004D66B6A32CA77B3536CF0B687EC17E0602E3CD3F7DFBD7E28D57A0199A3F44' : true, '8292BA5BEFCD8A6FA63D55F984F6D6B7F9B5B632455F9CBEEC575F80DCE96E2CC7B278B7' : true, '84901D95304956FC4181F045D776C46B439E525F5A6A47C32CEBC45C63ED39317CE5F4DF' : true, '852FF4764CD5426CCB5E7DF717E835BD4EFCED9C6BDD0C985CA3C7D253063C5BE6FC620C' : true, '85CA765A1BD16822DCA22312CAC680345BCDCDCC66F6DCE4441FE37D5CC3134C46F47038' : true, '86386D5E49636C855CDB6DDC94B7D0F7ACED5F6553FD25CE015F1F7A483B6A749F6178C6' : true, '86420509BCA79DEC1DF32E0EBAD81DD01D8259CA2127C3CBC16CD932F62C65298CA88712' : true, '86ACDE2BC56DC3D98C2888D38D16131ECE6A64A309E42FBBD9851C453E6409EAE87D60F1' : true, '86EF8E319D9F8569A2A41A127168BA1B90DECE77F8C825340E62EBD635E1BE20CF7327DD' : true, '8714AB83C4041BF193C750E2D721EBEF30779E9315022E94856A3FF8BCF815B082F9AEFD' : true, '879055F2CE31153C33D927C876E37DE13070F8833E4AA6803E09A646AE3F7D8AE1FD1654' : true, '87CE0B7B2A0E4900E158719B37A893720563B8630D62D75ABBC8AB1E4BDFB5A899B24D43' : true, '882C8C52B8A23CF3F7BB03EAAEAC420B74207441729CDD92EC7931D823108DC28192E2BB' : true, '8949548CC8689A8329ECDC067321AB97A60F34C8626C81F68BF77DA9F667588A903F7D36' : true, '8956AA4D441E59D805A1886DEAC828B26372C49DA9FFF051B8B5C7D4E5AAE30384024B9C' : true, '8BCA525F7553D02C6F630D8F882E1CD78EB03FC3CF7BB292866268B751223DB5103405CB' : true, '8CCADC0B22CEF5BE72AC411A11A8D81291C6D6EE3E8AC86384E548C299295C756C817B81' : true, '8CD79FEBC7B8144C5478A7903BA935671F55E8839BAC30728BE7108EDE7B0BB0D3298224' : true, '8D26FF2F316D5929DDE636A7E2CE6425720FC15DDC27D456D098FABF3CDD78D31EF5A8DA' : true, '8D639B56C114E4EE9A128586119082A3D2441AA8C203AECAA96E501F124D52B68FE4C375' : true, '8D7251DBA03ACF2077DFF265065EDFEFC8C25F169EF85074D5BEE8CDA2D43CAEE75FD257' : true, '8EADB501AA4D81E48C1DD1E1140095193679CA35668772304D30A5FB873B0FA77BB70D54' : true, '8F5D770627C4983C5B9378E7D77D9BCC7E784A101C8265CC2DE1F16D47B440CAD90A1945' : true, '8F91E7EEE3FCDA86CAFCDC70EDB7B70C8250BED5A214433A66377CBC10EF83F669DA3A67' : true, '911B3F6ECD9EABEE07FE1F71D2B36127E19FE30E8B84609E809B170D72A8C5BA6E1409BD' : true, '91DE0625ABDAFD32170CBB25172A84672796BAE63F1801E277261BA0D77770028F20EEE4' : true, '91F4035520A1F8632C62DEACFB611C8E21FCBD8E7F6CAF051BD1B343ECA8E76147F20F8A' : true, '9265588BA21A317273685CB4A57A0748E621F3354379059A4B68309D8A2F74221587EC79' : true, '932A3EF6FD23690D7120D42B47992BA6CBA1C5F8B0E35EB8B94512D3F934A2E90610D336' : true, '937F901CED846717A4655F9BCB3002978781C25A96BDC2FB4C65064FF9390B26048A0E01' : true, '93C28E117BD4F30319BD2875134A454AAB48F333DB04ABB9C072DA5B0CC1D057F0369B46' : true, '93EB36130BC154F13E7505E5E01CD4375F4E1FCF31B7913B850B54F6E5FF501A2B6FC6CF' : true, '93F1AD340B2BE7A85460E2738CA49431705D2B4565C7047A540694A79AF7ABB842BDC161' : true, '9414777E3E5EFD8F30BD41B0CFE7D03075E0ABB6138512271C04F85FDDDE38E4B7242EFE' : true, '96897D61D1552B27E25A39B42A6C446F8EFDCABC93E61E925D4D1DED181A4320A467A139' : true, '9760E8575FD35047E5430C94368AB06290AEA26985FF14804C434952ECE9608477AF556F' : true, '978FC66B3B3E40857724750B76BB55F8B5D303BF8682E152919D83F184ED05F1DCE5370C' : true, '9A771918ED96CFDF1BB70EF58DB9882ECF74BFFF9B86815B08335440363E87B6B6F0BF73' : true, '9AAEF722F533FB4EEC0A249DC63D7D255E997CA5945AAB75FFD14804A974BF2AE1DFE7E1' : true, '9B340D1A315B97462698BCA6136A71969E6CEB179185A29EC6060CA53E1974AF94AF59D4' : true, '9D666ACCFFD5F543B4BF8C16D12BA8998939576E178DF705780FCC5EC84F84F6253A4893' : true, '9DFBF9ACED893322F428488325235BE0A69A91FD057F136A42630BB1760D2D51120C1650' : true, '9E80FF78010C2EC136BDFE96906E08F34ABDEEEC950D359C89AEC752A12C5B29F6D6AA0C' : true, '9F6C1F0F07AC1921F915BBD5C72CD82AF5C27CF5FFF3029ACF1A1A4BEC7EE1964C77D784' : true, '9FDDDBABFF8EFF45215FF06C9D8FFE2B9656CD7B57969895D0E141466806FBB8C6110687' : true, 'A10B44B3CA10D8006E9D0FD80F920AD1B80186D1EB9C86A54104CF3054F34C52B7E558C6' : true, 'A208E4B33EEFDE084B60D0BF7952498D8CC4307BC60755E7B22DD9F7FEA245936C7CF288' : true, 'A2339B4C747873D46CE7C1F38DCB5CE985371CA6E550143DCE2803471BDE3A09E8F8770F' : true, 'A26F53B7EE40DB4A68E7FA18D9104B7269BD8CF49CD300FB592E1793CA556AF3ECAA35FB' : true, 'A33D88FE161BDDF95C9F1A7FD8C89008A3E31E20B2E46A328520472D0CDE9523E7260C6D' : true, 'A37D2C27E4A7F3AA5F75D4C49264026AB6AF5BE5F878A00114C3D7FEF8C775C34CCD17B6' : true, 'A3EC750F2E88DFFA48014E0B5C486FFB37F76DE6077C90C5B13E931AB74110B4F2E49A27' : true, 'A66B6090239B3F2DBB986FD6A7190D46E0AB059420725493056062023670F7CD2EFC6666' : true, 'A771FD26FC3CE540F19906EBC1936DE9E619D25B380B7B13FDA33E8A58CD82D8A88E0515' : true, 'A7F2E41606411150306B9CE3B49CB0C9E12DFB4B41D7D9C32B30514BAC1D81D8385E2D46' : true, 'A80D6F3978B9436D77426D985ACC23CAD6DAA8208D09D2154D24B52FCB346EB258B28A58' : true, 'A8EDDEEB938866D82FC3BD1DBE45BE4D7639C71847E151B5C7EA01C758FBF12ABA298F7A' : true, 'A923759BBA49366E31C2DBF2E766BA87317A2AD07F2B335EF5A1C34E4B57E8B7D8F1FCA6' : true, 'A981C0B73A9250BC91A521FF3D47879FCB658264EA8CDA186E1752FB52C397367EA387BE' : true, 'AA088FF6F97BB7F2B1A71E9BEAEABD79CF9E876DD3EBFC422697A3B5A37AA076A9062348' : true, 'AA8E5DD9F8DB0A58B78D26876C823555409D4BD917B55C27B69B64CB9822440DCD09B889' : true, 'AABFBF6497DA981D6FC6083A957033CA394FF6850B06BE52E51856CC10E180E882B385CC' : true, 'AB57A65B7D428219B5D85826285EFDFFB12E13634586A46F1AB2606837582DC4ACFD9497' : true, 'ABAB8D2DB740E5973D2FF2A63BDA6A05C18211328A92B3B23809B9B5E2740A07FB12EB5E' : true, 'ABBFEAE36B29A6CCA6783599EFAD2B802F173F7DE99667AFA57AF80AA2D1B12FAC830338' : true, 'ACB694A59C17E0D791529BB19706A6E4D4DE20D05E66FC53FE1A50882C78DB2852CAE474' : true, 'AD8E0F9E016BA0C574D50CD368654F1ECFDEFE102FDA05BBE4C78D2E4423589005B2571D' : true, 'AFB8336E7CDDC60264AD58FC0D4F7BCFBC7B3C6FEF26B9F7AB10D7A1F6B67C5ED2A12D3D' : true, 'B001EE14D9AF291894768EF169332A846E3A55A4190C195C93843CC0DB722E313061F0B1' : true, 'B147BC1857D118A0782DEC71E82A9573204285DCF7EB764195578E136BD4B7D1E98E46A5' : true, 'B39C25B1C32E32538015309D4D02773E6782AAE0EDEEE21A5839D3C0CD14680A4F60142A' : true, 'B3A53E77216DAC4AC0C9FBD5413DCA0658119F0E128287EA50FDD987456F4F78DCFAD6D4' : true, 'B44ADBE85916461E5AD86EDA064352622964B686135B5DFDDD3253A89BBC24D74B08C64D' : true, 'B465220A7CADDF41B7D544D5ADFA9A75BC9219DDC98E14BF1A781F6E280B04C27F902712' : true, 'B4819E89AC1724FD2A4285271D0C2B5D20CB594FB4EDD895763FD5254E959A6674C6EEB2' : true, 'B5E83436C910445848706D2E83D4B805039EEDB80BE7A03C6953893B20D2D9323A4C2AFD' : true, 'B75274E292B48093F275E4CCD7F2EA263BC49F48F8F373A09C1EBDF85BB1C365C7D811B3' : true, 'B774CD487C5F9A0D3BF3FE66F41B3DFA5B4E0EC28EBD8292A51782241281AD9FEEDD4E4C' : true, 'B7B0D1EC1A033ECEA91511CCB16FB2AEE3D73606996CDFEF61FA04C335E98EA96104264A' : true, 'B8089AF003CC1B0DC86C0B76A1756423A0A1AB90C9FC847B3B1261E8977D5FD32261D3CC' : true, 'B816334C4C4CF2D8D34D06B4A65B4003838E30F77FDD14AA385ED145009C0E2236494FAA' : true, 'B8D312034E8C0C5A47C9B6C59E5B97FD0560A2C738FF98D1172A94FE45FB8A47D665371E' : true, 'BA21EA20D6DDDB8FC1578B40ADA1FCFC801D62D07B449D5C5C035C98EA61FA443C2A58FE' : true, 'BA926442161FCBA116481AF6405C59870456F23D1E9C43AECB0D807F1C0647551A05F456' : true, 'BC6C5133A7E9D366635415721B2192935922A1E15AEA163521F898396A4646B0441B0FA9' : true, 'BD8ACE34A8AE6148E85EC87A1CE8CCBFD2EDF88B41B6FE01461D6E2834EC7C8F6C77721E' : true, 'BDD6F58A7C3CC4A6F934CCC38961F6B2CABB51672400588E6419F1D40878D0403AA20264' : true, 'BE395ABE078AB1121725CC1D46343CB2DE990CED99E0431F60EDC3937E7CD5BF0ED9E5FA' : true, 'BF6059A35BBAF6A77642DA6F1A7B50CF5D989CDB159611365165641B560FDBEA2AC23EF1' : true, 'BFB5E77D3DEA6F1DF08A50BC8C1CFA1DE4554333CA390E128B8BF81D90B70F4002D1D6E9' : true, 'C1623E23C582739C03594B2BE977497F2AB628485E78FBF3AD9E7910DD6BDF99722C96E5' : true, 'C1D43E07AEEBECFD7589E67EA84CEBCD76B76096DD145629AC7585D37063C1BC47861C8B' : true, 'C1D951C084B86A75E82FD7D65F7EAC460B972C9EA6E7CC58D93B20BF71EC412E7209FABF' : true, 'C22A59ABCF152F4CF7E631A316AE840C9158C5EF987301A8903CFDAB03D72DA1D88909C9' : true, 'C2DBAB8E9652C5EEAEF25500896D55953913853E45C439A2DA718CDFB6F3E033E04FEE71' : true, 'C45D0E48B6AC28304E0ABCF938168757D8A6332CE0036FB185F6634F7D6A066526322827' : true, 'C463AB44201C36E437C05F279D0F6F6E97E2E99636A547554F838FBA38B82E74F89A830A' : true, 'C4D7F0B2A3C57D6167F004CD43D3BA5890DEDE9E4C4E9F6FD88617579DD391BC65A68964' : true, 'C570C4A2ED53780CC810538164CBD01D23E594945195F2414803B4D564D2A3A3F5D88B8C' : true, 'C5A1B7FF73DDD6D7343218DFFC3CAD8806083F593F15A104A069A46BA903D006B7970991' : true, 'C5DFB849CA051355EE2DBA1AC33EB028D69B561148F01C77C54578C10926DF5B856976AD' : true, 'C5E67BBF06D04F43EDC47A658AFB6B19339B6B1450249B557A01877284D9E02FC3D2D8E9' : true, 'C69F6D5CB379B00389CBF03FA4C09F8AEF2DACCBEABB682D32CE4ABD6CB90025236C07BC' : true, 'C7BD11D6918A3582C53666017C6F4779634C3B0230CF1B78B4569FECF2C04A8652EFEF0E' : true, 'C86E97F335A729144782892391A6BEC84A3F8D6BDC0E1ECFCD72E377DEF2D7FF92C19BC7' : true, 'C91962D0DA7E1020FCA4CD0380872DF551A44C28F313E3F9CB5E7C0A1E0E0DD2843758AE' : true, 'C9982777281E3D0E153C8400B88503E656E0FAC03B8F18235518E5D311CAE8C24331AB66' : true, 'CA3DD368F1035CD032FAB82B59E85ADB97817950D81C9670CC34D809CF794431367EF474' : true, 'CB17E431673EE209FE455793F30AFA1C4EB6D578499B1CCF5F581EAD56BE3D9B6744A5E5' : true, 'CBBDC3682DB3CB1859D32952E8C66489C9321DE6B5A82666CF6971A18A56F2D3A8675602' : true, 'CC4DAEFB306BD838FE50EB86614BD2269C615C4D4D85103A5326C24DBAEAE4A2D2D5CC97' : true, 'CD3B3D625B09B80936879E122F7164BA67EB337B684CEB0EC2B0760AB488278CDD9597DD' : true, 'CD68B6A7C7C4CE75E01D4F5744619209132D0D45534B6997CDB2D5C339E25576609B5CC6' : true, 'CD996CDB2AC296155ABF879EAEA5EE93EE29D6EA98E632C6E527E0906F0280688BDF44DC' : true, 'CDF439F3B51850D73EA4C591A03E214BE1A45B141A21DA1A79F41A42A961D669CD0634C1' : true, 'CE78335C5978016E18EAB936A0B92E23AE5083ED7CF45CBC8F61C621FE685D794221156E' : true, 'CF8F3B62A3CACA711BA3E1CB4857351F5D003860F002ED829DEAA41868F788186D62127F' : true, 'CFF4270DD4EDDC6516496D3DDABF6EDE3A44735AE581901F248661461E3B9CC45FF53A1B' : true, 'D2EDEE7992F78272180BFED98BEC13D8A7F8390BA57705096FD36941D42E7198C6D4D9D5' : true, 'D35376E3CE58C5B0F29FF42A05F0A1F2211165CA379FBB5ED801E31C430A62AAC109BCB4' : true, 'D3D9BDAE9FAC6724B3C81B52E1B9A9BD4A65D5F41DEF39B8B8904A4AD3648133CFC7A1D1' : true, 'D3F3A616C0FA6B1D59B12D964D0E112E74F8A3C3EFE7B390064B83903C21646020E5DFCE' : true, 'D474DE575C39B2D39C8583C5C065498A5FB7EE0633E259DBAD0C4C9AE6D38F1A61C7DC25' : true, 'D480656824F9892228DBF5A49A178F14016897E1A0B8F2C3B134665C20A727B7A158E28F' : true, 'D59788DA6416E71D664AA6EA37FC7ADCEC93DE083C93D933A986B3D5CDE25ACB2FEECF8E' : true, 'D5BEFFB5EE826CF0E2578EA7E5346F03D904080A4929C838E9F185ECF7A22DEF99342407' : true, 'D5E98140C51869FC462C8975620FAA7807E032E020B72C3F192F0628A2593A19A70F069E' : true, 'D63981C6527E9669FCFCCA66ED05F296B51C067CEE2B0C3DF855AB2D92F4FE39D4E70F0E' : true, 'D6A5C3ED5DDD3E00C13D87921F1D3FE4B31EB1B740E36C8402DADC37D44DF5D4674952F9' : true, 'D6ED3CCAE2660FAF10430D779B0409BF85B5FF679B0C79961FC86E4422004613DB179284' : true, 'D7343DEF1D270928E131025B132BDDF7B172B1A56D95F91FE50287E14D37EA6A4463768A' : true, 'D87E32EF69F8BF72031D4082E8A775AF42EFDDE6BFF35ED0BAE6ACDD204C50AE86C4F4FA' : true, 'DA26B6E6C7C2F7B79E4659B3577718653E84D3BCC544C0F6FA19435C851F3F2FCBA8E814' : true, 'DB233DF969FA4BB9958044735E7D4183273EE12457FDC4F90C55E82B56167F62F532E547' : true, 'DBC8F2272EB1EA6A29235DFE563E33DFC8EC8C879269CB4BAB39E98D7E5767F31495739D' : true, 'DC32C3A76D2557C768099DEA2DA9A2D18782C6C304353BCFD29692D2593E7D44D934FF11' : true, 'DC6D6FAF897CDD17332FB5BA9035E9CE7F88CD7223F3C813818C994614A89C99FA3B5247' : true, 'DD753F56BFBBC5A17A1553C690F9FBCC24A40A1F573643A67F0A4B0749F6A22BF28ABB6B' : true, 'DF0DBC7CC836B77699A1ABF0D20F896A342CD9D3062DA48C346965297F081EBC2EF68FDC' : true, 'DF168A83EA83845DB96501C6A65D193EDBAC3C7AA4254DA1AA5CAAD68468CB88EEDDEEA8' : true, 'DF3C735981E7395081044C34A2CBB37B61573A11DF0ED87ED5926522EAD056D744B32371' : true, 'DFF28073CCF1E66173FCF542E9C57CEE99A69BE61AFE886B4D2B82007CB854FC317E1539' : true, 'E006A1C97DCFC9FC0DC0567596D862139BAAE59F56EE21CB435ABE2593DFA7F040D11DCB' : true, 'E14B5273D71BDB9330E5BDE4096EBEFB216B2A29E62A00CE820146D8244141B92511B279' : true, 'E1C07EA0AABBD4B77B84C228117808A7CDD4EEAE6000AC7F40C3802C171E30148030C072' : true, 'E2D52023ECEEB872E12B5D296FFA43DA9BACF3B664EAC5A17BED08437C72E4ACDA12F7E7' : true, 'E2D8F867F4509435FC5E05FC822295C30446C8BB9A6983C95C8A2E5464687C1115AAB74A' : true, 'E2F8E080D0083F1EC1E9D23F8069AE06C73026E325FE21916B55C4B53A56B13DCAF3D625' : true, 'E60BD2C9CA2D88DB1A710E4B78EB024140E78C1D523D1CD9954FAC1A1AB3BD3CBAA15BFC' : true, 'E77ADCB11F6E061F746C591627C34BC07454535C24A3A758207E3E3ED324F816FB211649' : true, 'E8CC9FB09B40C51F4FBA7421F952857A688B6EB807E8EDA5C7B17C4393D0795F0FAE155F' : true, 'EBB04F1D3A2E372F1DDA6E27D6B680FA18F7C1FCC3090203FD5BAA2F861A754976C8DD25' : true, 'EBF59D290D61F9421F7CC2BA6DE3150928903A635B5280FAE6774C0B6DA7D6BAA64AF2E8' : true, 'EC407D2B765267052CEAF23A4F65F0D8A5EC73D48C34FCBEF1005AEB85843524BBFAB727' : true, 'ED41F58C50C52B9C73E6EE6CEBC2A8261B4B396126276B6491A2686DD70243212D1F1D96' : true, 'EE2931BC327E9AE6E8B5F751B4347190503006091D97D4F5AE39F7CBE7927D7D652D3431' : true, 'EE7A41E0CF757D889280A21A9A7BA157679A4F81FC705DDEC419778DD2EBD875F4C242C6' : true, 'EEFE6169656EF89CC62AF4D72B63EFA29FAD91A6CE6AC6C50047C44EC9D4A50D92D84979' : true, 'EF5AF133EFF1CDBB5102EE12144B96C4A1DB6393916F17E4185509400415C70240B0AE6B' : true, 'F058C503826717AB8FDA0310278E19C2CB44A097857C45FA187ED952086CB9841F2D51B5' : true, 'F096B62FC510D5678E832532E85E2EE52388C9D371CC9E963DFF7D3CA7CEFCD625EC190D' : true, 'F09E639376A595BC1861F19BFBD364DD80BF3DE9A41D768D194B293C85632CDBC8EA8CF7' : true, 'F16A2218C9CDDFCE821D1DB7785CA9A57998A308E14D6585E6C21E153A719FBA5AD34AD9' : true, 'F1BC636A54E0B527F5CDE71AE34D6E4A36B12B49F9819ED74C9EBC380FC6568F5DACB2F7' : true, 'F20598E5964BBE5D55181B55B388E3929078C5A28F9A4325C2A7C73813CDFE13C20F934E' : true, 'F27DE954E4A3220D769FE70BBBB3242B049811056AFE9FD0F5BE01685AACE6A5D1C4454C' : true, 'F37E3A13DC746306741A3C38328CFBA9253F775B0E7797AB645F15915597C39E263631D1' : true, 'F3D752A875FD18ECE17D35B1706EA59C968338F113E36A7BABDD08F7776391A68736582E' : true, 'F4FF97428070FE66168BBED35315819BF44095C238AC73FC4F77BF8F98DF70F8F091BC52' : true, 'F520DA5203862B92768D5CB72D8B93ADA65CB4733D94A5C865A864647C2C01272C89B143' : true, 'F775AB29FB514EB7775EFF053C998EF5DE28F4A4FFE5B92FA3C503D1A349A7F9962A8212' : true, 'F7B661AB03C25C463E2D2CF4A124D854FAA7D9FB31B746F200A85E65797613D816E063B5' : true, 'F8387C7788DF2C16682EC2E2524BB8F95F3AFC0A8B64F686673474DF7EA9A2FEF9FA7A51' : true, 'F8BEC46322C9A846748BB81D1E4A2BF661EF43D77FCAD46151BC98E0C35912AF9FEB6311' : true, 'FB1B5D438A94CD44C676F2434B47E731F18B538D1BE903B6A6F056435B171589CAF36BF2' : true, 'FC11B8D8089330006D23F97EEB521E0270179B868C00A4FA609152223F9F3E32BDE00562' : true, 'FD49BE5B185A25ECF9C354851040E8D4086418E906CEE89C2353B6E27FBD9E7439F76316' : true };
ahri/docker-private-browsing
browser/profile/extensions/[email protected]/chrome/content/code/Root-CAs.js
JavaScript
lgpl-3.0
29,290
//Sample code for SmartStore // This file assumes that all of the javascript and css files required // as well as the required DOM objects are specified in the index.html file. var SAMPLE_SOUP_NAME = "myPeopleSoup"; var lastSoupCursor = null; var sfSmartstore = cordova.require("salesforce/plugin/smartstore"); function regLinkClickHandlers() { var logToConsole = cordova.require("salesforce/util/logger").logToConsole; logToConsole("regLinkClickHandlers"); $('#link_fetch_sfdc_contacts').click(function() { logToConsole("link_fetch_sfdc_contacts clicked"); forcetkClient.query("SELECT Name,Id FROM Contact", onSuccessSfdcContacts, onErrorSfdc); }); $('#link_reset').click(function() { logToConsole("link_reset clicked"); $("#div_device_contact_list").html(""); $("#div_sfdc_contact_list").html(""); $("#div_sfdc_account_list").html(""); $("#div_sfdc_soup_entry_list").html(""); $("#console").html(""); }); $('#link_logout').click(function() { logToConsole("link_logout clicked"); var sfOAuthPlugin = cordova.require("salesforce/plugin/oauth"); sfOAuthPlugin.logout(); }); $('#link_reg_soup').click(function() { logToConsole("link_reg_soup clicked"); var indexes = [ {path:"Name",type:"string"}, {path:"Id",type:"string"} ]; sfSmartstore.registerSoup(SAMPLE_SOUP_NAME, indexes, onSuccessRegSoup, onErrorRegSoup ); }); $('#link_stuff_soup').click(function() { logToConsole("link_stuff_soup clicked"); runStuffSoup(); }); $('#link_remove_soup').click(function() { sfSmartstore.removeSoup(SAMPLE_SOUP_NAME, onSuccessRemoveSoup, onErrorRemoveSoup); }); $('#link_soup_exists').click(function() { sfSmartstore.soupExists(SAMPLE_SOUP_NAME, onSoupExistsDone, onSoupExistsDone); }); $('#link_query_soup').click(function() { runQuerySoup(); }); $('#link_retrieve_entries').click(function() { runRetrieveEntries(); }); $('#link_cursor_page_zero').click(function() { logToConsole("link_cursor_page_zero clicked"); sfSmartstore.moveCursorToPageIndex(lastSoupCursor,0, onSuccessQuerySoup,onErrorQuerySoup); }); $('#link_cursor_page_prev').click(function() { logToConsole("link_cursor_page_prev clicked"); sfSmartstore.moveCursorToPreviousPage(lastSoupCursor,onSuccessQuerySoup,onErrorQuerySoup); }); $('#link_cursor_page_next').click(function() { logToConsole("link_cursor_page_next clicked"); sfSmartstore.moveCursorToNextPage(lastSoupCursor,onSuccessQuerySoup,onErrorQuerySoup); }); } function addEntriesToTestSoup(entries,cb) { var logToConsole = cordova.require("salesforce/util/logger").logToConsole; sfSmartstore.upsertSoupEntries(SAMPLE_SOUP_NAME,entries, function(items) { logToConsole("added entries: " + items.length); $("#div_soup_status_line").html("Soup upsert OK"); if (typeof cb !== "undefined") { cb(items); } }, function(err) { logToConsole("onErrorUpsert: " + err); $("#div_soup_status_line").html("Soup upsert ERROR"); if (typeof cb !== "undefined") { cb(null); } } ); } function addGeneratedEntriesToTestSoup(nEntries, cb) { cordova.require("salesforce/util/logger").logToConsole("addGeneratedEntriesToTestSoup " + nEntries); var entries = []; for (var i = 0; i < nEntries; i++) { var myEntry = { Name: "Todd Stellanova" + i, Id: "00300" + i, attributes:{type:"Contact"} }; entries.push(myEntry); } addEntriesToTestSoup(entries,cb); } function runStuffSoup() { var inputStr = $('#input_stuff_soup_count').val(); if (inputStr.length === 0) { inputStr = null; } var inputVal = 1; if (inputStr !== null) { inputVal = parseInt(inputStr); } addGeneratedEntriesToTestSoup(inputVal); } function runQuerySoup() { var indexPath = $('#input_indexPath').val(); if (indexPath.length === 0) { indexPath = null; } var beginKey = $('#input_querySoup_beginKey').val(); if (beginKey.length === 0) { beginKey = null; } var endKey = $('#input_querySoup_endKey').val(); if (endKey.length === 0) { endKey = null; } var queryType = $('#select_querySoup_type').val(); var pageSizeStr = $('#input_querySoup_pageSize').val(); if (pageSizeStr.length === 0) { pageSizeStr = null; } var pageSizeVal = 25; if (pageSizeStr !== null) { pageSizeVal = parseInt(pageSizeStr); } cordova.require("salesforce/util/logger").logToConsole("querySoup path: '"+ indexPath + "' begin: '" + beginKey + "' end: '" + endKey + "' [" + pageSizeVal + ']'); var querySpec; if ("range" == queryType) { querySpec = sfSmartstore.buildRangeQuerySpec(indexPath,beginKey,endKey,null,pageSizeVal); } else if ("like" == queryType) { querySpec = sfSmartstore.buildLikeQuerySpec(indexPath,beginKey,null,pageSizeVal); } else if ("all" == queryType) { querySpec = sfSmartstore.buildAllQuerySpec(indexPath, null, pageSizeVal) ; } else { //"exact" querySpec = sfSmartstore.buildExactQuerySpec(indexPath,beginKey,null,pageSizeVal); } sfSmartstore.querySoup(SAMPLE_SOUP_NAME,querySpec, onSuccessQuerySoup, onErrorQuerySoup ); } function runRetrieveEntries() { var inputStr = $('#input_retrieve_entries').val(); if (inputStr.length === 0) { inputStr = null; } cordova.require("salesforce/util/logger").logToConsole("runRetrieveEntries: " + inputStr ); var entryIds = eval(inputStr); sfSmartstore.retrieveSoupEntries(SAMPLE_SOUP_NAME, entryIds, onSuccessRetrieveEntries, onErrorRetrieveEntries ); } function onSuccessRegSoup(param) { cordova.require("salesforce/util/logger").logToConsole("onSuccessRegSoup: " + param); $("#div_soup_status_line").html("Soup registered: " + SAMPLE_SOUP_NAME); } function onErrorRegSoup(param) { cordova.require("salesforce/util/logger").logToConsole("onErrorRegSoup: " + param); $("#div_soup_status_line").html("registerSoup ERROR"); } function onSuccessUpsert(param) { cordova.require("salesforce/util/logger").logToConsole("onSuccessUpsert: " + param); $("#div_soup_status_line").html("Soup upsert OK"); } function onErrorUpsert(param) { cordova.require("salesforce/util/logger").logToConsole("onErrorUpsert: " + param); $("#div_soup_status_line").html("Soup upsert ERROR"); } function onSuccessQuerySoup(cursor) { cordova.require("salesforce/util/logger").logToConsole("onSuccessQuerySoup totalPages: " + cursor.totalPages); lastSoupCursor = cursor; $("#div_sfdc_soup_entry_list").html(""); var ul = $('<ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a">Page ' + (cursor.currentPageIndex+1) + '/' + cursor.totalPages + ' Entries: ' + cursor.currentPageOrderedEntries.length + ' </ul>'); $("#div_sfdc_soup_entry_list").append(ul); var curPageEntries = cursor.currentPageOrderedEntries; $.each(curPageEntries, function(i,entry) { var formattedName = entry.name; var entryId = entry._soupEntryId; var phatName = entry.Name; if (phatName) { formattedName = phatName; } var newLi = $("<li><a href='#'>" + entryId + " - " + formattedName + "</a></li>"); ul.append(newLi); }); $("#div_sfdc_soup_entry_list").trigger( "create" ); } function onErrorQuerySoup(param) { cordova.require("salesforce/util/logger").logToConsole("onErrorQuerySoup: " + param); } function onSuccessRetrieveEntries(entries ) { cordova.require("salesforce/util/logger").logToConsole("onSuccessRetrieveEntries : " + entries.length); $("#div_sfdc_soup_entry_list").html(""); var ul = $('<ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a"> ' + ' Entries: ' + entries.length + ' </ul>'); $("#div_sfdc_soup_entry_list").append(ul); $.each(entries, function(i,entry) { var formattedName = entry.name; var entryId = entry._soupEntryId; var phatName = entry.Name; if (phatName) { formattedName = phatName; } var newLi = $("<li><a href='#'>" + entryId + " - " + formattedName + "</a></li>"); ul.append(newLi); }); $("#div_sfdc_soup_entry_list").trigger( "create" ); } function onErrorRetrieveEntries(param) { cordova.require("salesforce/util/logger").logToConsole("onErrorRetrieveEntries: " + param); } function onSuccessRemoveSoup(param) { cordova.require("salesforce/util/logger").logToConsole("onSuccessRemoveSoup: " + param); $("#div_soup_status_line").html("Soup removed: " + SAMPLE_SOUP_NAME); } function onErrorRemoveSoup(param) { cordova.require("salesforce/util/logger").logToConsole("onErrorRemoveSoup: " + param); $("#div_soup_status_line").html("removeSoup ERROR"); } function onSoupExistsDone(param) { cordova.require("salesforce/util/logger").logToConsole("onSoupExistsDone: " + param); $("#div_soup_status_line").html("Soup exists: " + param); } function onSuccessSfdcContacts(response) { var logToConsole = cordova.require("salesforce/util/logger").logToConsole; logToConsole("onSuccessSfdcContacts: received " + response.totalSize + " contacts"); var entries = []; $("#div_sfdc_contact_list").html(""); var ul = $('<ul data-role="listview" data-inset="true" data-theme="a" data-dividertheme="a"></ul>'); $("#div_sfdc_contact_list").append(ul); ul.append($('<li data-role="list-divider">Salesforce Contacts: ' + response.totalSize + '</li>')); $.each(response.records, function(i, contact) { entries.push(contact); logToConsole("name: " + contact.Name); var newLi = $("<li><a href='#'>" + (i+1) + " - " + contact.Name + "</a></li>"); ul.append(newLi); }); if (entries.length > 0) { sfSmartstore.upsertSoupEntries(SAMPLE_SOUP_NAME, entries, function(items) { var statusTxt = "upserted: " + items.length + " contacts"; logToConsole(statusTxt); $("#div_soup_status_line").html(statusTxt); $("#div_sfdc_contact_list").trigger( "create" ); }, onErrorUpsert); } } function onErrorSfdc(error) { cordova.require("salesforce/util/logger").logToConsole("onErrorSfdc: " + JSON.stringify(error)); alert('Error getting sfdc contacts!'); }
marcus-bessa/MobileCampaign
forcedroid/hybrid/SampleApps/SmartStoreExplorer/assets/www/smartstoreexplorer.js
JavaScript
unlicense
13,221
;(function($){ /** * jqGrid extension for manipulating Grid Data * Tony Tomov [email protected] * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl-2.0.html **/ //jsHint options /*global alert, $, jQuery */ "use strict"; $.jgrid.inlineEdit = $.jgrid.inlineEdit || {}; $.jgrid.extend({ //Editing editRow : function(rowid,keys,oneditfunc,successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) { // Compatible mode old versions var o={}, args = $.makeArray(arguments).slice(1); if( $.type(args[0]) === "object" ) { o = args[0]; } else { if (typeof keys !== "undefined") { o.keys = keys; } if ($.isFunction(oneditfunc)) { o.oneditfunc = oneditfunc; } if ($.isFunction(successfunc)) { o.successfunc = successfunc; } if (typeof url !== "undefined") { o.url = url; } if (typeof extraparam !== "undefined") { o.extraparam = extraparam; } if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; } if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; } if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; } // last two not as param, but as object (sorry) //if (typeof restoreAfterError !== "undefined") { o.restoreAfterError = restoreAfterError; } //if (typeof mtype !== "undefined") { o.mtype = mtype || "POST"; } } o = $.extend(true, { keys : false, oneditfunc: null, successfunc: null, url: null, extraparam: {}, aftersavefunc: null, errorfunc: null, afterrestorefunc: null, restoreAfterError: true, mtype: "POST" }, $.jgrid.inlineEdit, o ); // End compatible return this.each(function(){ var $t = this, nm, tmp, editable, cnt=0, focus=null, svr={}, ind,cm; if (!$t.grid ) { return; } ind = $($t).jqGrid("getInd",rowid,true); if( ind === false ) {return;} editable = $(ind).attr("editable") || "0"; if (editable == "0" && !$(ind).hasClass("not-editable-row")) { cm = $t.p.colModel; $('td[role="gridcell"]',ind).each( function(i) { nm = cm[i].name; var treeg = $t.p.treeGrid===true && nm == $t.p.ExpandColumn; if(treeg) { tmp = $("span:first",this).html();} else { try { tmp = $.unformat.call($t,this,{rowId:rowid, colModel:cm[i]},i); } catch (_) { tmp = ( cm[i].edittype && cm[i].edittype == 'textarea' ) ? $(this).text() : $(this).html(); } } if ( nm != 'cb' && nm != 'subgrid' && nm != 'rn') { if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); } svr[nm]=tmp; if(cm[i].editable===true) { if(focus===null) { focus = i; } if (treeg) { $("span:first",this).html(""); } else { $(this).html(""); } var opt = $.extend({},cm[i].editoptions || {},{id:rowid+"_"+nm,name:nm}); if(!cm[i].edittype) { cm[i].edittype = "text"; } if(tmp == "&nbsp;" || tmp == "&#160;" || (tmp.length==1 && tmp.charCodeAt(0)==160) ) {tmp='';} var elc = $.jgrid.createEl.call($t,cm[i].edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {})); $(elc).addClass("editable"); if(treeg) { $("span:first",this).append(elc); } else { $(this).append(elc); } //Again IE if(cm[i].edittype == "select" && typeof(cm[i].editoptions)!=="undefined" && cm[i].editoptions.multiple===true && typeof(cm[i].editoptions.dataUrl)==="undefined" && $.browser.msie) { $(elc).width($(elc).width()); } cnt++; } } }); if(cnt > 0) { svr.id = rowid; $t.p.savedRow.push(svr); $(ind).attr("editable","1"); $("td:eq("+focus+") input",ind).focus(); if(o.keys===true) { $(ind).bind("keydown",function(e) { if (e.keyCode === 27) { $($t).jqGrid("restoreRow",rowid, o.afterrestorefunc); if($t.p._inlinenav) { try { $($t).jqGrid('showAddEditButtons'); } catch (eer1) {} } return false; } if (e.keyCode === 13) { var ta = e.target; if(ta.tagName == 'TEXTAREA') { return true; } if( $($t).jqGrid("saveRow", rowid, o ) ) { if($t.p._inlinenav) { try { $($t).jqGrid('showAddEditButtons'); } catch (eer2) {} } } return false; } }); } $($t).triggerHandler("jqGridInlineEditRow", [rowid, o]); if( $.isFunction(o.oneditfunc)) { o.oneditfunc.call($t, rowid); } } } }); }, saveRow : function(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc) { // Compatible mode old versions var args = $.makeArray(arguments).slice(1), o = {}; if( $.type(args[0]) === "object" ) { o = args[0]; } else { if ($.isFunction(successfunc)) { o.successfunc = successfunc; } if (typeof url !== "undefined") { o.url = url; } if (typeof extraparam !== "undefined") { o.extraparam = extraparam; } if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; } if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; } if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; } } o = $.extend(true, { successfunc: null, url: null, extraparam: {}, aftersavefunc: null, errorfunc: null, afterrestorefunc: null, restoreAfterError: true, mtype: "POST" }, $.jgrid.inlineEdit, o ); // End compatible var success = false; var $t = this[0], nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind; if (!$t.grid ) { return success; } ind = $($t).jqGrid("getInd",rowid,true); if(ind === false) {return success;} editable = $(ind).attr("editable"); o.url = o.url ? o.url : $t.p.editurl; if (editable==="1") { var cm; $('td[role="gridcell"]',ind).each(function(i) { cm = $t.p.colModel[i]; nm = cm.name; if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) { switch (cm.edittype) { case "checkbox": var cbv = ["Yes","No"]; if(cm.editoptions ) { cbv = cm.editoptions.value.split(":"); } tmp[nm]= $("input",this).is(":checked") ? cbv[0] : cbv[1]; break; case 'text': case 'password': case 'textarea': case "button" : tmp[nm]=$("input, textarea",this).val(); break; case 'select': if(!cm.editoptions.multiple) { tmp[nm] = $("select option:selected",this).val(); tmp2[nm] = $("select option:selected", this).text(); } else { var sel = $("select",this), selectedText = []; tmp[nm] = $(sel).val(); if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; } $("select option:selected",this).each( function(i,selected){ selectedText[i] = $(selected).text(); } ); tmp2[nm] = selectedText.join(","); } if(cm.formatter && cm.formatter == 'select') { tmp2={}; } break; case 'custom' : try { if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) { tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement",this),'get'); if (tmp[nm] === undefined) { throw "e2"; } } else { throw "e1"; } } catch (e) { if (e=="e1") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.nodefined,$.jgrid.edit.bClose); } if (e=="e2") { $.jgrid.info_dialog($.jgrid.errors.errcap,"function 'custom_value' "+$.jgrid.edit.msg.novalue,$.jgrid.edit.bClose); } else { $.jgrid.info_dialog($.jgrid.errors.errcap,e.message,$.jgrid.edit.bClose); } } break; } cv = $.jgrid.checkValues(tmp[nm],i,$t); if(cv[0] === false) { cv[1] = tmp[nm] + " " + cv[1]; return false; } if($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); } if(o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) { if(tmp[nm] === "") { tmp3[nm] = 'null'; } } } }); if (cv[0] === false){ try { var positions = $.jgrid.findPos($("#"+$.jgrid.jqID(rowid), $t.grid.bDiv)[0]); $.jgrid.info_dialog($.jgrid.errors.errcap,cv[1],$.jgrid.edit.bClose,{left:positions[0],top:positions[1]}); } catch (e) { alert(cv[1]); } return success; } var idname, opers, oper; opers = $t.p.prmNames; oper = opers.oper; idname = opers.id; if(tmp) { tmp[oper] = opers.editoper; tmp[idname] = rowid; if(typeof($t.p.inlineData) == 'undefined') { $t.p.inlineData ={}; } tmp = $.extend({},tmp,$t.p.inlineData,o.extraparam); } if (o.url == 'clientArray') { tmp = $.extend({},tmp, tmp2); if($t.p.autoencode) { $.each(tmp,function(n,v){ tmp[n] = $.jgrid.htmlDecode(v); }); } var resp = $($t).jqGrid("setRowData",rowid,tmp); $(ind).attr("editable","0"); for( var k=0;k<$t.p.savedRow.length;k++) { if( $t.p.savedRow[k].id == rowid) {fr = k; break;} } if(fr >= 0) { $t.p.savedRow.splice(fr,1); } $($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, resp, tmp, o]); if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,resp, o); } success = true; $(ind).unbind("keydown"); } else { $("#lui_"+$.jgrid.jqID($t.p.id)).show(); tmp3 = $.extend({},tmp,tmp3); tmp3[idname] = $.jgrid.stripPref($t.p.idPrefix, tmp3[idname]); $.ajax($.extend({ url:o.url, data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3, type: o.mtype, async : false, //?!? complete: function(res,stat){ $("#lui_"+$.jgrid.jqID($t.p.id)).hide(); if (stat === "success"){ var ret = true, sucret; sucret = $($t).triggerHandler("jqGridInlineSuccessSaveRow", [res, rowid, o]); if (!$.isArray(sucret)) {sucret = [true, tmp];} if (sucret[0] && $.isFunction(o.successfunc)) {sucret = o.successfunc.call($t, res);} if($.isArray(sucret)) { // expect array - status, data, rowid ret = sucret[0]; tmp = sucret[1] ? sucret[1] : tmp; } else { ret = sucret; } if (ret===true) { if($t.p.autoencode) { $.each(tmp,function(n,v){ tmp[n] = $.jgrid.htmlDecode(v); }); } tmp = $.extend({},tmp, tmp2); $($t).jqGrid("setRowData",rowid,tmp); $(ind).attr("editable","0"); for( var k=0;k<$t.p.savedRow.length;k++) { if( $t.p.savedRow[k].id == rowid) {fr = k; break;} } if(fr >= 0) { $t.p.savedRow.splice(fr,1); } $($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, res, tmp, o]); if( $.isFunction(o.aftersavefunc) ) { o.aftersavefunc.call($t, rowid,res); } success = true; $(ind).unbind("keydown"); } else { $($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, null, o]); if($.isFunction(o.errorfunc) ) { o.errorfunc.call($t, rowid, res, stat, null); } if(o.restoreAfterError === true) { $($t).jqGrid("restoreRow",rowid, o.afterrestorefunc); } } } }, error:function(res,stat,err){ $("#lui_"+$.jgrid.jqID($t.p.id)).hide(); $($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, err, o]); if($.isFunction(o.errorfunc) ) { o.errorfunc.call($t, rowid, res, stat, err); } else { var rT = res.responseText || res.statusText; try { $.jgrid.info_dialog($.jgrid.errors.errcap,'<div class="ui-state-error">'+ rT +'</div>', $.jgrid.edit.bClose,{buttonalign:'right'}); } catch(e) { alert(rT); } } if(o.restoreAfterError === true) { $($t).jqGrid("restoreRow",rowid, o.afterrestorefunc); } } }, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {})); } } return success; }, restoreRow : function(rowid, afterrestorefunc) { // Compatible mode old versions var args = $.makeArray(arguments).slice(1), o={}; if( $.type(args[0]) === "object" ) { o = args[0]; } else { if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; } } o = $.extend(true, $.jgrid.inlineEdit, o ); // End compatible return this.each(function(){ var $t= this, fr, ind, ares={}; if (!$t.grid ) { return; } ind = $($t).jqGrid("getInd",rowid,true); if(ind === false) {return;} for( var k=0;k<$t.p.savedRow.length;k++) { if( $t.p.savedRow[k].id == rowid) {fr = k; break;} } if(fr >= 0) { if($.isFunction($.fn.datepicker)) { try { $("input.hasDatepicker","#"+$.jgrid.jqID(ind.id)).datepicker('hide'); } catch (e) {} } $.each($t.p.colModel, function(){ if(this.editable === true && this.name in $t.p.savedRow[fr] ) { ares[this.name] = $t.p.savedRow[fr][this.name]; } }); $($t).jqGrid("setRowData",rowid,ares); $(ind).attr("editable","0").unbind("keydown"); $t.p.savedRow.splice(fr,1); if($("#"+$.jgrid.jqID(rowid), "#"+$.jgrid.jqID($t.p.id)).hasClass("jqgrid-new-row")){ setTimeout(function(){$($t).jqGrid("delRowData",rowid);},0); } } $($t).triggerHandler("jqGridInlineAfterRestoreRow", [rowid]); if ($.isFunction(o.afterrestorefunc)) { o.afterrestorefunc.call($t, rowid); } }); }, addRow : function ( p ) { p = $.extend(true, { rowID : "new_row", initdata : {}, position :"first", useDefValues : true, useFormatter : false, addRowParams : {extraparam:{}} },p || {}); return this.each(function(){ if (!this.grid ) { return; } var $t = this; if(p.useDefValues === true) { $($t.p.colModel).each(function(){ if( this.editoptions && this.editoptions.defaultValue ) { var opt = this.editoptions.defaultValue, tmp = $.isFunction(opt) ? opt.call($t) : opt; p.initdata[this.name] = tmp; } }); } $($t).jqGrid('addRowData', p.rowID, p.initdata, p.position); p.rowID = $t.p.idPrefix + p.rowID; $("#"+$.jgrid.jqID(p.rowID), "#"+$.jgrid.jqID($t.p.id)).addClass("jqgrid-new-row"); if(p.useFormatter) { $("#"+$.jgrid.jqID(p.rowID)+" .ui-inline-edit", "#"+$.jgrid.jqID($t.p.id)).click(); } else { var opers = $t.p.prmNames, oper = opers.oper; p.addRowParams.extraparam[oper] = opers.addoper; $($t).jqGrid('editRow', p.rowID, p.addRowParams); $($t).jqGrid('setSelection', p.rowID); } }); }, inlineNav : function (elem, o) { o = $.extend({ edit: true, editicon: "ui-icon-pencil", add: true, addicon:"ui-icon-plus", save: true, saveicon:"ui-icon-disk", cancel: true, cancelicon:"ui-icon-cancel", addParams : {useFormatter : false,rowID : "new_row"}, editParams : {}, restoreAfterSelect : true }, $.jgrid.nav, o ||{}); return this.each(function(){ if (!this.grid ) { return; } var $t = this, onSelect, gID = $.jgrid.jqID($t.p.id); $t.p._inlinenav = true; // detect the formatactions column if(o.addParams.useFormatter === true) { var cm = $t.p.colModel,i; for (i = 0; i<cm.length; i++) { if(cm[i].formatter && cm[i].formatter === "actions" ) { if(cm[i].formatoptions) { var defaults = { keys:false, onEdit : null, onSuccess: null, afterSave:null, onError: null, afterRestore: null, extraparam: {}, url: null }, ap = $.extend( defaults, cm[i].formatoptions ); o.addParams.addRowParams = { "keys" : ap.keys, "oneditfunc" : ap.onEdit, "successfunc" : ap.onSuccess, "url" : ap.url, "extraparam" : ap.extraparam, "aftersavefunc" : ap.afterSavef, "errorfunc": ap.onError, "afterrestorefunc" : ap.afterRestore }; } break; } } } if(o.add) { $($t).jqGrid('navButtonAdd', elem,{ caption : o.addtext, title : o.addtitle, buttonicon : o.addicon, id : $t.p.id+"_iladd", onClickButton : function () { $($t).jqGrid('addRow', o.addParams); if(!o.addParams.useFormatter) { $("#"+gID+"_ilsave").removeClass('ui-state-disabled'); $("#"+gID+"_ilcancel").removeClass('ui-state-disabled'); $("#"+gID+"_iladd").addClass('ui-state-disabled'); $("#"+gID+"_iledit").addClass('ui-state-disabled'); } } }); } if(o.edit) { $($t).jqGrid('navButtonAdd', elem,{ caption : o.edittext, title : o.edittitle, buttonicon : o.editicon, id : $t.p.id+"_iledit", onClickButton : function () { var sr = $($t).jqGrid('getGridParam','selrow'); if(sr) { $($t).jqGrid('editRow', sr, o.editParams); $("#"+gID+"_ilsave").removeClass('ui-state-disabled'); $("#"+gID+"_ilcancel").removeClass('ui-state-disabled'); $("#"+gID+"_iladd").addClass('ui-state-disabled'); $("#"+gID+"_iledit").addClass('ui-state-disabled'); } else { $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus(); } } }); } if(o.save) { $($t).jqGrid('navButtonAdd', elem,{ caption : o.savetext || '', title : o.savetitle || 'Save row', buttonicon : o.saveicon, id : $t.p.id+"_ilsave", onClickButton : function () { var sr = $t.p.savedRow[0].id; if(sr) { var opers = $t.p.prmNames, oper = opers.oper; if(!o.editParams.extraparam) { o.editParams.extraparam = {}; } if($("#"+$.jgrid.jqID(sr), "#"+gID ).hasClass("jqgrid-new-row")) { o.editParams.extraparam[oper] = opers.addoper; } else { o.editParams.extraparam[oper] = opers.editoper; } if( $($t).jqGrid('saveRow', sr, o.editParams) ) { $($t).jqGrid('showAddEditButtons'); } } else { $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus(); } } }); $("#"+gID+"_ilsave").addClass('ui-state-disabled'); } if(o.cancel) { $($t).jqGrid('navButtonAdd', elem,{ caption : o.canceltext || '', title : o.canceltitle || 'Cancel row editing', buttonicon : o.cancelicon, id : $t.p.id+"_ilcancel", onClickButton : function () { var sr = $t.p.savedRow[0].id; if(sr) { $($t).jqGrid('restoreRow', sr, o.editParams); $($t).jqGrid('showAddEditButtons'); } else { $.jgrid.viewModal("#alertmod",{gbox:"#gbox_"+gID,jqm:true});$("#jqg_alrt").focus(); } } }); $("#"+gID+"_ilcancel").addClass('ui-state-disabled'); } if(o.restoreAfterSelect === true) { if($.isFunction($t.p.beforeSelectRow)) { onSelect = $t.p.beforeSelectRow; } else { onSelect = false; } $t.p.beforeSelectRow = function(id, stat) { var ret = true; if($t.p.savedRow.length > 0 && $t.p._inlinenav===true && ( id !== $t.p.selrow && $t.p.selrow !==null) ) { if($t.p.selrow == o.addParams.rowID ) { $($t).jqGrid('delRowData', $t.p.selrow); } else { $($t).jqGrid('restoreRow', $t.p.selrow, o.editParams); } $($t).jqGrid('showAddEditButtons'); } if(onSelect) { ret = onSelect.call($t, id, stat); } return ret; }; } }); }, showAddEditButtons : function() { return this.each(function(){ if (!this.grid ) { return; } var gID = $.jgrid.jqID(this.p.id); $("#"+gID+"_ilsave").addClass('ui-state-disabled'); $("#"+gID+"_ilcancel").addClass('ui-state-disabled'); $("#"+gID+"_iladd").removeClass('ui-state-disabled'); $("#"+gID+"_iledit").removeClass('ui-state-disabled'); }); } //end inline edit }); })(jQuery);
fdcmessenger/framework
sampleWebApp/src/main/webapp/scripts/jqgrid/src/grid.inlinedit.js
JavaScript
apache-2.0
19,833
/* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') { define = function(deps, factory) { deps = deps.map.forEach(function(id) { return require(id); }); module.exports = factory(deps); }; define.amd = {}; } if (typeof define === 'function' && define.amd) { define('activesync/codepages',[ 'wbxml', './codepages/Common', './codepages/AirSync', './codepages/Contacts', './codepages/Email', './codepages/Calendar', './codepages/Move', './codepages/ItemEstimate', './codepages/FolderHierarchy', './codepages/MeetingResponse', './codepages/Tasks', './codepages/ResolveRecipients', './codepages/ValidateCert', './codepages/Contacts2', './codepages/Ping', './codepages/Provision', './codepages/Search', './codepages/GAL', './codepages/AirSyncBase', './codepages/Settings', './codepages/DocumentLibrary', './codepages/ItemOperations', './codepages/ComposeMail', './codepages/Email2', './codepages/Notes', './codepages/RightsManagement' ], factory); } else { root.ActiveSyncCodepages = factory(WBXML, ASCPCommon, ASCPAirSync, ASCPContacts, ASCPEmail, ASCPCalendar, ASCPMove, ASCPItemEstimate, ASCPHierarchy, ASCPMeetingResponse, ASCPTasks, ASCPResolveRecipients, ASCPValidateCert, ASCPContacts2, ASCPPing, ASCPProvision, ASCPSearch, ASCPGAL, ASCPAirSyncBase, ASCPSettings, ASCPDocumentLibrary, ASCPItemOperations, ASCPComposeMail, ASCPEmail2, ASCPNotes, ASCPRightsManagement); } }(this, function(WBXML, Common, AirSync, Contacts, Email, Calendar, Move, ItemEstimate, FolderHierarchy, MeetingResponse, Tasks, ResolveRecipients, ValidateCert, Contacts2, Ping, Provision, Search, GAL, AirSyncBase, Settings, DocumentLibrary, ItemOperations, ComposeMail, Email2, Notes, RightsManagement) { 'use strict'; var codepages = { Common: Common, AirSync: AirSync, Contacts: Contacts, Email: Email, Calendar: Calendar, Move: Move, ItemEstimate: ItemEstimate, FolderHierarchy: FolderHierarchy, MeetingResponse: MeetingResponse, Tasks: Tasks, ResolveRecipients: ResolveRecipients, ValidateCert: ValidateCert, Contacts2: Contacts2, Ping: Ping, Provision: Provision, Search: Search, GAL: GAL, AirSyncBase: AirSyncBase, Settings: Settings, DocumentLibrary: DocumentLibrary, ItemOperations: ItemOperations, ComposeMail: ComposeMail, Email2: Email2, Notes: Notes, RightsManagement: RightsManagement }; WBXML.CompileCodepages(codepages); return codepages; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('wbxml',factory); else root.WBXML = factory(); }(this, function() { 'use strict'; var exports = {}; var Tokens = { SWITCH_PAGE: 0x00, END: 0x01, ENTITY: 0x02, STR_I: 0x03, LITERAL: 0x04, EXT_I_0: 0x40, EXT_I_1: 0x41, EXT_I_2: 0x42, PI: 0x43, LITERAL_C: 0x44, EXT_T_0: 0x80, EXT_T_1: 0x81, EXT_T_2: 0x82, STR_T: 0x83, LITERAL_A: 0x84, EXT_0: 0xC0, EXT_1: 0xC1, EXT_2: 0xC2, OPAQUE: 0xC3, LITERAL_AC: 0xC4, }; /** * Create a constructor for a custom error type that works like a built-in * Error. * * @param name the string name of the error * @param parent (optional) a parent class for the error, defaults to Error * @param extraArgs an array of extra arguments that can be passed to the * constructor of this error type * @return the constructor for this error */ function makeError(name, parent, extraArgs) { function CustomError() { // Try to let users call this as CustomError(...) without the "new". This // is imperfect, and if you call this function directly and give it a // |this| that's a CustomError, things will break. Don't do it! var self = this instanceof CustomError ? this : Object.create(CustomError.prototype); var tmp = Error(); var offset = 1; self.stack = tmp.stack.substring(tmp.stack.indexOf('\n') + 1); self.message = arguments[0] || tmp.message; if (extraArgs) { offset += extraArgs.length; for (var i = 0; i < extraArgs.length; i++) self[extraArgs[i]] = arguments[i+1]; } var m = /@(.+):(.+)/.exec(self.stack); self.fileName = arguments[offset] || (m && m[1]) || ""; self.lineNumber = arguments[offset + 1] || (m && m[2]) || 0; return self; } CustomError.prototype = Object.create((parent || Error).prototype); CustomError.prototype.name = name; CustomError.prototype.constructor = CustomError; return CustomError; } var ParseError = makeError('WBXML.ParseError'); exports.ParseError = ParseError; function StringTable(data, decoder) { this.strings = []; this.offsets = {}; var start = 0; for (var i = 0; i < data.length; i++) { if (data[i] === 0) { this.offsets[start] = this.strings.length; this.strings.push(decoder.decode( data.subarray(start, i) )); start = i + 1; } } } StringTable.prototype = { get: function(offset) { if (offset in this.offsets) return this.strings[this.offsets[offset]]; else { if (offset < 0) throw new ParseError('offset must be >= 0'); var curr = 0; for (var i = 0; i < this.strings.length; i++) { // Add 1 to the current string's length here because we stripped a // null-terminator earlier. if (offset < curr + this.strings[i].length + 1) return this.strings[i].slice(offset - curr); curr += this.strings[i].length + 1; } } throw new ParseError('invalid offset'); }, }; function CompileCodepages(codepages) { codepages.__nsnames__ = {}; codepages.__tagnames__ = {}; codepages.__attrdata__ = {}; for (var iter in Iterator(codepages)) { var name = iter[0], page = iter[1]; if (name.match(/^__/)) continue; if (page.Tags) { var v = Iterator(page.Tags).next(); codepages.__nsnames__[v[1] >> 8] = name; for (var iter2 in Iterator(page.Tags)) { var tag = iter2[0], value = iter2[1]; codepages.__tagnames__[value] = tag; } } if (page.Attrs) { for (var iter3 in Iterator(page.Attrs)) { var attr = iter3[0], data = iter3[1]; if (!('name' in data)) data.name = attr; codepages.__attrdata__[data.value] = data; page.Attrs[attr] = data.value; } } } } exports.CompileCodepages = CompileCodepages; var mib2str = { 3: 'US-ASCII', 4: 'ISO-8859-1', 5: 'ISO-8859-2', 6: 'ISO-8859-3', 7: 'ISO-8859-4', 8: 'ISO-8859-5', 9: 'ISO-8859-6', 10: 'ISO-8859-7', 11: 'ISO-8859-8', 12: 'ISO-8859-9', 13: 'ISO-8859-10', 106: 'UTF-8', }; // TODO: Really, we should build our own map here with synonyms for the // various encodings, but this is a step in the right direction. var str2mib = {}; for (var iter in Iterator(mib2str)) { str2mib[iter[1]] = iter[0]; } function Element(ownerDocument, type, tag) { this.ownerDocument = ownerDocument; this.type = type; this._attrs = {}; if (typeof tag === 'string') { var pieces = tag.split(':'); if (pieces.length === 1) { this.localTagName = pieces[0]; } else { this.namespaceName = pieces[0]; this.localTagName = pieces[1]; } } else { this.tag = tag; Object.defineProperties(this, { 'namespace': { get: function() { return this.tag >> 8; } }, 'localTag': { get: function() { return this.tag & 0xff; } }, 'namespaceName': { get: function() { return this.ownerDocument._codepages.__nsnames__[this.namespace]; } }, 'localTagName': { get: function() { return this.ownerDocument._codepages.__tagnames__[this.tag]; } }, }); } } exports.Element = Element; Element.prototype = { get tagName() { var ns = this.namespaceName; ns = ns ? ns + ':' : ''; return ns + this.localTagName; }, getAttributes: function() { var attributes = []; for (var iter in Iterator(this._attrs)) { var name = iter[0], pieces = iter[1]; var data = name.split(':'); attributes.push({ name: name, namespace: data[0], localName: data[1], value: this._getAttribute(pieces) }); } return attributes; }, getAttribute: function(attr) { if (typeof attr === 'number') attr = this.ownerDocument._codepages.__attrdata__[attr].name; else if (!(attr in this._attrs) && this.namespace !== null && attr.indexOf(':') === -1) attr = this.namespaceName + ':' + attr; return this._getAttribute(this._attrs[attr]); }, _getAttribute: function(pieces) { var strValue = ''; var array = []; for (var iter in Iterator(pieces)) { var hunk = iter[1]; if (hunk instanceof Extension) { if (strValue) { array.push(strValue); strValue = ''; } array.push(hunk); } else if (typeof hunk === 'number') { strValue += this.ownerDocument._codepages.__attrdata__[hunk].data || ''; } else { strValue += hunk; } } if (strValue) array.push(strValue); return array.length === 1 ? array[0] : array; }, _addAttribute: function(attr) { if (typeof attr === 'string') { if (attr in this._attrs) throw new ParseError('attribute '+attr+' is repeated'); return this._attrs[attr] = []; } else { var namespace = attr >> 8; var localAttr = attr & 0xff; var localName = this.ownerDocument._codepages.__attrdata__[localAttr] .name; var nsName = this.ownerDocument._codepages.__nsnames__[namespace]; var name = nsName + ':' + localName; if (name in this._attrs) throw new ParseError('attribute '+name+' is repeated'); return this._attrs[name] = [attr]; } }, }; function EndTag(ownerDocument) { this.ownerDocument = ownerDocument; } exports.EndTag = EndTag; EndTag.prototype = { get type() { return 'ETAG'; }, }; function Text(ownerDocument, textContent) { this.ownerDocument = ownerDocument; this.textContent = textContent; } exports.Text = Text; Text.prototype = { get type() { return 'TEXT'; }, }; function Extension(ownerDocument, subtype, index, value) { this.ownerDocument = ownerDocument; this.subtype = subtype; this.index = index; this.value = value; } exports.Extension = Extension; Extension.prototype = { get type() { return 'EXT'; }, }; function ProcessingInstruction(ownerDocument) { this.ownerDocument = ownerDocument; } exports.ProcessingInstruction = ProcessingInstruction; ProcessingInstruction.prototype = { get type() { return 'PI'; }, get target() { if (typeof this.targetID === 'string') return this.targetID; else return this.ownerDocument._codepages.__attrdata__[this.targetID].name; }, _setTarget: function(target) { this.targetID = target; if (typeof target === 'string') return this._data = []; else return this._data = [target]; }, // XXX: this seems impolite... _getAttribute: Element.prototype._getAttribute, get data() { return this._getAttribute(this._data); }, }; function Opaque(ownerDocument, data) { this.ownerDocument = ownerDocument; this.data = data; } exports.Opaque = Opaque; Opaque.prototype = { get type() { return 'OPAQUE'; }, }; function Reader(data, codepages) { this._data = data instanceof Writer ? data.bytes : data; this._codepages = codepages; this.rewind(); } exports.Reader = Reader; Reader.prototype = { _get_uint8: function() { if (this._index === this._data.length) throw StopIteration; return this._data[this._index++]; }, _get_mb_uint32: function() { var b; var result = 0; do { b = this._get_uint8(); result = result*128 + (b & 0x7f); } while(b & 0x80); return result; }, _get_slice: function(length) { var start = this._index; this._index += length; return this._data.subarray(start, this._index); }, _get_c_string: function() { var start = this._index; while (this._get_uint8()); return this._data.subarray(start, this._index - 1); }, rewind: function() { // Although in theory we could cache this.document since we no longer use // iterators, there is clearly some kind of rep exposure that goes awry // for us, so I'm having us re-do our work. This does not matter in the // normal use-case, just for debugging and just for our test server, which // both rely on rewind(). this._index = 0; var v = this._get_uint8(); this.version = ((v & 0xf0) + 1).toString() + '.' + (v & 0x0f).toString(); this.pid = this._get_mb_uint32(); this.charset = mib2str[this._get_mb_uint32()] || 'unknown'; this._decoder = TextDecoder(this.charset); var tbl_len = this._get_mb_uint32(); this.strings = new StringTable(this._get_slice(tbl_len), this._decoder); this.document = this._getDocument(); }, // start = version publicid charset strtbl body // strtbl = length *byte // body = *pi element *pi // element = stag [ 1*attribute END ] [ *content END ] // // content = element | string | extension | entity | pi | opaque // // stag = TAG | ( LITERAL index ) // attribute = attrStart *attrValue // attrStart = ATTRSTART | ( LITERAL index ) // attrValue = ATTRVALUE | string | extension | entity // // extension = ( EXT_I termstr ) | ( EXT_T index ) | EXT // // string = inline | tableref // inline = STR_I termstr // tableref = STR_T index // // entity = ENTITY entcode // entcode = mb_u_int32 // UCS-4 character code // // pi = PI attrStart *attrValue END // // opaque = OPAQUE length *byte // // version = u_int8 containing WBXML version number // publicid = mb_u_int32 | ( zero index ) // charset = mb_u_int32 // termstr = charset-dependent string with termination // index = mb_u_int32 // integer index into string table. // length = mb_u_int32 // integer length. // zero = u_int8 // containing the value zero (0). _getDocument: function() { // Parser states var States = { BODY: 0, ATTRIBUTES: 1, ATTRIBUTE_PI: 2, }; var state = States.BODY; var currentNode; var currentAttr; var codepage = 0; var depth = 0; var foundRoot = false; var doc = []; var appendString = (function(s) { if (state === States.BODY) { if (!currentNode) currentNode = new Text(this, s); else currentNode.textContent += s; } else { // if (state === States.ATTRIBUTES || state === States.ATTRIBUTE_PI) currentAttr.push(s); } // We can assume that we're in a valid state, so don't bother checking // here. }).bind(this); try { while (true) { var tok = this._get_uint8(); if (tok === Tokens.SWITCH_PAGE) { codepage = this._get_uint8(); if (!(codepage in this._codepages.__nsnames__)) throw new ParseError('unknown codepage '+codepage); } else if (tok === Tokens.END) { if (state === States.BODY && depth-- > 0) { if (currentNode) { doc.push(currentNode); currentNode = null; } doc.push(new EndTag(this)); } else if (state === States.ATTRIBUTES || state === States.ATTRIBUTE_PI) { state = States.BODY; doc.push(currentNode); currentNode = null; currentAttr = null; } else { throw new ParseError('unexpected END token'); } } else if (tok === Tokens.ENTITY) { if (state === States.BODY && depth === 0) throw new ParseError('unexpected ENTITY token'); var e = this._get_mb_uint32(); appendString('&#'+e+';'); } else if (tok === Tokens.STR_I) { if (state === States.BODY && depth === 0) throw new ParseError('unexpected STR_I token'); appendString(this._decoder.decode(this._get_c_string())); } else if (tok === Tokens.PI) { if (state !== States.BODY) throw new ParseError('unexpected PI token'); state = States.ATTRIBUTE_PI; if (currentNode) doc.push(currentNode); currentNode = new ProcessingInstruction(this); } else if (tok === Tokens.STR_T) { if (state === States.BODY && depth === 0) throw new ParseError('unexpected STR_T token'); var r = this._get_mb_uint32(); appendString(this.strings.get(r)); } else if (tok === Tokens.OPAQUE) { if (state !== States.BODY) throw new ParseError('unexpected OPAQUE token'); var len = this._get_mb_uint32(); var data = this._get_slice(len); if (currentNode) { doc.push(currentNode); currentNode = null; } doc.push(new Opaque(this, data)); } else if (((tok & 0x40) || (tok & 0x80)) && (tok & 0x3f) < 3) { var hi = tok & 0xc0; var lo = tok & 0x3f; var subtype; var value; if (hi === Tokens.EXT_I_0) { subtype = 'string'; value = this._decoder.decode(this._get_c_string()); } else if (hi === Tokens.EXT_T_0) { subtype = 'integer'; value = this._get_mb_uint32(); } else { // if (hi === Tokens.EXT_0) subtype = 'byte'; value = null; } var ext = new Extension(this, subtype, lo, value); if (state === States.BODY) { if (currentNode) { doc.push(currentNode); currentNode = null; } doc.push(ext); } else { // if (state === States.ATTRIBUTES || state === States.ATTRIBUTE_PI) currentAttr.push(ext); } } else if (state === States.BODY) { if (depth === 0) { if (foundRoot) throw new ParseError('multiple root nodes found'); foundRoot = true; } var tag = (codepage << 8) + (tok & 0x3f); if ((tok & 0x3f) === Tokens.LITERAL) { var r = this._get_mb_uint32(); tag = this.strings.get(r); } if (currentNode) doc.push(currentNode); currentNode = new Element(this, (tok & 0x40) ? 'STAG' : 'TAG', tag); if (tok & 0x40) depth++; if (tok & 0x80) { state = States.ATTRIBUTES; } else { state = States.BODY; doc.push(currentNode); currentNode = null; } } else { // if (state === States.ATTRIBUTES || state === States.ATTRIBUTE_PI) var attr = (codepage << 8) + tok; if (!(tok & 0x80)) { if (tok === Tokens.LITERAL) { var r = this._get_mb_uint32(); attr = this.strings.get(r); } if (state === States.ATTRIBUTE_PI) { if (currentAttr) throw new ParseError('unexpected attribute in PI'); currentAttr = currentNode._setTarget(attr); } else { currentAttr = currentNode._addAttribute(attr); } } else { currentAttr.push(attr); } } } } catch (e) { if (!(e instanceof StopIteration)) throw e; } return doc; }, dump: function(indentation, header) { var result = ''; if (indentation === undefined) indentation = 2; var indent = function(level) { return new Array(level*indentation + 1).join(' '); }; var tagstack = []; if (header) { result += 'Version: ' + this.version + '\n'; result += 'Public ID: ' + this.pid + '\n'; result += 'Charset: ' + this.charset + '\n'; result += 'String table:\n "' + this.strings.strings.join('"\n "') + '"\n\n'; } var newline = false; var doc = this.document; var doclen = doc.length; for (var iNode = 0; iNode < doclen; iNode++) { var node = doc[iNode]; if (node.type === 'TAG' || node.type === 'STAG') { result += indent(tagstack.length) + '<' + node.tagName; var attributes = node.getAttributes(); for (var i = 0; i < attributes.length; i++) { var attr = attributes[i]; result += ' ' + attr.name + '="' + attr.value + '"'; } if (node.type === 'STAG') { tagstack.push(node.tagName); result += '>\n'; } else result += '/>\n'; } else if (node.type === 'ETAG') { var tag = tagstack.pop(); result += indent(tagstack.length) + '</' + tag + '>\n'; } else if (node.type === 'TEXT') { result += indent(tagstack.length) + node.textContent + '\n'; } else if (node.type === 'PI') { result += indent(tagstack.length) + '<?' + node.target; if (node.data) result += ' ' + node.data; result += '?>\n'; } else if (node.type === 'OPAQUE') { result += indent(tagstack.length) + '<![CDATA[' + node.data + ']]>\n'; } else { throw new Error('Unknown node type "' + node.type + '"'); } } return result; }, }; function Writer(version, pid, charset, strings) { this._rawbuf = new ArrayBuffer(1024); this._buffer = new Uint8Array(this._rawbuf); this._pos = 0; this._codepage = 0; this._tagStack = []; var infos = version.split('.').map(function(x) { return parseInt(x); }); var major = infos[0], minor = infos[1]; var v = ((major - 1) << 4) + minor; var charsetNum = charset; if (typeof charset === 'string') { charsetNum = str2mib[charset]; if (charsetNum === undefined) throw new Error('unknown charset '+charset); } var encoder = this._encoder = TextEncoder(charset); this._write(v); this._write(pid); this._write(charsetNum); if (strings) { var bytes = strings.map(function(s) { return encoder.encode(s); }); var len = bytes.reduce(function(x, y) { return x + y.length + 1; }, 0); this._write_mb_uint32(len); for (var iter in Iterator(bytes)) { var b = iter[1]; this._write_bytes(b); this._write(0x00); } } else { this._write(0x00); } } exports.Writer = Writer; Writer.Attribute = function(name, value) { this.isValue = typeof name === 'number' && (name & 0x80); if (this.isValue && value !== undefined) throw new Error("Can't specify a value for attribute value constants"); this.name = name; this.value = value; }; Writer.StringTableRef = function(index) { this.index = index; }; Writer.Entity = function(code) { this.code = code; }; Writer.Extension = function(subtype, index, data) { var validTypes = { 'string': { value: Tokens.EXT_I_0, validator: function(data) { return typeof data === 'string'; } }, 'integer': { value: Tokens.EXT_T_0, validator: function(data) { return typeof data === 'number'; } }, 'byte': { value: Tokens.EXT_0, validator: function(data) { return data === null || data === undefined; } }, }; var info = validTypes[subtype]; if (!info) throw new Error('Invalid WBXML Extension type'); if (!info.validator(data)) throw new Error('Data for WBXML Extension does not match type'); if (index !== 0 && index !== 1 && index !== 2) throw new Error('Invalid WBXML Extension index'); this.subtype = info.value; this.index = index; this.data = data; }; Writer.a = function(name, val) { return new Writer.Attribute(name, val); }; Writer.str_t = function(index) { return new Writer.StringTableRef(index); }; Writer.ent = function(code) { return new Writer.Entity(code) }; Writer.ext = function(subtype, index, data) { return new Writer.Extension( subtype, index, data); }; Writer.prototype = { _write: function(tok) { // Expand the buffer by a factor of two if we ran out of space. if (this._pos === this._buffer.length - 1) { this._rawbuf = new ArrayBuffer(this._rawbuf.byteLength * 2); var buffer = new Uint8Array(this._rawbuf); for (var i = 0; i < this._buffer.length; i++) buffer[i] = this._buffer[i]; this._buffer = buffer; } this._buffer[this._pos++] = tok; }, _write_mb_uint32: function(value) { var bytes = []; bytes.push(value % 0x80); while (value >= 0x80) { value >>= 7; bytes.push(0x80 + (value % 0x80)); } for (var i = bytes.length - 1; i >= 0; i--) this._write(bytes[i]); }, _write_bytes: function(bytes) { for (var i = 0; i < bytes.length; i++) this._write(bytes[i]); }, _write_str: function(str) { this._write_bytes(this._encoder.encode(str)); }, _setCodepage: function(codepage) { if (this._codepage !== codepage) { this._write(Tokens.SWITCH_PAGE); this._write(codepage); this._codepage = codepage; } }, _writeTag: function(tag, stag, attrs) { if (tag === undefined) throw new Error('unknown tag'); var flags = 0x00; if (stag) flags += 0x40; if (attrs.length) flags += 0x80; if (tag instanceof Writer.StringTableRef) { this._write(Tokens.LITERAL + flags); this._write_mb_uint32(tag.index); } else { this._setCodepage(tag >> 8); this._write((tag & 0xff) + flags); } if (attrs.length) { for (var iter in Iterator(attrs)) { var attr = iter[1]; this._writeAttr(attr); } this._write(Tokens.END); } }, _writeAttr: function(attr) { if (!(attr instanceof Writer.Attribute)) throw new Error('Expected an Attribute object'); if (attr.isValue) throw new Error("Can't use attribute value constants here"); if (attr.name instanceof Writer.StringTableRef) { this._write(Tokens.LITERAL); this._write(attr.name.index); } else { this._setCodepage(attr.name >> 8); this._write(attr.name & 0xff); } this._writeText(attr.value, true); }, _writeText: function(value, inAttr) { if (Array.isArray(value)) { for (var iter in Iterator(value)) { var piece = iter[1]; this._writeText(piece, inAttr); } } else if (value instanceof Writer.StringTableRef) { this._write(Tokens.STR_T); this._write_mb_uint32(value.index); } else if (value instanceof Writer.Entity) { this._write(Tokens.ENTITY); this._write_mb_uint32(value.code); } else if (value instanceof Writer.Extension) { this._write(value.subtype + value.index); if (value.subtype === Tokens.EXT_I_0) { this._write_str(value.data); this._write(0x00); } else if (value.subtype === Tokens.EXT_T_0) { this._write_mb_uint32(value.data); } } else if (value instanceof Writer.Attribute) { if (!value.isValue) throw new Error('Unexpected Attribute object'); if (!inAttr) throw new Error("Can't use attribute value constants outside of " + "attributes"); this._setCodepage(value.name >> 8); this._write(value.name & 0xff); } else if (value !== null && value !== undefined) { this._write(Tokens.STR_I); this._write_str(value.toString()); this._write(0x00); } }, tag: function(tag) { var tail = arguments.length > 1 ? arguments[arguments.length - 1] : null; if (tail === null || tail instanceof Writer.Attribute) { var rest = Array.prototype.slice.call(arguments, 1); this._writeTag(tag, false, rest); return this; } else { var head = Array.prototype.slice.call(arguments, 0, -1); return this.stag.apply(this, head) .text(tail) .etag(); } }, stag: function(tag) { var rest = Array.prototype.slice.call(arguments, 1); this._writeTag(tag, true, rest); this._tagStack.push(tag); return this; }, etag: function(tag) { if (this._tagStack.length === 0) throw new Error('Spurious etag() call!'); var expectedTag = this._tagStack.pop(); if (tag !== undefined && tag !== expectedTag) throw new Error('Closed the wrong tag'); this._write(Tokens.END); return this; }, text: function(value) { this._writeText(value); return this; }, pi: function(target, data) { this._write(Tokens.PI); this._writeAttr(Writer.a(target, data)); this._write(Tokens.END); return this; }, ext: function(subtype, index, data) { return this.text(Writer.ext(subtype, index, data)); }, opaque: function(data) { this._write(Tokens.OPAQUE); this._write_mb_uint32(data.length); if (typeof data === 'string') { this._write_str(data); } else { for (var i = 0; i < data.length; i++) this._write(data[i]); } return this; }, get buffer() { return this._rawbuf.slice(0, this._pos); }, get bytes() { return new Uint8Array(this._rawbuf, 0, this._pos); }, }; function EventParser() { this.listeners = []; this.onerror = function(e) { throw e; }; } exports.EventParser = EventParser; EventParser.prototype = { addEventListener: function(path, callback) { this.listeners.push({path: path, callback: callback}); }, _pathMatches: function(a, b) { return a.length === b.length && a.every(function(val, i) { if (b[i] === '*') return true; else if (Array.isArray(b[i])) { return b[i].indexOf(val) !== -1; } else return val === b[i]; }); }, run: function(reader) { var fullPath = []; var recPath = []; var recording = 0; var doc = reader.document; var doclen = doc.length; for (var iNode = 0; iNode < doclen; iNode++) { var node = doc[iNode]; if (node.type === 'TAG') { fullPath.push(node.tag); for (var iter in Iterator(this.listeners)) { var listener = iter[1]; if (this._pathMatches(fullPath, listener.path)) { node.children = []; try { listener.callback(node); } catch (e) { if (this.onerror) this.onerror(e); } } } fullPath.pop(); } else if (node.type === 'STAG') { fullPath.push(node.tag); for (var iter in Iterator(this.listeners)) { var listener = iter[1]; if (this._pathMatches(fullPath, listener.path)) { recording++; } } } else if (node.type === 'ETAG') { for (var iter in Iterator(this.listeners)) { var listener = iter[1]; if (this._pathMatches(fullPath, listener.path)) { recording--; try { listener.callback(recPath[recPath.length-1]); } catch (e) { if (this.onerror) this.onerror(e); } } } fullPath.pop(); } if (recording) { if (node.type === 'STAG') { node.type = 'TAG'; node.children = []; if (recPath.length) recPath[recPath.length-1].children.push(node); recPath.push(node); } else if (node.type === 'ETAG') { recPath.pop(); } else { node.children = []; recPath[recPath.length-1].children.push(node); } } } }, }; return exports; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Common',[], factory); else root.ASCPCommon = factory(); }(this, function() { 'use strict'; return { Enums: { Status: { InvalidContent: '101', InvalidWBXML: '102', InvalidXML: '103', InvalidDateTime: '104', InvalidCombinationOfIDs: '105', InvalidIDs: '106', InvalidMIME: '107', DeviceIdMissingOrInvalid: '108', DeviceTypeMissingOrInvalid: '109', ServerError: '110', ServerErrorRetryLater: '111', ActiveDirectoryAccessDenied: '112', MailboxQuotaExceeded: '113', MailboxServerOffline: '114', SendQuotaExceeded: '115', MessageRecipientUnresolved: '116', MessageReplyNotAllowed: '117', MessagePreviouslySent: '118', MessageHasNoRecipient: '119', MailSubmissionFailed: '120', MessageReplyFailed: '121', AttachmentIsTooLarge: '122', UserHasNoMailbox: '123', UserCannotBeAnonymous: '124', UserPrincipalCouldNotBeFound: '125', UserDisabledForSync: '126', UserOnNewMailboxCannotSync: '127', UserOnLegacyMailboxCannotSync: '128', DeviceIsBlockedForThisUser: '129', AccessDenied: '130', AccountDisabled: '131', SyncStateNotFound: '132', SyncStateLocked: '133', SyncStateCorrupt: '134', SyncStateAlreadyExists: '135', SyncStateVersionInvalid: '136', CommandNotSupported: '137', VersionNotSupported: '138', DeviceNotFullyProvisionable: '139', RemoteWipeRequested: '140', LegacyDeviceOnStrictPolicy: '141', DeviceNotProvisioned: '142', PolicyRefresh: '143', InvalidPolicyKey: '144', ExternallyManagedDevicesNotAllowed: '145', NoRecurrenceInCalendar: '146', UnexpectedItemClass: '147', RemoteServerHasNoSSL: '148', InvalidStoredRequest: '149', ItemNotFound: '150', TooManyFolders: '151', NoFoldersFounds: '152', ItemsLostAfterMove: '153', FailureInMoveOperation: '154', MoveCommandDisallowedForNonPersistentMoveAction: '155', MoveCommandInvalidDestinationFolder: '156', AvailabilityTooManyRecipients: '160', AvailabilityDLLimitReached: '161', AvailabilityTransientFailure: '162', AvailabilityFailure: '163', BodyPartPreferenceTypeNotSupported: '164', DeviceInformationRequired: '165', InvalidAccountId: '166', AccountSendDisabled: '167', IRM_FeatureDisabled: '168', IRM_TransientError: '169', IRM_PermanentError: '170', IRM_InvalidTemplateID: '171', IRM_OperationNotPermitted: '172', NoPicture: '173', PictureTooLarge: '174', PictureLimitReached: '175', BodyPart_ConversationTooLarge: '176', MaximumDevicesReached: '177', }, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Contacts',[], factory); else root.ASCPContacts = factory(); }(this, function() { 'use strict'; return { Tags: { Anniversary: 0x0105, AssistantName: 0x0106, AssistantPhoneNumber: 0x0107, Birthday: 0x0108, Body: 0x0109, BodySize: 0x010A, BodyTruncated: 0x010B, Business2PhoneNumber: 0x010C, BusinessAddressCity: 0x010D, BusinessAddressCountry: 0x010E, BusinessAddressPostalCode: 0x010F, BusinessAddressState: 0x0110, BusinessAddressStreet: 0x0111, BusinessFaxNumber: 0x0112, BusinessPhoneNumber: 0x0113, CarPhoneNumber: 0x0114, Categories: 0x0115, Category: 0x0116, Children: 0x0117, Child: 0x0118, CompanyName: 0x0119, Department: 0x011A, Email1Address: 0x011B, Email2Address: 0x011C, Email3Address: 0x011D, FileAs: 0x011E, FirstName: 0x011F, Home2PhoneNumber: 0x0120, HomeAddressCity: 0x0121, HomeAddressCountry: 0x0122, HomeAddressPostalCode: 0x0123, HomeAddressState: 0x0124, HomeAddressStreet: 0x0125, HomeFaxNumber: 0x0126, HomePhoneNumber: 0x0127, JobTitle: 0x0128, LastName: 0x0129, MiddleName: 0x012A, MobilePhoneNumber: 0x012B, OfficeLocation: 0x012C, OtherAddressCity: 0x012D, OtherAddressCountry: 0x012E, OtherAddressPostalCode: 0x012F, OtherAddressState: 0x0130, OtherAddressStreet: 0x0131, PagerNumber: 0x0132, RadioPhoneNumber: 0x0133, Spouse: 0x0134, Suffix: 0x0135, Title: 0x0136, WebPage: 0x0137, YomiCompanyName: 0x0138, YomiFirstName: 0x0139, YomiLastName: 0x013A, CompressedRTF: 0x013B, Picture: 0x013C, Alias: 0x013D, WeightedRank: 0x013E, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Calendar',[], factory); else root.ASCPCalendar = factory(); }(this, function() { 'use strict'; return { Tags: { TimeZone: 0x0405, AllDayEvent: 0x0406, Attendees: 0x0407, Attendee: 0x0408, Email: 0x0409, Name: 0x040A, Body: 0x040B, BodyTruncated: 0x040C, BusyStatus: 0x040D, Categories: 0x040E, Category: 0x040F, CompressedRTF: 0x0410, DtStamp: 0x0411, EndTime: 0x0412, Exception: 0x0413, Exceptions: 0x0414, Deleted: 0x0415, ExceptionStartTime: 0x0416, Location: 0x0417, MeetingStatus: 0x0418, OrganizerEmail: 0x0419, OrganizerName: 0x041A, Recurrence: 0x041B, Type: 0x041C, Until: 0x041D, Occurrences: 0x041E, Interval: 0x041F, DayOfWeek: 0x0420, DayOfMonth: 0x0421, WeekOfMonth: 0x0422, MonthOfYear: 0x0423, Reminder: 0x0424, Sensitivity: 0x0425, Subject: 0x0426, StartTime: 0x0427, UID: 0x0428, AttendeeStatus: 0x0429, AttendeeType: 0x042A, Attachment: 0x042B, Attachments: 0x042C, AttName: 0x042D, AttSize: 0x042E, AttOid: 0x042F, AttMethod: 0x0430, AttRemoved: 0x0431, DisplayName: 0x0432, DisallowNewTimeProposal: 0x0433, ResponseRequested: 0x0434, AppointmentReplyTime: 0x0435, ResponseType: 0x0436, CalendarType: 0x0437, IsLeapMonth: 0x0438, FirstDayOfWeek: 0x0439, OnlineMeetingConfLink: 0x043A, OnlineMeetingExternalLink: 0x043B, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/MeetingResponse',[], factory); else root.ASCPMeetingResponse = factory(); }(this, function() { 'use strict'; return { Tags: { CalendarId: 0x0805, CollectionId: 0x0806, MeetingResponse: 0x0807, RequestId: 0x0808, Request: 0x0809, Result: 0x080A, Status: 0x080B, UserResponse: 0x080C, InstanceId: 0x080E, }, Enums: { Status: { Success: '1', InvalidRequest: '2', MailboxError: '3', ServerError: '4', }, UserResponse: { Accepted: '1', Tentative: '2', Declined: '3', }, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Tasks',[], factory); else root.ASCPTasks = factory(); }(this, function() { 'use strict'; return { Tags: { Body: 0x0905, BodySize: 0x0906, BodyTruncated: 0x0907, Categories: 0x0908, Category: 0x0909, Complete: 0x090A, DateCompleted: 0x090B, DueDate: 0x090C, UtcDueDate: 0x090D, Importance: 0x090E, Recurrence: 0x090F, Recurrence_Type: 0x0910, Recurrence_Start: 0x0911, Recurrence_Until: 0x0912, Recurrence_Occurrences: 0x0913, Recurrence_Interval: 0x0914, Recurrence_DayOfMonth: 0x0915, Recurrence_DayOfWeek: 0x0916, Recurrence_WeekOfMonth: 0x0917, Recurrence_MonthOfYear: 0x0918, Recurrence_Regenerate: 0x0919, Recurrence_DeadOccur: 0x091A, ReminderSet: 0x091B, ReminderTime: 0x091C, Sensitivity: 0x091D, StartDate: 0x091E, UtcStartDate: 0x091F, Subject: 0x0920, CompressedRTF: 0x0921, OrdinalDate: 0x0922, SubOrdinalDate: 0x0923, CalendarType: 0x0924, IsLeapMonth: 0x0925, FirstDayOfWeek: 0x0926, } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/ResolveRecipients',[], factory); else root.ASCPResolveRecipients = factory(); }(this, function() { 'use strict'; return { Tags: { ResolveRecipients: 0x0A05, Response: 0x0A06, Status: 0x0A07, Type: 0x0A08, Recipient: 0x0A09, DisplayName: 0x0A0A, EmailAddress: 0x0A0B, Certificates: 0x0A0C, Certificate: 0x0A0D, MiniCertificate: 0x0A0E, Options: 0x0A0F, To: 0x0A10, CertificateRetrieval: 0x0A11, RecipientCount: 0x0A12, MaxCertificates: 0x0A13, MaxAmbiguousRecipients: 0x0A14, CertificateCount: 0x0A15, Availability: 0x0A16, StartTime: 0x0A17, EndTime: 0x0A18, MergedFreeBusy: 0x0A19, Picture: 0x0A1A, MaxSize: 0x0A1B, Data: 0x0A1C, MaxPictures: 0x0A1D, }, Enums: { Status: { Success: '1', AmbiguousRecipientFull: '2', AmbiguousRecipientPartial: '3', RecipientNotFound: '4', ProtocolError: '5', ServerError: '6', InvalidSMIMECert: '7', CertLimitReached: '8', }, CertificateRetrieval: { None: '1', Full: '2', Mini: '3', }, MergedFreeBusy: { Free: '0', Tentative: '1', Busy: '2', Oof: '3', NoData: '4', }, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/ValidateCert',[], factory); else root.ASCPValidateCert = factory(); }(this, function() { 'use strict'; return { Tags: { ValidateCert: 0x0B05, Certificates: 0x0B06, Certificate: 0x0B07, CertificateChain: 0x0B08, CheckCRL: 0x0B09, Status: 0x0B0A, }, Enums: { Status: { Success: '1', ProtocolError: '2', InvalidSignature: '3', UntrustedSource: '4', InvalidChain: '5', NotForEmail: '6', Expired: '7', InconsistentTimes: '8', IdMisused: '9', MissingInformation: '10', CAEndMismatch: '11', EmailAddressMismatch: '12', Revoked: '13', ServerOffline: '14', ChainRevoked: '15', RevocationUnknown: '16', UnknownError: '17', }, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Contacts2',[], factory); else root.ASCPContacts2 = factory(); }(this, function() { 'use strict'; return { Tags: { CustomerId: 0x0C05, GovernmentId: 0x0C06, IMAddress: 0x0C07, IMAddress2: 0x0C08, IMAddress3: 0x0C09, ManagerName: 0x0C0A, CompanyMainPhone: 0x0C0B, AccountName: 0x0C0C, NickName: 0x0C0D, MMS: 0x0C0E, } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Ping',[], factory); else root.ASCPPing = factory(); }(this, function() { 'use strict'; return { Tags: { Ping: 0x0D05, AutdState: 0x0D06, Status: 0x0D07, HeartbeatInterval: 0x0D08, Folders: 0x0D09, Folder: 0x0D0A, Id: 0x0D0B, Class: 0x0D0C, MaxFolders: 0x0D0D, }, Enums: { Status: { Expired: '1', Changed: '2', MissingParameters: '3', SyntaxError: '4', InvalidInterval: '5', TooManyFolders: '6', SyncFolders: '7', ServerError: '8', }, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Provision',[], factory); else root.ASCPProvision = factory(); }(this, function() { 'use strict'; return { Tags: { Provision: 0x0E05, Policies: 0x0E06, Policy: 0x0E07, PolicyType: 0x0E08, PolicyKey: 0x0E09, Data: 0x0E0A, Status: 0x0E0B, RemoteWipe: 0x0E0C, EASProvisionDoc: 0x0E0D, DevicePasswordEnabled: 0x0E0E, AlphanumericDevicePasswordRequired: 0x0E0F, DeviceEncryptionEnabled: 0x0E10, RequireStorageCardEncryption: 0x0E10, PasswordRecoveryEnabled: 0x0E11, AttachmentsEnabled: 0x0E13, MinDevicePasswordLength: 0x0E14, MaxInactivityTimeDeviceLock: 0x0E15, MaxDevicePasswordFailedAttempts: 0x0E16, MaxAttachmentSize: 0x0E17, AllowSimpleDevicePassword: 0x0E18, DevicePasswordExpiration: 0x0E19, DevicePasswordHistory: 0x0E1A, AllowStorageCard: 0x0E1B, AllowCamera: 0x0E1C, RequireDeviceEncryption: 0x0E1D, AllowUnsignedApplications: 0x0E1E, AllowUnsignedInstallationPackages: 0x0E1F, MinDevicePasswordComplexCharacters: 0x0E20, AllowWiFi: 0x0E21, AllowTextMessaging: 0x0E22, AllowPOPIMAPEmail: 0x0E23, AllowBluetooth: 0x0E24, AllowIrDA: 0x0E25, RequireManualSyncWhenRoaming: 0x0E26, AllowDesktopSync: 0x0E27, MaxCalendarAgeFilter: 0x0E28, AllowHTMLEmail: 0x0E29, MaxEmailAgeFilter: 0x0E2A, MaxEmailBodyTruncationSize: 0x0E2B, MaxEmailHTMLBodyTruncationSize: 0x0E2C, RequireSignedSMIMEMessages: 0x0E2D, RequireEncryptedSMIMEMessages: 0x0E2E, RequireSignedSMIMEAlgorithm: 0x0E2F, RequireEncryptionSMIMEAlgorithm: 0x0E30, AllowSMIMEEncryptionAlgorithmNegotiation: 0x0E31, AllowSMIMESoftCerts: 0x0E32, AllowBrowser: 0x0E33, AllowConsumerEmail: 0x0E34, AllowRemoteDesktop: 0x0E35, AllowInternetSharing: 0x0E36, UnapprovedInROMApplicationList: 0x0E37, ApplicationName: 0x0E38, ApprovedApplicationList: 0x0E39, Hash: 0x0E3A, } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Search',[], factory); else root.ASCPSearch = factory(); }(this, function() { 'use strict'; return { Tags: { Search: 0x0F05, Stores: 0x0F06, Store: 0x0F07, Name: 0x0F08, Query: 0x0F09, Options: 0x0F0A, Range: 0x0F0B, Status: 0x0F0C, Response: 0x0F0D, Result: 0x0F0E, Properties: 0x0F0F, Total: 0x0F10, EqualTo: 0x0F11, Value: 0x0F12, And: 0x0F13, Or: 0x0F14, FreeText: 0x0F15, DeepTraversal: 0x0F17, LongId: 0x0F18, RebuildResults: 0x0F19, LessThan: 0x0F1A, GreaterThan: 0x0F1B, Schema: 0x0F1C, Supported: 0x0F1D, UserName: 0x0F1E, Password: 0x0F1F, ConversationId: 0x0F20, Picture: 0x0F21, MaxSize: 0x0F22, MaxPictures: 0x0F23, }, Enums: { Status: { Success: '1', InvalidRequest: '2', ServerError: '3', BadLink: '4', AccessDenied: '5', NotFound: '6', ConnectionFailure: '7', TooComplex: '8', Timeout: '10', SyncFolders: '11', EndOfRange: '12', AccessBlocked: '13', CredentialsRequired: '14', } } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/GAL',[], factory); else root.ASCPGAL = factory(); }(this, function() { 'use strict'; return { Tags: { DisplayName: 0x1005, Phone: 0x1006, Office: 0x1007, Title: 0x1008, Company: 0x1009, Alias: 0x100A, FirstName: 0x100B, LastName: 0x100C, HomePhone: 0x100D, MobilePhone: 0x100E, EmailAddress: 0x100F, Picture: 0x1010, Status: 0x1011, Data: 0x1012, } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Settings',[], factory); else root.ASCPSettings = factory(); }(this, function() { 'use strict'; return { Tags: { Settings: 0x1205, Status: 0x1206, Get: 0x1207, Set: 0x1208, Oof: 0x1209, OofState: 0x120A, StartTime: 0x120B, EndTime: 0x120C, OofMessage: 0x120D, AppliesToInternal: 0x120E, AppliesToExternalKnown: 0x120F, AppliesToExternalUnknown: 0x1210, Enabled: 0x1211, ReplyMessage: 0x1212, BodyType: 0x1213, DevicePassword: 0x1214, Password: 0x1215, DeviceInformation: 0x1216, Model: 0x1217, IMEI: 0x1218, FriendlyName: 0x1219, OS: 0x121A, OSLanguage: 0x121B, PhoneNumber: 0x121C, UserInformation: 0x121D, EmailAddresses: 0x121E, SmtpAddress: 0x121F, UserAgent: 0x1220, EnableOutboundSMS: 0x1221, MobileOperator: 0x1222, PrimarySmtpAddress: 0x1223, Accounts: 0x1224, Account: 0x1225, AccountId: 0x1226, AccountName: 0x1227, UserDisplayName: 0x1228, SendDisabled: 0x1229, /* Missing tag value 0x122A */ RightsManagementInformation: 0x122B, }, Enums: { Status: { Success: '1', ProtocolError: '2', AccessDenied: '3', ServerError: '4', InvalidArguments: '5', ConflictingArguments: '6', DeniedByPolicy: '7', }, OofState: { Disabled: '0', Global: '1', TimeBased: '2', } } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/DocumentLibrary',[], factory); else root.ASCPDocumentLibrary = factory(); }(this, function() { 'use strict'; return { Tags: { LinkId: 0x1305, DisplayName: 0x1306, IsFolder: 0x1307, CreationDate: 0x1308, LastModifiedDate: 0x1309, IsHidden: 0x130A, ContentLength: 0x130B, ContentType: 0x130C, }, }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Email2',[], factory); else root.ASCPEmail2 = factory(); }(this, function() { 'use strict'; return { Tags: { UmCallerID: 0x1605, UmUserNotes: 0x1606, UmAttDuration: 0x1607, UmAttOrder: 0x1608, ConversationId: 0x1609, ConversationIndex: 0x160A, LastVerbExecuted: 0x160B, LastVerbExecutionTime: 0x160C, ReceivedAsBcc: 0x160D, Sender: 0x160E, CalendarType: 0x160F, IsLeapMonth: 0x1610, AccountId: 0x1611, FirstDayOfWeek: 0x1612, MeetingMessageType: 0x1613, }, Enums: { LastVerbExecuted: { Unknown: '0', ReplyToSender: '1', ReplyToAll: '2', Forward: '3', }, CalendarType: { Default: '0', Gregorian: '1', GregorianUS: '2', Japan: '3', Taiwan: '4', Korea: '5', Hijri: '6', Thai: '7', Hebrew: '8', GregorianMeFrench: '9', GregorianArabic: '10', GregorianTranslatedEnglish: '11', GregorianTranslatedFrench: '12', JapaneseLunar: '14', ChineseLunar: '15', KoreanLunar: '20', }, FirstDayOfWeek: { Sunday: '0', Monday: '1', Tuesday: '2', Wednesday: '3', Thursday: '4', Friday: '5', Saturday: '6', }, MeetingMessageType: { Unspecified: '0', InitialRequest: '1', FullUpdate: '2', InformationalUpdate: '3', Outdated: '4', DelegatorsCopy: '5', Delegated: '6', } } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/Notes',[], factory); else root.ASCPNotes = factory(); }(this, function() { 'use strict'; return { Tags: { Subject: 0x1705, MessageClass: 0x1706, LastModifiedDate: 0x1707, Categories: 0x1708, Category: 0x1709, } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(); else if (typeof define === 'function' && define.amd) define('activesync/codepages/RightsManagement',[], factory); else root.ASCPRightsManagement = factory(); }(this, function() { 'use strict'; return { Tags: { RightsManagementSupport: 0x1805, RightsManagementTemplates: 0x1806, RightsManagementTemplate: 0x1807, RightsManagementLicense: 0x1808, EditAllowed: 0x1809, ReplyAllowed: 0x180A, ReplyAllAllowed: 0x180B, ForwardAllowed: 0x180C, ModifyRecipientsAllowed: 0x180D, ExtractAllowed: 0x180E, PrintAllowed: 0x180F, ExportAllowed: 0x1810, ProgrammaticAccessAllowed: 0x1811, Owner: 0x1812, ContentExpiryDate: 0x1813, TemplateID: 0x1814, TemplateName: 0x1815, TemplateDescription: 0x1816, ContentOwner: 0x1817, RemoveRightsManagementDistribution: 0x1818, } }; })); /* Copyright 2012 Mozilla Foundation * * 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 (root, factory) { if (typeof exports === 'object') module.exports = factory(require('wbxml'), require('activesync/codepages')); else if (typeof define === 'function' && define.amd) define('activesync/protocol',['wbxml', 'activesync/codepages'], factory); else root.ActiveSyncProtocol = factory(WBXML, ActiveSyncCodepages); }(this, function(WBXML, ASCP) { 'use strict'; var exports = {}; function nullCallback() {} /** * Create a constructor for a custom error type that works like a built-in * Error. * * @param name the string name of the error * @param parent (optional) a parent class for the error, defaults to Error * @param extraArgs an array of extra arguments that can be passed to the * constructor of this error type * @return the constructor for this error */ function makeError(name, parent, extraArgs) { function CustomError() { // Try to let users call this as CustomError(...) without the "new". This // is imperfect, and if you call this function directly and give it a // |this| that's a CustomError, things will break. Don't do it! var self = this instanceof CustomError ? this : Object.create(CustomError.prototype); var tmp = Error(); var offset = 1; self.stack = tmp.stack.substring(tmp.stack.indexOf('\n') + 1); self.message = arguments[0] || tmp.message; if (extraArgs) { offset += extraArgs.length; for (var i = 0; i < extraArgs.length; i++) self[extraArgs[i]] = arguments[i+1]; } var m = /@(.+):(.+)/.exec(self.stack); self.fileName = arguments[offset] || (m && m[1]) || ""; self.lineNumber = arguments[offset + 1] || (m && m[2]) || 0; return self; } CustomError.prototype = Object.create((parent || Error).prototype); CustomError.prototype.name = name; CustomError.prototype.constructor = CustomError; return CustomError; } var AutodiscoverError = makeError('ActiveSync.AutodiscoverError'); exports.AutodiscoverError = AutodiscoverError; var AutodiscoverDomainError = makeError('ActiveSync.AutodiscoverDomainError', AutodiscoverError); exports.AutodiscoverDomainError = AutodiscoverDomainError; var HttpError = makeError('ActiveSync.HttpError', null, ['status']); exports.HttpError = HttpError; function nsResolver(prefix) { var baseUrl = 'http://schemas.microsoft.com/exchange/autodiscover/'; var ns = { rq: baseUrl + 'mobilesync/requestschema/2006', ad: baseUrl + 'responseschema/2006', ms: baseUrl + 'mobilesync/responseschema/2006', }; return ns[prefix] || null; } function Version(str) { var details = str.split('.').map(function(x) { return parseInt(x); }); this.major = details[0], this.minor = details[1]; } exports.Version = Version; Version.prototype = { eq: function(other) { if (!(other instanceof Version)) other = new Version(other); return this.major === other.major && this.minor === other.minor; }, ne: function(other) { return !this.eq(other); }, gt: function(other) { if (!(other instanceof Version)) other = new Version(other); return this.major > other.major || (this.major === other.major && this.minor > other.minor); }, gte: function(other) { if (!(other instanceof Version)) other = new Version(other); return this.major >= other.major || (this.major === other.major && this.minor >= other.minor); }, lt: function(other) { return !this.gte(other); }, lte: function(other) { return !this.gt(other); }, toString: function() { return this.major + '.' + this.minor; }, }; /** * Set the Authorization header on an XMLHttpRequest. * * @param xhr the XMLHttpRequest * @param username the username * @param password the user's password */ function setAuthHeader(xhr, username, password) { var authorization = 'Basic ' + btoa(username + ':' + password); xhr.setRequestHeader('Authorization', authorization); } /** * Perform autodiscovery for the server associated with this account. * * @param aEmailAddress the user's email address * @param aPassword the user's password * @param aTimeout a timeout (in milliseconds) for the request * @param aCallback a callback taking an error status (if any) and the * server's configuration * @param aNoRedirect true if autodiscovery should *not* follow any * specified redirects (typically used when autodiscover has already * told us about a redirect) */ function autodiscover(aEmailAddress, aPassword, aTimeout, aCallback, aNoRedirect) { if (!aCallback) aCallback = nullCallback; var domain = aEmailAddress.substring(aEmailAddress.indexOf('@') + 1); // The first time we try autodiscovery, we should try to recover from // AutodiscoverDomainErrors and HttpErrors. The second time, *all* errors // should be reported to the callback. do_autodiscover(domain, aEmailAddress, aPassword, aTimeout, aNoRedirect, function(aError, aConfig) { if (aError instanceof AutodiscoverDomainError || aError instanceof HttpError) do_autodiscover('autodiscover.' + domain, aEmailAddress, aPassword, aTimeout, aNoRedirect, aCallback); else aCallback(aError, aConfig); }); } exports.autodiscover = autodiscover; /** * Perform the actual autodiscovery process for a given URL. * * @param aHost the host name to attempt autodiscovery for * @param aEmailAddress the user's email address * @param aPassword the user's password * @param aTimeout a timeout (in milliseconds) for the request * @param aNoRedirect true if autodiscovery should *not* follow any * specified redirects (typically used when autodiscover has already * told us about a redirect) * @param aCallback a callback taking an error status (if any) and the * server's configuration */ function do_autodiscover(aHost, aEmailAddress, aPassword, aTimeout, aNoRedirect, aCallback) { var xhr = new XMLHttpRequest({mozSystem: true, mozAnon: true}); xhr.open('POST', 'https://' + aHost + '/autodiscover/autodiscover.xml', true); setAuthHeader(xhr, aEmailAddress, aPassword); xhr.setRequestHeader('Content-Type', 'text/xml'); xhr.timeout = aTimeout; xhr.upload.onprogress = xhr.upload.onload = function() { xhr.timeout = 0; }; xhr.onload = function() { if (xhr.status < 200 || xhr.status >= 300) return aCallback(new HttpError(xhr.statusText, xhr.status)); var uid = Math.random(); self.postMessage({ uid: uid, type: 'configparser', cmd: 'accountactivesync', args: [xhr.responseText] }); self.addEventListener('message', function onworkerresponse(evt) { var data = evt.data; if (data.type != 'configparser' || data.cmd != 'accountactivesync' || data.uid != uid) { return; } self.removeEventListener(evt.type, onworkerresponse); var args = data.args; var config = args[0], error = args[1], redirectedEmail = args[2]; if (error) { aCallback(new AutodiscoverDomainError(error), config); } else if (redirectedEmail) { autodiscover(redirectedEmail, aPassword, aTimeout, aCallback, true); } else { aCallback(null, config); } }); }; xhr.ontimeout = xhr.onerror = function() { aCallback(new Error('Error getting Autodiscover URL')); }; // TODO: use something like // http://ejohn.org/blog/javascript-micro-templating/ here? var postdata = '<?xml version="1.0" encoding="utf-8"?>\n' + '<Autodiscover xmlns="' + nsResolver('rq') + '">\n' + ' <Request>\n' + ' <EMailAddress>' + aEmailAddress + '</EMailAddress>\n' + ' <AcceptableResponseSchema>' + nsResolver('ms') + '</AcceptableResponseSchema>\n' + ' </Request>\n' + '</Autodiscover>'; xhr.send(postdata); } /** * Create a new ActiveSync connection. * * ActiveSync connections use XMLHttpRequests to communicate with the * server. These XHRs are created with mozSystem: true and mozAnon: true to, * respectively, help with CORS, and to ignore the authentication cache. The * latter is important because 1) it prevents the HTTP auth dialog from * appearing if the user's credentials are wrong and 2) it allows us to * connect to the same server as multiple users. * * @param aDeviceId (optional) a string identifying this device * @param aDeviceType (optional) a string identifying the type of this device */ function Connection(aDeviceId, aDeviceType) { this._deviceId = aDeviceId || 'v140Device'; this._deviceType = aDeviceType || 'SmartPhone'; this.timeout = 0; this._connected = false; this._waitingForConnection = false; this._connectionError = null; this._connectionCallbacks = []; this.baseUrl = null; this._username = null; this._password = null; this.versions = []; this.supportedCommands = []; this.currentVersion = null; } exports.Connection = Connection; Connection.prototype = { /** * Perform any callbacks added during the connection process. * * @param aError the error status (if any) */ _notifyConnected: function(aError) { if (aError) this.disconnect(); for (var iter in Iterator(this._connectionCallbacks)) { var callback = iter[1]; callback.apply(callback, arguments); } this._connectionCallbacks = []; }, /** * Get the connection status. * * @return true iff we are fully connected to the server */ get connected() { return this._connected; }, /* * Initialize the connection with a server and account credentials. * * @param aServer the ActiveSync server to connect to * @param aUsername the account's username * @param aPassword the account's password */ open: function(aServer, aUsername, aPassword) { this.baseUrl = aServer + '/Microsoft-Server-ActiveSync'; this._username = aUsername; this._password = aPassword; }, /** * Connect to the server with this account by getting the OPTIONS from * the server (and verifying the account's credentials). * * @param aCallback a callback taking an error status (if any) and the * server's options. */ connect: function(aCallback) { // If we're already connected, just run the callback and return. if (this.connected) { if (aCallback) aCallback(null); return; } // Otherwise, queue this callback up to fire when we do connect. if (aCallback) this._connectionCallbacks.push(aCallback); // Don't do anything else if we're already trying to connect. if (this._waitingForConnection) return; this._waitingForConnection = true; this._connectionError = null; this.getOptions((function(aError, aOptions) { this._waitingForConnection = false; this._connectionError = aError; if (aError) { console.error('Error connecting to ActiveSync:', aError); return this._notifyConnected(aError, aOptions); } this._connected = true; this.versions = aOptions.versions; this.supportedCommands = aOptions.commands; this.currentVersion = new Version(aOptions.versions.slice(-1)[0]); return this._notifyConnected(null, aOptions); }).bind(this)); }, /** * Disconnect from the ActiveSync server, and reset the connection state. * The server and credentials remain set however, so you can safely call * connect() again immediately after. */ disconnect: function() { if (this._waitingForConnection) throw new Error("Can't disconnect while waiting for server response"); this._connected = false; this.versions = []; this.supportedCommands = []; this.currentVersion = null; }, /** * Attempt to provision this account. XXX: Currently, this doesn't actually * do anything, but it's useful as a test command for Gmail to ensure that * the user entered their password correctly. * * @param aCallback a callback taking an error status (if any) and the * WBXML response */ provision: function(aCallback) { var pv = ASCP.Provision.Tags; var w = new WBXML.Writer('1.3', 1, 'UTF-8'); w.stag(pv.Provision) .etag(); this.postCommand(w, aCallback); }, /** * Get the options for the server associated with this account. * * @param aCallback a callback taking an error status (if any), and the * resulting options. */ getOptions: function(aCallback) { if (!aCallback) aCallback = nullCallback; var conn = this; var xhr = new XMLHttpRequest({mozSystem: true, mozAnon: true}); xhr.open('OPTIONS', this.baseUrl, true); setAuthHeader(xhr, this._username, this._password); xhr.timeout = this.timeout; xhr.upload.onprogress = xhr.upload.onload = function() { xhr.timeout = 0; }; xhr.onload = function() { if (xhr.status < 200 || xhr.status >= 300) { console.error('ActiveSync options request failed with response ' + xhr.status); aCallback(new HttpError(xhr.statusText, xhr.status)); return; } var result = { versions: xhr.getResponseHeader('MS-ASProtocolVersions').split(','), commands: xhr.getResponseHeader('MS-ASProtocolCommands').split(','), }; aCallback(null, result); }; xhr.ontimeout = xhr.onerror = function() { var error = new Error('Error getting OPTIONS URL'); console.error(error); aCallback(error); }; // Set the response type to "text" so that we don't try to parse an empty // body as XML. xhr.responseType = 'text'; xhr.send(); }, /** * Check if the server supports a particular command. Requires that we be * connected to the server already. * * @param aCommand a string/tag representing the command type * @return true iff the command is supported */ supportsCommand: function(aCommand) { if (!this.connected) throw new Error('Connection required to get command'); if (typeof aCommand === 'number') aCommand = ASCP.__tagnames__[aCommand]; return this.supportedCommands.indexOf(aCommand) !== -1; }, /** * DEPRECATED. See postCommand() below. */ doCommand: function() { console.warn('doCommand is deprecated. Use postCommand instead.'); this.postCommand.apply(this, arguments); }, /** * Send a WBXML command to the ActiveSync server and listen for the * response. * * @param aCommand the WBXML representing the command or a string/tag * representing the command type for empty commands * @param aCallback a callback to call when the server has responded; takes * two arguments: an error status (if any) and the response as a * WBXML reader. If the server returned an empty response, the * response argument is null. * @param aExtraParams (optional) an object containing any extra URL * parameters that should be added to the end of the request URL * @param aExtraHeaders (optional) an object containing any extra HTTP * headers to send in the request * @param aProgressCallback (optional) a callback to invoke with progress * information, when available. Two arguments are provided: the * number of bytes received so far, and the total number of bytes * expected (when known, 0 if unknown). */ postCommand: function(aCommand, aCallback, aExtraParams, aExtraHeaders, aProgressCallback) { var contentType = 'application/vnd.ms-sync.wbxml'; if (typeof aCommand === 'string' || typeof aCommand === 'number') { this.postData(aCommand, contentType, null, aCallback, aExtraParams, aExtraHeaders); } else { var r = new WBXML.Reader(aCommand, ASCP); var commandName = r.document[0].localTagName; this.postData(commandName, contentType, aCommand.buffer, aCallback, aExtraParams, aExtraHeaders, aProgressCallback); } }, /** * Send arbitrary data to the ActiveSync server and listen for the response. * * @param aCommand a string (or WBXML tag) representing the command type * @param aContentType the content type of the post data * @param aData the data to be posted * @param aCallback a callback to call when the server has responded; takes * two arguments: an error status (if any) and the response as a * WBXML reader. If the server returned an empty response, the * response argument is null. * @param aExtraParams (optional) an object containing any extra URL * parameters that should be added to the end of the request URL * @param aExtraHeaders (optional) an object containing any extra HTTP * headers to send in the request * @param aProgressCallback (optional) a callback to invoke with progress * information, when available. Two arguments are provided: the * number of bytes received so far, and the total number of bytes * expected (when known, 0 if unknown). */ postData: function(aCommand, aContentType, aData, aCallback, aExtraParams, aExtraHeaders, aProgressCallback) { // Make sure our command name is a string. if (typeof aCommand === 'number') aCommand = ASCP.__tagnames__[aCommand]; if (!this.supportsCommand(aCommand)) { var error = new Error("This server doesn't support the command " + aCommand); console.error(error); aCallback(error); return; } // Build the URL parameters. var params = [ ['Cmd', aCommand], ['User', this._username], ['DeviceId', this._deviceId], ['DeviceType', this._deviceType] ]; if (aExtraParams) { for (var iter in Iterator(params)) { var param = iter[1]; if (param[0] in aExtraParams) throw new TypeError('reserved URL parameter found'); } for (var kv in Iterator(aExtraParams)) params.push(kv); } var paramsStr = params.map(function(i) { return encodeURIComponent(i[0]) + '=' + encodeURIComponent(i[1]); }).join('&'); // Now it's time to make our request! var xhr = new XMLHttpRequest({mozSystem: true, mozAnon: true}); xhr.open('POST', this.baseUrl + '?' + paramsStr, true); setAuthHeader(xhr, this._username, this._password); xhr.setRequestHeader('MS-ASProtocolVersion', this.currentVersion); xhr.setRequestHeader('Content-Type', aContentType); // Add extra headers if we have any. if (aExtraHeaders) { for (var iter in Iterator(aExtraHeaders)) { var key = iter[0], key = iter[1]; xhr.setRequestHeader(key, value); } } xhr.timeout = this.timeout; xhr.upload.onprogress = xhr.upload.onload = function() { xhr.timeout = 0; }; xhr.onprogress = function(event) { if (aProgressCallback) aProgressCallback(event.loaded, event.total); }; var conn = this; var parentArgs = arguments; xhr.onload = function() { // This status code is a proprietary Microsoft extension used to // indicate a redirect, not to be confused with the draft-standard // "Unavailable For Legal Reasons" status. More info available here: // <http://msdn.microsoft.com/en-us/library/gg651019.aspx> if (xhr.status === 451) { conn.baseUrl = xhr.getResponseHeader('X-MS-Location'); conn.postData.apply(conn, parentArgs); return; } if (xhr.status < 200 || xhr.status >= 300) { console.error('ActiveSync command ' + aCommand + ' failed with ' + 'response ' + xhr.status); aCallback(new HttpError(xhr.statusText, xhr.status)); return; } var response = null; if (xhr.response.byteLength > 0) response = new WBXML.Reader(new Uint8Array(xhr.response), ASCP); aCallback(null, response); }; xhr.ontimeout = xhr.onerror = function() { var error = new Error('Error getting command URL'); console.error(error); aCallback(error); }; xhr.responseType = 'arraybuffer'; xhr.send(aData); }, }; return exports; }));
sergecodd/FireFox-OS
B2G/gaia/apps/email/js/ext/mailapi/activesync/protocollayer.js
JavaScript
apache-2.0
98,854
/** * @license Copyright 2017 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. */ 'use strict'; /** * Manages drag and drop file input for the page. */ class DragAndDrop { /** * @param {function(!File)} fileHandlerCallback Invoked when the user chooses a new file. */ constructor(fileHandlerCallback) { this._dropZone = document.querySelector('.drop_zone'); this._fileHandlerCallback = fileHandlerCallback; this._dragging = false; this._addListeners(); } _addListeners() { // The mouseleave event is more reliable than dragleave when the user drops // the file outside the window. document.addEventListener('mouseleave', _ => { if (!this._dragging) { return; } this._resetDraggingUI(); }); document.addEventListener('dragover', e => { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; // Explicitly show as copy action. }); document.addEventListener('dragenter', _ => { this._dropZone.classList.add('dropping'); this._dragging = true; }); document.addEventListener('drop', e => { e.stopPropagation(); e.preventDefault(); this._resetDraggingUI(); // Note, this ignores multiple files in the drop, only taking the first. this._fileHandlerCallback(e.dataTransfer.files[0]); }); } _resetDraggingUI() { this._dropZone.classList.remove('dropping'); this._dragging = false; } } if (typeof module !== 'undefined' && module.exports) { module.exports = DragAndDrop; }
tkadlec/lighthouse
lighthouse-viewer/app/src/drag-and-drop.js
JavaScript
apache-2.0
2,079
import React from 'react'; import {Link} from 'react-router'; import '../../styles/about-page.css'; // Since this component is simple and static, there's no parent container for it. const AboutPage = () => { return ( <div> <h2 className="alt-header">About</h2> <p> This example app is part of the <a href="https://github.com/coryhouse/react-slingshot">React-Slingshot starter kit</a>. </p> <p> <Link to="/badlink">Click this bad link</Link> to see the 404 page. </p> </div> ); }; export default AboutPage;
Takaitra/RecipeRunt
web/src/components/pages/AboutPage.js
JavaScript
apache-2.0
574
/*global emp, cmapi */ // Register a channel handler for MAP_FEATURE_PLOT_URL. cmapi.channel.handler[cmapi.channel.names.MAP_FEATURE_PLOT_URL] = { // args will have a message and sender property process: function (args) { var featureTransaction, mapServiceTransaction, i, len, mapServiceItems = [], featureItems = [], message = args.message, sender = args.sender, payload, //schema, item, visible, layers, bUseProxy; // get schema for this channel // can use for channel specific validation // schema = cmapi.channel.schema["map.feature.plot.url"]; if (!Array.isArray(message.payload)) { message.payload = [message.payload]; } len = message.payload.length; // plot.url can load kml, geojson, and WMS. // // We need to handle WMS differently that kml and geojson // kml and geoJSON will use the typeLibrary.Feature // WMS will use typeLibrary.WMS // If the message has an array of payload we will check to see if it is mixed between // WMS and others. This is an edge case, but is valid according to CMAPI // for (i = 0; i < len; i = i + 1) { payload = message.payload[i]; item = {}; visible = true; layers = []; // determine if we need to use the proxy. bUseProxy = payload.useProxy; if ((payload.overlayId === undefined) || (payload.overlayId === null)) { payload.overlayId = sender.id; } visible = true; if (payload.visible !== undefined && payload.visible === false) { visible = false; } if (!payload.hasOwnProperty('format')) { payload.format = 'kml'; } switch (payload.format.toLowerCase()) { case "wms": if (payload.hasOwnProperty("params")) { if (payload.params.hasOwnProperty("layers")) { if (!emp.util.isEmptyString(payload.params.layers)) { layers = payload.params.layers.split(","); // We need to remove the layers parameter. delete payload.params["layers"]; } else if (Array.isArray(payload.params.layers)) { layers = payload.params.layers; delete payload.params.layers; } } } item = new emp.typeLibrary.WMS({ id: payload.featureId, overlayId: payload.overlayId, visible: visible, layers: layers, zoom: payload.zoom, name: payload.name, format: payload.format, url: payload.url, useProxy: bUseProxy, params: payload.params, transactionId: message.messageId, messageId: payload.messageId, intent: emp.intents.control.MAP_SERVICE_ADD }); mapServiceItems.push(item); break; case "wmts": item = new emp.typeLibrary.WMTS({ id: payload.featureId, overlayId: payload.overlayId, visible: visible, name: payload.name, layer: payload.layer, format: payload.format, url: payload.url, useProxy: bUseProxy, params: payload.params, transactionId: message.messageId, messageId: payload.messageId, intent: emp.intents.control.MAP_SERVICE_ADD }); mapServiceItems.push(item); break; case "kmllayer": item = new emp.typeLibrary.KmlLayer({ id: payload.featureId, overlayId: payload.overlayId, visible: visible, name: payload.name, kmlData: payload.kmlString, format: payload.format, url: payload.url, useProxy: bUseProxy, transactionId: message.messageId, messageId: payload.messageId, intent: emp.intents.control.MAP_SERVICE_ADD }); mapServiceItems.push(item); break; case "geojson": default: item = new emp.typeLibrary.Feature({ featureId: payload.featureId, parentId: payload.parentId, overlayId: payload.overlayId, visible: visible, zoom: payload.zoom, name: payload.name, format: payload.format, url: payload.url, params: payload.params, properties: payload.properties }); item.validate(); featureItems.push(item); break; } } if (featureItems.length > 0) { featureTransaction = new emp.typeLibrary.Transaction({ intent: emp.intents.control.FEATURE_ADD, mapInstanceId: args.mapInstanceId, transactionId: message.messageId, sender: sender.id, originChannel: cmapi.channel.names.MAP_FEATURE_PLOT_URL, source: emp.api.cmapi.SOURCE, originalMessage: args.originalMessage, messageOriginator: sender.id, originalMessageType: cmapi.channel.names.MAP_FEATURE_PLOT_URL, items: featureItems }); featureTransaction.queue(); } if (mapServiceItems.length > 0) { mapServiceTransaction = new emp.typeLibrary.Transaction({ intent: emp.intents.control.MAP_SERVICE_ADD, mapInstanceId: args.mapInstanceId, transactionId: message.messageId, sender: sender.id, originChannel: cmapi.channel.names.MAP_FEATURE_PLOT_URL, source: emp.api.cmapi.SOURCE, originalMessage: args.originalMessage, messageOriginator: sender.id, originalMessageType: cmapi.channel.names.MAP_FEATURE_PLOT_URL, items: mapServiceItems }); mapServiceTransaction.queue(); } } };
missioncommand/emp3-web
src/sdk/core/api/cmapi/channel/handler/map.feature.plot.url.js
JavaScript
apache-2.0
6,584
(function() { function config($stateProvider, $locationProvider) { $locationProvider .html5Mode({ enabled: true, requireBase: false }); $stateProvider .state('landing', { url: '/', controller: 'LandingCtrl as landing', templateUrl: '/templates/landing.html' }) .state('newroom', { url: '/', controller: 'NewRoomCtrl as newroom', templateUrl: '/templates/newroom.html' }) .state('login', { url: '/', controller: 'LoginCtrl as login', templateUrl: '/templates/login.html' }); } function BlocChatCookies($cookies,$uibModal) { if (!$cookies.blocChatCurrentUser || $cookies.blocChatCurrentUser === '') { this.animationsEnabled = true; $uibModal.open({ animation: this.animationsEnabled, backdrop: 'static', templateUrl: '/templates/login.html', size: "sm", controller: "LoginCtrl", controllerAs: "login", }); } } angular .module('blocChat',['ui.router','ui.bootstrap','firebase','ngCookies']) .config(config) .run(['$cookies','$uibModal', BlocChatCookies]); })();
smclaren727/bloc-chat
dist/scripts/app.js
JavaScript
apache-2.0
1,436
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DNSCache = exports.DNS_DEFAULT_EXPIRE = void 0; var _dns = _interopRequireDefault(require("dns")); var _net = _interopRequireDefault(require("net")); var _logger = require("./logger"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } async function lookup(hostname) { return new Promise((resolve, reject) => { _dns.default.lookup(hostname, function (err, address) { if (err) { reject(err); } else { resolve(address); } }); }); } function now() { return Date.now(); } const DNS_DEFAULT_EXPIRE = 3600000; exports.DNS_DEFAULT_EXPIRE = DNS_DEFAULT_EXPIRE; class DNSCache { static init(expire) { if (typeof expire === 'number' && expire >= 0) { DNSCache.expire = expire; } DNSCache.pool = {}; } static async get(hostname) { if (_net.default.isIP(hostname)) { return hostname; } let address = null; if (!DNSCache.pool[hostname]) { address = await lookup(hostname); DNSCache._put(hostname, address); } else { const [addr, expire] = DNSCache.pool[hostname]; const _now = now(); if (_now >= expire) { delete DNSCache.pool[hostname]; } _logger.logger.verbose(`[dns-cache] hit: hostname=${hostname} resolved=${addr} ttl=${expire - _now}ms`); address = addr; } return address; } static clear() { DNSCache.pool = {}; } static _put(hostname, address) { if (DNSCache.expire > 0) { const expire = now() + DNSCache.expire; DNSCache.pool[hostname] = [address, expire]; } } } exports.DNSCache = DNSCache; _defineProperty(DNSCache, "pool", {}); _defineProperty(DNSCache, "expire", DNS_DEFAULT_EXPIRE);
blinksocks/blinksocks
lib/utils/dns-cache.js
JavaScript
apache-2.0
2,047
'use strict'; var chai = require('chai'); require('chai-as-promised'); var should = chai.should(); var PouchDB = require('pouchdb-browser'); PouchDB.adapter('worker', require('../../client')); describe('custom api test suite', function () { this.timeout(180000); var db; before(function () { var worker = new Worker('/test/custom-api/worker-bundle.js'); db = new PouchDB('testdb', { adapter: 'worker', worker: function () { return worker; } }); }); after(function () { return db.destroy(); }); it('should exist', function () { should.exist(db); }); it('should be valid', function () { db.adapter.should.equal('worker'); }); it('should put() and get data', function () { return db.put({ _id: 'foo' }).then(function () { return db.get('foo'); }).then(function (doc) { doc._id.should.equal('foo'); return db.info(); }).then(function (info) { info.doc_count.should.equal(1); }); }); });
nolanlawson/worker-pouch
test/custom-api/test.js
JavaScript
apache-2.0
1,003
/* eslint-env jest */ import { actionReducer } from './utils' describe('actionReducer', () => { const counter = actionReducer(0, { INCREMENT (state, action) { return state + 1 }, DECREMENT (state, action) { return state - 1 }, SET_VALUE (state, action) { return action.value }, }) it('returns initial state on no action', () => { expect(counter(undefined, {})).toEqual(0) }) it('utilizes initial state for known action', () => { expect(counter(undefined, { type: 'INCREMENT' })).toEqual(1) }) it('utilizes current state for known action', () => { expect(counter(1, { type: 'INCREMENT' })).toEqual(2) expect(counter(4, { type: 'DECREMENT' })).toEqual(3) }) it('preserves state on unknown actions', () => { expect(counter(42, { type: 'UNKNOWN' })).toEqual(42) }) it('enables action handlers to consume action parameters', () => { expect(counter(5, { type: 'SET_VALUE', value: 7 })).toEqual(7) }) })
mareklibra/userportal
src/reducers/utils.test.js
JavaScript
apache-2.0
994
/** * @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. */ CLASS({ name: 'TooltipDemo', package: 'foam.ui.polymer.demo', extends: 'foam.ui.View', requires: [ 'foam.ui.polymer.demo.ElementWithTooltip', 'foam.ui.polymer.Tooltip' ], properties: [ { type: 'String', name: 'right', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'Right' }, { type: 'String', name: 'top', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'Top' }, { type: 'String', name: 'left', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'Left' }, { type: 'String', name: 'bottom', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'Bottom' }, { type: 'String', name: 'noArrow', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'NoArrow' }, { type: 'String', name: 'richText', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'RichText' }, { type: 'String', name: 'show', view: 'foam.ui.polymer.demo.ElementWithTooltip', defaultValue: 'Show' } ], templates: [ function toHTML() {/* <div class="centeredDiv"> $$top{ tooltipConfig: { text: 'Tooltip on the top', position: 'top' } } </div><div class="centeredDiv"> $$left{ tooltipConfig: { text: 'Tooltip on the left', position: 'left' } } </div><div class="centeredDiv"> $$right{ tooltipConfig: { text: 'Tooltip on the right', position: 'right' } } </div><div class="centeredDiv"> $$bottom{ tooltipConfig: { text: 'Tooltip on the bottom', position: 'bottom' } } </div><div class="centeredDiv"> $$noArrow{ tooltipConfig: { text: 'Tooltip without arrow', noarrow: true } } </div><div class="centeredDiv"> $$richText{ tooltipConfig: { html: 'Tooltip with <b>rich</b> <i>text</i>' } } </div><div class="centeredDiv"> $$show{ tooltipConfig: { text: 'Tooltip always shown', show: true } } </div> */}, function CSS() {/* .centeredDiv { cursor: pointer; width: 0; margin: 0 auto; } */} ] });
jlhughes/foam
js/foam/ui/polymer/demo/TooltipDemo.js
JavaScript
apache-2.0
3,019
// Backbone.Syphon.KeySplitter // --------------------------- // This function is used to split DOM element keys in to an array // of parts, which are then used to create a nested result structure. // returning `["foo", "bar"]` results in `{foo: { bar: "value" }}`. // // Override this method to use a custom key splitter, such as: // `<input name="foo.bar.baz">`, `return key.split(".")` Backbone.Syphon.KeySplitter = function(key){ var matches = key.match(/[^\[\]]+/g); if (key.indexOf("[]") === key.length - 2){ lastKey = matches.pop(); matches.push([lastKey]); } return matches; }
CenturyLinkCloud/EstimatorTCO
source/js/libs/backbone.syphon/src/backbone.syphon.keysplitter.js
JavaScript
apache-2.0
604
import * as THREE from 'three'; import STORE from 'store'; import { MAP_WS } from 'store/websocket'; import _ from 'lodash'; import { drawSegmentsFromPoints, drawDashedLineFromPoints, drawShapeFromPoints, } from 'utils/draw'; import Text3D, { TEXT_ALIGN } from 'renderer/text3d'; import TrafficSigns from 'renderer/traffic_controls/traffic_signs'; import TrafficSignals from 'renderer/traffic_controls/traffic_signals'; import stopSignMaterial from 'assets/models/stop_sign.mtl'; import stopSignObject from 'assets/models/stop_sign.obj'; import yieldSignMaterial from 'assets/models/yield_sign.mtl'; import yieldSignObject from 'assets/models/yield_sign.obj'; const STOP_SIGN_SCALE = 0.01; const YIELD_SIGN_SCALE = 1.5; const colorMapping = { YELLOW: 0XDAA520, WHITE: 0xCCCCCC, CORAL: 0xFF7F50, RED: 0xFF6666, GREEN: 0x006400, BLUE: 0x30A5FF, PURE_WHITE: 0xFFFFFF, DEFAULT: 0xC0C0C0, }; export default class Map { constructor() { this.textRender = new Text3D(); this.hash = -1; this.data = {}; this.initialized = false; this.elementKindsDrawn = ''; this.trafficSignals = new TrafficSignals(); this.stopSigns = new TrafficSigns( stopSignMaterial, stopSignObject, STOP_SIGN_SCALE, ); this.yieldSigns = new TrafficSigns( yieldSignMaterial, yieldSignObject, YIELD_SIGN_SCALE, ); this.zOffsetFactor = 1; } // The result will be the all the elements in current but not in data. diffMapElements(elementIds, data) { const result = {}; let empty = true; for (const kind in elementIds) { if (!this.shouldDrawObjectOfThisElementKind(kind)) { continue; } result[kind] = []; const newIds = elementIds[kind]; const oldData = data[kind]; for (let i = 0; i < newIds.length; ++i) { const found = oldData ? oldData.find((old) => old.id.id === newIds[i]) : false; if (!found) { empty = false; result[kind].push(newIds[i]); } } } return empty ? {} : result; } addLaneMesh(laneType, points) { switch (laneType) { case 'DOTTED_YELLOW': return drawDashedLineFromPoints( points, colorMapping.YELLOW, 4, 3, 3, this.zOffsetFactor, 1, false, ); case 'DOTTED_WHITE': return drawDashedLineFromPoints( points, colorMapping.WHITE, 2, 0.5, 0.25, this.zOffsetFactor, 0.4, false, ); case 'SOLID_YELLOW': return drawSegmentsFromPoints( points, colorMapping.YELLOW, 3, this.zOffsetFactor, false, ); case 'SOLID_WHITE': return drawSegmentsFromPoints( points, colorMapping.WHITE, 3, this.zOffsetFactor, false, ); case 'DOUBLE_YELLOW': const left = drawSegmentsFromPoints( points, colorMapping.YELLOW, 2, this.zOffsetFactor, false, ); const right = drawSegmentsFromPoints( points.map((point) => new THREE.Vector3(point.x + 0.3, point.y + 0.3, point.z)), colorMapping.YELLOW, 3, this.zOffsetFactor, false, ); left.add(right); return left; case 'CURB': return drawSegmentsFromPoints( points, colorMapping.CORAL, 3, this.zOffsetFactor, false, ); default: return drawSegmentsFromPoints( points, colorMapping.DEFAULT, 3, this.zOffsetFactor, false, ); } } addLane(lane, coordinates, scene) { const drewObjects = []; const centralLine = lane.centralCurve.segment; centralLine.forEach((segment) => { const points = coordinates.applyOffsetToArray(segment.lineSegment.point); const centerLine = drawSegmentsFromPoints( points, colorMapping.GREEN, 1, this.zOffsetFactor, false); centerLine.name = `CentralLine-${lane.id.id}`; scene.add(centerLine); drewObjects.push(centerLine); }); const rightLaneType = lane.rightBoundary.boundaryType[0].types[0]; // TODO: this is a temp. fix for repeated boundary types. lane.rightBoundary.curve.segment.forEach((segment, index) => { const points = coordinates.applyOffsetToArray(segment.lineSegment.point); const boundary = this.addLaneMesh(rightLaneType, points); boundary.name = `RightBoundary-${lane.id.id}`; scene.add(boundary); drewObjects.push(boundary); }); const leftLaneType = lane.leftBoundary.boundaryType[0].types[0]; lane.leftBoundary.curve.segment.forEach((segment, index) => { const points = coordinates.applyOffsetToArray(segment.lineSegment.point); const boundary = this.addLaneMesh(leftLaneType, points); boundary.name = `LeftBoundary-${lane.id.id}`; scene.add(boundary); drewObjects.push(boundary); }); return drewObjects; } addLaneId(lane, coordinates, scene) { const centralLine = lane.centralCurve.segment; let position = _.get(centralLine, '[0].startPosition'); if (position) { position.z = 0.04; position = coordinates.applyOffset(position); } const rotation = { x: 0.0, y: 0.0, z: 0.0 }; const points = _.get(centralLine, '[0].lineSegment.point', []); if (points.length >= 2) { const p1 = points[0]; const p2 = points[1]; rotation.z = Math.atan2(p2.y - p1.y, p2.x - p1.x); } const text = this.textRender.drawText( lane.id.id, scene, colorMapping.WHITE, TEXT_ALIGN.LEFT, ); if (text) { const textPosition = position || _.get(points, '[0]'); if (textPosition) { text.position.set(textPosition.x, textPosition.y, textPosition.z); text.rotation.set(rotation.x, rotation.y, rotation.z); } text.visible = false; scene.add(text); } return text; } addRoad(road, coordinates, scene) { const drewObjects = []; road.section.forEach((section) => { section.boundary.outerPolygon.edge.forEach((edge) => { edge.curve.segment.forEach((segment, index) => { const points = coordinates.applyOffsetToArray(segment.lineSegment.point); const boundary = this.addLaneMesh('CURB', points); boundary.name = `Road-${road.id.id}`; scene.add(boundary); drewObjects.push(boundary); }); }); }); return drewObjects; } addBorder(borderPolygon, color, coordinates, scene) { const drewObjects = []; const border = coordinates.applyOffsetToArray(borderPolygon.polygon.point); border.push(border[0]); const mesh = drawSegmentsFromPoints( border, color, 2, this.zOffsetFactor, true, false, 1.0, ); scene.add(mesh); drewObjects.push(mesh); return drewObjects; } addParkingSpaceId(parkingSpace, coordinates, scene) { const text = this.textRender.drawText(parkingSpace.id.id, scene, colorMapping.WHITE); const points = _.get(parkingSpace, 'polygon.point'); if (points && points.length >= 3 && text) { const point1 = points[0]; const point2 = points[1]; const point3 = points[2]; let textPosition = { x: (point1.x + point3.x) / 2, y: (point1.y + point3.y) / 2, z: 0.04, }; textPosition = coordinates.applyOffset(textPosition); const textRotationZ = Math.atan2(point2.y - point1.y, point2.x - point1.x); text.position.set(textPosition.x, textPosition.y, textPosition.z); text.rotation.set(0, 0, textRotationZ); text.visible = false; scene.add(text); } return text; } addZone(zone, color, coordinates, scene) { const drewObjects = []; const border = coordinates.applyOffsetToArray(zone.polygon.point); border.push(border[0]); const zoneMaterial = new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.15, }); const zoneShape = drawShapeFromPoints( border, zoneMaterial, false, this.zOffsetFactor * 3, false, ); scene.add(zoneShape); drewObjects.push(zoneShape); const mesh = drawSegmentsFromPoints( border, color, 2, this.zOffsetFactor, true, false, 1.0, ); scene.add(mesh); drewObjects.push(mesh); return drewObjects; } addCurve(lines, color, coordinates, scene) { const drewObjects = []; lines.forEach((line) => { line.segment.forEach((segment) => { const points = coordinates.applyOffsetToArray(segment.lineSegment.point); const mesh = drawSegmentsFromPoints( points, color, 5, this.zOffsetFactor * 2, false, ); scene.add(mesh); drewObjects.push(mesh); }); }); return drewObjects; } addStopLine(stopLine, coordinates, scene) { const drewObjects = this.addCurve( stopLine, colorMapping.PURE_WHITE, coordinates, scene, ); return drewObjects; } removeDrewText(textMesh, scene) { if (textMesh) { textMesh.children.forEach((c) => c.visible = false); scene.remove(textMesh); } } removeDrewObjects(drewObjects, scene) { if (drewObjects) { drewObjects.forEach((object) => { scene.remove(object); if (object.geometry) { object.geometry.dispose(); } if (object.material) { object.material.dispose(); } }); } } removeAllElements(scene) { this.removeExpiredElements([], scene); this.trafficSignals.removeAll(scene); this.stopSigns.removeAll(scene); this.yieldSigns.removeAll(scene); } removeExpiredElements(elementIds, scene) { const newData = {}; for (const kind in this.data) { const drawThisKind = this.shouldDrawObjectOfThisElementKind(kind); newData[kind] = []; const oldDataOfThisKind = this.data[kind]; const currentIds = elementIds[kind]; oldDataOfThisKind.forEach((oldData) => { if (drawThisKind && currentIds && currentIds.includes(oldData.id.id)) { newData[kind].push(oldData); } else { this.removeDrewObjects(oldData.drewObjects, scene); this.removeDrewText(oldData.text, scene); } }); } this.data = newData; } // I do not want to do premature optimization either. Should the // performance become an issue, all the diff should be done at the server // side. This also means that the server should maintain a state of // (possibly) visible elements, presummably in the global store. appendMapData(newData, coordinates, scene) { for (const kind in newData) { if (!newData[kind]) { continue; } if (!this.data[kind]) { this.data[kind] = []; } for (let i = 0; i < newData[kind].length; ++i) { switch (kind) { case 'lane': const lane = newData[kind][i]; this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addLane(lane, coordinates, scene), text: this.addLaneId(lane, coordinates, scene), })); break; case 'clearArea': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addZone( newData[kind][i], colorMapping.YELLOW, coordinates, scene, ), })); break; case 'crosswalk': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addZone( newData[kind][i], colorMapping.PURE_WHITE, coordinates, scene, ), })); break; case 'junction': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addBorder( newData[kind][i], colorMapping.BLUE, coordinates, scene, ), })); break; case 'pncJunction': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addZone( newData[kind][i], colorMapping.BLUE, coordinates, scene, ), })); break; case 'signal': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addStopLine( newData[kind][i].stopLine, coordinates, scene, ), })); this.trafficSignals.add([newData[kind][i]], coordinates, scene); break; case 'stopSign': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addStopLine( newData[kind][i].stopLine, coordinates, scene, ), })); this.stopSigns.add([newData[kind][i]], coordinates, scene); break; case 'yield': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addStopLine( newData[kind][i].stopLine, coordinates, scene, ), })); this.yieldSigns.add([newData[kind][i]], coordinates, scene); break; case 'road': const road = newData[kind][i]; this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addRoad(road, coordinates, scene), })); break; case 'parkingSpace': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addBorder( newData[kind][i], colorMapping.YELLOW, coordinates, scene, ), text: this.addParkingSpaceId(newData[kind][i], coordinates, scene), })); break; case 'speedBump': this.data[kind].push(Object.assign(newData[kind][i], { drewObjects: this.addCurve( newData[kind][i].position, colorMapping.RED, coordinates, scene, ), })); break; default: this.data[kind].push(newData[kind][i]); break; } } } } shouldDrawObjectOfThisElementKind(kind) { // Ex: mapping 'lane' to 'showMapLane' option const optionName = `showMap${kind[0].toUpperCase()}${kind.slice(1)}`; // NOTE: return true if the option is not found return STORE.options[optionName] !== false; } shouldDrawTextOfThisElementKind(kind) { // showMapLaneId option controls both laneId and parkingSpaceId return STORE.options.showMapLaneId && ['parkingSpace', 'lane'].includes(kind); } updateText() { for (const kind in this.data) { const isVisible = this.shouldDrawTextOfThisElementKind(kind); this.data[kind].forEach((element) => { if (element.text) { element.text.visible = isVisible; } }); } } updateIndex(hash, elementIds, scene) { if (STORE.hmi.inNavigationMode) { MAP_WS.requestRelativeMapData(); } else { this.updateText(); let newElementKindsDrawn = ''; for (const kind of Object.keys(elementIds).sort()) { if (this.shouldDrawObjectOfThisElementKind(kind)) { newElementKindsDrawn += kind; } } if (hash !== this.hash || this.elementKindsDrawn !== newElementKindsDrawn) { this.hash = hash; this.elementKindsDrawn = newElementKindsDrawn; const diff = this.diffMapElements(elementIds, this.data); if (!_.isEmpty(diff) || !this.initialized) { MAP_WS.requestMapData(diff); this.initialized = true; } this.removeExpiredElements(elementIds, scene); if (!this.shouldDrawObjectOfThisElementKind('signal')) { this.trafficSignals.removeAll(scene); } else { this.trafficSignals.removeExpired(elementIds.signal, scene); } if (!this.shouldDrawObjectOfThisElementKind('stopSign')) { this.stopSigns.removeAll(scene); } else { this.stopSigns.removeExpired(elementIds.stopSign, scene); } if (!this.shouldDrawObjectOfThisElementKind('yield')) { this.yieldSigns.removeAll(scene); } else { this.yieldSigns.removeExpired(elementIds.yield, scene); } } } // Do not set zOffset in camera view, since zOffset will affect the accuracy of matching // between hdmap and camera image this.zOffsetFactor = STORE.options.showCameraView ? 0 : 1; } update(world) { this.trafficSignals.updateTrafficLightStatus(world.perceivedSignal); } }
xiaoxq/apollo
modules/dreamview/frontend/src/renderer/map.js
JavaScript
apache-2.0
16,450
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { settings } from 'carbon-components'; import ListBulleted16 from '@carbon/icons-react/lib/list--bulleted/16'; import Grid16 from '@carbon/icons-react/lib/grid/16'; const { prefix } = settings; /** * The layout button for `<Search>`. */ class SearchLayoutButton extends Component { state = { format: 'list' }; static propTypes = { /** * The layout. */ format: PropTypes.oneOf(['list', 'grid']), /** * The a11y label text. */ labelText: PropTypes.string, /** * The description for the "list" icon. */ iconDescriptionList: PropTypes.string, /** * The description for the "grid" icon. */ iconDescriptionGrid: PropTypes.string, /** * The callback called when layout switches. */ onChangeFormat: PropTypes.func, }; static defaultProps = { labelText: 'Filter', iconDescriptionList: 'list', iconDescriptionGrid: 'grid', }; static getDerivedStateFromProps({ format }, state) { const { prevFormat } = state; return prevFormat === format ? null : { format: format || 'list', prevFormat: format, }; } /** * Toggles the button state upon user-initiated event. */ toggleLayout = () => { const format = this.state.format === 'list' ? 'grid' : 'list'; this.setState({ format }, () => { const { onChangeFormat } = this.props; if (typeof onChangeFormat === 'function') { onChangeFormat({ format }); } }); }; render() { const { labelText, iconDescriptionList, iconDescriptionGrid } = this.props; const SearchLayoutButtonIcon = () => { if (this.state.format === 'list') { return ( <ListBulleted16 className={`${prefix}--search-view`} aria-label={iconDescriptionList} /> ); } return ( <Grid16 className={`${prefix}--search-view`} aria-label={iconDescriptionGrid} /> ); }; return ( <button className={`${prefix}--search-button`} type="button" onClick={this.toggleLayout} aria-label={labelText} title={labelText}> <div className={`${prefix}--search__toggle-layout__container`}> <SearchLayoutButtonIcon /> </div> </button> ); } } export default SearchLayoutButton;
carbon-design-system/carbon-components-react
src/components/SearchLayoutButton/SearchLayoutButton.js
JavaScript
apache-2.0
2,657
alert("XSS from JS file");
datla/JavaSecurity
xss/src/main/webapp/alert.js
JavaScript
apache-2.0
26
sap.ui.define([ 'jquery.sap.global', 'sap/ui/core/Fragment', 'sap/ui/core/mvc/Controller', 'sap/ui/model/Filter', 'sap/ui/model/json/JSONModel' ], function(jQuery, Fragment, Controller, Filter, JSONModel) { "use strict"; var CController = Controller.extend("sap.m.sample.InputAssistedTwoValues.C", { inputId: '', onInit: function () { // set explored app's demo model on this sample var oModel = new JSONModel(jQuery.sap.getModulePath("sap.ui.demo.mock", "/products.json")); this.getView().setModel(oModel); }, handleValueHelp : function (oController) { this.inputId = oController.oSource.sId; // create value help dialog if (!this._valueHelpDialog) { this._valueHelpDialog = sap.ui.xmlfragment( "sap.m.sample.InputAssistedTwoValues.Dialog", this ); this.getView().addDependent(this._valueHelpDialog); } // open value help dialog this._valueHelpDialog.open(); }, _handleValueHelpSearch : function (evt) { var sValue = evt.getParameter("value"); var oFilter = new Filter( "Name", sap.ui.model.FilterOperator.Contains, sValue ); evt.getSource().getBinding("items").filter([oFilter]); }, _handleValueHelpClose : function (evt) { var oSelectedItem = evt.getParameter("selectedItem"); if (oSelectedItem) { var productInput = this.byId(this.inputId); productInput.setValue(oSelectedItem.getTitle()); } evt.getSource().getBinding("items").filter([]); } }); return CController; });
SQCLabs/openui5
src/sap.m/test/sap/m/demokit/sample/InputAssistedTwoValues/C.controller.js
JavaScript
apache-2.0
1,505
/** * @class Ext.ClassManager * * @author Jacky Nguyen <[email protected]> * @aside guide class_system * @aside video class-system * * Ext.ClassManager manages all classes and handles mapping from string class name to * actual class objects throughout the whole framework. It is not generally accessed directly, rather through * these convenient shorthands: * * - {@link Ext#define Ext.define} * - {@link Ext#create Ext.create} * - {@link Ext#widget Ext.widget} * - {@link Ext#getClass Ext.getClass} * - {@link Ext#getClassName Ext.getClassName} * * ## Basic syntax: * * Ext.define(className, properties); * * in which `properties` is an object represent a collection of properties that apply to the class. See * {@link Ext.ClassManager#create} for more detailed instructions. * * Ext.define('Person', { * name: 'Unknown', * * constructor: function(name) { * if (name) { * this.name = name; * } * * return this; * }, * * eat: function(foodType) { * alert("I'm eating: " + foodType); * * return this; * } * }); * * var aaron = new Person("Aaron"); * aaron.eat("Sandwich"); // alert("I'm eating: Sandwich"); * * Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of * everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc. * * ## Inheritance: * * Ext.define('Developer', { * extend: 'Person', * * constructor: function(name, isGeek) { * this.isGeek = isGeek; * * // Apply a method from the parent class' prototype * this.callParent([name]); * * return this; * * }, * * code: function(language) { * alert("I'm coding in: " + language); * * this.eat("Bugs"); * * return this; * } * }); * * var jacky = new Developer("Jacky", true); * jacky.code("JavaScript"); // alert("I'm coding in: JavaScript"); * // alert("I'm eating: Bugs"); * * See {@link Ext.Base#callParent} for more details on calling superclass' methods * * ## Mixins: * * Ext.define('CanPlayGuitar', { * playGuitar: function() { * alert("F#...G...D...A"); * } * }); * * Ext.define('CanComposeSongs', { * composeSongs: function() { } * }); * * Ext.define('CanSing', { * sing: function() { * alert("I'm on the highway to hell...") * } * }); * * Ext.define('Musician', { * extend: 'Person', * * mixins: { * canPlayGuitar: 'CanPlayGuitar', * canComposeSongs: 'CanComposeSongs', * canSing: 'CanSing' * } * }) * * Ext.define('CoolPerson', { * extend: 'Person', * * mixins: { * canPlayGuitar: 'CanPlayGuitar', * canSing: 'CanSing' * }, * * sing: function() { * alert("Ahem...."); * * this.mixins.canSing.sing.call(this); * * alert("[Playing guitar at the same time...]"); * * this.playGuitar(); * } * }); * * var me = new CoolPerson("Jacky"); * * me.sing(); // alert("Ahem..."); * // alert("I'm on the highway to hell..."); * // alert("[Playing guitar at the same time...]"); * // alert("F#...G...D...A"); * * ## Config: * * Ext.define('SmartPhone', { * config: { * hasTouchScreen: false, * operatingSystem: 'Other', * price: 500 * }, * * isExpensive: false, * * constructor: function(config) { * this.initConfig(config); * * return this; * }, * * applyPrice: function(price) { * this.isExpensive = (price > 500); * * return price; * }, * * applyOperatingSystem: function(operatingSystem) { * if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) { * return 'Other'; * } * * return operatingSystem; * } * }); * * var iPhone = new SmartPhone({ * hasTouchScreen: true, * operatingSystem: 'iOS' * }); * * iPhone.getPrice(); // 500; * iPhone.getOperatingSystem(); // 'iOS' * iPhone.getHasTouchScreen(); // true; * * iPhone.isExpensive; // false; * iPhone.setPrice(600); * iPhone.getPrice(); // 600 * iPhone.isExpensive; // true; * * iPhone.setOperatingSystem('AlienOS'); * iPhone.getOperatingSystem(); // 'Other' * * ## Statics: * * Ext.define('Computer', { * statics: { * factory: function(brand) { * // 'this' in static methods refer to the class itself * return new this(brand); * } * }, * * constructor: function() { } * }); * * var dellComputer = Computer.factory('Dell'); * * Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing * static properties within class methods * * @singleton */ (function(Class, alias, arraySlice, arrayFrom, global) { //<if nonBrowser> var isNonBrowser = typeof window == 'undefined'; //</if> var Manager = Ext.ClassManager = { /** * @property classes * @type Object * All classes which were defined through the ClassManager. Keys are the * name of the classes and the values are references to the classes. * @private */ classes: {}, /** * @private */ existCache: {}, /** * @private */ namespaceRewrites: [{ from: 'Ext.', to: Ext }], /** * @private */ maps: { alternateToName: {}, aliasToName: {}, nameToAliases: {}, nameToAlternates: {} }, /** @private */ enableNamespaceParseCache: true, /** @private */ namespaceParseCache: {}, /** @private */ instantiators: [], /** * Checks if a class has already been created. * * @param {String} className * @return {Boolean} exist */ isCreated: function(className) { var existCache = this.existCache, i, ln, part, root, parts; //<debug error> if (typeof className != 'string' || className.length < 1) { throw new Error("[Ext.ClassManager] Invalid classname, must be a string and must not be empty"); } //</debug> if (this.classes[className] || existCache[className]) { return true; } root = global; parts = this.parseNamespace(className); for (i = 0, ln = parts.length; i < ln; i++) { part = parts[i]; if (typeof part != 'string') { root = part; } else { if (!root || !root[part]) { return false; } root = root[part]; } } existCache[className] = true; this.triggerCreated(className); return true; }, /** * @private */ createdListeners: [], /** * @private */ nameCreatedListeners: {}, /** * @private */ triggerCreated: function(className) { var listeners = this.createdListeners, nameListeners = this.nameCreatedListeners, alternateNames = this.maps.nameToAlternates[className], names = [className], i, ln, j, subLn, listener, name; for (i = 0,ln = listeners.length; i < ln; i++) { listener = listeners[i]; listener.fn.call(listener.scope, className); } if (alternateNames) { names.push.apply(names, alternateNames); } for (i = 0,ln = names.length; i < ln; i++) { name = names[i]; listeners = nameListeners[name]; if (listeners) { for (j = 0,subLn = listeners.length; j < subLn; j++) { listener = listeners[j]; listener.fn.call(listener.scope, name); } delete nameListeners[name]; } } }, /** * @private */ onCreated: function(fn, scope, className) { var listeners = this.createdListeners, nameListeners = this.nameCreatedListeners, listener = { fn: fn, scope: scope }; if (className) { if (this.isCreated(className)) { fn.call(scope, className); return; } if (!nameListeners[className]) { nameListeners[className] = []; } nameListeners[className].push(listener); } else { listeners.push(listener); } }, /** * Supports namespace rewriting * @private */ parseNamespace: function(namespace) { //<debug error> if (typeof namespace != 'string') { throw new Error("[Ext.ClassManager] Invalid namespace, must be a string"); } //</debug> var cache = this.namespaceParseCache; if (this.enableNamespaceParseCache) { if (cache.hasOwnProperty(namespace)) { return cache[namespace]; } } var parts = [], rewrites = this.namespaceRewrites, root = global, name = namespace, rewrite, from, to, i, ln; for (i = 0, ln = rewrites.length; i < ln; i++) { rewrite = rewrites[i]; from = rewrite.from; to = rewrite.to; if (name === from || name.substring(0, from.length) === from) { name = name.substring(from.length); if (typeof to != 'string') { root = to; } else { parts = parts.concat(to.split('.')); } break; } } parts.push(root); parts = parts.concat(name.split('.')); if (this.enableNamespaceParseCache) { cache[namespace] = parts; } return parts; }, /** * Creates a namespace and assign the `value` to the created object * * Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject); * alert(MyCompany.pkg.Example === someObject); // alerts true * * @param {String} name * @param {Mixed} value */ setNamespace: function(name, value) { var root = global, parts = this.parseNamespace(name), ln = parts.length - 1, leaf = parts[ln], i, part; for (i = 0; i < ln; i++) { part = parts[i]; if (typeof part != 'string') { root = part; } else { if (!root[part]) { root[part] = {}; } root = root[part]; } } root[leaf] = value; return root[leaf]; }, /** * The new Ext.ns, supports namespace rewriting * @private */ createNamespaces: function() { var root = global, parts, part, i, j, ln, subLn; for (i = 0, ln = arguments.length; i < ln; i++) { parts = this.parseNamespace(arguments[i]); for (j = 0, subLn = parts.length; j < subLn; j++) { part = parts[j]; if (typeof part != 'string') { root = part; } else { if (!root[part]) { root[part] = {}; } root = root[part]; } } } return root; }, /** * Sets a name reference to a class. * * @param {String} name * @param {Object} value * @return {Ext.ClassManager} this */ set: function(name, value) { var me = this, maps = me.maps, nameToAlternates = maps.nameToAlternates, targetName = me.getName(value), alternates; me.classes[name] = me.setNamespace(name, value); if (targetName && targetName !== name) { maps.alternateToName[name] = targetName; alternates = nameToAlternates[targetName] || (nameToAlternates[targetName] = []); alternates.push(name); } return this; }, /** * Retrieve a class by its name. * * @param {String} name * @return {Ext.Class} class */ get: function(name) { var classes = this.classes; if (classes[name]) { return classes[name]; } var root = global, parts = this.parseNamespace(name), part, i, ln; for (i = 0, ln = parts.length; i < ln; i++) { part = parts[i]; if (typeof part != 'string') { root = part; } else { if (!root || !root[part]) { return null; } root = root[part]; } } return root; }, /** * Register the alias for a class. * * @param {Ext.Class/String} cls a reference to a class or a className * @param {String} alias Alias to use when referring to this class */ setAlias: function(cls, alias) { var aliasToNameMap = this.maps.aliasToName, nameToAliasesMap = this.maps.nameToAliases, className; if (typeof cls == 'string') { className = cls; } else { className = this.getName(cls); } if (alias && aliasToNameMap[alias] !== className) { //<debug info> if (aliasToNameMap[alias]) { Ext.Logger.info("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " + "of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional."); } //</debug> aliasToNameMap[alias] = className; } if (!nameToAliasesMap[className]) { nameToAliasesMap[className] = []; } if (alias) { Ext.Array.include(nameToAliasesMap[className], alias); } return this; }, /** * Get a reference to the class by its alias. * * @param {String} alias * @return {Ext.Class} class */ getByAlias: function(alias) { return this.get(this.getNameByAlias(alias)); }, /** * Get the name of a class by its alias. * * @param {String} alias * @return {String} className */ getNameByAlias: function(alias) { return this.maps.aliasToName[alias] || ''; }, /** * Get the name of a class by its alternate name. * * @param {String} alternate * @return {String} className */ getNameByAlternate: function(alternate) { return this.maps.alternateToName[alternate] || ''; }, /** * Get the aliases of a class by the class name * * @param {String} name * @return {Array} aliases */ getAliasesByName: function(name) { return this.maps.nameToAliases[name] || []; }, /** * Get the name of the class by its reference or its instance; * usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName} * Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action" * @param {Ext.Class/Object} object * @return {String} className * @markdown */ getName: function(object) { return object && object.$className || ''; }, /** * Get the class of the provided object; returns null if it's not an instance * of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass} * * var component = new Ext.Component(); * * Ext.ClassManager.getClass(component); // returns Ext.Component * * @param {Object} object * @return {Ext.Class} class */ getClass: function(object) { return object && object.self || null; }, /** * @private */ create: function(className, data, createdFn) { //<debug error> if (typeof className != 'string') { throw new Error("[Ext.define] Invalid class name '" + className + "' specified, must be a non-empty string"); } //</debug> data.$className = className; return new Class(data, function() { var postprocessorStack = data.postprocessors || Manager.defaultPostprocessors, registeredPostprocessors = Manager.postprocessors, index = 0, postprocessors = [], postprocessor, process, i, ln, j, subLn, postprocessorProperties, postprocessorProperty; delete data.postprocessors; for (i = 0,ln = postprocessorStack.length; i < ln; i++) { postprocessor = postprocessorStack[i]; if (typeof postprocessor == 'string') { postprocessor = registeredPostprocessors[postprocessor]; postprocessorProperties = postprocessor.properties; if (postprocessorProperties === true) { postprocessors.push(postprocessor.fn); } else if (postprocessorProperties) { for (j = 0,subLn = postprocessorProperties.length; j < subLn; j++) { postprocessorProperty = postprocessorProperties[j]; if (data.hasOwnProperty(postprocessorProperty)) { postprocessors.push(postprocessor.fn); break; } } } } else { postprocessors.push(postprocessor); } } process = function(clsName, cls, clsData) { postprocessor = postprocessors[index++]; if (!postprocessor) { Manager.set(className, cls); if (createdFn) { createdFn.call(cls, cls); } Manager.triggerCreated(className); return; } if (postprocessor.call(this, clsName, cls, clsData, process) !== false) { process.apply(this, arguments); } }; process.call(Manager, className, this, data); }); }, createOverride: function(className, data) { var overriddenClassName = data.override; delete data.override; this.existCache[className] = true; // Override the target class right after it's created this.onCreated(function() { this.get(overriddenClassName).override(data); // This push the overridding file itself into Ext.Loader.history // Hence if the target class never exists, the overriding file will // never be included in the build this.triggerCreated(className); }, this, overriddenClassName); return this; }, /** * Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias} * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will * attempt to load the class via synchronous loading. * * var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... }); * * @param {String} alias * @param {Mixed...} args Additional arguments after the alias will be passed to the class constructor. * @return {Object} instance */ instantiateByAlias: function() { var alias = arguments[0], args = arraySlice.call(arguments), className = this.getNameByAlias(alias); if (!className) { className = this.maps.aliasToName[alias]; //<debug error> if (!className) { throw new Error("[Ext.createByAlias] Cannot create an instance of unrecognized alias: " + alias); } //</debug> //<debug warn> Ext.Logger.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " + "Ext.require('" + alias + "') above Ext.onReady"); //</debug> Ext.syncRequire(className); } args[0] = className; return this.instantiate.apply(this, args); }, /** * Instantiate a class by either full name, alias or alternate name; usually invoked by the convenient * shorthand {@link Ext#create Ext.create} * * If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will * attempt to load the class via synchronous loading. * * For example, all these three lines return the same result: * * // alias * var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... }); * * // alternate name * var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... }); * * // full class name * var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... }); * * @param {String} name * @param {Mixed} args,... Additional arguments after the name will be passed to the class' constructor. * @return {Object} instance */ instantiate: function() { var name = arguments[0], args = arraySlice.call(arguments, 1), alias = name, possibleName, cls; if (typeof name != 'function') { //<debug error> if ((typeof name != 'string' || name.length < 1)) { throw new Error("[Ext.create] Invalid class name or alias '" + name + "' specified, must be a non-empty string"); } //</debug> cls = this.get(name); } else { cls = name; } // No record of this class name, it's possibly an alias, so look it up if (!cls) { possibleName = this.getNameByAlias(name); if (possibleName) { name = possibleName; cls = this.get(name); } } // Still no record of this class name, it's possibly an alternate name, so look it up if (!cls) { possibleName = this.getNameByAlternate(name); if (possibleName) { name = possibleName; cls = this.get(name); } } // Still not existing at this point, try to load it via synchronous mode as the last resort if (!cls) { //<debug warn> //<if nonBrowser> !isNonBrowser && //</if> Ext.Logger.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding '" + ((possibleName) ? alias : name) + "' explicitly as a require of the corresponding class"); //</debug> Ext.syncRequire(name); cls = this.get(name); } //<debug error> if (!cls) { throw new Error("[Ext.create] Cannot create an instance of unrecognized class name / alias: " + alias); } if (typeof cls != 'function') { throw new Error("[Ext.create] '" + name + "' is a singleton and cannot be instantiated"); } //</debug> return this.getInstantiator(args.length)(cls, args); }, /** * @private * @param name * @param args */ dynInstantiate: function(name, args) { args = arrayFrom(args, true); args.unshift(name); return this.instantiate.apply(this, args); }, /** * @private * @param length */ getInstantiator: function(length) { var instantiators = this.instantiators, instantiator; instantiator = instantiators[length]; if (!instantiator) { var i = length, args = []; for (i = 0; i < length; i++) { args.push('a[' + i + ']'); } instantiator = instantiators[length] = new Function('c', 'a', 'return new c(' + args.join(',') + ')'); //<debug> instantiator.displayName = "Ext.ClassManager.instantiate" + length; //</debug> } return instantiator; }, /** * @private */ postprocessors: {}, /** * @private */ defaultPostprocessors: [], /** * Register a post-processor function. * * @private * @param {String} name * @param {Function} postprocessor */ registerPostprocessor: function(name, fn, properties, position, relativeTo) { if (!position) { position = 'last'; } if (!properties) { properties = [name]; } this.postprocessors[name] = { name: name, properties: properties || false, fn: fn }; this.setDefaultPostprocessorPosition(name, position, relativeTo); return this; }, /** * Set the default post processors array stack which are applied to every class. * * @private * @param {String/Array} The name of a registered post processor or an array of registered names. * @return {Ext.ClassManager} this */ setDefaultPostprocessors: function(postprocessors) { this.defaultPostprocessors = arrayFrom(postprocessors); return this; }, /** * Insert this post-processor at a specific position in the stack, optionally relative to * any existing post-processor * * @private * @param {String} name The post-processor name. Note that it needs to be registered with * {@link Ext.ClassManager#registerPostprocessor} before this * @param {String} offset The insertion position. Four possible values are: * 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument) * @param {String} relativeName * @return {Ext.ClassManager} this */ setDefaultPostprocessorPosition: function(name, offset, relativeName) { var defaultPostprocessors = this.defaultPostprocessors, index; if (typeof offset == 'string') { if (offset === 'first') { defaultPostprocessors.unshift(name); return this; } else if (offset === 'last') { defaultPostprocessors.push(name); return this; } offset = (offset === 'after') ? 1 : -1; } index = Ext.Array.indexOf(defaultPostprocessors, relativeName); if (index !== -1) { Ext.Array.splice(defaultPostprocessors, Math.max(0, index + offset), 0, name); } return this; }, /** * Converts a string expression to an array of matching class names. An expression can either refers to class aliases * or class names. Expressions support wildcards: * * // returns ['Ext.window.Window'] * var window = Ext.ClassManager.getNamesByExpression('widget.window'); * * // returns ['widget.panel', 'widget.window', ...] * var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*'); * * // returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...] * var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*'); * * @param {String} expression * @return {Array} classNames * @markdown */ getNamesByExpression: function(expression) { var nameToAliasesMap = this.maps.nameToAliases, names = [], name, alias, aliases, possibleName, regex, i, ln; //<debug error> if (typeof expression != 'string' || expression.length < 1) { throw new Error("[Ext.ClassManager.getNamesByExpression] Expression " + expression + " is invalid, must be a non-empty string"); } //</debug> if (expression.indexOf('*') !== -1) { expression = expression.replace(/\*/g, '(.*?)'); regex = new RegExp('^' + expression + '$'); for (name in nameToAliasesMap) { if (nameToAliasesMap.hasOwnProperty(name)) { aliases = nameToAliasesMap[name]; if (name.search(regex) !== -1) { names.push(name); } else { for (i = 0, ln = aliases.length; i < ln; i++) { alias = aliases[i]; if (alias.search(regex) !== -1) { names.push(name); break; } } } } } } else { possibleName = this.getNameByAlias(expression); if (possibleName) { names.push(possibleName); } else { possibleName = this.getNameByAlternate(expression); if (possibleName) { names.push(possibleName); } else { names.push(expression); } } } return names; } }; //<feature classSystem.alias> /** * @cfg {String[]} alias * @member Ext.Class * List of short aliases for class names. Most useful for defining xtypes for widgets: * * Ext.define('MyApp.CoolPanel', { * extend: 'Ext.panel.Panel', * alias: ['widget.coolpanel'], * title: 'Yeah!' * }); * * // Using Ext.create * Ext.widget('widget.coolpanel'); * // Using the shorthand for widgets and in xtypes * Ext.widget('panel', { * items: [ * {xtype: 'coolpanel', html: 'Foo'}, * {xtype: 'coolpanel', html: 'Bar'} * ] * }); */ Manager.registerPostprocessor('alias', function(name, cls, data) { var aliases = data.alias, i, ln; for (i = 0,ln = aliases.length; i < ln; i++) { alias = aliases[i]; this.setAlias(cls, alias); } }, ['xtype', 'alias']); //</feature> //<feature classSystem.singleton> /** * @cfg {Boolean} singleton * @member Ext.Class * When set to true, the class will be instantiated as singleton. For example: * * Ext.define('Logger', { * singleton: true, * log: function(msg) { * console.log(msg); * } * }); * * Logger.log('Hello'); */ Manager.registerPostprocessor('singleton', function(name, cls, data, fn) { fn.call(this, name, new cls(), data); return false; }); //</feature> //<feature classSystem.alternateClassName> /** * @cfg {String/String[]} alternateClassName * @member Ext.Class * Defines alternate names for this class. For example: * * Ext.define('Developer', { * alternateClassName: ['Coder', 'Hacker'], * code: function(msg) { * alert('Typing... ' + msg); * } * }); * * var joe = Ext.create('Developer'); * joe.code('stackoverflow'); * * var rms = Ext.create('Hacker'); * rms.code('hack hack'); */ Manager.registerPostprocessor('alternateClassName', function(name, cls, data) { var alternates = data.alternateClassName, i, ln, alternate; if (!(alternates instanceof Array)) { alternates = [alternates]; } for (i = 0, ln = alternates.length; i < ln; i++) { alternate = alternates[i]; //<debug error> if (typeof alternate != 'string') { throw new Error("[Ext.define] Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"); } //</debug> this.set(alternate, cls); } }); //</feature> Ext.apply(Ext, { /** * Convenient shorthand, see {@link Ext.ClassManager#instantiate} * @member Ext * @method create */ create: alias(Manager, 'instantiate'), /** * Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias} * * var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button') * var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel') * * @member Ext * @method widget */ widget: function(name) { var args = arraySlice.call(arguments); args[0] = 'widget.' + name; return Manager.instantiateByAlias.apply(Manager, args); }, /** * Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias} * @member Ext * @method createByAlias */ createByAlias: alias(Manager, 'instantiateByAlias'), /** * Defines a class or override. A basic class is defined like this: * * Ext.define('My.awesome.Class', { * someProperty: 'something', * * someMethod: function(s) { * console.log(s + this.someProperty); * } * }); * * var obj = new My.awesome.Class(); * * obj.someMethod('Say '); // logs 'Say something' to the console * * To defines an override, include the `override` property. The content of an * override is aggregated with the specified class in order to extend or modify * that class. This can be as simple as setting default property values or it can * extend and/or replace methods. This can also extend the statics of the class. * * One use for an override is to break a large class into manageable pieces. * * // File: /src/app/Panel.js * * Ext.define('My.app.Panel', { * extend: 'Ext.panel.Panel', * requires: [ * 'My.app.PanelPart2', * 'My.app.PanelPart3' * ] * * constructor: function (config) { * this.callParent(arguments); // calls Ext.panel.Panel's constructor * //... * }, * * statics: { * method: function () { * return 'abc'; * } * } * }); * * // File: /src/app/PanelPart2.js * Ext.define('My.app.PanelPart2', { * override: 'My.app.Panel', * * constructor: function (config) { * this.callParent(arguments); // calls My.app.Panel's constructor * //... * } * }); * * Another use for an override is to provide optional parts of classes that can be * independently required. In this case, the class may even be unaware of the * override altogether. * * Ext.define('My.ux.CoolTip', { * override: 'Ext.tip.ToolTip', * * constructor: function (config) { * this.callParent(arguments); // calls Ext.tip.ToolTip's constructor * //... * } * }); * * The above override can now be required as normal. * * Ext.define('My.app.App', { * requires: [ * 'My.ux.CoolTip' * ] * }); * * Overrides can also contain statics: * * Ext.define('My.app.BarMod', { * override: 'Ext.foo.Bar', * * statics: { * method: function (x) { * return this.callParent([x * 2]); // call Ext.foo.Bar.method * } * } * }); * * IMPORTANT: An override is only included in a build if the class it overrides is * required. Otherwise, the override, like the target class, is not included. * * @param {String} className The class name to create in string dot-namespaced format, for example: * 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager' * * It is highly recommended to follow this simple convention: * - The root and the class name are 'CamelCased' * - Everything else is lower-cased * * @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of * any valid strings, except those in the reserved listed below: * * - `mixins` * - `statics` * - `config` * - `alias` * - `self` * - `singleton` * - `alternateClassName` * - `override` * * @param {Function} createdFn Optional callback to execute after the class (or override) * is created. The execution scope (`this`) will be the newly created class itself. * @return {Ext.Base} * * @member Ext * @method define */ define: function (className, data, createdFn) { if ('override' in data) { return Manager.createOverride.apply(Manager, arguments); } return Manager.create.apply(Manager, arguments); }, /** * Convenient shorthand for {@link Ext.ClassManager#getName}. * @member Ext * @method getClassName * @inheritdoc Ext.ClassManager#getName */ getClassName: alias(Manager, 'getName'), /** * Returns the display name for object. This name is looked for in order from the following places: * * - `displayName` field of the object. * - `$name` and `$class` fields of the object. * - '$className` field of the object. * * This method is used by {@link Ext.Logger#log} to display information about objects. * * @param {Mixed} [object] The object who's display name to determine. * @return {String} The determined display name, or "Anonymous" if none found. * @member Ext */ getDisplayName: function(object) { if (object) { if (object.displayName) { return object.displayName; } if (object.$name && object.$class) { return Ext.getClassName(object.$class) + '#' + object.$name; } if (object.$className) { return object.$className; } } return 'Anonymous'; }, /** * Convenient shorthand, see {@link Ext.ClassManager#getClass} * @member Ext * @method getClass */ getClass: alias(Manager, 'getClass'), /** * Creates namespaces to be used for scoping variables and classes so that they are not global. * Specifying the last node of a namespace implicitly creates all other nodes. Usage: * * Ext.namespace('Company', 'Company.data'); * * // equivalent and preferable to the above syntax * Ext.namespace('Company.data'); * * Company.Widget = function() { ... }; * * Company.data.CustomStore = function(config) { ... }; * * @param {String} namespace1 * @param {String} namespace2 * @param {String} etc * @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created) * @function * @member Ext * @method namespace */ namespace: alias(Manager, 'createNamespaces') }); /** * Old name for {@link Ext#widget}. * @deprecated 4.0.0 Please use {@link Ext#widget} instead. * @method createWidget * @member Ext */ Ext.createWidget = Ext.widget; /** * Convenient alias for {@link Ext#namespace Ext.namespace} * @member Ext * @method ns */ Ext.ns = Ext.namespace; Class.registerPreprocessor('className', function(cls, data) { if (data.$className) { cls.$className = data.$className; //<debug> cls.displayName = cls.$className; //</debug> } }, true, 'first'); Class.registerPreprocessor('alias', function(cls, data) { var prototype = cls.prototype, xtypes = arrayFrom(data.xtype), aliases = arrayFrom(data.alias), widgetPrefix = 'widget.', widgetPrefixLength = widgetPrefix.length, xtypesChain = Array.prototype.slice.call(prototype.xtypesChain || []), xtypesMap = Ext.merge({}, prototype.xtypesMap || {}), i, ln, alias, xtype; for (i = 0,ln = aliases.length; i < ln; i++) { alias = aliases[i]; //<debug error> if (typeof alias != 'string' || alias.length < 1) { throw new Error("[Ext.define] Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"); } //</debug> if (alias.substring(0, widgetPrefixLength) === widgetPrefix) { xtype = alias.substring(widgetPrefixLength); Ext.Array.include(xtypes, xtype); } } cls.xtype = data.xtype = xtypes[0]; data.xtypes = xtypes; for (i = 0,ln = xtypes.length; i < ln; i++) { xtype = xtypes[i]; if (!xtypesMap[xtype]) { xtypesMap[xtype] = true; xtypesChain.push(xtype); } } data.xtypesChain = xtypesChain; data.xtypesMap = xtypesMap; Ext.Function.interceptAfter(data, 'onClassCreated', function() { var mixins = prototype.mixins, key, mixin; for (key in mixins) { if (mixins.hasOwnProperty(key)) { mixin = mixins[key]; xtypes = mixin.xtypes; if (xtypes) { for (i = 0,ln = xtypes.length; i < ln; i++) { xtype = xtypes[i]; if (!xtypesMap[xtype]) { xtypesMap[xtype] = true; xtypesChain.push(xtype); } } } } } }); for (i = 0,ln = xtypes.length; i < ln; i++) { xtype = xtypes[i]; //<debug error> if (typeof xtype != 'string' || xtype.length < 1) { throw new Error("[Ext.define] Invalid xtype of: '" + xtype + "' for class: '" + name + "'; must be a valid non-empty string"); } //</debug> Ext.Array.include(aliases, widgetPrefix + xtype); } data.alias = aliases; }, ['xtype', 'alias']); })(Ext.Class, Ext.Function.alias, Array.prototype.slice, Ext.Array.from, Ext.global);
pierotofy/glassomium
src/server/WebRoot/apps/Maps/src/core/class/ClassManager.js
JavaScript
apache-2.0
47,766
"use strict"; const {strict: assert} = require("assert"); const {zrequire} = require("../zjsunit/namespace"); const {run_test} = require("../zjsunit/test"); const user_groups = zrequire("user_groups"); const user_group_pill = zrequire("user_group_pill"); const admins = { name: "Admins", description: "foo", id: 101, members: [10, 20], }; const testers = { name: "Testers", description: "bar", id: 102, members: [20, 50, 30, 40], }; const admins_pill = { id: admins.id, group_name: admins.name, type: "user_group", display_value: admins.name + ": " + admins.members.length + " users", }; const testers_pill = { id: testers.id, group_name: testers.name, type: "user_group", display_value: testers.name + ": " + testers.members.length + " users", }; const groups = [admins, testers]; for (const group of groups) { user_groups.add(group); } run_test("create_item", () => { function test_create_item(group_name, current_items, expected_item) { const item = user_group_pill.create_item_from_group_name(group_name, current_items); assert.deepEqual(item, expected_item); } test_create_item(" admins ", [], admins_pill); test_create_item("admins", [testers_pill], admins_pill); test_create_item("admins", [admins_pill], undefined); test_create_item("unknown", [], undefined); }); run_test("get_stream_id", () => { assert.equal(user_group_pill.get_group_name_from_item(admins_pill), admins.name); }); run_test("get_user_ids", () => { const items = [admins_pill, testers_pill]; const widget = {items: () => items}; const user_ids = user_group_pill.get_user_ids(widget); assert.deepEqual(user_ids, [10, 20, 30, 40, 50]); }); run_test("get_group_ids", () => { const items = [admins_pill, testers_pill]; const widget = {items: () => items}; const group_ids = user_group_pill.get_group_ids(widget); assert.deepEqual(group_ids, [101, 102]); });
zulip/zulip
frontend_tests/node_tests/user_group_pill.js
JavaScript
apache-2.0
1,987
/* * @弹出提示层 ( 加载动画(load), 提示动画(tip), 成功(success), 错误(error), ) * @method tipBox * @description 默认配置参数 * @time 2014-12-19 * @param {Number} width -宽度 * @param {Number} height -高度 * @param {String} str -默认文字 * @param {Object} windowDom -载入窗口 默认当前窗口 * @param {Number} setTime -定时消失(毫秒) 默认为0 不消失 * @param {Boolean} hasMask -是否显示遮罩 * @param {Boolean} hasMaskWhite -显示白色遮罩 * @param {Boolean} clickDomCancel -点击空白取消 * @param {Function} callBack -回调函数 (只在开启定时消失时才生效) * @param {Function} hasBtn -显示按钮 * @param {String} type -动画类型 (加载,成功,失败,提示) * @example * new TipBox(); * new TipBox({type:'load',setTime:1000,callBack:function(){ alert(..) }}); */ function TipBox(cfg){ this.config = { width : 250, height : 170, str : '正在处理', windowDom : window, setTime : 0, hasMask : true, hasMaskWhite : false, clickDomCancel : false, callBack : null, hasBtn : false, type : 'success' } $.extend(this.config,cfg); //存在就retrun if(TipBox.prototype.boundingBox) return; //初始化 this.render(this.config.type); return this; }; //外层box TipBox.prototype.boundingBox = null; //渲染 TipBox.prototype.render = function(tipType,container){ this.renderUI(tipType); //绑定事件 this.bindUI(); //初始化UI this.syncUI(); $(container || this.config.windowDom.document.body).append(TipBox.prototype.boundingBox); }; //渲染UI TipBox.prototype.renderUI = function(tipType){ TipBox.prototype.boundingBox = $("<div id='animationTipBox'></div>"); tipType == 'load' && this.loadRenderUI(); tipType == 'success' && this.successRenderUI(); tipType == 'error' && this.errorRenderUI(); tipType == 'tip' && this.tipRenderUI(); TipBox.prototype.boundingBox.appendTo(this.config.windowDom.document.body); //是否显示遮罩 if(this.config.hasMask){ this.config.hasMaskWhite ? this._mask = $("<div class='mask_white'></div>") : this._mask = $("<div class='mask'></div>"); this._mask.appendTo(this.config.windowDom.document.body); } // 是否显示按钮 if(this.config.hasBtn){ this.config.height = 206; $('#animationTipBox').css("margin-top","103px"); switch(this.config.type){ case 'success':$(".success").after("<button class='okoButton'>ok</button>"); break; case 'error':$(".lose").after("<button class='okoButton redOkoButton'>ok</button>"); break; case 'tip':$(".tip").after("<button class='okoButton'>ok</button>"); break; default: break; } $('button.okoButton').on('click',function(){_this.close();}); } //定时消失 _this = this; !this.config.setTime && typeof this.config.callBack === "function" && (this.config.setTime = 1); this.config.setTime && setTimeout( function(){ _this.close(); }, _this.config.setTime ); }; TipBox.prototype.bindUI = function(){ _this = this; //点击空白立即取消 this.config.clickDomCancel && this._mask && this._mask.click(function(){_this.close();}); }; TipBox.prototype.syncUI = function(){ TipBox.prototype.boundingBox.css({ width : this.config.width+'px', height : this.config.height+'px', marginLeft : "-"+(this.config.width/2)+'px', marginTop : "-"+(this.config.height/2)+'px' }); }; //提示效果UI TipBox.prototype.tipRenderUI = function(){ var tip = "<div class='tip'>"; tip +=" <div class='icon'>i</div>"; tip +=" <div class='dec_txt'>"+this.config.str+"</div>"; tip += "</div>"; TipBox.prototype.boundingBox.append(tip); }; //成功效果UI TipBox.prototype.successRenderUI = function(){ var suc = "<div class='success'>"; suc +=" <div class='icon'>"; suc += "<div class='line_short'></div>"; suc += "<div class='line_long'></div> "; suc += "</div>"; suc +=" <div class='dec_txt'>"+this.config.str+"</div>"; suc += "</div>"; TipBox.prototype.boundingBox.append(suc); }; //错误效果UI TipBox.prototype.errorRenderUI = function(){ var err = "<div class='lose'>"; err += " <div class='icon'>"; err += " <div class='icon_box'>"; err += " <div class='line_left'></div>"; err += " <div class='line_right'></div>"; err += " </div>"; err += " </div>"; err += "<div class='dec_txt'>"+this.config.str+"</div>"; err += "</div>"; TipBox.prototype.boundingBox.append(err); }; //加载动画load UI TipBox.prototype.loadRenderUI = function(){ var load = "<div class='load'>"; load += "<div class='icon_box'>"; for(var i = 1; i < 4; i++ ){ load += "<div class='cirBox"+i+"'>"; load += "<div class='cir1'></div>"; load += "<div class='cir2'></div>"; load += "<div class='cir3'></div>"; load += "<div class='cir4'></div>"; load += "</div>"; } load += "</div>"; load += "</div>"; load += "<div class='dec_txt'>"+this.config.str+"</div>"; TipBox.prototype.boundingBox.append(load); }; //关闭 TipBox.prototype.close = function(){ TipBox.prototype.destroy(); this.destroy(); this.config.setTime && typeof this.config.callBack === "function" && this.config.callBack(); }; //销毁 TipBox.prototype.destroy = function(){ this._mask && this._mask.remove(); TipBox.prototype.boundingBox && TipBox.prototype.boundingBox.remove(); TipBox.prototype.boundingBox = null; };
userKarl/sctd
target/td-1.0/resources/evaluate/js/mdialog.js
JavaScript
apache-2.0
6,493
/** * Passport configuration * * This is the configuration for your Passport.js setup and where you * define the authentication strategies you want your application to employ. * * I have tested the service with all of the providers listed below - if you * come across a provider that for some reason doesn't work, feel free to open * an issue on GitHub. * * Also, authentication scopes can be set through the `scope` property. * * For more information on the available providers, check out: * http://passportjs.org/guide/providers/ */ module.exports.passport = { local: { strategy: require('passport-local').Strategy }, bearer: { strategy: require('passport-http-bearer').Strategy } /*twitter: { name: 'Twitter', protocol: 'oauth', strategy: require('passport-twitter').Strategy, options: { consumerKey: 'your-consumer-key', consumerSecret: 'your-consumer-secret' } }, github: { name: 'GitHub', protocol: 'oauth2', strategy: require('passport-github').Strategy, options: { clientID: 'your-client-id', clientSecret: 'your-client-secret' } }, facebook: { name: 'Facebook', protocol: 'oauth2', strategy: require('passport-facebook').Strategy, options: { clientID: 'your-client-id', clientSecret: 'your-client-secret', scope: ['email'] } }, google: { name: 'Google', protocol: 'oauth2', strategy: require('passport-google-oauth').OAuth2Strategy, options: { clientID: 'your-client-id', clientSecret: 'your-client-secret' } }, cas: { name: 'CAS', protocol: 'cas', strategy: require('passport-cas').Strategy, options: { ssoBaseURL: 'http://your-cas-url', serverBaseURL: 'http://localhost:1337', serviceURL: 'http://localhost:1337/auth/cas/callback' } }*/ };
porybox/porybox
config/passport.js
JavaScript
apache-2.0
1,880
/** * 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 friendsWrapper() { /* * Loads the owner, the viewer, the owner's friends, and the viewer's * friends and mutual friends between owner and viewer. Response data is put into the variables owner, viewer, * ownerFriends, and viewerFriends, mutualFriends respectively. * * */ this.loadFriends = function(){ var req = opensocial.newDataRequest(); req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer'); req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.OWNER), 'owner'); var viewerFriends = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" }); var ownerFriends = opensocial.newIdSpec({ "userId" : "OWNER", "groupId" : "FRIENDS" }); var opt_params = {}; opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100; req.add(req.newFetchPeopleRequest(viewerFriends, opt_params), 'viewerFriends'); req.add(req.newFetchPeopleRequest(ownerFriends, opt_params), 'ownerFriends'); var params = {}; params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100; // Usage of isFriendsWith filter to get mutual friends. filterValue should be set to the friend with whom mutual friends is to be found. params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.IS_FRIENDS_WITH; params["filterValue"] = opensocial.IdSpec.PersonId.VIEWER; req.add(req.newFetchPeopleRequest(ownerFriends, params), 'mutualFriends'); var app_params = {}; app_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100; // Usage of hasApp filter to get list of friends who use this app. app_params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP; req.add(req.newFetchPeopleRequest(ownerFriends, app_params), 'friendsUsingApp'); req.send(displayFriends); }; function displayFriends(data) { var viewer = data.get('viewer').getData(); var viewerFriends = data.get('viewerFriends').getData(); var owner = data.get('owner').getData(); var ownerFriends = data.get('ownerFriends').getData(); html = new Array(); html.push(owner.getDisplayName() + '\'s Friends(',ownerFriends.size(),') <br>'); html.push('<ul>'); ownerFriends.each(function(person) { if (person.getId()) { html.push('<li>', person.getDisplayName(), '</li>'); } }); html.push('</ul>'); if(owner.getDisplayName()!=viewer.getDisplayName()) { var mutualFriends = data.get('mutualFriends').getData(); html.push('Mutual Friends with ',viewer.getDisplayName(),'(',mutualFriends.size(),') <br>'); html.push('<ul>'); mutualFriends.each(function(person) { if (person.getId()) { html.push('<li>', person.getDisplayName(), '</li>'); } }); html.push('</ul>'); } var friendsUsingApp = data.get('friendsUsingApp').getData(); html.push('Friends using this Widget (',friendsUsingApp.size(),') <br>'); html.push('<ul>'); friendsUsingApp.each(function(person) { if (person.getId()) { html.push('<li>', person.getDisplayName(), '</li>'); } }); html.push('</ul>'); document.getElementById('friends').innerHTML = html.join(''); gadgets.window.adjustHeight(); } }
kidaa/rave
rave-demo-gadgets/src/main/webapp/friendsWrapper.js
JavaScript
apache-2.0
4,255
import { FunctionNode } from './FunctionNode.js'; function ExpressionNode( src, type, keywords, extensions, includes ) { FunctionNode.call( this, src, includes, extensions, keywords, type ); } ExpressionNode.prototype = Object.create( FunctionNode.prototype ); ExpressionNode.prototype.constructor = ExpressionNode; ExpressionNode.prototype.nodeType = "Expression"; export { ExpressionNode };
sinorise/sinorise.github.io
three/jsm/nodes/core/ExpressionNode.js
JavaScript
apache-2.0
399
/** * @file * Provides JavaScript additions to the managed file field type. * * This file provides progress bar support (if available), popup windows for * file previews, and disabling of other file fields during Ajax uploads (which * prevents separate file fields from accidentally uploading files). */ (function ($) { "use strict"; /** * Attach behaviors to managed file element upload fields. */ Drupal.behaviors.fileValidateAutoAttach = { attach: function (context, settings) { var $context = $(context); var validateExtension = Drupal.file.validateExtension; var selector, elements; if (settings.file && settings.file.elements) { elements = settings.file.elements; for (selector in elements) { if (elements.hasOwnProperty(selector)) { $context.find(selector).bind('change', {extensions: elements[selector]}, validateExtension); } } } }, detach: function (context, settings) { var $context = $(context); var validateExtension = Drupal.file.validateExtension; var selector, elements; if (settings.file && settings.file.elements) { elements = settings.file.elements; for (selector in elements) { if (elements.hasOwnProperty(selector)) { $context.find(selector).unbind('change', validateExtension); } } } } }; /** * Attach behaviors to managed file element upload fields. */ Drupal.behaviors.fileAutoUpload = { attach: function (context) { $(context).find('input[type="file"]').once('auto-file-upload').on('change.autoFileUpload', Drupal.file.triggerUploadButton); }, detach: function (context, setting, trigger) { if (trigger === 'unload') { $(context).find('input[type="file"]').removeOnce('auto-file-upload').off('.autoFileUpload'); } } }; /** * Attach behaviors to the file upload and remove buttons. */ Drupal.behaviors.fileButtons = { attach: function (context) { var $context = $(context); $context.find('input.form-submit').bind('mousedown', Drupal.file.disableFields); $context.find('div.form-managed-file input.form-submit').bind('mousedown', Drupal.file.progressBar); }, detach: function (context) { var $context = $(context); $context.find('input.form-submit').unbind('mousedown', Drupal.file.disableFields); $context.find('div.form-managed-file input.form-submit').unbind('mousedown', Drupal.file.progressBar); } }; /** * Attach behaviors to links within managed file elements. */ Drupal.behaviors.filePreviewLinks = { attach: function (context) { $(context).find('div.form-managed-file .file a, .file-widget .file a').bind('click',Drupal.file.openInNewWindow); }, detach: function (context){ $(context).find('div.form-managed-file .file a, .file-widget .file a').unbind('click', Drupal.file.openInNewWindow); } }; /** * File upload utility functions. */ Drupal.file = Drupal.file || { /** * Client-side file input validation of file extensions. */ validateExtension: function (event) { event.preventDefault(); // Remove any previous errors. $('.file-upload-js-error').remove(); // Add client side validation for the input[type=file]. var extensionPattern = event.data.extensions.replace(/,\s*/g, '|'); if (extensionPattern.length > 1 && this.value.length > 0) { var acceptableMatch = new RegExp('\\.(' + extensionPattern + ')$', 'gi'); if (!acceptableMatch.test(this.value)) { var error = Drupal.t("The selected file %filename cannot be uploaded. Only files with the following extensions are allowed: %extensions.", { // According to the specifications of HTML5, a file upload control // should not reveal the real local path to the file that a user // has selected. Some web browsers implement this restriction by // replacing the local path with "C:\fakepath\", which can cause // confusion by leaving the user thinking perhaps Drupal could not // find the file because it messed up the file path. To avoid this // confusion, therefore, we strip out the bogus fakepath string. '%filename': this.value.replace('C:\\fakepath\\', ''), '%extensions': extensionPattern.replace(/\|/g, ', ') }); $(this).closest('div.form-managed-file').prepend('<div class="messages messages--error file-upload-js-error" aria-live="polite">' + error + '</div>'); this.value = ''; } } }, /** * Trigger the upload_button mouse event to auto-upload as a managed file. */ triggerUploadButton: function (event){ $(event.target).closest('.form-managed-file').find('.form-submit').trigger('mousedown'); }, /** * Prevent file uploads when using buttons not intended to upload. */ disableFields: function (event){ var clickedButton = this; // Only disable upload fields for Ajax buttons. if (!$(clickedButton).hasClass('ajax-processed')) { return; } // Check if we're working with an "Upload" button. var $enabledFields = []; if ($(this).closest('div.form-managed-file').length > 0) { $enabledFields = $(this).closest('div.form-managed-file').find('input.form-file'); } // Temporarily disable upload fields other than the one we're currently // working with. Filter out fields that are already disabled so that they // do not get enabled when we re-enable these fields at the end of behavior // processing. Re-enable in a setTimeout set to a relatively short amount // of time (1 second). All the other mousedown handlers (like Drupal's Ajax // behaviors) are excuted before any timeout functions are called, so we // don't have to worry about the fields being re-enabled too soon. // @todo If the previous sentence is true, why not set the timeout to 0? var $fieldsToTemporarilyDisable = $('div.form-managed-file input.form-file').not($enabledFields).not(':disabled'); $fieldsToTemporarilyDisable.prop('disabled', true); setTimeout(function (){ $fieldsToTemporarilyDisable.prop('disabled', false); }, 1000); }, /** * Add progress bar support if possible. */ progressBar: function (event) { var clickedButton = this; var $progressId = $(clickedButton).closest('div.form-managed-file').find('input.file-progress'); if ($progressId.length) { var originalName = $progressId.attr('name'); // Replace the name with the required identifier. $progressId.attr('name', originalName.match(/APC_UPLOAD_PROGRESS|UPLOAD_IDENTIFIER/)[0]); // Restore the original name after the upload begins. setTimeout(function () { $progressId.attr('name', originalName); }, 1000); } // Show the progress bar if the upload takes longer than half a second. setTimeout(function () { $(clickedButton).closest('div.form-managed-file').find('div.ajax-progress-bar').slideDown(); }, 500); }, /** * Open links to files within forms in a new window. */ openInNewWindow: function (event) { event.preventDefault(); $(this).attr('target', '_blank'); window.open(this.href, 'filePreview', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,width=500,height=550'); } }; })(jQuery);
nickopris/musicapp
www/core/modules/file/file.js
JavaScript
apache-2.0
7,305
var Event = { addListener: function (obj, event, listener, scope) { if (obj) { if (typeof obj.__listeners == "undefined") { obj.__listeners = new Object(); } if (typeof obj.__listeners[event] == "undefined") { obj.__listeners[event] = new Array(); obj.__listeners[event].__listenerCount = 0; } if (typeof scope == "undefined") obj.__listeners[event].push(listener); else obj.__listeners[event].push({ "listener": listener, "scope": scope }); obj.__listeners[event].__listenerCount++; obj["on" + event] = function () { Event.fire(obj, event, arguments); }; return obj.__listeners[event].length - 1; } }, removeListener: function (obj, event, listener, scope) { if (obj && obj.__listeners && obj.__listeners[event]) { for (var i = 0; i < obj.__listeners[event].length; i++) { if (obj.__listeners[event][i] === listener) { obj.__listeners[event][i] = null; delete obj.__listeners[event][i]; obj.__listeners[event].__listenerCount--; } else { var l = obj.__listeners[event][i]; if (l && l.listener === listener && l.scope === scope) { obj.__listeners[event][i] = null; delete obj.__listeners[event][i]; obj.__listeners[event].__listenerCount--; } } } Event.defragListeners(obj, event); } }, removeListenerById: function (obj, event, listenerId) { if (obj && obj.__listeners && obj.__listeners[event] && obj.__listeners[event][listenerId]) { obj.__listeners[event][listenerId] = null; delete obj.__listeners[event][listenerId]; obj.__listeners[event].__listenerCount--; } Event.defragListeners(obj, event); }, removeAllListeners: function(obj, event) { if(obj && obj.__listeners) { if(typeof event == "undefined") { obj.__listeners = new Object(); } else if(typeof obj.__listeners[event] != "undefined") { obj.__listeners[event] = new Array(); obj.__listeners[event].__listenerCount = 0; } } }, defragListener: function(obj, event) { // do nothing right now }, fire: function (obj, event, args) { if(!args) args = new Array(); for (var i = 0; obj && obj.__listeners && obj.__listeners[event] && i < obj.__listeners[event].length; i++) { var f = obj.__listeners[event][i]; if (typeof f == "function") { // TODO: should the scope be the obj, the listener, or should it be passed in? f.apply(obj, args); } else if (f && typeof f.listener == "function") { f.listener.apply(f.scope, args); } } } };
donniet/livegame
src/main/webapp/client/0.2/event.js
JavaScript
apache-2.0
3,158
var utils = require('./utils'), Signals = require('./Signals'); /** * Support for the W3C Page Visibility API - http://www.w3.org/TR/page-visibility * * {@link module:enyo/pageVisibility.hidden} and {@link module:enyo/pageVisibility.visibilityState} * contain the same information as `document.hidden` and * `document.visibilityState` in supported browsers. The `visibilitychange` * event is channelled through the [Signals]{@link module:enyo/Signals~Signals} mechanism. * * Partly based on {@linkplain http://stackoverflow.com/a/1060034}. * * Example: * * ```javascript * var * kind = require('enyo/kind'), * Signals = require('enyo/Signals'); * * module.exports = kind({ * name: 'App', * components: [ * {kind: Signals, onvisibilitychange: 'visibilitychanged'} * ], * visibilitychanged: function() { * if(enyo.hidden){ * // page hidden * } else { * // page visible * } * } * }); * ``` * * @module enyo/pageVisibility * @private */ var doc = global.document, hidden = 'hidden', visibilityState = 'visibilityState', hiddenMap = {}; var pageVisibility = module.exports = { // set inital values for enyo.hidden and enyo.visibilityState it's probably save to assume // that the current document is visible when loading the page /** * `true` if the document is hidden; otherwise, `false`. * * @readonly * @type {Boolean} * @default false * @public */ hidden: typeof doc[hidden] !== 'undefined' ? doc[hidden] : false, /** * String indicating the document's visibility state. * * @readonly * @type {String} * @default 'visible' * @public */ visibilityState: typeof doc[visibilityState] !== 'undefined' ? doc[visibilityState] : 'visible' }; // map compatibility events to document.hidden state hiddenMap.blur = hiddenMap.focusout = hiddenMap.pagehide = true; hiddenMap.focus = hiddenMap.focusin = hiddenMap.pageshow = false; function onchange (event) { event = event || global.event; pageVisibility.hidden = (event.type in hiddenMap) ? hiddenMap[event.type] : doc[hidden]; pageVisibility.visibilityState = (event.type in hiddenMap) ? (hiddenMap[event.type] ? 'hidden' : 'visible' ) : doc[visibilityState]; Signals.send('onvisibilitychange', utils.mixin(event, {hidden: pageVisibility.hidden})); } // Standards: if (hidden in doc) { doc.addEventListener('visibilitychange', onchange); } else if ((hidden = 'mozHidden') in doc) { doc.addEventListener('mozvisibilitychange', onchange); visibilityState = 'mozVisibilityState'; } else if ((hidden = 'webkitHidden') in doc) { doc.addEventListener('webkitvisibilitychange', onchange); visibilityState = 'webkitVisibilityState'; } else if ((hidden = 'msHidden') in doc) { doc.addEventListener('msvisibilitychange', onchange); visibilityState = 'msVisibilityState'; } else if ('onfocusin' in doc) { // IE 9 and lower: doc.onfocusin = doc.onfocusout = onchange; } else { // All others: global.onpageshow = global.onpagehide = global.onfocus = global.onblur = onchange; }
PKRoma/enyo
src/pageVisibility.js
JavaScript
apache-2.0
2,971
/* * 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'); /** * Base class for backup ProtectionIntent. * * @extends models['Resource'] */ class ProtectionIntentResource extends models['Resource'] { /** * Create a ProtectionIntentResource. * @member {object} [properties] ProtectionIntentResource properties * @member {string} [properties.backupManagementType] Type of backup * managemenent for the backed up item. Possible values include: 'Invalid', * 'AzureIaasVM', 'MAB', 'DPM', 'AzureBackupServer', 'AzureSql', * 'AzureStorage', 'AzureWorkload', 'DefaultBackup' * @member {string} [properties.sourceResourceId] ARM ID of the resource to * be backed up. * @member {string} [properties.itemId] ID of the item which is getting * protected, In case of Azure Vm , it is ProtectedItemId * @member {string} [properties.policyId] ID of the backup policy with which * this item is backed up. * @member {string} [properties.protectionState] Backup state of this backup * item. Possible values include: 'Invalid', 'NotProtected', 'Protecting', * 'Protected', 'ProtectionFailed' * @member {string} [properties.protectionIntentItemType] Polymorphic * Discriminator */ constructor() { super(); } /** * Defines the metadata of ProtectionIntentResource * * @returns {object} metadata of ProtectionIntentResource * */ mapper() { return { required: false, serializedName: 'ProtectionIntentResource', type: { name: 'Composite', className: 'ProtectionIntentResource', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, location: { required: false, serializedName: 'location', type: { name: 'String' } }, tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } }, eTag: { required: false, serializedName: 'eTag', type: { name: 'String' } }, properties: { required: false, serializedName: 'properties', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'protectionIntentItemType', clientName: 'protectionIntentItemType' }, uberParent: 'ProtectionIntent', className: 'ProtectionIntent' } } } } }; } } module.exports = ProtectionIntentResource;
xingwu1/azure-sdk-for-node
lib/services/recoveryServicesBackupManagement/lib/models/protectionIntentResource.js
JavaScript
apache-2.0
3,687
/* * 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'); /** * Class representing a ProductionOrStagingEndpointInfo. * @extends models['EndpointInfo'] */ class ProductionOrStagingEndpointInfo extends models['EndpointInfo'] { /** * Create a ProductionOrStagingEndpointInfo. */ constructor() { super(); } /** * Defines the metadata of ProductionOrStagingEndpointInfo * * @returns {object} metadata of ProductionOrStagingEndpointInfo * */ mapper() { return { required: false, serializedName: 'ProductionOrStagingEndpointInfo', type: { name: 'Composite', className: 'ProductionOrStagingEndpointInfo', modelProperties: { versionId: { required: false, serializedName: 'versionId', type: { name: 'String' } }, isStaging: { required: false, serializedName: 'isStaging', type: { name: 'Boolean' } }, endpointUrl: { required: false, serializedName: 'endpointUrl', type: { name: 'String' } }, region: { required: false, serializedName: 'region', type: { name: 'String' } }, assignedEndpointKey: { required: false, serializedName: 'assignedEndpointKey', type: { name: 'String' } }, endpointRegion: { required: false, serializedName: 'endpointRegion', type: { name: 'String' } }, failedRegions: { required: false, serializedName: 'failedRegions', type: { name: 'String' } }, publishedDateTime: { required: false, serializedName: 'publishedDateTime', type: { name: 'String' } } } } }; } } module.exports = ProductionOrStagingEndpointInfo;
xingwu1/azure-sdk-for-node
lib/services/luis/authoring/lib/models/productionOrStagingEndpointInfo.js
JavaScript
apache-2.0
2,500
(function() { function AlbumCtrl(Fixtures, SongPlayer) { this.albumData = []; this.albumData.push(Fixtures.getAlbum()); this.songPlayer = SongPlayer; } angular .module('blocJams') .controller('AlbumCtrl', ['Fixtures','SongPlayer', AlbumCtrl]); })();
javierforero/bloc-jams-angular
dist/scripts/controllers/AlbumCtrl.js
JavaScript
apache-2.0
303
Genoverse.Genomes.mus_musculus = { "1": { "size": 195471971, "bands": [ { "id": "A1", "start": 2973781, "end": 8840440, "type": "gpos100" }, { "id": "A2", "start": 8840441, "end": 12278389, "type": "gneg" }, { "id": "A3", "start": 12278390, "end": 20136559, "type": "gpos33" }, { "id": "A4", "start": 20136560, "end": 22101101, "type": "gneg" }, { "id": "A5", "start": 22101102, "end": 30941542, "type": "gpos100" }, { "id": "B", "start": 30941543, "end": 43219933, "type": "gneg" }, { "id": "C1.1", "start": 43219934, "end": 54516051, "type": "gpos66" }, { "id": "C1.2", "start": 54516052, "end": 55989458, "type": "gneg" }, { "id": "C1.3", "start": 55989459, "end": 59427408, "type": "gpos66" }, { "id": "C2", "start": 59427409, "end": 65321034, "type": "gneg" }, { "id": "C3", "start": 65321035, "end": 74652611, "type": "gpos33" }, { "id": "C4", "start": 74652612, "end": 80055103, "type": "gneg" }, { "id": "C5", "start": 80055104, "end": 87422136, "type": "gpos33" }, { "id": "cenp", "start": 991261, "end": 1982520, "type": "acen" }, { "id": "cenq", "start": 1982521, "end": 2973780, "type": "acen" }, { "id": "D", "start": 87422137, "end": 99700527, "type": "gneg" }, { "id": "E1.1", "start": 99700528, "end": 102647341, "type": "gpos33" }, { "id": "E1.2", "start": 102647342, "end": 103629611, "type": "gneg" }, { "id": "E2.1", "start": 103629612, "end": 112470053, "type": "gpos100" }, { "id": "E2.2", "start": 112470054, "end": 113943460, "type": "gneg" }, { "id": "E2.3", "start": 113943461, "end": 125730714, "type": "gpos100" }, { "id": "E3", "start": 125730715, "end": 128677528, "type": "gneg" }, { "id": "E4", "start": 128677529, "end": 139482511, "type": "gpos66" }, { "id": "F", "start": 139482512, "end": 147340680, "type": "gneg" }, { "id": "G1", "start": 147340681, "end": 151760902, "type": "gpos100" }, { "id": "G2", "start": 151760903, "end": 152743172, "type": "gneg" }, { "id": "G3", "start": 152743173, "end": 157163393, "type": "gpos100" }, { "id": "H1", "start": 157163394, "end": 160110206, "type": "gneg" }, { "id": "H2.1", "start": 160110207, "end": 164039291, "type": "gpos33" }, { "id": "H2.2", "start": 164039292, "end": 165512698, "type": "gneg" }, { "id": "H2.3", "start": 165512699, "end": 169932918, "type": "gpos33" }, { "id": "H3", "start": 169932919, "end": 175826546, "type": "gneg" }, { "id": "H4", "start": 175826547, "end": 181720173, "type": "gpos33" }, { "id": "H5", "start": 181720174, "end": 188104936, "type": "gneg" }, { "id": "H6", "start": 188104937, "end": 195471971, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 991260, "type": "tip" } ] }, "2": { "size": 182113224, "bands": [ { "id": "A1", "start": 3006028, "end": 14080919, "type": "gpos100" }, { "id": "A2", "start": 14080920, "end": 16427738, "type": "gneg" }, { "id": "A3", "start": 16427739, "end": 29100566, "type": "gpos33" }, { "id": "B", "start": 29100567, "end": 48344489, "type": "gneg" }, { "id": "C1.1", "start": 48344490, "end": 60547952, "type": "gpos100" }, { "id": "C1.2", "start": 60547953, "end": 61017316, "type": "gneg" }, { "id": "C1.3", "start": 61017317, "end": 68527140, "type": "gpos100" }, { "id": "C2", "start": 68527141, "end": 71812688, "type": "gneg" }, { "id": "C3", "start": 71812689, "end": 81199967, "type": "gpos66" }, { "id": "cenp", "start": 1002010, "end": 2004018, "type": "acen" }, { "id": "cenq", "start": 2004019, "end": 3006027, "type": "acen" }, { "id": "D", "start": 81199968, "end": 88709791, "type": "gneg" }, { "id": "E1", "start": 88709792, "end": 101382619, "type": "gpos100" }, { "id": "E2", "start": 101382620, "end": 105137530, "type": "gneg" }, { "id": "E3", "start": 105137531, "end": 113116719, "type": "gpos33" }, { "id": "E4", "start": 113116720, "end": 115932902, "type": "gneg" }, { "id": "E5", "start": 115932903, "end": 123912089, "type": "gpos66" }, { "id": "F1", "start": 123912090, "end": 131891278, "type": "gneg" }, { "id": "F2", "start": 131891279, "end": 134707461, "type": "gpos33" }, { "id": "F3", "start": 134707462, "end": 141278557, "type": "gneg" }, { "id": "G1", "start": 141278558, "end": 146910925, "type": "gpos100" }, { "id": "G2", "start": 146910926, "end": 147849652, "type": "gneg" }, { "id": "G3", "start": 147849653, "end": 152543293, "type": "gpos100" }, { "id": "H1", "start": 152543294, "end": 159114388, "type": "gneg" }, { "id": "H2", "start": 159114389, "end": 163338664, "type": "gpos33" }, { "id": "H3", "start": 163338665, "end": 173664671, "type": "gneg" }, { "id": "H4", "start": 173664672, "end": 182113224, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1002009, "type": "tip" } ] }, "3": { "size": 160039680, "bands": [ { "id": "A1", "start": 3008269, "end": 18541181, "type": "gpos100" }, { "id": "A2", "start": 18541182, "end": 20492885, "type": "gneg" }, { "id": "A3", "start": 20492886, "end": 35618586, "type": "gpos66" }, { "id": "B", "start": 35618587, "end": 46840881, "type": "gneg" }, { "id": "C", "start": 46840882, "end": 56599398, "type": "gpos100" }, { "id": "cenp", "start": 1002757, "end": 2005512, "type": "acen" }, { "id": "cenq", "start": 2005513, "end": 3008268, "type": "acen" }, { "id": "D", "start": 56599399, "end": 60990731, "type": "gneg" }, { "id": "E1", "start": 60990732, "end": 69773396, "type": "gpos33" }, { "id": "E2", "start": 69773397, "end": 72700951, "type": "gneg" }, { "id": "E3", "start": 72700952, "end": 83923246, "type": "gpos100" }, { "id": "F1", "start": 83923247, "end": 93193837, "type": "gneg" }, { "id": "F2.1", "start": 93193838, "end": 97585169, "type": "gpos33" }, { "id": "F2.2", "start": 97585170, "end": 106367835, "type": "gneg" }, { "id": "F2.3", "start": 106367836, "end": 108319539, "type": "gpos33" }, { "id": "F3", "start": 108319540, "end": 115150501, "type": "gneg" }, { "id": "G1", "start": 115150502, "end": 126860721, "type": "gpos100" }, { "id": "G2", "start": 126860722, "end": 128812424, "type": "gneg" }, { "id": "G3", "start": 128812425, "end": 138570942, "type": "gpos66" }, { "id": "H1", "start": 138570943, "end": 143938126, "type": "gneg" }, { "id": "H2", "start": 143938127, "end": 148329459, "type": "gpos33" }, { "id": "H3", "start": 148329460, "end": 154184569, "type": "gneg" }, { "id": "H4", "start": 154184570, "end": 160039680, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1002756, "type": "tip" } ] }, "4": { "size": 156508116, "bands": [ { "id": "A1", "start": 3016925, "end": 14882673, "type": "gpos100" }, { "id": "A2", "start": 14882674, "end": 17763190, "type": "gneg" }, { "id": "A3", "start": 17763191, "end": 28325088, "type": "gpos100" }, { "id": "A4", "start": 28325089, "end": 30245433, "type": "gneg" }, { "id": "A5", "start": 30245434, "end": 43687847, "type": "gpos66" }, { "id": "B1", "start": 43687848, "end": 51849313, "type": "gneg" }, { "id": "B2", "start": 51849314, "end": 55209917, "type": "gpos33" }, { "id": "B3", "start": 55209918, "end": 63371383, "type": "gneg" }, { "id": "C1", "start": 63371384, "end": 69612504, "type": "gpos33" }, { "id": "C2", "start": 69612505, "end": 72012935, "type": "gneg" }, { "id": "C3", "start": 72012936, "end": 84015092, "type": "gpos100" }, { "id": "C4", "start": 84015093, "end": 89776127, "type": "gneg" }, { "id": "C5", "start": 89776128, "end": 97457507, "type": "gpos66" }, { "id": "C6", "start": 97457508, "end": 105618973, "type": "gneg" }, { "id": "C7", "start": 105618974, "end": 110899922, "type": "gpos66" }, { "id": "cenp", "start": 1005642, "end": 2011283, "type": "acen" }, { "id": "cenq", "start": 2011284, "end": 3016924, "type": "acen" }, { "id": "D1", "start": 110899923, "end": 117621129, "type": "gneg" }, { "id": "D2.1", "start": 117621130, "end": 120501647, "type": "gpos33" }, { "id": "D2.2", "start": 120501648, "end": 131063544, "type": "gneg" }, { "id": "D2.3", "start": 131063545, "end": 133944061, "type": "gpos33" }, { "id": "D3", "start": 133944062, "end": 141625441, "type": "gneg" }, { "id": "E1", "start": 141625442, "end": 147866562, "type": "gpos100" }, { "id": "E2", "start": 147866563, "end": 156508116, "type": "gneg" }, { "id": "tip", "start": 1, "end": 1005641, "type": "tip" } ] }, "5": { "size": 151834684, "bands": [ { "id": "A1", "start": 2986183, "end": 14895174, "type": "gpos100" }, { "id": "A2", "start": 14895175, "end": 16336642, "type": "gneg" }, { "id": "A3", "start": 16336643, "end": 25465943, "type": "gpos66" }, { "id": "B1", "start": 25465944, "end": 33634265, "type": "gneg" }, { "id": "B2", "start": 33634266, "end": 35556222, "type": "gpos33" }, { "id": "B3", "start": 35556223, "end": 50451397, "type": "gneg" }, { "id": "C1", "start": 50451398, "end": 58619719, "type": "gpos33" }, { "id": "C2", "start": 58619720, "end": 61022166, "type": "gneg" }, { "id": "C3.1", "start": 61022167, "end": 71592935, "type": "gpos100" }, { "id": "C3.2", "start": 71592936, "end": 73514894, "type": "gneg" }, { "id": "C3.3", "start": 73514895, "end": 77839299, "type": "gpos66" }, { "id": "cenp", "start": 995395, "end": 1990788, "type": "acen" }, { "id": "cenq", "start": 1990789, "end": 2986182, "type": "acen" }, { "id": "D", "start": 77839300, "end": 81683215, "type": "gneg" }, { "id": "E1", "start": 81683216, "end": 91293005, "type": "gpos100" }, { "id": "E2", "start": 91293006, "end": 93695452, "type": "gneg" }, { "id": "E3", "start": 93695453, "end": 99461326, "type": "gpos33" }, { "id": "E4", "start": 99461327, "end": 101863775, "type": "gneg" }, { "id": "E5", "start": 101863776, "end": 107629649, "type": "gpos33" }, { "id": "F", "start": 107629650, "end": 124927270, "type": "gneg" }, { "id": "G1.1", "start": 124927271, "end": 126849229, "type": "gpos33" }, { "id": "G1.2", "start": 126849230, "end": 127810207, "type": "gneg" }, { "id": "G1.3", "start": 127810208, "end": 130693144, "type": "gpos33" }, { "id": "G2", "start": 130693145, "end": 146068809, "type": "gneg" }, { "id": "G3", "start": 146068810, "end": 151834684, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 995394, "type": "tip" } ] }, "6": { "size": 149736546, "bands": [ { "id": "A1", "start": 3004405, "end": 16637393, "type": "gpos100" }, { "id": "A2", "start": 16637394, "end": 21530744, "type": "gneg" }, { "id": "A3.1", "start": 21530745, "end": 27402766, "type": "gpos100" }, { "id": "A3.2", "start": 27402767, "end": 28381436, "type": "gneg" }, { "id": "A3.3", "start": 28381437, "end": 34253457, "type": "gpos100" }, { "id": "B1", "start": 34253458, "end": 41593484, "type": "gneg" }, { "id": "B2.1", "start": 41593485, "end": 44529494, "type": "gpos66" }, { "id": "B2.2", "start": 44529495, "end": 45997500, "type": "gneg" }, { "id": "B2.3", "start": 45997501, "end": 50890851, "type": "gpos66" }, { "id": "B3", "start": 50890852, "end": 62634894, "type": "gneg" }, { "id": "C1", "start": 62634895, "end": 74378937, "type": "gpos100" }, { "id": "C2", "start": 74378938, "end": 76825612, "type": "gneg" }, { "id": "C3", "start": 76825613, "end": 86122980, "type": "gpos66" }, { "id": "cenp", "start": 1001469, "end": 2002936, "type": "acen" }, { "id": "cenq", "start": 2002937, "end": 3004404, "type": "acen" }, { "id": "D1", "start": 86122981, "end": 94441677, "type": "gneg" }, { "id": "D2", "start": 94441678, "end": 95909682, "type": "gpos33" }, { "id": "D3", "start": 95909683, "end": 103249709, "type": "gneg" }, { "id": "E1", "start": 103249710, "end": 108632395, "type": "gpos100" }, { "id": "E2", "start": 108632396, "end": 109611066, "type": "gneg" }, { "id": "E3", "start": 109611067, "end": 116951092, "type": "gpos100" }, { "id": "F1", "start": 116951093, "end": 122823113, "type": "gneg" }, { "id": "F2", "start": 122823114, "end": 125269789, "type": "gpos33" }, { "id": "F3", "start": 125269790, "end": 132120481, "type": "gneg" }, { "id": "G1", "start": 132120482, "end": 139460507, "type": "gpos66" }, { "id": "G2", "start": 139460508, "end": 142885854, "type": "gneg" }, { "id": "G3", "start": 142885855, "end": 149736546, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1001468, "type": "tip" } ] }, "7": { "size": 145441459, "bands": [ { "id": "A1", "start": 2860683, "end": 15202939, "type": "gpos100" }, { "id": "A2", "start": 15202940, "end": 18243527, "type": "gneg" }, { "id": "A3", "start": 18243528, "end": 28378820, "type": "gpos33" }, { "id": "B1", "start": 28378821, "end": 34459996, "type": "gneg" }, { "id": "B2", "start": 34459997, "end": 37500585, "type": "gpos33" }, { "id": "B3", "start": 37500585, "end": 47635877, "type": "gneg" }, { "id": "B4", "start": 47635878, "end": 54223818, "type": "gpos33" }, { "id": "B5", "start": 54223819, "end": 60811759, "type": "gneg" }, { "id": "C", "start": 60811760, "end": 71453817, "type": "gpos100" }, { "id": "cenp", "start": 953561, "end": 1907121, "type": "acen" }, { "id": "cenq", "start": 1907122, "end": 2860682, "type": "acen" }, { "id": "D1", "start": 71453818, "end": 77028228, "type": "gneg" }, { "id": "D2", "start": 77028229, "end": 80575581, "type": "gpos66" }, { "id": "D3", "start": 80575582, "end": 90204109, "type": "gneg" }, { "id": "E1", "start": 90204110, "end": 99832638, "type": "gpos100" }, { "id": "E2", "start": 99832639, "end": 102366461, "type": "gneg" }, { "id": "E3", "start": 102366462, "end": 111488225, "type": "gpos33" }, { "id": "F1", "start": 111488226, "end": 118582930, "type": "gneg" }, { "id": "F2", "start": 118582931, "end": 123143812, "type": "gpos33" }, { "id": "F3", "start": 123143813, "end": 137333224, "type": "gneg" }, { "id": "F4", "start": 137333225, "end": 140880576, "type": "gpos33" }, { "id": "F5", "start": 140880577, "end": 145441459, "type": "gneg" }, { "id": "tip", "start": 1, "end": 953560, "type": "tip" } ] }, "8": { "size": 129401213, "bands": [ { "id": "A1.1", "start": 2946767, "end": 15940728, "type": "gpos100" }, { "id": "A1.2", "start": 15940729, "end": 16878419, "type": "gneg" }, { "id": "A1.3", "start": 16878420, "end": 20160333, "type": "gpos33" }, { "id": "A2", "start": 20160334, "end": 29537233, "type": "gneg" }, { "id": "A3", "start": 29537234, "end": 33756838, "type": "gpos33" }, { "id": "A4", "start": 33756839, "end": 44071427, "type": "gneg" }, { "id": "B1.1", "start": 44071428, "end": 48291032, "type": "gpos66" }, { "id": "B1.2", "start": 48291033, "end": 50166412, "type": "gneg" }, { "id": "B1.3", "start": 50166413, "end": 55792551, "type": "gpos66" }, { "id": "B2", "start": 55792552, "end": 59543311, "type": "gneg" }, { "id": "B3.1", "start": 59543312, "end": 67044831, "type": "gpos100" }, { "id": "B3.2", "start": 67044832, "end": 67982520, "type": "gneg" }, { "id": "B3.3", "start": 67982521, "end": 74546350, "type": "gpos100" }, { "id": "C1", "start": 74546351, "end": 80172490, "type": "gneg" }, { "id": "C2", "start": 80172491, "end": 84860939, "type": "gpos33" }, { "id": "C3", "start": 84860940, "end": 90018235, "type": "gneg" }, { "id": "C4", "start": 90018236, "end": 91424769, "type": "gpos33" }, { "id": "C5", "start": 91424770, "end": 95644374, "type": "gneg" }, { "id": "cenp", "start": 982256, "end": 1964510, "type": "acen" }, { "id": "cenq", "start": 1964511, "end": 2946766, "type": "acen" }, { "id": "D1", "start": 95644375, "end": 103145894, "type": "gpos100" }, { "id": "D2", "start": 103145895, "end": 104083583, "type": "gneg" }, { "id": "D3", "start": 104083584, "end": 110647414, "type": "gpos33" }, { "id": "E1", "start": 110647414, "end": 123775073, "type": "gneg" }, { "id": "E2", "start": 123775074, "end": 129401213, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 982255, "type": "tip" } ] }, "9": { "size": 124595110, "bands": [ { "id": "A1", "start": 3012548, "end": 14412120, "type": "gpos100" }, { "id": "A2", "start": 14412121, "end": 19526099, "type": "gneg" }, { "id": "A3", "start": 19526100, "end": 24175170, "type": "gpos33" }, { "id": "A4", "start": 24175171, "end": 38122383, "type": "gneg" }, { "id": "A5.1", "start": 38122384, "end": 44166176, "type": "gpos66" }, { "id": "A5.2", "start": 44166177, "end": 46490712, "type": "gneg" }, { "id": "A5.3", "start": 46490713, "end": 54859040, "type": "gpos66" }, { "id": "B", "start": 54859041, "end": 63227368, "type": "gneg" }, { "id": "C", "start": 63227369, "end": 69736068, "type": "gpos33" }, { "id": "cenp", "start": 1004183, "end": 2008364, "type": "acen" }, { "id": "cenq", "start": 2008365, "end": 3012547, "type": "acen" }, { "id": "D", "start": 69736069, "end": 77639490, "type": "gneg" }, { "id": "E1", "start": 77639491, "end": 82753467, "type": "gpos33" }, { "id": "E2", "start": 82753468, "end": 84613096, "type": "gneg" }, { "id": "E3.1", "start": 84613097, "end": 91121796, "type": "gpos100" }, { "id": "E3.2", "start": 91121797, "end": 91586703, "type": "gneg" }, { "id": "E3.3", "start": 91586704, "end": 100884845, "type": "gpos100" }, { "id": "E4", "start": 100884846, "end": 101814660, "type": "gpos66" }, { "id": "F1", "start": 101814661, "end": 108323360, "type": "gneg" }, { "id": "F2", "start": 108323361, "end": 111112803, "type": "gpos33" }, { "id": "F3", "start": 111112804, "end": 119946038, "type": "gneg" }, { "id": "F4", "start": 119946039, "end": 124595110, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1004182, "type": "tip" } ] }, "10": { "size": 130694993, "bands": [ { "id": "A1", "start": 3016195, "end": 12822904, "type": "gpos100" }, { "id": "A2", "start": 12822905, "end": 17754791, "type": "gneg" }, { "id": "A3", "start": 17754792, "end": 23673055, "type": "gpos33" }, { "id": "A4", "start": 23673056, "end": 33536827, "type": "gneg" }, { "id": "B1", "start": 33536828, "end": 41427846, "type": "gpos100" }, { "id": "B2", "start": 41427847, "end": 48332487, "type": "gneg" }, { "id": "B3", "start": 48332488, "end": 56223505, "type": "gpos100" }, { "id": "B4", "start": 56223506, "end": 64114524, "type": "gneg" }, { "id": "B5.1", "start": 64114525, "end": 68060033, "type": "gpos100" }, { "id": "B5.2", "start": 68060034, "end": 68553222, "type": "gneg" }, { "id": "B5.3", "start": 68553223, "end": 74964674, "type": "gpos100" }, { "id": "C1", "start": 74964675, "end": 89267145, "type": "gneg" }, { "id": "C2", "start": 89267146, "end": 96171787, "type": "gpos33" }, { "id": "C3", "start": 96171788, "end": 99130918, "type": "gneg" }, { "id": "cenp", "start": 1005399, "end": 2010796, "type": "acen" }, { "id": "cenq", "start": 2010797, "end": 3016194, "type": "acen" }, { "id": "D1", "start": 99130919, "end": 111953823, "type": "gpos100" }, { "id": "D2", "start": 111953824, "end": 124776728, "type": "gneg" }, { "id": "D3", "start": 124776729, "end": 130694993, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1005398, "type": "tip" } ] }, "11": { "size": 122082543, "bands": [ { "id": "A1", "start": 3005877, "end": 13046988, "type": "gpos100" }, { "id": "A2", "start": 13046989, "end": 17240663, "type": "gneg" }, { "id": "A3.1", "start": 17240664, "end": 21900302, "type": "gpos100" }, { "id": "A3.2", "start": 21900303, "end": 25628014, "type": "gneg" }, { "id": "A3.3", "start": 25628015, "end": 30287653, "type": "gpos100" }, { "id": "A4", "start": 30287654, "end": 36345184, "type": "gneg" }, { "id": "A5", "start": 36345185, "end": 43334642, "type": "gpos100" }, { "id": "B1.1", "start": 43334643, "end": 47994281, "type": "gneg" }, { "id": "B1.2", "start": 47994282, "end": 49858137, "type": "gpos33" }, { "id": "B1.3", "start": 49858138, "end": 60109343, "type": "gneg" }, { "id": "B2", "start": 60109344, "end": 62905126, "type": "gpos33" }, { "id": "B3", "start": 62905127, "end": 70826512, "type": "gneg" }, { "id": "B4", "start": 70826513, "end": 74088260, "type": "gpos33" }, { "id": "B5", "start": 74088261, "end": 82009646, "type": "gneg" }, { "id": "C", "start": 82009647, "end": 90396996, "type": "gpos100" }, { "id": "cenp", "start": 1001959, "end": 2003917, "type": "acen" }, { "id": "cenq", "start": 2003918, "end": 3005876, "type": "acen" }, { "id": "D", "start": 90396997, "end": 102512058, "type": "gneg" }, { "id": "E1", "start": 102512059, "end": 110433444, "type": "gpos66" }, { "id": "E2", "start": 110433445, "end": 122082543, "type": "gneg" }, { "id": "tip", "start": 1, "end": 1001958, "type": "tip" } ] }, "12": { "size": 120129022, "bands": [ { "id": "A1.1", "start": 2972080, "end": 17601321, "type": "gpos100" }, { "id": "A1.2", "start": 17601322, "end": 21121586, "type": "gneg" }, { "id": "A1.3", "start": 21121587, "end": 25961949, "type": "gpos66" }, { "id": "A2", "start": 25961949, "end": 31682378, "type": "gneg" }, { "id": "A3", "start": 31682379, "end": 39162941, "type": "gpos33" }, { "id": "B1", "start": 39162942, "end": 44003304, "type": "gneg" }, { "id": "B2", "start": 44003305, "end": 44883370, "type": "gpos33" }, { "id": "B3", "start": 44883371, "end": 51923898, "type": "gneg" }, { "id": "C1", "start": 51923899, "end": 66004956, "type": "gpos100" }, { "id": "C2", "start": 66004957, "end": 71285352, "type": "gneg" }, { "id": "C3", "start": 71285353, "end": 80966079, "type": "gpos100" }, { "id": "cenp", "start": 990694, "end": 1981386, "type": "acen" }, { "id": "cenq", "start": 1981387, "end": 2972079, "type": "acen" }, { "id": "D1", "start": 80966080, "end": 85366410, "type": "gneg" }, { "id": "D2", "start": 85366411, "end": 88446642, "type": "gpos33" }, { "id": "D3", "start": 88446643, "end": 95487170, "type": "gneg" }, { "id": "E", "start": 95487171, "end": 106047964, "type": "gpos100" }, { "id": "F1", "start": 106047965, "end": 114408591, "type": "gneg" }, { "id": "F2", "start": 114408592, "end": 120129022, "type": "gpos66" }, { "id": "tip", "start": 1, "end": 990693, "type": "tip" } ] }, "13": { "size": 120421639, "bands": [ { "id": "A1", "start": 3003426, "end": 16286532, "type": "gpos100" }, { "id": "A2", "start": 16286533, "end": 21221846, "type": "gneg" }, { "id": "A3.1", "start": 21221847, "end": 29611877, "type": "gpos66" }, { "id": "A3.2", "start": 29611878, "end": 33066596, "type": "gneg" }, { "id": "A3.3", "start": 33066597, "end": 41456629, "type": "gpos33" }, { "id": "A4", "start": 41456630, "end": 44417817, "type": "gneg" }, { "id": "A5", "start": 44417818, "end": 52807849, "type": "gpos33" }, { "id": "B1", "start": 52807850, "end": 59223756, "type": "gneg" }, { "id": "B2", "start": 59223757, "end": 61691412, "type": "gpos33" }, { "id": "B3", "start": 61691413, "end": 69587913, "type": "gneg" }, { "id": "C1", "start": 69587914, "end": 78471477, "type": "gpos33" }, { "id": "C2", "start": 78471478, "end": 80939133, "type": "gneg" }, { "id": "C3", "start": 80939134, "end": 94758010, "type": "gpos100" }, { "id": "cenp", "start": 1001142, "end": 2002283, "type": "acen" }, { "id": "cenq", "start": 2002284, "end": 3003425, "type": "acen" }, { "id": "D1", "start": 94758011, "end": 106602762, "type": "gneg" }, { "id": "D2.1", "start": 106602763, "end": 110551012, "type": "gpos33" }, { "id": "D2.2", "start": 110551013, "end": 116473388, "type": "gneg" }, { "id": "D2.3", "start": 116473389, "end": 120421639, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1001141, "type": "tip" } ] }, "14": { "size": 124902244, "bands": [ { "id": "A1", "start": 2992989, "end": 14988268, "type": "gpos100" }, { "id": "A2", "start": 14988269, "end": 19484749, "type": "gneg" }, { "id": "A3", "start": 19484750, "end": 29976538, "type": "gpos33" }, { "id": "B", "start": 29976539, "end": 43465980, "type": "gneg" }, { "id": "C1", "start": 43465981, "end": 51959333, "type": "gpos100" }, { "id": "C2", "start": 51959334, "end": 54956987, "type": "gneg" }, { "id": "C3", "start": 54956988, "end": 59953076, "type": "gpos66" }, { "id": "cenp", "start": 997663, "end": 1995325, "type": "acen" }, { "id": "cenq", "start": 1995326, "end": 2992988, "type": "acen" }, { "id": "D1", "start": 59953077, "end": 68946037, "type": "gneg" }, { "id": "D2", "start": 68946038, "end": 72942909, "type": "gpos33" }, { "id": "D3", "start": 72942910, "end": 84933525, "type": "gneg" }, { "id": "E1", "start": 84933526, "end": 88930397, "type": "gpos66" }, { "id": "E2.1", "start": 88930398, "end": 98922576, "type": "gpos100" }, { "id": "E2.2", "start": 98922577, "end": 99921795, "type": "gneg" }, { "id": "E2.3", "start": 99921795, "end": 107415929, "type": "gpos100" }, { "id": "E3", "start": 107415930, "end": 110913192, "type": "gneg" }, { "id": "E4", "start": 110913193, "end": 120905371, "type": "gpos100" }, { "id": "E5", "start": 120905372, "end": 124902244, "type": "gneg" }, { "id": "tip", "start": 1, "end": 997662, "type": "tip" } ] }, "15": { "size": 104043685, "bands": [ { "id": "A1", "start": 3015906, "end": 16500319, "type": "gpos100" }, { "id": "A2", "start": 16500320, "end": 24292137, "type": "gneg" }, { "id": "B1", "start": 24292138, "end": 29792243, "type": "gpos33" }, { "id": "B2", "start": 29792244, "end": 32083955, "type": "gneg" }, { "id": "B3.1", "start": 32083956, "end": 43084168, "type": "gpos100" }, { "id": "B3.2", "start": 43084169, "end": 44917537, "type": "gneg" }, { "id": "B3.3", "start": 44917538, "end": 49959301, "type": "gpos66" }, { "id": "C", "start": 49959302, "end": 53626039, "type": "gneg" }, { "id": "cenp", "start": 1005302, "end": 2010603, "type": "acen" }, { "id": "cenq", "start": 2010604, "end": 3015905, "type": "acen" }, { "id": "D1", "start": 53626040, "end": 66459622, "type": "gpos100" }, { "id": "D2", "start": 66459623, "end": 68751333, "type": "gneg" }, { "id": "D3", "start": 68751334, "end": 77459835, "type": "gpos66" }, { "id": "E1", "start": 77459836, "end": 83876626, "type": "gneg" }, { "id": "E2", "start": 83876627, "end": 87085022, "type": "gpos33" }, { "id": "E3", "start": 87085023, "end": 95793524, "type": "gneg" }, { "id": "F1", "start": 95793525, "end": 101293631, "type": "gpos66" }, { "id": "F2", "start": 101293632, "end": 102210316, "type": "gneg" }, { "id": "F3", "start": 102210317, "end": 104043685, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 1005301, "type": "tip" } ] }, "16": { "size": 98207768, "bands": [ { "id": "A1", "start": 2996602, "end": 15432649, "type": "gpos100" }, { "id": "A2", "start": 15432650, "end": 16367961, "type": "gneg" }, { "id": "A3", "start": 16367962, "end": 20576864, "type": "gpos33" }, { "id": "B1", "start": 20576865, "end": 26188738, "type": "gneg" }, { "id": "B2", "start": 26188739, "end": 32268266, "type": "gpos33" }, { "id": "B3", "start": 32268267, "end": 38347794, "type": "gneg" }, { "id": "B4", "start": 38347795, "end": 44894979, "type": "gpos33" }, { "id": "B5", "start": 44894980, "end": 53780444, "type": "gneg" }, { "id": "C1.1", "start": 53780445, "end": 57989348, "type": "gpos66" }, { "id": "C1.2", "start": 57989349, "end": 58924660, "type": "gneg" }, { "id": "C1.3", "start": 58924661, "end": 66874813, "type": "gpos66" }, { "id": "C2", "start": 66874814, "end": 70616061, "type": "gneg" }, { "id": "C3.1", "start": 70616062, "end": 79033870, "type": "gpos100" }, { "id": "C3.2", "start": 79033871, "end": 79501525, "type": "gneg" }, { "id": "C3.3", "start": 79501526, "end": 91660583, "type": "gpos100" }, { "id": "C4", "start": 91660584, "end": 98207768, "type": "gneg" }, { "id": "cenp", "start": 998868, "end": 1997734, "type": "acen" }, { "id": "cenq", "start": 1997735, "end": 2996601, "type": "acen" }, { "id": "tip", "start": 1, "end": 998867, "type": "tip" } ] }, "17": { "size": 94987271, "bands": [ { "id": "A1", "start": 2991014, "end": 13943085, "type": "gpos100" }, { "id": "A2", "start": 13943086, "end": 16121691, "type": "gneg" }, { "id": "A3.1", "start": 16121692, "end": 17428856, "type": "gpos33" }, { "id": "A3.2", "start": 17428857, "end": 21786070, "type": "gneg" }, { "id": "A3.3", "start": 21786071, "end": 31371942, "type": "gpos66" }, { "id": "B1", "start": 31371943, "end": 40086370, "type": "gneg" }, { "id": "B2", "start": 40086371, "end": 41393535, "type": "gpos33" }, { "id": "B3", "start": 41393536, "end": 45750749, "type": "gneg" }, { "id": "C", "start": 45750750, "end": 55772342, "type": "gpos66" }, { "id": "cenp", "start": 997005, "end": 1994009, "type": "acen" }, { "id": "cenq", "start": 1994010, "end": 2991013, "type": "acen" }, { "id": "D", "start": 55772343, "end": 60129556, "type": "gneg" }, { "id": "E1.1", "start": 60129557, "end": 67972542, "type": "gpos100" }, { "id": "E1.2", "start": 67972543, "end": 68843984, "type": "gneg" }, { "id": "E1.3", "start": 68843985, "end": 73201199, "type": "gpos100" }, { "id": "E2", "start": 73201200, "end": 78429856, "type": "gneg" }, { "id": "E3", "start": 78429857, "end": 82787070, "type": "gpos33" }, { "id": "E4", "start": 82787071, "end": 88887170, "type": "gneg" }, { "id": "E5", "start": 88887171, "end": 94987271, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 997004, "type": "tip" } ] }, "18": { "size": 90702639, "bands": [ { "id": "A1", "start": 2997707, "end": 19406145, "type": "gpos100" }, { "id": "A2", "start": 19406146, "end": 29531091, "type": "gneg" }, { "id": "B1", "start": 29531092, "end": 35437309, "type": "gpos66" }, { "id": "B2", "start": 35437310, "end": 37124800, "type": "gneg" }, { "id": "B3", "start": 37124801, "end": 45562255, "type": "gpos100" }, { "id": "C", "start": 45562256, "end": 49780983, "type": "gneg" }, { "id": "cenp", "start": 999236, "end": 1998471, "type": "acen" }, { "id": "cenq", "start": 1998472, "end": 2997706, "type": "acen" }, { "id": "D1", "start": 49780984, "end": 53999710, "type": "gpos100" }, { "id": "D2", "start": 53999711, "end": 54421582, "type": "gneg" }, { "id": "D3", "start": 54421583, "end": 60749673, "type": "gpos100" }, { "id": "E1", "start": 60749674, "end": 67921510, "type": "gneg" }, { "id": "E2", "start": 67921511, "end": 75093346, "type": "gpos33" }, { "id": "E3", "start": 75093347, "end": 83530801, "type": "gneg" }, { "id": "E4", "start": 83530802, "end": 90702639, "type": "gpos33" }, { "id": "tip", "start": 1, "end": 999235, "type": "tip" } ] }, "19": { "size": 61431566, "bands": [ { "id": "A", "start": 3004360, "end": 16680093, "type": "gpos100" }, { "id": "B", "start": 16680094, "end": 25630388, "type": "gneg" }, { "id": "C1", "start": 25630389, "end": 34987514, "type": "gpos66" }, { "id": "C2", "start": 34987515, "end": 38242166, "type": "gneg" }, { "id": "C3", "start": 38242167, "end": 47599292, "type": "gpos66" }, { "id": "cenp", "start": 1001454, "end": 2002906, "type": "acen" }, { "id": "cenq", "start": 2002907, "end": 3004359, "type": "acen" }, { "id": "D1", "start": 47599293, "end": 51667607, "type": "gneg" }, { "id": "D2", "start": 51667608, "end": 58990576, "type": "gpos33" }, { "id": "D3", "start": 58990577, "end": 61431566, "type": "gneg" }, { "id": "tip", "start": 1, "end": 1001453, "type": "tip" } ] }, "X": { "size": 171031299, "bands": [ { "id": "A1.1", "start": 3078866, "end": 15772338, "type": "gpos100" }, { "id": "A1.2", "start": 15772339, "end": 18236766, "type": "gneg" }, { "id": "A1.3", "start": 18236767, "end": 21194079, "type": "gpos33" }, { "id": "A2", "start": 21194080, "end": 28094478, "type": "gneg" }, { "id": "A3.1", "start": 28094479, "end": 33516219, "type": "gpos66" }, { "id": "A3.2", "start": 33516220, "end": 34501990, "type": "gneg" }, { "id": "A3.3", "start": 34501991, "end": 39923731, "type": "gpos66" }, { "id": "A4", "start": 39923732, "end": 47809901, "type": "gneg" }, { "id": "A5", "start": 47809902, "end": 56188956, "type": "gpos66" }, { "id": "A6", "start": 56188957, "end": 63089355, "type": "gneg" }, { "id": "A7.1", "start": 63089356, "end": 69496866, "type": "gpos66" }, { "id": "A7.2", "start": 69496868, "end": 70975524, "type": "gneg" }, { "id": "A7.3", "start": 70975525, "end": 77383036, "type": "gpos66" }, { "id": "B", "start": 77383037, "end": 82311892, "type": "gneg" }, { "id": "C1", "start": 82311893, "end": 91183833, "type": "gpos100" }, { "id": "C2", "start": 91183834, "end": 92169603, "type": "gneg" }, { "id": "C3", "start": 92169604, "end": 101041544, "type": "gpos100" }, { "id": "cenp", "start": 1026289, "end": 2052577, "type": "acen" }, { "id": "cenq", "start": 2052578, "end": 3078865, "type": "acen" }, { "id": "D", "start": 101041545, "end": 109913485, "type": "gneg" }, { "id": "E1", "start": 109913486, "end": 120264082, "type": "gpos100" }, { "id": "E2", "start": 120264084, "end": 121249853, "type": "gneg" }, { "id": "E3", "start": 121249854, "end": 135050651, "type": "gpos100" }, { "id": "F1", "start": 135050652, "end": 141458162, "type": "gneg" }, { "id": "F2", "start": 141458163, "end": 148851447, "type": "gpos33" }, { "id": "F3", "start": 148851448, "end": 156244730, "type": "gneg" }, { "id": "F4", "start": 156244731, "end": 163638014, "type": "gpos33" }, { "id": "F5", "start": 163638015, "end": 171031299, "type": "gneg" }, { "id": "tip", "start": 1, "end": 1026288, "type": "tip" } ] }, "Y": { "size": 91744698, "bands": [ { "id": "A1", "start": 5, "end": 20642552, "type": "gpos100" }, { "id": "A2", "start": 20642557, "end": 32684047, "type": "gpos66" }, { "id": "B", "start": 32684053, "end": 45298941, "type": "gpos33" }, { "id": "C1", "start": 45298947, "end": 54473414, "type": "gpos100" }, { "id": "C2", "start": 54473420, "end": 61927667, "type": "gpos33" }, { "id": "C3", "start": 61927673, "end": 72248949, "type": "gpos100" }, { "id": "D", "start": 72248955, "end": 83143629, "type": "gpos33" }, { "id": "E", "start": 83143635, "end": 91744698, "type": "gpos66" } ] }, "MT": { "size": 16299, "bands": [ { "start": 1, "end": 16299 } ] } };
RNAcentral/angularjs-genoverse
lib/Genoverse/js/genomes/mus_musculus.js
JavaScript
apache-2.0
53,885
/** * 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 * as dom from './dom'; import {AmpEvents} from './amp-events'; import {CommonSignals} from './common-signals'; import {ElementStub} from './element-stub'; import { Layout, applyStaticLayout, isInternalElement, isLoadingAllowed, } from './layout'; import {LayoutDelayMeter} from './layout-delay-meter'; import {ResourceState} from './service/resource'; import {Services} from './services'; import {Signals} from './utils/signals'; import {blockedByConsentError, isBlockedByConsent, reportError} from './error'; import {createLoaderElement} from '../src/loader.js'; import {dev, devAssert, rethrowAsync, user, userAssert} from './log'; import {getIntersectionChangeEntry} from '../src/utils/intersection-observer-polyfill'; import {getMode} from './mode'; import {htmlFor} from './static-template'; import {parseSizeList} from './size-list'; import {setStyle} from './style'; import {shouldBlockOnConsentByMeta} from '../src/consent'; import {startupChunk} from './chunk'; import {toWin} from './types'; import {tryResolve} from '../src/utils/promise'; const TAG = 'CustomElement'; /** * @enum {number} */ const UpgradeState = { NOT_UPGRADED: 1, UPGRADED: 2, UPGRADE_FAILED: 3, UPGRADE_IN_PROGRESS: 4, }; /** * Caches whether the template tag is supported to avoid memory allocations. * @type {boolean|undefined} */ let templateTagSupported; /** * Whether this platform supports template tags. * @return {boolean} */ function isTemplateTagSupported() { if (templateTagSupported === undefined) { const template = self.document.createElement('template'); templateTagSupported = 'content' in template; } return templateTagSupported; } /** * Creates a named custom element class. * * @param {!Window} win The window in which to register the custom element. * @return {typeof AmpElement} The custom element class. */ export function createCustomElementClass(win) { const BaseCustomElement = /** @type {typeof HTMLElement} */ (createBaseCustomElementClass( win )); // It's necessary to create a subclass, because the same "base" class cannot // be registered to multiple custom elements. class CustomAmpElement extends BaseCustomElement {} return /** @type {typeof AmpElement} */ (CustomAmpElement); } /** * Creates a base custom element class. * * @param {!Window} win The window in which to register the custom element. * @return {typeof HTMLElement} */ function createBaseCustomElementClass(win) { if (win.__AMP_BASE_CE_CLASS) { return win.__AMP_BASE_CE_CLASS; } const htmlElement = /** @type {typeof HTMLElement} */ (win.HTMLElement); /** * @abstract @extends {HTMLElement} */ class BaseCustomElement extends htmlElement { /** */ constructor() { super(); this.createdCallback(); } /** * Called when elements is created. Sets instance vars since there is no * constructor. * @final */ createdCallback() { // Flag "notbuilt" is removed by Resource manager when the resource is // considered to be built. See "setBuilt" method. /** @private {boolean} */ this.built_ = false; /** * Several APIs require the element to be connected to the DOM tree, but * the CustomElement lifecycle APIs are async. This lead to subtle bugs * that require state tracking. See #12849, https://crbug.com/821195, and * https://bugs.webkit.org/show_bug.cgi?id=180940. * @private {boolean} */ this.isConnected_ = false; /** @private {?Promise} */ this.buildingPromise_ = null; /** @type {string} */ this.readyState = 'loading'; /** @type {boolean} */ this.everAttached = false; /** * Ampdoc can only be looked up when an element is attached. * @private {?./service/ampdoc-impl.AmpDoc} */ this.ampdoc_ = null; /** * Resources can only be looked up when an element is attached. * @private {?./service/resources-interface.ResourcesInterface} */ this.resources_ = null; /** @private {!Layout} */ this.layout_ = Layout.NODISPLAY; /** @private {number} */ this.layoutWidth_ = -1; /** @private {number} */ this.layoutHeight_ = -1; /** @private {number} */ this.layoutCount_ = 0; /** @private {boolean} */ this.isFirstLayoutCompleted_ = false; /** @private {boolean} */ this.isInViewport_ = false; /** @private {boolean} */ this.paused_ = false; /** @private {string|null|undefined} */ this.mediaQuery_ = undefined; /** @private {!./size-list.SizeList|null|undefined} */ this.sizeList_ = undefined; /** @private {!./size-list.SizeList|null|undefined} */ this.heightsList_ = undefined; /** @public {boolean} */ this.warnOnMissingOverflow = true; /** * This element can be assigned by the {@link applyStaticLayout} to a * child element that will be used to size this element. * @package {?Element|undefined} */ this.sizerElement = undefined; /** @private {boolean|undefined} */ this.loadingDisabled_ = undefined; /** @private {boolean|undefined} */ this.loadingState_ = undefined; /** @private {?Element} */ this.loadingContainer_ = null; /** @private {?Element} */ this.loadingElement_ = null; /** @private {?Element|undefined} */ this.overflowElement_ = undefined; /** * The time at which this element was scheduled for layout relative to * the epoch. This value will be set to 0 until the this element has been * scheduled. * Note that this value may change over time if the element is enqueued, * then dequeued and re-enqueued by the scheduler. * @type {number|undefined} */ this.layoutScheduleTime = undefined; // Closure compiler appears to mark HTMLElement as @struct which // disables bracket access. Force this with a type coercion. const nonStructThis = /** @type {!Object} */ (this); // `opt_implementationClass` is only used for tests. let Ctor = win.__AMP_EXTENDED_ELEMENTS && win.__AMP_EXTENDED_ELEMENTS[this.localName]; if (getMode().test && nonStructThis['implementationClassForTesting']) { Ctor = nonStructThis['implementationClassForTesting']; } devAssert(Ctor); /** @private {!./base-element.BaseElement} */ this.implementation_ = new Ctor(this); /** * An element always starts in a unupgraded state until it's added to DOM * for the first time in which case it can be upgraded immediately or wait * for script download or `upgradeCallback`. * @private {!UpgradeState} */ this.upgradeState_ = UpgradeState.NOT_UPGRADED; /** * Time delay imposed by baseElement upgradeCallback. If no * upgradeCallback specified or not yet executed, delay is 0. * @private {number} */ this.upgradeDelayMs_ = 0; /** * Action queue is initially created and kept around until the element * is ready to send actions directly to the implementation. * - undefined initially * - array if used * - null after unspun * @private {?Array<!./service/action-impl.ActionInvocation>|undefined} */ this.actionQueue_ = undefined; /** * Whether the element is in the template. * @private {boolean|undefined} */ this.isInTemplate_ = undefined; /** @private @const */ this.signals_ = new Signals(); const perf = Services.performanceForOrNull(win); /** @private {boolean} */ this.perfOn_ = perf && perf.isPerformanceTrackingOn(); /** @private {?./layout-delay-meter.LayoutDelayMeter} */ this.layoutDelayMeter_ = null; if (nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_RESOLVER]) { nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_RESOLVER](nonStructThis); delete nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_RESOLVER]; delete nonStructThis[dom.UPGRADE_TO_CUSTOMELEMENT_PROMISE]; } } /** @return {!Signals} */ signals() { return this.signals_; } /** * Returns the associated ampdoc. Only available after attachment. It throws * exception before the element is attached. * @return {!./service/ampdoc-impl.AmpDoc} * @final * @package */ getAmpDoc() { devAssert(this.ampdoc_, 'no ampdoc yet, since element is not attached'); return /** @type {!./service/ampdoc-impl.AmpDoc} */ (this.ampdoc_); } /** * Returns Resources manager. Only available after attachment. It throws * exception before the element is attached. * @return {!./service/resources-interface.ResourcesInterface} * @final * @package */ getResources() { devAssert( this.resources_, 'no resources yet, since element is not attached' ); return /** @type {!./service/resources-interface.ResourcesInterface} */ (this .resources_); } /** * Whether the element has been upgraded yet. Always returns false when * the element has not yet been added to DOM. After the element has been * added to DOM, the value depends on the `BaseElement` implementation and * its `upgradeElement` callback. * @return {boolean} * @final */ isUpgraded() { return this.upgradeState_ == UpgradeState.UPGRADED; } /** @return {!Promise} */ whenUpgraded() { return this.signals_.whenSignal(CommonSignals.UPGRADED); } /** * Upgrades the element to the provided new implementation. If element * has already been attached, it's layout validation and attachment flows * are repeated for the new implementation. * @param {typeof ./base-element.BaseElement} newImplClass * @final @package */ upgrade(newImplClass) { if (this.isInTemplate_) { return; } if (this.upgradeState_ != UpgradeState.NOT_UPGRADED) { // Already upgraded or in progress or failed. return; } this.implementation_ = new newImplClass(this); if (this.everAttached) { // Usually, we do an implementation upgrade when the element is // attached to the DOM. But, if it hadn't yet upgraded from // ElementStub, we couldn't. Now that it's upgraded from a stub, go // ahead and do the full upgrade. this.tryUpgrade_(); } } /** * Time delay imposed by baseElement upgradeCallback. If no * upgradeCallback specified or not yet executed, delay is 0. * @return {number} */ getUpgradeDelayMs() { return this.upgradeDelayMs_; } /** * Completes the upgrade of the element with the provided implementation. * @param {!./base-element.BaseElement} newImpl * @param {number} upgradeStartTime * @final @private */ completeUpgrade_(newImpl, upgradeStartTime) { this.upgradeDelayMs_ = win.Date.now() - upgradeStartTime; this.upgradeState_ = UpgradeState.UPGRADED; this.implementation_ = newImpl; this.classList.remove('amp-unresolved'); this.classList.remove('i-amphtml-unresolved'); this.implementation_.createdCallback(); this.assertLayout_(); // TODO(wg-runtime): Don't set BaseElement ivars externally. this.implementation_.layout_ = this.layout_; this.implementation_.firstAttachedCallback(); this.dispatchCustomEventForTesting(AmpEvents.ATTACHED); this.getResources().upgraded(this); this.signals_.signal(CommonSignals.UPGRADED); } /** @private */ assertLayout_() { if ( this.layout_ != Layout.NODISPLAY && !this.implementation_.isLayoutSupported(this.layout_) ) { userAssert( this.getAttribute('layout'), 'The element did not specify a layout attribute. ' + 'Check https://amp.dev/documentation/guides-and-tutorials/' + 'develop/style_and_layout/control_layout and the respective ' + 'element documentation for details.' ); userAssert(false, `Layout not supported: ${this.layout_}`); } } /** * Whether the element has been built. A built element had its * {@link buildCallback} method successfully invoked. * @return {boolean} * @final */ isBuilt() { return this.built_; } /** * Returns the promise that's resolved when the element has been built. If * the build fails, the resulting promise is rejected. * @return {!Promise} */ whenBuilt() { return this.signals_.whenSignal(CommonSignals.BUILT); } /** * Get the priority to load the element. * @return {number} */ getLayoutPriority() { devAssert(this.isUpgraded(), 'Cannot get priority of unupgraded element'); return this.implementation_.getLayoutPriority(); } /** * TODO(wg-runtime, #25824): Make Resource.getLayoutBox() the source of truth. * @return {number} * @deprecated */ getLayoutWidth() { return this.layoutWidth_; } /** * Get the default action alias. * @return {?string} */ getDefaultActionAlias() { devAssert( this.isUpgraded(), 'Cannot get default action alias of unupgraded element' ); return this.implementation_.getDefaultActionAlias(); } /** @return {boolean} */ isBuilding() { return !!this.buildingPromise_; } /** * Requests or requires the element to be built. The build is done by * invoking {@link BaseElement.buildCallback} method. * * Can only be called on a upgraded element. May only be called from * resource.js to ensure an element and its resource are in sync. * * @return {?Promise} * @final */ build() { assertNotTemplate(this); devAssert(this.isUpgraded(), 'Cannot build unupgraded element'); if (this.buildingPromise_) { return this.buildingPromise_; } return (this.buildingPromise_ = new Promise((resolve, reject) => { const policyId = this.getConsentPolicy_(); if (!policyId) { resolve(this.implementation_.buildCallback()); } else { Services.consentPolicyServiceForDocOrNull(this) .then((policy) => { if (!policy) { return true; } return policy.whenPolicyUnblock(/** @type {string} */ (policyId)); }) .then((shouldUnblock) => { if (shouldUnblock) { resolve(this.implementation_.buildCallback()); } else { reject(blockedByConsentError()); } }); } }).then( () => { this.preconnect(/* onLayout */ false); this.built_ = true; this.classList.remove('i-amphtml-notbuilt'); this.classList.remove('amp-notbuilt'); this.signals_.signal(CommonSignals.BUILT); if (this.isInViewport_) { this.updateInViewport_(true); } if (this.actionQueue_) { // Only schedule when the queue is not empty, which should be // the case 99% of the time. Services.timerFor(toWin(this.ownerDocument.defaultView)).delay( this.dequeueActions_.bind(this), 1 ); } if (!this.getPlaceholder()) { const placeholder = this.createPlaceholder(); if (placeholder) { this.appendChild(placeholder); } } }, (reason) => { this.signals_.rejectSignal( CommonSignals.BUILT, /** @type {!Error} */ (reason) ); if (!isBlockedByConsent(reason)) { reportError(reason, this); } throw reason; } )); } /** * Called to instruct the element to preconnect to hosts it uses during * layout. * @param {boolean} onLayout Whether this was called after a layout. */ preconnect(onLayout) { if (onLayout) { this.implementation_.preconnectCallback(onLayout); } else { // If we do early preconnects we delay them a bit. This is kind of // an unfortunate trade off, but it seems faster, because the DOM // operations themselves are not free and might delay startupChunk(this.getAmpDoc(), () => { const TAG = this.tagName; if (!this.ownerDocument) { dev().error(TAG, 'preconnect without ownerDocument'); return; } else if (!this.ownerDocument.defaultView) { dev().error(TAG, 'preconnect without defaultView'); return; } this.implementation_.preconnectCallback(onLayout); }); } } /** * Whether the custom element declares that it has to be fixed. * @return {boolean} */ isAlwaysFixed() { return this.implementation_.isAlwaysFixed(); } /** * Updates the layout box of the element. * Should only be called by Resources. * @param {!./layout-rect.LayoutRectDef} layoutBox * @param {boolean} sizeChanged */ updateLayoutBox(layoutBox, sizeChanged = false) { this.layoutWidth_ = layoutBox.width; this.layoutHeight_ = layoutBox.height; if (this.isBuilt()) { this.onMeasure(sizeChanged); } } /** * Calls onLayoutMeasure() (and onMeasureChanged() if size changed) * on the BaseElement implementation. * Should only be called by Resources. * @param {boolean} sizeChanged */ onMeasure(sizeChanged = false) { devAssert(this.isBuilt()); try { this.implementation_.onLayoutMeasure(); if (sizeChanged) { this.implementation_.onMeasureChanged(); } } catch (e) { reportError(e, this); } } /** * @return {?Element} * @private */ getSizer_() { if ( this.sizerElement === undefined && (this.layout_ === Layout.RESPONSIVE || this.layout_ === Layout.INTRINSIC) ) { // Expect sizer to exist, just not yet discovered. this.sizerElement = this.querySelector('i-amphtml-sizer'); } return this.sizerElement || null; } /** * @param {Element} sizer * @private */ resetSizer_(sizer) { if (this.layout_ === Layout.RESPONSIVE) { setStyle(sizer, 'paddingTop', '0'); return; } if (this.layout_ === Layout.INTRINSIC) { const intrinsicSizerImg = sizer.querySelector( '.i-amphtml-intrinsic-sizer' ); if (!intrinsicSizerImg) { return; } intrinsicSizerImg.setAttribute('src', ''); return; } } /** * If the element has a media attribute, evaluates the value as a media * query and based on the result adds or removes the class * `i-amphtml-hidden-by-media-query`. The class adds display:none to the * element which in turn prevents any of the resource loading to happen for * the element. * * This method is called by Resources and shouldn't be called by anyone * else. * * @final * @package */ applySizesAndMediaQuery() { assertNotTemplate(this); // Media query. if (this.mediaQuery_ === undefined) { this.mediaQuery_ = this.getAttribute('media') || null; } if (this.mediaQuery_) { const {defaultView} = this.ownerDocument; this.classList.toggle( 'i-amphtml-hidden-by-media-query', !defaultView.matchMedia(this.mediaQuery_).matches ); } // Sizes. if (this.sizeList_ === undefined) { const sizesAttr = this.getAttribute('sizes'); const isDisabled = this.hasAttribute('disable-inline-width'); this.sizeList_ = !isDisabled && sizesAttr ? parseSizeList(sizesAttr) : null; } if (this.sizeList_) { setStyle( this, 'width', this.sizeList_.select(toWin(this.ownerDocument.defaultView)) ); } // Heights. if ( this.heightsList_ === undefined && this.layout_ === Layout.RESPONSIVE ) { const heightsAttr = this.getAttribute('heights'); this.heightsList_ = heightsAttr ? parseSizeList(heightsAttr, /* allowPercent */ true) : null; } if (this.heightsList_) { const sizer = this.getSizer_(); if (sizer) { setStyle( sizer, 'paddingTop', this.heightsList_.select(toWin(this.ownerDocument.defaultView)) ); } } } /** * Applies a size change to the element. * * This method is called by Resources and shouldn't be called by anyone * else. This method must always be called in the mutation context. * * @param {number|undefined} newHeight * @param {number|undefined} newWidth * @param {!./layout-rect.LayoutMarginsDef=} opt_newMargins * @final * @package */ applySize(newHeight, newWidth, opt_newMargins) { const sizer = this.getSizer_(); if (sizer) { // From the moment height is changed the element becomes fully // responsible for managing its height. Aspect ratio is no longer // preserved. this.sizerElement = null; this.resetSizer_(sizer); this.mutateOrInvoke_(() => { if (sizer) { dom.removeElement(sizer); } }); } if (newHeight !== undefined) { setStyle(this, 'height', newHeight, 'px'); } if (newWidth !== undefined) { setStyle(this, 'width', newWidth, 'px'); } if (opt_newMargins) { if (opt_newMargins.top != null) { setStyle(this, 'marginTop', opt_newMargins.top, 'px'); } if (opt_newMargins.right != null) { setStyle(this, 'marginRight', opt_newMargins.right, 'px'); } if (opt_newMargins.bottom != null) { setStyle(this, 'marginBottom', opt_newMargins.bottom, 'px'); } if (opt_newMargins.left != null) { setStyle(this, 'marginLeft', opt_newMargins.left, 'px'); } } if (this.isAwaitingSize_()) { this.sizeProvided_(); } this.dispatchCustomEvent(AmpEvents.SIZE_CHANGED); } /** * Called when the element is first connected to the DOM. Calls * {@link firstAttachedCallback} if this is the first attachment. * * This callback is guarded by checks to see if the element is still * connected. Chrome and Safari can trigger connectedCallback even when * the node is disconnected. See #12849, https://crbug.com/821195, and * https://bugs.webkit.org/show_bug.cgi?id=180940. Thankfully, * connectedCallback will later be called when the disconnected root is * connected to the document tree. * * @final */ connectedCallback() { if (!isTemplateTagSupported() && this.isInTemplate_ === undefined) { this.isInTemplate_ = !!dom.closestAncestorElementBySelector( this, 'template' ); } if (this.isInTemplate_) { return; } if (this.isConnected_ || !dom.isConnectedNode(this)) { return; } this.isConnected_ = true; if (!this.everAttached) { this.classList.add('i-amphtml-element'); this.classList.add('i-amphtml-notbuilt'); this.classList.add('amp-notbuilt'); } if (!this.ampdoc_) { // Ampdoc can now be initialized. const win = toWin(this.ownerDocument.defaultView); const ampdocService = Services.ampdocServiceFor(win); const ampdoc = ampdocService.getAmpDoc(this); this.ampdoc_ = ampdoc; // Load the pre-stubbed extension if needed. const extensionId = this.tagName.toLowerCase(); if ( isStub(this.implementation_) && !ampdoc.declaresExtension(extensionId) ) { Services.extensionsFor(win).installExtensionForDoc( ampdoc, extensionId ); } } if (!this.resources_) { // Resources can now be initialized since the ampdoc is now available. this.resources_ = Services.resourcesForDoc(this.ampdoc_); } this.getResources().add(this); if (this.everAttached) { const reconstruct = this.reconstructWhenReparented(); if (reconstruct) { this.reset_(); } if (this.isUpgraded()) { if (reconstruct) { this.getResources().upgraded(this); } this.dispatchCustomEventForTesting(AmpEvents.ATTACHED); } } else { this.everAttached = true; try { this.layout_ = applyStaticLayout( this, Services.platformFor(toWin(this.ownerDocument.defaultView)).isIe() ); } catch (e) { reportError(e, this); } if (!isStub(this.implementation_)) { this.tryUpgrade_(); } if (!this.isUpgraded()) { this.classList.add('amp-unresolved'); this.classList.add('i-amphtml-unresolved'); // amp:attached is dispatched from the ElementStub class when it // replayed the firstAttachedCallback call. this.dispatchCustomEventForTesting(AmpEvents.STUBBED); } // Classically, sizes/media queries are applied just before // Resource.measure. With IntersectionObserver, observe() is the // equivalent which happens above in Resources.add(). Applying here // also avoids unnecessary reinvocation during reparenting. if (this.getResources().isIntersectionExperimentOn()) { this.applySizesAndMediaQuery(); } } } /** * @return {boolean} * @private */ isAwaitingSize_() { return this.classList.contains('i-amphtml-layout-awaiting-size'); } /** * @private */ sizeProvided_() { this.classList.remove('i-amphtml-layout-awaiting-size'); } /** The Custom Elements V0 sibling to `connectedCallback`. */ attachedCallback() { this.connectedCallback(); } /** * Try to upgrade the element with the provided implementation. * @private @final */ tryUpgrade_() { const impl = this.implementation_; devAssert(!isStub(impl), 'Implementation must not be a stub'); if (this.upgradeState_ != UpgradeState.NOT_UPGRADED) { // Already upgraded or in progress or failed. return; } // The `upgradeCallback` only allows redirect once for the top-level // non-stub class. We may allow nested upgrades later, but they will // certainly be bad for performance. this.upgradeState_ = UpgradeState.UPGRADE_IN_PROGRESS; const startTime = win.Date.now(); const res = impl.upgradeCallback(); if (!res) { // Nothing returned: the current object is the upgraded version. this.completeUpgrade_(impl, startTime); } else if (typeof res.then == 'function') { // It's a promise: wait until it's done. res .then((upgrade) => { this.completeUpgrade_(upgrade || impl, startTime); }) .catch((reason) => { this.upgradeState_ = UpgradeState.UPGRADE_FAILED; rethrowAsync(reason); }); } else { // It's an actual instance: upgrade immediately. this.completeUpgrade_( /** @type {!./base-element.BaseElement} */ (res), startTime ); } } /** * Called when the element is disconnected from the DOM. * * @final */ disconnectedCallback() { this.disconnect(/* pretendDisconnected */ false); } /** The Custom Elements V0 sibling to `disconnectedCallback`. */ detachedCallback() { this.disconnectedCallback(); } /** * Called when an element is disconnected from DOM, or when an ampDoc is * being disconnected (the element itself may still be connected to ampDoc). * * This callback is guarded by checks to see if the element is still * connected. See #12849, https://crbug.com/821195, and * https://bugs.webkit.org/show_bug.cgi?id=180940. * If the element is still connected to the document, you'll need to pass * opt_pretendDisconnected. * * @param {boolean} pretendDisconnected Forces disconnection regardless * of DOM isConnected. */ disconnect(pretendDisconnected) { if (this.isInTemplate_ || !this.isConnected_) { return; } if (!pretendDisconnected && dom.isConnectedNode(this)) { return; } // This path only comes from Resource#disconnect, which deletes the // Resource instance tied to this element. Therefore, it is no longer // an AMP Element. But, DOM queries for i-amphtml-element assume that // the element is tied to a Resource. if (pretendDisconnected) { this.classList.remove('i-amphtml-element'); } this.isConnected_ = false; this.getResources().remove(this); this.implementation_.detachedCallback(); } /** * Dispatches a custom event. * * @param {string} name * @param {!Object=} opt_data Event data. * @final */ dispatchCustomEvent(name, opt_data) { const data = opt_data || {}; // Constructors of events need to come from the correct window. Sigh. const event = this.ownerDocument.createEvent('Event'); event.data = data; event.initEvent(name, /* bubbles */ true, /* cancelable */ true); this.dispatchEvent(event); } /** * Dispatches a custom event only in testing environment. * * @param {string} name * @param {!Object=} opt_data Event data. * @final */ dispatchCustomEventForTesting(name, opt_data) { if (!getMode().test) { return; } this.dispatchCustomEvent(name, opt_data); } /** * Whether the element can pre-render. * @return {boolean} * @final */ prerenderAllowed() { return this.implementation_.prerenderAllowed(); } /** * Whether the element has render-blocking service. * @return {boolean} * @final */ isBuildRenderBlocking() { return this.implementation_.isBuildRenderBlocking(); } /** * Creates a placeholder for the element. * @return {?Element} * @final */ createPlaceholder() { return this.implementation_.createPlaceholderCallback(); } /** * Creates a loader logo. * @return {{ * content: (!Element|undefined), * color: (string|undefined), * }} * @final */ createLoaderLogo() { return this.implementation_.createLoaderLogoCallback(); } /** * Whether the element should ever render when it is not in viewport. * @return {boolean|number} * @final */ renderOutsideViewport() { return this.implementation_.renderOutsideViewport(); } /** * Whether the element should render outside of renderOutsideViewport when * the scheduler is idle. * @return {boolean|number} * @final */ idleRenderOutsideViewport() { return this.implementation_.idleRenderOutsideViewport(); } /** * Returns a previously measured layout box adjusted to the viewport. This * mainly affects fixed-position elements that are adjusted to be always * relative to the document position in the viewport. * @return {!./layout-rect.LayoutRectDef} * @final */ getLayoutBox() { return this.getResource_().getLayoutBox(); } /** * Returns a previously measured layout box relative to the page. The * fixed-position elements are relative to the top of the document. * @return {!./layout-rect.LayoutRectDef} * @final */ getPageLayoutBox() { return this.getResource_().getPageLayoutBox(); } /** * @return {?Element} * @final */ getOwner() { return this.getResource_().getOwner(); } /** * Returns a change entry for that should be compatible with * IntersectionObserverEntry. * @return {!IntersectionObserverEntry} A change entry. * @final */ getIntersectionChangeEntry() { const box = this.implementation_.getIntersectionElementLayoutBox(); const owner = this.getOwner(); const viewportBox = this.implementation_.getViewport().getRect(); // TODO(jridgewell, #4826): We may need to make this recursive. const ownerBox = owner && owner.getLayoutBox(); return getIntersectionChangeEntry(box, ownerBox, viewportBox); } /** * Returns the resource of the element. * @return {!./service/resource.Resource} * @private */ getResource_() { return this.getResources().getResourceForElement(this); } /** * Returns the resource ID of the element. * @return {number} */ getResourceId() { return this.getResource_().getId(); } /** * The runtime calls this method to determine if {@link layoutCallback} * should be called again when layout changes. * @return {boolean} * @package @final */ isRelayoutNeeded() { return this.implementation_.isRelayoutNeeded(); } /** * Returns reference to upgraded implementation. * @param {boolean} waitForBuild If true, waits for element to be built before * resolving the returned Promise. Default is true. * @return {!Promise<!./base-element.BaseElement>} */ getImpl(waitForBuild = true) { const waitFor = waitForBuild ? this.whenBuilt() : this.whenUpgraded(); return waitFor.then(() => this.implementation_); } /** * Returns the layout of the element. * @return {!Layout} */ getLayout() { return this.layout_; } /** * Instructs the element to layout its content and load its resources if * necessary by calling the {@link BaseElement.layoutCallback} method that * should be implemented by BaseElement subclasses. Must return a promise * that will yield when the layout and associated loadings are complete. * * This method is always called for the first layout, but for subsequent * layouts the runtime consults {@link isRelayoutNeeded} method. * * Can only be called on a upgraded and built element. * * @return {!Promise} * @package @final */ layoutCallback() { assertNotTemplate(this); devAssert(this.isBuilt(), 'Must be built to receive viewport events'); this.dispatchCustomEventForTesting(AmpEvents.LOAD_START); const isLoadEvent = this.layoutCount_ == 0; // First layout is "load". this.signals_.reset(CommonSignals.UNLOAD); if (isLoadEvent) { this.signals_.signal(CommonSignals.LOAD_START); } if (this.perfOn_) { this.getLayoutDelayMeter_().startLayout(); } const promise = tryResolve(() => this.implementation_.layoutCallback()); this.preconnect(/* onLayout */ true); this.classList.add('i-amphtml-layout'); return promise.then( () => { if (isLoadEvent) { this.signals_.signal(CommonSignals.LOAD_END); } this.readyState = 'complete'; this.layoutCount_++; this.toggleLoading(false, {cleanup: true}); // Check if this is the first success layout that needs // to call firstLayoutCompleted. if (!this.isFirstLayoutCompleted_) { this.implementation_.firstLayoutCompleted(); this.isFirstLayoutCompleted_ = true; this.dispatchCustomEventForTesting(AmpEvents.LOAD_END); } }, (reason) => { // add layoutCount_ by 1 despite load fails or not if (isLoadEvent) { this.signals_.rejectSignal( CommonSignals.LOAD_END, /** @type {!Error} */ (reason) ); } this.layoutCount_++; this.toggleLoading(false, {cleanup: true}); throw reason; } ); } /** * Whether the resource is currently visible in the viewport. * @return {boolean} * @final @package */ isInViewport() { return this.isInViewport_; } /** * Instructs the resource that it entered or exited the visible viewport. * * Can only be called on a upgraded and built element. * * @param {boolean} inViewport Whether the element has entered or exited * the visible viewport. * @final @package */ viewportCallback(inViewport) { assertNotTemplate(this); if (inViewport == this.isInViewport_) { return; } // TODO(dvoytenko, #9177): investigate/cleanup viewport signals for // elements in dead iframes. if (!this.ownerDocument || !this.ownerDocument.defaultView) { return; } this.isInViewport_ = inViewport; if (this.layoutCount_ == 0) { if (!inViewport) { this.toggleLoading(false); } else { // Set a minimum delay in case the element loads very fast or if it // leaves the viewport. const loadingStartTime = win.Date.now(); Services.timerFor(toWin(this.ownerDocument.defaultView)).delay(() => { // TODO(dvoytenko, #9177): cleanup `this.ownerDocument.defaultView` // once investigation is complete. It appears that we get a lot of // errors here once the iframe is destroyed due to timer. if ( this.isInViewport_ && this.ownerDocument && this.ownerDocument.defaultView && this.layoutCount_ === 0 // Ensures that layoutCallback hasn't completed in this 100ms window. ) { this.toggleLoading(true, {startTime: loadingStartTime}); } }, 100); } } if (this.isBuilt()) { this.updateInViewport_(inViewport); } } /** * @param {boolean} inViewport * @private */ updateInViewport_(inViewport) { this.implementation_.inViewport_ = inViewport; this.implementation_.viewportCallback(inViewport); if (inViewport && this.perfOn_) { this.getLayoutDelayMeter_().enterViewport(); } } /** * Whether the resource is currently paused. * @return {boolean} * @final @package */ isPaused() { return this.paused_; } /** * Requests the resource to stop its activity when the document goes into * inactive state. The scope is up to the actual component. Among other * things the active playback of video or audio content must be stopped. * * @package @final */ pauseCallback() { assertNotTemplate(this); if (this.paused_) { return; } this.paused_ = true; this.viewportCallback(false); if (this.isBuilt()) { this.implementation_.pauseCallback(); } } /** * Requests the resource to resume its activity when the document returns * from an inactive state. The scope is up to the actual component. Among * other things the active playback of video or audio content may be * resumed. * * @package @final */ resumeCallback() { assertNotTemplate(this); if (!this.paused_) { return; } this.paused_ = false; if (this.isBuilt()) { this.implementation_.resumeCallback(); } } /** * Requests the element to unload any expensive resources when the element * goes into non-visible state. The scope is up to the actual component. * * Calling this method on unbuilt or unupgraded element has no effect. * * @return {boolean} * @package @final */ unlayoutCallback() { assertNotTemplate(this); if (!this.isBuilt()) { return false; } this.signals_.signal(CommonSignals.UNLOAD); const isReLayoutNeeded = this.implementation_.unlayoutCallback(); if (isReLayoutNeeded) { this.reset_(); } this.dispatchCustomEventForTesting(AmpEvents.UNLOAD); return isReLayoutNeeded; } /** @private */ reset_() { this.layoutCount_ = 0; this.isFirstLayoutCompleted_ = false; this.signals_.reset(CommonSignals.RENDER_START); this.signals_.reset(CommonSignals.LOAD_START); this.signals_.reset(CommonSignals.LOAD_END); this.signals_.reset(CommonSignals.INI_LOAD); } /** * Whether to call {@link unlayoutCallback} when pausing the element. * Certain elements cannot properly pause (like amp-iframes with unknown * video content), and so we must unlayout to stop playback. * * @return {boolean} * @package @final */ unlayoutOnPause() { return this.implementation_.unlayoutOnPause(); } /** * Whether the element needs to be reconstructed after it has been * re-parented. Many elements cannot survive fully the reparenting and * are better to be reconstructed from scratch. * * @return {boolean} * @package @final */ reconstructWhenReparented() { return this.implementation_.reconstructWhenReparented(); } /** * Collapses the element, and notifies its owner (if there is one) that the * element is no longer present. */ collapse() { this.implementation_./*OK*/ collapse(); } /** * Called every time an owned AmpElement collapses itself. * @param {!AmpElement} element */ collapsedCallback(element) { this.implementation_.collapsedCallback(element); } /** * Expands the element, and notifies its owner (if there is one) that the * element is now present. */ expand() { this.implementation_./*OK*/ expand(); } /** * Called every time an owned AmpElement expands itself. * @param {!AmpElement} element */ expandedCallback(element) { this.implementation_.expandedCallback(element); } /** * Called when one or more attributes are mutated. * Note: Must be called inside a mutate context. * Note: Boolean attributes have a value of `true` and `false` when * present and missing, respectively. * @param {!JsonObject<string, (null|boolean|string|number|Array|Object)>} mutations */ mutatedAttributesCallback(mutations) { this.implementation_.mutatedAttributesCallback(mutations); } /** * Enqueues the action with the element. If element has been upgraded and * built, the action is dispatched to the implementation right away. * Otherwise the invocation is enqueued until the implementation is ready * to receive actions. * @param {!./service/action-impl.ActionInvocation} invocation * @final */ enqueAction(invocation) { assertNotTemplate(this); if (!this.isBuilt()) { if (this.actionQueue_ === undefined) { this.actionQueue_ = []; } devAssert(this.actionQueue_).push(invocation); } else { this.executionAction_(invocation, false); } } /** * Dequeues events from the queue and dispatches them to the implementation * with "deferred" flag. * @private */ dequeueActions_() { if (!this.actionQueue_) { return; } const actionQueue = devAssert(this.actionQueue_); this.actionQueue_ = null; // Notice, the actions are currently not de-duped. actionQueue.forEach((invocation) => { this.executionAction_(invocation, true); }); } /** * Executes the action immediately. All errors are consumed and reported. * @param {!./service/action-impl.ActionInvocation} invocation * @param {boolean} deferred * @final * @private */ executionAction_(invocation, deferred) { try { this.implementation_.executeAction(invocation, deferred); } catch (e) { rethrowAsync( 'Action execution failed:', e, invocation.node.tagName, invocation.method ); } } /** * Get the consent policy to follow. * @return {?string} */ getConsentPolicy_() { let policyId = this.getAttribute('data-block-on-consent'); if (policyId === null) { if (shouldBlockOnConsentByMeta(this)) { policyId = 'default'; this.setAttribute('data-block-on-consent', policyId); } else { // data-block-on-consent attribute not set return null; } } if (policyId == '' || policyId == 'default') { // data-block-on-consent value not set, up to individual element // Note: data-block-on-consent and data-block-on-consent='default' is // treated exactly the same return this.implementation_.getConsentPolicy(); } return policyId; } /** * Returns the original nodes of the custom element without any service * nodes that could have been added for markup. These nodes can include * Text, Comment and other child nodes. * @return {!Array<!Node>} * @package @final */ getRealChildNodes() { return dom.childNodes(this, (node) => !isInternalOrServiceNode(node)); } /** * Returns the original children of the custom element without any service * nodes that could have been added for markup. * @return {!Array<!Element>} * @package @final */ getRealChildren() { return dom.childElements( this, (element) => !isInternalOrServiceNode(element) ); } /** * Returns an optional placeholder element for this custom element. * @return {?Element} * @package @final */ getPlaceholder() { return dom.lastChildElement(this, (el) => { return ( el.hasAttribute('placeholder') && // Denylist elements that has a native placeholder property // like input and textarea. These are not allowed to be AMP // placeholders. !isInputPlaceholder(el) ); }); } /** * Hides or shows the placeholder, if available. * @param {boolean} show * @package @final */ togglePlaceholder(show) { assertNotTemplate(this); if (show) { const placeholder = this.getPlaceholder(); if (placeholder) { dev().assertElement(placeholder).classList.remove('amp-hidden'); } } else { const placeholders = dom.childElementsByAttr(this, 'placeholder'); for (let i = 0; i < placeholders.length; i++) { // Don't toggle elements with a native placeholder property // e.g. input, textarea if (isInputPlaceholder(placeholders[i])) { continue; } placeholders[i].classList.add('amp-hidden'); } } } /** * Returns an optional fallback element for this custom element. * @return {?Element} * @package @final */ getFallback() { return dom.childElementByAttr(this, 'fallback'); } /** * Hides or shows the fallback, if available. This function must only * be called inside a mutate context. * @param {boolean} show * @package @final */ toggleFallback(show) { assertNotTemplate(this); const resourceState = this.getResource_().getState(); // Do not show fallback before layout if ( show && (resourceState == ResourceState.NOT_BUILT || resourceState == ResourceState.NOT_LAID_OUT || resourceState == ResourceState.READY_FOR_LAYOUT) ) { return; } // This implementation is notably less efficient then placeholder // toggling. The reasons for this are: (a) "not supported" is the state of // the whole element, (b) some relayout is expected and (c) fallback // condition would be rare. this.classList.toggle('amp-notsupported', show); if (show == true) { const fallbackElement = this.getFallback(); if (fallbackElement) { Services.ownersForDoc(this.getAmpDoc()).scheduleLayout( this, fallbackElement ); } } } /** * An implementation can call this method to signal to the element that * it has started rendering. * @package @final */ renderStarted() { this.signals_.signal(CommonSignals.RENDER_START); this.togglePlaceholder(false); this.toggleLoading(false); } /** * Whether the loading can be shown for this element. * @return {boolean} * @private */ isLoadingEnabled_() { // No loading indicator will be shown if either one of these conditions // true: // 1. The document is A4A. // 2. `noloading` attribute is specified; // 3. The element has already been laid out, and does not support reshowing the indicator (include having loading // error); // 4. The element is too small or has not yet been measured; // 5. The element has not been allowlisted; // 6. The element is an internal node (e.g. `placeholder` or `fallback`); // 7. The element's layout is not nodisplay. if (this.isInA4A()) { return false; } if (this.loadingDisabled_ === undefined) { this.loadingDisabled_ = this.hasAttribute('noloading'); } const laidOut = this.layoutCount_ > 0 || this.signals_.get(CommonSignals.RENDER_START); if ( this.loadingDisabled_ || (laidOut && !this.implementation_.isLoadingReused()) || this.layoutWidth_ <= 0 || // Layout is not ready or invisible !isLoadingAllowed(this) || isInternalOrServiceNode(this) || this.layout_ == Layout.NODISPLAY ) { return false; } return true; } /** * @return {boolean} */ isInA4A() { return ( // in FIE (this.ampdoc_ && this.ampdoc_.win != this.ownerDocument.defaultView) || // in inabox getMode().runtime == 'inabox' ); } /** * Creates a loading object. The caller must ensure that loading can * actually be shown. This method must also be called in the mutate * context. * @private * @param {number=} startTime */ prepareLoading_(startTime) { if (!this.isLoadingEnabled_()) { return; } if (!this.loadingContainer_) { const doc = this.ownerDocument; devAssert(doc); const container = htmlFor(/** @type {!Document} */ (doc))` <div class="i-amphtml-loading-container i-amphtml-fill-content amp-hidden"></div>`; const loadingElement = createLoaderElement( this.getAmpDoc(), this, this.layoutWidth_, this.layoutHeight_, startTime ); container.appendChild(loadingElement); this.appendChild(container); this.loadingContainer_ = container; this.loadingElement_ = loadingElement; } } /** * Turns the loading indicator on or off. * @param {boolean} state * @param {{cleanup:(boolean|undefined), startTime:(number|undefined)}=} opt_options * @public @final */ toggleLoading(state, opt_options) { const cleanup = opt_options && opt_options.cleanup; const startTime = opt_options && opt_options.startTime; assertNotTemplate(this); if (state === this.loadingState_ && !opt_options) { // Loading state is the same. return; } this.loadingState_ = state; if (!state && !this.loadingContainer_) { return; } // Check if loading should be shown. if (state && !this.isLoadingEnabled_()) { this.loadingState_ = false; return; } this.mutateOrInvoke_( () => { let state = this.loadingState_; // Repeat "loading enabled" check because it could have changed while // waiting for vsync. if (state && !this.isLoadingEnabled_()) { state = false; } if (state) { this.prepareLoading_(startTime); } if (!this.loadingContainer_) { return; } this.loadingContainer_.classList.toggle('amp-hidden', !state); this.loadingElement_.classList.toggle('amp-active', state); if (!state && cleanup && !this.implementation_.isLoadingReused()) { const loadingContainer = this.loadingContainer_; this.loadingContainer_ = null; this.loadingElement_ = null; this.mutateOrInvoke_( () => { dom.removeElement(loadingContainer); }, undefined, true ); } }, undefined, /* skipRemeasure */ true ); } /** * Returns an optional overflow element for this custom element. * @return {!./layout-delay-meter.LayoutDelayMeter} */ getLayoutDelayMeter_() { if (!this.layoutDelayMeter_) { this.layoutDelayMeter_ = new LayoutDelayMeter( toWin(this.ownerDocument.defaultView), this.getLayoutPriority() ); } return this.layoutDelayMeter_; } /** * Returns an optional overflow element for this custom element. * @return {?Element} */ getOverflowElement() { if (this.overflowElement_ === undefined) { this.overflowElement_ = dom.childElementByAttr(this, 'overflow'); if (this.overflowElement_) { if (!this.overflowElement_.hasAttribute('tabindex')) { this.overflowElement_.setAttribute('tabindex', '0'); } if (!this.overflowElement_.hasAttribute('role')) { this.overflowElement_.setAttribute('role', 'button'); } } } return this.overflowElement_; } /** * Hides or shows the overflow, if available. This function must only * be called inside a mutate context. * @param {boolean} overflown * @param {number|undefined} requestedHeight * @param {number|undefined} requestedWidth * @package @final */ overflowCallback(overflown, requestedHeight, requestedWidth) { this.getOverflowElement(); if (!this.overflowElement_) { if (overflown && this.warnOnMissingOverflow) { user().warn( TAG, 'Cannot resize element and overflow is not available', this ); } } else { this.overflowElement_.classList.toggle('amp-visible', overflown); if (overflown) { this.overflowElement_.onclick = () => { const mutator = Services.mutatorForDoc(this.getAmpDoc()); mutator.forceChangeSize(this, requestedHeight, requestedWidth); mutator.mutateElement(this, () => { this.overflowCallback( /* overflown */ false, requestedHeight, requestedWidth ); }); }; } else { this.overflowElement_.onclick = null; } } } /** * Mutates the element using resources if available. * * @param {function()} mutator * @param {?Element=} opt_element * @param {boolean=} opt_skipRemeasure */ mutateOrInvoke_(mutator, opt_element, opt_skipRemeasure = false) { if (this.ampdoc_) { Services.mutatorForDoc(this.getAmpDoc()).mutateElement( opt_element || this, mutator, opt_skipRemeasure ); } else { mutator(); } } } win.__AMP_BASE_CE_CLASS = BaseCustomElement; return /** @type {typeof HTMLElement} */ (win.__AMP_BASE_CE_CLASS); } /** * @param {!Element} element * @return {boolean} */ function isInputPlaceholder(element) { return 'placeholder' in element; } /** @param {!Element} element */ function assertNotTemplate(element) { devAssert(!element.isInTemplate_, 'Must never be called in template'); } /** * Whether the implementation is a stub. * @param {?./base-element.BaseElement} impl * @return {boolean} */ function isStub(impl) { return impl instanceof ElementStub; } /** * Returns "true" for internal AMP nodes or for placeholder elements. * @param {!Node} node * @return {boolean} */ function isInternalOrServiceNode(node) { if (isInternalElement(node)) { return true; } if ( node.tagName && (node.hasAttribute('placeholder') || node.hasAttribute('fallback') || node.hasAttribute('overflow')) ) { return true; } return false; } /** * Creates a new custom element class prototype. * * @param {!Window} win The window in which to register the custom element. * @param {(typeof ./base-element.BaseElement)=} opt_implementationClass For testing only. * @return {!Object} Prototype of element. */ export function createAmpElementForTesting(win, opt_implementationClass) { const Element = createCustomElementClass(win); if (getMode().test && opt_implementationClass) { Element.prototype.implementationClassForTesting = opt_implementationClass; } return Element; }
adup-tech/amphtml
src/custom-element.js
JavaScript
apache-2.0
58,872
// UserController for AngularJS ecollabroApp.controller('userController', ['$scope', 'securityService', function ($scope, securityService) { $scope.user = {}; $scope.activeRoles = []; $scope.userId = 0; //Method initialize $scope.initialize = function (userId) { $scope.userId = userId; includeChangePassword($scope, securityService, 'admin'); $scope.loadUser(); }; //Method loadUser $scope.loadUser = function () { if ($scope.userId == 0) { $scope.user.IsActive = true; $scope.loadActiveRoles(); return; } securityService.getUser($scope.userId).then(function (resp) { if (resp.businessException == null) { $scope.user = resp.result; $scope.loadActiveRoles(); } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); }; //Method saveUser $scope.saveUser = function () { if (!$("#frmUser").valid()) { return; } else { if ($scope.user.UserRoles == null || $scope.user.UserRoles.length == 0) { showMessage("divSummaryMessageUser", "Select at-least one role for user!", "danger"); return; } } securityService.saveUser($scope.user).then(function (resp) { if (resp.businessException == null) { $scope.user.UserId = resp.result.Id; var divUsers = document.getElementById("divUsers"); if (divUsers) { showUsers(resp.result.Message); // calling parent's method } else { showMessage("divSummaryMessageUser", resp.result.Message, "success"); } } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); }; //Method restPassword $scope.resetPassword = function () { bootbox.confirm("This will reset User's password and will send email with new credential? Are you sure to reset the password for selected User?", function (result) { if (result) { securityService.resetUserPassword($scope.user.UserId).then(function (resp) { if (resp.businessException == null) { showMessage("divSummaryMessageUser", resp.result, "success"); } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); } }); }; //Method confirmUser $scope.confirmUser = function () { securityService.confirmUser($scope.user.UserId).then(function (resp) { if (resp.businessException == null) { showMessage("divSummaryMessageUser", resp.result, "success"); $scope.user.IsConfirmed = true; } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); }; //Method unlockUser $scope.unlockUser = function () { securityService.unlockUser($scope.user.UserId).then(function (resp) { if (resp.businessException == null) { showMessage("divSummaryMessageUser", resp.result, "success"); $scope.user.IsLocked = false; } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); }; //Method approveUser $scope.approveUser = function () { securityService.approveUser($scope.user.UserId).then(function (resp) { if (resp.businessException == null) { showMessage("divSummaryMessageUser", resp.result, "success"); $scope.user.IsApproved = true; } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); }; //Method getActiveRole $scope.getActiveRole = function (roleId) { var activeRole = null; for (var ctr = 0; ctr < $scope.activeRoles.length; ctr++) { if ($scope.activeRoles[ctr].RoleId == roleId) { activeRole = $scope.activeRoles[ctr]; break; } } return activeRole; } // Method loadAactiveRoles $scope.loadActiveRoles = function () { securityService.getActiveRoles($scope.user).then(function (resp) { if (resp.businessException == null) { $scope.activeRoles = resp.result.data; if ($scope.user.UserRoles != null && $scope.user.UserRoles.length > 0) { var existingRoles = $scope.user.UserRoles; $scope.user.UserRoles = []; for (var ctr = 0; ctr < existingRoles.length; ctr++) { var activeRole = $scope.getActiveRole(existingRoles[ctr].RoleId); if (activeRole != null) $scope.user.UserRoles.push(activeRole); } } } else { showMessage("divSummaryMessageUser", resp.businessException.ExceptionMessage, "danger"); } }); }; //method openUsers $scope.openUsers = function () { location.href = "/security/users"; }; }]);
eCollobro/eCollabro
eCollabro.Web/obj/Release/Package/PackageTmp/app/controllers/user/user.js
JavaScript
apache-2.0
5,849
$(document).ready(function() { $('#btn-create-version').on('click', function(e) { e.preventDefault(); var newVersion = $('#new-version').val(); if (newVersion) { var assetId = $('#asset-id').val(); var assetType = $('#asset-type').val(); var path = caramel.url('/apis/asset/' + assetId + '/create-version?type=' + assetType); var assetPath = caramel.url('/assets/' + assetType + '/details/'); $('#btn-create-version').addClass('disabled'); $('#new-version-loading').removeClass('hide'); var alertMessage = $("#alertSection"); $.ajax({ url: path, data: JSON.stringify({ "attributes": { "overview_version": newVersion } }), type: 'POST', success: function(response) { messages.alertSuccess('Asset version created successfully!,You will be redirected to new asset details page in few seconds.....'); setTimeout(function() { var path = caramel.url('assets/' + assetType + '/details/' + response.data); window.location = path; }, 3000); }, error: function(error) { var errorText = JSON.parse(error.responseText).error; messages.alertError(errorText); $('#btn-create-version').removeClass('disabled'); $('#new-version-loading').addClass('hide'); } }); } }); $('#btn-cancel-version').on('click', function(e) { var assetId = $('#asset-id').val(); var assetType = $('#asset-type').val(); var path = caramel.url('/assets/' + assetType + '/details/' + assetId); $.ajax({ success: function(response) { window.location = path; } }); }); });
sameerak/carbon-store
apps/publisher/themes/default/js/copy-asset.js
JavaScript
apache-2.0
2,044
export { Clock } from './Clock';
HewlettPackard/grommet
src/js/components/Clock/index.js
JavaScript
apache-2.0
33
/** * Copyright 2017 Google Inc. * * 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. */ const path = require('path'); const webpack = require('webpack'); module.exports = { devtool: 'source-map', module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, use: 'ts-loader' }, { test: /\.[tj]sx?$/, use: 'source-map-loader', enforce: 'pre' }, { test: /\.tsx?$/, use: { loader: 'istanbul-instrumenter-loader', options: { esModules: true } }, enforce: 'post', include: path.resolve(process.cwd(), 'src') } ] }, resolve: { modules: ['node_modules', path.resolve(__dirname, '../../node_modules')], extensions: ['.js', '.ts'] } };
FirebasePrivate/firebase-js-sdk-1
config/webpack.test.js
JavaScript
apache-2.0
1,306
// Copyright 2014 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 Controller for the conversation skin. */ // Note: This file should be assumed to be in an IIFE, and the constants below // should only be used within this file. var TIME_FADEOUT_MSEC = 100; var TIME_HEIGHT_CHANGE_MSEC = 500; var TIME_FADEIN_MSEC = 100; var TIME_NUM_CARDS_CHANGE_MSEC = 500; oppia.animation('.conversation-skin-responses-animate-slide', function() { return { removeClass: function(element, className, done) { if (className !== 'ng-hide') { done(); return; } element.hide().slideDown(400, done); }, addClass: function(element, className, done) { if (className !== 'ng-hide') { done(); return; } element.slideUp(400, done); } }; }); oppia.animation('.conversation-skin-animate-tutor-card-on-narrow', function() { var tutorCardLeft, tutorCardWidth, tutorCardHeight, oppiaAvatarLeft; var tutorCardAnimatedLeft, tutorCardAnimatedWidth; var beforeAddClass = function(element, className, done) { if (className !== 'ng-hide') { done(); return; } var tutorCard = element; var supplementalCard = $('.conversation-skin-supplemental-card-container'); var oppiaAvatar = $('.conversation-skin-oppia-avatar.show-tutor-card'); oppiaAvatarLeft = supplementalCard.position().left + supplementalCard.width() - oppiaAvatar.width(); tutorCardLeft = tutorCard.position().left; tutorCardWidth = tutorCard.width(); tutorCardHeight = tutorCard.height(); if (tutorCard.offset().left + tutorCardWidth > oppiaAvatar.offset().left) { var animationLength = Math.min(oppiaAvatarLeft - tutorCard.offset().left, tutorCardWidth); tutorCardAnimatedLeft = tutorCardLeft + animationLength; tutorCardAnimatedWidth = tutorCardWidth - animationLength; } else { tutorCardAnimatedLeft = oppiaAvatarLeft; tutorCardAnimatedWidth = 0; } oppiaAvatar.hide(); tutorCard.css({ 'min-width': 0 }); tutorCard.animate({ left: tutorCardAnimatedLeft, width: tutorCardAnimatedWidth, height: 0, opacity: 1 }, 500, function() { oppiaAvatar.show(); tutorCard.css({ left: '', width: '', height: '', opacity: '', 'min-width': '' }); done(); }); }; var removeClass = function(element, className, done) { if (className !== 'ng-hide') { done(); return; } var tutorCard = element; $('.conversation-skin-oppia-avatar.show-tutor-card').hide(0, function() { tutorCard.css({ left: tutorCardAnimatedLeft, width: tutorCardAnimatedWidth, height: 0, opacity: 0, 'min-width': 0 }); tutorCard.animate({ left: tutorCardLeft, width: tutorCardWidth, height: tutorCardHeight, opacity: 1 }, 500, function() { tutorCard.css({ left: '', width: '', height: '', opacity: '', 'min-width': '' }); done(); }); }); }; return { beforeAddClass: beforeAddClass, removeClass: removeClass }; }); oppia.animation('.conversation-skin-animate-cards', function() { // This removes the newly-added class once the animation is finished. var animateCards = function(element, className, done) { var tutorCardElt = jQuery(element).find( '.conversation-skin-main-tutor-card'); var supplementalCardElt = jQuery(element).find( '.conversation-skin-supplemental-card-container'); if (className === 'animate-to-two-cards') { var supplementalWidth = supplementalCardElt.width(); supplementalCardElt.css({ width: 0, 'min-width': '0', opacity: '0' }); supplementalCardElt.animate({ width: supplementalWidth }, TIME_NUM_CARDS_CHANGE_MSEC, function() { supplementalCardElt.animate({ opacity: '1' }, TIME_FADEIN_MSEC, function() { supplementalCardElt.css({ width: '', 'min-width': '', opacity: '' }); jQuery(element).removeClass('animate-to-two-cards'); done(); }); }); return function(cancel) { if (cancel) { supplementalCardElt.css({ width: '', 'min-width': '', opacity: '' }); supplementalCardElt.stop(); jQuery(element).removeClass('animate-to-two-cards'); } }; } else if (className === 'animate-to-one-card') { supplementalCardElt.css({ opacity: 0, 'min-width': 0 }); supplementalCardElt.animate({ width: 0 }, TIME_NUM_CARDS_CHANGE_MSEC, function() { jQuery(element).removeClass('animate-to-one-card'); done(); }); return function(cancel) { if (cancel) { supplementalCardElt.css({ opacity: '', 'min-width': '', width: '' }); supplementalCardElt.stop(); jQuery(element).removeClass('animate-to-one-card'); } }; } else { return; } }; return { addClass: animateCards }; }); oppia.animation('.conversation-skin-animate-card-contents', function() { var animateCardChange = function(element, className, done) { if (className !== 'animate-card-change') { return; } var currentHeight = element.height(); var expectedNextHeight = $( '.conversation-skin-future-tutor-card ' + '.conversation-skin-tutor-card-content' ).height(); // Fix the current card height, so that it does not change during the // animation, even though its contents might. element.css('height', currentHeight); jQuery(element).animate({ opacity: 0 }, TIME_FADEOUT_MSEC).animate({ height: expectedNextHeight }, TIME_HEIGHT_CHANGE_MSEC).animate({ opacity: 1 }, TIME_FADEIN_MSEC, function() { element.css('height', ''); done(); }); return function(cancel) { if (cancel) { element.css('opacity', '1.0'); element.css('height', ''); element.stop(); } }; }; return { addClass: animateCardChange }; }); oppia.directive('conversationSkin', [function() { return { restrict: 'E', scope: {}, templateUrl: 'skins/Conversation', controller: [ '$scope', '$timeout', '$rootScope', '$window', '$translate', 'messengerService', 'oppiaPlayerService', 'urlService', 'focusService', 'LearnerViewRatingService', 'windowDimensionsService', 'playerTranscriptService', 'LearnerParamsService', 'playerPositionService', 'explorationRecommendationsService', 'StatsReportingService', 'UrlInterpolationService', function( $scope, $timeout, $rootScope, $window, $translate, messengerService, oppiaPlayerService, urlService, focusService, LearnerViewRatingService, windowDimensionsService, playerTranscriptService, LearnerParamsService, playerPositionService, explorationRecommendationsService, StatsReportingService, UrlInterpolationService) { $scope.CONTINUE_BUTTON_FOCUS_LABEL = 'continueButton'; // The exploration domain object. $scope.exploration = null; // The minimum width, in pixels, needed to be able to show two cards // side-by-side. var TWO_CARD_THRESHOLD_PX = 960; var TIME_PADDING_MSEC = 250; var TIME_SCROLL_MSEC = 600; var MIN_CARD_LOADING_DELAY_MSEC = 950; var CONTENT_FOCUS_LABEL_PREFIX = 'content-focus-label-'; var hasInteractedAtLeastOnce = false; var _answerIsBeingProcessed = false; var _nextFocusLabel = null; // This variable is used only when viewport is narrow. // Indicates whether the tutor card is displayed. var tutorCardIsDisplayedIfNarrow = true; $scope.explorationId = oppiaPlayerService.getExplorationId(); $scope.isInPreviewMode = oppiaPlayerService.isInPreviewMode(); $scope.isIframed = urlService.isIframed(); $rootScope.loadingMessage = 'Loading'; $scope.hasFullyLoaded = false; $scope.recommendedExplorationSummaries = []; $scope.OPPIA_AVATAR_IMAGE_URL = ( UrlInterpolationService.getStaticImageUrl( '/avatar/oppia_black_72px.png')); $scope.activeCard = null; $scope.numProgressDots = 0; $scope.arePreviousResponsesShown = false; $scope.upcomingStateName = null; $scope.upcomingContentHtml = null; $scope.upcomingInlineInteractionHtml = null; $scope.helpCardHtml = null; $scope.helpCardHasContinueButton = false; $scope.profilePicture = ( UrlInterpolationService.getStaticImageUrl( '/avatar/user_blue_72px.png')); $scope.DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER = GLOBALS.DEFAULT_TWITTER_SHARE_MESSAGE_PLAYER; oppiaPlayerService.getUserProfileImage().then(function(result) { $scope.profilePicture = result; }); $scope.clearHelpCard = function() { $scope.helpCardHtml = null; $scope.helpCardHasContinueButton = false; }; $scope.getContentFocusLabel = function(index) { return CONTENT_FOCUS_LABEL_PREFIX + index; }; // If the exploration is iframed, send data to its parent about its // height so that the parent can be resized as necessary. $scope.lastRequestedHeight = 0; $scope.lastRequestedScroll = false; $scope.adjustPageHeight = function(scroll, callback) { $timeout(function() { var newHeight = document.body.scrollHeight; if (Math.abs($scope.lastRequestedHeight - newHeight) > 50.5 || (scroll && !$scope.lastRequestedScroll)) { // Sometimes setting iframe height to the exact content height // still produces scrollbar, so adding 50 extra px. newHeight += 50; messengerService.sendMessage(messengerService.HEIGHT_CHANGE, { height: newHeight, scroll: scroll }); $scope.lastRequestedHeight = newHeight; $scope.lastRequestedScroll = scroll; } if (callback) { callback(); } }, 100); }; $scope.isOnTerminalCard = function() { return $scope.activeCard && $scope.exploration.isStateTerminal($scope.activeCard.stateName); }; var isSupplementalCardNonempty = function(card) { return !$scope.exploration.isInteractionInline(card.stateName); }; $scope.isCurrentSupplementalCardNonempty = function() { return $scope.activeCard && isSupplementalCardNonempty( $scope.activeCard); }; // Navigates to the currently-active card, and resets the 'show previous // responses' setting. var _navigateToActiveCard = function() { var index = playerPositionService.getActiveCardIndex(); $scope.activeCard = playerTranscriptService.getCard(index); $scope.arePreviousResponsesShown = false; $scope.clearHelpCard(); tutorCardIsDisplayedIfNarrow = true; if (_nextFocusLabel && playerTranscriptService.isLastCard(index)) { focusService.setFocusIfOnDesktop(_nextFocusLabel); } else { focusService.setFocusIfOnDesktop( $scope.getContentFocusLabel(index)); } }; var animateToTwoCards = function(doneCallback) { $scope.isAnimatingToTwoCards = true; $timeout(function() { $scope.isAnimatingToTwoCards = false; if (doneCallback) { doneCallback(); } }, TIME_NUM_CARDS_CHANGE_MSEC + TIME_FADEIN_MSEC + TIME_PADDING_MSEC); }; var animateToOneCard = function(doneCallback) { $scope.isAnimatingToOneCard = true; $timeout(function() { $scope.isAnimatingToOneCard = false; if (doneCallback) { doneCallback(); } }, TIME_NUM_CARDS_CHANGE_MSEC); }; $scope.isCurrentCardAtEndOfTranscript = function() { return playerTranscriptService.isLastCard( playerPositionService.getActiveCardIndex()); }; var _addNewCard = function( stateName, newParams, contentHtml, interactionHtml) { playerTranscriptService.addNewCard( stateName, newParams, contentHtml, interactionHtml); if (newParams) { LearnerParamsService.init(newParams); } $scope.numProgressDots++; var totalNumCards = playerTranscriptService.getNumCards(); var previousSupplementalCardIsNonempty = ( totalNumCards > 1 && isSupplementalCardNonempty( playerTranscriptService.getCard(totalNumCards - 2))); var nextSupplementalCardIsNonempty = isSupplementalCardNonempty( playerTranscriptService.getLastCard()); if (totalNumCards > 1 && $scope.canWindowFitTwoCards() && !previousSupplementalCardIsNonempty && nextSupplementalCardIsNonempty) { playerPositionService.setActiveCardIndex( $scope.numProgressDots - 1); animateToTwoCards(function() {}); } else if ( totalNumCards > 1 && $scope.canWindowFitTwoCards() && previousSupplementalCardIsNonempty && !nextSupplementalCardIsNonempty) { animateToOneCard(function() { playerPositionService.setActiveCardIndex( $scope.numProgressDots - 1); }); } else { playerPositionService.setActiveCardIndex( $scope.numProgressDots - 1); } if ($scope.exploration.isStateTerminal(stateName)) { explorationRecommendationsService.getRecommendedSummaryDicts( $scope.exploration.getAuthorRecommendedExpIds(stateName), function(summaries) { $scope.recommendedExplorationSummaries = summaries; }); } }; $scope.toggleShowPreviousResponses = function() { $scope.arePreviousResponsesShown = !$scope.arePreviousResponsesShown; }; $scope.initializePage = function() { $scope.waitingForOppiaFeedback = false; hasInteractedAtLeastOnce = false; $scope.recommendedExplorationSummaries = []; playerPositionService.init(_navigateToActiveCard); oppiaPlayerService.init(function(exploration, initHtml, newParams) { $scope.exploration = exploration; $scope.isLoggedIn = oppiaPlayerService.isLoggedIn(); _nextFocusLabel = focusService.generateFocusLabel(); _addNewCard( exploration.initStateName, newParams, initHtml, oppiaPlayerService.getInteractionHtml( exploration.initStateName, _nextFocusLabel)); $rootScope.loadingMessage = ''; $scope.hasFullyLoaded = true; // If the exploration is embedded, use the exploration language // as site language. If the exploration language is not supported // as site language, English is used as default. var langCodes = $window.GLOBALS.SUPPORTED_SITE_LANGUAGES.map( function(language) { return language.id; }); if ($scope.isIframed) { var explorationLanguageCode = ( oppiaPlayerService.getExplorationLanguageCode()); if (langCodes.indexOf(explorationLanguageCode) !== -1) { $translate.use(explorationLanguageCode); } else { $translate.use('en'); } } $scope.adjustPageHeight(false, null); $window.scrollTo(0, 0); focusService.setFocusIfOnDesktop(_nextFocusLabel); }); }; $scope.submitAnswer = function(answer, interactionRulesService) { // For some reason, answers are getting submitted twice when the // submit button is clicked. This guards against that. if (_answerIsBeingProcessed || !$scope.isCurrentCardAtEndOfTranscript() || $scope.activeCard.destStateName) { return; } $scope.clearHelpCard(); _answerIsBeingProcessed = true; hasInteractedAtLeastOnce = true; $scope.waitingForOppiaFeedback = true; var _oldStateName = playerTranscriptService.getLastCard().stateName; playerTranscriptService.addNewAnswer(answer); var timeAtServerCall = new Date().getTime(); oppiaPlayerService.submitAnswer( answer, interactionRulesService, function( newStateName, refreshInteraction, feedbackHtml, contentHtml, newParams) { // Do not wait if the interaction is supplemental -- there's // already a delay bringing in the help card. var millisecsLeftToWait = ( !$scope.exploration.isInteractionInline(_oldStateName) ? 1.0 : Math.max(MIN_CARD_LOADING_DELAY_MSEC - ( new Date().getTime() - timeAtServerCall), 1.0)); $timeout(function() { $scope.waitingForOppiaFeedback = false; var pairs = ( playerTranscriptService.getLastCard().answerFeedbackPairs); var lastAnswerFeedbackPair = pairs[pairs.length - 1]; if (_oldStateName === newStateName) { // Stay on the same card. playerTranscriptService.addNewFeedback(feedbackHtml); if (feedbackHtml && !$scope.exploration.isInteractionInline( $scope.activeCard.stateName)) { $scope.helpCardHtml = feedbackHtml; } if (refreshInteraction) { // Replace the previous interaction with another of the // same type. _nextFocusLabel = focusService.generateFocusLabel(); playerTranscriptService.updateLatestInteractionHtml( oppiaPlayerService.getInteractionHtml( newStateName, _nextFocusLabel) + oppiaPlayerService.getRandomSuffix()); } focusService.setFocusIfOnDesktop(_nextFocusLabel); scrollToBottom(); } else { // There is a new card. If there is no feedback, move on // immediately. Otherwise, give the learner a chance to read // the feedback, and display a 'Continue' button. _nextFocusLabel = focusService.generateFocusLabel(); playerTranscriptService.setDestination(newStateName); // These are used to compute the dimensions for the next card. $scope.upcomingStateName = newStateName; $scope.upcomingParams = newParams; $scope.upcomingContentHtml = ( contentHtml + oppiaPlayerService.getRandomSuffix()); var _isNextInteractionInline = ( $scope.exploration.isInteractionInline(newStateName)); $scope.upcomingInlineInteractionHtml = ( _isNextInteractionInline ? oppiaPlayerService.getInteractionHtml( newStateName, _nextFocusLabel ) + oppiaPlayerService.getRandomSuffix() : ''); if (feedbackHtml) { playerTranscriptService.addNewFeedback(feedbackHtml); if (!$scope.exploration.isInteractionInline( $scope.activeCard.stateName)) { $scope.helpCardHtml = feedbackHtml; $scope.helpCardHasContinueButton = true; } _nextFocusLabel = $scope.CONTINUE_BUTTON_FOCUS_LABEL; focusService.setFocusIfOnDesktop(_nextFocusLabel); scrollToBottom(); } else { playerTranscriptService.addNewFeedback(feedbackHtml); $scope.showPendingCard( newStateName, newParams, contentHtml + oppiaPlayerService.getRandomSuffix()); } } _answerIsBeingProcessed = false; }, millisecsLeftToWait); } ); }; $scope.startCardChangeAnimation = false; $scope.showPendingCard = function( newStateName, newParams, newContentHtml) { $scope.startCardChangeAnimation = true; $timeout(function() { var newInteractionHtml = oppiaPlayerService.getInteractionHtml( newStateName, _nextFocusLabel); // Note that newInteractionHtml may be null. if (newInteractionHtml) { newInteractionHtml += oppiaPlayerService.getRandomSuffix(); } _addNewCard( newStateName, newParams, newContentHtml, newInteractionHtml); $scope.upcomingStateName = null; $scope.upcomingParams = null; $scope.upcomingContentHtml = null; $scope.upcomingInlineInteractionHtml = null; }, TIME_FADEOUT_MSEC + 0.1 * TIME_HEIGHT_CHANGE_MSEC); $timeout(function() { focusService.setFocusIfOnDesktop(_nextFocusLabel); scrollToTop(); }, TIME_FADEOUT_MSEC + TIME_HEIGHT_CHANGE_MSEC + 0.5 * TIME_FADEIN_MSEC); $timeout(function() { $scope.startCardChangeAnimation = false; }, TIME_FADEOUT_MSEC + TIME_HEIGHT_CHANGE_MSEC + TIME_FADEIN_MSEC + TIME_PADDING_MSEC); }; var scrollToBottom = function() { $timeout(function() { var tutorCard = $('.conversation-skin-main-tutor-card'); if (tutorCard.length === 0) { return; } var tutorCardBottom = ( tutorCard.offset().top + tutorCard.outerHeight()); if ($(window).scrollTop() + $(window).height() < tutorCardBottom) { $('html, body').animate({ scrollTop: tutorCardBottom - $(window).height() + 12 }, { duration: TIME_SCROLL_MSEC, easing: 'easeOutQuad' }); } }, 100); }; var scrollToTop = function() { $timeout(function() { $('html, body').animate({ scrollTop: 0 }, 800, 'easeOutQuart'); return false; }); }; $scope.submitUserRating = function(ratingValue) { LearnerViewRatingService.submitUserRating(ratingValue); }; $scope.$on('ratingUpdated', function() { $scope.userRating = LearnerViewRatingService.getUserRating(); }); $window.addEventListener('beforeunload', function(e) { if (hasInteractedAtLeastOnce && !$scope.isInPreviewMode && !$scope.exploration.isStateTerminal( playerTranscriptService.getLastCard().stateName)) { StatsReportingService.recordMaybeLeaveEvent( playerTranscriptService.getLastStateName(), LearnerParamsService.getAllParams()); var confirmationMessage = ( 'If you navigate away from this page, your progress on the ' + 'exploration will be lost.'); (e || $window.event).returnValue = confirmationMessage; return confirmationMessage; } }); $scope.windowWidth = windowDimensionsService.getWidth(); $window.onresize = function() { $scope.adjustPageHeight(false, null); $scope.windowWidth = windowDimensionsService.getWidth(); }; $window.addEventListener('scroll', function() { fadeDotsOnScroll(); fixSupplementOnScroll(); }); var fadeDotsOnScroll = function() { var progressDots = $('.conversation-skin-progress-dots'); var progressDotsTop = progressDots.height(); var newOpacity = Math.max( (progressDotsTop - $(window).scrollTop()) / progressDotsTop, 0); progressDots.css({ opacity: newOpacity }); }; var fixSupplementOnScroll = function() { var supplementCard = $('div.conversation-skin-supplemental-card'); var topMargin = $('.navbar-container').height() - 20; if ($(window).scrollTop() > topMargin) { supplementCard.addClass( 'conversation-skin-supplemental-card-fixed'); } else { supplementCard.removeClass( 'conversation-skin-supplemental-card-fixed'); } }; $scope.canWindowFitTwoCards = function() { return $scope.windowWidth >= TWO_CARD_THRESHOLD_PX; }; $scope.isViewportNarrow = function() { return $scope.windowWidth < TWO_CARD_THRESHOLD_PX; }; $scope.isWindowTall = function() { return document.body.scrollHeight > $window.innerHeight; }; $scope.isScreenNarrowAndShowingTutorCard = function() { if (!$scope.isCurrentSupplementalCardNonempty()) { return $scope.isViewportNarrow(); } return $scope.isViewportNarrow() && tutorCardIsDisplayedIfNarrow; }; $scope.isScreenNarrowAndShowingSupplementalCard = function() { return $scope.isViewportNarrow() && !tutorCardIsDisplayedIfNarrow; }; $scope.showTutorCardIfScreenIsNarrow = function() { if ($scope.isViewportNarrow()) { tutorCardIsDisplayedIfNarrow = true; } }; $scope.showSupplementalCardIfScreenIsNarrow = function() { if ($scope.isViewportNarrow()) { tutorCardIsDisplayedIfNarrow = false; } }; $scope.initializePage(); LearnerViewRatingService.init(function(userRating) { $scope.userRating = userRating; }); $scope.collectionId = GLOBALS.collectionId; $scope.collectionTitle = GLOBALS.collectionTitle; } ] }; }]);
raju249/oppia
core/templates/dev/head/player/ConversationSkinDirective.js
JavaScript
apache-2.0
27,713
(function(e,t,n){"use strict";var r=e(document),i=t.Modernizr;e(document).ready(function(){e.fn.foundationAlerts?r.foundationAlerts():null;e.fn.foundationButtons?r.foundationButtons():null;e.fn.foundationAccordion?r.foundationAccordion():null;e.fn.foundationNavigation?r.foundationNavigation():null;e.fn.foundationTopBar?r.foundationTopBar():null;e.fn.foundationCustomForms?r.foundationCustomForms():null;e.fn.foundationMediaQueryViewer?r.foundationMediaQueryViewer():null;e.fn.foundationTabs?r.foundationTabs({callback:e.foundation.customForms.appendCustomMarkup}):null;e.fn.foundationTooltips?r.foundationTooltips():null;e.fn.foundationMagellan?r.foundationMagellan():null;e.fn.foundationClearing?r.foundationClearing():null;e.fn.placeholder?e("input, textarea").placeholder():null});i.touch&&!t.location.hash&&e(t).load(function(){setTimeout(function(){e(t).scrollTop()<20&&t.scrollTo(0,1)},0)})})(jQuery,this);
nasa/39A
spaceapps/static/javascripts/foundation/app-ck.js
JavaScript
apache-2.0
914
/* * Copyright 2016 e-UCM (http://www.e-ucm.es/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * This project has received funding from the European Union’s Horizon * 2020 research and innovation programme under grant agreement No 644187. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 (link is external) * * 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. */ 'use strict'; // Declare app level module which depends on filters, and services angular.module('myApp', [ 'ngRoute', 'toolbarApp', 'signupApp', 'loginApp', 'loginPluginApp', 'classApp', 'participantsApp', 'classesApp', 'activitiesApp', 'activityApp', 'gameApp', 'analysisApp', 'kibanaApp', 'gamesApp', 'activityApp', 'analyticsApp', 'devVisualizatorApp', 'services', 'xeditable', 'env-vars', 'ui.router', 'blockUI' ]).run(function (editableOptions, $localStorage, $cookies) { editableOptions.theme = 'bs3'; if ($localStorage.user) { $cookies.put('rageUserCookie', $localStorage.user.token, { path: '/' }); } }).filter('prettyDateId', function () { return function (_id) { if (_id) { return $.format.prettyDate(new Date(parseInt(_id.slice(0, 8), 16) * 1000)); } }; }).filter('prettyDate', function () { return function (date) { if (date) { return $.format.prettyDate(new Date(date)); } }; }).filter('list', function () { return function (list) { if (!list || list.length === 0) { return 'Empty list'; } var result = ''; list.forEach(function (v) { result += v + ', '; }); return result; }; }).filter('object2array', function () { return function (input) { var out = []; for (var i in input) { out.push(input[i]); } return out; }; }).factory('httpRequestInterceptor', ['$localStorage', function ($localStorage) { return { request: function (config) { config.headers.Accept = 'application/json'; if ($localStorage.user) { config.headers.Authorization = 'Bearer ' + $localStorage.user.token; } return config; } }; } ]).config(['$routeProvider', '$httpProvider', '$locationProvider', '$stateProvider', 'blockUIConfig', function ($routeProvider, $httpProvider, $locationProvider, $stateProvider, blockUIConfig) { $httpProvider.interceptors.push('httpRequestInterceptor'); $locationProvider.html5Mode({enabled: true, requireBase: false}); $stateProvider.state({ name: 'default', url: '/', templateUrl: 'view/home' }); $stateProvider.state({ name: 'home', url: '/home', templateUrl: 'view/home' }); $stateProvider.state({ name: 'login', url: '/login', templateUrl: 'view/login' }); $stateProvider.state({ name: 'signup', url: '/signup', templateUrl: 'view/signup' }); $stateProvider.state({ name: 'class', url: '/class', templateUrl: 'view/classactivity' }); $stateProvider.state({ name: 'data', url: '/data', templateUrl: 'view/data' }); $stateProvider.state({ name: 'game', url: '/game', templateUrl: 'view/gameactivity' }); blockUIConfig.autoBlock = false; blockUIConfig.message = 'Please wait...'; } ]).controller('AppCtrl', ['$rootScope', '$scope', '$location', '$http', '$timeout', '$localStorage', '$window', 'Games', 'Classes', 'Activities', 'Versions', 'Analysis', 'Role', 'CONSTANTS', 'QueryParams', function ($rootScope, $scope, $location, $http, $timeout, $localStorage, $window, Games, Classes, Activities, Versions, Analysis, Role, CONSTANTS, QueryParams) { $scope.$storage = $localStorage; $scope.DOCS = CONSTANTS.DOCS; // Role determination $scope.isUser = function () { return Role.isUser(); }; $scope.isAdmin = function () { return Role.isAdmin(); }; $scope.isStudent = function () { return Role.isStudent(); }; $scope.isTeacher = function () { return Role.isTeacher(); }; $scope.isOfflineActivity = function () { return $scope.isOfflineActivityParam($scope.selectedActivity); }; $scope.isOnlineActivity = function () { return $scope.isOnlineActivityParam($scope.selectedActivity); }; $scope.isOfflineActivityParam = function (activity) { return activity && activity.offline; }; $scope.isOnlineActivityParam = function (activity) { return activity && !activity.offline; }; $scope.isDeveloper = function () { return Role.isDeveloper(); }; $scope.goToClass = function(c) { $scope.$emit('selectClass', { class: c}); }; $scope.goToGame = function(game) { $scope.$emit('selectGame', { game: game}); }; $scope.goToActivity = function(activity) { $scope.$emit('selectActivity', { activity: activity}); }; var checkLogin = function() { $scope.username = $scope.isUser() ? $scope.$storage.user.username : ''; }; checkLogin(); $scope.$on('login', checkLogin); $scope.href = function (href) { $window.location.href = href; }; $scope.logout = function () { $http.delete(CONSTANTS.APIPATH + '/logout').success(function () { delete $scope.$storage.user; $timeout(function () { $location.url('login'); }, 50); }).error(function (data, status) { delete $scope.$storage.user; console.error('Error on get /logout ' + JSON.stringify(data) + ', status: ' + status); }); }; $scope.testIndex = 'default'; $scope.statementSubmitted = false; $scope.submitStatementsFile = function () { $scope.loadingDashboard = true; $scope.statementsFile.contents = JSON.parse($scope.statementsFile.contents); if ($scope.statementsFile.contents) { $http.post(CONSTANTS.PROXY + '/activities/test/' + $scope.selectedGame._id, $scope.statementsFile.contents) .success(function (data) { $scope.testIndex = data.id; $scope.statementSubmitted = true; $scope.generateTestVisualization(); $scope.loadingDashboard = false; }).error(function (data, status) { $scope.statementSubmitted = true; $scope.generateTestVisualization(); console.error('Error on post /activities/test/' + $scope.selectedGame._id + ' ' + JSON.stringify(data) + ', status: ' + status); $scope.loadingDashboard = false; }); } }; if (!$scope.selectedConfigView) { $scope.selectedConfigView = 'stormAnalysis'; } $scope.getActiveClass = function (id) { if (id === $scope.selectedConfigView) { return 'active'; } return null; }; $scope.templateButtonMsg = function (opened) { if (opened) { return 'Hide default JSON'; } return 'Show JSON'; }; $scope.$on('selectGame', function (event, params) { if (params.game) { $scope.selectedGame = params.game; Versions.forGame({gameId: params.game._id}).$promise.then(function(versions) { $scope.selectedVersion = versions[0]; if (Role.isDeveloper()) { $location.url('data'); } else { $location.url('game'); } $location.search('game', params.game._id); $location.search('version', $scope.selectedVersion._id); }); } }); $scope.$on('selectClass', function (event, params) { if (params.class) { $scope.selectedClass = params.class; $location.url('class'); $location.search('class', params.class._id); } }); $scope.$on('selectActivity', function (event, params) { if (params.activity) { $scope.selectedActivity = params.activity; $scope.selectedClass = Classes.get({classId: params.activity.classId}); $scope.selectedVersion = Versions.get({gameId: gameId, versionId: params.activity.versionId}); $scope.selectedGame = Games.get({gameId: params.activity.gameId}); $location.url('data'); $location.search('activity', params.activity._id); } }); $scope.developer = { name: '' }; // Load if ($scope.isUser()) { var gameId = QueryParams.getQueryParam('game'); if (gameId) { $scope.selectedGame = Games.get({gameId: gameId}); } var versionId = QueryParams.getQueryParam('version'); if (gameId && versionId) { $scope.selectedVersion = Versions.get({gameId: gameId, versionId: versionId}); } var classId = QueryParams.getQueryParam('class'); if (classId) { $scope.selectedClass = Classes.get({classId: classId}); } var activityId = QueryParams.getQueryParam('activity'); if (activityId) { Activities.get({activityId: activityId}).$promise.then(function(activity) { $scope.selectedActivity = activity; $scope.selectedClass = Classes.get({classId: activity.classId}); $scope.selectedVersion = Versions.get({gameId: gameId, versionId: activity.versionId}); $scope.selectedGame = Games.get({gameId: activity.gameId}); }); } } else if (!$window.location.pathname.endsWith('loginbyplugin')) { $location.url('login'); } } ]);
gorco/gf
app/public/js/controllers/app.js
JavaScript
apache-2.0
11,160
/* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. json.js 2006-10-05 This file adds these methods to JavaScript: object.toJSONString() This method produces a JSON text from an object. The object must not contain any cyclical references. array.toJSONString() This method produces a JSON text from an array. The array must not contain any cyclical references. string.parseJSON() This method parses a JSON text to produce an object or array. It will return false if there is an error. It is expected that these methods will formally become part of the JavaScript Programming Language in the Fourth Edition of the ECMAScript standard. */ (function () { var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, s = { array: function (x) { var a = ['['], b, f, i, l = x.length, v; for (i = 0; i < l; i += 1) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a.length] = ','; } a[a.length] = v; b = true; } } } a[a.length] = ']'; return a.join(''); }, 'boolean': function (x) { return String(x); }, 'null': function (x) { return "null"; }, number: function (x) { return isFinite(x) ? String(x) : 'null'; }, object: function (x) { if (x) { if (x instanceof Array) { return s.array(x); } var a = ['{'], b, f, i, v; for (i in x) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { if (b) { a[a.length] = ','; } a.push(s.string(i), ':', v); b = true; } } } a[a.length] = '}'; return a.join(''); } return 'null'; }, string: function (x) { if (/["\\\x00-\x1f]/.test(x)) { x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = m[b]; if (c) { return c; } c = b.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }); } return '"' + x + '"'; } }; Object.prototype.toJSONString = function () { return s.object(this); }; Array.prototype.toJSONString = function () { return s.array(this); }; })(); String.prototype.parseJSON = function () { try { return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) && eval('(' + this + ')'); } catch (e) { return false; } };
apache/chukwa
core/src/main/web/hicc/js/json.js
JavaScript
apache-2.0
4,907
/** * Created by hooxin on 14-10-10. */ /** * 字典维护标志 */ Ext.define('Techsupport.store.DictMaintFlag', { extend: 'Ext.data.Store', fields: ['text', 'value'], data: [ {text: '维护', value: 0}, {text: '停止维护', value: 1} ] })
firefoxmmx2/techsupport_ext4_scala
public/javascripts/app/store/DictMaintFlag.js
JavaScript
apache-2.0
279
/* FileSaver.js * A saveAs() & saveTextAs() FileSaver implementation. * 2014-06-24 * * Modify by Brian Chen * Author: Eli Grey, http://eligrey.com * License: X11/MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs // IE 10+ (native saveAs) || (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator)) // Everyone else || (function (view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function () { return view.URL || view.webkitURL || view; } , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = !view.externalHost && "download" in save_link , click = function (node) { var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); node.dispatchEvent(event); } , webkit_req_fs = view.webkitRequestFileSystem , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem , throw_outside = function (ex) { (view.setImmediate || view.setTimeout)(function () { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" , fs_min_size = 0 , deletion_queue = [] , process_deletion_queue = function () { var i = deletion_queue.length; while (i--) { var file = deletion_queue[i]; if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } } deletion_queue.length = 0; // clear queue } , dispatch = function (filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , FileSaver = function (blob, name) { // First try a.download, then web filesystem, then object URLs var filesaver = this , type = blob.type , blob_changed = false , object_url , target_view , get_object_url = function () { var object_url = get_URL().createObjectURL(blob); deletion_queue.push(object_url); return object_url; } , dispatch_all = function () { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function () { // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_object_url(blob); } if (target_view) { target_view.location.href = object_url; } else { window.open(object_url, "_blank"); } filesaver.readyState = filesaver.DONE; dispatch_all(); } , abortable = function (func) { return function () { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; } , create_if_not_found = { create: true, exclusive: false } , slice ; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_object_url(blob); save_link.href = object_url; save_link.download = name; click(save_link); filesaver.readyState = filesaver.DONE; dispatch_all(); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) { var save = function () { dir.getFile(name, create_if_not_found, abortable(function (file) { file.createWriter(abortable(function (writer) { writer.onwriteend = function (event) { target_view.location.href = file.toURL(); deletion_queue.push(file); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); }; writer.onerror = function () { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function (event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function () { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, { create: false }, abortable(function (file) { // delete file if it already exists file.remove(); save(); }), abortable(function (ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); } , FS_proto = FileSaver.prototype , saveAs = function (blob, name) { return new FileSaver(blob, name); } ; FS_proto.abort = function () { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; view.addEventListener("unload", process_deletion_queue, false); saveAs.unload = function () { process_deletion_queue(); view.removeEventListener("unload", process_deletion_queue, false); }; return saveAs; }( typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module !== null) { module.exports = saveAs; } else if ((typeof define !== "undefined" && define !== null) && (define.amd != null)) { define([], function () { return saveAs; }); } String.prototype.endsWithAny = function () { var strArray = Array.prototype.slice.call(arguments), $this = this.toLowerCase().toString(); for (var i = 0; i < strArray.length; i++) { if ($this.indexOf(strArray[i], $this.length - strArray[i].length) !== -1) return true; } return false; }; var saveTextAs = saveTextAs || (function (textContent, fileName, charset) { fileName = fileName || 'download.txt'; charset = charset || 'utf-8'; textContent = (textContent || '').replace(/\r?\n/g, "\r\n"); if (saveAs && Blob) { var blob = new Blob([textContent], { type: "text/plain;charset=" + charset }); saveAs(blob, fileName); return true; } else {//IE9- var saveTxtWindow = window.frames.saveTxtWindow; if (!saveTxtWindow) { saveTxtWindow = document.createElement('iframe'); saveTxtWindow.id = 'saveTxtWindow'; saveTxtWindow.style.display = 'none'; document.body.insertBefore(saveTxtWindow, null); saveTxtWindow = window.frames.saveTxtWindow; if (!saveTxtWindow) { saveTxtWindow = window.open('', '_temp', 'width=100,height=100'); if (!saveTxtWindow) { window.alert('Sorry, download file could not be created.'); return false; } } } var doc = saveTxtWindow.document; doc.open('text/html', 'replace'); doc.charset = charset; if (fileName.endsWithAny('.htm', '.html')) { doc.close(); doc.body.innerHTML = '\r\n' + textContent + '\r\n'; } else { if (!fileName.endsWithAny('.txt')) fileName += '.txt'; doc.write(textContent); doc.close(); } var retValue = doc.execCommand('SaveAs', null, fileName); saveTxtWindow.close(); return retValue; } })
PTRPlay/PrompterPro
Main/SoftServe.ITA.PrompterPro/PrompterPro.WebApplication/Scripts/FileSaver.js
JavaScript
apache-2.0
12,241
(function(angular){ 'use strict'; var app = angular.module('bernhardposselt.enhancetext', ['ngSanitize']); app.factory('TextEnhancer', ["SmileyEnhancer", "VideoEnhancer", "NewLineEnhancer", "ImageEnhancer", "YouTubeEnhancer", "LinkEnhancer", function (SmileyEnhancer, VideoEnhancer, NewLineEnhancer, ImageEnhancer, YouTubeEnhancer, LinkEnhancer) { return function (text, options) { text = escapeHtml(text); text = SmileyEnhancer(text, options.smilies); if (options.embedImages) { text = ImageEnhancer(text, options.embeddedImagesHeight, options.embeddedVideosWidth, options.embeddedLinkTarget); } if (options.embedVideos) { text = VideoEnhancer(text, options.embeddedImagesHeight, options.embeddedVideosWidth); } if (options.embedYoutube) { text = YouTubeEnhancer(text, options.embeddedYoutubeHeight, options.embeddedYoutubeWidth); } if (options.newLineToBr) { text = NewLineEnhancer(text); } if (options.embedLinks) { text = LinkEnhancer(text, options.embeddedLinkTarget); } return text; }; }]); app.factory('ImageEnhancer', function () { return function (text, height, width, target) { if(target === undefined) { target = '_blank'; } var imgRegex = /((?:https?):\/\/\S*\.(?:gif|jpg|jpeg|tiff|png|svg|webp))(\s&lt;\1&gt;){0,1}/gi; var imgDimensions = getDimensionsHtml(height, width); var img = '<a href="$1" target="' + target + '">' + '<img ' + imgDimensions + 'alt="image" src="$1"/>$1</a>'; return text.replace(imgRegex, img); }; }); app.factory('LinkEnhancer', function () { return function (text, target) { if(target === undefined) { target = '_blank'; } var regex = /((href|src)=["']|)(\b(https?|ftp|file):\/\/((?!&gt;)[-A-Z0-9+&@#\/%?=~_|!:,.;])*((?!&gt;)[-A-Z0-9+&@#\/%=~_|]))/ig; return text.replace(regex, function() { return arguments[1] ? arguments[0] : '<a target="' + target + '" href="'+ arguments[3] + '">' + arguments[3] + '</a>'; }); }; }); app.factory('NewLineEnhancer', function () { return function (text) { return text.replace(/\n/g, '<br/>').replace(/&#10;/g, '<br/>'); }; }); app.factory('SmileyEnhancer', function () { return function(text, smilies) { var smileyKeys = Object.keys(smilies); // split input into lines to avoid dealing with tons of // additional complexity/combinations arising from new lines var lines = text.split('\n'); var smileyReplacer = function (smiley, replacement, line) { // four possibilities: at the beginning, at the end, in the // middle or only the smiley var startSmiley = "^" + escapeRegExp(smiley) + " "; var endSmiley = " " + escapeRegExp(smiley) + "$"; var middleSmiley = " " + escapeRegExp(smiley) + " "; var onlySmiley = "^" + escapeRegExp(smiley) + "$"; return line. replace(new RegExp(startSmiley), replacement + " "). replace(new RegExp(endSmiley), " " + replacement). replace(new RegExp(middleSmiley), " " + replacement + " "). replace(new RegExp(onlySmiley), replacement); }; // loop over smilies and replace them in the text for (var i=0; i<smileyKeys.length; i++) { var smiley = smileyKeys[i]; var replacement = '<img alt="' + smiley + '" src="' + smilies[smiley] + '"/>'; // partially apply the replacer function to set the replacement // string var replacer = smileyReplacer.bind(null, smiley, replacement); lines = lines.map(replacer); } return lines.join('\n'); }; }); app.factory('VideoEnhancer', function () { return function (text, height, width) { var regex = /((?:https?):\/\/\S*\.(?:ogv|webm))/gi; var dimensions = getDimensionsHtml(height, width); var vid = '<video ' + dimensions + 'src="$1" controls preload="none"></video>'; return text.replace(regex, vid); }; }); app.factory('YouTubeEnhancer', function () { return function (text, height, width) { var regex = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/gi; var dimensions = getDimensionsHtml(height, width); var html = '<iframe ' + dimensions + 'src="https://www.youtube.com/embed/$1" ' + 'frameborder="0" allowfullscreen></iframe>'; return text.replace(regex, html); }; }); app.provider('enhanceTextFilter', function () { var options = { cache: true, newLineToBr: true, embedLinks: true, embeddedLinkTarget: '_blank', embedImages: true, embeddedImagesHeight: undefined, embeddedImagesWidth: undefined, embedVideos: true, embeddedVideosHeight: undefined, embeddedVideosWidth: undefined, embedYoutube: true, embeddedYoutubeHeight: undefined, embeddedYoutubeWidth: undefined, smilies: {} }, textCache = {}; this.setOptions = function (customOptions) { angular.extend(options, customOptions); }; /* @ngInject */ this.$get = function ($sce, TextEnhancer) { return function (text) { var originalText = text; // hit cache first before replacing if (options.cache) { var cachedResult = textCache[text]; if (angular.isDefined(cachedResult)) { return cachedResult; } } text = TextEnhancer(text, options); // trust result to able to use it in ng-bind-html text = $sce.trustAsHtml(text); // cache result if (options.cache) { textCache[originalText] = text; } return text; }; }; this.$get.$inject = ["$sce", "TextEnhancer"]; }); function escapeHtml(str) { var div = document.createElement('div'); div.appendChild(document.createTextNode(str)); return div.innerHTML; } // taken from https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions function escapeRegExp (str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getDimensionsHtml (height, width) { var dimensions = ''; if (angular.isDefined(height)) { dimensions += 'height="' + height + '" '; } if (angular.isDefined(width)) { dimensions += 'width="' + width + '" '; } return dimensions; } })(angular, undefined);
gzwfdy/zone
src/main/webapp/static/app/js/vendor/angular-enhance-text.min.js
JavaScript
apache-2.0
7,184
import "./main"; import "core/utils"; import "bootstrap/js/dist/tab"; import dayjs from "dayjs"; import advancedFormat from "dayjs/plugin/advancedFormat"; import utc from "dayjs/plugin/utc"; import timezone from "dayjs/plugin/timezone"; import timezones from "../timezones"; import CTFd from "core/CTFd"; import { default as helpers } from "core/helpers"; import $ from "jquery"; import { ezQuery, ezProgressBar, ezAlert } from "core/ezq"; import CodeMirror from "codemirror"; import "codemirror/mode/htmlmixed/htmlmixed.js"; import Vue from "vue/dist/vue.esm.browser"; import FieldList from "../components/configs/fields/FieldList.vue"; dayjs.extend(advancedFormat); dayjs.extend(utc); dayjs.extend(timezone); function loadTimestamp(place, timestamp) { if (typeof timestamp == "string") { timestamp = parseInt(timestamp, 10) * 1000; } const d = dayjs(timestamp); $("#" + place + "-month").val(d.month() + 1); // Months are zero indexed (https://day.js.org/docs/en/get-set/month) $("#" + place + "-day").val(d.date()); $("#" + place + "-year").val(d.year()); $("#" + place + "-hour").val(d.hour()); $("#" + place + "-minute").val(d.minute()); loadDateValues(place); } function loadDateValues(place) { const month = $("#" + place + "-month").val(); const day = $("#" + place + "-day").val(); const year = $("#" + place + "-year").val(); const hour = $("#" + place + "-hour").val(); const minute = $("#" + place + "-minute").val(); const timezone_string = $("#" + place + "-timezone").val(); const utc = convertDateToMoment(month, day, year, hour, minute); if (utc.unix() && month && day && year && hour && minute) { $("#" + place).val(utc.unix()); $("#" + place + "-local").val( utc.format("dddd, MMMM Do YYYY, h:mm:ss a z (zzz)") ); $("#" + place + "-zonetime").val( utc.tz(timezone_string).format("dddd, MMMM Do YYYY, h:mm:ss a z (zzz)") ); } else { $("#" + place).val(""); $("#" + place + "-local").val(""); $("#" + place + "-zonetime").val(""); } } function convertDateToMoment(month, day, year, hour, minute) { let month_num = month.toString(); if (month_num.length == 1) { month_num = "0" + month_num; } let day_str = day.toString(); if (day_str.length == 1) { day_str = "0" + day_str; } let hour_str = hour.toString(); if (hour_str.length == 1) { hour_str = "0" + hour_str; } let min_str = minute.toString(); if (min_str.length == 1) { min_str = "0" + min_str; } // 2013-02-08 24:00 const date_string = year.toString() + "-" + month_num + "-" + day_str + " " + hour_str + ":" + min_str + ":00"; return dayjs(date_string); } function updateConfigs(event) { event.preventDefault(); const obj = $(this).serializeJSON(); const params = {}; if (obj.mail_useauth === false) { obj.mail_username = null; obj.mail_password = null; } else { if (obj.mail_username === "") { delete obj.mail_username; } if (obj.mail_password === "") { delete obj.mail_password; } } Object.keys(obj).forEach(function(x) { if (obj[x] === "true") { params[x] = true; } else if (obj[x] === "false") { params[x] = false; } else { params[x] = obj[x]; } }); CTFd.api.patch_config_list({}, params).then(function(_response) { if (_response.success) { window.location.reload(); } else { let errors = _response.errors.value.join("\n"); ezAlert({ title: "Error!", body: errors, button: "Okay" }); } }); } function uploadLogo(event) { event.preventDefault(); let form = event.target; helpers.files.upload(form, {}, function(response) { const f = response.data[0]; const params = { value: f.location }; CTFd.fetch("/api/v1/configs/ctf_logo", { method: "PATCH", body: JSON.stringify(params) }) .then(function(response) { return response.json(); }) .then(function(response) { if (response.success) { window.location.reload(); } else { ezAlert({ title: "Error!", body: "Logo uploading failed!", button: "Okay" }); } }); }); } function switchUserMode(event) { event.preventDefault(); if ( confirm( "Are you sure you'd like to switch user modes?\n\nAll user submissions, awards, unlocks, and tracking will be deleted!" ) ) { let formData = new FormData(); formData.append("submissions", true); formData.append("nonce", CTFd.config.csrfNonce); fetch(CTFd.config.urlRoot + "/admin/reset", { method: "POST", credentials: "same-origin", body: formData }); // Bind `this` so that we can reuse the updateConfigs function let binded = updateConfigs.bind(this); binded(event); } } function removeLogo() { ezQuery({ title: "Remove logo", body: "Are you sure you'd like to remove the CTF logo?", success: function() { const params = { value: null }; CTFd.api .patch_config({ configKey: "ctf_logo" }, params) .then(_response => { window.location.reload(); }); } }); } function smallIconUpload(event) { event.preventDefault(); let form = event.target; helpers.files.upload(form, {}, function(response) { const f = response.data[0]; const params = { value: f.location }; CTFd.fetch("/api/v1/configs/ctf_small_icon", { method: "PATCH", body: JSON.stringify(params) }) .then(function(response) { return response.json(); }) .then(function(response) { if (response.success) { window.location.reload(); } else { ezAlert({ title: "Error!", body: "Icon uploading failed!", button: "Okay" }); } }); }); } function removeSmallIcon() { ezQuery({ title: "Remove logo", body: "Are you sure you'd like to remove the small site icon?", success: function() { const params = { value: null }; CTFd.api .patch_config({ configKey: "ctf_small_icon" }, params) .then(_response => { window.location.reload(); }); } }); } function importCSV(event) { event.preventDefault(); let csv_file = document.getElementById("import-csv-file").files[0]; let csv_type = document.getElementById("import-csv-type").value; let form_data = new FormData(); form_data.append("csv_file", csv_file); form_data.append("csv_type", csv_type); form_data.append("nonce", CTFd.config.csrfNonce); let pg = ezProgressBar({ width: 0, title: "Upload Progress" }); $.ajax({ url: CTFd.config.urlRoot + "/admin/import/csv", type: "POST", data: form_data, processData: false, contentType: false, statusCode: { 500: function(resp) { // Normalize errors let errors = JSON.parse(resp.responseText); let errorText = ""; errors.forEach(element => { errorText += `Line ${element[0]}: ${JSON.stringify(element[1])}\n`; }); // Show errors alert(errorText); // Hide progress modal if its there pg = ezProgressBar({ target: pg, width: 100 }); setTimeout(function() { pg.modal("hide"); }, 500); } }, xhr: function() { let xhr = $.ajaxSettings.xhr(); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { let width = (e.loaded / e.total) * 100; pg = ezProgressBar({ target: pg, width: width }); } }; return xhr; }, success: function(_data) { pg = ezProgressBar({ target: pg, width: 100 }); setTimeout(function() { pg.modal("hide"); }, 500); setTimeout(function() { window.location.reload(); }, 700); } }); } function importConfig(event) { event.preventDefault(); let import_file = document.getElementById("import-file").files[0]; let form_data = new FormData(); form_data.append("backup", import_file); form_data.append("nonce", CTFd.config.csrfNonce); let pg = ezProgressBar({ width: 0, title: "Upload Progress" }); $.ajax({ url: CTFd.config.urlRoot + "/admin/import", type: "POST", data: form_data, processData: false, contentType: false, statusCode: { 500: function(resp) { alert(resp.responseText); } }, xhr: function() { let xhr = $.ajaxSettings.xhr(); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { let width = (e.loaded / e.total) * 100; pg = ezProgressBar({ target: pg, width: width }); } }; return xhr; }, success: function(_data) { pg = ezProgressBar({ target: pg, width: 100 }); setTimeout(function() { pg.modal("hide"); }, 500); setTimeout(function() { window.location.reload(); }, 700); } }); } function exportConfig(event) { event.preventDefault(); window.location.href = $(this).attr("href"); } function insertTimezones(target) { let current = $("<option>").text(dayjs.tz.guess()); $(target).append(current); let tz_names = timezones; for (let i = 0; i < tz_names.length; i++) { let tz = $("<option>").text(tz_names[i]); $(target).append(tz); } } $(() => { const theme_header_editor = CodeMirror.fromTextArea( document.getElementById("theme-header"), { lineNumbers: true, lineWrapping: true, mode: "htmlmixed", htmlMode: true } ); const theme_footer_editor = CodeMirror.fromTextArea( document.getElementById("theme-footer"), { lineNumbers: true, lineWrapping: true, mode: "htmlmixed", htmlMode: true } ); const theme_settings_editor = CodeMirror.fromTextArea( document.getElementById("theme-settings"), { lineNumbers: true, lineWrapping: true, readOnly: true, mode: { name: "javascript", json: true } } ); // Handle refreshing codemirror when switching tabs. // Better than the autorefresh approach b/c there's no flicker $("a[href='#theme']").on("shown.bs.tab", function(_e) { theme_header_editor.refresh(); theme_footer_editor.refresh(); theme_settings_editor.refresh(); }); $( "a[href='#legal'], a[href='#tos-config'], a[href='#privacy-policy-config']" ).on("shown.bs.tab", function(_e) { $("#tos-config .CodeMirror").each(function(i, el) { el.CodeMirror.refresh(); }); $("#privacy-policy-config .CodeMirror").each(function(i, el) { el.CodeMirror.refresh(); }); }); $("#theme-settings-modal form").submit(function(e) { e.preventDefault(); theme_settings_editor .getDoc() .setValue(JSON.stringify($(this).serializeJSON(), null, 2)); $("#theme-settings-modal").modal("hide"); }); $("#theme-settings-button").click(function() { let form = $("#theme-settings-modal form"); let data; // Ignore invalid JSON data try { data = JSON.parse(theme_settings_editor.getValue()); } catch (e) { data = {}; } $.each(data, function(key, value) { var ctrl = form.find(`[name='${key}']`); switch (ctrl.prop("type")) { case "radio": case "checkbox": ctrl.each(function() { if ($(this).attr("value") == value) { $(this).attr("checked", value); } }); break; default: ctrl.val(value); } }); $("#theme-settings-modal").modal(); }); insertTimezones($("#start-timezone")); insertTimezones($("#end-timezone")); insertTimezones($("#freeze-timezone")); $(".config-section > form:not(.form-upload, .custom-config-form)").submit( updateConfigs ); $("#logo-upload").submit(uploadLogo); $("#user-mode-form").submit(switchUserMode); $("#remove-logo").click(removeLogo); $("#ctf-small-icon-upload").submit(smallIconUpload); $("#remove-small-icon").click(removeSmallIcon); $("#export-button").click(exportConfig); $("#import-button").click(importConfig); $("#import-csv-form").submit(importCSV); $("#config-color-update").click(function() { const hex_code = $("#config-color-picker").val(); const user_css = theme_header_editor.getValue(); let new_css; if (user_css.length) { let css_vars = `theme-color: ${hex_code};`; new_css = user_css.replace(/theme-color: (.*);/, css_vars); } else { new_css = `<style id="theme-color">\n` + `:root {--theme-color: ${hex_code};}\n` + `.navbar{background-color: var(--theme-color) !important;}\n` + `.jumbotron{background-color: var(--theme-color) !important;}\n` + `</style>\n`; } theme_header_editor.getDoc().setValue(new_css); }); $(".start-date").change(function() { loadDateValues("start"); }); $(".end-date").change(function() { loadDateValues("end"); }); $(".freeze-date").change(function() { loadDateValues("freeze"); }); const start = $("#start").val(); const end = $("#end").val(); const freeze = $("#freeze").val(); if (start) { loadTimestamp("start", start); } if (end) { loadTimestamp("end", end); } if (freeze) { loadTimestamp("freeze", freeze); } // Toggle username and password based on stored value $("#mail_useauth") .change(function() { $("#mail_username_password").toggle(this.checked); }) .change(); // Insert FieldList element for users const fieldList = Vue.extend(FieldList); let userVueContainer = document.createElement("div"); document.querySelector("#user-field-list").appendChild(userVueContainer); new fieldList({ propsData: { type: "user" } }).$mount(userVueContainer); // Insert FieldList element for teams let teamVueContainer = document.createElement("div"); document.querySelector("#team-field-list").appendChild(teamVueContainer); new fieldList({ propsData: { type: "team" } }).$mount(teamVueContainer); });
isislab/CTFd
CTFd/themes/admin/assets/js/pages/configs.js
JavaScript
apache-2.0
14,384
//// [declFileWithExtendsClauseThatHasItsContainerNameConflict.ts] declare module A.B.C { class B { } } module A.B { export class EventManager { id: number; } } module A.B.C { export class ContextMenu extends EventManager { name: string; } } //// [declFileWithExtendsClauseThatHasItsContainerNameConflict.js] 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; } __.prototype = b.prototype; d.prototype = new __(); }; var A; (function (A) { var B; (function (B) { var EventManager = (function () { function EventManager() { } return EventManager; })(); B.EventManager = EventManager; })(B = A.B || (A.B = {})); })(A || (A = {})); var A; (function (A) { var B; (function (B) { var C; (function (C) { var ContextMenu = (function (_super) { __extends(ContextMenu, _super); function ContextMenu() { _super.apply(this, arguments); } return ContextMenu; })(B.EventManager); C.ContextMenu = ContextMenu; })(C = B.C || (B.C = {})); })(B = A.B || (A.B = {})); })(A || (A = {})); //// [declFileWithExtendsClauseThatHasItsContainerNameConflict.d.ts] declare module A.B.C { class B { } } declare module A.B { class EventManager { id: number; } } declare module A.B.C { class ContextMenu extends EventManager { name: string; } }
Raynos/TypeScript
tests/baselines/reference/declFileWithExtendsClauseThatHasItsContainerNameConflict.js
JavaScript
apache-2.0
1,706
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u0434\u043f", "\u043f\u043f" ], "DAY": [ "\u043d\u0435\u0434\u0456\u043b\u044f", "\u043f\u043e\u043d\u0435\u0434\u0456\u043b\u043e\u043a", "\u0432\u0456\u0432\u0442\u043e\u0440\u043e\u043a", "\u0441\u0435\u0440\u0435\u0434\u0430", "\u0447\u0435\u0442\u0432\u0435\u0440", "\u043f\u02bc\u044f\u0442\u043d\u0438\u0446\u044f", "\u0441\u0443\u0431\u043e\u0442\u0430" ], "ERANAMES": [ "\u0434\u043e \u043d\u0430\u0448\u043e\u0457 \u0435\u0440\u0438", "\u043d\u0430\u0448\u043e\u0457 \u0435\u0440\u0438" ], "ERAS": [ "\u0434\u043e \u043d. \u0435.", "\u043d. \u0435." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u0441\u0456\u0447\u043d\u044f", "\u043b\u044e\u0442\u043e\u0433\u043e", "\u0431\u0435\u0440\u0435\u0437\u043d\u044f", "\u043a\u0432\u0456\u0442\u043d\u044f", "\u0442\u0440\u0430\u0432\u043d\u044f", "\u0447\u0435\u0440\u0432\u043d\u044f", "\u043b\u0438\u043f\u043d\u044f", "\u0441\u0435\u0440\u043f\u043d\u044f", "\u0432\u0435\u0440\u0435\u0441\u043d\u044f", "\u0436\u043e\u0432\u0442\u043d\u044f", "\u043b\u0438\u0441\u0442\u043e\u043f\u0430\u0434\u0430", "\u0433\u0440\u0443\u0434\u043d\u044f" ], "SHORTDAY": [ "\u041d\u0434", "\u041f\u043d", "\u0412\u0442", "\u0421\u0440", "\u0427\u0442", "\u041f\u0442", "\u0421\u0431" ], "SHORTMONTH": [ "\u0441\u0456\u0447.", "\u043b\u044e\u0442.", "\u0431\u0435\u0440.", "\u043a\u0432\u0456\u0442.", "\u0442\u0440\u0430\u0432.", "\u0447\u0435\u0440\u0432.", "\u043b\u0438\u043f.", "\u0441\u0435\u0440\u043f.", "\u0432\u0435\u0440.", "\u0436\u043e\u0432\u0442.", "\u043b\u0438\u0441\u0442.", "\u0433\u0440\u0443\u0434." ], "STANDALONEMONTH": [ "\u0441\u0456\u0447\u0435\u043d\u044c", "\u043b\u044e\u0442\u0438\u0439", "\u0431\u0435\u0440\u0435\u0437\u0435\u043d\u044c", "\u043a\u0432\u0456\u0442\u0435\u043d\u044c", "\u0442\u0440\u0430\u0432\u0435\u043d\u044c", "\u0447\u0435\u0440\u0432\u0435\u043d\u044c", "\u043b\u0438\u043f\u0435\u043d\u044c", "\u0441\u0435\u0440\u043f\u0435\u043d\u044c", "\u0432\u0435\u0440\u0435\u0441\u0435\u043d\u044c", "\u0436\u043e\u0432\u0442\u0435\u043d\u044c", "\u043b\u0438\u0441\u0442\u043e\u043f\u0430\u0434", "\u0433\u0440\u0443\u0434\u0435\u043d\u044c" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y '\u0440'.", "longDate": "d MMMM y '\u0440'.", "medium": "d MMM y '\u0440'. HH:mm:ss", "mediumDate": "d MMM y '\u0440'.", "mediumTime": "HH:mm:ss", "short": "dd.MM.yy HH:mm", "shortDate": "dd.MM.yy", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u0433\u0440\u043d.", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "uk-ua", "localeID": "uk_UA", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (vf.v == 0 && i % 10 == 1 && i % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14)) { return PLURAL_CATEGORY.FEW; } if (vf.v == 0 && i % 10 == 0 || vf.v == 0 && i % 10 >= 5 && i % 10 <= 9 || vf.v == 0 && i % 100 >= 11 && i % 100 <= 14) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;} }); }]);
yoyocms/YoYoCms.AbpProjectTemplate
src/YoYoCms.AbpProjectTemplate.Web/Scripts/i18n/angular-locale_uk-ua.js
JavaScript
apache-2.0
4,569
// // Copyright (c) Microsoft and contributors. 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. // var assert = require('assert'); // Test includes var testutil = require('../../framework/util'); // Lib includes var ISO8061Date = require('../../../lib/common/util/iso8061date'); var date = require('../../../lib/common/util/date'); describe('iso8061date-tests', function () { it('parse should work', function (done) { var datetime = new Date(Date.UTC(2011, 6, 17, 14, 0, 23, 270)); var datetimeAtom = "2011-07-17T14:00:23.270Z"; var parsed = ISO8061Date.parse(datetimeAtom); assert.deepEqual(parsed, datetime); done(); }); it('parsing a long Timestamp should work', function (done) { var datetime = new Date(Date.UTC(2011, 6, 17, 14, 0, 23, 270)); var datetimeAtom = "2011-07-17T14:00:23.2701234Z"; var parsed = ISO8061Date.parse(datetimeAtom); assert.deepEqual(parsed, datetime); done(); }); it('parsing a long Timestamp with rounding shoudl work', function (done) { var datetime = new Date(Date.UTC(2011, 6, 17, 14, 0, 23, 270)); var datetimeAtom = "2011-07-17T14:00:23.26993Z"; var parsed = ISO8061Date.parse(datetimeAtom); assert.deepEqual(parsed, datetime); done(); }); it('parsing a short Millisecond field should work', function (done) { var datetime = new Date(Date.UTC(2011, 6, 17, 14, 0, 23, 200)); var datetimeAtom = "2011-07-17T14:00:23.2Z"; var parsed = ISO8061Date.parse(datetimeAtom); assert.deepEqual(parsed, datetime); done(); }); it('parsing padded short Milliseconds should work', function (done) { var datetime = new Date(Date.UTC(2011, 6, 17, 14, 0, 23, 3)); var datetimeAtom = "2011-07-17T14:00:23.003Z"; var parsed = ISO8061Date.parse(datetimeAtom); assert.deepEqual(parsed, datetime); done(); }); it('format should work', function (done) { var datetime = Date.UTC(2011, 6, 17, 14, 0, 23, 270); var datetimeAtom = "2011-07-17T14:00:23.2700000Z"; var strdate = ISO8061Date.format(new Date(datetime)); assert.equal(strdate, datetimeAtom); done(); }); }); describe('date-tests', function () { it ('daysFromNow should work', function (done) { var shift = 5; assert.equal(date.daysFromNow(shift).getDay(), ((new Date()).getDay() + shift) % 7); done(); }); it ('hoursFromNow should work', function (done) { var shift = 20; assert.equal(date.hoursFromNow(shift).getHours(), ((new Date()).getHours() + shift) % 24); done(); }); it ('minutesFromNow should work', function (done) { var shift = 20; assert.equal(date.minutesFromNow(shift).getMinutes(), ((new Date()).getMinutes() + shift) % 60); done(); }); it ('secondsFromNow should work', function (done) { var shift = 58; assert.equal(date.secondsFromNow(shift).getSeconds(), ((new Date()).getSeconds() + shift) % 60); done(); }); });
XiaoningLiu/azure-storage-node
test/common/util/iso8061date-tests.js
JavaScript
apache-2.0
3,463
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es6id: 23.1.3.8 description: > Throws a TypeError if `this` object does not have a [[MapData]] internal slot. info: | Map.prototype.keys () 1. Let M be the this value. 2. Return CreateMapIterator(M, "key"). 23.1.5.1 CreateMapIterator Abstract Operation ... 2. If map does not have a [[MapData]] internal slot, throw a TypeError exception. ... ---*/ var m = new Map(); assert.throws(TypeError, function() { Map.prototype.keys.call([]); }); assert.throws(TypeError, function() { m.keys.call([]); }); assert.throws(TypeError, function() { Map.prototype.keys.call({}); }); assert.throws(TypeError, function() { m.keys.call({}); });
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Map/prototype/keys/does-not-have-mapdata-internal-slot.js
JavaScript
bsd-2-clause
807
import TLSFingerprints from "./models/TLSFingerprints"; import FingerPrintsTemplate from "./templates/Fingerprints.html"; import FingerPrintTemplate from "./templates/Fingerprint.html"; import FingerPrintDialogContent from "./templates/FingerPrintDialogContent.html"; const model = new TLSFingerprints(); const FingerPrintSingle = Backbone.View.extend({ initialize: function(params) { this.ua = params.ua; }, events: { "click button": "trust_fingerprint" }, render: function () { this.$el.html(FingerPrintTemplate(this.model.toJSON())); }, trust_fingerprint: function() { const that = this; BootstrapDialog.show({ type: BootstrapDialog.TYPE_INFO, title: "Save new fingerprint", message: $('<div></div>').html(FingerPrintDialogContent({})), buttons: [{ label: "Save", cssClass: 'btn-primary', icon: 'fa fa-floppy-o ', action: function (dlg) { // bind to controller that.handle_trust( dlg.$modalBody.find('#fp_description').val(), dlg.$modalBody.find('#fp_trusted').is(':checked') ); dlg.close(); } }, { label: 'Close', action: function (dlg) { dlg.close(); } }] }); }, handle_trust: function (description, trusted) { ajaxCall( "/api/nginx/settings/addtls_fingerprint", { 'tls_fingerprint': { 'curves' : this.model.get('curves'), 'ciphers': this.model.get('ciphers'), 'user_agent': this.ua, 'trusted': trusted ? '1' : '0', 'description': description } }, function (data, status) { } ); } }); const FingerPrintList = Backbone.View.extend({ initialize: function (params) { this.ua = params.ua; this.render(); }, render: function () { const that = this; this.$el.html(FingerPrintsTemplate({ua: this.ua})); const content_holder = this.$el.find('.content_holder'); const chart_holder = this.$el.find('.chart_holder'); const chart_data = this.collection.map(function (d) { return {label: d.get('ciphers') + "||" + d.get('curves'), value: d.get('count')}; }); this.collection.forEach(function (fingerprint) { const row = new FingerPrintSingle({'model': fingerprint, 'ua': that.ua}); content_holder.append(row.$el); row.render(); }); try { nv.addGraph(function () { const chart = nv.models.pieChart(); chart.x(function (d) { return d.label; }); chart.y(function (d) { return d.value; }); chart.showLabels(false); chart.labelType("value"); chart.donut(true); chart.donutRatio(0.2); d3.select(chart_holder[0]) .datum(chart_data) .transition().duration(350) .call(chart); return chart; }); } catch (e) { console.log(e); } } }); const FingerprintMain = Backbone.View.extend({ initialize: function() { this.listenTo(this.model, "sync", this.render); }, render: function () { this.$el.html(''); this.render_all(this.model.attributes); }, render_all(attributes) { for (const ua in attributes) { // skip loop if the property is from prototype if (attributes.hasOwnProperty(ua)) { const fingerprints = new Backbone.Collection(attributes[ua]); const fingerprints_view = new FingerPrintList({'collection': fingerprints, 'ua': ua}); this.$el.append(fingerprints_view.$el); } } }, }); const fpm = new FingerprintMain({'model': model}); $('#tls_handshakes_application').append(fpm.$el); model.fetch();
evbevz/plugins
www/nginx/src/opnsense/www/js/nginx/src/tls_handshakes.js
JavaScript
bsd-2-clause
4,364
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: | If pos is a value of Number type that is an integer, then the result of x.charAt(pos) is equal to the result of x.substring(pos, pos+1) es5id: 15.5.4.4_A4_T2 description: > Compare results of x.charAt(pos) and x.substring(pos, pos+1), wheb pos is smaller of zero ---*/ ////////////////////////////////////////////////////////////////////////////// //CHECK#1 for (var i = -2; i < 0; i++) { if ("ABC\u0041\u0042\u0043".charAt(i) !== "\u0041\u0042\u0043ABC".substring(i, i + 1)) { $ERROR('#' + (i + 2) + ': "ABC\\u0041\\u0042\\u0043".charAt(' + i + ') === "\\u0041\\u0042\\u0043ABC".substring(' + i + ', ' + (i + 1) + '). Actual: "ABC\\u0041\\u0042\\u0043".charAt(' + i + ') ===' + ("ABC\u0041\u0042\u0043".charAt(i))); } } // //////////////////////////////////////////////////////////////////////////////
sebastienros/jint
Jint.Tests.Test262/test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T2.js
JavaScript
bsd-2-clause
976
"use strict"; module.exports = { delegates: { im_too_lazy: function() { $C("button", { name: "my first button" }, function(btn) { $("#button_holder").empty(); // extra btn.prependTo($("#button_holder")); // alright, this is technically extra btn.$el.hide(); btn.$el.fadeIn(); }); } } };
logV/snorkel.sf
snorkel/app/controllers/home/client.js
JavaScript
bsd-2-clause
388
/* * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. */ 'use strict'; /* global createProcessedMediaStreamTrack */ // defined in main.js /** * Wrapper around createProcessedMediaStreamTrack to apply transform to a * MediaStream. * @param {!MediaStream} sourceStream the video stream to be transformed. The * first video track will be used. * @param {!FrameTransformFn} transform the transform to apply to the * sourceStream. * @param {!AbortSignal} signal can be used to stop processing * @return {!MediaStream} holds a single video track of the transformed video * frames */ function createProcessedMediaStream(sourceStream, transform, signal) { // For this sample, we're only dealing with video tracks. /** @type {!MediaStreamTrack} */ const sourceTrack = sourceStream.getVideoTracks()[0]; const processedTrack = createProcessedMediaStreamTrack(sourceTrack, transform, signal); // Create a new MediaStream to hold our processed track. const processedStream = new MediaStream(); processedStream.addTrack(processedTrack); return processedStream; } /** * Interface implemented by all video sources the user can select. A common * interface allows the user to choose a source independently of the transform * and sink. * @interface */ class MediaStreamSource { // eslint-disable-line no-unused-vars /** * Sets the path to this object from the debug global var. * @param {string} path */ setDebugPath(path) {} /** * Indicates if the source video should be mirrored/displayed on the page. If * false (the default), any element producing frames will not be a child of * the document. * @param {boolean} visible whether to add the raw source video to the page */ setVisibility(visible) {} /** * Initializes and returns the MediaStream for this source. * @return {!Promise<!MediaStream>} */ async getMediaStream() {} /** Frees any resources used by this object. */ destroy() {} } /** * Interface implemented by all video transforms that the user can select. A * common interface allows the user to choose a transform independently of the * source and sink. * @interface */ class FrameTransform { // eslint-disable-line no-unused-vars /** Initializes state that is reused across frames. */ async init() {} /** * Applies the transform to frame. Queues the output frame (if any) using the * controller. * @param {!VideoFrame} frame the input frame * @param {!TransformStreamDefaultController<!VideoFrame>} controller */ async transform(frame, controller) {} /** Frees any resources used by this object. */ destroy() {} } /** * Interface implemented by all video sinks that the user can select. A common * interface allows the user to choose a sink independently of the source and * transform. * @interface */ class MediaStreamSink { // eslint-disable-line no-unused-vars /** * @param {!MediaStream} stream */ async setMediaStream(stream) {} /** Frees any resources used by this object. */ destroy() {} } /** * Assembles a MediaStreamSource, FrameTransform, and MediaStreamSink together. */ class Pipeline { // eslint-disable-line no-unused-vars constructor() { /** @private {?MediaStreamSource} set by updateSource*/ this.source_ = null; /** @private {?FrameTransform} set by updateTransform */ this.frameTransform_ = null; /** @private {?MediaStreamSink} set by updateSink */ this.sink_ = null; /** @private {!AbortController} may used to stop all processing */ this.abortController_ = new AbortController(); /** * @private {?MediaStream} set in maybeStartPipeline_ after all of source_, * frameTransform_, and sink_ are set */ this.processedStream_ = null; } /** @return {?MediaStreamSource} */ getSource() { return this.source_; } /** * Sets a new source for the pipeline. * @param {!MediaStreamSource} mediaStreamSource */ async updateSource(mediaStreamSource) { if (this.source_) { this.abortController_.abort(); this.abortController_ = new AbortController(); this.source_.destroy(); this.processedStream_ = null; } this.source_ = mediaStreamSource; this.source_.setDebugPath('debug.pipeline.source_'); console.log( '[Pipeline] Updated source.', 'debug.pipeline.source_ = ', this.source_); await this.maybeStartPipeline_(); } /** @private */ async maybeStartPipeline_() { if (this.processedStream_ || !this.source_ || !this.frameTransform_ || !this.sink_) { return; } const sourceStream = await this.source_.getMediaStream(); await this.frameTransform_.init(); try { this.processedStream_ = createProcessedMediaStream( sourceStream, async (frame, controller) => { if (this.frameTransform_) { await this.frameTransform_.transform(frame, controller); } }, this.abortController_.signal); } catch (e) { this.destroy(); return; } await this.sink_.setMediaStream(this.processedStream_); console.log( '[Pipeline] Pipeline started.', 'debug.pipeline.abortController_ =', this.abortController_); } /** * Sets a new transform for the pipeline. * @param {!FrameTransform} frameTransform */ async updateTransform(frameTransform) { if (this.frameTransform_) this.frameTransform_.destroy(); this.frameTransform_ = frameTransform; console.log( '[Pipeline] Updated frame transform.', 'debug.pipeline.frameTransform_ = ', this.frameTransform_); if (this.processedStream_) { await this.frameTransform_.init(); } else { await this.maybeStartPipeline_(); } } /** * Sets a new sink for the pipeline. * @param {!MediaStreamSink} mediaStreamSink */ async updateSink(mediaStreamSink) { if (this.sink_) this.sink_.destroy(); this.sink_ = mediaStreamSink; console.log( '[Pipeline] Updated sink.', 'debug.pipeline.sink_ = ', this.sink_); if (this.processedStream_) { await this.sink_.setMediaStream(this.processedStream_); } else { await this.maybeStartPipeline_(); } } /** Frees any resources used by this object. */ destroy() { console.log('[Pipeline] Destroying Pipeline'); this.abortController_.abort(); if (this.source_) this.source_.destroy(); if (this.frameTransform_) this.frameTransform_.destroy(); if (this.sink_) this.sink_.destroy(); } }
webrtc/samples
src/content/insertable-streams/video-processing/js/pipeline.js
JavaScript
bsd-3-clause
6,704
/** * @license * Copyright 2019 Google LLC. * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * Code distributed by Google as part of this project is also * subject to an additional IP rights grant found at * http://polymer.github.io/PATENTS.txt */ import {PolymerElement} from '../deps/@polymer/polymer/polymer-element.js'; import {MessengerMixin} from './arcs-shared.js'; import {html} from '../deps/@polymer/polymer/lib/utils/html-tag.js'; import '../deps/golden-layout/src/css/goldenlayout-base.css.js'; import '../deps/golden-layout/src/css/goldenlayout-light-theme.css.js'; import './arcs-overview.js'; import './arcs-stores.js'; import './arcs-planning.js'; import './arcs-communication-channel.js'; import './arcs-environment.js'; import './arcs-notifications.js'; import './arcs-tracing.js'; import './arcs-pec-log.js'; import './arcs-hcr-list.js'; import './arcs-selector.js'; import './strategy-explorer/strategy-explorer.js'; import './arcs-recipe-editor.js'; import './arcs-connection-status.js'; class ArcsDevtoolsApp extends MessengerMixin(PolymerElement) { static get template() { return html` <style include="shared-styles goldenlayout-base.css goldenlayout-light-theme.css"> :host { height: 100vh; display: flex; flex-direction: column; } header { height: 27px; flex-grow: 0; } arcs-notifications:not([visible]) + [divider] { display: none; } #main { position: relative; flex-grow: 1; } /* TODO: Create our own golden-layout theme instead of overriding. */ .lm_content { background: white; position: relative; overflow: auto; } .lm_header .lm_tab { /* Fixing uneven padding caused by missing close button. This can be reverted once we allow closing and re-opening tools. */ padding: 0 10px 4px; } </style> <arcs-communication-channel></arcs-communication-channel> <arcs-connection-status></arcs-connection-status> <header id="header" class="header"> <div section> <arcs-notifications></arcs-notifications><div divider></div> <arcs-selector active-page="[[routeData.page]]"></arcs-selector> </div> </header> <div id="main"></div> `; } static get is() { return 'arcs-devtools-app'; } ready() { super.ready(); const tools = { 'Overview': 'arcs-overview', 'Environment': 'arcs-environment', 'Storage': 'arcs-stores', 'Execution Log': 'arcs-pec-log', 'Strategizer': 'strategy-explorer', 'Planner': 'arcs-planning', 'Tracing': 'arcs-tracing', 'Editor': 'arcs-recipe-editor', 'HCR': 'arcs-hcr-list' }; // TODO: Save user's layout to local storage and restore from it. const layout = new GoldenLayout({ content: [{ type: 'stack', content: Object.entries(tools).map(([name]) => ({ type: 'component', componentName: name, // TODO: Allow closing and then re-opening tools. isClosable: false })) }], settings: { // Pulling a tool into a popup resets its state, // which we cannot recover. showPopoutIcon: false, }, }, this.$.main); for (const [name, elementName] of Object.entries(tools)) { layout.registerComponent(name, function(container) { const element = document.createElement(elementName); container.getElement().append(element); container.on('show', () => element.setAttribute('active', '')); container.on('hide', () => element.removeAttribute('active')); }); } layout.init(); // We need to observe the body for changes as opposed to #main, because when the viewport // shrinks #main will not shrink if it is filled with content, body however will. new ResizeObserver(rects => { const {height, width} = rects[0].contentRect; layout.updateSize(width, height - this.$.header.offsetHeight); }).observe(document.body); } } window.customElements.define(ArcsDevtoolsApp.is, ArcsDevtoolsApp);
PolymerLabs/arcs-live
devtools/src/arcs-devtools-app.js
JavaScript
bsd-3-clause
4,211
import assert from "assert"; import {Point2D, Vector2D, Matrix2D} from "../index.js"; describe("Point2D", () => { it("new point", () => { const p = new Point2D(10, 20); assert.strictEqual(p.x, 10); assert.strictEqual(p.y, 20); }); it("clone", () => { const p = new Point2D(10, 20); const c = p.clone(); assert.strictEqual(p.x, c.x); assert.strictEqual(p.y, c.y); assert.strictEqual(c.x, 10); assert.strictEqual(c.y, 20); }); it("add", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(20, 30); const p3 = p1.add(p2); assert.strictEqual(p3.x, 30); assert.strictEqual(p3.y, 50); }); it("subtract", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(20, 40); const p3 = p1.subtract(p2); assert.strictEqual(p3.x, -10); assert.strictEqual(p3.y, -20); }); it("multiply", () => { const p1 = new Point2D(10, 20); const p2 = p1.multiply(0.5); assert.strictEqual(p2.x, 5); assert.strictEqual(p2.y, 10); }); it("divide", () => { const p1 = new Point2D(10, 20); const p2 = p1.divide(2); assert.strictEqual(p2.x, 5); assert.strictEqual(p2.y, 10); }); it("equal", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(10, 20); assert.strictEqual(p1.equals(p2), true); }); it("not equal", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(10, 21); assert.strictEqual(p1.equals(p2), false); }); it("interpolate between two points", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(30, 40); const p3 = p1.lerp(p2, 0.25); assert.strictEqual(p3.x, 15); assert.strictEqual(p3.y, 25); }); it("distance between two points", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(13, 24); const dist = p1.distanceFrom(p2); assert.strictEqual(dist, 5); }); it("min", () => { const p1 = new Point2D(30, 5); const p2 = new Point2D(10, 50); const p3 = p1.min(p2); assert.strictEqual(p3.x, 10); assert.strictEqual(p3.y, 5); }); it("max", () => { const p1 = new Point2D(30, 5); const p2 = new Point2D(10, 50); const p3 = p1.max(p2); assert.strictEqual(p3.x, 30); assert.strictEqual(p3.y, 50); }); it("translate", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().translate(20, 30); const p2 = p1.transform(m); assert.strictEqual(p2.x, 30); assert.strictEqual(p2.y, 50); }); it("scale", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().scale(2); const p2 = p1.transform(m); assert.strictEqual(p2.x, 20); assert.strictEqual(p2.y, 40); }); it("scale non-uniform", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().scaleNonUniform(2, 3); const p2 = p1.transform(m); assert.strictEqual(p2.x, 20); assert.strictEqual(p2.y, 60); }); it("rotate", () => { const p1 = new Point2D(10, 0); const m = new Matrix2D().rotate(Math.PI / 4.0); const p2 = p1.transform(m); assert.strictEqual(p2.x, 7.0710678118654755); assert.strictEqual(p2.y, 7.071067811865475); }); it("rotate from vector", () => { const p1 = new Point2D(10, 0); const v = new Vector2D(Math.PI / 4.0, Math.PI / 4.0); const m = new Matrix2D().rotateFromVector(v); const p2 = p1.transform(m); assert.strictEqual(p2.x, 7.0710678118654755); assert.strictEqual(p2.y, 7.0710678118654755); }); it("flip x", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().flipX(); const p2 = p1.transform(m); assert.strictEqual(p2.x, -10); assert.strictEqual(p2.y, 20); }); it("flip y", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().flipY(); const p2 = p1.transform(m); assert.strictEqual(p2.x, 10); assert.strictEqual(p2.y, -20); }); it("inverse transform", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().translate(30, 50).inverse(); const p2 = p1.transform(m); assert.strictEqual(p2.x, -20); assert.strictEqual(p2.y, -30); }); it("to string", () => { const p = new Point2D(10, 20); assert.strictEqual("point(10,20)", p.toString()); }); });
lysz210/kld-affine
test/point_tests.js
JavaScript
bsd-3-clause
4,778
;(function ($, window) { "use strict"; /** * @options * @param customClass [string] <''> "Class applied to instance" * @param lables.up [string] <'Up'> "Up arrow label" * @param lables.down [string] <'Down'> "Down arrow label" */ var options = { customClass: "", labels: { up: "Up", down: "Down" } }; var pub = { /** * @method * @name defaults * @description Sets default plugin options * @param opts [object] <{}> "Options object" * @example $.stepper("defaults", opts); */ defaults: function(opts) { options = $.extend(options, opts || {}); return (typeof this === 'object') ? $(this) : true; }, /** * @method * @name destroy * @description Removes instance of plugin * @example $(".target").stepper("destroy"); */ destroy: function() { return $(this).each(function(i) { var data = $(this).data("stepper"); if (data) { // Unbind click events data.$stepper.off(".stepper") .find(".stepper-arrow") .remove(); // Restore DOM data.$input.unwrap() .removeClass("stepper-input"); } }); }, /** * @method * @name disable * @description Disables target instance * @example $(".target").stepper("disable"); */ disable: function() { return $(this).each(function(i) { var data = $(this).data("stepper"); if (data) { data.$input.attr("disabled", "disabled"); data.$stepper.addClass("disabled"); } }); }, /** * @method * @name enable * @description Enables target instance * @example $(".target").stepper("enable"); */ enable: function() { return $(this).each(function(i) { var data = $(this).data("stepper"); if (data) { data.$input.attr("disabled", null); data.$stepper.removeClass("disabled"); } }); } }; /** * @method private * @name _init * @description Initializes plugin * @param opts [object] "Initialization options" */ function _init(opts) { // Local options opts = $.extend({}, options, opts || {}); // Apply to each element var $items = $(this); for (var i = 0, count = $items.length; i < count; i++) { _build($items.eq(i), opts); } return $items; } /** * @method private * @name _build * @description Builds each instance * @param $select [jQuery object] "Target jQuery object" * @param opts [object] <{}> "Options object" */ function _build($input, opts) { if (!$input.hasClass("stepper-input")) { // EXTEND OPTIONS opts = $.extend({}, opts, $input.data("stepper-options")); // HTML5 attributes var min = parseFloat($input.attr("min")), max = parseFloat($input.attr("max")), step = parseFloat($input.attr("step")) || 1; // Modify DOM $input.addClass("stepper-input") .wrap('<div class="stepper ' + opts.customClass + '" />') .after('<span class="stepper-arrow up">' + opts.labels.up + '</span><span class="stepper-arrow down">' + opts.labels.down + '</span>'); // Store data var $stepper = $input.parent(".stepper"), data = $.extend({ $stepper: $stepper, $input: $input, $arrow: $stepper.find(".stepper-arrow"), min: (typeof min !== undefined && !isNaN(min)) ? min : false, max: (typeof max !== undefined && !isNaN(max)) ? max : false, step: (typeof step !== undefined && !isNaN(step)) ? step : 1, timer: null }, opts); data.digits = _digits(data.step); // Check disabled if ($input.is(":disabled")) { $stepper.addClass("disabled"); } // Bind keyboard events $stepper.on("keypress", ".stepper-input", data, _onKeyup); // Bind click events $stepper.on("touchstart.stepper mousedown.stepper", ".stepper-arrow", data, _onMouseDown) .data("stepper", data); } } /** * @method private * @name _onKeyup * @description Handles keypress event on inputs * @param e [object] "Event data" */ function _onKeyup(e) { var data = e.data; // If arrow keys if (e.keyCode === 38 || e.keyCode === 40) { e.preventDefault(); _step(data, (e.keyCode === 38) ? data.step : -data.step); } } /** * @method private * @name _onMouseDown * @description Handles mousedown event on instance arrows * @param e [object] "Event data" */ function _onMouseDown(e) { e.preventDefault(); e.stopPropagation(); // Make sure we reset the states _onMouseUp(e); var data = e.data; if (!data.$input.is(':disabled') && !data.$stepper.hasClass("disabled")) { var change = $(e.target).hasClass("up") ? data.step : -data.step; data.timer = _startTimer(data.timer, 125, function() { _step(data, change, false); }); _step(data, change); $("body").on("touchend.stepper mouseup.stepper", data, _onMouseUp); } } /** * @method private * @name _onMouseUp * @description Handles mouseup event on instance arrows * @param e [object] "Event data" */ function _onMouseUp(e) { e.preventDefault(); e.stopPropagation(); var data = e.data; _clearTimer(data.timer); $("body").off(".stepper"); } /** * @method private * @name _step * @description Steps through values * @param e [object] "Event data" * @param change [string] "Change value" */ function _step(data, change) { var originalValue = parseFloat(data.$input.val()), value = change; if (typeof originalValue === undefined || isNaN(originalValue)) { if (data.min !== false) { value = data.min; } else { value = 0; } } else if (data.min !== false && originalValue < data.min) { value = data.min; } else { value += originalValue; } var diff = (value - data.min) % data.step; if (diff !== 0) { value -= diff; } if (data.min !== false && value < data.min) { value = data.min; } if (data.max !== false && value > data.max) { value -= data.step; } if (value !== originalValue) { value = _round(value, data.digits); data.$input.val(value) .trigger("change"); } } /** * @method private * @name _startTimer * @description Starts an internal timer * @param timer [int] "Timer ID" * @param time [int] "Time until execution" * @param callback [int] "Function to execute" */ function _startTimer(timer, time, callback) { _clearTimer(timer); return setInterval(callback, time); } /** * @method private * @name _clearTimer * @description Clears an internal timer * @param timer [int] "Timer ID" */ function _clearTimer(timer) { if (timer) { clearInterval(timer); timer = null; } } /** * @method private * @name _digits * @description Analyzes and returns significant digit count * @param value [float] "Value to analyze" * @return [int] "Number of significant digits" */ function _digits(value) { var test = String(value); if (test.indexOf(".") > -1) { return test.length - test.indexOf(".") - 1; } else { return 0; } } /** * @method private * @name _round * @description Rounds a number to a sepcific significant digit count * @param value [float] "Value to round" * @param digits [float] "Digits to round to" * @return [number] "Rounded number" */ function _round(value, digits) { var exp = Math.pow(10, digits); return Math.round(value * exp) / exp; } $.fn.stepper = function(method) { if (pub[method]) { return pub[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return _init.apply(this, arguments); } return this; }; $.stepper = function(method) { if (method === "defaults") { pub.defaults.apply(this, Array.prototype.slice.call(arguments, 1)); } }; })(jQuery, this);
juniorspecialist/moab
web/js/jquery.fs.stepper.js
JavaScript
bsd-3-clause
7,683
var React = require('react'); var ReactFeatureFlags = require('ReactFeatureFlags'); var ReactDOM; var AsyncComponent = React.unstable_AsyncComponent; describe('ReactDOMFiberAsync', () => { var container; beforeEach(() => { container = document.createElement('div'); ReactDOM = require('react-dom'); }); it('renders synchronously by default', () => { var ops = []; ReactDOM.render(<div>Hi</div>, container, () => { ops.push(container.textContent); }); ReactDOM.render(<div>Bye</div>, container, () => { ops.push(container.textContent); }); expect(ops).toEqual(['Hi', 'Bye']); }); describe('with feature flag disabled', () => { beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('ReactFeatureFlags'); container = document.createElement('div'); ReactFeatureFlags.enableAsyncSubtreeAPI = false; ReactDOM = require('react-dom'); }); it('renders synchronously', () => { ReactDOM.render( <AsyncComponent><div>Hi</div></AsyncComponent>, container, ); expect(container.textContent).toEqual('Hi'); ReactDOM.render( <AsyncComponent><div>Bye</div></AsyncComponent>, container, ); expect(container.textContent).toEqual('Bye'); }); }); describe('with feature flag enabled', () => { beforeEach(() => { jest.resetModules(); ReactFeatureFlags = require('ReactFeatureFlags'); container = document.createElement('div'); ReactFeatureFlags.enableAsyncSubtreeAPI = true; ReactDOM = require('react-dom'); }); it('AsyncComponent at the root makes the entire tree async', () => { ReactDOM.render( <AsyncComponent><div>Hi</div></AsyncComponent>, container, ); expect(container.textContent).toEqual(''); jest.runAllTimers(); expect(container.textContent).toEqual('Hi'); ReactDOM.render( <AsyncComponent><div>Bye</div></AsyncComponent>, container, ); expect(container.textContent).toEqual('Hi'); jest.runAllTimers(); expect(container.textContent).toEqual('Bye'); }); it('updates inside an async tree are async by default', () => { let instance; class Component extends React.Component { state = {step: 0}; render() { instance = this; return <div>{this.state.step}</div>; } } ReactDOM.render( <AsyncComponent><Component /></AsyncComponent>, container, ); expect(container.textContent).toEqual(''); jest.runAllTimers(); expect(container.textContent).toEqual('0'); instance.setState({step: 1}); expect(container.textContent).toEqual('0'); jest.runAllTimers(); expect(container.textContent).toEqual('1'); }); it('AsyncComponent creates an async subtree', () => { let instance; class Component extends React.unstable_AsyncComponent { state = {step: 0}; render() { instance = this; return <div>{this.state.step}</div>; } } ReactDOM.render(<div><Component /></div>, container); jest.runAllTimers(); instance.setState({step: 1}); expect(container.textContent).toEqual('0'); jest.runAllTimers(); expect(container.textContent).toEqual('1'); }); it('updates inside an async subtree are async by default', () => { class Component extends React.unstable_AsyncComponent { render() { return <Child />; } } let instance; class Child extends React.Component { state = {step: 0}; render() { instance = this; return <div>{this.state.step}</div>; } } ReactDOM.render(<div><Component /></div>, container); jest.runAllTimers(); instance.setState({step: 1}); expect(container.textContent).toEqual('0'); jest.runAllTimers(); expect(container.textContent).toEqual('1'); }); it('flushSync batches sync updates and flushes them at the end of the batch', () => { let ops = []; let instance; class Component extends React.Component { state = {text: ''}; push(val) { this.setState(state => ({text: state.text + val})); } componentDidUpdate() { ops.push(this.state.text); } render() { instance = this; return <span>{this.state.text}</span>; } } ReactDOM.render(<Component />, container); instance.push('A'); expect(ops).toEqual(['A']); expect(container.textContent).toEqual('A'); ReactDOM.flushSync(() => { instance.push('B'); instance.push('C'); // Not flushed yet expect(container.textContent).toEqual('A'); expect(ops).toEqual(['A']); }); expect(container.textContent).toEqual('ABC'); expect(ops).toEqual(['A', 'ABC']); instance.push('D'); expect(container.textContent).toEqual('ABCD'); expect(ops).toEqual(['A', 'ABC', 'ABCD']); }); it('flushSync flushes updates even if nested inside another flushSync', () => { let ops = []; let instance; class Component extends React.Component { state = {text: ''}; push(val) { this.setState(state => ({text: state.text + val})); } componentDidUpdate() { ops.push(this.state.text); } render() { instance = this; return <span>{this.state.text}</span>; } } ReactDOM.render(<Component />, container); instance.push('A'); expect(ops).toEqual(['A']); expect(container.textContent).toEqual('A'); ReactDOM.flushSync(() => { instance.push('B'); instance.push('C'); // Not flushed yet expect(container.textContent).toEqual('A'); expect(ops).toEqual(['A']); ReactDOM.flushSync(() => { instance.push('D'); }); // The nested flushSync caused everything to flush. expect(container.textContent).toEqual('ABCD'); expect(ops).toEqual(['A', 'ABCD']); }); expect(container.textContent).toEqual('ABCD'); expect(ops).toEqual(['A', 'ABCD']); }); it('flushSync throws if already performing work', () => { class Component extends React.Component { componentDidUpdate() { ReactDOM.flushSync(() => {}); } render() { return null; } } // Initial mount ReactDOM.render(<Component />, container); // Update expect(() => ReactDOM.render(<Component />, container)).toThrow( 'flushSync was called from inside a lifecycle method', ); }); it('flushSync flushes updates before end of the tick', () => { let ops = []; let instance; class Component extends React.unstable_AsyncComponent { state = {text: ''}; push(val) { this.setState(state => ({text: state.text + val})); } componentDidUpdate() { ops.push(this.state.text); } render() { instance = this; return <span>{this.state.text}</span>; } } ReactDOM.render(<Component />, container); jest.runAllTimers(); // Updates are async by default instance.push('A'); expect(ops).toEqual([]); expect(container.textContent).toEqual(''); ReactDOM.flushSync(() => { instance.push('B'); instance.push('C'); // Not flushed yet expect(container.textContent).toEqual(''); expect(ops).toEqual([]); }); // Only the active updates have flushed expect(container.textContent).toEqual('BC'); expect(ops).toEqual(['BC']); instance.push('D'); expect(container.textContent).toEqual('BC'); expect(ops).toEqual(['BC']); // Flush the async updates jest.runAllTimers(); expect(container.textContent).toEqual('BCAD'); expect(ops).toEqual(['BC', 'BCAD']); }); }); });
yangshun/react
src/renderers/dom/fiber/__tests__/ReactDOMFiberAsync-test.js
JavaScript
bsd-3-clause
8,185
'use strict'; exports.__esModule = true; const moduleRequire = require('./module-require').default; const extname = require('path').extname; const fs = require('fs'); const log = require('debug')('eslint-plugin-import:parse'); function getBabelEslintVisitorKeys(parserPath) { if (parserPath.endsWith('index.js')) { const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js'); if (fs.existsSync(hypotheticalLocation)) { const keys = moduleRequire(hypotheticalLocation); return keys.default || keys; } } return null; } function keysFromParser(parserPath, parserInstance, parsedResult) { // Exposed by @typescript-eslint/parser and @babel/eslint-parser if (parsedResult && parsedResult.visitorKeys) { return parsedResult.visitorKeys; } if (/.*espree.*/.test(parserPath)) { return parserInstance.VisitorKeys; } if (/.*babel-eslint.*/.test(parserPath)) { return getBabelEslintVisitorKeys(parserPath); } return null; } exports.default = function parse(path, content, context) { if (context == null) throw new Error('need context to parse properly'); let parserOptions = context.parserOptions; const parserPath = getParserPath(path, context); if (!parserPath) throw new Error('parserPath is required!'); // hack: espree blows up with frozen options parserOptions = Object.assign({}, parserOptions); parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures); // always include comments and tokens (for doc parsing) parserOptions.comment = true; parserOptions.attachComment = true; // keeping this for backward-compat with older parsers parserOptions.tokens = true; // attach node locations parserOptions.loc = true; parserOptions.range = true; // provide the `filePath` like eslint itself does, in `parserOptions` // https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637 parserOptions.filePath = path; // @typescript-eslint/parser will parse the entire project with typechecking if you provide // "project" or "projects" in parserOptions. Removing these options means the parser will // only parse one file in isolate mode, which is much, much faster. // https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962 delete parserOptions.project; delete parserOptions.projects; // require the parser relative to the main module (i.e., ESLint) const parser = moduleRequire(parserPath); if (typeof parser.parseForESLint === 'function') { let ast; try { const parserRaw = parser.parseForESLint(content, parserOptions); ast = parserRaw.ast; return { ast, visitorKeys: keysFromParser(parserPath, parser, parserRaw), }; } catch (e) { console.warn(); console.warn('Error while parsing ' + parserOptions.filePath); console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message); } if (!ast || typeof ast !== 'object') { console.warn( '`parseForESLint` from parser `' + parserPath + '` is invalid and will just be ignored' ); } else { return { ast, visitorKeys: keysFromParser(parserPath, parser, undefined), }; } } const keys = keysFromParser(parserPath, parser, undefined); return { ast: parser.parse(content, parserOptions), visitorKeys: keys, }; }; function getParserPath(path, context) { const parsers = context.settings['import/parsers']; if (parsers != null) { const extension = extname(path); for (const parserPath in parsers) { if (parsers[parserPath].indexOf(extension) > -1) { // use this alternate parser log('using alt parser:', parserPath); return parserPath; } } } // default to use ESLint parser return context.parserPath; }
ChromeDevTools/devtools-frontend
node_modules/eslint-module-utils/parse.js
JavaScript
bsd-3-clause
3,870
// Copyright (c) 2013, salesforce.com, 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: // // 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 salesforce.com, inc. 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 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. (function ($$){ var sr, mobile, postType, thumbnailUrl; myPublisher = { init : function(signedRequest, isMobile) { sr = signedRequest; mobile = isMobile; }, // Auto resize the iframe to fit the current content. resize : function() { $$.client.resize(sr.client); }, // Simply display incoming events in order logEvent : function(name) { var elem = $$.byId("events"); var sep = ($$.isNil(elem.value)) ? "" : ","; elem.value += sep + name }, selectPostType : function(e) { console.log("got click", e); postType = e; // Enable the share button $$.client.publish(sr.client, {name : "publisher.setValidForSubmit", payload : true}); }, clearPostTypes : function() { var i, elements = $$.byClass('postType'); for (i = 0; i < elements.length; i+=1) { elements[i].checked=false; } }, canvasOptions : function(elem, option) { var bool = Sfdc.canvas.indexOf(sr.context.application.options, option) == -1; elem.innerHTML = (bool) ? "&#x2713;" : "&#x2717;"; elem.style.color = (bool) ? "green" : "red"; }, updateContent : function() { if (!mobile) { $$.byId('name').innerHTML = sr.context.user.firstName + " " + sr.context.user.lastName; $$.byId('location').innerHTML = sr.context.environment.displayLocation; myPublisher.canvasOptions($$.byId('header-enabled'), "HideHeader"); myPublisher.canvasOptions($$.byId('share-enabled'), "HideShare"); } }, selectThumbnail: function(e) { thumbnailUrl = (e === "none") ? null : window.location.origin + e; console.log("Thumbnail URL " + thumbnailUrl); }, handlers : function() { var handlers = { onSetupPanel : function (payload) { myPublisher.resize(); // Do I want to do this on iphone? myPublisher.logEvent("setupPanel"); }, onShowPanel : function(payload) { myPublisher.logEvent("showPanel"); }, onClearPanelState : function(payload) { myPublisher.logEvent("clearPanelState"); myPublisher.clearPostTypes(); // Clear all the text fields and reset radio buttons }, onSuccess : function() { myPublisher.logEvent("success"); }, onFailure : function (payload) { myPublisher.logEvent("failure"); myPublisher.clearPostTypes(); if (payload && payload.errors && payload.errors.message) { alert("Error: " + payload.errors.message); } }, onGetPayload : function() { myPublisher.logEvent("getPayload"); var p = {}; if (postType === 'Text') { // Example of a Text Post p.feedItemType = "TextPost"; p.auxText = $$.byId('auxText').value; } else if (postType === 'Link') { // Example of a Link Post p.feedItemType = "LinkPost"; p.auxText = $$.byId('auxText').value; p.url = "http://www.salesforce.com"; p.urlName = $$.byId('title').value; } else if (postType === 'Canvas') { // Example of a Canvas Post p.feedItemType = "CanvasPost"; p.auxText = $$.byId('auxText').value; p.namespace = sr.context.application.namespace; p.developerName = sr.context.application.developerName; p.height = $$.byId('height').value; p.title = $$.byId('title').value; p.description = $$.byId('description').value; p.parameters = $$.byId('parameters').value; p.thumbnailUrl = thumbnailUrl; } $$.client.publish(sr.client, {name : 'publisher.setPayload', payload : p}); } }; return { subscriptions : [ {name : 'publisher.setupPanel', onData : handlers.onSetupPanel}, {name : 'publisher.showPanel', onData : handlers.onShowPanel}, {name : 'publisher.clearPanelState', onData : handlers.onClearPanelState}, {name : 'publisher.failure', onData : handlers.onFailure}, {name : 'publisher.success', onData : handlers.onSuccess}, {name : 'publisher.getPayload', onData : handlers.onGetPayload} ] }; } }; }(Sfdc.canvas));
jthurst01/canvas-app-json
src/main/webapp/Publisher/publisher.js
JavaScript
bsd-3-clause
6,834
/** * * <i>Copyright (c) 2017 ItsAsbreuk - http://itsasbreuk.nl</i><br> * New BSD License - http://choosealicense.com/licenses/bsd-3-clause/ * * * @since 16.2.0 */ 'use strict'; const reload = require('require-reload')(require), // see https://github.com/fastest963/require-reload cwd = process.cwd(), generateServiceWorker = require('../..//serviceworker/generate-serviceworker'), OFFLINE_IMAGE = require('../../offline-image'), OFFLINE_PAGE = '/offline/', EXPIRE_ONE_YEAR = 365 * 24 * 60 * 60 * 1000, EXPIRE_TEN_YEARS = 10 * EXPIRE_ONE_YEAR; const generate = async (server, urlsToCache, appConfig, startupTime) => { const prefix = '/build', cwdPrefix = cwd+prefix, serverConnection = server.root, favicon = ((appConfig.cdn && appConfig.cdn.enabled) ? appConfig.cdn.url : cwdPrefix+'/public/') + 'assets/' + appConfig.packageVersion + '/favicon.ico', routes = reload(cwd+'/src/routes.js'); if (appConfig.pageNotFoundView) { server.root.ext('onPreResponse', function(request, reply) { // manage mismatches based upon the `scope`: let response = request.response, splitted, uri, isHtmlPage; if (response.isBoom && response.output && (response.output.statusCode===404)) { // if request to a page, then redirect: splitted = request.url.path.split('?'); uri = splitted[0].toUpperCase(); isHtmlPage = uri.endsWith('.HTML') || uri.endsWith('.HTM') || (uri.lastIndexOf('.')<uri.lastIndexOf('/')); if (isHtmlPage) { return reply.reactview(appConfig.pageNotFoundView); } } return reply.continue(); }); } serverConnection.activateRoutes = function() { var startRouting = setTimeout(function() { console.error('Error: failied to load routes'); }, 5000); try { serverConnection.route(routes); } catch (err) { console.warn(err); } clearTimeout(startRouting); serverConnection.routes = { prefix: prefix }; }; routes.push({ method: 'GET', path: '/favicon.ico', handler: function(request, reply) { if (appConfig.cdn && appConfig.cdn.enabled) { reply().redirect(favicon).permanent().rewritable(); } else { reply.file(favicon); } }, config: { cache: { expiresIn: EXPIRE_ONE_YEAR, privacy: 'private' } } }); // assets created with `require` follow with as deep nested as needed, they also have a version in the url: routes.push({ method: 'GET', path: '/assets/'+appConfig.packageVersion+'/{filename*}', handler: function(request, reply) { // inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same. reply.file(cwdPrefix+'/public/assets/'+appConfig.packageVersion+'/'+request.params.filename); }, config: { cache: { expiresIn: EXPIRE_ONE_YEAR, privacy: 'private' } } }); // assets created with `require` follow with as deep nested as needed, they also have a version in the url: routes.push({ method: 'GET', path: '/assets-private/'+appConfig.packageVersion+'/{filename*}', handler: function(request, reply) { // inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same. reply.file(cwdPrefix+'/private/assets-private/'+appConfig.packageVersion+'/'+request.params.filename); }, config: { cache: { expiresIn: EXPIRE_ONE_YEAR, privacy: 'private' } } }); // external modules, created by webpack routes.push({ method: 'GET', path: '/assets/_itsa_server_external_modules/{versionedmodule*}', handler: function(request, reply) { reply.file(cwdPrefix+'/public/assets/_itsa_server_external_modules/'+request.params.versionedmodule); }, config: { cache: { expiresIn: EXPIRE_TEN_YEARS, privacy: 'private' } } }); routes.push({ method: 'GET', path: '/assets/local/{filename*}', handler: function(request, reply) { // inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same. reply.file(cwdPrefix+'/private/assets/'+request.params.filename); }, config: { cache: { expiresIn: EXPIRE_ONE_YEAR, privacy: 'private' } } }); routes.push({ method: 'GET', path: '/assets/{filename*}', handler: function(request, reply) { // inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same. reply.file(cwdPrefix+'/public/assets/'+appConfig.packageVersion+'/'+request.params.filename); }, config: { cache: { expiresIn: EXPIRE_ONE_YEAR, privacy: 'private' } } }); routes.push({ method: 'GET', path: '/_itsa_server_serviceworker.js', handler: function(request, reply) { if (appConfig['service-workers'] && appConfig['service-workers'].enabled) { // inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same. generateServiceWorker.generateFile(startupTime, urlsToCache, OFFLINE_IMAGE, OFFLINE_PAGE, appConfig.socketPort || 4002, (appConfig.cdn && appConfig.cdn.enabled) ? appConfig.cdn.url : null) .then(fileContent => reply(fileContent).type('application/javascript; charset=utf-8').header('Cache-Control', 'no-cache, no-store, must-revalidate')) .catch(err => { console.warn(err); reply(err); }); } else { reply('').type('application/javascript; charset=utf-8').header('Cache-Control', 'no-cache, no-store, must-revalidate'); } } }); serverConnection.activateRoutes(); }; module.exports = { generate };
ItsAsbreuk/itsa-react-server
lib/hapi-plugin/helpers/apply-server-routes.js
JavaScript
bsd-3-clause
6,635
var webpackConfig = require('./webpack.local.config.js'); webpackConfig.entry = {}; module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha'], // list of files / patterns to load in the browser files: [ '../js/src/test_index.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { '../js/src/test_index.js': ['webpack', 'sourcemap'], }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, autoWatchBatchDelay: 300, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, // Webpack webpack: webpackConfig, webpackServer: { noInfo: true } }); };
genomics-geek/cookiecutter-django-reactjs
{{cookiecutter.project_slug}}/frontend/webpack/karma.config.js
JavaScript
bsd-3-clause
1,857
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u2d5c\u2d49\u2d3c\u2d30\u2d61\u2d5c", "\u2d5c\u2d30\u2d37\u2d33\u2d33\u2d6f\u2d30\u2d5c" ], "DAY": [ "\u2d30\u2d59\u2d30\u2d4e\u2d30\u2d59", "\u2d30\u2d62\u2d4f\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d4f\u2d30\u2d59", "\u2d30\u2d3d\u2d55\u2d30\u2d59", "\u2d30\u2d3d\u2d61\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d4e\u2d61\u2d30\u2d59", "\u2d30\u2d59\u2d49\u2d39\u2d62\u2d30\u2d59" ], "ERANAMES": [ "\u2d37\u2d30\u2d5c \u2d4f \u2d44\u2d49\u2d59\u2d30", "\u2d37\u2d3c\u2d3c\u2d49\u2d54 \u2d4f \u2d44\u2d49\u2d59\u2d30" ], "ERAS": [ "\u2d37\u2d30\u2d44", "\u2d37\u2d3c\u2d44" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54", "\u2d31\u2d55\u2d30\u2d62\u2d55", "\u2d4e\u2d30\u2d55\u2d5a", "\u2d49\u2d31\u2d54\u2d49\u2d54", "\u2d4e\u2d30\u2d62\u2d62\u2d53", "\u2d62\u2d53\u2d4f\u2d62\u2d53", "\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63", "\u2d56\u2d53\u2d5b\u2d5c", "\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d3d\u2d5c\u2d53\u2d31\u2d54", "\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54" ], "SHORTDAY": [ "\u2d30\u2d59\u2d30", "\u2d30\u2d62\u2d4f", "\u2d30\u2d59\u2d49", "\u2d30\u2d3d\u2d55", "\u2d30\u2d3d\u2d61", "\u2d30\u2d59\u2d49\u2d4e", "\u2d30\u2d59\u2d49\u2d39" ], "SHORTMONTH": [ "\u2d49\u2d4f\u2d4f", "\u2d31\u2d55\u2d30", "\u2d4e\u2d30\u2d55", "\u2d49\u2d31\u2d54", "\u2d4e\u2d30\u2d62", "\u2d62\u2d53\u2d4f", "\u2d62\u2d53\u2d4d", "\u2d56\u2d53\u2d5b", "\u2d5b\u2d53\u2d5c", "\u2d3d\u2d5c\u2d53", "\u2d4f\u2d53\u2d61", "\u2d37\u2d53\u2d4a" ], "STANDALONEMONTH": [ "\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54", "\u2d31\u2d55\u2d30\u2d62\u2d55", "\u2d4e\u2d30\u2d55\u2d5a", "\u2d49\u2d31\u2d54\u2d49\u2d54", "\u2d4e\u2d30\u2d62\u2d62\u2d53", "\u2d62\u2d53\u2d4f\u2d62\u2d53", "\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63", "\u2d56\u2d53\u2d5b\u2d5c", "\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d3d\u2d5c\u2d53\u2d31\u2d54", "\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54", "\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM, y HH:mm:ss", "mediumDate": "d MMM, y", "mediumTime": "HH:mm:ss", "short": "d/M/y HH:mm", "shortDate": "d/M/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "dh", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a4", "posPre": "", "posSuf": "\u00a4" } ] }, "id": "zgh-ma", "localeID": "zgh_MA", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
mudunuriRaju/tlr-live
tollbackend/web/js/angular-1.5.5/i18n/angular-locale_zgh-ma.js
JavaScript
bsd-3-clause
5,388
export async function getNodeSummary(nodeId, nodeType) { const bioentityUrl = `${biolink}bioentity/${nodeType}/${nodeId}`; console.log('getNodeSummary bioentityUrl', nodeId, nodeType, bioentityUrl); const params = { fetch_objects: true, unselect_evidence: false, exclude_automatic_assertions: false, use_compact_associations: false, rows: 100, }; const resp = await axios.get(bioentityUrl, { params }); const responseData = resp.data; const graphUrl = `${biolink}graph/node/${nodeId}`; const graphResponse = await axios.get(graphUrl); const graphResponseData = graphResponse.data; responseData.edges = graphResponseData.edges; responseData.nodes = graphResponseData.nodes; return responseData; }
kshefchek/monarch-app
ui/monarchAccess/demo.js
JavaScript
bsd-3-clause
745
// Copyright (c) 2012 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 Offline message screen implementation. */ login.createScreen('ErrorMessageScreen', 'error-message', function() { // Link which starts guest session for captive portal fixing. /** @const */ var FIX_CAPTIVE_PORTAL_ID = 'captive-portal-fix-link'; /** @const */ var FIX_PROXY_SETTINGS_ID = 'proxy-settings-fix-link'; // Id of the element which holds current network name. /** @const */ var CURRENT_NETWORK_NAME_ID = 'captive-portal-network-name'; // Link which triggers frame reload. /** @const */ var RELOAD_PAGE_ID = 'proxy-error-signin-retry-link'; // Array of the possible UI states of the screen. Must be in the // same order as ErrorScreen::UIState enum values. /** @const */ var UI_STATES = [ ERROR_SCREEN_UI_STATE.UNKNOWN, ERROR_SCREEN_UI_STATE.UPDATE, ERROR_SCREEN_UI_STATE.SIGNIN, ERROR_SCREEN_UI_STATE.MANAGED_USER_CREATION_FLOW, ERROR_SCREEN_UI_STATE.KIOSK_MODE, ERROR_SCREEN_UI_STATE.LOCAL_STATE_ERROR ]; // Possible error states of the screen. /** @const */ var ERROR_STATE = { UNKNOWN: 'error-state-unknown', PORTAL: 'error-state-portal', OFFLINE: 'error-state-offline', PROXY: 'error-state-proxy', AUTH_EXT_TIMEOUT: 'error-state-auth-ext-timeout' }; // Possible error states of the screen. Must be in the same order as // ErrorScreen::ErrorState enum values. /** @const */ var ERROR_STATES = [ ERROR_STATE.UNKNOWN, ERROR_STATE.PORTAL, ERROR_STATE.OFFLINE, ERROR_STATE.PROXY, ERROR_STATE.AUTH_EXT_TIMEOUT ]; return { EXTERNAL_API: [ 'updateLocalizedContent', 'onBeforeShow', 'onBeforeHide', 'allowGuestSignin', 'allowOfflineLogin', 'setUIState', 'setErrorState' ], // Error screen initial UI state. ui_state_: ERROR_SCREEN_UI_STATE.UNKNOWN, // Error screen initial error state. error_state_: ERROR_STATE.UNKNOWN, /** @override */ decorate: function() { cr.ui.DropDown.decorate($('offline-networks-list')); this.updateLocalizedContent(); }, /** * Updates localized content of the screen that is not updated via template. */ updateLocalizedContent: function() { $('captive-portal-message-text').innerHTML = loadTimeData.getStringF( 'captivePortalMessage', '<b id="' + CURRENT_NETWORK_NAME_ID + '"></b>', '<a id="' + FIX_CAPTIVE_PORTAL_ID + '" class="signin-link" href="#">', '</a>'); $(FIX_CAPTIVE_PORTAL_ID).onclick = function() { chrome.send('showCaptivePortal'); }; $('captive-portal-proxy-message-text').innerHTML = loadTimeData.getStringF( 'captivePortalProxyMessage', '<a id="' + FIX_PROXY_SETTINGS_ID + '" class="signin-link" href="#">', '</a>'); $(FIX_PROXY_SETTINGS_ID).onclick = function() { chrome.send('openProxySettings'); }; $('update-proxy-message-text').innerHTML = loadTimeData.getStringF( 'updateProxyMessageText', '<a id="update-proxy-error-fix-proxy" class="signin-link" href="#">', '</a>'); $('update-proxy-error-fix-proxy').onclick = function() { chrome.send('openProxySettings'); }; $('signin-proxy-message-text').innerHTML = loadTimeData.getStringF( 'signinProxyMessageText', '<a id="' + RELOAD_PAGE_ID + '" class="signin-link" href="#">', '</a>', '<a id="signin-proxy-error-fix-proxy" class="signin-link" href="#">', '</a>'); $(RELOAD_PAGE_ID).onclick = function() { var gaiaScreen = $(SCREEN_GAIA_SIGNIN); // Schedules an immediate retry. gaiaScreen.doReload(); }; $('signin-proxy-error-fix-proxy').onclick = function() { chrome.send('openProxySettings'); }; $('error-guest-signin').innerHTML = loadTimeData.getStringF( 'guestSignin', '<a id="error-guest-signin-link" class="signin-link" href="#">', '</a>'); $('error-guest-signin-link').onclick = function() { chrome.send('launchIncognito'); }; $('error-offline-login').innerHTML = loadTimeData.getStringF( 'offlineLogin', '<a id="error-offline-login-link" class="signin-link" href="#">', '</a>'); $('error-offline-login-link').onclick = function() { chrome.send('offlineLogin'); }; this.onContentChange_(); }, /** * Event handler that is invoked just before the screen in shown. * @param {Object} data Screen init payload. */ onBeforeShow: function(data) { cr.ui.Oobe.clearErrors(); cr.ui.DropDown.show('offline-networks-list', false); if (data === undefined) return; if ('uiState' in data) this.setUIState(data['uiState']); if ('errorState' in data && 'network' in data) this.setErrorState(data['errorState'], data['network']); if ('guestSigninAllowed' in data) this.allowGuestSignin(data['guestSigninAllowed']); if ('offlineLoginAllowed' in data) this.allowOfflineLogin(data['offlineLoginAllowed']); }, /** * Event handler that is invoked just before the screen is hidden. */ onBeforeHide: function() { cr.ui.DropDown.hide('offline-networks-list'); }, /** * Buttons in oobe wizard's button strip. * @type {array} Array of Buttons. */ get buttons() { var buttons = []; var powerwashButton = this.ownerDocument.createElement('button'); powerwashButton.id = 'error-message-restart-and-powerwash-button'; powerwashButton.textContent = loadTimeData.getString('localStateErrorPowerwashButton'); powerwashButton.classList.add('show-with-ui-state-local-state-error'); powerwashButton.addEventListener('click', function(e) { chrome.send('localStateErrorPowerwashButtonClicked'); e.stopPropagation(); }); buttons.push(powerwashButton); return buttons; }, /** * Sets current UI state of the screen. * @param {string} ui_state New UI state of the screen. * @private */ setUIState_: function(ui_state) { this.classList.remove(this.ui_state); this.ui_state = ui_state; this.classList.add(this.ui_state); if (ui_state == ERROR_SCREEN_UI_STATE.LOCAL_STATE_ERROR) { // Hide header bar and progress dots, because there are no way // from the error screen about broken local state. Oobe.getInstance().headerHidden = true; $('progress-dots').hidden = true; } this.onContentChange_(); }, /** * Sets current error state of the screen. * @param {string} error_state New error state of the screen. * @param {string} network Name of the current network * @private */ setErrorState_: function(error_state, network) { this.classList.remove(this.error_state); $(CURRENT_NETWORK_NAME_ID).textContent = network; this.error_state = error_state; this.classList.add(this.error_state); this.onContentChange_(); }, /* Method called after content of the screen changed. * @private */ onContentChange_: function() { if (Oobe.getInstance().currentScreen === this) Oobe.getInstance().updateScreenSize(this); }, /** * Prepares error screen to show guest signin link. * @private */ allowGuestSignin: function(allowed) { this.classList.toggle('allow-guest-signin', allowed); this.onContentChange_(); }, /** * Prepares error screen to show offline login link. * @private */ allowOfflineLogin: function(allowed) { this.classList.toggle('allow-offline-login', allowed); this.onContentChange_(); }, /** * Sets current UI state of the screen. * @param {number} ui_state New UI state of the screen. * @private */ setUIState: function(ui_state) { this.setUIState_(UI_STATES[ui_state]); }, /** * Sets current error state of the screen. * @param {number} error_state New error state of the screen. * @param {string} network Name of the current network * @private */ setErrorState: function(error_state, network) { this.setErrorState_(ERROR_STATES[error_state], network); } }; });
cvsuser-chromium/chromium
chrome/browser/resources/chromeos/login/screen_error_message.js
JavaScript
bsd-3-clause
8,584
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ (function() { var imageDialog = function( editor, dialogType ) { // Load image preview. var IMAGE = 1, LINK = 2, PREVIEW = 4, CLEANUP = 8, regexGetSize = /^\s*(\d+)((px)|\%)?\s*$/i, regexGetSizeOrEmpty = /(^\s*(\d+)((px)|\%)?\s*$)|^$/i, pxLengthRegex = /^\d+px$/; var onSizeChange = function() { var value = this.getValue(), // This = input element. dialog = this.getDialog(), aMatch = value.match( regexGetSize ); // Check value if ( aMatch ) { if ( aMatch[2] == '%' ) // % is allowed - > unlock ratio. switchLockRatio( dialog, false ); // Unlock. value = aMatch[1]; } // Only if ratio is locked if ( dialog.lockRatio ) { var oImageOriginal = dialog.originalElement; if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) { if ( this.id == 'txtHeight' ) { if ( value && value != '0' ) value = Math.round( oImageOriginal.$.width * ( value / oImageOriginal.$.height ) ); if ( !isNaN( value ) ) dialog.setValueOf( 'info', 'txtWidth', value ); } else //this.id = txtWidth. { if ( value && value != '0' ) value = Math.round( oImageOriginal.$.height * ( value / oImageOriginal.$.width ) ); if ( !isNaN( value ) ) dialog.setValueOf( 'info', 'txtHeight', value ); } } } updatePreview( dialog ); }; var updatePreview = function( dialog ) { //Don't load before onShow. if ( !dialog.originalElement || !dialog.preview ) return 1; // Read attributes and update imagePreview; dialog.commitContent( PREVIEW, dialog.preview ); return 0; }; // Custom commit dialog logic, where we're intended to give inline style // field (txtdlgGenStyle) higher priority to avoid overwriting styles contribute // by other fields. function commitContent() { var args = arguments; var inlineStyleField = this.getContentElement( 'advanced', 'txtdlgGenStyle' ); inlineStyleField && inlineStyleField.commit.apply( inlineStyleField, args ); this.foreach( function( widget ) { if ( widget.commit && widget.id != 'txtdlgGenStyle' ) widget.commit.apply( widget, args ); }); } // Avoid recursions. var incommit; // Synchronous field values to other impacted fields is required, e.g. border // size change should alter inline-style text as well. function commitInternally( targetFields ) { if ( incommit ) return; incommit = 1; var dialog = this.getDialog(), element = dialog.imageElement; if ( element ) { // Commit this field and broadcast to target fields. this.commit( IMAGE, element ); targetFields = [].concat( targetFields ); var length = targetFields.length, field; for ( var i = 0; i < length; i++ ) { field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) ); // May cause recursion. field && field.setup( IMAGE, element ); } } incommit = 0; } var switchLockRatio = function( dialog, value ) { var oImageOriginal = dialog.originalElement; // Dialog may already closed. (#5505) if( !oImageOriginal ) return null; var ratioButton = CKEDITOR.document.getById( btnLockSizesId ); if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) { if ( value == 'check' ) // Check image ratio and original image ratio. { var width = dialog.getValueOf( 'info', 'txtWidth' ), height = dialog.getValueOf( 'info', 'txtHeight' ), originalRatio = oImageOriginal.$.width * 1000 / oImageOriginal.$.height, thisRatio = width * 1000 / height; dialog.lockRatio = false; // Default: unlock ratio if ( !width && !height ) dialog.lockRatio = true; else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) ) { if ( Math.round( originalRatio ) == Math.round( thisRatio ) ) dialog.lockRatio = true; } } else if ( value != undefined ) dialog.lockRatio = value; else dialog.lockRatio = !dialog.lockRatio; } else if ( value != 'check' ) // I can't lock ratio if ratio is unknown. dialog.lockRatio = false; if ( dialog.lockRatio ) ratioButton.removeClass( 'cke_btn_unlocked' ); else ratioButton.addClass( 'cke_btn_unlocked' ); var lang = dialog._.editor.lang.image, label = lang[ dialog.lockRatio ? 'unlockRatio' : 'lockRatio' ]; ratioButton.setAttribute( 'title', label ); ratioButton.getFirst().setText( label ); return dialog.lockRatio; }; var resetSize = function( dialog ) { var oImageOriginal = dialog.originalElement; if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) { dialog.setValueOf( 'info', 'txtWidth', oImageOriginal.$.width ); dialog.setValueOf( 'info', 'txtHeight', oImageOriginal.$.height ); } updatePreview( dialog ); }; var setupDimension = function( type, element ) { if ( type != IMAGE ) return; function checkDimension( size, defaultValue ) { var aMatch = size.match( regexGetSize ); if ( aMatch ) { if ( aMatch[2] == '%' ) // % is allowed. { aMatch[1] += '%'; switchLockRatio( dialog, false ); // Unlock ratio } return aMatch[1]; } return defaultValue; } var dialog = this.getDialog(), value = '', dimension = (( this.id == 'txtWidth' )? 'width' : 'height' ), size = element.getAttribute( dimension ); if ( size ) value = checkDimension( size, value ); value = checkDimension( element.getStyle( dimension ), value ); this.setValue( value ); }; var previewPreloader; var onImgLoadEvent = function() { // Image is ready. var original = this.originalElement; original.setCustomData( 'isReady', 'true' ); original.removeListener( 'load', onImgLoadEvent ); original.removeListener( 'error', onImgLoadErrorEvent ); original.removeListener( 'abort', onImgLoadErrorEvent ); // Hide loader CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' ); // New image -> new domensions if ( !this.dontResetSize ) resetSize( this ); if ( this.firstLoad ) CKEDITOR.tools.setTimeout( function(){ switchLockRatio( this, 'check' ); }, 0, this ); this.firstLoad = false; this.dontResetSize = false; }; var onImgLoadErrorEvent = function() { // Error. Image is not loaded. var original = this.originalElement; original.removeListener( 'load', onImgLoadEvent ); original.removeListener( 'error', onImgLoadErrorEvent ); original.removeListener( 'abort', onImgLoadErrorEvent ); // Set Error image. var noimage = CKEDITOR.getUrl( editor.skinPath + 'images/noimage.png' ); if ( this.preview ) this.preview.setAttribute( 'src', noimage ); // Hide loader CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' ); switchLockRatio( this, false ); // Unlock. }; var numbering = function( id ) { return CKEDITOR.tools.getNextId() + '_' + id; }, btnLockSizesId = numbering( 'btnLockSizes' ), btnResetSizeId = numbering( 'btnResetSize' ), imagePreviewLoaderId = numbering( 'ImagePreviewLoader' ), imagePreviewBoxId = numbering( 'ImagePreviewBox' ), previewLinkId = numbering( 'previewLink' ), previewImageId = numbering( 'previewImage' ); return { title : editor.lang.image[ dialogType == 'image' ? 'title' : 'titleButton' ], minWidth : 420, minHeight : 360, onShow : function() { this.imageElement = false; this.linkElement = false; // Default: create a new element. this.imageEditMode = false; this.linkEditMode = false; this.lockRatio = true; this.dontResetSize = false; this.firstLoad = true; this.addLink = false; var editor = this.getParentEditor(), sel = this.getParentEditor().getSelection(), element = sel.getSelectedElement(), link = element && element.getAscendant( 'a' ); //Hide loader. CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' ); // Create the preview before setup the dialog contents. previewPreloader = new CKEDITOR.dom.element( 'img', editor.document ); this.preview = CKEDITOR.document.getById( previewImageId ); // Copy of the image this.originalElement = editor.document.createElement( 'img' ); this.originalElement.setAttribute( 'alt', '' ); this.originalElement.setCustomData( 'isReady', 'false' ); if ( link ) { this.linkElement = link; this.linkEditMode = true; // Look for Image element. var linkChildren = link.getChildren(); if ( linkChildren.count() == 1 ) // 1 child. { var childTagName = linkChildren.getItem( 0 ).getName(); if ( childTagName == 'img' || childTagName == 'input' ) { this.imageElement = linkChildren.getItem( 0 ); if ( this.imageElement.getName() == 'img' ) this.imageEditMode = 'img'; else if ( this.imageElement.getName() == 'input' ) this.imageEditMode = 'input'; } } // Fill out all fields. if ( dialogType == 'image' ) this.setupContent( LINK, link ); } if ( element && element.getName() == 'img' && !element.data( 'cke-realelement' ) || element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'image' ) { this.imageEditMode = element.getName(); this.imageElement = element; } if ( this.imageEditMode ) { // Use the original element as a buffer from since we don't want // temporary changes to be committed, e.g. if the dialog is canceled. this.cleanImageElement = this.imageElement; this.imageElement = this.cleanImageElement.clone( true, true ); // Fill out all fields. this.setupContent( IMAGE, this.imageElement ); // Refresh LockRatio button switchLockRatio ( this, true ); } else this.imageElement = editor.document.createElement( 'img' ); // Dont show preview if no URL given. if ( !CKEDITOR.tools.trim( this.getValueOf( 'info', 'txtUrl' ) ) ) { this.preview.removeAttribute( 'src' ); this.preview.setStyle( 'display', 'none' ); } }, onOk : function() { // Edit existing Image. if ( this.imageEditMode ) { var imgTagName = this.imageEditMode; // Image dialog and Input element. if ( dialogType == 'image' && imgTagName == 'input' && confirm( editor.lang.image.button2Img ) ) { // Replace INPUT-> IMG imgTagName = 'img'; this.imageElement = editor.document.createElement( 'img' ); this.imageElement.setAttribute( 'alt', '' ); editor.insertElement( this.imageElement ); } // ImageButton dialog and Image element. else if ( dialogType != 'image' && imgTagName == 'img' && confirm( editor.lang.image.img2Button )) { // Replace IMG -> INPUT imgTagName = 'input'; this.imageElement = editor.document.createElement( 'input' ); this.imageElement.setAttributes( { type : 'image', alt : '' } ); editor.insertElement( this.imageElement ); } else { // Restore the original element before all commits. this.imageElement = this.cleanImageElement; delete this.cleanImageElement; } } else // Create a new image. { // Image dialog -> create IMG element. if ( dialogType == 'image' ) this.imageElement = editor.document.createElement( 'img' ); else { this.imageElement = editor.document.createElement( 'input' ); this.imageElement.setAttribute ( 'type' ,'image' ); } this.imageElement.setAttribute( 'alt', '' ); } // Create a new link. if ( !this.linkEditMode ) this.linkElement = editor.document.createElement( 'a' ); // Set attributes. this.commitContent( IMAGE, this.imageElement ); this.commitContent( LINK, this.linkElement ); // Remove empty style attribute. if ( !this.imageElement.getAttribute( 'style' ) ) this.imageElement.removeAttribute( 'style' ); // Insert a new Image. if ( !this.imageEditMode ) { if ( this.addLink ) { //Insert a new Link. if ( !this.linkEditMode ) { editor.insertElement(this.linkElement); this.linkElement.append(this.imageElement, false); } else //Link already exists, image not. editor.insertElement(this.imageElement ); } else editor.insertElement( this.imageElement ); } else // Image already exists. { //Add a new link element. if ( !this.linkEditMode && this.addLink ) { editor.insertElement( this.linkElement ); this.imageElement.appendTo( this.linkElement ); } //Remove Link, Image exists. else if ( this.linkEditMode && !this.addLink ) { editor.getSelection().selectElement( this.linkElement ); editor.insertElement( this.imageElement ); } } }, onLoad : function() { if ( dialogType != 'image' ) this.hidePage( 'Link' ); //Hide Link tab. var doc = this._.element.getDocument(); this.addFocusable( doc.getById( btnResetSizeId ), 5 ); this.addFocusable( doc.getById( btnLockSizesId ), 5 ); this.commitContent = commitContent; }, onHide : function() { if ( this.preview ) this.commitContent( CLEANUP, this.preview ); if ( this.originalElement ) { this.originalElement.removeListener( 'load', onImgLoadEvent ); this.originalElement.removeListener( 'error', onImgLoadErrorEvent ); this.originalElement.removeListener( 'abort', onImgLoadErrorEvent ); this.originalElement.remove(); this.originalElement = false; // Dialog is closed. } delete this.imageElement; }, contents : [ { id : 'info', label : editor.lang.image.infoTab, accessKey : 'I', elements : [ { type : 'vbox', padding : 0, children : [ { type : 'hbox', widths : [ '280px', '110px' ], align : 'right', children : [ { id : 'txtUrl', type : 'text', label : editor.lang.common.url, required: true, onChange : function() { var dialog = this.getDialog(), newUrl = this.getValue(); //Update original image if ( newUrl.length > 0 ) //Prevent from load before onShow { dialog = this.getDialog(); var original = dialog.originalElement; dialog.preview.removeStyle( 'display' ); original.setCustomData( 'isReady', 'false' ); // Show loader var loader = CKEDITOR.document.getById( imagePreviewLoaderId ); if ( loader ) loader.setStyle( 'display', '' ); original.on( 'load', onImgLoadEvent, dialog ); original.on( 'error', onImgLoadErrorEvent, dialog ); original.on( 'abort', onImgLoadErrorEvent, dialog ); original.setAttribute( 'src', newUrl ); // Query the preloader to figure out the url impacted by based href. previewPreloader.setAttribute( 'src', newUrl ); dialog.preview.setAttribute( 'src', previewPreloader.$.src ); updatePreview( dialog ); } // Dont show preview if no URL given. else if ( dialog.preview ) { dialog.preview.removeAttribute( 'src' ); dialog.preview.setStyle( 'display', 'none' ); } }, setup : function( type, element ) { if ( type == IMAGE ) { var url = element.data( 'cke-saved-src' ) || element.getAttribute( 'src' ); var field = this; this.getDialog().dontResetSize = true; field.setValue( url ); // And call this.onChange() // Manually set the initial value.(#4191) field.setInitValue(); } }, commit : function( type, element ) { if ( type == IMAGE && ( this.getValue() || this.isChanged() ) ) { element.data( 'cke-saved-src', this.getValue() ); element.setAttribute( 'src', this.getValue() ); } else if ( type == CLEANUP ) { element.setAttribute( 'src', '' ); // If removeAttribute doesn't work. element.removeAttribute( 'src' ); } }, validate : CKEDITOR.dialog.validate.notEmpty( editor.lang.image.urlMissing ) }, { type : 'button', id : 'browse', // v-align with the 'txtUrl' field. // TODO: We need something better than a fixed size here. style : 'display:inline-block;margin-top:10px;', align : 'center', label : editor.lang.common.browseServer, hidden : true, filebrowser : 'info:txtUrl' } ] } ] }, { id : 'txtAlt', type : 'text', label : editor.lang.image.alt, accessKey : 'T', 'default' : '', onChange : function() { updatePreview( this.getDialog() ); }, setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'alt' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'alt', this.getValue() ); } else if ( type == PREVIEW ) { element.setAttribute( 'alt', this.getValue() ); } else if ( type == CLEANUP ) { element.removeAttribute( 'alt' ); } } }, { type : 'hbox', children : [ { type : 'vbox', children : [ { type : 'hbox', widths : [ '50%', '50%' ], children : [ { type : 'vbox', padding : 1, children : [ { type : 'text', width: '40px', id : 'txtWidth', label : editor.lang.common.width, onKeyUp : onSizeChange, onChange : function() { commitInternally.call( this, 'advanced:txtdlgGenStyle' ); }, validate : function() { var aMatch = this.getValue().match( regexGetSizeOrEmpty ); if ( !aMatch ) alert( editor.lang.common.invalidWidth ); return !!aMatch; }, setup : setupDimension, commit : function( type, element, internalCommit ) { var value = this.getValue(); if ( type == IMAGE ) { if ( value ) element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) ); else if ( !value && this.isChanged( ) ) element.removeStyle( 'width' ); !internalCommit && element.removeAttribute( 'width' ); } else if ( type == PREVIEW ) { var aMatch = value.match( regexGetSize ); if ( !aMatch ) { var oImageOriginal = this.getDialog().originalElement; if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) element.setStyle( 'width', oImageOriginal.$.width + 'px'); } else element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) ); } else if ( type == CLEANUP ) { element.removeAttribute( 'width' ); element.removeStyle( 'width' ); } } }, { type : 'text', id : 'txtHeight', width: '40px', label : editor.lang.common.height, onKeyUp : onSizeChange, onChange : function() { commitInternally.call( this, 'advanced:txtdlgGenStyle' ); }, validate : function() { var aMatch = this.getValue().match( regexGetSizeOrEmpty ); if ( !aMatch ) alert( editor.lang.common.invalidHeight ); return !!aMatch; }, setup : setupDimension, commit : function( type, element, internalCommit ) { var value = this.getValue(); if ( type == IMAGE ) { if ( value ) element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) ); else if ( !value && this.isChanged( ) ) element.removeStyle( 'height' ); if ( !internalCommit && type == IMAGE ) element.removeAttribute( 'height' ); } else if ( type == PREVIEW ) { var aMatch = value.match( regexGetSize ); if ( !aMatch ) { var oImageOriginal = this.getDialog().originalElement; if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' ) element.setStyle( 'height', oImageOriginal.$.height + 'px' ); } else element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) ); } else if ( type == CLEANUP ) { element.removeAttribute( 'height' ); element.removeStyle( 'height' ); } } } ] }, { type : 'html', style : 'margin-top:30px;width:40px;height:40px;', onLoad : function() { // Activate Reset button var resetButton = CKEDITOR.document.getById( btnResetSizeId ), ratioButton = CKEDITOR.document.getById( btnLockSizesId ); if ( resetButton ) { resetButton.on( 'click', function(evt) { resetSize( this ); evt.data.preventDefault(); }, this.getDialog() ); resetButton.on( 'mouseover', function() { this.addClass( 'cke_btn_over' ); }, resetButton ); resetButton.on( 'mouseout', function() { this.removeClass( 'cke_btn_over' ); }, resetButton ); } // Activate (Un)LockRatio button if ( ratioButton ) { ratioButton.on( 'click', function(evt) { var locked = switchLockRatio( this ), oImageOriginal = this.originalElement, width = this.getValueOf( 'info', 'txtWidth' ); if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' && width ) { var height = oImageOriginal.$.height / oImageOriginal.$.width * width; if ( !isNaN( height ) ) { this.setValueOf( 'info', 'txtHeight', Math.round( height ) ); updatePreview( this ); } } evt.data.preventDefault(); }, this.getDialog() ); ratioButton.on( 'mouseover', function() { this.addClass( 'cke_btn_over' ); }, ratioButton ); ratioButton.on( 'mouseout', function() { this.removeClass( 'cke_btn_over' ); }, ratioButton ); } }, html : '<div>'+ '<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.unlockRatio + '" class="cke_btn_locked" id="' + btnLockSizesId + '" role="button"><span class="cke_label">' + editor.lang.image.unlockRatio + '</span></a>' + '<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.resetSize + '" class="cke_btn_reset" id="' + btnResetSizeId + '" role="button"><span class="cke_label">' + editor.lang.image.resetSize + '</span></a>'+ '</div>' } ] }, { type : 'vbox', padding : 1, children : [ { type : 'text', id : 'txtBorder', width: '60px', label : editor.lang.image.border, 'default' : '', onKeyUp : function() { updatePreview( this.getDialog() ); }, onChange : function() { commitInternally.call( this, 'advanced:txtdlgGenStyle' ); }, validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateBorder ), setup : function( type, element ) { if ( type == IMAGE ) { var value, borderStyle = element.getStyle( 'border-width' ); borderStyle = borderStyle && borderStyle.match( /^(\d+px)(?: \1 \1 \1)?$/ ); value = borderStyle && parseInt( borderStyle[ 1 ], 10 ); isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'border' ) ); this.setValue( value ); } }, commit : function( type, element, internalCommit ) { var value = parseInt( this.getValue(), 10 ); if ( type == IMAGE || type == PREVIEW ) { if ( !isNaN( value ) ) { element.setStyle( 'border-width', CKEDITOR.tools.cssLength( value ) ); element.setStyle( 'border-style', 'solid' ); } else if ( !value && this.isChanged() ) { element.removeStyle( 'border-width' ); element.removeStyle( 'border-style' ); element.removeStyle( 'border-color' ); } if ( !internalCommit && type == IMAGE ) element.removeAttribute( 'border' ); } else if ( type == CLEANUP ) { element.removeAttribute( 'border' ); element.removeStyle( 'border-width' ); element.removeStyle( 'border-style' ); element.removeStyle( 'border-color' ); } } }, { type : 'text', id : 'txtHSpace', width: '60px', label : editor.lang.image.hSpace, 'default' : '', onKeyUp : function() { updatePreview( this.getDialog() ); }, onChange : function() { commitInternally.call( this, 'advanced:txtdlgGenStyle' ); }, validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateHSpace ), setup : function( type, element ) { if ( type == IMAGE ) { var value, marginLeftPx, marginRightPx, marginLeftStyle = element.getStyle( 'margin-left' ), marginRightStyle = element.getStyle( 'margin-right' ); marginLeftStyle = marginLeftStyle && marginLeftStyle.match( pxLengthRegex ); marginRightStyle = marginRightStyle && marginRightStyle.match( pxLengthRegex ); marginLeftPx = parseInt( marginLeftStyle, 10 ); marginRightPx = parseInt( marginRightStyle, 10 ); value = ( marginLeftPx == marginRightPx ) && marginLeftPx; isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'hspace' ) ); this.setValue( value ); } }, commit : function( type, element, internalCommit ) { var value = parseInt( this.getValue(), 10 ); if ( type == IMAGE || type == PREVIEW ) { if ( !isNaN( value ) ) { element.setStyle( 'margin-left', CKEDITOR.tools.cssLength( value ) ); element.setStyle( 'margin-right', CKEDITOR.tools.cssLength( value ) ); } else if ( !value && this.isChanged( ) ) { element.removeStyle( 'margin-left' ); element.removeStyle( 'margin-right' ); } if ( !internalCommit && type == IMAGE ) element.removeAttribute( 'hspace' ); } else if ( type == CLEANUP ) { element.removeAttribute( 'hspace' ); element.removeStyle( 'margin-left' ); element.removeStyle( 'margin-right' ); } } }, { type : 'text', id : 'txtVSpace', width : '60px', label : editor.lang.image.vSpace, 'default' : '', onKeyUp : function() { updatePreview( this.getDialog() ); }, onChange : function() { commitInternally.call( this, 'advanced:txtdlgGenStyle' ); }, validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateVSpace ), setup : function( type, element ) { if ( type == IMAGE ) { var value, marginTopPx, marginBottomPx, marginTopStyle = element.getStyle( 'margin-top' ), marginBottomStyle = element.getStyle( 'margin-bottom' ); marginTopStyle = marginTopStyle && marginTopStyle.match( pxLengthRegex ); marginBottomStyle = marginBottomStyle && marginBottomStyle.match( pxLengthRegex ); marginTopPx = parseInt( marginTopStyle, 10 ); marginBottomPx = parseInt( marginBottomStyle, 10 ); value = ( marginTopPx == marginBottomPx ) && marginTopPx; isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'vspace' ) ); this.setValue( value ); } }, commit : function( type, element, internalCommit ) { var value = parseInt( this.getValue(), 10 ); if ( type == IMAGE || type == PREVIEW ) { if ( !isNaN( value ) ) { element.setStyle( 'margin-top', CKEDITOR.tools.cssLength( value ) ); element.setStyle( 'margin-bottom', CKEDITOR.tools.cssLength( value ) ); } else if ( !value && this.isChanged( ) ) { element.removeStyle( 'margin-top' ); element.removeStyle( 'margin-bottom' ); } if ( !internalCommit && type == IMAGE ) element.removeAttribute( 'vspace' ); } else if ( type == CLEANUP ) { element.removeAttribute( 'vspace' ); element.removeStyle( 'margin-top' ); element.removeStyle( 'margin-bottom' ); } } }, { id : 'cmbAlign', type : 'select', widths : [ '35%','65%' ], style : 'width:90px', label : editor.lang.common.align, 'default' : '', items : [ [ editor.lang.common.notSet , ''], [ editor.lang.common.alignLeft , 'left'], [ editor.lang.common.alignRight , 'right'] // Backward compatible with v2 on setup when specified as attribute value, // while these values are no more available as select options. // [ editor.lang.image.alignAbsBottom , 'absBottom'], // [ editor.lang.image.alignAbsMiddle , 'absMiddle'], // [ editor.lang.image.alignBaseline , 'baseline'], // [ editor.lang.image.alignTextTop , 'text-top'], // [ editor.lang.image.alignBottom , 'bottom'], // [ editor.lang.image.alignMiddle , 'middle'], // [ editor.lang.image.alignTop , 'top'] ], onChange : function() { updatePreview( this.getDialog() ); commitInternally.call( this, 'advanced:txtdlgGenStyle' ); }, setup : function( type, element ) { if ( type == IMAGE ) { var value = element.getStyle( 'float' ); switch( value ) { // Ignore those unrelated values. case 'inherit': case 'none': value = ''; } !value && ( value = ( element.getAttribute( 'align' ) || '' ).toLowerCase() ); this.setValue( value ); } }, commit : function( type, element, internalCommit ) { var value = this.getValue(); if ( type == IMAGE || type == PREVIEW ) { if ( value ) element.setStyle( 'float', value ); else element.removeStyle( 'float' ); if ( !internalCommit && type == IMAGE ) { value = ( element.getAttribute( 'align' ) || '' ).toLowerCase(); switch( value ) { // we should remove it only if it matches "left" or "right", // otherwise leave it intact. case 'left': case 'right': element.removeAttribute( 'align' ); } } } else if ( type == CLEANUP ) element.removeStyle( 'float' ); } } ] } ] }, { type : 'vbox', height : '250px', children : [ { type : 'html', style : 'width:95%;', html : '<div>' + CKEDITOR.tools.htmlEncode( editor.lang.common.preview ) +'<br>'+ '<div id="' + imagePreviewLoaderId + '" class="ImagePreviewLoader" style="display:none"><div class="loading">&nbsp;</div></div>'+ '<div id="' + imagePreviewBoxId + '" class="ImagePreviewBox"><table><tr><td>'+ '<a href="javascript:void(0)" target="_blank" onclick="return false;" id="' + previewLinkId + '">'+ '<img id="' + previewImageId + '" alt="" /></a>' + ( editor.config.image_previewText || 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '+ 'Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, '+ 'nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.' ) + '</td></tr></table></div></div>' } ] } ] } ] }, { id : 'Link', label : editor.lang.link.title, padding : 0, elements : [ { id : 'txtUrl', type : 'text', label : editor.lang.common.url, style : 'width: 100%', 'default' : '', setup : function( type, element ) { if ( type == LINK ) { var href = element.data( 'cke-saved-href' ); if ( !href ) href = element.getAttribute( 'href' ); this.setValue( href ); } }, commit : function( type, element ) { if ( type == LINK ) { if ( this.getValue() || this.isChanged() ) { var url = decodeURI( this.getValue() ); element.data( 'cke-saved-href', url ); element.setAttribute( 'href', url ); if ( this.getValue() || !editor.config.image_removeLinkByEmptyURL ) this.getDialog().addLink = true; } } } }, { type : 'button', id : 'browse', filebrowser : { action : 'Browse', target: 'Link:txtUrl', url: editor.config.filebrowserImageBrowseLinkUrl }, style : 'float:right', hidden : true, label : editor.lang.common.browseServer }, { id : 'cmbTarget', type : 'select', label : editor.lang.common.target, 'default' : '', items : [ [ editor.lang.common.notSet , ''], [ editor.lang.common.targetNew , '_blank'], [ editor.lang.common.targetTop , '_top'], [ editor.lang.common.targetSelf , '_self'], [ editor.lang.common.targetParent , '_parent'] ], setup : function( type, element ) { if ( type == LINK ) this.setValue( element.getAttribute( 'target' ) || '' ); }, commit : function( type, element ) { if ( type == LINK ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'target', this.getValue() ); } } } ] }, { id : 'Upload', hidden : true, filebrowser : 'uploadButton', label : editor.lang.image.upload, elements : [ { type : 'file', id : 'upload', label : editor.lang.image.btnUpload, style: 'height:40px', size : 38 }, { type : 'fileButton', id : 'uploadButton', filebrowser : 'info:txtUrl', label : editor.lang.image.btnUpload, 'for' : [ 'Upload', 'upload' ] } ] }, { id : 'advanced', label : editor.lang.common.advancedTab, elements : [ { type : 'hbox', widths : [ '50%', '25%', '25%' ], children : [ { type : 'text', id : 'linkId', label : editor.lang.common.id, setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'id' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'id', this.getValue() ); } } }, { id : 'cmbLangDir', type : 'select', style : 'width : 100px;', label : editor.lang.common.langDir, 'default' : '', items : [ [ editor.lang.common.notSet, '' ], [ editor.lang.common.langDirLtr, 'ltr' ], [ editor.lang.common.langDirRtl, 'rtl' ] ], setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'dir' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'dir', this.getValue() ); } } }, { type : 'text', id : 'txtLangCode', label : editor.lang.common.langCode, 'default' : '', setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'lang' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'lang', this.getValue() ); } } } ] }, { type : 'text', id : 'txtGenLongDescr', label : editor.lang.common.longDescr, setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'longDesc' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'longDesc', this.getValue() ); } } }, { type : 'hbox', widths : [ '50%', '50%' ], children : [ { type : 'text', id : 'txtGenClass', label : editor.lang.common.cssClass, 'default' : '', setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'class' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'class', this.getValue() ); } } }, { type : 'text', id : 'txtGenTitle', label : editor.lang.common.advisoryTitle, 'default' : '', onChange : function() { updatePreview( this.getDialog() ); }, setup : function( type, element ) { if ( type == IMAGE ) this.setValue( element.getAttribute( 'title' ) ); }, commit : function( type, element ) { if ( type == IMAGE ) { if ( this.getValue() || this.isChanged() ) element.setAttribute( 'title', this.getValue() ); } else if ( type == PREVIEW ) { element.setAttribute( 'title', this.getValue() ); } else if ( type == CLEANUP ) { element.removeAttribute( 'title' ); } } } ] }, { type : 'text', id : 'txtdlgGenStyle', label : editor.lang.common.cssStyle, 'default' : '', setup : function( type, element ) { if ( type == IMAGE ) { var genStyle = element.getAttribute( 'style' ); if ( !genStyle && element.$.style.cssText ) genStyle = element.$.style.cssText; this.setValue( genStyle ); var height = element.$.style.height, width = element.$.style.width, aMatchH = ( height ? height : '' ).match( regexGetSize ), aMatchW = ( width ? width : '').match( regexGetSize ); this.attributesInStyle = { height : !!aMatchH, width : !!aMatchW }; } }, onChange : function () { commitInternally.call( this, [ 'info:cmbFloat', 'info:cmbAlign', 'info:txtVSpace', 'info:txtHSpace', 'info:txtBorder', 'info:txtWidth', 'info:txtHeight' ] ); updatePreview( this ); }, commit : function( type, element ) { if ( type == IMAGE && ( this.getValue() || this.isChanged() ) ) { element.setAttribute( 'style', this.getValue() ); } } } ] } ] }; }; CKEDITOR.dialog.add( 'image', function( editor ) { return imageDialog( editor, 'image' ); }); CKEDITOR.dialog.add( 'imagebutton', function( editor ) { return imageDialog( editor, 'imagebutton' ); }); })();
fredd-for/codice.v.1.1
ckeditor/_source/plugins/image/dialogs/image.js
JavaScript
bsd-3-clause
46,523
/** * 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 FB_MODULE_RE = /^(.*) \[from (.*)\]$/; const cachedDisplayNames = new WeakMap(); function getDisplayName(type: Function): string { if (cachedDisplayNames.has(type)) { return cachedDisplayNames.get(type); } let displayName = type.displayName || type.name || 'Unknown'; // Facebook-specific hack to turn "Image [from Image.react]" into just "Image". // We need displayName with module name for error reports but it clutters the DevTools. const match = displayName.match(FB_MODULE_RE); if (match) { const componentName = match[1]; const moduleName = match[2]; if (componentName && moduleName) { if ( moduleName === componentName || moduleName.startsWith(componentName + '.') ) { displayName = componentName; } } } cachedDisplayNames.set(type, displayName); return displayName; } module.exports = getDisplayName;
jhen0409/react-devtools
backend/getDisplayName.js
JavaScript
bsd-3-clause
1,237
/* * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['sap/ui/base/EventProvider','./Serializer','./delegate/HTML','sap/ui/thirdparty/vkbeautify'],function(E,S,H,v){"use strict";var a=E.extend("sap.ui.core.util.serializer.HTMLViewSerializer",{constructor:function(V,w,g,G){E.apply(this);this._oView=V;this._oWindow=w;this._fnGetControlId=g;this._fnGetEventHandlerName=G;}});a.prototype.serialize=function(){var s=function(C){return(C instanceof this._oWindow.sap.ui.core.mvc.View);};var c=new S(this._oView,new H(this._fnGetControlId,this._fnGetEventHandlerName),true,this._oWindow,s);var r=c.serialize();var V=[];V.push('<template');if(this._oView.getControllerName&&this._oView.getControllerName()){V.push(' data-controller-name="'+this._oView.getControllerName()+'"');}V.push(" >");V.push(r);V.push("</template>");return v.xml(V.join(""));};return a;});
dirga123/clr
openui5/sap/ui/core/util/serializer/HTMLViewSerializer.js
JavaScript
isc
1,003
'use strict'; var _ = require('lodash'); var helpers = require('./helpers'); var responseParser = require('./responseparser'); var request = require('./request'); // A resource on the API, instances of this are used as the prototype of // instances of each API resource. This constructor will build up a method // for each action that can be performed on the resource. // // - @param {Object} options // - @param {Object} schema // // The `options` argument should have the following properties: // // - `resourceDefinition` - the definition of the resource and its actions from // the schema definition. // - `consumerkey` - the oauth consumerkey // - `consumersecret` the oauth consumersecret // - `schema` - the schema defintion // - `format` - the desired response format // - `logger` - for logging output function Resource(options, schema) { this.logger = options.logger; this.resourceName = options.resourceDefinition.resource; this.host = options.resourceDefinition.host || schema.host; this.sslHost = options.resourceDefinition.sslHost || schema.sslHost; this.port = options.resourceDefinition.port || schema.port; this.prefix = options.resourceDefinition.prefix || schema.prefix; this.consumerkey = options.consumerkey; this.consumersecret = options.consumersecret; if(this.logger.silly) { this.logger.silly('Creating constructor for resource: ' + this.resourceName); } _.each(options.resourceDefinition.actions, function processAction(action) { this.createAction(action, options.userManagement); }, this); } // Figure out the appropriate method name for an action on a resource on // the API // // - @param {Mixed} - actionDefinition - Either a string if the action method // name is the same as the action path component on the underlying API call // or a hash if they differ. // - @return {String} Resource.prototype.chooseMethodName = function (actionDefinition) { var fnName; // Default the action name to getXXX if we only have the URL slug as the // action definition. if (_.isString(actionDefinition)) { fnName = 'get' + helpers.capitalize(actionDefinition); } else { fnName = actionDefinition.methodName; } return fnName; }; // Utility method for creating the necessary methods on the Resource for // dispatching the request to the 7digital API. // // - @param {Mixed} actionDefinition - Either a string if the action method // name is the same as the action path component on the underlying API call // or a hash if they differ. Resource.prototype.createAction = function (actionDefinition, isManaged) { var url; var fnName = this.chooseMethodName(actionDefinition); var action = typeof actionDefinition.apiCall === 'undefined' ? actionDefinition : actionDefinition.apiCall; var httpMethod = (actionDefinition.method || 'GET').toUpperCase(); var host = actionDefinition.host || this.host; var sslHost = actionDefinition.sslHost || this.sslHost; var port = actionDefinition.port || this.port; var prefix = actionDefinition.prefix || this.prefix; var authType = (actionDefinition.oauth && actionDefinition.oauth === '3-legged' && isManaged) ? '2-legged' : actionDefinition.oauth; if(this.logger.silly) { this.logger.silly( 'Creating method: ' + fnName + ' for ' + action + ' action with ' + httpMethod + ' HTTP verb'); } /*jshint validthis: true */ function invokeAction(requestData, callback) { var self = this; var endpointInfo = { host: invokeAction.host, sslHost: invokeAction.sslHost || sslHost, port: invokeAction.port, prefix: invokeAction.prefix, authtype: authType, url: helpers.formatPath(invokeAction.prefix, this.resourceName, action) }; var credentials = { consumerkey: this.consumerkey, consumersecret: this.consumersecret }; if (_.isFunction(requestData)) { callback = requestData; requestData = {}; } function checkAndParse(err, data, response) { if (err) { return callback(err); } return responseParser.parse(data, { format: self.format, logger: self.logger, url: endpointInfo.url, params: requestData, contentType: response.headers['content-type'] }, getLocationForRedirectsAndCallback); function getLocationForRedirectsAndCallback(err, parsed) { if (err) { return callback(err); } if (response && response.headers['location']) { parsed.location = response.headers['location']; } return callback(null, parsed); } } _.defaults(requestData, this.defaultParams); if (httpMethod === 'GET') { // Add the default parameters to the request data return request.get(endpointInfo, requestData, this.headers, credentials, this.logger, checkAndParse); } if (httpMethod === 'POST' || httpMethod === 'PUT') { return request.postOrPut(httpMethod, endpointInfo, requestData, this.headers, credentials, this.logger, checkAndParse); } return callback(new Error('Unsupported HTTP verb: ' + httpMethod)); } invokeAction.action = action; invokeAction.authtype = authType; invokeAction.host = host; invokeAction.sslHost = sslHost; invokeAction.port = port; invokeAction.prefix = prefix; this[fnName] = invokeAction; }; module.exports = Resource;
raoulmillais/7digital-api
lib/resource.js
JavaScript
isc
5,206
/** * Custom events to control showing and hiding of tooltip * * @attributes * - `event` {String} * - `eventOff` {String} */ export const checkStatus = function(dataEventOff, e) { const { show } = this.state; const { id } = this.props; const isCapture = this.isCapture(e.currentTarget); const currentItem = e.currentTarget.getAttribute('currentItem'); if (!isCapture) e.stopPropagation(); if (show && currentItem === 'true') { if (!dataEventOff) this.hideTooltip(e); } else { e.currentTarget.setAttribute('currentItem', 'true'); setUntargetItems(e.currentTarget, this.getTargetArray(id)); this.showTooltip(e); } }; const setUntargetItems = function(currentTarget, targetArray) { for (let i = 0; i < targetArray.length; i++) { if (currentTarget !== targetArray[i]) { targetArray[i].setAttribute('currentItem', 'false'); } else { targetArray[i].setAttribute('currentItem', 'true'); } } }; const customListeners = { id: '9b69f92e-d3fe-498b-b1b4-c5e63a51b0cf', set(target, event, listener) { if (this.id in target) { const map = target[this.id]; map[event] = listener; } else { // this is workaround for WeakMap, which is not supported in older browsers, such as IE Object.defineProperty(target, this.id, { configurable: true, value: { [event]: listener } }); } }, get(target, event) { const map = target[this.id]; if (map !== undefined) { return map[event]; } } }; export default function(target) { target.prototype.isCustomEvent = function(ele) { const { event } = this.state; return event || !!ele.getAttribute('data-event'); }; /* Bind listener for custom event */ target.prototype.customBindListener = function(ele) { const { event, eventOff } = this.state; const dataEvent = ele.getAttribute('data-event') || event; const dataEventOff = ele.getAttribute('data-event-off') || eventOff; dataEvent.split(' ').forEach(event => { ele.removeEventListener(event, customListeners.get(ele, event)); const customListener = checkStatus.bind(this, dataEventOff); customListeners.set(ele, event, customListener); ele.addEventListener(event, customListener, false); }); if (dataEventOff) { dataEventOff.split(' ').forEach(event => { ele.removeEventListener(event, this.hideTooltip); ele.addEventListener(event, this.hideTooltip, false); }); } }; /* Unbind listener for custom event */ target.prototype.customUnbindListener = function(ele) { const { event, eventOff } = this.state; const dataEvent = event || ele.getAttribute('data-event'); const dataEventOff = eventOff || ele.getAttribute('data-event-off'); ele.removeEventListener(dataEvent, customListeners.get(ele, event)); if (dataEventOff) ele.removeEventListener(dataEventOff, this.hideTooltip); }; }
wwayne/react-tooltip
src/decorators/customEvent.js
JavaScript
mit
2,931
var Request = require('request'); function NewsFetcher() { this._newsLink = 'http://kaku.rocks/news.json'; } NewsFetcher.prototype.get = function() { var promise = new Promise((resolve, reject) => { Request.get(this._newsLink, (error, response, body) => { if (error) { reject(error); console.log(error); } else { var result = JSON.parse(body); resolve(result.news); } }); }); return promise; }; module.exports = new NewsFetcher();
uirsevla/Kaku
src/modules/NewsFetcher.js
JavaScript
mit
506
/** * @fileoverview Tests for max-depth. * @author Ian Christian Myers */ //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslintTester = require("eslint-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ eslintTester.addRuleTest("lib/rules/max-depth", { valid: [ { code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 3] }, "function foo() { if (true) { if (false) { if (true) { } } } }" ], invalid: [ { code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 2], errors: [{ message: "Blocks are nested too deeply (3).", type: "IfStatement"}] }, { code: "function foo() { if (true) {} else { for(;;) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "ForStatement"}] }, { code: "function foo() { while (true) { if (true) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}] }, { code: "function foo() { while (true) { if (true) { if (false) { } } } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}, { message: "Blocks are nested too deeply (3).", type: "IfStatement"}] } ] });
natesilva/eslint
tests/lib/rules/max-depth.js
JavaScript
mit
1,497
'use strict'; exports.__esModule = true; 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; }; exports.isReactChildren = isReactChildren; exports.createRouteFromReactElement = createRouteFromReactElement; exports.createRoutesFromReactChildren = createRoutesFromReactChildren; exports.createRoutes = createRoutes; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _warning = require('warning'); var _warning2 = _interopRequireDefault(_warning); function isValidChild(object) { return object == null || (0, _react.isValidElement)(object); } function isReactChildren(object) { return isValidChild(object) || Array.isArray(object) && object.every(isValidChild); } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent'; for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName); if (error instanceof Error) (0, _warning2['default'])(false, error.message); } } } function createRouteFromReactElement(element) { var type = element.type; var route = _extends({}, type.defaultProps, element.props); if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route); if (route.children) { route.childRoutes = createRoutesFromReactChildren(route.children); delete route.children; } return route; } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router'; * * var routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ); * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ function createRoutesFromReactChildren(children) { var routes = []; _react2['default'].Children.forEach(children, function (element) { if ((0, _react.isValidElement)(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { routes.push(element.type.createRouteFromReactElement(element)); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (!Array.isArray(routes)) { routes = [routes]; } return routes; }
yomolify/cc-server
node_modules/react-router/lib/RouteUtils.js
JavaScript
mit
3,153
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import ReactDOM from 'react-dom'; import Nav from '../src/Nav'; import NavItem from '../src/NavItem'; import Tab from '../src/Tab'; import TabPane from '../src/TabPane'; import Tabs from '../src/Tabs'; import ValidComponentChildren from '../src/utils/ValidComponentChildren'; import { render } from './helpers'; describe('<Tabs>', () => { it('Should show the correct tab', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={1}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/)); assert.ok(!ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/)); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.context.$bs_tabContainer.activeKey, 1); }); it('Should only show the tabs with `Tab.props.title` set', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={3}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab eventKey={2}>Tab 2 content</Tab> <Tab title="Tab 2" eventKey={3}>Tab 3 content</Tab> </Tabs> ); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(ValidComponentChildren.count(nav.props.children), 2); }); it('Should allow tab to have React components', () => { const tabTitle = ( <strong className="special-tab">Tab 2</strong> ); const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={2}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title={tabTitle} eventKey={2}>Tab 2 content</Tab> </Tabs> ); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(nav, 'special-tab')); }); it('Should call onSelect when tab is selected', (done) => { function onSelect(key) { assert.equal(key, '2'); done(); } const tab2 = <span className="tab2">Tab2</span>; const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" onSelect={onSelect} activeKey={1}> <Tab title="Tab 1" eventKey="1">Tab 1 content</Tab> <Tab title={tab2} eventKey="2">Tab 2 content</Tab> </Tabs> ); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab2') ); }); it('Should have children with the correct DOM properties', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={1}> <Tab title="Tab 1" className="custom" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" tabClassName="tcustom" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, Tab); const navs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem); assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bcustom\b/)); assert.ok(ReactDOM.findDOMNode(navs[1]).className.match(/\btcustom\b/)); assert.equal(ReactDOM.findDOMNode(panes[0]).id, 'test-pane-1'); }); it('Should show the correct first tab with no active key value', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test"> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/)); assert.ok(!ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/)); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.context.$bs_tabContainer.activeKey, 1); }); it('Should show the correct first tab with children array', () => { const panes = [0, 1].map(index => ( <Tab key={index} eventKey={index} title={`Tab #${index}`} > <div> content </div> </Tab> )); let instance = ReactTestUtils.renderIntoDocument( <Tabs id="test"> {panes} {null} </Tabs> ); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.context.$bs_tabContainer.activeKey, 0); }); it('Should show the correct tab when selected', () => { const tab1 = <span className="tab1">Tab 1</span>; const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={2} animation={false}> <Tab title={tab1} eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1') ); assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/)); assert.ok(!ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/)); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.context.$bs_tabContainer.activeKey, 1); }); it('Should mount initial tab and no others when unmountOnExit is true and animation is false', () => { const tab1 = <span className="tab1">Tab 1</span>; const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={1} animation={false} unmountOnExit> <Tab title={tab1} eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> <Tab title="Tab 3" eventKey={3}>Tab 3 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); expect(ReactDOM.findDOMNode(panes[0])).to.exist; expect(ReactDOM.findDOMNode(panes[1])).to.not.exist; expect(ReactDOM.findDOMNode(panes[2])).to.not.exist; }); it('Should mount the correct tab when selected and unmount the previous when unmountOnExit is true and animation is false', () => { const tab1 = <span className="tab1">Tab 1</span>; const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={2} animation={false} unmountOnExit> <Tab title={tab1} eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1') ); expect(ReactDOM.findDOMNode(panes[0])).to.exist; expect(ReactDOM.findDOMNode(panes[1])).to.not.exist; const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.context.$bs_tabContainer.activeKey, 1); }); it('Should treat active key of null as nothing selected', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" activeKey={null} onSelect={()=>{}}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); expect(nav.context.$bs_tabContainer.activeKey).to.not.exist; }); it('Should pass default bsStyle (of "tabs") to Nav', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={1} animation={false}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav-tabs')); }); it('Should pass bsStyle to Nav', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" bsStyle="pills" defaultActiveKey={1} animation={false}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav-pills')); }); it('Should pass disabled to Nav', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={1}> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2} disabled>Tab 2 content</Tab> </Tabs> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled')); }); it('Should not show content when clicking disabled tab', () => { const tab1 = <span className="tab1">Tab 1</span>; const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" defaultActiveKey={2} animation={false}> <Tab title={tab1} eventKey={1} disabled>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); ReactTestUtils.Simulate.click( ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1') ); assert.ok(!ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/)); assert.ok(ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/)); const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.context.$bs_tabContainer.activeKey, 2); }); describe('active state invariants', () => { let mountPoint; beforeEach(() => { mountPoint = document.createElement('div'); document.body.appendChild(mountPoint); }); afterEach(() => { ReactDOM.unmountComponentAtNode(mountPoint); document.body.removeChild(mountPoint); }); [true, false].forEach(animation => { it(`should correctly set "active" after Tab is removed with "animation=${animation}"`, () => { const instance = render( <Tabs id="test" activeKey={2} animation={animation} onSelect={() => {}} > <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> , mountPoint); const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane); assert.ok(!ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/)); assert.ok(ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/)); // second tab has been removed render( <Tabs id="test" activeKey={1} animation={animation} onSelect={() => {}} > <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> </Tabs> , mountPoint).refs.inner; assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/)); }); }); }); describe('Web Accessibility', () => { let instance; beforeEach(() => { instance = ReactTestUtils.renderIntoDocument( <Tabs defaultActiveKey={2} id="test"> <Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); }); it('Should generate ids from parent id', () => { const tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem); tabs.every(tab => assert.ok(tab.props['aria-controls'] && tab.props.id)); }); it('Should add aria-labelledby', () => { const panes = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'tab-pane'); assert.equal(panes[0].getAttribute('aria-labelledby'), 'test-tab-1'); assert.equal(panes[1].getAttribute('aria-labelledby'), 'test-tab-2'); }); it('Should add aria-controls', () => { const tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem); assert.equal(tabs[0].props['aria-controls'], 'test-pane-1'); assert.equal(tabs[1].props['aria-controls'], 'test-pane-2'); }); it('Should add role=tablist to the nav', () => { const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav); assert.equal(nav.props.role, 'tablist'); }); it('Should add aria-selected to the nav item for the selected tab', () => { const tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem); const link1 = ReactTestUtils.findRenderedDOMComponentWithTag(tabs[0], 'a'); const link2 = ReactTestUtils.findRenderedDOMComponentWithTag(tabs[1], 'a'); assert.equal(link1.getAttribute('aria-selected'), 'false'); assert.equal(link2.getAttribute('aria-selected'), 'true'); }); }); it('Should not pass className to Nav', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" bsStyle="pills" defaultActiveKey={1} animation={false}> <Tab title="Tab 1" eventKey={1} className="my-tab-class">Tab 1 content</Tab> <Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab> </Tabs> ); const myTabClass = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'my-tab-class'); const myNavItem = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'nav-pills')[0]; assert.notDeepEqual(myTabClass, myNavItem); }); it('Should pass className, Id, and style to Tabs', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs bsStyle="pills" defaultActiveKey={1} animation={false} className="my-tabs-class" id="my-tabs-id" style={{ opacity: 0.5 }} /> ); assert.equal(ReactDOM.findDOMNode(instance).getAttribute('class'), 'my-tabs-class'); assert.equal(ReactDOM.findDOMNode(instance).getAttribute('id'), 'my-tabs-id'); // Decimal point string depends on locale assert.equal(parseFloat(ReactDOM.findDOMNode(instance).style.opacity), 0.5); }); it('should derive bsClass from parent', () => { const instance = ReactTestUtils.renderIntoDocument( <Tabs id="test" bsClass="my-tabs"> <Tab eventKey={1} title="Tab 1" /> <Tab eventKey={2} title="Tab 2" bsClass="my-pane" /> </Tabs> ); assert.lengthOf(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'my-tabs-pane'), 2); assert.lengthOf(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'my-pane'), 0); }); });
mmarcant/react-bootstrap
test/TabsSpec.js
JavaScript
mit
14,836
'use strict'; const gulp = require('gulp'); const sequence = require('run-sequence'); gulp.task('start', cb => { sequence('configure', 'build', 'install', cb); });
radekk/webtask-mfa-monitor
gulp/tasks/start.js
JavaScript
mit
168
semantic.dropdown = {}; // ready event semantic.dropdown.ready = function() { // selector cache var // alias handler ; // event handlers handler = { }; $('.first.example .menu .item') .tab({ context: '.first.example' }) ; $('.history.example .menu .item') .tab({ context : '.history.example', history : true, path : '/modules/tab.html' }) ; $('.dynamic.example .menu .item') .tab({ context : '.dynamic.example', auto : true, path : '/modules/tab.html' }) ; }; // attach ready event $(document) .ready(semantic.dropdown.ready) ;
taylorrose/taylorrose.github.io
blog/js/tab.js
JavaScript
mit
690
/* * mobile table unit tests */ (function($){ module( "Basic Table", { setup: function(){ var hash = "#basic-table-test"; if( location.hash != hash ){ stop(); $(document).one("pagechange", function() { start(); }); $.mobile.changePage( hash ); } }, teardown: function() { } }); asyncTest( "The page should be enhanced correctly" , function(){ setTimeout(function() { var $table = $('#basic-table-test .ui-table'); ok( $table.length, ".ui-table class added to table element" ); start(); }, 800); }); asyncTest( "Has data object attributed to table" , function(){ setTimeout(function(){ var $table = $('#basic-table-test .ui-table'), self = $table.data( "mobile-table" ); ok( self , "Data object is available" ); start(); }, 800); }); asyncTest( "Has headers option" , function(){ setTimeout(function() { var $table = $('#basic-table-test .ui-table'), self = $table.data( "mobile-table" ); ok( self.headers.length , "Header array is not empty"); equal( 5 , self.headers.length , "Number of headers is correct"); start(); }, 800); }); module( "Reflow Mode", { setup: function(){ var hash = "#reflow-table-test"; if( location.hash != hash ){ stop(); $(document).one("pagechange", function() { start(); }); $.mobile.changePage( hash ); } }, teardown: function() { } }); asyncTest( "The page should be enhanced correctly" , function(){ setTimeout(function() { ok($('#reflow-table-test .ui-table-reflow').length, ".ui-table-reflow class added to table element"); start(); }, 800); }); asyncTest( "The appropriate label is added" , function(){ setTimeout(function(){ var $table = $( "#reflow-table-test table" ), $body = $table.find( "tbody" ), $tds = $body.find( "td" ), labels = $tds.find( "b.ui-table-cell-label" ); ok( labels , "Appropriate label placed" ); equal( $( labels[0] ).text(), "Movie Title" , "Appropriate label placed" ); start(); }, 800); }); module( "Column toggle table Mode", { setup: function(){ var hash = "#column-table-test"; if( location.hash != hash ){ stop(); $(document).one("pagechange", function() { start(); }); $.mobile.changePage( hash ); } }, teardown: function() { } }); asyncTest( "The page should be enhanced correctly" , function(){ setTimeout(function() { var $popup = $('#column-table-test #movie-table-column-popup-popup'); ok($('#column-table-test .ui-table-columntoggle').length, ".ui-table-columntoggle class added to table element"); ok($('#column-table-test .ui-table-columntoggle-btn').length, ".ui-table-columntoggle-btn button added"); equal($('#column-table-test .ui-table-columntoggle-btn').text(), "Columns...", "Column toggle button has correct text"); ok( $popup.length, "dialog added" ); ok( $popup.is( ".ui-popup-hidden" ) , "dialog hidden"); ok($('#column-table-test #movie-table-column-popup-popup').find( "input[type=checkbox]" ).length > 0 , "Checkboxes added"); start(); }, 800); }); asyncTest( "The dialog should become visible when button is clicked" , function(){ expect( 2 ); var $input; $.testHelper.pageSequence([ function() { $( ".ui-table-columntoggle-btn" ).click(); }, function() { setTimeout(function() { ok( $( "#movie-table-column-popup-popup" ).not( ".ui-popup-hidden" ) , "Table popup is shown on click" ); }, 800); }, function() { $input = $( ".ui-popup-container" ).find( "input:first" ); $input.click(); }, function(){ setTimeout(function(){ var headers = $( "#column-table-test table tr" ).find( "th:first" ); if( $input.is( ":checked" ) ){ ok( headers.not( ".ui-table-cell-hidden" ) ); } else { ok( headers.is( ".ui-table-cell-hidden" ) ); } }, 800); }, function() { start(); } ]); }); })(jQuery);
abhishekbhalani/jquery-mobile
tests/unit/table/table_core.js
JavaScript
mit
3,944