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
$(document).ready(function(){ $("#startDate").datepicker({dateFormat:'yy-mm-dd'}); $("#endDate").datepicker({dateFormat:'yy-mm-dd'}); //$('#startDate').datepicker(); //$('#endDate').datepicker(); })
sorabhv6/mylib
php_lib/google_analytics/js/custom.js
JavaScript
gpl-2.0
211
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/Device", "opensap/manageproducts/model/models", "opensap/manageproducts/controller/ErrorHandler" ], function (UIComponent, Device, models, ErrorHandler) { "use strict"; return UIComponent.extend("opensap.manageproducts.Component", { metadata : { manifest: "json" }, /** * The component is initialized by UI5 automatically during the startup of the app and calls the init method once. * In this function, the device models are set and the router is initialized. * @public * @override */ init : function () { // call the base component's init function UIComponent.prototype.init.apply(this, arguments); // initialize the error handler with the component this._oErrorHandler = new ErrorHandler(this); // set the device model this.setModel(models.createDeviceModel(), "device"); // create the views based on the url/hash this.getRouter().initialize(); }, /** * The component is destroyed by UI5 automatically. * In this method, the ErrorHandler is destroyed. * @public * @override */ destroy : function () { this._oErrorHandler.destroy(); // call the base component's destroy function UIComponent.prototype.destroy.apply(this, arguments); }, /** * This method can be called to determine whether the sapUiSizeCompact or sapUiSizeCozy * design mode class should be set, which influences the size appearance of some controls. * @public * @return {string} css class, either 'sapUiSizeCompact' or 'sapUiSizeCozy' - or an empty string if no css class should be set */ getContentDensityClass : function() { if (this._sContentDensityClass === undefined) { // check whether FLP has already set the content density class; do nothing in this case if (jQuery(document.body).hasClass("sapUiSizeCozy") || jQuery(document.body).hasClass("sapUiSizeCompact")) { this._sContentDensityClass = ""; } else if (!Device.support.touch) { // apply "compact" mode if touch is not supported this._sContentDensityClass = "sapUiSizeCompact"; } else { // "cozy" in case of touch support; default for most sap.m controls, but needed for desktop-first controls like sap.ui.table.Table this._sContentDensityClass = "sapUiSizeCozy"; } } return this._sContentDensityClass; } }); } );
carlitosalcala/openui
ManageProducts/webapp/Component.js
JavaScript
gpl-2.0
2,424
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER * * Copyright (c) 2012-2013 Universidad Politécnica de Madrid * Copyright (c) 2012-2013 the Center for Open Middleware * * 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. */ /*global gettext, ngettext, interpolate, StyledElements, Wirecloud*/ (function () { "use strict"; /************************************************************************* * Private functions *************************************************************************/ var updateErrorInfo = function updateErrorInfo() { var label, errorCount = this.entity.logManager.getErrorCount(); this.log_button.setDisabled(errorCount === 0); label = ngettext("%(errorCount)s error", "%(errorCount)s errors", errorCount); label = interpolate(label, {errorCount: errorCount}, true); this.log_button.setTitle(label); }; /************************************************************************* * Constructor *************************************************************************/ /** * GenericInterface Class */ var GenericInterface = function GenericInterface(extending, wiringEditor, entity, title, manager, className, isGhost) { if (extending === true) { return; } var del_button, log_button, type, msg, ghostNotification; StyledElements.Container.call(this, {'class': className}, []); Object.defineProperty(this, 'entity', {value: entity}); this.editingPos = false; this.targetAnchorsByName = {}; this.sourceAnchorsByName = {}; this.targetAnchors = []; this.sourceAnchors = []; this.wiringEditor = wiringEditor; this.title = title; this.className = className; this.initPos = {'x': 0, 'y': 0}; this.draggableSources = []; this.draggableTargets = []; this.activatedTree = null; this.hollowConnections = {}; this.fullConnections = {}; this.subdataConnections = {}; this.isMinimized = false; this.minWidth = ''; this.movement = false; this.numberOfSources = 0; this.numberOfTargets = 0; this.potentialArrow = null; // Only for minimize maximize operators. this.initialPos = null; this.isGhost = isGhost; this.readOnlyEndpoints = 0; this.readOnly = false; if (manager instanceof Wirecloud.ui.WiringEditor.ArrowCreator) { this.isMiniInterface = false; this.arrowCreator = manager; } else { this.isMiniInterface = true; this.arrowCreator = null; } // Interface buttons, not for miniInterface if (!this.isMiniInterface) { if (className == 'iwidget') { type = 'widget'; this.version = this.entity.version; this.vendor = this.entity.vendor; this.name = this.entity.name; } else { type = 'operator'; this.version = this.entity.meta.version; this.vendor = this.entity.meta.vendor; this.name = this.entity.meta.name; } // header, sources and targets for the widget this.resourcesDiv = new StyledElements.BorderLayout({'class': "geContainer"}); this.sourceDiv = this.resourcesDiv.getEastContainer(); this.sourceDiv.addClassName("sources"); this.targetDiv = this.resourcesDiv.getWestContainer(); this.targetDiv.addClassName("targets"); this.header = this.resourcesDiv.getNorthContainer(); this.header.addClassName('header'); this.wrapperElement.appendChild(this.resourcesDiv.wrapperElement); // Ghost interface if (isGhost) { this.vendor = this.entity.name.split('/')[0]; this.name = this.entity.name.split('/')[1]; this.version = new Wirecloud.Version(this.entity.name.split('/')[2].trim()); this.wrapperElement.classList.add('ghost'); ghostNotification = document.createElement("span"); ghostNotification.classList.add('ghostNotification'); msg = gettext('Warning: %(type)s not found!'); msg = interpolate(msg, {type: type}, true); ghostNotification.textContent = msg; this.header.appendChild(ghostNotification); } // Version Status if (type == 'operator' && this.wiringEditor.operatorVersions[this.vendor + '/' + this.name] && this.wiringEditor.operatorVersions[this.vendor + '/' + this.name].lastVersion.compareTo(this.version) > 0) { // Old Entity Version this.versionStatus = document.createElement("span"); this.versionStatus.classList.add('status'); this.versionStatus.classList.add('icon-exclamation-sign'); this.versionStatus.setAttribute('title', 'Outdated Version (' + this.version.text + ')'); this.header.appendChild(this.versionStatus); this.wrapperElement.classList.add('old') } // Widget name this.nameElement = document.createElement("span"); this.nameElement.textContent = title; this.nameElement.title = title; this.header.appendChild(this.nameElement); // Close button del_button = new StyledElements.StyledButton({ 'title': gettext("Remove"), 'class': 'closebutton icon-remove', 'plain': true }); del_button.insertInto(this.header); del_button.addEventListener('click', function () { if (this.readOnly == true) { return; } if (className == 'iwidget') { this.wiringEditor.events.widgetremoved.dispatch(this); } else { this.wiringEditor.events.operatorremoved.dispatch(this); } }.bind(this)); // Log button this.log_button = new StyledElements.StyledButton({ 'plain': true, 'class': 'logbutton icon-warning-sign' }); if (!isGhost) { this.log_button.addEventListener("click", function () { var dialog = new Wirecloud.ui.LogWindowMenu(this.entity.logManager); dialog.show(); }.bind(this)); updateErrorInfo.call(this); this.entity.logManager.addEventListener('newentry', updateErrorInfo.bind(this)); } else { this.log_button.disable(); } this.log_button.insertInto(this.header); // special icon for minimized interface this.iconAux = document.createElement("div"); this.iconAux.classList.add("specialIcon"); this.iconAux.classList.add("icon-cogs"); this.iconAux.setAttribute('title', title); this.resourcesDiv.wrapperElement.appendChild(this.iconAux); this.iconAux.addEventListener('click', function () { if (!this.movement) { this.restore(); } }.bind(this)); // Add a menu button except on mini interfaces this.menu_button = new StyledElements.PopupButton({ 'title': gettext("Menu"), 'class': 'editPos_button icon-cog', 'plain': true }); this.menu_button.insertInto(this.header); this.menu_button.popup_menu.append(new Wirecloud.ui.WiringEditor.GenericInterfaceSettingsMenuItems(this)); } else { // MiniInterface this.header = document.createElement("div"); this.header.classList.add('header'); this.wrapperElement.appendChild(this.header); // MiniInterface name this.nameElement = document.createElement("span"); this.nameElement.textContent = title; this.header.appendChild(this.nameElement); // MiniInterface status this.miniStatus = document.createElement("span"); this.miniStatus.classList.add('status'); this.miniStatus.classList.add('icon-exclamation-sign'); this.miniStatus.setAttribute('title', gettext('Warning! this is an old version of the operator, click to change the version')); this._miniwidgetMenu_button_callback = function _miniwidgetMenu_button_callback(e) { // Context Menu e.stopPropagation(); if (this.contextmenu.isVisible()) { this.contextmenu.hide(); } else { this.contextmenu.show(this.wrapperElement.getBoundingClientRect()); } return; }.bind(this); this.miniStatus.addEventListener('mousedown', Wirecloud.Utils.stopPropagationListener, false); this.miniStatus.addEventListener('click', this._miniwidgetMenu_button_callback, false); this.miniStatus.addEventListener('contextmenu', this._miniwidgetMenu_button_callback, false); this.header.appendChild(this.miniStatus); // MiniInterface Context Menu if (className == 'ioperator') { this.contextmenu = new StyledElements.PopupMenu({'position': ['bottom-left', 'top-left']}); this._miniwidgetMenu_callback = function _miniwidgetMenu_callback(e) { // Context Menu e.stopPropagation(); if (e.button === 2) { if (this.contextmenu.isVisible()) { this.contextmenu.hide(); } else { this.contextmenu.show(this.wrapperElement.getBoundingClientRect()); } return; } }.bind(this); this.wrapperElement.addEventListener('mousedown', this._miniwidgetMenu_callback, false); this.contextmenu.append(new Wirecloud.ui.WiringEditor.MiniInterfaceSettingsMenuItems(this)); } this.wrapperElement.addEventListener('contextmenu', Wirecloud.Utils.preventDefaultListener); } // Draggable if (!this.isMiniInterface) { this.makeDraggable(); } else { //miniInterface this.draggable = new Wirecloud.ui.Draggable(this.wrapperElement, {iObject: this}, function onStart(draggable, context) { var miniwidget_clon, pos_miniwidget, headerHeight; headerHeight = context.iObject.wiringEditor.getBoundingClientRect().top; //initial position pos_miniwidget = context.iObject.getBoundingClientRect(); context.y = pos_miniwidget.top - (headerHeight); context.x = pos_miniwidget.left; //create a miniwidget clon if (context.iObject instanceof Wirecloud.ui.WiringEditor.WidgetInterface) { miniwidget_clon = new Wirecloud.ui.WiringEditor.WidgetInterface(context.iObject.wiringEditor, context.iObject.iwidget, context.iObject.wiringEditor, true); } else { miniwidget_clon = new Wirecloud.ui.WiringEditor.OperatorInterface(context.iObject.wiringEditor, context.iObject.ioperator, context.iObject.wiringEditor, true); } miniwidget_clon.addClassName('clon'); //set the clon position over the originar miniWidget miniwidget_clon.setBoundingClientRect(pos_miniwidget, {top: -headerHeight, left: 0, width: -2, height: -10}); // put the miniwidget clon in the layout context.iObject.wiringEditor.layout.wrapperElement.appendChild(miniwidget_clon.wrapperElement); //put the clon in the context.iObject context.iObjectClon = miniwidget_clon; }, function onDrag(e, draggable, context, xDelta, yDelta) { context.iObjectClon.setPosition({posX: context.x + xDelta, posY: context.y + yDelta}); context.iObjectClon.repaint(); }, this.onFinish.bind(this), function () { return this.enabled && !this.wrapperElement.classList.contains('clon'); }.bind(this) ); }//else miniInterface }; GenericInterface.prototype = new StyledElements.Container({'extending': true}); /************************************************************************* * Private methods *************************************************************************/ var getElementPos = function getElementPos(elemList, elem) { var i; for (i = 0; i < elemList.length; i++) { if (elem === elemList[i]) { return i; } } }; /** * @Private * is empty object? */ var isEmpty = function isEmpty(obj) { for(var key in obj) { return false; } return true; }; var createMulticonnector = function createMulticonnector(name, anchor) { var multiconnector; multiconnector = new Wirecloud.ui.WiringEditor.Multiconnector(this.wiringEditor.nextMulticonnectorId, this.getId(), name, this.wiringEditor.layout.getCenterContainer().wrapperElement, this.wiringEditor, anchor, null, null); this.wiringEditor.nextMulticonnectorId = parseInt(this.wiringEditor.nextMulticonnectorId, 10) + 1; this.wiringEditor.addMulticonnector(multiconnector); multiconnector.addMainArrow(); }; /** * OutputSubendpoint */ var OutputSubendpoint = function OutputSubendpoint(name, description, iwidget, type) { var nameList, subdata, i; this.iwidget = iwidget; this.name = name; this.subdata = description.subdata; this.variable = description; this.type = type; this.friendcode = description.friendcode; nameList = name.split('/'); subdata = JSON.parse(description.subdata); for (i = 1; i < nameList.length; i++) { if (nameList[0] == nameList[1]) { break; } subdata = subdata[nameList[i]]; this.friendcode = subdata.semanticType; subdata = subdata.subdata; } }; /** * Serialize OutputSubendpoint */ OutputSubendpoint.prototype.serialize = function serialize() { return { 'type': this.type, 'id': this.iwidget.id, 'endpoint': this.name }; }; /** * Set ActionLabel listeners in a endpoint */ var setlabelActionListeners = function setlabelActionListeners(labelActionLayer, checkbox) { // Emphasize listeners labelActionLayer.addEventListener('mouseover',function (thecheckbox) { this.wiringEditor.recommendations.emphasize(thecheckbox); }.bind(this, checkbox), false); labelActionLayer.addEventListener('mouseout',function (thecheckbox) { this.wiringEditor.recommendations.deemphasize(thecheckbox); }.bind(this, checkbox), false); checkbox.wrapperElement.addEventListener('mouseover',function (thecheckbox) { this.wiringEditor.recommendations.emphasize(thecheckbox); }.bind(this, checkbox), false); checkbox.wrapperElement.addEventListener('mouseout',function (thecheckbox) { this.wiringEditor.recommendations.deemphasize(thecheckbox); }.bind(this, checkbox), false); // Sticky effect labelActionLayer.addEventListener('mouseover', checkbox._mouseover_callback, false); labelActionLayer.addEventListener('mouseout', checkbox._mouseout_callback, false); // Connect anchor whith mouseup on the label labelActionLayer.addEventListener('mouseup', checkbox._mouseup_callback, false); }; /** * format Tree */ var formatTree = function(treeDiv, entityWidth) { var heightPerLeaf, branchList, i, j, nleafsAux, desp, checkbox, label, height, firstFrame, firstTree, width, diff, treeWidth, actionLayer, bounding, treeBounding, leafs, lastTop, subtrees; firstFrame = treeDiv.getElementsByClassName("labelsFrame")[0]; firstTree = treeDiv.getElementsByClassName("tree")[0]; diff = (firstTree.getBoundingClientRect().top - firstFrame.getBoundingClientRect().top); if (diff == -10) { return; } firstFrame.style.top = diff + 10 + 'px'; height = firstFrame.getBoundingClientRect().height + 10; width = firstFrame.getBoundingClientRect().width; firstTree.style.height = height + 10 + 'px'; treeWidth = treeDiv.getBoundingClientRect().width; if (treeWidth < entityWidth - 14) { treeDiv.style.width = entityWidth - 14 + 'px'; treeDiv.style.left = 7 + 'px'; } treeDiv.style.height = height + 'px'; // Vertical Alignment leafs = treeDiv.getElementsByClassName('leaf'); heightPerLeaf = height/leafs.length; branchList = treeDiv.getElementsByClassName("dataTree branch"); for (i = 0; i < branchList.length; i++) { // Set Label position nleafsAux = branchList[i].getElementsByClassName('leaf').length; desp = -(((nleafsAux / 2) * heightPerLeaf) - (heightPerLeaf / 2)); label = branchList[i].getElementsByClassName('labelTree')[branchList[i].getElementsByClassName('labelTree').length - 1]; // Set label and anchor position checkbox = branchList[i].getElementsByClassName('subAnchor')[branchList[i].getElementsByClassName('subAnchor').length - 1]; label.style.top = desp + 'px'; checkbox.style.top = desp + 'px'; // Set action layer bounding for the label treeBounding = branchList[i].getBoundingClientRect(); if (i == 0) { lastTop = treeBounding.top; } actionLayer = branchList[i].nextElementSibling; bounding = label.getBoundingClientRect(); actionLayer.style.height = bounding.height + 'px'; actionLayer.style.width = bounding.width + 'px'; actionLayer.style.left = (bounding.left - treeBounding.left) + 'px'; actionLayer.style.top = Math.abs(lastTop - bounding.top) + 'px'; lastTop = treeBounding.top + 1; // Set leaf action layers setLeafActionLayers(branchList[i].parentNode.children); // Set leaf action layers in only-leafs subtree if (branchList[i].getElementsByClassName("dataTree branch").length == 0) { subtrees = branchList[i].getElementsByClassName('subTree'); for (j = 0; j < subtrees.length; j++) { // All leafs subtree found setLeafActionLayers(subtrees[j].getElementsByClassName('labelsFrame')[0].children); } } } }; var setLeafActionLayers = function setLeafActionLayers (brothers) { var acumulatedTop, j, treeBounding, bounding, actionLayer; acumulatedTop = 5; for (j = 0; j < brothers.length; j += 2) { treeBounding = brothers[j].getBoundingClientRect(); if (brothers[j].hasClassName('dataTree leaf')) { bounding = brothers[j].getElementsByClassName('labelTree')[0].getBoundingClientRect(); actionLayer = brothers[j].nextElementSibling; actionLayer.style.height = bounding.height + 'px'; actionLayer.style.width = bounding.width + 'px'; actionLayer.style.left = (bounding.left - treeBounding.left) + 'px'; actionLayer.style.top = acumulatedTop + 'px'; } acumulatedTop += treeBounding.height; } }; /************************************************************************* * Public methods *************************************************************************/ /** * Making Interface Draggable. */ GenericInterface.prototype.makeDraggable = function makeDraggable() { this.draggable = new Wirecloud.ui.Draggable(this.wrapperElement, {iObject: this}, function onStart(draggable, context) { context.y = context.iObject.wrapperElement.style.top === "" ? 0 : parseInt(context.iObject.wrapperElement.style.top, 10); context.x = context.iObject.wrapperElement.style.left === "" ? 0 : parseInt(context.iObject.wrapperElement.style.left, 10); context.preselected = context.iObject.selected; context.iObject.select(true); context.iObject.wiringEditor.onStarDragSelected(); }, function onDrag(e, draggable, context, xDelta, yDelta) { context.iObject.setPosition({posX: context.x + xDelta, posY: context.y + yDelta}); context.iObject.repaint(); context.iObject.wiringEditor.onDragSelectedObjects(xDelta, yDelta); }, function onFinish(draggable, context) { context.iObject.wiringEditor.onFinishSelectedObjects(); var position = context.iObject.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } context.iObject.setPosition(position); context.iObject.repaint(); //pseudoClick if ((Math.abs(context.x - position.posX) < 2) && (Math.abs(context.y - position.posY) < 2)) { if (context.preselected) { context.iObject.unselect(true); } context.iObject.movement = false; } else { if (!context.preselected) { context.iObject.unselect(true); } context.iObject.movement = true; } }, function () {return true; } ); }; /** * Make draggable all sources and targets for sorting */ GenericInterface.prototype.makeSlotsDraggable = function makeSlotsDraggable() { var i; for (i = 0; i < this.draggableSources.length; i++) { this.makeSlotDraggable(this.draggableSources[i], this.wiringEditor.layout.center, 'source_clon'); } for (i = 0; i < this.draggableTargets.length; i++) { this.makeSlotDraggable(this.draggableTargets[i], this.wiringEditor.layout.center, 'target_clon'); } }; /** * Make draggable a specific sources or targets for sorting */ GenericInterface.prototype.makeSlotDraggable = function makeSlotDraggable(element, place, className) { element.draggable = new Wirecloud.ui.Draggable(element.wrapperElement, {iObject: element, genInterface: this, wiringEditor: this.wiringEditor}, function onStart(draggable, context) { var clon, pos_miniwidget, gridbounds, childsN, childPos; //initial position pos_miniwidget = context.iObject.wrapperElement.getBoundingClientRect(); gridbounds = context.wiringEditor.getGridElement().getBoundingClientRect(); context.y = pos_miniwidget.top - gridbounds.top; context.x = pos_miniwidget.left - gridbounds.left; //create clon context.iObject.wrapperElement.classList.add('moving'); clon = context.iObject.wrapperElement.cloneNode(true); clon.classList.add(className); // put the clon in place place.wrapperElement.appendChild(clon); //set the clon position over the originar miniWidget clon.style.height = (pos_miniwidget.height) + 'px'; clon.style.left = (context.x) + 'px'; clon.style.top = (context.y) + 'px'; clon.style.width = (pos_miniwidget.width) + 'px'; //put the clon in the context.iObjectClon context.iObjectClon = clon; //put the reference height for change position context.refHeigth = context.iObject.wrapperElement.getBoundingClientRect().height + 2; context.refHeigthUp = context.refHeigth; context.refHeigthDown = context.refHeigth; childsN = context.iObject.wrapperElement.parentNode.childElementCount; childPos = getElementPos(context.iObject.wrapperElement.parentNode.children, context.iObject.wrapperElement); context.maxUps = childPos; context.maxDowns = childsN - (childPos + 1); }, function onDrag(e, draggable, context, xDelta, yDelta) { var top; context.iObjectClon.style.left = (context.x + xDelta) + 'px'; context.iObjectClon.style.top = (context.y + yDelta) + 'px'; top = parseInt(context.iObjectClon.style.top, 10); if (((context.y - top) > context.refHeigthUp) && (context.maxUps > 0)) { context.maxDowns += 1; context.maxUps -= 1; context.refHeigthUp += context.refHeigth; context.refHeigthDown -= context.refHeigth; context.genInterface.up(context.iObject); } else if (((top - context.y) > context.refHeigthDown) && (context.maxDowns > 0)) { context.maxUps += 1; context.maxDowns -= 1; context.refHeigthDown += context.refHeigth; context.refHeigthUp -= context.refHeigth; context.genInterface.down(context.iObject); } }, function onFinish(draggable, context) { context.iObject.wrapperElement.classList.remove('moving'); if (context.iObjectClon.parentNode) { context.iObjectClon.parentNode.removeChild(context.iObjectClon); } context.iObjectClon = null; }, function () {return true; } ); }; /** * Get the GenericInterface position. */ GenericInterface.prototype.getPosition = function getPosition() { var coordinates = {posX: this.wrapperElement.offsetLeft, posY: this.wrapperElement.offsetTop}; return coordinates; }; /** * Get the GenericInterface style position. */ GenericInterface.prototype.getStylePosition = function getStylePosition() { var coordinates; coordinates = {posX: parseInt(this.wrapperElement.style.left, 10), posY: parseInt(this.wrapperElement.style.top, 10)}; return coordinates; }; /** * Gets an anchor given a name */ GenericInterface.prototype.getAnchor = function getAnchor(name) { if (name in this.sourceAnchorsByName) { return this.sourceAnchorsByName[name]; } else if (name in this.targetAnchorsByName) { return this.targetAnchorsByName[name]; } else { return null; } }; /** * Add Ghost Endpoint */ GenericInterface.prototype.addGhostEndpoint = function addGhostEndpoint(theEndpoint, isSource) { var context; if (isSource) { context = {'data': new Wirecloud.wiring.GhostSourceEndpoint(theEndpoint, this.entity), 'iObject': this}; this.addSource(theEndpoint.endpoint, '', theEndpoint.endpoint, context, true); return this.sourceAnchorsByName[theEndpoint.endpoint]; } else { context = {'data': new Wirecloud.wiring.GhostTargetEndpoint(theEndpoint, this.entity), 'iObject': this}; this.addTarget(theEndpoint.endpoint, '', theEndpoint.endpoint, context, true); return this.targetAnchorsByName[theEndpoint.endpoint]; } }; /** * Set the GenericInterface position. */ GenericInterface.prototype.setPosition = function setPosition(coordinates) { this.wrapperElement.style.left = coordinates.posX + 'px'; this.wrapperElement.style.top = coordinates.posY + 'px'; }; /** * Set the BoundingClientRect parameters */ GenericInterface.prototype.setBoundingClientRect = function setBoundingClientRect(BoundingClientRect, move) { this.wrapperElement.style.height = (BoundingClientRect.height + move.height) + 'px'; this.wrapperElement.style.left = (BoundingClientRect.left + move.left) + 'px'; this.wrapperElement.style.top = (BoundingClientRect.top + move.top) + 'px'; this.wrapperElement.style.width = (BoundingClientRect.width + move.width) + 'px'; }; /** * Set the initial position in the menubar, miniobjects. */ GenericInterface.prototype.setMenubarPosition = function setMenubarPosition(menubarPosition) { this.menubarPosition = menubarPosition; }; /** * Set the initial position in the menubar, miniobjects. */ GenericInterface.prototype.getMenubarPosition = function getMenubarPosition() { return this.menubarPosition; }; /** * Increasing the number of read only connections */ GenericInterface.prototype.incReadOnlyConnectionsCount = function incReadOnlyConnectionsCount() { this.readOnlyEndpoints += 1; this.readOnly = true; }; /** * Reduce the number of read only connections */ GenericInterface.prototype.reduceReadOnlyConnectionsCount = function reduceReadOnlyConnectionsCount() { this.readOnlyEndpoints -= 1; if (this.readOnlyEndpoints == 0) { this.readOnly = false; } }; /** * Generic repaint */ GenericInterface.prototype.repaint = function repaint(temporal) { var key; StyledElements.Container.prototype.repaint.apply(this, arguments); for (key in this.sourceAnchorsByName) { this.sourceAnchorsByName[key].repaint(temporal); } for (key in this.targetAnchorsByName) { this.targetAnchorsByName[key].repaint(temporal); } }; /** * Generate SubTree */ GenericInterface.prototype.generateSubTree = function generateSubTree(anchorContext, subAnchors) { var treeFrame, key, lab, checkbox, subdata, subTree, labelsFrame, context, name, labelActionLayer, entity, type; treeFrame = document.createElement("div"); treeFrame.classList.add('subTree'); labelsFrame = document.createElement("div"); labelsFrame.classList.add('labelsFrame'); treeFrame.appendChild(labelsFrame); if (!isEmpty(subAnchors.subdata)) { for (key in subAnchors.subdata) { lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = subAnchors.subdata[key].label; name = anchorContext.data.name + "/" + key; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors.subdata[key]); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); subTree = this.generateSubTree(context, subAnchors.subdata[key], checkbox); if (subTree !== null) { subdata.appendChild(subTree); subdata.classList.add("branch"); } else{ subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelsFrame.appendChild(subdata); labelsFrame.appendChild(labelActionLayer); } return treeFrame; } else { return null; } }; /** * Generate Tree */ GenericInterface.prototype.generateTree = function generateTree(anchor, name, anchorContext, subtree, label, closeHandler) { var subAnchors, treeFrame, lab, checkbox, subdata, key, subTree, subTreeFrame, type, labelsFrame, labelMain, close_button, context, name, labelActionLayer, entity, treeDiv; // Generate tree treeDiv = document.createElement("div"); treeDiv.classList.add('anchorTree'); treeDiv.addEventListener('click', function (e) { e.stopPropagation(); }.bind(this), false); treeDiv.addEventListener('mousedown', function (e) { e.stopPropagation(); }.bind(this), false); treeFrame = document.createElement("div"); treeFrame.classList.add('tree'); treeFrame.classList.add('sources'); // Close button close_button = new StyledElements.StyledButton({ 'title': gettext("Hide"), 'class': 'hideTreeButton icon-off', 'plain': true }); close_button.insertInto(treeFrame); close_button.addEventListener('click', function () {closeHandler();}, false); subAnchors = JSON.parse(subtree); subTreeFrame = null; labelsFrame = document.createElement("div"); labelsFrame.classList.add('labelsFrame'); if (subAnchors !== null) { subTreeFrame = document.createElement("div"); subTreeFrame.classList.add('subTree'); for (key in subAnchors) { lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = subAnchors[key].label; name = anchorContext.data.name + "/" + key; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors[key]); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); subTree = this.generateSubTree(context, subAnchors[key], checkbox); if (subTree !== null) { subdata.appendChild(subTree); subdata.classList.add("branch"); } else{ subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelsFrame.appendChild(subdata); labelsFrame.appendChild(labelActionLayer); subTreeFrame.appendChild(labelsFrame); } } lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = label; name = anchorContext.data.name + "/" + anchorContext.data.name; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); if (subTreeFrame !== null) { subdata.appendChild(subTreeFrame); subdata.classList.add("branch"); } else { subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelMain = document.createElement("div"); labelMain.classList.add('labelsFrame'); labelMain.appendChild(subdata); labelMain.appendChild(labelActionLayer); treeFrame.appendChild(labelMain); treeDiv.appendChild(treeFrame); this.wrapperElement.appendChild(treeDiv); // Handler for subdata tree menu anchor.menu.append(new StyledElements.MenuItem(gettext("Unfold data structure"), this.subdataHandler.bind(this, treeDiv, name))); }; /** * handler for show/hide anchorTrees */ GenericInterface.prototype.subdataHandler = function subdataHandler(treeDiv, name) { var initialHeiht, initialWidth, key, i, externalRep, layer, subDataArrow, firstIndex, mainEndpoint, mainSubEndPoint, theArrow, mainEndpointArrows; if (treeDiv == null) { // Descend canvas this.wiringEditor.canvas.canvasElement.classList.remove("elevated"); // Hide tree this.activatedTree.classList.remove('activated'); this.activatedTree = null; // Deactivate subdataMode this.wrapperElement.classList.remove('subdataMode'); // Hide subdata connections, and show hollow and full connections if (!isEmpty(this.subdataConnections[name])) { for (key in this.subdataConnections[name]) { firstIndex = this.subdataConnections[name][key].length - 1; for (i = firstIndex; i >= 0 ; i -= 1) { externalRep = this.subdataConnections[name][key][i].externalRep; subDataArrow = this.subdataConnections[name][key][i].subDataArrow; externalRep.show(); if (externalRep.hasClassName('hollow')) { subDataArrow.hide(); } else { // Remove all subconnections that represent full connections subDataArrow.destroy(); this.subdataConnections[name][key].splice(i, 1); this.fullConnections[name][key].splice(this.fullConnections[name][key].indexOf(externalRep), 1); } } } } } else { // Elevate canvas this.wiringEditor.canvas.canvasElement.classList.add("elevated"); // Show tree initialWidth = this.wrapperElement.getBoundingClientRect().width; treeDiv.classList.add('activated'); this.activatedTree = treeDiv; formatTree(treeDiv, initialWidth); // Activate subdataMode this.wrapperElement.classList.add('subdataMode'); // Add a subconnection for each main connexion in the main endpoint layer = this.wiringEditor.arrowCreator.layer; mainEndpoint = this.sourceAnchorsByName[name]; mainSubEndPoint = this.sourceAnchorsByName[name + "/" + name]; mainEndpointArrows = mainEndpoint.getArrows(); for (i = 0; i < mainEndpointArrows.length ; i += 1) { if (!mainEndpointArrows[i].hasClassName('hollow')) { // New full subConnection theArrow = this.wiringEditor.canvas.drawArrow(mainSubEndPoint.getCoordinates(layer), mainEndpointArrows[i].endAnchor.getCoordinates(layer), "arrow subdataConnection full"); theArrow.setEndAnchor(mainEndpointArrows[i].endAnchor); theArrow.setStartAnchor(mainSubEndPoint); mainSubEndPoint.addArrow(theArrow); mainEndpointArrows[i].endAnchor.addArrow(theArrow); // Add this connections to subdataConnections if (this.subdataConnections[name] == null) { this.subdataConnections[name] = {}; } if (this.subdataConnections[name][name + "/" + name] == null) { this.subdataConnections[name][name + "/" + name] = []; } this.subdataConnections[name][name + "/" + name].push({'subDataArrow' : theArrow, 'externalRep': mainEndpointArrows[i]}); // Add this connections to fullConnections if (this.fullConnections[name] == null) { this.fullConnections[name] = {}; } if (this.fullConnections[name][name + "/" + name] == null) { this.fullConnections[name][name + "/" + name] = []; } this.fullConnections[name][name + "/" + name].push(mainEndpointArrows[i]); } } // Show subdata connections, and hide hollow connections for (key in this.subdataConnections[name]) { for (i = 0; i < this.subdataConnections[name][key].length ; i += 1) { this.subdataConnections[name][key][i].externalRep.hide(); this.subdataConnections[name][key][i].subDataArrow.show(); } } } this.repaint(); this.wiringEditor.activatedTree = this.activatedTree; }; /** * Add subdata connection. */ GenericInterface.prototype.addSubdataConnection = function addSubdataConnection(endpoint, subdatakey, connection, sourceAnchor, targetAnchor, isLoadingWiring) { var theArrow, mainEndpoint, layer; if (this.subdataConnections[endpoint] == null) { this.subdataConnections[endpoint] = {}; } if (this.subdataConnections[endpoint][subdatakey] == null) { this.subdataConnections[endpoint][subdatakey] = []; } layer = this.wiringEditor.arrowCreator.layer; mainEndpoint = this.sourceAnchorsByName[endpoint]; if ((endpoint + "/" + endpoint) == subdatakey) { // Add full connection if (this.fullConnections[endpoint] == null) { this.fullConnections[endpoint] = {}; } if (this.fullConnections[endpoint][subdatakey] == null) { this.fullConnections[endpoint][subdatakey] = []; } connection.addClassName('full'); theArrow = this.wiringEditor.canvas.drawArrow(mainEndpoint.getCoordinates(layer), targetAnchor.getCoordinates(layer), "arrow"); this.fullConnections[endpoint][subdatakey].push(theArrow); } else { // Add a hollow connection if (this.hollowConnections[endpoint] == null) { this.hollowConnections[endpoint] = {}; } if (this.hollowConnections[endpoint][subdatakey] == null) { this.hollowConnections[endpoint][subdatakey] = []; } theArrow = this.wiringEditor.canvas.drawArrow(mainEndpoint.getCoordinates(layer), targetAnchor.getCoordinates(layer), "arrow hollow"); this.hollowConnections[endpoint][subdatakey].push(theArrow); } theArrow.setEndAnchor(targetAnchor); theArrow.setStartAnchor(mainEndpoint); mainEndpoint.addArrow(theArrow); targetAnchor.addArrow(theArrow); if (isLoadingWiring) { connection.hide(); } else { theArrow.hide(); } this.subdataConnections[endpoint][subdatakey].push({'subDataArrow' : connection, 'externalRep': theArrow}); }; /** * Remove subdata connection. */ GenericInterface.prototype.removeSubdataConnection = function removeSubdataConnection(endpoint, subdatakey, connection) { var i, externalRep; if ((endpoint + "/" + endpoint) == subdatakey) { // Remove full connection if (this.fullConnections[endpoint] != null && this.fullConnections[endpoint][subdatakey] != null) { for (i = 0; i < this.subdataConnections[endpoint][subdatakey].length ; i += 1) { if (this.subdataConnections[endpoint][subdatakey][i].subDataArrow == connection) { externalRep = this.subdataConnections[endpoint][subdatakey][i].externalRep; this.fullConnections[endpoint][subdatakey].splice(this.fullConnections[endpoint][subdatakey].indexOf(externalRep), 1); externalRep.destroy(); connection.destroy(); this.subdataConnections[endpoint][subdatakey].splice(i, 1); break; } } } else { // Error } } else { // Remove a hollow connection if (this.hollowConnections[endpoint] != null && this.hollowConnections[endpoint][subdatakey] != null) { for (i = 0; i < this.subdataConnections[endpoint][subdatakey].length ; i += 1) { if (this.subdataConnections[endpoint][subdatakey][i].subDataArrow == connection) { externalRep = this.subdataConnections[endpoint][subdatakey][i].externalRep; this.hollowConnections[endpoint][subdatakey].splice(this.hollowConnections[endpoint][subdatakey].indexOf(externalRep), 1); externalRep.destroy(); connection.destroy(); this.subdataConnections[endpoint][subdatakey].splice(i, 1); break; } } } else { // Error } } }; /** * Add Source. */ GenericInterface.prototype.addSource = function addSource(label, desc, name, anchorContext, isGhost) { var anchor, anchorDiv, labelDiv, anchorLabel, treeDiv, subAnchors; // Sources counter this.numberOfSources += 1; // AnchorDiv anchorDiv = document.createElement("div"); // If the output have not description, take the label if (desc === '') { desc = label; } if (isGhost) { anchorDiv.setAttribute('title', gettext("Mismatch endpoint! ") + label); } else { anchorDiv.setAttribute('title', label + ': ' + desc); } anchorDiv.classList.add('anchorDiv'); if (isGhost) { anchorDiv.classList.add('ghost'); } // Anchor visible label anchorLabel = document.createElement("span"); anchorLabel.textContent = label; labelDiv = document.createElement("div"); anchorDiv.appendChild(labelDiv); labelDiv.setAttribute('class', 'labelDiv'); labelDiv.appendChild(anchorLabel); if (!this.isMiniInterface) { anchor = new Wirecloud.ui.WiringEditor.SourceAnchor(anchorContext, this.arrowCreator, null, isGhost); labelDiv.appendChild(anchor.wrapperElement); anchor.menu.append(new StyledElements.MenuItem(gettext('Add multiconnector'), createMulticonnector.bind(this, name, anchor))); subAnchors = anchorContext.data.subdata; if (subAnchors != null) { // Generate the tree this.generateTree(anchor, name, anchorContext, subAnchors, label, this.subdataHandler.bind(this, null, name)); } labelDiv.addEventListener('mouseover', function () { this.wiringEditor.recommendations.emphasize(anchor); }.bind(this)); labelDiv.addEventListener('mouseout', function () { this.wiringEditor.recommendations.deemphasize(anchor); }.bind(this)); // Sticky effect anchorDiv.addEventListener('mouseover', function (e) { anchor._mouseover_callback(e); }.bind(this)); anchorDiv.addEventListener('mouseout', function (e) { anchor._mouseout_callback(e); }.bind(this)); // Connect anchor whith mouseup on the label anchorDiv.addEventListener('mouseup', function (e) { anchor._mouseup_callback(e); }.bind(this)); this.sourceAnchorsByName[name] = anchor; this.sourceAnchors.push(anchor); } this.sourceDiv.appendChild(anchorDiv); this.draggableSources.push({'wrapperElement': anchorDiv, 'context': anchorContext}); }; /** * Add Target. */ GenericInterface.prototype.addTarget = function addTarget(label, desc, name, anchorContext, isGhost) { var anchor, anchorDiv, labelDiv, anchorLabel; // Targets counter this.numberOfTargets += 1; // AnchorDiv anchorDiv = document.createElement("div"); // If the output have not description, take the label if (desc === '') { desc = label; } if (isGhost) { anchorDiv.setAttribute('title', gettext('Mismatch endpoint! ') + label); } else { anchorDiv.setAttribute('title', label + ': ' + desc); } anchorDiv.classList.add('anchorDiv'); if (isGhost) { anchorDiv.classList.add('ghost'); } // Anchor visible label anchorLabel = document.createElement("span"); anchorLabel.textContent = label; labelDiv = document.createElement("div"); anchorDiv.appendChild(labelDiv); labelDiv.setAttribute('class', 'labelDiv'); labelDiv.appendChild(anchorLabel); if (!this.isMiniInterface) { anchor = new Wirecloud.ui.WiringEditor.TargetAnchor(anchorContext, this.arrowCreator, isGhost); labelDiv.appendChild(anchor.wrapperElement); anchor.menu.append(new StyledElements.MenuItem(gettext('Add multiconnector'), createMulticonnector.bind(this, name, anchor))); labelDiv.addEventListener('mouseover', function () { if (!this.wiringEditor.recommendationsActivated) { this.wiringEditor.recommendations.emphasize(anchor); } }.bind(this)); labelDiv.addEventListener('mouseout', function () { if (!this.wiringEditor.recommendationsActivated) { this.wiringEditor.recommendations.deemphasize(anchor); } }.bind(this)); // Sticky effect anchorDiv.addEventListener('mouseover', function (e) { anchor._mouseover_callback(e); }.bind(this)); anchorDiv.addEventListener('mouseout', function (e) { anchor._mouseout_callback(e); }.bind(this)); // Connect anchor whith mouseup on the label anchorDiv.addEventListener('mouseup', function (e) { anchor._mouseup_callback(e); }.bind(this)); this.targetAnchorsByName[name] = anchor; this.targetAnchors.push(anchor); } this.targetDiv.appendChild(anchorDiv); this.draggableTargets.push({'wrapperElement': anchorDiv, 'context': anchorContext}); }; /** * Add new class in to the genericInterface */ GenericInterface.prototype.addClassName = function addClassName(className) { var atr; if (className == null) { return; } atr = this.wrapperElement.getAttribute('class'); if (atr == null) { atr = ''; } this.wrapperElement.setAttribute('class', Wirecloud.Utils.appendWord(atr, className)); }; /** * Remove a genericInterface Class name */ GenericInterface.prototype.removeClassName = function removeClassName(className) { var atr; if (className == null) { return; } atr = this.wrapperElement.getAttribute('class'); if (atr == null) { atr = ''; } this.wrapperElement.setAttribute('class', Wirecloud.Utils.removeWord(atr, className)); }; /** * Select this genericInterface */ GenericInterface.prototype.select = function select(withCtrl) { var i, j, arrows; if (this.hasClassName('disabled')) { return; } if (this.hasClassName('selected')) { return; } if (!(this.wiringEditor.ctrlPushed) && (this.wiringEditor.selectedCount > 0) && (withCtrl)) { this.wiringEditor.resetSelection(); } this.selected = true; this.addClassName('selected'); // Arrows for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].emphasize(); } } for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].emphasize(); } } this.wiringEditor.addSelectedObject(this); }; /** * Unselect this genericInterface */ GenericInterface.prototype.unselect = function unselect(withCtrl) { var i, j, arrows; this.selected = false; this.removeClassName('selected'); //arrows for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].deemphasize(); } } for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].deemphasize(); } } this.wiringEditor.removeSelectedObject(this); if (!(this.wiringEditor.ctrlPushed) && (this.wiringEditor.selectedCount > 0) && (withCtrl)) { this.wiringEditor.resetSelection(); } }; /** * Destroy */ GenericInterface.prototype.destroy = function destroy() { var i, j, arrows; this.unselect(); if (this.editingPos === true) { this.disableEdit(); } StyledElements.Container.prototype.destroy.call(this); for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows.slice(0); for (j = 0; j < arrows.length; j += 1) { if (!arrows[j].controlledDestruction()) { arrows[j].destroy(); } } this.sourceAnchors[i].destroy(); } for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows.slice(0); for (j = 0; j < arrows.length; j += 1) { if (!arrows[j].controlledDestruction()) { arrows[j].destroy(); } } this.targetAnchors[i].destroy(); } this.draggable.destroy(); this.draggable = null; this.draggableSources = null; this.draggableTargets = null; this.wrapperElement = null; this.hollowConnections = null; this.subdataConnections = null; }; /** * Edit source and targets positions */ GenericInterface.prototype.editPos = function editPos() { var obj; obj = null; if ((this.targetAnchors.length <= 1) && (this.sourceAnchors.length <= 1)) { return; } if (this.editingPos === true) { this.disableEdit(); } else { this.enableEdit(); obj = this; } this.repaint(); return obj; }; /** * Enable poditions editor */ GenericInterface.prototype.enableEdit = function enableEdit() { this.draggable.destroy(); this.editingPos = true; this.sourceDiv.wrapperElement.classList.add("editing"); this.targetDiv.wrapperElement.classList.add("editing"); this.addClassName("editing"); this.makeSlotsDraggable(); }; /** * Disable poditions editor */ GenericInterface.prototype.disableEdit = function disableEdit() { var i; this.makeDraggable(); this.editingPos = false; this.sourceDiv.wrapperElement.classList.remove("editing"); this.targetDiv.wrapperElement.classList.remove("editing"); this.removeClassName("editing"); for (i = 0; i < this.draggableSources.length; i++) { this.draggableSources[i].draggable.destroy(); } for (i = 0; i < this.draggableTargets.length; i++) { this.draggableTargets[i].draggable.destroy(); } }; /** * Move an endpoint up 1 position. */ GenericInterface.prototype.up = function up(element) { element.wrapperElement.parentNode.insertBefore(element.wrapperElement, element.wrapperElement.previousElementSibling); this.repaint(); }; /** * Move an endpoint down 1 position. */ GenericInterface.prototype.down = function down(element) { if (element.wrapperElement.nextElementSibling !== null) { element.wrapperElement.parentNode.insertBefore(element.wrapperElement, element.wrapperElement.nextElementSibling.nextElementSibling); this.repaint(); } }; /** * Get sources and targets titles lists in order to save positions */ GenericInterface.prototype.getInOutPositions = function getInOutPositions() { var i, sources, targets; sources = []; targets = []; for (i = 0; i < this.sourceDiv.wrapperElement.childNodes.length; i++) { sources[i] = this.getNameForSort(this.sourceDiv.wrapperElement.childNodes[i], 'source'); } for (i = 0; i < this.targetDiv.wrapperElement.childNodes.length; i++) { targets[i] = this.getNameForSort(this.targetDiv.wrapperElement.childNodes[i], 'target'); } return {'sources': sources, 'targets': targets}; }; /** * Get the source or target name for the especific node */ GenericInterface.prototype.getNameForSort = function getNameForSort(node, type) { var i, collection; if (type === 'source') { collection = this.draggableSources; } else { collection = this.draggableTargets; } for (i = 0; collection.length; i++) { if (collection[i].wrapperElement === node) { return collection[i].context.data.name; } } }; /** * Change to minimized view for operators */ GenericInterface.prototype.minimize = function minimize(omitEffects) { var position, oc, scrollX, scrollY; if (!omitEffects) { this.resizeTransitStart(); } this.initialPos = this.wrapperElement.getBoundingClientRect(); this.minWidth = this.wrapperElement.style.minWidth; this.wrapperElement.classList.add('reducedInt'); this.wrapperElement.style.minWidth = '55px'; // Scroll correction oc = this.wiringEditor.layout.getCenterContainer(); scrollX = parseInt(oc.wrapperElement.scrollLeft, 10); scrollY = parseInt(oc.wrapperElement.scrollTop, 10); this.wrapperElement.style.top = (this.initialPos.top + scrollY - this.wiringEditor.headerHeight) + ((this.initialPos.height - 8) / 2) - 12 + 'px'; this.wrapperElement.style.left = (this.initialPos.left + scrollX - this.wiringEditor.menubarWidth) + (this.initialPos.width / 2) - 32 + 'px'; // correct it pos if is out of grid position = this.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } this.setPosition(position); this.isMinimized = true; this.repaint(); }; /** * Change to normal view for operators */ GenericInterface.prototype.restore = function restore(omitEffects) { var currentPos, position, oc, scrollX, scrollY; if (!omitEffects) { this.resizeTransitStart(); } // Scroll correction oc = this.wiringEditor.layout.getCenterContainer(); scrollX = parseInt(oc.wrapperElement.scrollLeft, 10) + 1; scrollY = parseInt(oc.wrapperElement.scrollTop, 10); currentPos = this.wrapperElement.getBoundingClientRect(); this.wrapperElement.style.top = (currentPos.top + scrollY - this.wiringEditor.headerHeight) - ((this.initialPos.height + 8) / 2) + 'px'; this.wrapperElement.style.left = (currentPos.left + scrollX - this.wiringEditor.menubarWidth) - (this.initialPos.width / 2) + 32 + 'px'; // correct it position if is out of grid position = this.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } this.setPosition(position); this.wrapperElement.style.minWidth = this.minWidth; this.wrapperElement.classList.remove('reducedInt'); this.isMinimized = false; this.repaint(); }; /** * Resize Transit Start */ GenericInterface.prototype.resizeTransitStart = function resizeTransitStart() { var interval; // transition events this.wrapperElement.classList.add('flex'); /*this.wrapperElement.addEventListener('webkitTransitionEnd', this.resizeTransitEnd.bind(this), false); this.wrapperElement.addEventListener('transitionend', this.resizeTransitEnd.bind(this), false); this.wrapperElement.addEventListener('oTransitionEnd', this.resizeTransitEnd.bind(this), false);*/ interval = setInterval(this.animateArrows.bind(this), 20); setTimeout(function () { clearInterval(interval); }, 400); setTimeout(function () { this.resizeTransitEnd(); }.bind(this), 450); }; /** * Resize Transit End */ GenericInterface.prototype.resizeTransitEnd = function resizeTransitEnd() { // transition events this.wrapperElement.classList.remove('flex'); /*this.wrapperElement.removeEventListener('webkitTransitionEnd', this.resizeTransitEnd.bind(this), false); this.wrapperElement.removeEventListener('transitionend', this.resizeTransitEnd.bind(this), false); this.wrapperElement.removeEventListener('oTransitionEnd', this.resizeTransitEnd.bind(this), false);*/ this.repaint(); }; /** * Animated arrows for the transitions betwen minimized an normal shape */ GenericInterface.prototype.animateArrows = function animateArrows() { var key, layer; for (key in this.sourceAnchorsByName) { this.sourceAnchorsByName[key].repaint(); } for (key in this.targetAnchorsByName) { this.targetAnchorsByName[key].repaint(); } if (this.potentialArrow != null) { layer = this.wiringEditor.canvas.getHTMLElement().parentNode; if (this.potentialArrow.startAnchor != null) { // from source to target this.potentialArrow.setStart(this.potentialArrow.startAnchor.getCoordinates(layer)); } else { // from target to source this.potentialArrow.setEnd(this.potentialArrow.endAnchor.getCoordinates(layer)); } } }; /************************************************************************* * Make GenericInterface public *************************************************************************/ Wirecloud.ui.WiringEditor.GenericInterface = GenericInterface; })();
sixuanwang/SAMSaaS
wirecloud-develop/src/wirecloud/platform/static/js/wirecloud/ui/WiringEditor/GenericInterface.js
JavaScript
gpl-2.0
67,661
module.exports = { browserSync: { hostname: "localhost", port: 8080, openAutomatically: false, reloadDelay: 50 }, drush: { enabled: false, alias: 'drush @SITE-ALIAS cache-rebuild' }, twig: { useCache: true } };
erdfisch/DBCD16
web/themes/custom/dbcd_theme_base/example.config.js
JavaScript
gpl-2.0
253
var expect = require('expect.js'); var Quantimodo = require('../../index'); var instance; beforeEach(function(){ instance = new Quantimodo.PostUserSettingsDataResponse(); }); describe('PostUserSettingsDataResponse', function(){ it('should create an instance of PostUserSettingsDataResponse', function(){ // uncomment below and update the code to test PostUserSettingsDataResponse //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be.a(Quantimodo.PostUserSettingsDataResponse); }); it('should have the property purchaseId (base name: "purchaseId")', function(){ // uncomment below and update the code to test the property purchaseId //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property description (base name: "description")', function(){ // uncomment below and update the code to test the property description //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property summary (base name: "summary")', function(){ // uncomment below and update the code to test the property summary //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property errors (base name: "errors")', function(){ // uncomment below and update the code to test the property errors //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function(){ // uncomment below and update the code to test the property status //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property success (base name: "success")', function(){ // uncomment below and update the code to test the property success //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property code (base name: "code")', function(){ // uncomment below and update the code to test the property code //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property link (base name: "link")', function(){ // uncomment below and update the code to test the property link //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property card (base name: "card")', function(){ // uncomment below and update the code to test the property card //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); });
QuantiModo/quantimodo-android-chrome-ios-web-app
plain-javascript-client/test/generated/model/PostUserSettingsDataResponse.spec.js
JavaScript
gpl-2.0
2,975
function updateLabel() { var form = $('contentForm'); var preset_ddm = form.elements['preset']; var presetIndex = preset_ddm[preset_ddm.selectedIndex].value; if ( labels[presetIndex] ) { form.newLabel.value = labels[presetIndex]; } else { form.newLabel.value = ''; } } window.addEvent('domready', updateLabel);
pliablepixels/ZoneMinder
web/skins/classic/views/js/controlpreset.js
JavaScript
gpl-2.0
332
jQuery(function($) { //Get Level 2 Category $('#level1').on("change", ":checkbox", function () { $("#imageloader").show(); if (this.checked) { var parentCat=this.value; // call ajax add_action declared in functions.php $.ajax({ url: "/wp-admin/admin-ajax.php", type:'POST', data:'action=home_category_select_action&parent_cat_ID=' + parentCat, success:function(results) { $("#level2help").hide(); $("#imageloader").hide(); $(".lev1.cat-col").removeClass('dsbl'); //Append all child element in level 2 $("#level2").append(results); } }); } else { //Remove all level 2 element if unchecked $("#imageloader").hide(); $("#getallcat"+this.value).remove(); } }); //Get Level 3 Category $('#level2').on("change", ":checkbox", function () { $("#imageloader2").show(); if (this.checked) { var parentCat=this.value; var parentvalue = $('#parent_id'+parentCat).val(); // call ajax $.ajax({ url: "/wp-admin/admin-ajax.php", type:'POST', data:'action=home_category_select_action&parent_cat_ID=' + parentCat, success:function(results) { $("#level3help").hide(); $(".lev2.cat-col").removeClass('dsbl'); $("#imageloader2").hide(); //Append all child element in level 3 $("#level3").append(results); //Disable parent category $("#level1 input[value='"+parentvalue+"']").prop("disabled", true); // removeChild.push(parentCat); } }); } else { $("#imageloader2").hide(); var parentvalue = $('#parent_id'+this.value).val(); var checkcheckbox=$('#getallcat'+parentvalue+' #parent_cat2').is(':checked'); //check if any child category is checked if(checkcheckbox==false) { //Enable the parent checkbox if unchecked all child element $("#level1 input[value='"+parentvalue+"']").prop("disabled", false); } //Remove all level 3 element if unchecked $("#getallcat"+this.value).remove(); } }); //Load Profile based on tags var list = new Array(); var $container = $('#getTagProfiles'); var $checkboxes = $('#levelContainer input.cb'); $('#levelContainer').on("change", ":checkbox", function () { if (this.checked) { var filterclass=".isoShow"; list.push(this.value); $("#getAllCatId").val(list); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=home_tag_select_action&All_cat_ID=' + list+'&listlength='+list.length, function(response) { $(".firstsearch").remove(); $("#contentSection").remove(); $container.html(response); if(!$container.hasClass('isotope')){ $container.isotope({ filter: filterclass }); } else { $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); } else //If unchecked { var filterclass=".isoShow"; list.splice( $.inArray(this.value,list) ,1 ); $("#getAllCatId").val(list); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=home_tag_select_action&All_cat_ID=' + list+'&listlength='+list.length, function(response) { $(".firstsearch").remove(); $("#contentSection").remove(); $container.html(response); if(!$container.hasClass('isotope')){ $container.isotope({ filter: filterclass }); } else { $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); } }); //Load more $('.more_button').live("click",function() { //var $container2 = $('#getTagProfiles .profile-sec'); var getId = $(this).attr("id"); var getCat= $("#getAllCatId").val(); var filterclass=".isoShow"; if(getId) { $("#load_more_"+getId).html('<img src="/wp-content/themes/marsaec/img/load_img.gif" style="padding:10px 0 0 100px;"/>'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=get_loadmore_profile&getLastContentId='+getId+'&getParentId='+getCat+'&listlength='+getCat.length, function(response) { $container.append(response); if(!$container.hasClass('isotope')){ $("#load_more_"+getId).remove(); $container.isotope({ filter: filterclass }); } else { $("#load_more_"+getId).remove(); $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); // $.ajax({ // type: "POST", // url: "/wp-admin/admin-ajax.php", // data:'action=get_loadmore_profile&getLastContentId='+getId+'&getParentId='+getCat+'&listlength='+getCat.length, // success: function(html){ // $container2.append(html); // $("#load_more_"+getId).remove(); // } // }); } return false; }); });
moveable-dev1/rep1
wp-content/themes/marsaec/js/toggle.js
JavaScript
gpl-2.0
7,013
(function ($) { 'use strict'; function Ninja() { this.keys = { arrowDown: 40, arrowLeft: 37, arrowRight: 39, arrowUp: 38, enter: 13, escape: 27, tab: 9 }; this.version = '0.0.0development'; } Ninja.prototype.log = function (message) { if (console && 'log' in console) { console.log('Ninja: ' + message); } }; Ninja.prototype.warn = function (message) { if (console && 'warn' in console) { console.warn('Ninja: ' + message); } }; Ninja.prototype.error = function (message) { var fullMessage = 'Ninja: ' + message; if (console && 'error' in console) { console.error(fullMessage); } throw fullMessage; }; Ninja.prototype.key = function (code, names) { var keys = this.keys, codes = $.map(names, function (name) { return keys[name]; }); return $.inArray(code, codes) > -1; }; $.Ninja = function (element, options) { if ($.isPlainObject(element)) { this.$element = $('<span>'); this.options = element; } else { this.$element = $(element); this.options = options || {}; } }; $.Ninja.prototype.deselect = function () { if (this.$element.hasClass('nui-slc') && !this.$element.hasClass('nui-dsb')) { this.$element.trigger('deselect.ninja'); } }; $.Ninja.prototype.disable = function () { this.$element.addClass('nui-dsb').trigger('disable.ninja'); }; $.Ninja.prototype.enable = function () { this.$element.removeClass('nui-dsb').trigger('enable.ninja'); }; $.Ninja.prototype.select = function () { if (!this.$element.hasClass('nui-dsb')) { this.$element.trigger('select.ninja'); } }; $.ninja = new Ninja(); $.fn.ninja = function (component, options) { return this.each(function () { if (!$.data(this, 'ninja.' + component)) { $.data(this, 'ninja.' + component); $.ninja[component](this, options); } }); }; }(jQuery));
Bremaweb/streber
js/ninja.js
JavaScript
gpl-2.0
2,022
define([ 'container/BasicContainer', 'text!./CascadeContainer.html', 'core/functions/ComponentFactory', 'jquery', 'underscore' ], function (BasicContainer, template, ComponentFactory, $, _) { var CascadeContainer = BasicContainer.extend({ events: { "click .btn-prev": "clickPrev", "click .btn-next": "clickNext" }, clickPrev: function () { if (this._currentindex > 0) { this._currentindex--; var root = this._containerRoot; var li = root.find('.form-bootstrapWizard>li'); li.removeClass('active'); li.eq(this._currentindex).addClass('active'); root.find('.form-pane'); var pane = root.find('.form-pane'); pane.hide(); pane.eq(this._currentindex).show(); } }, clickNext: function (state) { if (this._currentindex <= this._renderindex - 1) { this._currentindex++; var root = this._containerRoot; var li = root.find('.form-bootstrapWizard>li'); li.removeClass('active'); li.eq(this._currentindex - 1).addClass(state || 'success'); li.eq(this._currentindex).addClass('active'); var pane = root.find('.form-pane'); pane.hide(); pane.eq(this._currentindex).show(); } }, addComponent: function (options) { this._components.push({ name: options.name, description: options.description, constructor: options.constructor, factory: options.factory || ComponentFactory, options: options.options, extend: options.extend }); }, getContainer: function (index, options) { var node = '<div id="' + index + '" class="form-pane" ' + (this._renderindex == 0 ? '' : 'style="display:none"') + ' data-value="step' + (this._renderindex + 1) + '" ></div>'; return $(node); }, addStep: function (name, index, text) { var root = this._containerRoot; root.find('.form-bootstrapWizard').append('<li ' + (index == 1 ? 'class="active"' : '') + ' data-target="step1">' + '<span class="step">' + index + '</span>' + '<span class="title">' + name + '</span>' + (text ? '<span class="text">' + text + '</span>' : '') + '</li>'); }, renderComponents: function (options) { this._currentindex = 0; this._renderindex = 0; var self = this; var containerRoot; if (this.options.root) { var tmp = this._containerRoot.find(this.options.root); containerRoot = tmp.length ? tmp : $(this._containerRoot.get(0)); } else { containerRoot = $(this._containerRoot.get(0)); } _.forEach(this._components, function (item) { var name = item.name; if (typeof self._componentStack[name] == 'undefined') { self._componentStack[name] = self.createComponent(item, options || {}); } var component = self._componentStack[name]; var el = self.getContainer(name, options || {}).appendTo(containerRoot).get(0); component.setElement(el); component.beforeShow(); component.render(options || {}); self.addStep(name, self._renderindex + 1, item.description); self._renderindex++; }); this.addStep('Complete', this._renderindex + 1); containerRoot.append('' + '<div id="Complete" class="form-pane" style="display:none" data-value="step' + (this._renderindex + 1) + '"><br/>' + '<h1 class="text-center text-success"><strong><i class="fa fa-check fa-lg"></i> Complete</strong></h1>' + '<h4 class="text-center">Click next to finish</h4>' + '<br/><br/></div>'); } }); CascadeContainer.create = function (options) { var ret = new CascadeContainer(); options.template = template; options.root = '.form-content'; if (ret.initialize(options) == false) { return false; } return ret; }; return CascadeContainer; });
MaxLeap/MyBaaS
webroot/javascript/core/container/CascadeContainer.js
JavaScript
gpl-2.0
4,532
var requestQueue = new Request.Queue({ concurrent: monitorData.length, stopOnFailure: false }); function Monitor(monitorData) { this.id = monitorData.id; this.connKey = monitorData.connKey; this.url = monitorData.url; this.status = null; this.alarmState = STATE_IDLE; this.lastAlarmState = STATE_IDLE; this.streamCmdParms = 'view=request&request=stream&connkey='+this.connKey; if ( auth_hash ) { this.streamCmdParms += '&auth='+auth_hash; } this.streamCmdTimer = null; this.type = monitorData.type; this.refresh = monitorData.refresh; this.start = function(delay) { if ( this.streamCmdQuery ) { this.streamCmdTimer = this.streamCmdQuery.delay(delay, this); } else { console.log("No streamCmdQuery"); } }; this.eventHandler = function(event) { console.log(event); }; this.onclick = function(evt) { var el = evt.currentTarget; var tag = 'watch'; var id = el.getAttribute("data-monitor-id"); var width = el.getAttribute("data-width"); var height = el.getAttribute("data-height"); var url = '?view=watch&mid='+id; var name = 'zmWatch'+id; evt.preventDefault(); createPopup(url, name, tag, width, height); }; this.setup_onclick = function() { var el = document.getElementById('imageFeed'+this.id); if ( el ) el.addEventListener('click', this.onclick, false); }; this.disable_onclick = function() { document.getElementById('imageFeed'+this.id).removeEventListener('click', this.onclick ); }; this.setStateClass = function(element, stateClass) { if ( !element.hasClass( stateClass ) ) { if ( stateClass != 'alarm' ) { element.removeClass('alarm'); } if ( stateClass != 'alert' ) { element.removeClass('alert'); } if ( stateClass != 'idle' ) { element.removeClass('idle'); } element.addClass(stateClass); } }; this.onError = function(text, error) { console.log('onerror: ' + text + ' error:'+error); // Requeue, but want to wait a while. var streamCmdTimeout = 10*statusRefreshTimeout; this.streamCmdTimer = this.streamCmdQuery.delay(streamCmdTimeout, this); }; this.onFailure = function(xhr) { console.log('onFailure: ' + this.connKey); console.log(xhr); if ( ! requestQueue.hasNext("cmdReq"+this.id) ) { console.log("Not requeuing because there is one already"); requestQueue.addRequest("cmdReq"+this.id, this.streamCmdReq); } if ( 0 ) { // Requeue, but want to wait a while. if ( this.streamCmdTimer ) { this.streamCmdTimer = clearTimeout( this.streamCmdTimer ); } var streamCmdTimeout = 1000*statusRefreshTimeout; this.streamCmdTimer = this.streamCmdQuery.delay( streamCmdTimeout, this, true ); requestQueue.resume(); } console.log("done failure"); }; this.getStreamCmdResponse = function(respObj, respText) { if ( this.streamCmdTimer ) { this.streamCmdTimer = clearTimeout( this.streamCmdTimer ); } var stream = $j('#liveStream'+this.id)[0]; if ( respObj.result == 'Ok' ) { if ( respObj.status ) { this.status = respObj.status; this.alarmState = this.status.state; var stateClass = ""; if ( this.alarmState == STATE_ALARM ) { stateClass = "alarm"; } else if ( this.alarmState == STATE_ALERT ) { stateClass = "alert"; } else { stateClass = "idle"; } if ( (!COMPACT_MONTAGE) && (this.type != 'WebSite') ) { $('fpsValue'+this.id).set('text', this.status.fps); $('stateValue'+this.id).set('text', stateStrings[this.alarmState]); this.setStateClass($('monitorState'+this.id), stateClass); } this.setStateClass($('monitor'+this.id), stateClass); /*Stream could be an applet so can't use moo tools*/ stream.className = stateClass; var isAlarmed = ( this.alarmState == STATE_ALARM || this.alarmState == STATE_ALERT ); var wasAlarmed = ( this.lastAlarmState == STATE_ALARM || this.lastAlarmState == STATE_ALERT ); var newAlarm = ( isAlarmed && !wasAlarmed ); var oldAlarm = ( !isAlarmed && wasAlarmed ); if ( newAlarm ) { if ( false && SOUND_ON_ALARM ) { // Enable the alarm sound $('alarmSound').removeClass('hidden'); } if ( POPUP_ON_ALARM ) { windowToFront(); } } if ( false && SOUND_ON_ALARM ) { if ( oldAlarm ) { // Disable alarm sound $('alarmSound').addClass('hidden'); } } if ( this.status.auth ) { if ( this.status.auth != auth_hash ) { // Try to reload the image stream. if ( stream ) { stream.src = stream.src.replace(/auth=\w+/i, 'auth='+this.status.auth); } console.log("Changed auth from " + auth_hash + " to " + this.status.auth); auth_hash = this.status.auth; } } // end if have a new auth hash } // end if has state } else { console.error(respObj.message); // Try to reload the image stream. if ( stream ) { if ( stream.src ) { console.log('Reloading stream: ' + stream.src); stream.src = stream.src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) )); } else { } } else { console.log('No stream to reload?'); } } // end if Ok or not var streamCmdTimeout = statusRefreshTimeout; // The idea here is if we are alarmed, do updates faster. // However, there is a timeout in the php side which isn't getting modified, // so this may cause a problem. Also the server may only be able to update so fast. //if ( this.alarmState == STATE_ALARM || this.alarmState == STATE_ALERT ) { //streamCmdTimeout = streamCmdTimeout/5; //} this.streamCmdTimer = this.streamCmdQuery.delay(streamCmdTimeout, this); this.lastAlarmState = this.alarmState; }; this.streamCmdQuery = function(resent) { if ( resent ) { console.log(this.connKey+": timeout: Resending"); this.streamCmdReq.cancel(); } //console.log("Starting CmdQuery for " + this.connKey ); if ( this.type != 'WebSite' ) { this.streamCmdReq.send(this.streamCmdParms+"&command="+CMD_QUERY); } }; if ( this.type != 'WebSite' ) { this.streamCmdReq = new Request.JSON( { url: this.url, method: 'get', timeout: AJAX_TIMEOUT, onSuccess: this.getStreamCmdResponse.bind(this), onTimeout: this.streamCmdQuery.bind(this, true), onError: this.onError.bind(this), onFailure: this.onFailure.bind(this), link: 'cancel' } ); console.log("queueing for " + this.id + " " + this.connKey + " timeout is: " + AJAX_TIMEOUT); requestQueue.addRequest("cmdReq"+this.id, this.streamCmdReq); } } // end function Monitor /** * called when the layoutControl select element is changed, or the page * is rendered * @param {*} element - the event data passed by onchange callback */ function selectLayout(element) { console.log(element); layout = $j(element).val(); if ( layout_id = parseInt(layout) ) { layout = layouts[layout]; for ( var i = 0, length = monitors.length; i < length; i++ ) { monitor = monitors[i]; // Need to clear the current positioning, and apply the new monitor_frame = $j('#monitorFrame'+monitor.id); if ( ! monitor_frame ) { console.log("Error finding frame for " + monitor.id); continue; } // Apply default layout options, like float left if ( layout.Positions['default'] ) { styles = layout.Positions['default']; for ( style in styles ) { monitor_frame.css(style, styles[style]); } } else { console.log("No default styles to apply" + layout.Positions); } // end if default styles if ( layout.Positions['mId'+monitor.id] ) { styles = layout.Positions['mId'+monitor.id]; for ( style in styles ) { monitor_frame.css(style, styles[style]); console.log("Applying " + style + ' : ' + styles[style]); } } else { console.log("No Monitor styles to apply"); } // end if specific monitor style } // end foreach monitor } // end if a stored layout if ( ! layout ) { return; } Cookie.write('zmMontageLayout', layout_id, {duration: 10*365}); if ( layouts[layout_id].Name != 'Freeform' ) { // 'montage_freeform.css' ) { Cookie.write( 'zmMontageScale', '', {duration: 10*365} ); $('scale').set('value', ''); $('width').set('value', 'auto'); for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; var streamImg = $('liveStream'+monitor.id); if ( streamImg ) { if ( streamImg.nodeName == 'IMG' ) { var src = streamImg.src; src = src.replace(/width=[\.\d]+/i, 'width=0' ); if ( src != streamImg.src ) { streamImg.src = ''; streamImg.src = src; } } else if ( streamImg.nodeName == 'APPLET' || streamImg.nodeName == 'OBJECT' ) { // APPLET's and OBJECTS need to be re-initialized } streamImg.style.width = '100%'; } } // end foreach monitor } } // end function selectLayout(element) /** * called when the widthControl|heightControl select elements are changed */ function changeSize() { var width = $('width').get('value'); var height = $('height').get('value'); for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; // Scale the frame monitor_frame = $j('#monitorFrame'+monitor.id); if ( !monitor_frame ) { console.log("Error finding frame for " + monitor.id); continue; } if ( width ) { monitor_frame.css('width', width); } if ( height ) { monitor_frame.css('height', height); } /*Stream could be an applet so can't use moo tools*/ var streamImg = $('liveStream'+monitor.id); if ( streamImg ) { if ( streamImg.nodeName == 'IMG' ) { var src = streamImg.src; streamImg.src = ''; src = src.replace(/width=[\.\d]+/i, 'width='+width); src = src.replace(/height=[\.\d]+/i, 'height='+height); src = src.replace(/rand=\d+/i, 'rand='+Math.floor((Math.random() * 1000000) )); streamImg.src = src; } streamImg.style.width = width ? width : null; streamImg.style.height = height ? height : null; //streamImg.style.height = ''; } } $('scale').set('value', ''); Cookie.write('zmMontageScale', '', {duration: 10*365}); Cookie.write('zmMontageWidth', width, {duration: 10*365}); Cookie.write('zmMontageHeight', height, {duration: 10*365}); //selectLayout('#zmMontageLayout'); } // end function changeSize() /** * called when the scaleControl select element is changed */ function changeScale() { var scale = $('scale').get('value'); $('width').set('value', 'auto'); $('height').set('value', 'auto'); Cookie.write('zmMontageScale', scale, {duration: 10*365}); Cookie.write('zmMontageWidth', '', {duration: 10*365}); Cookie.write('zmMontageHeight', '', {duration: 10*365}); if ( !scale ) { selectLayout('#zmMontageLayout'); return; } for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; var newWidth = ( monitorData[i].width * scale ) / SCALE_BASE; var newHeight = ( monitorData[i].height * scale ) / SCALE_BASE; // Scale the frame monitor_frame = $j('#monitorFrame'+monitor.id); if ( !monitor_frame ) { console.log("Error finding frame for " + monitor.id); continue; } if ( newWidth ) { monitor_frame.css('width', newWidth); } // We don't set the frame height because it has the status bar as well //if ( height ) { ////monitor_frame.css('height', height+'px'); //} /*Stream could be an applet so can't use moo tools*/ var streamImg = $j('#liveStream'+monitor.id)[0]; if ( streamImg ) { if ( streamImg.nodeName == 'IMG' ) { var src = streamImg.src; streamImg.src = ''; //src = src.replace(/rand=\d+/i,'rand='+Math.floor((Math.random() * 1000000) )); src = src.replace(/scale=[\.\d]+/i, 'scale='+scale); src = src.replace(/width=[\.\d]+/i, 'width='+newWidth); src = src.replace(/height=[\.\d]+/i, 'height='+newHeight); streamImg.src = src; } streamImg.style.width = newWidth + "px"; streamImg.style.height = newHeight + "px"; } } } function toGrid(value) { return Math.round(value / 80) * 80; } // Makes monitorFrames draggable. function edit_layout(button) { // Turn off the onclick on the image. for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; monitor.disable_onclick(); }; $j('#monitors .monitorFrame').draggable({ cursor: 'crosshair', //revert: 'invalid' }); $j('#SaveLayout').show(); $j('#EditLayout').hide(); } // end function edit_layout function save_layout(button) { var form = button.form; var name = form.elements['Name'].value; if ( !name ) { name = form.elements['zmMontageLayout'].options[form.elements['zmMontageLayout'].selectedIndex].text; } if ( name=='Freeform' || name=='2 Wide' || name=='3 Wide' || name=='4 Wide' || name=='5 Wide' ) { alert('You cannot edit the built in layouts. Please give the layout a new name.'); return; } // In fixed positioning, order doesn't matter. In floating positioning, it does. var Positions = {}; for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; monitor_frame = $j('#monitorFrame'+monitor.id); Positions['mId'+monitor.id] = { width: monitor_frame.css('width'), height: monitor_frame.css('height'), top: monitor_frame.css('top'), bottom: monitor_frame.css('bottom'), left: monitor_frame.css('left'), right: monitor_frame.css('right'), position: monitor_frame.css('position'), float: monitor_frame.css('float'), }; } // end foreach monitor form.Positions.value = JSON.stringify(Positions); form.submit(); } // end function save_layout function cancel_layout(button) { $j('#SaveLayout').hide(); $j('#EditLayout').show(); for ( var i = 0, length = monitors.length; i < length; i++ ) { var monitor = monitors[i]; monitor.setup_onclick(); //monitor_feed = $j('#imageFeed'+monitor.id); //monitor_feed.click(monitor.onclick); }; selectLayout('#zmMontageLayout'); } function reloadWebSite(ndx) { document.getElementById('imageFeed'+ndx).innerHTML = document.getElementById('imageFeed'+ndx).innerHTML; } var monitors = new Array(); function initPage() { jQuery(document).ready(function() { jQuery("#hdrbutton").click(function() { jQuery("#flipMontageHeader").slideToggle("slow"); jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up'); Cookie.write( 'zmMontageHeaderFlip', jQuery('#hdrbutton').hasClass('glyphicon-menu-up') ? 'up' : 'down', {duration: 10*365} ); }); }); if ( Cookie.read('zmMontageHeaderFlip') == 'down' ) { // The chosen dropdowns require the selects to be visible, so once chosen has initialized, we can hide the header jQuery("#flipMontageHeader").slideToggle("fast"); jQuery("#hdrbutton").toggleClass('glyphicon-menu-down').toggleClass('glyphicon-menu-up'); } for ( var i = 0, length = monitorData.length; i < length; i++ ) { monitors[i] = new Monitor(monitorData[i]); // Start the fps and status updates. give a random delay so that we don't assault the server var delay = Math.round( (Math.random()+0.5)*statusRefreshTimeout ); monitors[i].start(delay); var interval = monitors[i].refresh; if ( monitors[i].type == 'WebSite' && interval > 0 ) { setInterval(reloadWebSite, interval*1000, i); } monitors[i].setup_onclick(); } selectLayout('#zmMontageLayout'); } // Kick everything off window.addEventListener('DOMContentLoaded', initPage);
Simpler1/ZoneMinder
web/skins/classic/views/js/montage.js
JavaScript
gpl-2.0
16,321
System.register(['angular2/core'], function(exports_1) { var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1; var MyComponent; return { setters:[ function (core_1_1) { core_1 = core_1_1; }], execute: function() { MyComponent = (function () { function MyComponent() { } MyComponent = __decorate([ core_1.Component({ selector: 'my-component', template: '<h1>My Component</h1>' }), __metadata('design:paramtypes', []) ], MyComponent); return MyComponent; })(); exports_1("MyComponent", MyComponent); } } }); //# sourceMappingURL=my_component.js.map
burner/AngularVibed
Examples2/Example05/node_modules/angular2/ts/examples/core/ts/prod_mode/my_component.js
JavaScript
gpl-3.0
1,526
/**************************************** * This file is part of UNIX Guide for the Perplexed project. * Copyright (C) 2014 by Assaf Gordon <[email protected]> * Released under GPLv3 or later. ****************************************/ /* Each test in 'tests' array has the following elements: * 1. short name for the test (must be unique). * 2. input string for the parser * 3. should-be-accepted: true/false. * if TRUE, the syntax is expected to be * accepted by the parser, using the specific rule in item 4, * *AND ALL SUBSEQUENT* rules. See "rules" variable for the list and order * of rules. * if FALSE, the syntax must not be accepted by the parser, using the * specific rule in item 4. * 4. parser rule to check. * The rule name must match the names in 'posix_shell.pegjs' . * See 'rules' variable for list of valid starting rules. */ "use strict"; /* List of rules, must be the same as the rules * listed in "posix_shell.pegjs". * For each rule (the key), the subsequent rules to be also tested are listed. * The hierarchial order must match 'posix_shell.pegjs'. */ var rules = { 'Non_Operator_UnquotedCharacters' : 'Tokens_Command', 'SingleQuotedString' : 'Tokens_Command', 'DoubleQuotedString' : 'Tokens_Command', 'SubshellExpandable' : 'Tokens_Command', 'BacktickExpandable' : 'Tokens_Command', 'ParameterExpandable' : 'Tokens_Command', 'ParameterOperationExpandable' : 'Tokens_Command', 'ArithmeticExpandable' : 'Tokens_Command', 'Expandable' : '', 'Tokens_Command' : 'SimpleCommand', 'Redirection' : 'Redirections', 'Assignment' : 'Assignments_Or_Redirections', 'Assignments_Or_Redirections' : 'SimpleCommand', 'Redirections' : 'SimpleCommand', 'SimpleCommand' : 'Command', 'Command' : 'Pipeline', 'Pipeline' : 'AndOrList', 'AndOrList' : 'List', 'List' : undefined, /* last rule in hierarchy */ /* Special rules, which should not automatically lead to subsequent rules */ 'Token_NoDelimiter' : undefined, 'TerminatedList' : undefined, /* NOTE: these rules must be used directly, no other rule points to them */ 'Compound_Command_Subshell' : 'Command', 'Compound_Command_Currentshell' : 'Command', 'For_clause' : 'Command' }; var tests = [ /* test-name, test-input, should-be-accepted, start-rule */ /* Single words, without any quoted characters, accpted in the context of a command. */ ["nqc1", "hello", true, "Non_Operator_UnquotedCharacters"], ["nqc2", "he%llo", true, "Non_Operator_UnquotedCharacters"], ["nqc3", "9hello", true, "Non_Operator_UnquotedCharacters"], ["nqc4", "h_", true, "Non_Operator_UnquotedCharacters"], ["nqc5", "==ds@_", true, "Non_Operator_UnquotedCharacters"], ["nqc6", "foo bar", true, "Non_Operator_UnquotedCharacters"], ["nqc7", "foo\"bar", false, "Non_Operator_UnquotedCharacters"], ["nqc8", "foo\$bar", false, "Non_Operator_UnquotedCharacters"], ["nqc9", "|foobar", false, "Non_Operator_UnquotedCharacters"], ["nqc10", "foobar>", false, "Non_Operator_UnquotedCharacters"], ["nqc11", "foobar&", false, "Non_Operator_UnquotedCharacters"], ["nqc12", "foobar;", false, "Non_Operator_UnquotedCharacters"], ["nqc13", ";foobar", false, "Non_Operator_UnquotedCharacters"], /* Single and Double Quoted strings (must be properly quoted) */ ["dquote1", '"hello"', true, "DoubleQuotedString"], ["dquote2", 'hello', false, "DoubleQuotedString"], ["dquote3", 'h"ello', false, "DoubleQuotedString"], ["dquote4", '"hello', false, "DoubleQuotedString"], ["dquote5", 'hello"', false, "DoubleQuotedString"], ["dquote6", '"he$llo"', true, "DoubleQuotedString"], ["dquote7", '"he>llo"', true, "DoubleQuotedString"], ["dquote8", '"he llo"', true, "DoubleQuotedString"], ["dquote9", '"he\\llo"', true, "DoubleQuotedString"], ["dquote10", '"he|llo"', true, "DoubleQuotedString"], ["dquote11", '""', true, "DoubleQuotedString"], ["dquote12", '"hell\'lo"', true, "DoubleQuotedString"], ["dquote13", '"hello world"',true, "DoubleQuotedString"], ["dquote14", '"foo\tbar"', true, "DoubleQuotedString"], ["dquote15", '"hello("', true, "DoubleQuotedString"], ["dquote16", '"he)llo"', true, "DoubleQuotedString"], ["dquote17", '"he{llo"', true, "DoubleQuotedString"], ["dquote18", '"he}llo"', true, "DoubleQuotedString"], ["dquote19", '"${FOO}world"',true, "DoubleQuotedString"], /* Double-Quotes with parameter expansion */ ["dquote30", '"hello$(uname)world"', true, "DoubleQuotedString"], ["dquote31", '"hello$(uname -s)world"',true, "DoubleQuotedString"], ["dquote32", '"hello${uname}world"', true, "DoubleQuotedString"], ["dquote33", '"hello$(echo "world")"',true, "DoubleQuotedString"], ["dquote34", '"hello$(echo \'world\')"',true, "DoubleQuotedString"], ["dquote37", '"hello$FOO"', true, "DoubleQuotedString"], ["dquote38", '"hello$((1+4))"',true, "DoubleQuotedString"], ["dquote39", '"hello$(echo"',false, "DoubleQuotedString"], ["dquote40", '"hello${echo"',false, "DoubleQuotedString"], ["dquote41", '"hello$((1+4)"',false, "DoubleQuotedString"], ["squote1", "'hello'", true, "SingleQuotedString"], ["squote2", "he'llo", false, "SingleQuotedString"], ["squote3", "'hello", false, "SingleQuotedString"], ["squote4", "hello'", false, "SingleQuotedString"], ["squote5", "'he$llo'", true, "SingleQuotedString"], ["squote6", "'he\"llo'", true, "SingleQuotedString"], ["squote7", "'he llo'", true, "SingleQuotedString"], ["squote8", "''", true, "SingleQuotedString"], ["squote9", "'\"'", true, "SingleQuotedString"], /* Test single tokens - any combination fo quoted and unquoted strings, that logically become one token/word. Special characters must be properly quoted. */ ["word1", 'he"llo"', true, "Token_NoDelimiter"], ["word2", 'he"ll\'o"', true, "Token_NoDelimiter"], ["word3", 'he"ll""o"', true, "Token_NoDelimiter"], ["word4", 'hell\\"o', true, "Token_NoDelimiter"], ["word5", 'he"\'ll"o', true, "Token_NoDelimiter"], ["word6", 'he\\|llo', true, "Token_NoDelimiter"], ["word7", 'he"\\|"llo', true, "Token_NoDelimiter"], ["word8", 'he"\\\\"llo', true, "Token_NoDelimiter"], ["word9", 'he\\\\llo', true, "Token_NoDelimiter"], ["word10", '"he|llo"', true, "Token_NoDelimiter"], ["word11", '"he l lo"', true, "Token_NoDelimiter"], ["word12", '"he&llo"', true, "Token_NoDelimiter"], ["word13", '"he;llo"', true, "Token_NoDelimiter"], ["word14", '"he>llo"', true, "Token_NoDelimiter"], ["word15", '"he>llo"world',true, "Token_NoDelimiter"], ["word16", 'foo>bar', false, "Token_NoDelimiter"], ["word17", 'foo|bar', false, "Token_NoDelimiter"], ["word18", 'foo bar', false, "Token_NoDelimiter"], ["word19", 'foo\\|bar', true, "Token_NoDelimiter"], ["word20", 'foo\\>bar', true, "Token_NoDelimiter"], ["word21", 'foo\\ bar', true, "Token_NoDelimiter"], ["word22", '"foo|bar"', true, "Token_NoDelimiter"], ["word23", '"foo>bar"', true, "Token_NoDelimiter"], ["word24", '"foo bar"', true, "Token_NoDelimiter"], ["word25", '"foo "bar', true, "Token_NoDelimiter"], ["word26", "'foo 'bar", true, "Token_NoDelimiter"], ["word27", "'foo '\"bar\"",true, "Token_NoDelimiter"], /* TODO: these are accepted, but at the moment - do not actually perform sub-shell and parameter expansion */ /* Test 'tokens' rule - whitespace separates tokens, only non-operator tokens should be accepted (operator characters can be accepted if they're quoted - thus losing their special meaning) */ ["token1", "hello world", true, "Tokens_Command"], ["token2", "hello world", true, "Tokens_Command"], ["token4", "'hello world' foo bar", true, "Tokens_Command"], ["token5", "'hello world' \"foo bar\"", true, "Tokens_Command"], /* single-quote not terminated */ ["token6", "hello world' \"foo bar\"", false, "Tokens_Command"], ["token7", "hello \t \t world", true, "Tokens_Command"], ["token8", "hello '' world", true, "Tokens_Command"], ["token9", 'cut -f1 -d""', true, "Tokens_Command"], ["token10", 'foo bar|', false, "Tokens_Command"], ["token11", 'foo|bar', false, "Tokens_Command"], ["token12", 'foo>bar', false, "Tokens_Command"], ["token13", 'foo ">bar"', true, "Tokens_Command"], ["token14", 'foo && bar', false, "Tokens_Command"], ["token15", 'foo ; bar', false, "Tokens_Command"], ["token16", 'foo > bar', false, "Tokens_Command"], ["token17", 'foo ">" bar', true, "Tokens_Command"], /* Token commands must not accept reserved words as first words of the command, but accept if non-first */ ["token18", 'echo if', true, "Tokens_Command"], ["token19", 'if echo', false, "Tokens_Command"], ["token20", 'echo {', true, "Tokens_Command"], ["token21", '{ echo', false, "Tokens_Command"], ["token22", 'echo }', true, "Tokens_Command"], ["token23", '} echo', false, "Tokens_Command"], ["token24", 'echo else', true, "Tokens_Command"], ["token25", 'else echo', false, "Tokens_Command"], ["token26", 'echo elif', true, "Tokens_Command"], ["token27", 'elif echo', false, "Tokens_Command"], ["token28", 'echo then', true, "Tokens_Command"], ["token29", 'then echo', false, "Tokens_Command"], ["token30", 'echo fi', true, "Tokens_Command"], ["token31", 'fi echo', false, "Tokens_Command"], ["token32", 'echo while', true, "Tokens_Command"], ["token33", 'while echo', false, "Tokens_Command"], ["token34", 'echo until', true, "Tokens_Command"], ["token35", 'until echo', false, "Tokens_Command"], ["token36", 'echo do', true, "Tokens_Command"], ["token37", 'do echo', false, "Tokens_Command"], ["token38", 'echo done', true, "Tokens_Command"], ["token39", 'done echo', false, "Tokens_Command"], ["token40", 'echo case', true, "Tokens_Command"], ["token41", 'case echo', false, "Tokens_Command"], ["token42", 'echo esac', true, "Tokens_Command"], ["token43", 'esac echo', false, "Tokens_Command"], ["token44", 'echo in', true, "Tokens_Command"], ["token45", 'in echo', false, "Tokens_Command"], ["token46", 'echo !', true, "Tokens_Command"], ["token47", '! echo', false, "Tokens_Command"], /* Test single redirection */ ["redir1", ">foo.txt", true, "Redirection"], ["redir2", "2>foo.txt", true, "Redirection"], ["redir3", "<foo.txt", true, "Redirection"], ["redir4", "2>&1", true, "Redirection"], ["redir5", ">&1", true, "Redirection"], ["redir6", "<>foo.txt", true, "Redirection"], ["redir7", ">>foo.txt", true, "Redirection"], ["redir8", ">'f o o.txt'", true, "Redirection"], ["redir9", ">f o o.txt", false, "Redirection"], ["redir10", ">", false, "Redirection"], ["redir11", "<", false, "Redirection"], /* The redirection rule accepts just one redirection. multiple redirections are tested below. */ ["redir12", ">foo.txt 2>&1", false, "Redirection"], ["redir13", "<bar.txt >foo.txt", false, "Redirection"], //allow whitespace before the filename ["redir14", "> foo.txt", true, "Redirection"], ["redir15", "< foo.txt", true, "Redirection"], ["redir16", ">> foo.txt", true, "Redirection"], ["redir17", "<> foo.txt", true, "Redirection"], /* Test Multiple Redirections */ ["mredir1", ">foo.txt 2>&1", true, "Redirections"], ["mredir2", "<bar.txt >foo.txt", true, "Redirections"], ["mredir3", "<bar.txt>foo.txt", true, "Redirections"], ["mredir4", "2>&1<foo.txt", true, "Redirections"], /* Test Single Assignment */ ["asgn1", "FOO=BAR", true, "Assignment"], ["asgn2", "FOO='fo fo > BAR'", true, "Assignment"], ["asgn3", "FOO=HELLO\"WOR LD\"", true, "Assignment"], ["asgn4", "FOO=", true, "Assignment"], ["asgn5", "F\"OO\"=BAR", false, "Assignment"], ["asgn6", "=BAR", false, "Assignment"], /* Test multiple assignments and redirections. though not very common, both assignments AND redirections can appear before the actual command to execute, eg.: FOO=BAR <input.txt >counts.txt wc -l Additionally, shell commands with only assignments and redirections (and no command to execute) are perfectly valid. */ ["asgnrdr1", "FOO=BAR >hello.txt", true, "Assignments_Or_Redirections"], ["asgnrdr2", "FOO=BAR HELLO=WORLD", true, "Assignments_Or_Redirections"], ["asgnrdr3", "2>&1 FOO=BAR BAZ=BOM", true, "Assignments_Or_Redirections"], ["asgnrdr4", "FOO=BAR>out.txt", true, "Assignments_Or_Redirections"], ["asgnrdr5", "FOO=\">foo.txt\">out.txt", true, "Assignments_Or_Redirections"], /* this test includes a command 'seq', and should not be accepted by this rule. it should be accepted by later rules. */ ["asgnrdr6", "FOO=BAR seq 10", false, "Assignments_Or_Redirections"], ["asgnrdr7", "FOO=BAR >out.txt seq 10", false, "Assignments_Or_Redirections"], /* Test Simple Commands, with assignment and redirections */ ["smpl1", "FOO=BAR cut -f1", true, "SimpleCommand" ], ["smpl2", "FOO=BAR HELLO=WORLD cut -f1", true, "SimpleCommand" ], /* NOTE: the last BAZ=BOO is NOT a variable assignment. it should be parsed * as a normal parameter to 'cut' - but it is still a valid command syntax. */ ["smpl3", "FOO=BAR HELLO=WORLD cut -f1 BAZ=BOO", true, "SimpleCommand" ], ["smpl4", "FOO=BAR <foo.txt cut -f1", true, "SimpleCommand" ], ["smpl5", "<foo.txt cut -f1", true, "SimpleCommand" ], ["smpl6", "7<foo.txt cut -f1", true, "SimpleCommand" ], ["smpl7", "7<foo.txt FOO=BAR ZOOM=ZOOM >text.txt cut -f1", true, "SimpleCommand" ], ["smpl8", "2>&1 FOO=BAR ZOOM=ZOOM cut -f1", true, "SimpleCommand" ], ["smpl9", "7<&1 FOO=BAR ZOOM=ZOOM cut -f1", true, "SimpleCommand" ], ["smpl10", "<>yes.txt FOO=BAR ZOOM=ZOOM cut -f1", true, "SimpleCommand" ], ["smpl11", "FFO=BAR>yes.txt cut -f1", true, "SimpleCommand" ], ["smpl12", ">yes.txt cut -f1 <foo.txt", true, "SimpleCommand" ], /* test 'redirection_word_hack' rule */ ["smpl13", "cut -f1 >foo.txt 2>&1", true, "SimpleCommand" ], ["smpl14", "cut -f1 2>&1", true, "SimpleCommand" ], ["smpl15", "cut -f1 1>foo.txt 2>&1", true, "SimpleCommand" ], ["smpl16", "HELLO=FOO 1>foo.txt 2>&1" , true, "SimpleCommand" ], /* Simple commands must not accept pipes, ands, ors and other special operators, unless quoted. */ ["smpl17", "seq 10 | wc -l", false, "SimpleCommand" ], ["smpl18", "seq 10 '|' wc -l", true, "SimpleCommand" ], ["smpl19", "seq 10 && echo ok", false, "SimpleCommand" ], ["smpl20", "seq 10 \"&&\" echo ok", true, "SimpleCommand" ], ["smpl21", "seq 10 || echo ok", false, "SimpleCommand" ], ["smpl22", "seq 10 \"||\" echo ok", true, "SimpleCommand" ], ["smpl23", "seq 10 \\|\\| echo ok" , true, "SimpleCommand" ], ["smpl25", "seq 10 ; echo ok", false, "SimpleCommand" ], ["smpl26", "seq 10 & echo ok", false, "SimpleCommand" ], /* Few more cases */ ["smpl27", "true>foo.txt", true, "SimpleCommand" ], ["smpl28", "true>foo.txt<foo.txt", true, "SimpleCommand" ], /* Simple Command rule must not accept compound commands */ ["smpl40", "( true | false )", false, "SimpleCommand" ], ["smpl41", "{ true ; false ; }", false, "SimpleCommand" ], /* Test Compound-Command-SubShell rule */ ["cmpss1", "( uname )", true, "Compound_Command_Subshell"], ["cmpss2", "(uname)", true, "Compound_Command_Subshell"], ["cmpss3", "( uname | true | false)", true, "Compound_Command_Subshell"], ["cmpss4", "( uname | true & false)", true, "Compound_Command_Subshell"], ["cmpss5", "( uname ; true ; false)", true, "Compound_Command_Subshell"], ["cmpss6", "( uname && true || false)", true, "Compound_Command_Subshell"], ["cmpss7", "()", false, "Compound_Command_Subshell"], /* Test Compound-Command-CurrentShell rule */ ["cmpcs1", "{ uname ; }", true, "Compound_Command_Currentshell"], ["cmpcs2", "{ uname & }", true, "Compound_Command_Currentshell"], ["cmpcs3", "{ uname }", false, "Compound_Command_Currentshell"], ["cmpcs4", "{ uname;}", true, "Compound_Command_Currentshell"], ["cmpcs5", "{ uname&}", true, "Compound_Command_Currentshell"], ["cmpcs6", "{ uname; }", true, "Compound_Command_Currentshell"], ["cmpcs7", "{ uname& }", true, "Compound_Command_Currentshell"], ["cmpcs9", "{ uname | true | false ; }", true, "Compound_Command_Currentshell"], ["cmpcs10", "{ uname | true & false ; }", true, "Compound_Command_Currentshell"], ["cmpcs11", "{ uname ; true ; false ; }", true, "Compound_Command_Currentshell"], ["cmpcs12", "{ uname && true || false & }", true, "Compound_Command_Currentshell"], ["cmpcs13", "{}", false, "Compound_Command_Currentshell"], /* Test For clause */ ["for1", "for a in a b c d ; do true ; done", true, "For_clause"], /* missing 'in' */ ["for2", "for a a b c d ; do true ; done", false, "For_clause"], /* missing semi-colon before do */ ["for3", "for a in a b c d do true ; done", false, "For_clause"], /* missing 'do' */ ["for4", "for a in a b c d ; true ; done", false, "For_clause"], /* missing semi-colon before done */ ["for5", "for a in a b c d ; do true done", false, "For_clause"], /* missing command between do and done */ ["for6", "for a in a b c d ; do ; done", false, "For_clause"], /* non-simple values in word-list */ ["for7", "for a in $(ls); do echo a=$a ; done", true, "For_clause"], /* Test Pipeline rule */ ["pipe1", "seq 1 2 10 | wc -l", true, "Pipeline"], ["pipe2", "seq 1 2 10 2>foo.txt | wc -l 2>>foo2.txt ", true, "Pipeline"], ["pipe3", "FOO=BAR seq 1 2 10 2>foo.txt | wc -l 2>>foo2.txt ", true, "Pipeline"], ["pipe4", "FOO=BAR seq 1 2 10 2>foo.txt | FOO=BAR Pc -l 2>>foo2.txt ", true, "Pipeline"], ["pipe5", "FOO=BAR seq 1 2 10 2>foo.txt | <input.txt wc -l 2>>foo2.txt ", true, "Pipeline"], ["pipe6", "FOO=BAR seq 1 2 10 2>foo.txt | FOO=BAR <input.txt wc -l 2>>foo2.txt ", true, "Pipeline"], ["pipe7", "cut -f1 <genes.txt|sort -k1V,1 -k2nr,2 ", true, "Pipeline"], ["pipe8", "cut -f1 <genes.txt | sort -k1V,1 -k2nr,2 | uniq -c >text.txt", true, "Pipeline"], /* Pipeline'd commands must not accept ands, ors and other special operators, unless quoted. */ ["pipe9", "cut -f1 | seq 10 && echo ok ", false, "Pipeline"], ["pipe10", "cut -f1 | seq 10 & echo ok ", false, "Pipeline"], ["pipe11", "cut -f1 | seq 10 ; echo ok ", false, "Pipeline"], ["pipe12", "true && cut -f1 | seq 10", false, "Pipeline"], ["pipe13", "cut -f1 |", false, "Pipeline"], ["pipe14", "|cut -f1 |", false, "Pipeline"], ["pipe15", "|cut -f1", false, "Pipeline"], /* Pipelines with compound commands */ ["pipe30", "seq 10 | ( sed -u 1q ; sort -nr)", true, "Pipeline"], ["pipe31", "( cat hello ; tac world ) | wc -l", true, "Pipeline"], ["pipe32", "seq 10 | { sed -u 1q ; sort -nr ; }", true, "Pipeline"], ["pipe33", "{ cat hello ; tac world ; } | wc -l", true, "Pipeline"], /* Test AndOrList rule */ ["andor1", "true && false || seq 1", true, "AndOrList" ], ["andor2", "true && false | wc", true, "AndOrList" ], ["andor3", "true && false | wc || seq 1", true, "AndOrList" ], ["andor4", "true && false && false && echo ok || echo fail",true, "AndOrList" ], ["andor5", "true && false ; wc", false, "AndOrList" ], ["andor6", "true && false & wc", false, "AndOrList" ], ["andor7", "true &&", false, "AndOrList" ], ["andor8", "true ||", false, "AndOrList" ], ["andor9", " && true", false, "AndOrList" ], ["andor10", " || true", false, "AndOrList" ], ["andor11", "&& true", false, "AndOrList" ], ["andor12", "|| true", false, "AndOrList" ], ["andor13", "true && && true", false, "AndOrList" ], ["andor14", "false && || true", false, "AndOrList" ], /* AndOrLists with compound commands */ ["andor30", "true && ( sed -u 1q ; sort -nr)", true, "AndOrList"], ["andor31", "( cat hello ; tac world ) || wc -l", true, "AndOrList"], ["andor32", "seq 10 && { sed -u 1q ; sort -nr ; }", true, "AndOrList"], ["andor33", "{ cat hello ; tac world ; } && wc -l", true, "AndOrList"], /* Test List rule */ ["list1", "true ;", true, "List" ], ["list2", "true &", true, "List" ], ["list3", "true ; false", true, "List" ], ["list4", "true ; false ;", true, "List" ], ["list5", "true & false ;", true, "List" ], ["list6", "true & false &", true, "List" ], ["list7", "true && false &", true, "List" ], ["list8", ";", false, "List" ], ["list9", "&", false, "List" ], /* Test TerminatedList Rule - a special rule for commands inside "{}" which requires that each command be terminated (unlike "List" rule, in which the last command is optionally terminated */ ["tlist1", "true ;", true, "TerminatedList"], ["tlist2", "true &", true, "TerminatedList"], ["tlist3", "true ; false ;", true, "TerminatedList"], ["tlist4", "true ; false &", true, "TerminatedList"], ["tlist5", "true", false, "TerminatedList"], ["tlist6", "true", false, "TerminatedList"], ["tlist7", "true ; false", false, "TerminatedList"], ["tlist8", "true ; false", false, "TerminatedList"], /* Test Sub-Shell Parameter Expansion */ ["subshell1", "$()", true, "SubshellExpandable"], ["subshell2", "$())", false, "SubshellExpandable"], ["subshell3", "$(ls)", true, "SubshellExpandable"], ["subshell4", "$(echo $(uname -s))", true, "SubshellExpandable"], ["subshell5", "$(()", false, "SubshellExpandable"], ["subshell6", "$(echo \\()", true, "SubshellExpandable"], ["subshell7", "$(echo \\))", true, "SubshellExpandable"], ["subshell8", "$(echo \\$)", true, "SubshellExpandable"], ["subshell9", "$(echo $($()$()$($($()))uname -s))", true, "SubshellExpandable"], ["subshell10", "$(echo ${USER})", true, "SubshellExpandable"], ["subshell11", "$(echo `uname -s`)", true, "SubshellExpandable"], ["subshell12", "aaa$()", false, "SubshellExpandable"], ["subshell13", "$(echo hi)" , true, "SubshellExpandable"], ["subshell14", "$( )", true, "SubshellExpandable"], ["subshell15", "$( \t \t )", true, "SubshellExpandable"], ["subshell16", "$(FOO=BAR)", true, "SubshellExpandable"], ["subshell17", "$(true|false)", true, "SubshellExpandable"], ["subshell18", "$(true;false)", true, "SubshellExpandable"], ["subshell19", "$(true;false;)", true, "SubshellExpandable"], ["subshell20", "$(foo 2>1.txt | wc-l)", true, "SubshellExpandable"], /* Test Backtick Subshell parameter expansion */ /*TODO: add more backtick tests */ ["backtick1", "`ls`", true, "BacktickExpandable"], ["backtick2", "`ls", false, "BacktickExpandable"], ["backtick3", "ls`", false, "BacktickExpandable"], ["backtick4", "ls``", false, "BacktickExpandable"], /* TODO: Test 5 should not fail. what's the diff between this and subshell13? */ /*["backtick5", "`echo hi`", true, "BacktickExpandable"],*/ /* Test Parameter Expansion (without operations) */ ["ParamExp1", "${FOO}", true, "ParameterExpandable"], ["ParamExp2", "$FOO", true, "ParameterExpandable"], ["ParamExp3", "${FOO", false, "ParameterExpandable"], ["ParamExp4", "$FOO}", false, "ParameterExpandable"], ["ParamExp5", "$F.OO", false, "ParameterExpandable"], ["ParamExp6", "$FOO=", false, "ParameterExpandable"], ["ParamExp7", "$FO${O}", false, "ParameterExpandable"], ["ParamExp8", "${FOO=BAR}", false, "ParameterExpandable"], /* Special parameters */ ["ParamExp9", "$!", true, "ParameterExpandable"], ["ParamExp10", "$$", true, "ParameterExpandable"], ["ParamExp11", "$-", true, "ParameterExpandable"], ["ParamExp12", "$?", true, "ParameterExpandable"], ["ParamExp13", "$@", true, "ParameterExpandable"], ["ParamExp14", "${!}", true, "ParameterExpandable"], ["ParamExp15", "${$}", true, "ParameterExpandable"], ["ParamExp16", "${-}", true, "ParameterExpandable"], ["ParamExp17", "${?}", true, "ParameterExpandable"], ["ParamExp18", "${@}", true, "ParameterExpandable"], /* Test Parameter Expansion with operations */ ["ParmOpExp1", "${FOO=BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp2", "${FOO:-BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp3", "${FOO-BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp4", "${FOO:=BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp5", "${FOO=BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp6", "${FOO:?BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp7", "${FOO?BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp8", "${FOO:+BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp9", "${FOO+BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp10", "${FOO%BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp12", "${FOO%%BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp13", "${FOO#BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp14", "${FOO##BAR}", true, "ParameterOperationExpandable"], ["ParmOpExp15", "${FOO=}", true, "ParameterOperationExpandable"], ["ParmOpExp16", "${FOO=(}", true, "ParameterOperationExpandable"], /* Go Recursive */ ["ParmOpExp17", "${FOO=${BAR}}", true, "ParameterOperationExpandable"], ["ParmOpExp18", "${FOO=BAR${BAR}}", true, "ParameterOperationExpandable"], ["ParmOpExp19", "${FOO=${BAR-BAZ}}", true, "ParameterOperationExpandable"], ["ParmOpExp20", "${FOO=$(uname -s)BAZ}", true, "ParameterOperationExpandable"], ["ParmOpExp21", "${FOO=$BAR}", true, "ParameterOperationExpandable"], /* Test bad syntax */ ["ParmOpExp22", "${FOO", false, "ParameterOperationExpandable"], ["ParmOpExp23", "${FOO=", false, "ParameterOperationExpandable"], ["ParmOpExp24", "$FOO=BAR", false, "ParameterOperationExpandable"], ["ParmOpExp25", "$FOO=BAR}", false, "ParameterOperationExpandable"], ["ParmOpExp26", "$FOO}", false, "ParameterOperationExpandable"], ["ParmOpExp28", "${FOO=HELLO\"WORLD}", false, "ParameterOperationExpandable"], ["ParmOpExp29", "${FOO=HELLO\'WORLD}", false, "ParameterOperationExpandable"], ["ParmOpExp30", "${FOO=HEL${LOWORLD}", false, "ParameterOperationExpandable"], ["ParmOpExp31", "${#FOO}", true, "ParameterOperationExpandable"], /* Test Arithmatic Expansion */ /* TODO: as more arithmetic operations are added, add appropriate tests */ ["arthm1", "$(())", true, "ArithmeticExpandable"], ["arthm2", "$(( ))", true, "ArithmeticExpandable"], ["arthm3", "$((1))", true, "ArithmeticExpandable"], ["arthm4", "$(( 3 ))", true, "ArithmeticExpandable"], ["arthm5", "$((A))", true, "ArithmeticExpandable"], ["arthm6", "$(($A))", true, "ArithmeticExpandable"], ["arthm7", "$((1+2+3))", true, "ArithmeticExpandable"], ["arthm8", "$((1+2*3))", true, "ArithmeticExpandable"], ["arthm9", "$((A*3))", true, "ArithmeticExpandable"], ["arthm10", "$((1+FOO*3))", true, "ArithmeticExpandable"], ["arthm11", "$(((1+FOO)*3))", true, "ArithmeticExpandable"], // Zero ["arthm12", "$((0))", true, "ArithmeticExpandable"], // Octal ["arthm13", "$((033))", true, "ArithmeticExpandable"], // Hex ["arthm14", "$((0x33))", true, "ArithmeticExpandable"], /* Go Recursive */ ["arthm20", "$(( $(nproc)+1 ))", true, "ArithmeticExpandable"], ["arthm21", "$(( ${PID}*1 ))", true, "ArithmeticExpandable"], ["arthm22", "$(( $((42))*9 ))", true, "ArithmeticExpandable"], /* Test bad syntax */ ["arthm30", "$(( 3+4 )", false, "ArithmeticExpandable"], /* Test possible combinations of parameter expansions - single token*/ ["expan1", "una$(echo me)", true, "Token_NoDelimiter"], ["expan2", "una${A}", true, "Token_NoDelimiter"], ["expan3", "una$A", true, "Token_NoDelimiter"], ["expan4", "una${FOO-me}", true, "Token_NoDelimiter"], ["expan5", "hel'lo'${USER}$(echo wo)`uptime`", true, "Token_NoDelimiter"], ["expan6", "${A}$(ls)$B$C${D}-foo", true, "Token_NoDelimiter"], /* TODO: test expansion with assignment, redirection */ ]; module.exports = { "tests" : tests, "parser_rules": rules };
agordon/agnostic
src/tests/shell_syntax_tests.js
JavaScript
gpl-3.0
27,765
import React, { PropTypes } from 'react' import classnames from 'classnames' const SettingsPageMenuLayout = ({ children, title, className }) => ( <div className={classnames( 'settings-page-menu-layout bg-white pt3 pr4 pl5 border-only-bottom border-gray94', className )} > <h1 className="h1 mt0 mb3">{title}</h1> {children} </div> ) SettingsPageMenuLayout.propTypes = { children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]), className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]), title: PropTypes.string.isRequired } export default SettingsPageMenuLayout
igr-santos/hub-client
app/components/Layout/SettingsPageMenuLayout.js
JavaScript
gpl-3.0
624
export default class FilesUploadHandler { static isUploadEnabled( mediaType ) { const unfilteredFilesTypes = [ 'svg', 'application/json' ]; if ( ! unfilteredFilesTypes.includes( mediaType ) ) { return true; } return elementor.config.filesUpload.unfilteredFiles; } static setUploadTypeCaller( frame ) { frame.uploader.uploader.param( 'uploadTypeCaller', 'elementor-wp-media-upload' ); } static getUnfilteredFilesNotEnabledDialog( callback ) { const onConfirm = () => { elementorCommon.ajax.addRequest( 'enable_unfiltered_files_upload', {}, true ); elementor.config.filesUpload.unfilteredFiles = true; callback(); }; return elementor.helpers.getSimpleDialog( 'e-enable-unfiltered-files-dialog', __( 'Enable Unfiltered File Uploads', 'elementor' ), __( 'Before you enable unfiltered files upload, note that this kind of files include a security risk. Elementor does run a process to remove possible malicious code, but there is still risk involved when using such files.', 'elementor' ), __( 'Enable', 'elementor' ), onConfirm ); } }
pojome/elementor
assets/dev/js/editor/utils/files-upload-handler.js
JavaScript
gpl-3.0
1,087
'use superstrict'; try { if ((-25 >> 3) === -4) { 'ok'; } else { 'fail'; } } catch (e) { }
vacuumlabs/babel-plugin-superstrict
test/eval_tests/casting_signed_right_shift_numbers.js
JavaScript
gpl-3.0
106
/** * Copyright 2013 hbz NRW (http://www.hbz-nrw.de/) * * This file is part of regal-drupal. * * regal-drupal is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * regal-drupal 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with regal-drupal. If not, see <http://www.gnu.org/licenses/>. */ (function($) { var translations = { } /** * Common behaviours */ Drupal.behaviors.edoweb = { attach: function (context, settings) { var home_href = Drupal.settings.basePath + 'resource'; if (document.location.pathname == home_href && '' != document.location.search) { var query_params = []; var all_params = document.location.search.substr(1).split('&'); $.each(all_params, function(i, param) { if ('query[0][facets]' == param.substr(0, 16)) { query_params.push(param); } }); if (query_params) { sessionStorage.setItem('edoweb_search', '?' + query_params.join('&')); } } else if (document.location.pathname == home_href) { sessionStorage.removeItem('edoweb_search'); } if (search = sessionStorage.getItem('edoweb_search')) { $('a[href="' + home_href + '"]').attr('href', home_href + search); if ('resource' == Drupal.settings.edoweb.site_frontpage) { $('a[href="/"]').attr('href', home_href + search); } } /** * Date parser for tablesort plugin */ $.tablesorter.addParser({ id: 'edowebDate', is: function(s) { return /^.*, /.test(s); }, format: function(s, table, cell, cellIndex) { return $(cell).closest('tr').attr('data-updated'); }, type: 'text' }); /** * Translations, these have to be defined here (i.e. in a behaviour) * in order for Drupal.t to pick them up. */ translations['Add researchData'] = Drupal.t('Add researchData'); translations['Add monograph'] = Drupal.t('Add monograph'); translations['Add journal'] = Drupal.t('Add journal'); translations['Add volume'] = Drupal.t('Add volume'); translations['Add issue'] = Drupal.t('Add issue'); translations['Add article'] = Drupal.t('Add article'); translations['Add file'] = Drupal.t('Add file'); translations['Add part'] = Drupal.t('Add part'); translations['Add webpage'] = Drupal.t('Add webpage'); translations['Add version'] = Drupal.t('Add version'); } } /** * Edoweb helper functions */ Drupal.edoweb = { /** * URI to CURIE */ compact_uri: function(uri) { var namespaces = Drupal.settings.edoweb.namespaces; for (prefix in namespaces) { if (uri.indexOf(namespaces[prefix]) == 0) { var local_part = uri.substring(namespaces[prefix].length); return prefix + ':' + local_part; } } return uri; }, expand_curie: function(curie) { var namespaces = Drupal.settings.edoweb.namespaces; var curie_parts = curie.split(':'); for (prefix in namespaces) { if (prefix == curie_parts[0]) { return namespaces[prefix] + curie_parts[1]; } } }, t: function(string) { if (string in translations) { return translations[string]; } else { return string; } }, /** * Pending AJAX requests */ pending_requests: [], /** * Function loads a tabular view for a list of linked entities */ entity_table: function(field_items, operations, view_mode) { view_mode = view_mode || 'default'; field_items.each(function() { var container = $(this); var curies = []; container.find('a[data-curie]').each(function() { curies.push(this.getAttribute('data-curie')); }); var columns = container.find('a[data-target-bundle]') .attr('data-target-bundle') .split(' ')[0]; if (columns && curies.length > 0) { container.siblings('table').remove(); var throbber = $('<div class="ajax-progress"><div class="throbber">&nbsp;</div></div>') container.before(throbber); Drupal.edoweb.entity_list('edoweb_basic', curies, columns, view_mode).onload = function () { if (this.status == 200) { var result_table = $(this.responseText).find('table'); result_table.find('a[data-curie]').not('.resolved').not('.edoweb.download').each(function() { Drupal.edoweb.entity_label($(this)); }); result_table.removeClass('sticky-enabled'); var updated_column = result_table.find('th[specifier="updated"]').index(); if (updated_column > -1) { result_table.tablesorter({sortList: [[updated_column,1]]}); } //TODO: check interference with tree navigation block //Drupal.attachBehaviors(result_table); container.find('div.field-item>a[data-curie]').each(function() { if (! result_table.find('tr[data-curie="' + $(this).attr('data-curie') + '"]').length) { var missing_entry = $(this).clone(); var row = $('<tr />'); result_table.find('thead').find('tr>th').each(function() { row.append($('<td />')); }); missing_entry.removeAttr('data-target-bundle'); row.find('td:eq(0)').append(missing_entry); row.find('td:eq(1)').append(missing_entry.attr('data-curie')); //FIXME: how to deal with this with configurable columns? result_table.append(row); } }); container.hide(); container.after(result_table); for (label in operations) { operations[label](result_table); } Drupal.edoweb.last_modified_label(result_table); Drupal.edoweb.hideEmptyTableColumns(result_table); Drupal.edoweb.hideTableHeaders(result_table); } throbber.remove(); }; } }); }, /** * Function loads a tabular view for a list of linked entities */ entity_table_detail: function(field_items, operations, view_mode) { view_mode = 'default'; field_items.each(function() { var container = $(this); var curies = []; container.find('a[data-curie]').each(function() { curies.push(this.getAttribute('data-curie')); }); var columns = container.find('a[data-target-bundle]') .attr('data-target-bundle') .split(' ')[0]; if (columns && curies.length > 0) { container.siblings('table').remove(); var throbber = $('<div class="ajax-progress"><div class="throbber">&nbsp;</div></div>') container.before(throbber); Drupal.edoweb.entity_list_detail('edoweb_basic', curies, columns, view_mode).onload = function () { if (this.status == 200) { result_table = $(this.responseText).find('table'); result_table.find('a[data-curie]').not('.resolved').not('.edoweb.download').each(function() { Drupal.edoweb.entity_label($(this)); }); result_table.removeClass('sticky-enabled'); var updated_column = result_table.find('th[specifier="updated"]').index(); if (updated_column > -1) { result_table.tablesorter({sortList: [[updated_column,1]]}); } //TODO: check interference with tree navigation block //Drupal.attachBehaviors(result_table); container.find('div.field-item>a[data-curie]').each(function() { if (! result_table.find('tr[data-curie="' + $(this).attr('data-curie') + '"]').length) { var missing_entry = $(this).clone(); var row = $('<tr />'); result_table.find('thead').find('tr>th').each(function() { row.append($('<td />')); }); missing_entry.removeAttr('data-target-bundle'); row.find('td:eq(0)').append(missing_entry); row.find('td:eq(1)').append(missing_entry.attr('data-curie')); //FIXME: how to deal with this with configurable columns? result_table.append(row); } }); container.hide(); container.after(result_table); container.after("<br/>"); for (label in operations) { operations[label](result_table); } Drupal.edoweb.last_modified_label(result_table); Drupal.edoweb.hideEmptyTableColumns(result_table); Drupal.edoweb.hideTableHeaders(result_table); } throbber.remove(); }; } }); }, /** * Function returns an entities label. */ entity_label: function(element) { var entity_type = 'edoweb_basic'; var entity_id = element.attr('data-curie'); if (cached_label = sessionStorage.getItem(entity_id)) { element.text(cached_label); } else { $.get(Drupal.settings.basePath + 'edoweb_entity_label/' + entity_type + '/' + entity_id).onload = function() { var label = this.status == 200 ? this.responseText : entity_id; if (this.status == 200) { sessionStorage.setItem(entity_id, label); } element.text(label); element.addClass('resolved'); }; } }, /** * Function returns a list of entities. */ entity_list: function(entity_type, entity_curies, columns, view_mode) { return $.get(Drupal.settings.basePath + 'edoweb_entity_list/' + entity_type + '/' + view_mode + '?' + $.param({'ids': entity_curies, 'columns': columns}) ); }, /** * Function returns a list of entities. */ entity_list_detail: function(entity_type, entity_curies, columns, view_mode) { return $.get(Drupal.settings.basePath + 'edoweb_entity_list_detail/' + entity_type + '/' + view_mode + '?' + $.param({'ids': entity_curies, 'columns': columns}) ); }, last_modified_label: function(container) { $('a.edoweb.lastmodified', container).each(function() { var link = $(this); $.get(link.attr('href'), function(data) { link.replaceWith($(data)); }); }); }, /** * Hides table columns that do not contain any data */ hideEmptyTableColumns: function(table) { // Hide table columns that do not contain any data table.find('th').each(function(i) { var remove = 0; var tds = $(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')') tds.each(function(j) { if ($(this).text() == '') remove++; }); if (remove == (table.find('tr').length - 1)) { $(this).hide(); tds.hide(); } }); }, /** * Hide the th of a table */ hideTableHeaders: function(table) { if (!(table.parent().hasClass('field-name-field-edoweb-struct-child')) && !(table.hasClass('sticky-enabled')) && !(table.closest('form').length)) { table.find('thead').hide(); } }, blockUIMessage: { message: '<div class="ajax-progress"><div class="throbber">&nbsp;</div></div> Bitte warten...' } } // AJAX navigation, if possible if (window.history && history.pushState) { Drupal.edoweb.navigateTo = function(href) { var throbber = $('<div class="ajax-progress"><div class="throbber">&nbsp;</div></div>'); $('#content').html(throbber); $.ajax({ url: href, complete: function(xmlHttp, status) { throbber.remove(); var html = $(xmlHttp.response); Drupal.attachBehaviors(html); $('#content').replaceWith(html.find('#content')); $('#breadcrumb').replaceWith(html.find('#breadcrumb')); if ($('#messages').length) { $('#messages').replaceWith(html.find('#messages')); } else { $('#header').after(html.find('#messages')); } document.title = html.filter('title').text(); $('.edoweb-tree li.active').removeClass('active'); $('.edoweb-tree li>a[href="' + location.pathname + '"]').closest('li').addClass('active'); } }); }; if (!this.attached) { history.replaceState({tree: true}, null, document.location); window.addEventListener("popstate", function(e) { if (e.state && e.state.tree) { Drupal.edoweb.navigateTo(location.pathname); if (Drupal.edoweb.refreshTree) { Drupal.edoweb.refreshTree(); } } }); this.attached = true; } } else { Drupal.edoweb.navigateTo = function(href) { window.location = href; }; } })(jQuery);
jschnasse/regal-drupal
edoweb/js/edoweb.js
JavaScript
gpl-3.0
13,745
/* * Copyright (c) 2018 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; mica.contact .factory('ContactsSearchResource', ['$resource', 'ContactSerializationService', function ($resource, ContactSerializationService) { return $resource(contextPath + '/ws/draft/persons/_search?', {}, { 'search': { method: 'GET', params: {query: '@query', 'exclude': '@exclude'}, transformResponse: ContactSerializationService.deserializeList, errorHandler: true } }); }]) .factory('PersonResource', ['$resource', function ($resource) { return $resource(contextPath + '/ws/draft/person/:id', {}, { 'get': {method: 'GET', params: {id: '@id'}}, 'update': {method: 'PUT', params: {id: '@id'}}, 'delete': {method: 'DELETE', params: {id: '@id'}}, 'create': {url: contextPath + '/ws/draft/persons', method: 'POST'}, 'getStudyMemberships': {url: contextPath + '/ws/draft/persons/study/:studyId', method: 'GET', isArray: true, params: {studyId: '@studyId'}}, 'getNetworkMemberships': {url: contextPath + '/ws/draft/persons/network/:networkId', method: 'GET', isArray: true, params: {networkId: '@networkId'}} }); }]) .factory('ContactSerializationService', ['LocalizedValues', function (LocalizedValues) { var it = this; this.serialize = function(person) { if (person.institution) { person.institution.name = LocalizedValues.objectToArray(person.institution.name); person.institution.department = LocalizedValues.objectToArray(person.institution.department); if (person.institution.address) { person.institution.address.street = LocalizedValues.objectToArray(person.institution.address.street); person.institution.address.city = LocalizedValues.objectToArray(person.institution.address.city); if (person.institution.address.country) { person.institution.address.country = {'iso': person.institution.address.country}; } } } return person; }; this.deserializeList = function (personsList) { personsList = angular.fromJson(personsList); if (personsList.persons) { personsList.persons = personsList.persons.map(function (person) { return it.deserialize(person); }); } return personsList; }; this.deserialize = function(person) { person = angular.copy(person); if (person.institution) { person.institution.name = LocalizedValues.arrayToObject(person.institution.name); person.institution.department = LocalizedValues.arrayToObject(person.institution.department); if (person.institution.address) { person.institution.address.street = LocalizedValues.arrayToObject(person.institution.address.street); person.institution.address.city = LocalizedValues.arrayToObject(person.institution.address.city); if (person.institution.address.country) { person.institution.address.country = person.institution.address.country.iso; } } } return person; }; return this; }]);
obiba/mica2
mica-webapp/src/main/webapp/app/contact/contact-service.js
JavaScript
gpl-3.0
3,513
/*! * web-SplayChat v0.4.0 - messaging web application for MTProto * http://SplayChat.com/ * Copyright (C) 2014 SplayChat Messenger <[email protected]> * http://SplayChat.com//blob/master/LICENSE */ chrome.app.runtime.onLaunched.addListener(function(launchData) { chrome.app.window.create('../index.html', { id: 'web-SplayChat-chat', innerBounds: { width: 1000, height: 700 }, minWidth: 320, minHeight: 400, frame: 'chrome' }); });
ishmaelchibvuri/splayweb.io
app/js/background.js
JavaScript
gpl-3.0
481
'use strict'; /** * A class representation of the BSON Double type. */ class Double { /** * Create a Double type * * @param {number} value the number we want to represent as a double. * @return {Double} */ constructor(value) { this.value = value; } /** * Access the number value. * * @method * @return {number} returns the wrapped double number. */ valueOf() { return this.value; } /** * @ignore */ toJSON() { return this.value; } /** * @ignore */ toExtendedJSON(options) { if (options && options.relaxed && isFinite(this.value)) return this.value; return { $numberDouble: this.value.toString() }; } /** * @ignore */ static fromExtendedJSON(doc, options) { return options && options.relaxed ? parseFloat(doc.$numberDouble) : new Double(parseFloat(doc.$numberDouble)); } } Object.defineProperty(Double.prototype, '_bsontype', { value: 'Double' }); module.exports = Double;
TamataOcean/TamataSpiru
node_modules/bson/lib/double.js
JavaScript
gpl-3.0
993
/* Scripts for cnprog.com Project Name: Lanai All Rights Resevred 2008. CNPROG.COM */ var lanai = { /** * Finds any <pre><code></code></pre> tags which aren't registered for * pretty printing, adds the appropriate class name and invokes prettify. */ highlightSyntax: function(){ var styled = false; $("pre code").parent().each(function(){ if (!$(this).hasClass('prettyprint')){ $(this).addClass('prettyprint'); styled = true; } }); if (styled){ prettyPrint(); } } }; //todo: clean-up now there is utils:WaitIcon function appendLoader(element) { loading = gettext('loading...') element.append('<img class="ajax-loader" ' + 'src="' + mediaUrl("media/images/indicator.gif") + '" title="' + loading + '" alt="' + loading + '" />'); } function removeLoader() { $("img.ajax-loader").remove(); } function setSubmitButtonDisabled(form, isDisabled) { form.find('input[type="submit"]').attr("disabled", isDisabled); } function enableSubmitButton(form) { setSubmitButtonDisabled(form, false); } function disableSubmitButton(form) { setSubmitButtonDisabled(form, true); } function setupFormValidation(form, validationRules, validationMessages, onSubmitCallback) { enableSubmitButton(form); form.validate({ debug: true, rules: (validationRules ? validationRules : {}), messages: (validationMessages ? validationMessages : {}), errorElement: "span", errorClass: "form-error", errorPlacement: function(error, element) { var span = element.next().find("span.form-error"); if (span.length === 0) { span = element.parent().find("span.form-error"); if (span.length === 0){ //for resizable textarea var element_id = element.attr('id'); span = $('label[for="' + element_id + '"]'); } } span.replaceWith(error); }, submitHandler: function(form_dom) { disableSubmitButton($(form_dom)); if (onSubmitCallback){ onSubmitCallback(); } else{ form_dom.submit(); } } }); } /** * generic tag cleaning function, settings * are from askbot live settings and askbot.const */ var cleanTag = function(tag_name, settings) { var tag_regex = new RegExp(settings['tag_regex']); if (tag_regex.test(tag_name) === false) { throw settings['messages']['wrong_chars'] } var max_length = settings['max_tag_length']; if (tag_name.length > max_length) { throw interpolate( ngettext( 'must be shorter than %(max_chars)s character', 'must be shorter than %(max_chars)s characters', max_length ), {'max_chars': max_length }, true ); } if (settings['force_lowercase_tags']) { return tag_name.toLowerCase(); } else { return tag_name; } }; var validateTagLength = function(value){ var tags = getUniqueWords(value); var are_tags_ok = true; $.each(tags, function(index, value){ if (value.length > askbot['settings']['maxTagLength']){ are_tags_ok = false; } }); return are_tags_ok; }; var validateTagCount = function(value){ var tags = getUniqueWords(value); return (tags.length <= askbot['settings']['maxTagsPerPost']); }; $.validator.addMethod('limit_tag_count', validateTagCount); $.validator.addMethod('limit_tag_length', validateTagLength); var CPValidator = function() { return { getQuestionFormRules : function() { return { tags: { required: askbot['settings']['tagsAreRequired'], maxlength: 105, limit_tag_count: true, limit_tag_length: true }, text: { minlength: askbot['settings']['minQuestionBodyLength'] }, title: { minlength: askbot['settings']['minTitleLength'] } }; }, getQuestionFormMessages: function(){ return { tags: { required: " " + gettext('tags cannot be empty'), maxlength: askbot['messages']['tagLimits'], limit_tag_count: askbot['messages']['maxTagsPerPost'], limit_tag_length: askbot['messages']['maxTagLength'] }, text: { required: " " + gettext('details are required'), minlength: interpolate( ngettext( 'details must have > %s character', 'details must have > %s characters', askbot['settings']['minQuestionBodyLength'] ), [askbot['settings']['minQuestionBodyLength'], ] ) }, title: { required: " " + gettext('enter your question'), minlength: interpolate( ngettext( 'question must have > %s character', 'question must have > %s characters', askbot['settings']['minTitleLength'] ), [askbot['settings']['minTitleLength'], ] ) } }; }, getAnswerFormRules : function(){ return { text: { minlength: askbot['settings']['minAnswerBodyLength'] }, }; }, getAnswerFormMessages: function(){ return { text: { required: " " + gettext('content cannot be empty'), minlength: interpolate( ngettext( 'answer must be > %s character', 'answer must be > %s characters', askbot['settings']['minAnswerBodyLength'] ), [askbot['settings']['minAnswerBodyLength'], ] ) }, } } }; }(); /** * @constructor */ var ThreadUsersDialog = function() { SimpleControl.call(this); this._heading_text = 'Add heading with the setHeadingText()'; }; inherits(ThreadUsersDialog, SimpleControl); ThreadUsersDialog.prototype.setHeadingText = function(text) { this._heading_text = text; }; ThreadUsersDialog.prototype.showUsers = function(html) { this._dialog.setContent(html); this._dialog.show(); }; ThreadUsersDialog.prototype.startShowingUsers = function() { var me = this; var threadId = this._threadId; var url = this._url; $.ajax({ type: 'GET', data: {'thread_id': threadId}, dataType: 'json', url: url, cache: false, success: function(data){ if (data['success'] == true){ me.showUsers(data['html']); } else { showMessage(me.getElement(), data['message'], 'after'); } } }); }; ThreadUsersDialog.prototype.decorate = function(element) { this._element = element; ThreadUsersDialog.superClass_.decorate.call(this, element); this._threadId = element.data('threadId'); this._url = element.data('url'); var dialog = new ModalDialog(); dialog.setRejectButtonText(''); dialog.setAcceptButtonText(gettext('Back to the question')); dialog.setHeadingText(this._heading_text); dialog.setAcceptHandler(function(){ dialog.hide(); }); var dialog_element = dialog.getElement(); $(dialog_element).find('.modal-footer').css('text-align', 'center'); $(document).append(dialog_element); this._dialog = dialog; var me = this; this.setHandler(function(){ me.startShowingUsers(); }); }; /** * @constructor */ var DraftPost = function() { WrappedElement.call(this); }; inherits(DraftPost, WrappedElement); /** * @return {string} */ DraftPost.prototype.getUrl = function() { throw 'Not Implemented'; }; /** * @return {boolean} */ DraftPost.prototype.shouldSave = function() { throw 'Not Implemented'; }; /** * @return {object} data dict */ DraftPost.prototype.getData = function() { throw 'Not Implemented'; }; DraftPost.prototype.backupData = function() { this._old_data = this.getData(); }; DraftPost.prototype.showNotification = function() { var note = $('.editor-status span'); note.hide(); note.html(gettext('draft saved...')); note.fadeIn().delay(3000).fadeOut(); }; DraftPost.prototype.getSaveHandler = function() { var me = this; return function(save_synchronously) { if (me.shouldSave()) { $.ajax({ type: 'POST', cache: false, dataType: 'json', async: save_synchronously ? false : true, url: me.getUrl(), data: me.getData(), success: function(data) { if (data['success'] && !save_synchronously) { me.showNotification(); } me.backupData(); } }); } }; }; DraftPost.prototype.decorate = function(element) { this._element = element; this.assignContentElements(); this.backupData(); setInterval(this.getSaveHandler(), 30000);//auto-save twice a minute var me = this; window.onbeforeunload = function() { var saveHandler = me.getSaveHandler(); saveHandler(true); //var msg = gettext("%s, we've saved your draft, but..."); //return interpolate(msg, [askbot['data']['userName']]); }; }; /** * @contstructor */ var DraftQuestion = function() { DraftPost.call(this); }; inherits(DraftQuestion, DraftPost); DraftQuestion.prototype.getUrl = function() { return askbot['urls']['saveDraftQuestion']; }; DraftQuestion.prototype.shouldSave = function() { var newd = this.getData(); var oldd = this._old_data; return ( newd['title'] !== oldd['title'] || newd['text'] !== oldd['text'] || newd['tagnames'] !== oldd['tagnames'] ); }; DraftQuestion.prototype.getData = function() { return { 'title': this._title_element.val(), 'text': this._text_element.val(), 'tagnames': this._tagnames_element.val() }; }; DraftQuestion.prototype.assignContentElements = function() { this._title_element = $('#id_title'); this._text_element = $('#editor'); this._tagnames_element = $('#id_tags'); }; var DraftAnswer = function() { DraftPost.call(this); }; inherits(DraftAnswer, DraftPost); DraftAnswer.prototype.setThreadId = function(id) { this._threadId = id; }; DraftAnswer.prototype.getUrl = function() { return askbot['urls']['saveDraftAnswer']; }; DraftAnswer.prototype.shouldSave = function() { return this.getData()['text'] !== this._old_data['text']; }; DraftAnswer.prototype.getData = function() { return { 'text': this._textElement.val(), 'thread_id': this._threadId }; }; DraftAnswer.prototype.assignContentElements = function() { this._textElement = $('#editor'); }; /** * @constructor * @extends {SimpleControl} * @param {Comment} comment to upvote */ var CommentVoteButton = function(comment){ SimpleControl.call(this); /** * @param {Comment} */ this._comment = comment; /** * @type {boolean} */ this._voted = false; /** * @type {number} */ this._score = 0; }; inherits(CommentVoteButton, SimpleControl); /** * @param {number} score */ CommentVoteButton.prototype.setScore = function(score){ this._score = score; if (this._element){ this._element.html(score); } }; /** * @param {boolean} voted */ CommentVoteButton.prototype.setVoted = function(voted){ this._voted = voted; if (this._element){ this._element.addClass('upvoted'); } }; CommentVoteButton.prototype.getVoteHandler = function(){ var me = this; var comment = this._comment; return function(){ var voted = me._voted; var post_id = me._comment.getId(); var data = { cancel_vote: voted ? true:false, post_id: post_id }; $.ajax({ type: 'POST', data: data, dataType: 'json', url: askbot['urls']['upvote_comment'], cache: false, success: function(data){ if (data['success'] == true){ me.setScore(data['score']); me.setVoted(true); } else { showMessage(comment.getElement(), data['message'], 'after'); } } }); }; }; CommentVoteButton.prototype.decorate = function(element){ this._element = element; this.setHandler(this.getVoteHandler()); var element = this._element; var comment = this._comment; /* can't call comment.getElement() here due * an issue in the getElement() of comment * so use an "illegal" access to comment._element here */ comment._element.mouseenter(function(){ //outside height may not be known //var height = comment.getElement().height(); //element.height(height); element.addClass('hover'); }); comment._element.mouseleave(function(){ element.removeClass('hover'); }); }; CommentVoteButton.prototype.createDom = function(){ this._element = this.makeElement('div'); if (this._score > 0){ this._element.html(this._score); } this._element.addClass('upvote'); if (this._voted){ this._element.addClass('upvoted'); } this.decorate(this._element); }; /** * legacy Vote class * handles all sorts of vote-like operations */ var Vote = function(){ // All actions are related to a question var questionId; //question slug to build redirect urls var questionSlug; // The object we operate on actually. It can be a question or an answer. var postId; var questionAuthorId; var currentUserId; var answerContainerIdPrefix = 'post-id-'; var voteContainerId = 'vote-buttons'; var imgIdPrefixAccept = 'answer-img-accept-'; var classPrefixFollow= 'button follow'; var classPrefixFollowed= 'button followed'; var imgIdPrefixQuestionVoteup = 'question-img-upvote-'; var imgIdPrefixQuestionVotedown = 'question-img-downvote-'; var imgIdPrefixAnswerVoteup = 'answer-img-upvote-'; var imgIdPrefixAnswerVotedown = 'answer-img-downvote-'; var divIdFavorite = 'favorite-number'; var commentLinkIdPrefix = 'comment-'; var voteNumberClass = "vote-number"; var offensiveIdPrefixQuestionFlag = 'question-offensive-flag-'; var removeOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-flag-'; var removeAllOffensiveIdPrefixQuestionFlag = 'question-offensive-remove-all-flag-'; var offensiveIdPrefixAnswerFlag = 'answer-offensive-flag-'; var removeOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-flag-'; var removeAllOffensiveIdPrefixAnswerFlag = 'answer-offensive-remove-all-flag-'; var offensiveClassFlag = 'offensive-flag'; var questionControlsId = 'question-controls'; var removeAnswerLinkIdPrefix = 'answer-delete-link-'; var questionSubscribeUpdates = 'question-subscribe-updates'; var questionSubscribeSidebar= 'question-subscribe-sidebar'; var acceptAnonymousMessage = gettext('insufficient privilege'); var acceptOwnAnswerMessage = gettext('cannot pick own answer as best'); var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">" + gettext('please login') + "</a>"; var favoriteAnonymousMessage = gettext('anonymous users cannot follow questions') + pleaseLogin; var subscribeAnonymousMessage = gettext('anonymous users cannot subscribe to questions') + pleaseLogin; var voteAnonymousMessage = gettext('anonymous users cannot vote') + pleaseLogin; //there were a couple of more messages... var offensiveConfirmation = gettext('please confirm offensive'); var removeOffensiveConfirmation = gettext('please confirm removal of offensive flag'); var offensiveAnonymousMessage = gettext('anonymous users cannot flag offensive posts') + pleaseLogin; var removeConfirmation = gettext('confirm delete'); var removeAnonymousMessage = gettext('anonymous users cannot delete/undelete') + pleaseLogin; var recoveredMessage = gettext('post recovered'); var deletedMessage = gettext('post deleted'); var VoteType = { acceptAnswer : 0, questionUpVote : 1, questionDownVote : 2, favorite : 4, answerUpVote: 5, answerDownVote:6, offensiveQuestion : 7, removeOffensiveQuestion : 7.5, removeAllOffensiveQuestion : 7.6, offensiveAnswer:8, removeOffensiveAnswer:8.5, removeAllOffensiveAnswer:8.6, removeQuestion: 9,//deprecate removeAnswer:10,//deprecate questionSubscribeUpdates:11, questionUnsubscribeUpdates:12 }; var getFavoriteButton = function(){ var favoriteButton = 'div.'+ voteContainerId +' a[class="'+ classPrefixFollow +'"]'; favoriteButton += ', div.'+ voteContainerId +' a[class="'+ classPrefixFollowed +'"]'; return $(favoriteButton); }; var getFavoriteNumber = function(){ var favoriteNumber = '#'+ divIdFavorite ; return $(favoriteNumber); }; var getQuestionVoteUpButton = function(){ var questionVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVoteup +'"]'; return $(questionVoteUpButton); }; var getQuestionVoteDownButton = function(){ var questionVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixQuestionVotedown +'"]'; return $(questionVoteDownButton); }; var getAnswerVoteUpButtons = function(){ var answerVoteUpButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVoteup +'"]'; return $(answerVoteUpButton); }; var getAnswerVoteDownButtons = function(){ var answerVoteDownButton = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAnswerVotedown +'"]'; return $(answerVoteDownButton); }; var getAnswerVoteUpButton = function(id){ var answerVoteUpButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVoteup + id + '"]'; return $(answerVoteUpButton); }; var getAnswerVoteDownButton = function(id){ var answerVoteDownButton = 'div.'+ voteContainerId +' div[id="'+ imgIdPrefixAnswerVotedown + id + '"]'; return $(answerVoteDownButton); }; var getOffensiveQuestionFlag = function(){ var offensiveQuestionFlag = '.question-card span[id^="'+ offensiveIdPrefixQuestionFlag +'"]'; return $(offensiveQuestionFlag); }; var getRemoveOffensiveQuestionFlag = function(){ var removeOffensiveQuestionFlag = '.question-card span[id^="'+ removeOffensiveIdPrefixQuestionFlag +'"]'; return $(removeOffensiveQuestionFlag); }; var getRemoveAllOffensiveQuestionFlag = function(){ var removeAllOffensiveQuestionFlag = '.question-card span[id^="'+ removeAllOffensiveIdPrefixQuestionFlag +'"]'; return $(removeAllOffensiveQuestionFlag); }; var getOffensiveAnswerFlags = function(){ var offensiveQuestionFlag = 'div.answer span[id^="'+ offensiveIdPrefixAnswerFlag +'"]'; return $(offensiveQuestionFlag); }; var getRemoveOffensiveAnswerFlag = function(){ var removeOffensiveAnswerFlag = 'div.answer span[id^="'+ removeOffensiveIdPrefixAnswerFlag +'"]'; return $(removeOffensiveAnswerFlag); }; var getRemoveAllOffensiveAnswerFlag = function(){ var removeAllOffensiveAnswerFlag = 'div.answer span[id^="'+ removeAllOffensiveIdPrefixAnswerFlag +'"]'; return $(removeAllOffensiveAnswerFlag); }; var getquestionSubscribeUpdatesCheckbox = function(){ return $('#' + questionSubscribeUpdates); }; var getquestionSubscribeSidebarCheckbox= function(){ return $('#' + questionSubscribeSidebar); }; var getremoveAnswersLinks = function(){ var removeAnswerLinks = 'div.answer-controls a[id^="'+ removeAnswerLinkIdPrefix +'"]'; return $(removeAnswerLinks); }; var setVoteImage = function(voteType, undo, object){ var flag = undo ? false : true; if (object.hasClass("on")) { object.removeClass("on"); }else{ object.addClass("on"); } if(undo){ if(voteType == VoteType.questionUpVote || voteType == VoteType.questionDownVote){ $(getQuestionVoteUpButton()).removeClass("on"); $(getQuestionVoteDownButton()).removeClass("on"); } else{ $(getAnswerVoteUpButton(postId)).removeClass("on"); $(getAnswerVoteDownButton(postId)).removeClass("on"); } } }; var setVoteNumber = function(object, number){ var voteNumber = object.parent('div.'+ voteContainerId).find('div.'+ voteNumberClass); $(voteNumber).text(number); }; var bindEvents = function(){ // accept answers var acceptedButtons = 'div.'+ voteContainerId +' div[id^="'+ imgIdPrefixAccept +'"]'; $(acceptedButtons).unbind('click').click(function(event){ Vote.accept($(event.target)); }); // set favorite question var favoriteButton = getFavoriteButton(); favoriteButton.unbind('click').click(function(event){ //Vote.favorite($(event.target)); Vote.favorite(favoriteButton); }); // question vote up var questionVoteUpButton = getQuestionVoteUpButton(); questionVoteUpButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.questionUpVote); }); var questionVoteDownButton = getQuestionVoteDownButton(); questionVoteDownButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.questionDownVote); }); var answerVoteUpButton = getAnswerVoteUpButtons(); answerVoteUpButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.answerUpVote); }); var answerVoteDownButton = getAnswerVoteDownButtons(); answerVoteDownButton.unbind('click').click(function(event){ Vote.vote($(event.target), VoteType.answerDownVote); }); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveQuestion); }); getRemoveAllOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_all_offensive(this, VoteType.removeAllOffensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveAnswer); }); getRemoveAllOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_all_offensive(this, VoteType.removeAllOffensiveAnswer); }); getquestionSubscribeUpdatesCheckbox().unbind('click').click(function(event){ //despeluchar esto if (this.checked){ getquestionSubscribeSidebarCheckbox().attr({'checked': true}); Vote.vote($(event.target), VoteType.questionSubscribeUpdates); } else { getquestionSubscribeSidebarCheckbox().attr({'checked': false}); Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates); } }); getquestionSubscribeSidebarCheckbox().unbind('click').click(function(event){ if (this.checked){ getquestionSubscribeUpdatesCheckbox().attr({'checked': true}); Vote.vote($(event.target), VoteType.questionSubscribeUpdates); } else { getquestionSubscribeUpdatesCheckbox().attr({'checked': false}); Vote.vote($(event.target), VoteType.questionUnsubscribeUpdates); } }); getremoveAnswersLinks().unbind('click').click(function(event){ Vote.remove(this, VoteType.removeAnswer); }); }; var submit = function(object, voteType, callback) { //this function submits votes $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['vote_url'], data: { "type": voteType, "postId": postId }, error: handleFail, success: function(data) { callback(object, voteType, data); } }); }; var handleFail = function(xhr, msg){ alert("Callback invoke error: " + msg); }; // callback function for Accept Answer action var callback_accept = function(object, voteType, data){ if(data.allowed == "0" && data.success == "0"){ showMessage(object, acceptAnonymousMessage); } else if(data.allowed == "-1"){ showMessage(object, acceptOwnAnswerMessage); } else if(data.status == "1"){ $("#"+answerContainerIdPrefix+postId).removeClass("accepted-answer"); $("#"+commentLinkIdPrefix+postId).removeClass("comment-link-accepted"); } else if(data.success == "1"){ var answers = ('div[id^="'+answerContainerIdPrefix +'"]'); $(answers).removeClass('accepted-answer'); var commentLinks = ('div[id^="'+answerContainerIdPrefix +'"] div[id^="'+ commentLinkIdPrefix +'"]'); $(commentLinks).removeClass("comment-link-accepted"); $("#"+answerContainerIdPrefix+postId).addClass("accepted-answer"); $("#"+commentLinkIdPrefix+postId).addClass("comment-link-accepted"); } else{ showMessage(object, data.message); } }; var callback_favorite = function(object, voteType, data){ if(data.allowed == "0" && data.success == "0"){ showMessage( object, favoriteAnonymousMessage.replace( '{{QuestionID}}', questionId).replace( '{{questionSlug}}', '' ) ); } else if(data.status == "1"){ var follow_html = gettext('Follow'); object.attr("class", 'button follow'); object.html(follow_html); var fav = getFavoriteNumber(); fav.removeClass("my-favorite-number"); if(data.count === 0){ data.count = ''; fav.text(''); }else{ var fmts = ngettext('%s follower', '%s followers', data.count); fav.text(interpolate(fmts, [data.count])); } } else if(data.success == "1"){ var followed_html = gettext('<div>Following</div><div class="unfollow">Unfollow</div>'); object.html(followed_html); object.attr("class", 'button followed'); var fav = getFavoriteNumber(); var fmts = ngettext('%s follower', '%s followers', data.count); fav.text(interpolate(fmts, [data.count])); fav.addClass("my-favorite-number"); } else{ showMessage(object, data.message); } }; var callback_vote = function(object, voteType, data){ if (data.success == '0'){ showMessage(object, data.message); return; } else { if (data.status == '1'){ setVoteImage(voteType, true, object); } else { setVoteImage(voteType, false, object); } setVoteNumber(object, data.count); if (data.message && data.message.length > 0){ showMessage(object, data.message); } return; } //may need to take a look at this again if (data.status == "1"){ setVoteImage(voteType, true, object); setVoteNumber(object, data.count); } else if (data.success == "1"){ setVoteImage(voteType, false, object); setVoteNumber(object, data.count); if (data.message.length > 0){ showMessage(object, data.message); } } }; var callback_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0) $(object).children('span[class="darkred"]').text("("+ data.count +")"); else $(object).children('span[class="darkred"]').text(""); // Change the link text and rebind events $(object).find("a.question-flag").html(gettext("remove flag")); var obj_id = $(object).attr("id"); $(object).attr("id", obj_id.replace("flag-", "remove-flag-")); getRemoveOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveQuestion); }); getRemoveOffensiveAnswerFlag().unbind('click').click(function(event){ Vote.remove_offensive(this, VoteType.removeOffensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0){ $(object).children('span[class="darkred"]').text("("+ data.count +")"); } else{ $(object).children('span[class="darkred"]').text(""); // Remove "remove all flags link" since there are no more flags to remove var remove_all = $(object).siblings('span.offensive-flag[id*="-offensive-remove-all-flag-"]'); $(remove_all).next("span.sep").remove(); $(remove_all).remove(); } // Change the link text and rebind events $(object).find("a.question-flag").html(gettext("flag offensive")); var obj_id = $(object).attr("id"); $(object).attr("id", obj_id.replace("remove-flag-", "flag-")); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove_all_offensive = function(object, voteType, data){ //todo: transfer proper translations of these from i18n.js //to django.po files //_('anonymous users cannot flag offensive posts') + pleaseLogin; if (data.success == "1"){ if(data.count > 0) $(object).children('span[class="darkred"]').text("("+ data.count +")"); else $(object).children('span[class="darkred"]').text(""); // remove the link. All flags are gone var remove_own = $(object).siblings('span.offensive-flag[id*="-offensive-remove-flag-"]'); $(remove_own).find("a.question-flag").html(gettext("flag offensive")); $(remove_own).attr("id", $(remove_own).attr("id").replace("remove-flag-", "flag-")); $(object).next("span.sep").remove(); $(object).remove(); getOffensiveQuestionFlag().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveQuestion); }); getOffensiveAnswerFlags().unbind('click').click(function(event){ Vote.offensive(this, VoteType.offensiveAnswer); }); } else { object = $(object); showMessage(object, data.message) } }; var callback_remove = function(object, voteType, data){ if (data.success == "1"){ if (removeActionType == 'delete'){ postNode.addClass('deleted'); postRemoveLink.innerHTML = gettext('undelete'); showMessage(object, deletedMessage); } else if (removeActionType == 'undelete') { postNode.removeClass('deleted'); postRemoveLink.innerHTML = gettext('delete'); showMessage(object, recoveredMessage); } } else { showMessage(object, data.message) } }; return { init : function(qId, qSlug, questionAuthor, userId){ questionId = qId; questionSlug = qSlug; questionAuthorId = questionAuthor; currentUserId = '' + userId;//convert to string bindEvents(); }, //accept answer accept: function(object){ postId = object.attr("id").substring(imgIdPrefixAccept.length); submit(object, VoteType.acceptAnswer, callback_accept); }, //mark question as favorite favorite: function(object){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( object, favoriteAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } postId = questionId; submit(object, VoteType.favorite, callback_favorite); }, vote: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE") { if (voteType == VoteType.questionSubscribeUpdates || voteType == VoteType.questionUnsubscribeUpdates){ getquestionSubscribeSidebarCheckbox().removeAttr('checked'); getquestionSubscribeUpdatesCheckbox().removeAttr('checked'); showMessage(object, subscribeAnonymousMessage); } else { showMessage( $(object), voteAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); } return false; } // up and downvote processor if (voteType == VoteType.answerUpVote){ postId = object.attr("id").substring(imgIdPrefixAnswerVoteup.length); } else if (voteType == VoteType.answerDownVote){ postId = object.attr("id").substring(imgIdPrefixAnswerVotedown.length); } else { postId = questionId; } submit(object, voteType, callback_vote); }, //flag offensive offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(offensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_offensive); } }, //remove flag offensive remove_offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(removeOffensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_remove_offensive); } }, remove_all_offensive: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), offensiveAnonymousMessage.replace( "{{QuestionID}}", questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } if (confirm(removeOffensiveConfirmation)){ postId = object.id.substr(object.id.lastIndexOf('-') + 1); submit(object, voteType, callback_remove_all_offensive); } }, //delete question or answer (comments are deleted separately) remove: function(object, voteType){ if (!currentUserId || currentUserId.toUpperCase() == "NONE"){ showMessage( $(object), removeAnonymousMessage.replace( '{{QuestionID}}', questionId ).replace( '{{questionSlug}}', questionSlug ) ); return false; } bits = object.id.split('-'); postId = bits.pop();/* this seems to be used within submit! */ postType = bits.shift(); var do_proceed = false; postNode = $('#post-id-' + postId); postRemoveLink = object; if (postNode.hasClass('deleted')) { removeActionType = 'undelete'; do_proceed = true; } else { removeActionType = 'delete'; do_proceed = confirm(removeConfirmation); } if (do_proceed) { submit($(object), voteType, callback_remove); } } }; } (); var questionRetagger = function(){ var oldTagsHTML = ''; var tagInput = null; var tagsDiv = null; var retagLink = null; var restoreEventHandlers = function(){ $(document).unbind('click'); }; var cancelRetag = function(){ tagsDiv.html(oldTagsHTML); tagsDiv.removeClass('post-retag'); tagsDiv.addClass('post-tags'); restoreEventHandlers(); initRetagger(); }; var drawNewTags = function(new_tags){ tagsDiv.empty(); if (new_tags === ''){ return; } new_tags = new_tags.split(/\s+/); var tags_html = '' $.each(new_tags, function(index, name){ var tag = new Tag(); tag.setName(name); tagsDiv.append(tag.getElement()); }); }; var doRetag = function(){ $.ajax({ type: "POST", url: retagUrl,//todo add this url to askbot['urls'] dataType: "json", data: { tags: getUniqueWords(tagInput.val()).join(' ') }, success: function(json) { if (json['success'] === true){ new_tags = getUniqueWords(json['new_tags']); oldTagsHtml = ''; cancelRetag(); drawNewTags(new_tags.join(' ')); if (json['message']) { notify.show(json['message']); } } else { cancelRetag(); showMessage(tagsDiv, json['message']); } }, error: function(xhr, textStatus, errorThrown) { showMessage(tagsDiv, gettext('sorry, something is not right here')); cancelRetag(); } }); return false; } var setupInputEventHandlers = function(input){ input.keydown(function(e){ if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)){ cancelRetag(); } }); $(document).unbind('click').click(cancelRetag, false); input.click(function(){return false}); }; var createRetagForm = function(old_tags_string){ var div = $('<form method="post"></form>'); tagInput = $('<input id="retag_tags" type="text" autocomplete="off" name="tags" size="30"/>'); //var tagLabel = $('<label for="retag_tags" class="error"></label>'); //populate input var tagAc = new AutoCompleter({ url: askbot['urls']['get_tag_list'], minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10 }); tagAc.decorate(tagInput); tagInput.val(old_tags_string); div.append(tagInput); //div.append(tagLabel); setupInputEventHandlers(tagInput); //button = $('<input type="submit" />'); //button.val(gettext('save tags')); //div.append(button); //setupButtonEventHandlers(button); div.validate({//copy-paste from utils.js rules: { tags: { required: askbot['settings']['tagsAreRequired'], maxlength: askbot['settings']['maxTagsPerPost'] * askbot['settings']['maxTagLength'], limit_tag_count: true, limit_tag_length: true } }, messages: { tags: { required: gettext('tags cannot be empty'), maxlength: askbot['messages']['tagLimits'], limit_tag_count: askbot['messages']['maxTagsPerPost'], limit_tag_length: askbot['messages']['maxTagLength'] } }, submitHandler: doRetag, errorClass: "retag-error" }); return div; }; var getTagsAsString = function(tags_div){ var links = tags_div.find('a'); var tags_str = ''; links.each(function(index, element){ if (index === 0){ //this is pretty bad - we should use Tag.getName() tags_str = $(element).data('tagName'); } else { tags_str += ' ' + $(element).data('tagName'); } }); return tags_str; }; var noopHandler = function(){ tagInput.focus(); return false; }; var deactivateRetagLink = function(){ retagLink.unbind('click').click(noopHandler); retagLink.unbind('keypress').keypress(noopHandler); }; var startRetag = function(){ tagsDiv = $('#question-tags'); oldTagsHTML = tagsDiv.html();//save to restore on cancel var old_tags_string = getTagsAsString(tagsDiv); var retag_form = createRetagForm(old_tags_string); tagsDiv.html(''); tagsDiv.append(retag_form); tagsDiv.removeClass('post-tags'); tagsDiv.addClass('post-retag'); tagInput.focus(); deactivateRetagLink(); return false; }; var setupClickAndEnterHandler = function(element, callback){ element.unbind('click').click(callback); element.unbind('keypress').keypress(function(e){ if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ callback(); } }); } var initRetagger = function(){ setupClickAndEnterHandler(retagLink, startRetag); }; return { init: function(){ retagLink = $('#retag'); initRetagger(); } }; }(); /** * @constructor * Controls vor voting for a post */ var VoteControls = function() { WrappedElement.call(this); this._postAuthorId = undefined; this._postId = undefined; }; inherits(VoteControls, WrappedElement); VoteControls.prototype.setPostId = function(postId) { this._postId = postId; }; VoteControls.prototype.getPostId = function() { return this._postId; }; VoteControls.prototype.setPostAuthorId = function(userId) { this._postAuthorId = userId; }; VoteControls.prototype.setSlug = function(slug) { this._slug = slug; }; VoteControls.prototype.setPostType = function(postType) { this._postType = postType; }; VoteControls.prototype.getPostType = function() { return this._postType; }; VoteControls.prototype.clearVotes = function() { this._upvoteButton.removeClass('on'); this._downvoteButton.removeClass('on'); }; VoteControls.prototype.toggleButton = function(button) { if (button.hasClass('on')) { button.removeClass('on'); } else { button.addClass('on'); } }; VoteControls.prototype.toggleVote = function(voteType) { if (voteType === 'upvote') { this.toggleButton(this._upvoteButton); } else { this.toggleButton(this._downvoteButton); } }; VoteControls.prototype.setVoteCount = function(count) { this._voteCount.html(count); }; VoteControls.prototype.updateDisplay = function(voteType, data) { if (data['status'] == '1'){ this.clearVotes(); } else { this.toggleVote(voteType); } this.setVoteCount(data['count']); if (data['message'] && data['message'].length > 0){ showMessage(this._element, data.message); } }; VoteControls.prototype.getAnonymousMessage = function(message) { var pleaseLogin = " <a href='" + askbot['urls']['user_signin'] + ">" + gettext('please login') + "</a>"; message += pleaseLogin; message = message.replace("{{QuestionID}}", this._postId); return message.replace('{{questionSlug}}', this._slug); }; VoteControls.prototype.getVoteHandler = function(voteType) { var me = this; return function() { if (askbot['data']['userIsAuthenticated'] === false) { var message = me.getAnonymousMessage(gettext('anonymous users cannot vote')); showMessage(me.getElement(), message); } else { //this function submits votes var voteMap = { 'question': { 'upvote': 1, 'downvote': 2 }, 'answer': { 'upvote': 5, 'downvote': 6 } }; var legacyVoteType = voteMap[me.getPostType()][voteType]; $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['vote_url'], data: { "type": legacyVoteType, "postId": me.getPostId() }, error: function() { showMessage(me.getElement(), gettext('sorry, something is not right here')); }, success: function(data) { if (data['success']) { me.updateDisplay(voteType, data); } else { showMessage(me.getElement(), data['message']); } } }); } }; }; VoteControls.prototype.decorate = function(element) { this._element = element; var upvoteButton = element.find('.upvote'); this._upvoteButton = upvoteButton; setupButtonEventHandlers(upvoteButton, this.getVoteHandler('upvote')); var downvoteButton = element.find('.downvote'); this._downvoteButton = downvoteButton; setupButtonEventHandlers(downvoteButton, this.getVoteHandler('downvote')); this._voteCount = element.find('.vote-number'); }; var DeletePostLink = function(){ SimpleControl.call(this); this._post_id = null; }; inherits(DeletePostLink, SimpleControl); DeletePostLink.prototype.setPostId = function(id){ this._post_id = id; }; DeletePostLink.prototype.getPostId = function(){ return this._post_id; }; DeletePostLink.prototype.getPostElement = function(){ return $('#post-id-' + this.getPostId()); }; DeletePostLink.prototype.isPostDeleted = function(){ return this._post_deleted; }; DeletePostLink.prototype.setPostDeleted = function(is_deleted){ var post = this.getPostElement(); if (is_deleted === true){ post.addClass('deleted'); this._post_deleted = true; this.getElement().html(gettext('undelete')); } else if (is_deleted === false){ post.removeClass('deleted'); this._post_deleted = false; this.getElement().html(gettext('delete')); } }; DeletePostLink.prototype.getDeleteHandler = function(){ var me = this; var post_id = this.getPostId(); return function(){ var data = { 'post_id': me.getPostId(), //todo rename cancel_vote -> undo 'cancel_vote': me.isPostDeleted() ? true: false }; $.ajax({ type: 'POST', data: data, dataType: 'json', url: askbot['urls']['delete_post'], cache: false, success: function(data){ if (data['success'] == true){ me.setPostDeleted(data['is_deleted']); } else { showMessage(me.getElement(), data['message']); } } }); }; }; DeletePostLink.prototype.decorate = function(element){ this._element = element; this._post_deleted = this.getPostElement().hasClass('deleted'); this.setHandler(this.getDeleteHandler()); } /** * Form for editing and posting new comment * supports 3 editors: markdown, tinymce and plain textarea. * There is only one instance of this form in use on the question page. * It can be attached to any comment on the page, or to a new blank * comment. */ var EditCommentForm = function(){ WrappedElement.call(this); this._comment = null; this._comment_widget = null; this._element = null; this._editorReady = false; this._text = ''; }; inherits(EditCommentForm, WrappedElement); EditCommentForm.prototype.setWaitingStatus = function(isWaiting) { if (isWaiting === true) { this._editor.getElement().hide(); this._submit_btn.hide(); this._cancel_btn.hide(); this._minorEditBox.hide(); this._element.hide(); } else { this._element.show(); this._editor.getElement().show(); this._submit_btn.show(); this._cancel_btn.show(); this._minorEditBox.show(); } }; EditCommentForm.prototype.getEditorType = function() { if (askbot['settings']['commentsEditorType'] === 'rich-text') { return askbot['settings']['editorType']; } else { return 'plain-text'; } }; EditCommentForm.prototype.startTinyMCEEditor = function() { var editorId = this.makeId('comment-editor'); var opts = { mode: 'exact', content_css: mediaUrl('media/style/tinymce/comments-content.css'), elements: editorId, plugins: 'autoresize', theme: 'advanced', theme_advanced_toolbar_location: 'top', theme_advanced_toolbar_align: 'left', theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist', theme_advanced_buttons2: '', theme_advanced_path: false, plugins: '', width: '100%', height: '70' }; var editor = new TinyMCE(opts); editor.setId(editorId); editor.setText(this._text); this._editorBox.prepend(editor.getElement()); editor.start(); this._editor = editor; }; EditCommentForm.prototype.startWMDEditor = function() { var editor = new WMD(); editor.setEnabledButtons('bold italic link code ol ul'); editor.setPreviewerEnabled(false); editor.setText(this._text); this._editorBox.prepend(editor.getElement());//attach DOM before start editor.start();//have to start after attaching DOM this._editor = editor; }; EditCommentForm.prototype.startSimpleEditor = function() { this._editor = new SimpleEditor(); this._editorBox.prepend(this._editor.getElement()); }; EditCommentForm.prototype.startEditor = function() { var editorType = this.getEditorType(); if (editorType === 'tinymce') { this.startTinyMCEEditor(); //@todo: implement save on enter and character counter in tinyMCE return; } else if (editorType === 'markdown') { this.startWMDEditor(); } else { this.startSimpleEditor(); } //code below is common to SimpleEditor and WMD var editorElement = this._editor.getElement(); var updateCounter = this.getCounterUpdater(); var escapeHandler = makeKeyHandler(27, this.getCancelHandler()); //todo: try this on the div var editor = this._editor; //this should be set on the textarea! editorElement.blur(updateCounter); editorElement.focus(updateCounter); editorElement.keyup(updateCounter) editorElement.keyup(escapeHandler); if (askbot['settings']['saveCommentOnEnter']){ var save_handler = makeKeyHandler(13, this.getSaveHandler()); editor.getElement().keydown(save_handler); } }; /** * attaches comment editor to a particular comment */ EditCommentForm.prototype.attachTo = function(comment, mode){ this._comment = comment; this._type = mode;//action: 'add' or 'edit' this._comment_widget = comment.getContainerWidget(); this._text = comment.getText(); comment.getElement().after(this.getElement()); comment.getElement().hide(); this._comment_widget.hideButton();//hide add comment button //fix up the comment submit button, depending on the mode if (this._type == 'add'){ this._submit_btn.html(gettext('add comment')); if (this._minorEditBox) { this._minorEditBox.hide(); } } else { this._submit_btn.html(gettext('save comment')); if (this._minorEditBox) { this._minorEditBox.show(); } } //enable the editor this.getElement().show(); this.enableForm(); this.startEditor(); this._editor.setText(this._text); var ed = this._editor var onFocus = function() { ed.putCursorAtEnd(); }; this._editor.focus(onFocus); setupButtonEventHandlers(this._submit_btn, this.getSaveHandler()); setupButtonEventHandlers(this._cancel_btn, this.getCancelHandler()); }; EditCommentForm.prototype.getCounterUpdater = function(){ //returns event handler var counter = this._text_counter; var editor = this._editor; var handler = function(){ var length = editor.getText().length; var length1 = maxCommentLength - 100; if (length1 < 0){ length1 = Math.round(0.7*maxCommentLength); } var length2 = maxCommentLength - 30; if (length2 < 0){ length2 = Math.round(0.9*maxCommentLength); } /* todo make smooth color transition, from gray to red * or rather - from start color to end color */ var color = 'maroon'; var chars = 10; if (length === 0){ var feedback = interpolate(gettext('enter at least %s characters'), [chars]); } else if (length < 10){ var feedback = interpolate(gettext('enter at least %s more characters'), [chars - length]); } else { if (length > length2) { color = '#f00'; } else if (length > length1) { color = '#f60'; } else { color = '#999'; } chars = maxCommentLength - length; var feedback = interpolate(gettext('%s characters left'), [chars]); } counter.html(feedback); counter.css('color', color); return true; }; return handler; }; /** * @todo: clean up this method so it does just one thing */ EditCommentForm.prototype.canCancel = function(){ if (this._element === null){ return true; } if (this._editor === undefined) { return true; }; var ctext = this._editor.getText(); if ($.trim(ctext) == $.trim(this._text)){ return true; } else if (this.confirmAbandon()){ return true; } this._editor.focus(); return false; }; EditCommentForm.prototype.getCancelHandler = function(){ var form = this; return function(evt){ if (form.canCancel()){ form.detach(); evt.preventDefault(); } return false; }; }; EditCommentForm.prototype.detach = function(){ if (this._comment === null){ return; } this._comment.getContainerWidget().showButton(); if (this._comment.isBlank()){ this._comment.dispose(); } else { this._comment.getElement().show(); } this.reset(); this._element = this._element.detach(); this._editor.dispose(); this._editor = undefined; removeButtonEventHandlers(this._submit_btn); removeButtonEventHandlers(this._cancel_btn); }; EditCommentForm.prototype.createDom = function(){ this._element = $('<form></form>'); this._element.attr('class', 'post-comments'); var div = $('<div></div>'); this._element.append(div); /** a stub container for the editor */ this._editorBox = div; /** * editor itself will live at this._editor * and will be initialized by the attachTo() */ this._controlsBox = this.makeElement('div'); this._controlsBox.addClass('edit-comment-buttons'); div.append(this._controlsBox); this._text_counter = $('<span></span>').attr('class', 'counter'); this._controlsBox.append(this._text_counter); this._submit_btn = $('<button class="submit"></button>'); this._controlsBox.append(this._submit_btn); this._cancel_btn = $('<button class="submit"></button>'); this._cancel_btn.html(gettext('cancel')); this._controlsBox.append(this._cancel_btn); //if email alerts are enabled, add a checkbox "suppress_email" if (askbot['settings']['enableEmailAlerts'] === true) { this._minorEditBox = this.makeElement('div'); this._minorEditBox.addClass('checkbox'); this._controlsBox.append(this._minorEditBox); var checkBox = this.makeElement('input'); checkBox.attr('type', 'checkbox'); checkBox.attr('name', 'suppress_email'); this._minorEditBox.append(checkBox); var label = this.makeElement('label'); label.attr('for', 'suppress_email'); label.html(gettext("minor edit (don't send alerts)")); this._minorEditBox.append(label); } }; EditCommentForm.prototype.isEnabled = function() { return (this._submit_btn.attr('disabled') !== 'disabled');//confusing! setters use boolean }; EditCommentForm.prototype.enableForm = function() { this._submit_btn.attr('disabled', false); this._cancel_btn.attr('disabled', false); }; EditCommentForm.prototype.disableForm = function() { this._submit_btn.attr('disabled', true); this._cancel_btn.attr('disabled', true); }; EditCommentForm.prototype.reset = function(){ this._comment = null; this._text = ''; this._editor.setText(''); this.enableForm(); }; EditCommentForm.prototype.confirmAbandon = function(){ this._editor.focus(); this._editor.getElement().scrollTop(); this._editor.setHighlight(true); var answer = confirm( gettext("Are you sure you don't want to post this comment?") ); this._editor.setHighlight(false); return answer; }; EditCommentForm.prototype.getSuppressEmail = function() { return this._element.find('input[name="suppress_email"]').is(':checked'); }; EditCommentForm.prototype.setSuppressEmail = function(bool) { this._element.find('input[name="suppress_email"]').prop('checked', bool); }; EditCommentForm.prototype.getSaveHandler = function(){ var me = this; var editor = this._editor; return function(){ if (me.isEnabled() === false) {//prevent double submits return false; } me.disableForm(); var text = editor.getText(); if (text.length < askbot['settings']['minCommentBodyLength']){ editor.focus(); me.enableForm(); return false; } //display the comment and show that it is not yet saved me.setWaitingStatus(true); me._comment.getElement().show(); var commentData = me._comment.getData(); var timestamp = commentData['comment_added_at'] || gettext('just now'); var userName = commentData['user_display_name'] || askbot['data']['userName']; me._comment.setContent({ 'html': editor.getHtml(), 'text': text, 'user_display_name': userName, 'comment_added_at': timestamp }); me._comment.setDraftStatus(true); me._comment.getContainerWidget().showButton(); var post_data = { comment: text }; if (me._type == 'edit'){ post_data['comment_id'] = me._comment.getId(); post_url = askbot['urls']['editComment']; post_data['suppress_email'] = me.getSuppressEmail(); me.setSuppressEmail(false); } else { post_data['post_type'] = me._comment.getParentType(); post_data['post_id'] = me._comment.getParentId(); post_url = askbot['urls']['postComments']; } $.ajax({ type: "POST", url: post_url, dataType: "json", data: post_data, success: function(json) { //type is 'edit' or 'add' me._comment.setDraftStatus(false); if (me._type == 'add'){ me._comment.dispose(); me._comment.getContainerWidget().reRenderComments(json); } else { me._comment.setContent(json); } me.setWaitingStatus(false); me.detach(); }, error: function(xhr, textStatus, errorThrown) { me._comment.getElement().show(); showMessage(me._comment.getElement(), xhr.responseText, 'after'); me._comment.setDraftStatus(false); me.setWaitingStatus(false); me.detach(); me.enableForm(); } }); return false; }; }; var Comment = function(widget, data){ WrappedElement.call(this); this._container_widget = widget; this._data = data || {}; this._blank = true;//set to false by setContent this._element = null; this._is_convertible = askbot['data']['userIsAdminOrMod']; this.convert_link = null; this._delete_prompt = gettext('delete this comment'); this._editorForm = undefined; if (data && data['is_deletable']){ this._deletable = data['is_deletable']; } else { this._deletable = false; } if (data && data['is_editable']){ this._editable = data['is_deletable']; } else { this._editable = false; } }; inherits(Comment, WrappedElement); Comment.prototype.getData = function() { return this._data; }; Comment.prototype.startEditing = function() { var form = this._editorForm || new EditCommentForm(); this._editorForm = form; // if new comment: if (this.isBlank()) { form.attachTo(this, 'add'); } else { form.attachTo(this, 'edit'); } }; Comment.prototype.decorate = function(element){ this._element = $(element); var parent_type = this._element.parent().parent().attr('id').split('-')[2]; var comment_id = this._element.attr('id').replace('comment-',''); this._data = {id: comment_id}; this._contentBox = this._element.find('.comment-content'); var timestamp = this._element.find('abbr.timeago'); this._data['comment_added_at'] = timestamp.attr('title'); var userLink = this._element.find('a.author'); this._data['user_display_name'] = userLink.html(); // @todo: read other data var commentBody = this._element.find('.comment-body'); if (commentBody.length > 0) { this._comment_body = commentBody; } var delete_img = this._element.find('span.delete-icon'); if (delete_img.length > 0){ this._deletable = true; this._delete_icon = new DeleteIcon(this.deletePrompt); this._delete_icon.setHandler(this.getDeleteHandler()); this._delete_icon.decorate(delete_img); } var edit_link = this._element.find('a.edit'); if (edit_link.length > 0){ this._editable = true; this._edit_link = new EditLink(); this._edit_link.setHandler(this.getEditHandler()); this._edit_link.decorate(edit_link); } var convert_link = this._element.find('form.convert-comment'); if (this._is_convertible){ this._convert_link = new CommentConvertLink(comment_id); this._convert_link.decorate(convert_link); } var deleter = this._element.find('.comment-delete'); if (deleter.length > 0) { this._comment_delete = deleter; }; var vote = new CommentVoteButton(this); vote.decorate(this._element.find('.comment-votes .upvote')); this._blank = false; }; Comment.prototype.setDraftStatus = function(isDraft) { return; //@todo: implement nice feedback about posting in progress //maybe it should be an element that lasts at least a second //to avoid the possible brief flash if (isDraft === true) { this._normalBackground = this._element.css('background'); this._element.css('background', 'rgb(255, 243, 195)'); } else { this._element.css('background', this._normalBackground); } }; Comment.prototype.isBlank = function(){ return this._blank; }; Comment.prototype.getId = function(){ return this._data['id']; }; Comment.prototype.hasContent = function(){ return ('id' in this._data); //shortcut for 'user_url' 'html' 'user_display_name' 'comment_age' }; Comment.prototype.hasText = function(){ return ('text' in this._data); } Comment.prototype.getContainerWidget = function(){ return this._container_widget; }; Comment.prototype.getParentType = function(){ return this._container_widget.getPostType(); }; Comment.prototype.getParentId = function(){ return this._container_widget.getPostId(); }; /** * this function is basically an "updateDom" * for which we don't have the convention */ Comment.prototype.setContent = function(data){ this._data = $.extend(this._data, data); this._element.addClass('comment'); this._element.css('display', 'table');//@warning: hardcoded //display is set to "block" if .show() is called, but we need table. this._element.attr('id', 'comment-' + this._data['id']); // 1) create the votes element if it is not there var votesBox = this._element.find('.comment-votes'); if (votesBox.length === 0) { votesBox = this.makeElement('div'); votesBox.addClass('comment-votes'); this._element.append(votesBox); var vote = new CommentVoteButton(this); if (this._data['upvoted_by_user']){ vote.setVoted(true); } vote.setScore(this._data['score']); var voteElement = vote.getElement(); votesBox.append(vote.getElement()); } // 2) create the comment content container if (this._contentBox === undefined) { var contentBox = this.makeElement('div'); contentBox.addClass('comment-content'); this._contentBox = contentBox; this._element.append(contentBox); } // 2) create the comment deleter if it is not there if (this._comment_delete === undefined) { this._comment_delete = $('<div class="comment-delete"></div>'); if (this._deletable){ this._delete_icon = new DeleteIcon(this._delete_prompt); this._delete_icon.setHandler(this.getDeleteHandler()); this._comment_delete.append(this._delete_icon.getElement()); } this._contentBox.append(this._comment_delete); } // 3) create or replace the comment body if (this._comment_body === undefined) { this._comment_body = $('<div class="comment-body"></div>'); this._contentBox.append(this._comment_body); } if (EditCommentForm.prototype.getEditorType() === 'tinymce') { var theComment = $('<div/>'); theComment.html(this._data['html']); //sanitize, just in case this._comment_body.empty(); this._comment_body.append(theComment); this._data['text'] = this._data['html']; } else { this._comment_body.empty(); this._comment_body.html(this._data['html']); } //this._comment_body.append(' &ndash; '); // 4) create user link if absent if (this._user_link !== undefined) { this._user_link.detach(); this._user_link = undefined; } this._user_link = $('<a></a>').attr('class', 'author'); this._user_link.attr('href', this._data['user_url']); this._user_link.html(this._data['user_display_name']); this._comment_body.append(' '); this._comment_body.append(this._user_link); // 5) create or update the timestamp if (this._comment_added_at !== undefined) { this._comment_added_at.detach(); this._comment_added_at = undefined; } this._comment_body.append(' ('); this._comment_added_at = $('<abbr class="timeago"></abbr>'); this._comment_added_at.html(this._data['comment_added_at']); this._comment_added_at.attr('title', this._data['comment_added_at']); this._comment_added_at.timeago(); this._comment_body.append(this._comment_added_at); this._comment_body.append(')'); if (this._editable) { if (this._edit_link !== undefined) { this._edit_link.dispose(); } this._edit_link = new EditLink(); this._edit_link.setHandler(this.getEditHandler()) this._comment_body.append(this._edit_link.getElement()); } if (this._is_convertible) { if (this._convert_link !== undefined) { this._convert_link.dispose(); } this._convert_link = new CommentConvertLink(this._data['id']); this._comment_body.append(this._convert_link.getElement()); } this._blank = false; }; Comment.prototype.dispose = function(){ if (this._comment_body){ this._comment_body.remove(); } if (this._comment_delete){ this._comment_delete.remove(); } if (this._user_link){ this._user_link.remove(); } if (this._comment_added_at){ this._comment_added_at.remove(); } if (this._delete_icon){ this._delete_icon.dispose(); } if (this._edit_link){ this._edit_link.dispose(); } if (this._convert_link){ this._convert_link.dispose(); } this._data = null; Comment.superClass_.dispose.call(this); }; Comment.prototype.getElement = function(){ Comment.superClass_.getElement.call(this); if (this.isBlank() && this.hasContent()){ this.setContent(); if (askbot['settings']['mathjaxEnabled'] === true){ MathJax.Hub.Queue(['Typeset', MathJax.Hub]); } } return this._element; }; Comment.prototype.loadText = function(on_load_handler){ var me = this; $.ajax({ type: "GET", url: askbot['urls']['getComment'], data: {id: this._data['id']}, success: function(json){ if (json['success']) { me._data['text'] = json['text']; on_load_handler() } else { showMessage(me.getElement(), json['message'], 'after'); } }, error: function(xhr, textStatus, exception) { showMessage(me.getElement(), xhr.responseText, 'after'); } }); }; Comment.prototype.getText = function(){ if (!this.isBlank()){ if ('text' in this._data){ return this._data['text']; } } return ''; } Comment.prototype.getEditHandler = function(){ var me = this; return function(){ if (me.hasText()){ me.startEditing(); } else { me.loadText(function(){ me.startEditing() }); } }; }; Comment.prototype.getDeleteHandler = function(){ var comment = this; var del_icon = this._delete_icon; return function(){ if (confirm(gettext('confirm delete comment'))){ comment.getElement().hide(); $.ajax({ type: 'POST', url: askbot['urls']['deleteComment'], data: { comment_id: comment.getId() }, success: function(json, textStatus, xhr) { comment.dispose(); }, error: function(xhr, textStatus, exception) { comment.getElement().show() showMessage(del_icon.getElement(), xhr.responseText); }, dataType: "json" }); } }; }; var PostCommentsWidget = function(){ WrappedElement.call(this); this._denied = false; }; inherits(PostCommentsWidget, WrappedElement); PostCommentsWidget.prototype.decorate = function(element){ var element = $(element); this._element = element; var widget_id = element.attr('id'); var id_bits = widget_id.split('-'); this._post_id = id_bits[3]; this._post_type = id_bits[2]; this._is_truncated = askbot['data'][widget_id]['truncated']; this._user_can_post = askbot['data'][widget_id]['can_post']; //see if user can comment here var controls = element.find('.controls'); this._activate_button = controls.find('.button'); if (this._user_can_post == false){ setupButtonEventHandlers( this._activate_button, this.getReadOnlyLoadHandler() ); } else { setupButtonEventHandlers( this._activate_button, this.getActivateHandler() ); } this._cbox = element.find('.content'); var comments = new Array(); var me = this; this._cbox.children('.comment').each(function(index, element){ var comment = new Comment(me); comments.push(comment) comment.decorate(element); }); this._comments = comments; }; PostCommentsWidget.prototype.getPostType = function(){ return this._post_type; }; PostCommentsWidget.prototype.getPostId = function(){ return this._post_id; }; PostCommentsWidget.prototype.hideButton = function(){ this._activate_button.hide(); }; PostCommentsWidget.prototype.showButton = function(){ if (this._is_truncated === false){ this._activate_button.html(askbot['messages']['addComment']); } this._activate_button.show(); } PostCommentsWidget.prototype.startNewComment = function(){ var opts = { 'is_deletable': true, 'is_editable': true }; var comment = new Comment(this, opts); this._cbox.append(comment.getElement()); comment.startEditing(); }; PostCommentsWidget.prototype.needToReload = function(){ return this._is_truncated; }; PostCommentsWidget.prototype.userCanPost = function() { var data = askbot['data']; if (data['userIsAuthenticated']) { //true if admin, post owner or high rep user if (data['userIsAdminOrMod']) { return true; } else if (this.getPostId() in data['user_posts']) { return true; } } return false; }; PostCommentsWidget.prototype.getActivateHandler = function(){ var me = this; var button = this._activate_button; return function() { if (me.needToReload()){ me.reloadAllComments(function(json){ me.reRenderComments(json); //2) change button text to "post a comment" button.html(gettext('post a comment')); }); } else { //if user can't post, we tell him something and refuse if (askbot['data']['userIsAuthenticated']) { me.startNewComment(); } else { var message = gettext('please sign in or register to post comments'); showMessage(button, message, 'after'); } } }; }; PostCommentsWidget.prototype.getReadOnlyLoadHandler = function(){ var me = this; return function(){ me.reloadAllComments(function(json){ me.reRenderComments(json); me._activate_button.remove(); }); }; }; PostCommentsWidget.prototype.reloadAllComments = function(callback){ var post_data = {post_id: this._post_id, post_type: this._post_type}; var me = this; $.ajax({ type: "GET", url: askbot['urls']['postComments'], data: post_data, success: function(json){ callback(json); me._is_truncated = false; }, dataType: "json" }); }; PostCommentsWidget.prototype.reRenderComments = function(json){ $.each(this._comments, function(i, item){ item.dispose(); }); this._comments = new Array(); var me = this; $.each(json, function(i, item){ var comment = new Comment(me, item); me._cbox.append(comment.getElement()); me._comments.push(comment); }); }; var socialSharing = function(){ var SERVICE_DATA = { //url - template for the sharing service url, params are for the popup identica: { url: "http://identi.ca/notice/new?status_textarea={TEXT}%20{URL}", params: "width=820, height=526,toolbar=1,status=1,resizable=1,scrollbars=1" }, twitter: { url: "http://twitter.com/share?url={URL}&ref=twitbtn&text={TEXT}", params: "width=820,height=526,toolbar=1,status=1,resizable=1,scrollbars=1" }, facebook: { url: "http://www.facebook.com/sharer.php?u={URL}&ref=fbshare&t={TEXT}", params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1" }, linkedin: { url: "http://www.linkedin.com/shareArticle?mini=true&url={URL}&title={TEXT}", params: "width=630,height=436,toolbar=1,status=1,resizable=1,scrollbars=1" } }; var URL = ""; var TEXT = ""; var share_page = function(service_name){ if (SERVICE_DATA[service_name]){ var url = SERVICE_DATA[service_name]['url']; url = url.replace('{TEXT}', TEXT); url = url.replace('{URL}', URL); var params = SERVICE_DATA[service_name]['params']; if(!window.open(url, "sharing", params)){ window.location.href=url; } return false; //@todo: change to some other url shortening service $.ajax({ url: "http://json-tinyurl.appspot.com/?&callback=?", dataType: "json", data: {'url':URL}, success: function(data) { url = url.replace('{URL}', data.tinyurl); }, error: function(xhr, opts, error) { url = url.replace('{URL}', URL); }, complete: function(data) { url = url.replace('{TEXT}', TEXT); var params = SERVICE_DATA[service_name]['params']; if(!window.open(url, "sharing", params)){ window.location.href=url; } } }); } } return { init: function(){ URL = window.location.href; var urlBits = URL.split('/'); URL = urlBits.slice(0, -2).join('/') + '/'; TEXT = encodeURIComponent($('h1 > a').html()); var hashtag = encodeURIComponent( askbot['settings']['sharingSuffixText'] ); TEXT = TEXT.substr(0, 134 - URL.length - hashtag.length); TEXT = TEXT + '... ' + hashtag; var fb = $('a.facebook-share') var tw = $('a.twitter-share'); var ln = $('a.linkedin-share'); var ica = $('a.identica-share'); copyAltToTitle(fb); copyAltToTitle(tw); copyAltToTitle(ln); copyAltToTitle(ica); setupButtonEventHandlers(fb, function(){ share_page("facebook") }); setupButtonEventHandlers(tw, function(){ share_page("twitter") }); setupButtonEventHandlers(ln, function(){ share_page("linkedin") }); setupButtonEventHandlers(ica, function(){ share_page("identica") }); } } }(); /** * @constructor * @extends {SimpleControl} */ var QASwapper = function(){ SimpleControl.call(this); this._ans_id = null; }; inherits(QASwapper, SimpleControl); QASwapper.prototype.decorate = function(element){ this._element = element; this._ans_id = parseInt(element.attr('id').split('-').pop()); var me = this; this.setHandler(function(){ me.startSwapping(); }); }; QASwapper.prototype.startSwapping = function(){ while (true){ var title = prompt(gettext('Please enter question title (>10 characters)')); if (title.length >= 10){ var data = {new_title: title, answer_id: this._ans_id}; $.ajax({ type: "POST", cache: false, dataType: "json", url: askbot['urls']['swap_question_with_answer'], data: data, success: function(data){ window.location.href = data['question_url']; } }); break; } } }; /** * @constructor * An element that encloses an editor and everything inside it. * By default editor is hidden and user sees a box with a prompt * suggesting to make a post. * When user clicks, editor becomes accessible. */ var FoldedEditor = function() { WrappedElement.call(this); }; inherits(FoldedEditor, WrappedElement); FoldedEditor.prototype.getEditor = function() { return this._editor; }; FoldedEditor.prototype.getEditorInputId = function() { return this._element.find('textarea').attr('id'); }; FoldedEditor.prototype.onAfterOpenHandler = function() { var editor = this.getEditor(); if (editor) { setTimeout(function() {editor.focus()}, 500); } }; FoldedEditor.prototype.getOpenHandler = function() { var editorBox = this._editorBox; var promptBox = this._prompt; var externalTrigger = this._externalTrigger; var me = this; return function() { promptBox.hide(); editorBox.show(); var element = me.getElement(); element.addClass('unfolded'); /* make the editor one shot - once it unfolds it's * not accepting any events */ element.unbind('click'); element.unbind('focus'); /* this function will open the editor * and focus cursor on the editor */ me.onAfterOpenHandler(); /* external trigger is a clickable target * placed outside of the this._element * that will cause the editor to unfold */ if (externalTrigger) { var label = me.makeElement('label'); label.html(externalTrigger.html()); //set what the label is for label.attr('for', me.getEditorInputId()); externalTrigger.replaceWith(label); } }; }; FoldedEditor.prototype.setExternalTrigger = function(element) { this._externalTrigger = element; }; FoldedEditor.prototype.decorate = function(element) { this._element = element; this._prompt = element.find('.prompt'); this._editorBox = element.find('.editor-proper'); var editorType = askbot['settings']['editorType']; if (editorType === 'tinymce') { var editor = new TinyMCE(); editor.decorate(element.find('textarea')); this._editor = editor; } else if (editorType === 'markdown') { var editor = new WMD(); editor.decorate(element); this._editor = editor; } var openHandler = this.getOpenHandler(); element.click(openHandler); element.focus(openHandler); if (this._externalTrigger) { this._externalTrigger.click(openHandler); } }; /** * @constructor * a simple textarea-based editor */ var SimpleEditor = function(attrs) { WrappedElement.call(this); attrs = attrs || {}; this._rows = attrs['rows'] || 10; this._cols = attrs['cols'] || 60; this._maxlength = attrs['maxlength'] || 1000; }; inherits(SimpleEditor, WrappedElement); SimpleEditor.prototype.focus = function(onFocus) { this._textarea.focus(); if (onFocus) { onFocus(); } }; SimpleEditor.prototype.putCursorAtEnd = function() { putCursorAtEnd(this._textarea); }; /** * a noop function */ SimpleEditor.prototype.start = function() {}; SimpleEditor.prototype.setHighlight = function(isHighlighted) { if (isHighlighted === true) { this._textarea.addClass('highlight'); } else { this._textarea.removeClass('highlight'); } }; SimpleEditor.prototype.getText = function() { return $.trim(this._textarea.val()); }; SimpleEditor.prototype.getHtml = function() { return '<div class="transient-comment">' + this.getText() + '</div>'; }; SimpleEditor.prototype.setText = function(text) { this._text = text; if (this._textarea) { this._textarea.val(text); }; }; /** * a textarea inside a div, * the reason for this is that we subclass this * in WMD, and that one requires a more complex structure */ SimpleEditor.prototype.createDom = function() { this._element = this.makeElement('div'); this._element.addClass('wmd-container'); var textarea = this.makeElement('textarea'); this._element.append(textarea); this._textarea = textarea; if (this._text) { textarea.val(this._text); }; textarea.attr({ 'cols': this._cols, 'rows': this._rows, 'maxlength': this._maxlength }); } /** * @constructor * a wrapper for the WMD editor */ var WMD = function(){ SimpleEditor.call(this); this._text = undefined; this._enabled_buttons = 'bold italic link blockquote code ' + 'image attachment ol ul heading hr'; this._is_previewer_enabled = true; }; inherits(WMD, SimpleEditor); //@todo: implement getHtml method that runs text through showdown renderer WMD.prototype.setEnabledButtons = function(buttons){ this._enabled_buttons = buttons; }; WMD.prototype.setPreviewerEnabled = function(state){ this._is_previewer_enabled = state; if (this._previewer){ this._previewer.hide(); } }; WMD.prototype.createDom = function(){ this._element = this.makeElement('div'); var clearfix = this.makeElement('div').addClass('clearfix'); this._element.append(clearfix); var wmd_container = this.makeElement('div'); wmd_container.addClass('wmd-container'); this._element.append(wmd_container); var wmd_buttons = this.makeElement('div') .attr('id', this.makeId('wmd-button-bar')) .addClass('wmd-panel'); wmd_container.append(wmd_buttons); var editor = this.makeElement('textarea') .attr('id', this.makeId('editor')); wmd_container.append(editor); this._textarea = editor; if (this._text){ editor.val(this._text); } var previewer = this.makeElement('div') .attr('id', this.makeId('previewer')) .addClass('wmd-preview'); wmd_container.append(previewer); this._previewer = previewer; if (this._is_previewer_enabled === false) { previewer.hide(); } }; WMD.prototype.decorate = function(element) { this._element = element; this._textarea = element.find('textarea'); this._previewer = element.find('.wmd-preview'); }; WMD.prototype.start = function(){ Attacklab.Util.startEditor(true, this._enabled_buttons, this.getIdSeed()); }; /** * @constructor */ var TinyMCE = function(config) { WrappedElement.call(this); this._config = config || {}; this._id = 'editor';//desired id of the textarea }; inherits(TinyMCE, WrappedElement); /* * not passed onto prototoype on purpose!!! */ TinyMCE.onInitHook = function() { //set initial content var ed = tinyMCE.activeEditor; ed.setContent(askbot['data']['editorContent'] || ''); //if we have spellchecker - enable it by default if (inArray('spellchecker', askbot['settings']['tinyMCEPlugins'])) { setTimeout(function() { ed.controlManager.setActive('spellchecker', true); tinyMCE.execCommand('mceSpellCheck', true); }, 1); } }; /* 3 dummy functions to match WMD api */ TinyMCE.prototype.setEnabledButtons = function() {}; TinyMCE.prototype.start = function() { //copy the options, because we need to modify them var opts = $.extend({}, this._config); var me = this; var extraOpts = { 'mode': 'exact', 'elements': this._id, }; opts = $.extend(opts, extraOpts); tinyMCE.init(opts); $('.mceStatusbar').remove(); }; TinyMCE.prototype.setPreviewerEnabled = function() {}; TinyMCE.prototype.setHighlight = function() {}; TinyMCE.prototype.putCursorAtEnd = function() { var ed = tinyMCE.activeEditor; //add an empty span with a unique id var endId = tinymce.DOM.uniqueId(); ed.dom.add(ed.getBody(), 'span', {'id': endId}, ''); //select that span var newNode = ed.dom.select('span#' + endId); ed.selection.select(newNode[0]); }; TinyMCE.prototype.focus = function(onFocus) { var editorId = this._id; var winH = $(window).height(); var winY = $(window).scrollTop(); var edY = this._element.offset().top; var edH = this._element.height(); //@todo: the fallacy of this method is timeout - should instead use queue //because at the time of calling focus() the editor may not be initialized yet setTimeout( function() { tinyMCE.execCommand('mceFocus', false, editorId); //@todo: make this general to all editors //if editor bottom is below viewport var isBelow = ((edY + edH) > (winY + winH)); var isAbove = (edY < winY); if (isBelow || isAbove) { //then center on screen $(window).scrollTop(edY - edH/2 - winY/2); } if (onFocus) { onFocus(); } }, 100 ); }; TinyMCE.prototype.setId = function(id) { this._id = id; }; TinyMCE.prototype.setText = function(text) { this._text = text; if (this.isLoaded()) { tinymce.get(this._id).setContent(text); } }; TinyMCE.prototype.getText = function() { return tinyMCE.activeEditor.getContent(); }; TinyMCE.prototype.getHtml = TinyMCE.prototype.getText; TinyMCE.prototype.isLoaded = function() { return (tinymce.get(this._id) !== undefined); }; TinyMCE.prototype.createDom = function() { var editorBox = this.makeElement('div'); editorBox.addClass('wmd-container'); this._element = editorBox; var textarea = this.makeElement('textarea'); textarea.attr('id', this._id); textarea.addClass('editor'); this._element.append(textarea); }; TinyMCE.prototype.decorate = function(element) { this._element = element; this._id = element.attr('id'); }; /** * @constructor * @todo: change this to generic object description editor */ var TagWikiEditor = function(){ WrappedElement.call(this); this._state = 'display';//'edit' or 'display' this._content_backup = ''; this._is_editor_loaded = false; this._enabled_editor_buttons = null; this._is_previewer_enabled = false; }; inherits(TagWikiEditor, WrappedElement); TagWikiEditor.prototype.backupContent = function(){ this._content_backup = this._content_box.contents(); }; TagWikiEditor.prototype.setEnabledEditorButtons = function(buttons){ this._enabled_editor_buttons = buttons; }; TagWikiEditor.prototype.setPreviewerEnabled = function(state){ this._is_previewer_enabled = state; if (this.isEditorLoaded()){ this._editor.setPreviewerEnabled(this._is_previewer_enabled); } }; TagWikiEditor.prototype.setContent = function(content){ this._content_box.empty(); this._content_box.append(content); }; TagWikiEditor.prototype.setState = function(state){ if (state === 'edit'){ this._state = state; this._edit_btn.hide(); this._cancel_btn.show(); this._save_btn.show(); this._cancel_sep.show(); } else if (state === 'display'){ this._state = state; this._edit_btn.show(); this._cancel_btn.hide(); this._cancel_sep.hide(); this._save_btn.hide(); } }; TagWikiEditor.prototype.restoreContent = function(){ var content_box = this._content_box; content_box.empty(); $.each(this._content_backup, function(idx, element){ content_box.append(element); }); }; TagWikiEditor.prototype.getTagId = function(){ return this._tag_id; }; TagWikiEditor.prototype.isEditorLoaded = function(){ return this._is_editor_loaded; }; TagWikiEditor.prototype.setEditorLoaded = function(){ return this._is_editor_loaded = true; }; /** * loads initial data for the editor input and activates * the editor */ TagWikiEditor.prototype.startActivatingEditor = function(){ var editor = this._editor; var me = this; var data = { object_id: me.getTagId(), model_name: 'Group' }; $.ajax({ type: 'GET', url: askbot['urls']['load_object_description'], data: data, cache: false, success: function(data){ me.backupContent(); editor.setText(data); me.setContent(editor.getElement()); me.setState('edit'); if (me.isEditorLoaded() === false){ editor.start(); me.setEditorLoaded(); } } }); }; TagWikiEditor.prototype.saveData = function(){ var me = this; var text = this._editor.getText(); var data = { object_id: me.getTagId(), model_name: 'Group',//todo: fixme text: text }; $.ajax({ type: 'POST', dataType: 'json', url: askbot['urls']['save_object_description'], data: data, cache: false, success: function(data){ if (data['success']){ me.setState('display'); me.setContent(data['html']); } else { showMessage(me.getElement(), data['message']); } } }); }; TagWikiEditor.prototype.cancelEdit = function(){ this.restoreContent(); this.setState('display'); }; TagWikiEditor.prototype.decorate = function(element){ //expect <div id='group-wiki-{{id}}'><div class="content"/><a class="edit"/></div> this._element = element; var edit_btn = element.find('.edit-description'); this._edit_btn = edit_btn; //adding two buttons... var save_btn = this.makeElement('a'); save_btn.html(gettext('save')); edit_btn.after(save_btn); save_btn.hide(); this._save_btn = save_btn; var cancel_btn = this.makeElement('a'); cancel_btn.html(gettext('cancel')); save_btn.after(cancel_btn); cancel_btn.hide(); this._cancel_btn = cancel_btn; this._cancel_sep = $('<span> | </span>'); cancel_btn.before(this._cancel_sep); this._cancel_sep.hide(); this._content_box = element.find('.content'); this._tag_id = element.attr('id').split('-').pop(); var me = this; if (askbot['settings']['editorType'] === 'markdown') { var editor = new WMD(); } else { var editor = new TinyMCE({//override defaults theme_advanced_buttons1: 'bold, italic, |, link, |, numlist, bullist', theme_advanced_buttons2: '', theme_advanced_path: false, plugins: '' }); } if (this._enabled_editor_buttons){ editor.setEnabledButtons(this._enabled_editor_buttons); } editor.setPreviewerEnabled(this._is_previewer_enabled); this._editor = editor; setupButtonEventHandlers(edit_btn, function(){ me.startActivatingEditor() }); setupButtonEventHandlers(cancel_btn, function(){me.cancelEdit()}); setupButtonEventHandlers(save_btn, function(){me.saveData()}); }; var ImageChanger = function(){ WrappedElement.call(this); this._image_element = undefined; this._delete_button = undefined; this._save_url = undefined; this._delete_url = undefined; this._messages = undefined; }; inherits(ImageChanger, WrappedElement); ImageChanger.prototype.setImageElement = function(image_element){ this._image_element = image_element; }; ImageChanger.prototype.setMessages = function(messages){ this._messages = messages; }; ImageChanger.prototype.setDeleteButton = function(delete_button){ this._delete_button = delete_button; }; ImageChanger.prototype.setSaveUrl = function(url){ this._save_url = url; }; ImageChanger.prototype.setDeleteUrl = function(url){ this._delete_url = url; }; ImageChanger.prototype.setAjaxData = function(data){ this._ajax_data = data; }; ImageChanger.prototype.showImage = function(image_url){ this._image_element.attr('src', image_url); this._image_element.show(); }; ImageChanger.prototype.deleteImage = function(){ this._image_element.attr('src', ''); this._image_element.css('display', 'none'); var me = this; var delete_url = this._delete_url; var data = this._ajax_data; $.ajax({ type: 'POST', dataType: 'json', url: delete_url, data: data, cache: false, success: function(data){ if (data['success'] === true){ showMessage(me.getElement(), data['message'], 'after'); } } }); }; ImageChanger.prototype.saveImageUrl = function(image_url){ var me = this; var data = this._ajax_data; data['image_url'] = image_url; var save_url = this._save_url; $.ajax({ type: 'POST', dataType: 'json', url: save_url, data: data, cache: false, success: function(data){ if (!data['success']){ showMessage(me.getElement(), data['message'], 'after'); } } }); }; ImageChanger.prototype.startDialog = function(){ //reusing the wmd's file uploader var me = this; var change_image_text = this._messages['change_image']; var change_image_button = this._element; Attacklab.Util.prompt( "<h3>" + gettext('Enter the logo url or upload an image') + '</h3>', 'http://', function(image_url){ if (image_url){ me.saveImageUrl(image_url); me.showImage(image_url); change_image_button.html(change_image_text); me.showDeleteButton(); } }, 'image' ); }; ImageChanger.prototype.showDeleteButton = function(){ this._delete_button.show(); this._delete_button.prev().show(); }; ImageChanger.prototype.hideDeleteButton = function(){ this._delete_button.hide(); this._delete_button.prev().hide(); }; ImageChanger.prototype.startDeleting = function(){ if (confirm(gettext('Do you really want to remove the image?'))){ this.deleteImage(); this._element.html(this._messages['add_image']); this.hideDeleteButton(); this._delete_button.hide(); var sep = this._delete_button.prev(); sep.hide(); }; }; /** * decorates an element that will serve as the image changer button */ ImageChanger.prototype.decorate = function(element){ this._element = element; var me = this; setupButtonEventHandlers( element, function(){ me.startDialog(); } ); setupButtonEventHandlers( this._delete_button, function(){ me.startDeleting(); } ) }; var UserGroupProfileEditor = function(){ TagWikiEditor.call(this); }; inherits(UserGroupProfileEditor, TagWikiEditor); UserGroupProfileEditor.prototype.toggleEmailModeration = function(){ var btn = this._moderate_email_btn; var group_id = this.getTagId(); $.ajax({ type: 'POST', dataType: 'json', cache: false, data: {group_id: group_id}, url: askbot['urls']['toggle_group_email_moderation'], success: function(data){ if (data['success']){ btn.html(data['new_button_text']); } else { showMessage(btn, data['message']); } } }); }; UserGroupProfileEditor.prototype.decorate = function(element){ this.setEnabledEditorButtons('bold italic link ol ul'); this.setPreviewerEnabled(false); UserGroupProfileEditor.superClass_.decorate.call(this, element); var change_logo_btn = element.find('.change-logo'); this._change_logo_btn = change_logo_btn; var moderate_email_toggle = new TwoStateToggle(); moderate_email_toggle.setPostData({ group_id: this.getTagId(), property_name: 'moderate_email' }); var moderate_email_btn = element.find('#moderate-email'); this._moderate_email_btn = moderate_email_btn; moderate_email_toggle.decorate(moderate_email_btn); var moderate_publishing_replies_toggle = new TwoStateToggle(); moderate_publishing_replies_toggle.setPostData({ group_id: this.getTagId(), property_name: 'moderate_answers_to_enquirers' }); var btn = element.find('#moderate-answers-to-enquirers'); moderate_publishing_replies_toggle.decorate(btn); var vip_toggle = new TwoStateToggle(); vip_toggle.setPostData({ group_id: this.getTagId(), property_name: 'is_vip' }); var btn = element.find('#vip-toggle'); vip_toggle.decorate(btn); var opennessSelector = new DropdownSelect(); var selectorElement = element.find('#group-openness-selector'); opennessSelector.setPostData({ group_id: this.getTagId(), property_name: 'openness' }); opennessSelector.decorate(selectorElement); var email_editor = new TextPropertyEditor(); email_editor.decorate(element.find('#preapproved-emails')); var domain_editor = new TextPropertyEditor(); domain_editor.decorate(element.find('#preapproved-email-domains')); var logo_changer = new ImageChanger(); logo_changer.setImageElement(element.find('.group-logo')); logo_changer.setAjaxData({ group_id: this.getTagId() }); logo_changer.setSaveUrl(askbot['urls']['save_group_logo_url']); logo_changer.setDeleteUrl(askbot['urls']['delete_group_logo_url']); logo_changer.setMessages({ change_image: gettext('change logo'), add_image: gettext('add logo') }); var delete_logo_btn = element.find('.delete-logo'); logo_changer.setDeleteButton(delete_logo_btn); logo_changer.decorate(change_logo_btn); }; var GroupJoinButton = function(){ TwoStateToggle.call(this); }; inherits(GroupJoinButton, TwoStateToggle); GroupJoinButton.prototype.getPostData = function(){ return { group_id: this._group_id }; }; GroupJoinButton.prototype.getHandler = function(){ var me = this; return function(){ $.ajax({ type: 'POST', dataType: 'json', cache: false, data: me.getPostData(), url: askbot['urls']['join_or_leave_group'], success: function(data){ if (data['success']){ var level = data['membership_level']; var new_state = 'off-state'; if (level == 'full' || level == 'pending') { new_state = 'on-state'; } me.setState(new_state); } else { showMessage(me.getElement(), data['message']); } } }); }; }; GroupJoinButton.prototype.decorate = function(elem) { GroupJoinButton.superClass_.decorate.call(this, elem); this._group_id = this._element.data('groupId'); }; var TagEditor = function() { WrappedElement.call(this); this._has_hot_backspace = false; this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(TagEditor, WrappedElement); TagEditor.prototype.getSelectedTags = function() { return $.trim(this._hidden_tags_input.val()).split(/\s+/); }; TagEditor.prototype.setSelectedTags = function(tag_names) { this._hidden_tags_input.val($.trim(tag_names.join(' '))); }; TagEditor.prototype.addSelectedTag = function(tag_name) { var tag_names = this._hidden_tags_input.val(); this._hidden_tags_input.val(tag_names + ' ' + tag_name); $('.acResults').hide();//a hack to hide the autocompleter }; TagEditor.prototype.isSelectedTagName = function(tag_name) { var tag_names = this.getSelectedTags(); return $.inArray(tag_name, tag_names) != -1; }; TagEditor.prototype.removeSelectedTag = function(tag_name) { var tag_names = this.getSelectedTags(); var idx = $.inArray(tag_name, tag_names); if (idx !== -1) { tag_names.splice(idx, 1) } this.setSelectedTags(tag_names); }; TagEditor.prototype.getTagDeleteHandler = function(tag){ var me = this; return function(){ me.removeSelectedTag(tag.getName()); me.clearErrorMessage(); tag.dispose(); $('.acResults').hide();//a hack to hide the autocompleter me.fixHeight(); }; }; TagEditor.prototype.cleanTag = function(tag_name, reject_dupe) { tag_name = $.trim(tag_name); tag_name = tag_name.replace(/\s+/, ' '); var force_lowercase = this._settings['force_lowercase_tags']; if (force_lowercase) { tag_name = tag_name.toLowerCase(); } if (reject_dupe && this.isSelectedTagName(tag_name)) { throw interpolate( gettext('tag "%s" was already added, no need to repeat (press "escape" to delete)'), [tag_name] ); } var max_tags = this._settings['max_tags_per_post']; if (this.getSelectedTags().length + 1 > max_tags) {//count current throw interpolate( ngettext( 'a maximum of %s tag is allowed', 'a maximum of %s tags are allowed', max_tags ), [max_tags] ); } //generic cleaning return cleanTag(tag_name, this._settings); }; TagEditor.prototype.addTag = function(tag_name) { var tag = new Tag(); tag.setName(tag_name); tag.setDeletable(true); tag.setLinkable(true); tag.setDeleteHandler(this.getTagDeleteHandler(tag)); this._tags_container.append(tag.getElement()); this.addSelectedTag(tag_name); }; TagEditor.prototype.immediateClearErrorMessage = function() { this._error_alert.html(''); this._error_alert.show(); //this._element.css('margin-top', '18px');//todo: the margin thing is a hack } TagEditor.prototype.clearErrorMessage = function(fade) { if (fade) { var me = this; this._error_alert.fadeOut(function(){ me.immediateClearErrorMessage(); }); } else { this.immediateClearErrorMessage(); } }; TagEditor.prototype.setErrorMessage = function(text) { var old_text = this._error_alert.html(); this._error_alert.html(text); if (old_text == '') { this._error_alert.hide(); this._error_alert.fadeIn(100); } //this._element.css('margin-top', '0');//todo: remove this hack }; TagEditor.prototype.getAddTagHandler = function() { var me = this; return function(tag_name) { if (me.isSelectedTagName(tag_name)) { return; } try { var clean_tag_name = me.cleanTag($.trim(tag_name)); me.addTag(clean_tag_name); me.clearNewTagInput(); me.fixHeight(); } catch (error) { me.setErrorMessage(error); setTimeout(function(){ me.clearErrorMessage(true); }, 1000); } }; }; TagEditor.prototype.getRawNewTagValue = function() { return this._visible_tags_input.val();//without trimming }; TagEditor.prototype.clearNewTagInput = function() { return this._visible_tags_input.val(''); }; TagEditor.prototype.editLastTag = function() { //delete rendered tag var tc = this._tags_container; tc.find('li:last').remove(); //remove from hidden tags input var tags = this.getSelectedTags(); var last_tag = tags.pop(); this.setSelectedTags(tags); //populate the tag editor this._visible_tags_input.val(last_tag); putCursorAtEnd(this._visible_tags_input); }; TagEditor.prototype.setHotBackspace = function(is_hot) { this._has_hot_backspace = is_hot; }; TagEditor.prototype.hasHotBackspace = function() { return this._has_hot_backspace; }; TagEditor.prototype.completeTagInput = function(reject_dupe) { var tag_name = $.trim(this._visible_tags_input.val()); try { tag_name = this.cleanTag(tag_name, reject_dupe); this.addTag(tag_name); this.clearNewTagInput(); } catch (error) { this.setErrorMessage(error); } }; TagEditor.prototype.saveHeight = function() { return; var elem = this._visible_tags_input; this._height = elem.offset().top; }; TagEditor.prototype.fixHeight = function() { return; var new_height = this._visible_tags_input.offset().top; //@todo: replace this by real measurement var element_height = parseInt( this._element.css('height').replace('px', '') ); if (new_height > this._height) { this._element.css('height', element_height + 28);//magic number!!! } else if (new_height < this._height) { this._element.css('height', element_height - 28);//magic number!!! } this.saveHeight(); }; TagEditor.prototype.closeAutoCompleter = function() { this._autocompleter.finish(); }; TagEditor.prototype.getTagInputKeyHandler = function() { var new_tags = this._visible_tags_input; var me = this; return function(e) { if (e.shiftKey) { return; } me.saveHeight(); var key = e.which || e.keyCode; var text = me.getRawNewTagValue(); //space 32, enter 13 if (key == 32 || key == 13) { var tag_name = $.trim(text); if (tag_name.length > 0) { me.completeTagInput(true);//true for reject dupes } me.fixHeight(); return false; } if (text == '') { me.clearErrorMessage(); me.closeAutoCompleter(); } else { try { /* do-nothing validation here * just to report any errors while * the user is typing */ me.cleanTag(text); me.clearErrorMessage(); } catch (error) { me.setErrorMessage(error); } } //8 is backspace if (key == 8 && text.length == 0) { if (me.hasHotBackspace() === true) { me.editLastTag(); me.setHotBackspace(false); } else { me.setHotBackspace(true); } } //27 is escape if (key == 27) { me.clearNewTagInput(); me.clearErrorMessage(); } if (key !== 8) { me.setHotBackspace(false); } me.fixHeight(); return false; }; } TagEditor.prototype.decorate = function(element) { this._element = element; this._hidden_tags_input = element.find('input[name="tags"]');//this one is hidden this._tags_container = element.find('ul.tags'); this._error_alert = $('.tag-editor-error-alert > span'); var me = this; this._tags_container.children().each(function(idx, elem){ var tag = new Tag(); tag.setDeletable(true); tag.setLinkable(false); tag.decorate($(elem)); tag.setDeleteHandler(me.getTagDeleteHandler(tag)); }); var visible_tags_input = element.find('.new-tags-input'); this._visible_tags_input = visible_tags_input; this.saveHeight(); var me = this; var tagsAc = new AutoCompleter({ url: askbot['urls']['get_tag_list'], onItemSelect: function(item){ if (me.isSelectedTagName(item['value']) === false) { me.completeTagInput(); } else { me.clearNewTagInput(); } }, minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10 }); tagsAc.decorate(visible_tags_input); this._autocompleter = tagsAc; visible_tags_input.keyup(this.getTagInputKeyHandler()); element.click(function(e) { visible_tags_input.focus(); return false; }); }; /** * @constructor * Category is a select box item * that has CategoryEditControls */ var Category = function() { SelectBoxItem.call(this); this._state = 'display'; this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(Category, SelectBoxItem); Category.prototype.setCategoryTree = function(tree) { this._tree = tree; }; Category.prototype.getCategoryTree = function() { return this._tree; }; Category.prototype.getName = function() { return this.getContent().getContent(); }; Category.prototype.getPath = function() { return this._tree.getPathToItem(this); }; Category.prototype.setState = function(state) { this._state = state; if ( !this._element ) { return; } this._input_box.val(''); if (state === 'display') { this.showContent(); this.hideEditor(); this.hideEditControls(); } else if (state === 'editable') { this._tree._state = 'editable';//a hack this.showContent(); this.hideEditor(); this.showEditControls(); } else if (state === 'editing') { this._prev_tree_state = this._tree.getState(); this._tree._state = 'editing';//a hack this._input_box.val(this.getName()); this.hideContent(); this.showEditor(); this.hideEditControls(); } }; Category.prototype.hideEditControls = function() { this._delete_button.hide(); this._edit_button.hide(); this._element.unbind('mouseenter mouseleave'); }; Category.prototype.showEditControls = function() { var del = this._delete_button; var edit = this._edit_button; this._element.hover( function(){ del.show(); edit.show(); }, function(){ del.hide(); edit.hide(); } ); }; Category.prototype.showEditControlsNow = function() { this._delete_button.show(); this._edit_button.show(); }; Category.prototype.hideContent = function() { this.getContent().getElement().hide(); }; Category.prototype.showContent = function() { this.getContent().getElement().show(); }; Category.prototype.showEditor = function() { this._input_box.show(); this._input_box.focus(); this._save_button.show(); this._cancel_button.show(); }; Category.prototype.hideEditor = function() { this._input_box.hide(); this._save_button.hide(); this._cancel_button.hide(); }; Category.prototype.getInput = function() { return this._input_box.val(); }; Category.prototype.getDeleteHandler = function() { var me = this; return function() { if (confirm(gettext('Delete category?'))) { var tree = me.getCategoryTree(); $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify({ tag_name: me.getName(), path: me.getPath() }), cache: false, url: askbot['urls']['delete_tag'], success: function(data) { if (data['success']) { //rebuild category tree based on data tree.setData(data['tree_data']); //re-open current branch tree.selectPath(tree.getCurrentPath()); tree.setState('editable'); } else { alert(data['message']); } } }); } return false; }; }; Category.prototype.getSaveHandler = function() { var me = this; var settings = this._settings; //here we need old value and new value return function(){ var to_name = me.getInput(); try { to_name = cleanTag(to_name, settings); var data = { from_name: me.getOriginalName(), to_name: to_name, path: me.getPath() }; $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify(data), cache: false, url: askbot['urls']['rename_tag'], success: function(data) { if (data['success']) { me.setName(to_name); me.setState('editable'); me.showEditControlsNow(); } else { alert(data['message']); } } }); } catch (error) { alert(error); } return false; }; }; Category.prototype.addControls = function() { var input_box = this.makeElement('input'); this._input_box = input_box; this._element.append(input_box); var save_button = this.makeButton( gettext('save'), this.getSaveHandler() ); this._save_button = save_button; this._element.append(save_button); var me = this; var cancel_button = this.makeButton( 'x', function(){ me.setState('editable'); me.showEditControlsNow(); return false; } ); this._cancel_button = cancel_button; this._element.append(cancel_button); var edit_button = this.makeButton( gettext('edit'), function(){ //todo: I would like to make only one at a time editable //var tree = me.getCategoryTree(); //tree.closeAllEditors(); //tree.setState('editable'); //calc path, then select it var tree = me.getCategoryTree(); tree.selectPath(me.getPath()); me.setState('editing'); return false; } ); this._edit_button = edit_button; this._element.append(edit_button); var delete_button = this.makeButton( 'x', this.getDeleteHandler() ); this._delete_button = delete_button; this._element.append(delete_button); }; Category.prototype.getOriginalName = function() { return this._original_name; }; Category.prototype.createDom = function() { Category.superClass_.createDom.call(this); this.addControls(); this.setState('display'); this._original_name = this.getName(); }; Category.prototype.decorate = function(element) { Category.superClass_.decorate.call(this, element); this.addControls(); this.setState('display'); this._original_name = this.getName(); }; var CategoryAdder = function() { WrappedElement.call(this); this._state = 'disabled';//waitedit this._tree = undefined;//category tree this._settings = JSON.parse(askbot['settings']['tag_editor']); }; inherits(CategoryAdder, WrappedElement); CategoryAdder.prototype.setCategoryTree = function(tree) { this._tree = tree; }; CategoryAdder.prototype.setLevel = function(level) { this._level = level; }; CategoryAdder.prototype.setState = function(state) { this._state = state; if (!this._element) { return; } if (state === 'waiting') { this._element.show(); this._input.val(''); this._input.hide(); this._save_button.hide(); this._cancel_button.hide(); this._trigger.show(); } else if (state === 'editable') { this._element.show(); this._input.show(); this._input.val(''); this._input.focus(); this._save_button.show(); this._cancel_button.show(); this._trigger.hide(); } else if (state === 'disabled') { this.setState('waiting');//a little hack this._state = 'disabled'; this._element.hide(); } }; CategoryAdder.prototype.cleanCategoryName = function(name) { name = $.trim(name); if (name === '') { throw gettext('category name cannot be empty'); } //if ( this._tree.hasCategory(name) ) { //throw interpolate( //throw gettext('this category already exists'); // [this._tree.getDisplayPathByName(name)] //) //} return cleanTag(name, this._settings); }; CategoryAdder.prototype.getPath = function() { var path = this._tree.getCurrentPath(); if (path.length > this._level + 1) { return path.slice(0, this._level + 1); } else { return path; } }; CategoryAdder.prototype.getSelectBox = function() { return this._tree.getSelectBox(this._level); }; CategoryAdder.prototype.startAdding = function() { try { var name = this._input.val(); name = this.cleanCategoryName(name); } catch (error) { alert(error); return; } //don't add dupes to the same level var existing_names = this.getSelectBox().getNames(); if ($.inArray(name, existing_names) != -1) { alert(gettext('already exists at the current level!')); return; } var me = this; var tree = this._tree; var adder_path = this.getPath(); $.ajax({ type: 'POST', dataType: 'json', data: JSON.stringify({ path: adder_path, new_category_name: name }), url: askbot['urls']['add_tag_category'], cache: false, success: function(data) { if (data['success']) { //rebuild category tree based on data tree.setData(data['tree_data']); tree.selectPath(data['new_path']); tree.setState('editable'); me.setState('waiting'); } else { alert(data['message']); } } }); }; CategoryAdder.prototype.createDom = function() { this._element = this.makeElement('li'); //add open adder link var trigger = this.makeElement('a'); this._trigger = trigger; trigger.html(gettext('add category')); this._element.append(trigger); //add input box and the add button var input = this.makeElement('input'); this._input = input; input.addClass('add-category'); input.attr('name', 'add_category'); this._element.append(input); //add save category button var save_button = this.makeElement('button'); this._save_button = save_button; save_button.html(gettext('save')); this._element.append(save_button); var cancel_button = this.makeElement('button'); this._cancel_button = cancel_button; cancel_button.html('x'); this._element.append(cancel_button); this.setState(this._state); var me = this; setupButtonEventHandlers( trigger, function(){ me.setState('editable'); } ) setupButtonEventHandlers( save_button, function() { me.startAdding(); return false;//prevent form submit } ); setupButtonEventHandlers( cancel_button, function() { me.setState('waiting'); return false;//prevent submit } ); //create input box, button and the "activate" link }; /** * @constructor * SelectBox subclass to create/edit/delete * categories */ var CategorySelectBox = function() { SelectBox.call(this); this._item_class = Category; this._category_adder = undefined; this._tree = undefined;//cat tree this._level = undefined; }; inherits(CategorySelectBox, SelectBox); CategorySelectBox.prototype.setState = function(state) { this._state = state; if (state === 'select') { if (this._category_adder) { this._category_adder.setState('disabled'); } $.each(this._items, function(idx, item){ item.setState('display'); }); } else if (state === 'editable') { this._category_adder.setState('waiting'); $.each(this._items, function(idx, item){ item.setState('editable'); }); } }; CategorySelectBox.prototype.setCategoryTree = function(tree) { this._tree = tree; }; CategorySelectBox.prototype.getCategoryTree = function() { }; CategorySelectBox.prototype.setLevel = function(level) { this._level = level; }; CategorySelectBox.prototype.getNames = function() { var names = []; $.each(this._items, function(idx, item) { names.push(item.getName()); }); return names; }; CategorySelectBox.prototype.appendCategoryAdder = function() { var adder = new CategoryAdder(); adder.setLevel(this._level); adder.setCategoryTree(this._tree); this._category_adder = adder; this._element.append(adder.getElement()); }; CategorySelectBox.prototype.createDom = function() { CategorySelectBox.superClass_.createDom(); if (askbot['data']['userIsAdmin']) { this.appendCategoryAdder(); } }; CategorySelectBox.prototype.decorate = function(element) { CategorySelectBox.superClass_.decorate.call(this, element); this.setState(this._state); if (askbot['data']['userIsAdmin']) { this.appendCategoryAdder(); } }; /** * @constructor * turns on/off the category editor */ var CategoryEditorToggle = function() { TwoStateToggle.call(this); }; inherits(CategoryEditorToggle, TwoStateToggle); CategoryEditorToggle.prototype.setCategorySelector = function(sel) { this._category_selector = sel; }; CategoryEditorToggle.prototype.getCategorySelector = function() { return this._category_selector; }; CategoryEditorToggle.prototype.decorate = function(element) { CategoryEditorToggle.superClass_.decorate.call(this, element); }; CategoryEditorToggle.prototype.getDefaultHandler = function() { var me = this; return function() { var editor = me.getCategorySelector(); if (me.isOn()) { me.setState('off-state'); editor.setState('select'); } else { me.setState('on-state'); editor.setState('editable'); } }; }; var CategorySelector = function() { Widget.call(this); this._data = null; this._select_handler = function(){};//dummy default this._current_path = [0];//path points to selected item in tree }; inherits(CategorySelector, Widget); /** * propagates state to the individual selectors */ CategorySelector.prototype.setState = function(state) { this._state = state; if (state === 'editing') { return;//do not propagate this state } $.each(this._selectors, function(idx, selector){ selector.setState(state); }); }; CategorySelector.prototype.getPathToItem = function(item) { function findPathToItemInTree(tree, item) { for (var i = 0; i < tree.length; i++) { var node = tree[i]; if (node[2] === item) { return [i]; } var path = findPathToItemInTree(node[1], item); if (path.length > 0) { path.unshift(i); return path; } } return []; }; return findPathToItemInTree(this._data, item); }; CategorySelector.prototype.applyToDataItems = function(func) { function applyToDataItems(tree) { $.each(tree, function(idx, item) { func(item); applyToDataItems(item[1]); }); }; if (this._data) { applyToDataItems(this._data); } }; CategorySelector.prototype.setData = function(data) { this._clearData this._data = data; var tree = this; function attachCategory(item) { var cat = new Category(); cat.setName(item[0]); cat.setCategoryTree(tree); item[2] = cat; }; this.applyToDataItems(attachCategory); }; /** * clears contents of selector boxes starting from * the given level, in range 0..2 */ CategorySelector.prototype.clearCategoryLevels = function(level) { for (var i = level; i < 3; i++) { this._selectors[i].detachAllItems(); } }; CategorySelector.prototype.getLeafItems = function(selection_path) { //traverse the tree down to items pointed to by the path var data = this._data[0]; for (var i = 1; i < selection_path.length; i++) { data = data[1][selection_path[i]]; } return data[1]; } /** * called when a sub-level needs to open */ CategorySelector.prototype.populateCategoryLevel = function(source_path) { var level = source_path.length - 1; if (level >= 3) { return; } //clear all items downstream this.clearCategoryLevels(level); //populate current selector var selector = this._selectors[level]; var items = this.getLeafItems(source_path); $.each(items, function(idx, item) { var category_name = item[0]; var category_subtree = item[1]; var category_object = item[2]; selector.addItemObject(category_object); if (category_subtree.length > 0) { category_object.addCssClass('tree'); } }); this.setState(this._state);//update state selector.clearSelection(); }; CategorySelector.prototype.selectPath = function(path) { for (var i = 1; i <= path.length; i++) { this.populateCategoryLevel(path.slice(0, i)); } for (var i = 1; i < path.length; i++) { var sel_box = this._selectors[i-1]; var category = sel_box.getItemByIndex(path[i]); sel_box.selectItem(category); } }; CategorySelector.prototype.getSelectBox = function(level) { return this._selectors[level]; }; CategorySelector.prototype.getSelectedPath = function(selected_level) { var path = [0];//root, todo: better use names for path??? /* * upper limit capped by current clicked level * we ignore all selection above the current level */ for (var i = 0; i < selected_level + 1; i++) { var selector = this._selectors[i]; var item = selector.getSelectedItem(); if (item) { path.push(selector.getItemIndex(item)); } else { return path; } } return path; }; /** getter and setter are not symmetric */ CategorySelector.prototype.setSelectHandler = function(handler) { this._select_handler = handler; }; CategorySelector.prototype.getSelectHandlerInternal = function() { return this._select_handler; }; CategorySelector.prototype.setCurrentPath = function(path) { return this._current_path = path; }; CategorySelector.prototype.getCurrentPath = function() { return this._current_path; }; CategorySelector.prototype.getEditorToggle = function() { return this._editor_toggle; }; /*CategorySelector.prototype.closeAllEditors = function() { $.each(this._selectors, function(idx, sel) { sel._category_adder.setState('wait'); $.each(sel._items, function(idx2, item) { item.setState('editable'); }); }); };*/ CategorySelector.prototype.getSelectHandler = function(level) { var me = this; return function(item_data) { if (me.getState() === 'editing') { return;//don't navigate when editing } //1) run the assigned select handler var tag_name = item_data['title'] if (me.getState() === 'select') { /* this one will actually select the tag * maybe a bit too implicit */ me.getSelectHandlerInternal()(tag_name); } //2) if appropriate, populate the higher level if (level < 2) { var current_path = me.getSelectedPath(level); me.setCurrentPath(current_path); me.populateCategoryLevel(current_path); } } }; CategorySelector.prototype.decorate = function(element) { this._element = element; this._selectors = []; var selector0 = new CategorySelectBox(); selector0.setLevel(0); selector0.setCategoryTree(this); selector0.decorate(element.find('.cat-col-0')); selector0.setSelectHandler(this.getSelectHandler(0)); this._selectors.push(selector0); var selector1 = new CategorySelectBox(); selector1.setLevel(1); selector1.setCategoryTree(this); selector1.decorate(element.find('.cat-col-1')); selector1.setSelectHandler(this.getSelectHandler(1)); this._selectors.push(selector1) var selector2 = new CategorySelectBox(); selector2.setLevel(2); selector2.setCategoryTree(this); selector2.decorate(element.find('.cat-col-2')); selector2.setSelectHandler(this.getSelectHandler(2)); this._selectors.push(selector2); if (askbot['data']['userIsAdminOrMod']) { var editor_toggle = new CategoryEditorToggle(); editor_toggle.setCategorySelector(this); var toggle_element = $('.category-editor-toggle'); toggle_element.show(); editor_toggle.decorate(toggle_element); this._editor_toggle = editor_toggle; } this.populateCategoryLevel([0]); }; /** * @constructor * loads html for the category selector from * the server via ajax and activates the * CategorySelector on the loaded HTML */ var CategorySelectorLoader = function() { WrappedElement.call(this); this._is_loaded = false; }; inherits(CategorySelectorLoader, WrappedElement); CategorySelectorLoader.prototype.setCategorySelector = function(sel) { this._category_selector = sel; }; CategorySelectorLoader.prototype.setLoaded = function(is_loaded) { this._is_loaded = is_loaded; }; CategorySelectorLoader.prototype.isLoaded = function() { return this._is_loaded; }; CategorySelectorLoader.prototype.setEditor = function(editor) { this._editor = editor; }; CategorySelectorLoader.prototype.closeEditor = function() { this._editor.hide(); this._editor_buttons.hide(); this._display_tags_container.show(); this._question_body.show(); this._question_controls.show(); }; CategorySelectorLoader.prototype.openEditor = function() { this._editor.show(); this._editor_buttons.show(); this._display_tags_container.hide(); this._question_body.hide(); this._question_controls.hide(); var sel = this._category_selector; sel.setState('select'); sel.getEditorToggle().setState('off-state'); }; CategorySelectorLoader.prototype.addEditorButtons = function() { this._editor.after(this._editor_buttons); }; CategorySelectorLoader.prototype.getOnLoadHandler = function() { var me = this; return function(html){ me.setLoaded(true); //append loaded html to dom var editor = $('<div>' + html + '</div>'); me.setEditor(editor); $('#question-tags').after(editor); var selector = askbot['functions']['initCategoryTree'](); me.setCategorySelector(selector); me.addEditorButtons(); me.openEditor(); //add the save button }; }; CategorySelectorLoader.prototype.startLoadingHTML = function(on_load) { var me = this; $.ajax({ type: 'GET', dataType: 'json', data: { template_name: 'widgets/tag_category_selector.html' }, url: askbot['urls']['get_html_template'], cache: true, success: function(data) { if (data['success']) { on_load(data['html']); } else { showMessage(me.getElement(), data['message']); } } }); }; CategorySelectorLoader.prototype.getRetagHandler = function() { var me = this; return function() { if (me.isLoaded() === false) { me.startLoadingHTML(me.getOnLoadHandler()); } else { me.openEditor(); } return false; } }; CategorySelectorLoader.prototype.drawNewTags = function(new_tags) { if (new_tags === ''){ this._display_tags_container.html(''); return; } new_tags = new_tags.split(/\s+/); var tags_html = '' $.each(new_tags, function(index, name){ var tag = new Tag(); tag.setName(name); tags_html += tag.getElement().outerHTML(); }); this._display_tags_container.html(tags_html); }; CategorySelectorLoader.prototype.getSaveHandler = function() { var me = this; return function() { var tagInput = $('input[name="tags"]'); $.ajax({ type: "POST", url: retagUrl,//add to askbot['urls'] dataType: "json", data: { tags: getUniqueWords(tagInput.val()).join(' ') }, success: function(json) { if (json['success'] === true){ var new_tags = getUniqueWords(json['new_tags']); oldTagsHtml = ''; me.closeEditor(); me.drawNewTags(new_tags.join(' ')); } else { me.closeEditor(); showMessage(me.getElement(), json['message']); } }, error: function(xhr, textStatus, errorThrown) { showMessage(tagsDiv, 'sorry, something is not right here'); cancelRetag(); } }); return false; }; }; CategorySelectorLoader.prototype.getCancelHandler = function() { var me = this; return function() { me.closeEditor(); }; }; CategorySelectorLoader.prototype.decorate = function(element) { this._element = element; this._display_tags_container = $('#question-tags'); this._question_body = $('.question .post-body'); this._question_controls = $('#question-controls'); this._editor_buttons = this.makeElement('div'); this._done_button = this.makeElement('button'); this._done_button.html(gettext('save tags')); this._editor_buttons.append(this._done_button); this._cancel_button = this.makeElement('button'); this._cancel_button.html(gettext('cancel')); this._editor_buttons.append(this._cancel_button); this._editor_buttons.find('button').addClass('submit'); this._editor_buttons.addClass('retagger-buttons'); //done button setupButtonEventHandlers( this._done_button, this.getSaveHandler() ); //cancel button setupButtonEventHandlers( this._cancel_button, this.getCancelHandler() ); //retag button setupButtonEventHandlers( element, this.getRetagHandler() ); }; $(document).ready(function() { $('[id^="comments-for-"]').each(function(index, element){ var comments = new PostCommentsWidget(); comments.decorate(element); }); $('[id^="swap-question-with-answer-"]').each(function(idx, element){ var swapper = new QASwapper(); swapper.decorate($(element)); }); $('[id^="post-id-"]').each(function(idx, element){ var deleter = new DeletePostLink(); //confusingly .question-delete matches the answers too need rename var post_id = element.id.split('-').pop(); deleter.setPostId(post_id); deleter.decorate($(element).find('.question-delete')); }); //todo: convert to "control" class var publishBtns = $('.answer-publish, .answer-unpublish'); publishBtns.each(function(idx, btn) { setupButtonEventHandlers($(btn), function() { var answerId = $(btn).data('answerId'); $.ajax({ type: 'POST', dataType: 'json', data: {'answer_id': answerId}, url: askbot['urls']['publishAnswer'], success: function(data) { if (data['success']) { window.location.reload(true); } else { showMessage($(btn), data['message']); } } }); }); }); if (askbot['settings']['tagSource'] == 'category-tree') { var catSelectorLoader = new CategorySelectorLoader(); catSelectorLoader.decorate($('#retag')); } else { questionRetagger.init(); } socialSharing.init(); var proxyUserNameInput = $('#id_post_author_username'); var proxyUserEmailInput = $('#id_post_author_email'); if (proxyUserNameInput.length === 1) { var userSelectHandler = function(data) { proxyUserEmailInput.val(data['data'][0]); }; var fakeUserAc = new AutoCompleter({ url: '/get-users-info/',//askbot['urls']['get_users_info'], promptText: gettext('User name:'), minChars: 1, useCache: true, matchInside: true, maxCacheLength: 100, delay: 10, onItemSelect: userSelectHandler }); fakeUserAc.decorate(proxyUserNameInput); if (proxyUserEmailInput.length === 1) { var tip = new TippedInput(); tip.decorate(proxyUserEmailInput); } } //if groups are enabled - activate share functions var groupsInput = $('#share_group_name'); if (groupsInput.length === 1) { var groupsAc = new AutoCompleter({ url: askbot['urls']['getGroupsList'], promptText: gettext('Group name:'), minChars: 1, useCache: false, matchInside: true, maxCacheLength: 100, delay: 10 }); groupsAc.decorate(groupsInput); } var usersInput = $('#share_user_name'); if (usersInput.length === 1) { var usersAc = new AutoCompleter({ url: '/get-users-info/', promptText: gettext('User name:'), minChars: 1, useCache: false, matchInside: true, maxCacheLength: 100, delay: 10 }); usersAc.decorate(usersInput); } var showSharedUsers = $('.see-related-users'); if (showSharedUsers.length) { var usersPopup = new ThreadUsersDialog(); usersPopup.setHeadingText(gettext('Shared with the following users:')); usersPopup.decorate(showSharedUsers); } var showSharedGroups = $('.see-related-groups'); if (showSharedGroups.length) { var groupsPopup = new ThreadUsersDialog(); groupsPopup.setHeadingText(gettext('Shared with the following groups:')); groupsPopup.decorate(showSharedGroups); } }); /* google prettify.js from google code */ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c< f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&& (j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r= {b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length, t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b=== "string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value", m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m= a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue= j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m, 250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit", PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
simalytics/askbot-devel
static/default/media/js/post.js
JavaScript
gpl-3.0
160,054
// http://eslint.org/docs/user-guide/configuring module.exports = { root: true, parser: 'babel-eslint', parserOptions: { sourceType: 'module' }, env: { browser: true, }, extends: 'airbnb-base', // required to lint *.vue files plugins: [ 'html' ], // check if imports actually resolve 'settings': { 'import/resolver': { 'webpack': { 'config': 'scripts/webpack.conf.js' } } }, // add your custom rules here 'rules': { // don't require .vue extension when importing 'import/extensions': ['error', 'always', { 'js': 'never', 'vue': 'never' }], // allow debugger during development 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 'no-console': ['warn', { allow: ['error', 'warn', 'info'], }], 'no-param-reassign': ['error', { props: false, }], 'consistent-return': 'off', 'no-use-before-define': ['error', 'nofunc'], 'object-shorthand': ['error', 'always'], 'no-mixed-operators': 'off', 'no-bitwise': ['error', { int32Hint: true }], 'no-underscore-dangle': 'off', 'arrow-parens': ['error', 'as-needed'], 'prefer-promise-reject-errors': 'off', 'prefer-destructuring': ['error', { array: false }], indent: ['error', 2, { MemberExpression: 0, flatTernaryExpressions: true, }], }, globals: { browser: true, zip: true, }, }
gera2ld/Stylish-mx
.eslintrc.js
JavaScript
gpl-3.0
1,429
var interval = setInterval(function () { $("button[type=submit]").hide(); $("p.info").hide(); try { var prompting = loadTXT("/data/status.json"); if (prompting.indexOf("started")>0 || prompting.indexOf("active")>0 ) { $("button[type=submit]").show(); $("p.warning").hide(); $("p.info").show(); clearInterval(interval); } } catch (e) { // Silently quit } }, 1000);
opendomo/OpenDomoOS
src/odbase/var/www/scripts/wizFirstConfigurationStep5.sh.js
JavaScript
gpl-3.0
389
/* * Copyright 2012 OSBI Ltd * * 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 account = 'UA-16172251-17'; if (window.location.hostname && window.location.hostname == "dev.analytical-labs.com" ) { account = 'UA-16172251-12'; } else if (window.location.hostname && window.location.hostname == "demo.analytical-labs.com" ) { account = 'UA-16172251-5'; } var _gaq = _gaq || []; _gaq.push(['_setAccount', account]); _gaq.push(['_setAllowLinker', true]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
clevernet/CleverNIM
saiku-ui/js/ga.js
JavaScript
gpl-3.0
1,366
// Copyright � 2010 - May 2014 Rise Vision Incorporated. // Use of this software is governed by the GPLv3 license // (reproduced in the LICENSE file). function rvPlayerDCPage() { var pageHTML = ""; this.get = function (port, ports, dcStatus, onStr, offStr) { var res = pageHTML.replace("[PORT]", port); res = res.replace("[PORTS]", ports); res = res.replace("[Status]", dcStatus); res = res.replace("[onStr]", onStr); res = res.replace("[offStr]", offStr); return res; } this.init = function () { download(chrome.runtime.getURL("display_page.html")); } var download = function (fileUrl) { var xhr = new XMLHttpRequest(); xhr.responseType = "text"; //xhr.onerror = ???; xhr.onload = function (xhrProgressEvent) { pageHTML = xhrProgressEvent.target.responseText; } xhr.open('GET', fileUrl, true); //async=true xhr.send(); }; }
xlsuite/reach.network
player-socialweedia/app/js/player/dc_page.js
JavaScript
gpl-3.0
985
import WordCombination from "../../src/values/WordCombination"; import relevantWords from "../../src/stringProcessing/relevantWords"; import polishFunctionWordsFactory from "../../src/researches/polish/functionWords.js"; const getRelevantWords = relevantWords.getRelevantWords; const polishFunctionWords = polishFunctionWordsFactory().all; describe( "gets Polish word combinations", function() { it( "returns word combinations", function() { const input = "W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast" + " dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy " + "natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce piersiowej, " + "to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w klatce " + "piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś odczuwa ból w" + " klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że gdy ktoś " + "odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas wie, że " + "gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę. W zasadzie każdy z nas" + " wie, że gdy ktoś odczuwa ból w klatce piersiowej, to należy natychmiast dzwonić po karetkę."; const expected = [ new WordCombination( [ "odczuwa", "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "natychmiast", "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ), new WordCombination( [ "ból", "w", "klatce", "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "odczuwa", "ból", "w", "klatce" ], 8, polishFunctionWords ), new WordCombination( [ "dzwonić", "po", "karetkę" ], 8, polishFunctionWords ), new WordCombination( [ "ból", "w", "klatce" ], 8, polishFunctionWords ), new WordCombination( [ "odczuwa", "ból" ], 8, polishFunctionWords ), new WordCombination( [ "natychmiast", "dzwonić" ], 8, polishFunctionWords ), new WordCombination( [ "klatce", "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "wie" ], 8, polishFunctionWords ), new WordCombination( [ "karetkę" ], 8, polishFunctionWords ), new WordCombination( [ "dzwonić" ], 8, polishFunctionWords ), new WordCombination( [ "natychmiast" ], 8, polishFunctionWords ), new WordCombination( [ "piersiowej" ], 8, polishFunctionWords ), new WordCombination( [ "klatce" ], 8, polishFunctionWords ), new WordCombination( [ "ból" ], 8, polishFunctionWords ), new WordCombination( [ "odczuwa" ], 8, polishFunctionWords ), new WordCombination( [ "zasadzie" ], 8, polishFunctionWords ), ]; // Make sure our words aren't filtered by density. spyOn( WordCombination.prototype, "getDensity" ).and.returnValue( 0.01 ); const words = getRelevantWords( input, "pl_PL" ); words.forEach( function( word ) { delete( word._relevantWords ); } ); expect( words ).toEqual( expected ); } ); } );
Yoast/js-text-analysis
spec/stringProcessing/relevantWordsPolishSpec.js
JavaScript
gpl-3.0
3,204
 function gestionSelectElement(elementId,msgConfirm) {field=document.getElementById(elementId);if(confirm(msgConfirm)) {selectedIndexASupprimer=field.options.selectedIndex;indice=new Array();texte=new Array();for(i=0;i<field.length;i++) {indice[i]=field.options[i].value;texte[i]=field.options[i].text;} field.innerHTML='';j=0;for(i=0;i<indice.length;i++) {if(i!=selectedIndexASupprimer) {field.options[j]=new Option(texte[i],indice[i]);j++;}}} for(i=0;i<field.length;i++) {field.options[i].selected=true;}}
rotagraziosi/archi-wiki-inpeople
includes/common.js
JavaScript
gpl-3.0
510
YUI.add("lang/calendar-base_es",function(e){e.Intl.add("calendar-base","es",{very_short_weekdays:["Do","Lu","Ma","Mi","Ju","Vi","Sa"],first_weekday:1,weekends:[0,6]})},"patched-v3.18.1");
Behzadkhosravifar/Alloy-DiagramBuilder-MVC
src/AlloyDiagram/Scripts/AlloyUi/calendar-base/lang/calendar-base_es.js
JavaScript
gpl-3.0
188
var http = require('https') , qs = require('querystring') , Cleverbot = function (options) { this.configure(options); }; Cleverbot.prepare = function(cb){ // noop for backwards compatibility cb(); }; Cleverbot.prototype = { configure: function (options){ if(options && options.constructor !== Object){ throw new TypeError("Cleverbot must be configured with an Object"); } this.options = options || {}; }, path: function(message){ var path = '/getreply' , query = { input: JSON.stringify(message), key: this.options.botapi || "CHANGEME" }; if(this.state) { query.cs = this.state; } return [path, qs.stringify(query)].join("?"); }, write: function (message, callback, errorCallback) { var clever = this; var body = this.params; var options = { host: 'www.cleverbot.com', port: 443, path: this.path(message), method: 'GET', headers: { 'Content-Type': 'text/javascript' } }; var cb = callback || function() { }; var err = errorCallback || function() {}; var req = http.request(options, function (res) { var chunks = []; res.on("data", function(data) { chunks.push(data); }); res.on("end", function(i) { var body = Buffer.concat(chunks).toString(); var responseBody; try{ responseBody = JSON.parse(body); } catch(e) { try{ eval("responseBody = " + body); } catch(e) { err(e, message, body); return; } } responseBody.message = responseBody.output; //for backwards compatibility this.state = responseBody.cs; cb(responseBody); }.bind(this)); }.bind(this)); req.end(); } }; module.exports = Cleverbot;
SrNativee/BotDeUmBot
node_modules/cleverbot-node/lib/cleverbot.js
JavaScript
gpl-3.0
2,085
/* * This file is generated and updated by Sencha Cmd. You can edit this file as * needed for your application, but these edits will have to be merged by * Sencha Cmd when upgrading. */ Ext.application({ name: 'LPB', extend: 'LPB.Application', requires: [ 'LPB.util.sha256', 'Ext.plugin.Viewport', 'Ext.list.Tree', 'LPB.view.login.Login', 'LPB.view.admin.Main', 'LPB.view.user.User', 'Ext.container.Container', 'Ext.layout.container.Anchor', 'Ext.sunfield.imageUploader.ImageUploader', 'Ext.sunfield.locationSelect.LocationSelect', 'Ext.sunfield.imageField.ImageField', 'Ext.sunfield.imageField.DatesField', 'Ext.sunfield.DateSlider', 'Ext.sunfield.sunEditor.SunEditor', 'Ext.sunfield.mruImages.MruImages', 'Ext.sunfield.groupEditor.GroupEditor', 'Ext.ux.form.ItemSelector' ] // The name of the initial view to create. With the classic toolkit this class // will gain a "viewport" plugin if it does not extend Ext.Viewport. With the // modern toolkit, the main view will be added to the Viewport. // //mainView: 'LPB.view.main.Main' //------------------------------------------------------------------------- // Most customizations should be made to LPB.Application. If you need to // customize this file, doing so below this section reduces the likelihood // of merge conflicts when upgrading to new versions of Sencha Cmd. //------------------------------------------------------------------------- });
Lytjepole/Lytjepole-Beheer
LPB/app.js
JavaScript
gpl-3.0
1,604
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Q = require('q'); /* jshint ignore:line */ var _ = require('lodash'); /* jshint ignore:line */ var Page = require('../../../../../base/Page'); /* jshint ignore:line */ var deserialize = require( '../../../../../base/deserialize'); /* jshint ignore:line */ var values = require('../../../../../base/values'); /* jshint ignore:line */ var MemberList; var MemberPage; var MemberInstance; var MemberContext; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @description Initialize the MemberList * * @param {Twilio.Api.V2010} version - Version of the resource * @param {string} accountSid - The account_sid * @param {string} queueSid - A string that uniquely identifies this queue */ /* jshint ignore:end */ MemberList = function MemberList(version, accountSid, queueSid) { /* jshint ignore:start */ /** * @function members * @memberof Twilio.Api.V2010.AccountContext.QueueContext * @instance * * @param {string} sid - sid of instance * * @returns {Twilio.Api.V2010.AccountContext.QueueContext.MemberContext} */ /* jshint ignore:end */ function MemberListInstance(sid) { return MemberListInstance.get(sid); } MemberListInstance._version = version; // Path Solution MemberListInstance._solution = { accountSid: accountSid, queueSid: queueSid }; MemberListInstance._uri = _.template( '/Accounts/<%= accountSid %>/Queues/<%= queueSid %>/Members.json' // jshint ignore:line )(MemberListInstance._solution); /* jshint ignore:start */ /** * Streams MemberInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory efficient. * * If a function is passed as the first argument, it will be used as the callback function. * * @function each * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {object|function} opts - ... * @param {number} [opts.limit] - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize=50] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @param {Function} [opts.callback] - * Function to process each record. If this and a positional * callback are passed, this one will be used * @param {Function} [opts.done] - * Function to be called upon completion of streaming * @param {Function} [callback] - Function to process each record */ /* jshint ignore:end */ MemberListInstance.each = function each(opts, callback) { opts = opts || {}; if (_.isFunction(opts)) { opts = { callback: opts }; } else if (_.isFunction(callback) && !_.isFunction(opts.callback)) { opts.callback = callback; } if (_.isUndefined(opts.callback)) { throw new Error('Callback function must be provided'); } var done = false; var currentPage = 1; var currentResource = 0; var limits = this._version.readLimits({ limit: opts.limit, pageSize: opts.pageSize }); function onComplete(error) { done = true; if (_.isFunction(opts.done)) { opts.done(error); } } function fetchNextPage(fn) { var promise = fn(); if (_.isUndefined(promise)) { onComplete(); return; } promise.then(function(page) { _.each(page.instances, function(instance) { if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) { done = true; return false; } currentResource++; opts.callback(instance, onComplete); }); if ((limits.pageLimit && limits.pageLimit <= currentPage)) { onComplete(); } else if (!done) { currentPage++; fetchNextPage(_.bind(page.nextPage, page)); } }); promise.catch(onComplete); } fetchNextPage(_.bind(this.page, this, _.merge(opts, limits))); }; /* jshint ignore:start */ /** * @description Lists MemberInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback function. * * @function list * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {object|function} opts - ... * @param {number} [opts.limit] - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ MemberListInstance.list = function list(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var allResources = []; opts.callback = function(resource, done) { allResources.push(resource); if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { done(); } }; opts.done = function(error) { if (_.isUndefined(error)) { deferred.resolve(allResources); } else { deferred.reject(error); } }; if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } this.each(opts); return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single page of MemberInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @function page * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {object|function} opts - ... * @param {string} [opts.pageToken] - PageToken provided by the API * @param {number} [opts.pageNumber] - * Page Number, this value is simply for client state * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ MemberListInstance.page = function page(opts, callback) { opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'PageToken': opts.pageToken, 'Page': opts.pageNumber, 'PageSize': opts.pageSize }); var promise = this._version.page({ uri: this._uri, method: 'GET', params: data }); promise = promise.then(function(payload) { deferred.resolve(new MemberPage( this._version, payload, this._solution )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single target page of MemberInstance records from the API. * Request is executed immediately * * If a function is passed as the first argument, it will be used as the callback function. * * @function getPage * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {string} [targetUrl] - API-generated URL for the requested results page * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ MemberListInstance.getPage = function getPage(targetUrl, callback) { var deferred = Q.defer(); var promise = this._version._domain.twilio.request({ method: 'GET', uri: targetUrl }); promise = promise.then(function(payload) { deferred.resolve(new MemberPage( this._version, payload, this._solution )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Constructs a member * * @function get * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberList * @instance * * @param {string} callSid - The call_sid * * @returns {Twilio.Api.V2010.AccountContext.QueueContext.MemberContext} */ /* jshint ignore:end */ MemberListInstance.get = function get(callSid) { return new MemberContext( this._version, this._solution.accountSid, this._solution.queueSid, callSid ); }; return MemberListInstance; }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberPage * @augments Page * @description Initialize the MemberPage * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} response - Response from the API * @param {object} solution - Path solution * * @returns MemberPage */ /* jshint ignore:end */ MemberPage = function MemberPage(version, response, solution) { // Path Solution this._solution = solution; Page.prototype.constructor.call(this, version, response, this._solution); }; _.extend(MemberPage.prototype, Page.prototype); MemberPage.prototype.constructor = MemberPage; /* jshint ignore:start */ /** * Build an instance of MemberInstance * * @function getInstance * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberPage * @instance * * @param {object} payload - Payload response from the API * * @returns MemberInstance */ /* jshint ignore:end */ MemberPage.prototype.getInstance = function getInstance(payload) { return new MemberInstance( this._version, payload, this._solution.accountSid, this._solution.queueSid ); }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance * @description Initialize the MemberContext * * @property {string} callSid - Unique string that identifies this resource * @property {Date} dateEnqueued - The date the member was enqueued * @property {number} position - This member's current position in the queue. * @property {string} uri - The uri * @property {number} waitTime - * The number of seconds the member has been in the queue. * * @param {Twilio.Api.V2010} version - Version of the resource * @param {object} payload - The instance payload * @param {sid} accountSid - The account_sid * @param {sid} queueSid - The Queue in which to find the members * @param {sid} callSid - The call_sid */ /* jshint ignore:end */ MemberInstance = function MemberInstance(version, payload, accountSid, queueSid, callSid) { this._version = version; // Marshaled Properties this.callSid = payload.call_sid; // jshint ignore:line this.dateEnqueued = deserialize.rfc2822DateTime(payload.date_enqueued); // jshint ignore:line this.position = deserialize.integer(payload.position); // jshint ignore:line this.uri = payload.uri; // jshint ignore:line this.waitTime = deserialize.integer(payload.wait_time); // jshint ignore:line // Context this._context = undefined; this._solution = { accountSid: accountSid, queueSid: queueSid, callSid: callSid || this.callSid, }; }; Object.defineProperty(MemberInstance.prototype, '_proxy', { get: function() { if (!this._context) { this._context = new MemberContext( this._version, this._solution.accountSid, this._solution.queueSid, this._solution.callSid ); } return this._context; } }); /* jshint ignore:start */ /** * fetch a MemberInstance * * @function fetch * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance * @instance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberInstance.prototype.fetch = function fetch(callback) { return this._proxy.fetch(callback); }; /* jshint ignore:start */ /** * update a MemberInstance * * @function update * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberInstance * @instance * * @param {object} opts - ... * @param {string} opts.url - The url * @param {string} opts.method - The method * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberInstance.prototype.update = function update(opts, callback) { return this._proxy.update(opts, callback); }; /* jshint ignore:start */ /** * @constructor Twilio.Api.V2010.AccountContext.QueueContext.MemberContext * @description Initialize the MemberContext * * @param {Twilio.Api.V2010} version - Version of the resource * @param {sid} accountSid - The account_sid * @param {sid} queueSid - The Queue in which to find the members * @param {sid} callSid - The call_sid */ /* jshint ignore:end */ MemberContext = function MemberContext(version, accountSid, queueSid, callSid) { this._version = version; // Path Solution this._solution = { accountSid: accountSid, queueSid: queueSid, callSid: callSid, }; this._uri = _.template( '/Accounts/<%= accountSid %>/Queues/<%= queueSid %>/Members/<%= callSid %>.json' // jshint ignore:line )(this._solution); }; /* jshint ignore:start */ /** * fetch a MemberInstance * * @function fetch * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberContext * @instance * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberContext.prototype.fetch = function fetch(callback) { var deferred = Q.defer(); var promise = this._version.fetch({ uri: this._uri, method: 'GET' }); promise = promise.then(function(payload) { deferred.resolve(new MemberInstance( this._version, payload, this._solution.accountSid, this._solution.queueSid, this._solution.callSid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * update a MemberInstance * * @function update * @memberof Twilio.Api.V2010.AccountContext.QueueContext.MemberContext * @instance * * @param {object} opts - ... * @param {string} opts.url - The url * @param {string} opts.method - The method * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed MemberInstance */ /* jshint ignore:end */ MemberContext.prototype.update = function update(opts, callback) { if (_.isUndefined(opts)) { throw new Error('Required parameter "opts" missing.'); } if (_.isUndefined(opts.url)) { throw new Error('Required parameter "opts.url" missing.'); } if (_.isUndefined(opts.method)) { throw new Error('Required parameter "opts.method" missing.'); } var deferred = Q.defer(); var data = values.of({ 'Url': _.get(opts, 'url'), 'Method': _.get(opts, 'method') }); var promise = this._version.update({ uri: this._uri, method: 'POST', data: data }); promise = promise.then(function(payload) { deferred.resolve(new MemberInstance( this._version, payload, this._solution.accountSid, this._solution.queueSid, this._solution.callSid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; module.exports = { MemberList: MemberList, MemberPage: MemberPage, MemberInstance: MemberInstance, MemberContext: MemberContext };
together-web-pj/together-web-pj
node_modules/twilio/lib/rest/api/v2010/account/queue/member.js
JavaScript
gpl-3.0
17,007
/* Product Name: dhtmlxSuite Version: 5.0 Edition: Standard License: content of this file is covered by GPL. Usage outside GPL terms is prohibited. To obtain Commercial or Enterprise license contact [email protected] Copyright UAB Dinamenta http://www.dhtmlx.com */ (function(){ var dhx = {}; //check some rule, show message as error if rule is not correct dhx.assert = function(test, message){ if (!test){ dhx.assert_error(message); } }; dhx.assert_error = function(message){ dhx.log("error",message); if (dhx.message && typeof message == "string") dhx.message({ type:"debug", text:message, expire:-1 }); if (dhx.debug !== false) eval("debugger;"); }; //entry point for analitic scripts dhx.assert_core_ready = function(){ if (window.dhx_on_core_ready) dhx_on_core_ready(); }; /* Common helpers */ dhx.codebase="./"; dhx.name = "Core"; //coding helpers dhx.clone = function(source){ var f = dhx.clone._function; f.prototype = source; return new f(); }; dhx.clone._function = function(){}; //copies methods and properties from source to the target dhx.extend = function(base, source, force){ dhx.assert(base,"Invalid mixing target"); dhx.assert(source,"Invalid mixing source"); if (base._dhx_proto_wait){ dhx.PowerArray.insertAt.call(base._dhx_proto_wait, source,1); return base; } //copy methods, overwrite existing ones in case of conflict for (var method in source) if (!base[method] || force) base[method] = source[method]; //in case of defaults - preffer top one if (source.defaults) dhx.extend(base.defaults, source.defaults); //if source object has init code - call init against target if (source.$init) source.$init.call(base); return base; }; //copies methods and properties from source to the target from all levels dhx.copy = function(source){ dhx.assert(source,"Invalid mixing target"); if(arguments.length>1){ var target = arguments[0]; source = arguments[1]; } else var target = (dhx.isArray(source)?[]:{}); for (var method in source){ if(source[method] && typeof source[method] == "object" && !dhx.isDate(source[method])){ target[method] = (dhx.isArray(source[method])?[]:{}); dhx.copy(target[method],source[method]); }else{ target[method] = source[method]; } } return target; }; dhx.single = function(source){ var instance = null; var t = function(config){ if (!instance) instance = new source({}); if (instance._reinit) instance._reinit.apply(instance, arguments); return instance; }; return t; }; dhx.protoUI = function(){ if (dhx.debug_proto) dhx.log("UI registered: "+arguments[0].name); var origins = arguments; var selfname = origins[0].name; var t = function(data){ if (!t) return dhx.ui[selfname].prototype; var origins = t._dhx_proto_wait; if (origins){ var params = [origins[0]]; for (var i=1; i < origins.length; i++){ params[i] = origins[i]; if (params[i]._dhx_proto_wait) params[i] = params[i].call(dhx, params[i].name); if (params[i].prototype && params[i].prototype.name) dhx.ui[params[i].prototype.name] = params[i]; } dhx.ui[selfname] = dhx.proto.apply(dhx, params); if (t._dhx_type_wait) for (var i=0; i < t._dhx_type_wait.length; i++) dhx.Type(dhx.ui[selfname], t._dhx_type_wait[i]); t = origins = null; } if (this != dhx) return new dhx.ui[selfname](data); else return dhx.ui[selfname]; }; t._dhx_proto_wait = Array.prototype.slice.call(arguments, 0); return dhx.ui[selfname]=t; }; dhx.proto = function(){ if (dhx.debug_proto) dhx.log("Proto chain:"+arguments[0].name+"["+arguments.length+"]"); var origins = arguments; var compilation = origins[0]; var has_constructor = !!compilation.$init; var construct = []; dhx.assert(compilation,"Invalid mixing target"); for (var i=origins.length-1; i>0; i--) { dhx.assert(origins[i],"Invalid mixing source"); if (typeof origins[i]== "function") origins[i]=origins[i].prototype; if (origins[i].$init) construct.push(origins[i].$init); if (origins[i].defaults){ var defaults = origins[i].defaults; if (!compilation.defaults) compilation.defaults = {}; for (var def in defaults) if (dhx.isUndefined(compilation.defaults[def])) compilation.defaults[def] = defaults[def]; } if (origins[i].type && compilation.type){ for (var def in origins[i].type) if (!compilation.type[def]) compilation.type[def] = origins[i].type[def]; } for (var key in origins[i]){ if (!compilation[key]) compilation[key] = origins[i][key]; } } if (has_constructor) construct.push(compilation.$init); compilation.$init = function(){ for (var i=0; i<construct.length; i++) construct[i].apply(this, arguments); }; var result = function(config){ this.$ready=[]; dhx.assert(this.$init,"object without init method"); this.$init(config); if (this._parseSettings) this._parseSettings(config, this.defaults); for (var i=0; i < this.$ready.length; i++) this.$ready[i].call(this); }; result.prototype = compilation; compilation = origins = null; return result; }; //creates function with specified "this" pointer dhx.bind=function(functor, object){ return function(){ return functor.apply(object,arguments); }; }; //loads module from external js file dhx.require=function(module, callback, master){ if (typeof module != "string"){ var count = module.length||0; var callback_origin = callback; if (!count){ for (var file in module) count++; callback = function(){ count--; if (count === 0) callback_origin.apply(this, arguments); }; for (var file in module) dhx.require(file, callback, master); } else { callback = function(){ if (count){ count--; dhx.require(module[module.length - count - 1], callback, master); } else return callback_origin.apply(this, arguments); }; callback(); } return; } if (dhx._modules[module] !== true){ if (module.substr(-4) == ".css") { var link = dhx.html.create("LINK",{ type:"text/css", rel:"stylesheet", href:dhx.codebase+module}); document.head.appendChild(link); if (callback) callback.call(master||window); return; } var step = arguments[4]; //load and exec the required module if (!callback){ //sync mode dhx.exec( dhx.ajax().sync().get(dhx.codebase+module).responseText ); dhx._modules[module]=true; } else { if (!dhx._modules[module]){ //first call dhx._modules[module] = [[callback, master]]; dhx.ajax(dhx.codebase+module, function(text){ dhx.exec(text); //evaluate code var calls = dhx._modules[module]; //callbacks dhx._modules[module] = true; for (var i=0; i<calls.length; i++) calls[i][0].call(calls[i][1]||window, !i); //first callback get true as parameter }); } else //module already loading dhx._modules[module].push([callback, master]); } } }; dhx._modules = {}; //hash of already loaded modules //evaluate javascript code in the global scoope dhx.exec=function(code){ if (window.execScript) //special handling for IE window.execScript(code); else window.eval(code); }; dhx.wrap = function(code, wrap){ if (!code) return wrap; return function(){ var result = code.apply(this, arguments); wrap.apply(this,arguments); return result; }; }; //check === undefined dhx.isUndefined=function(a){ return typeof a == "undefined"; }; //delay call to after-render time dhx.delay=function(method, obj, params, delay){ return window.setTimeout(function(){ var ret = method.apply(obj,(params||[])); method = obj = params = null; return ret; },delay||1); }; //common helpers //generates unique ID (unique per window, nog GUID) dhx.uid = function(){ if (!this._seed) this._seed=(new Date).valueOf(); //init seed with timestemp this._seed++; return this._seed; }; //resolve ID as html object dhx.toNode = function(node){ if (typeof node == "string") return document.getElementById(node); return node; }; //adds extra methods for the array dhx.toArray = function(array){ return dhx.extend((array||[]),dhx.PowerArray, true); }; //resolve function name dhx.toFunctor=function(str){ return (typeof(str)=="string") ? eval(str) : str; }; /*checks where an object is instance of Array*/ dhx.isArray = function(obj) { return Array.isArray?Array.isArray(obj):(Object.prototype.toString.call(obj) === '[object Array]'); }; dhx.isDate = function(obj){ return obj instanceof Date; }; //dom helpers //hash of attached events dhx._events = {}; //attach event to the DOM element dhx.event=function(node,event,handler,master){ node = dhx.toNode(node); var id = dhx.uid(); if (master) handler=dhx.bind(handler,master); dhx._events[id]=[node,event,handler]; //store event info, for detaching //use IE's of FF's way of event's attaching if (node.addEventListener) node.addEventListener(event, handler, false); else if (node.attachEvent) node.attachEvent("on"+event, handler); return id; //return id of newly created event, can be used in eventRemove }; //remove previously attached event dhx.eventRemove=function(id){ if (!id) return; dhx.assert(this._events[id],"Removing non-existing event"); var ev = dhx._events[id]; //browser specific event removing if (ev[0].removeEventListener) ev[0].removeEventListener(ev[1],ev[2],false); else if (ev[0].detachEvent) ev[0].detachEvent("on"+ev[1],ev[2]); delete this._events[id]; //delete all traces }; //debugger helpers //anything starting from error or log will be removed during code compression //add message in the log dhx.log = function(type,message,details){ if (arguments.length == 1){ message = type; type = "log"; } /*jsl:ignore*/ if (window.console && console.log){ type=type.toLowerCase(); if (window.console[type]) window.console[type](message||"unknown error"); else window.console.log(type +": "+message); if (details) window.console.log(details); } /*jsl:end*/ }; //register rendering time from call point dhx.log_full_time = function(name){ dhx._start_time_log = new Date(); dhx.log("Timing start ["+name+"]"); window.setTimeout(function(){ var time = new Date(); dhx.log("Timing end ["+name+"]:"+(time.valueOf()-dhx._start_time_log.valueOf())/1000+"s"); },1); }; //register execution time from call point dhx.log_time = function(name){ var fname = "_start_time_log"+name; if (!dhx[fname]){ dhx[fname] = new Date(); dhx.log("Info","Timing start ["+name+"]"); } else { var time = new Date(); dhx.log("Info","Timing end ["+name+"]:"+(time.valueOf()-dhx[fname].valueOf())/1000+"s"); dhx[fname] = null; } }; dhx.debug_code = function(code){ code.call(dhx); }; //event system dhx.EventSystem={ $init:function(){ if (!this._evs_events){ this._evs_events = {}; //hash of event handlers, name => handler this._evs_handlers = {}; //hash of event handlers, ID => handler this._evs_map = {}; } }, //temporary block event triggering blockEvent : function(){ this._evs_events._block = true; }, //re-enable event triggering unblockEvent : function(){ this._evs_events._block = false; }, mapEvent:function(map){ dhx.extend(this._evs_map, map, true); }, on_setter:function(config){ if(config){ for(var i in config){ if(typeof config[i] == 'function') this.attachEvent(i, config[i]); } } }, //trigger event callEvent:function(type,params){ if (this._evs_events._block) return true; type = type.toLowerCase(); var event_stack =this._evs_events[type.toLowerCase()]; //all events for provided name var return_value = true; if (dhx.debug) //can slowdown a lot dhx.log("info","["+this.name+"] event:"+type,params); if (event_stack) for(var i=0; i<event_stack.length; i++){ /* Call events one by one If any event return false - result of whole event will be false Handlers which are not returning anything - counted as positive */ if (event_stack[i].apply(this,(params||[]))===false) return_value=false; } if (this._evs_map[type] && !this._evs_map[type].callEvent(type,params)) return_value = false; return return_value; }, //assign handler for some named event attachEvent:function(type,functor,id){ dhx.assert(functor, "Invalid event handler for "+type); type=type.toLowerCase(); id=id||dhx.uid(); //ID can be used for detachEvent functor = dhx.toFunctor(functor); //functor can be a name of method var event_stack=this._evs_events[type]||dhx.toArray(); //save new event handler event_stack.push(functor); this._evs_events[type]=event_stack; this._evs_handlers[id]={ f:functor,t:type }; return id; }, //remove event handler detachEvent:function(id){ if(!this._evs_handlers[id]){ return; } var type=this._evs_handlers[id].t; var functor=this._evs_handlers[id].f; //remove from all collections var event_stack=this._evs_events[type]; event_stack.remove(functor); delete this._evs_handlers[id]; }, hasEvent:function(type){ type=type.toLowerCase(); return this._evs_events[type]?true:false; } }; dhx.extend(dhx, dhx.EventSystem); //array helper //can be used by dhx.toArray() dhx.PowerArray={ //remove element at specified position removeAt:function(pos,len){ if (pos>=0) this.splice(pos,(len||1)); }, //find element in collection and remove it remove:function(value){ this.removeAt(this.find(value)); }, //add element to collection at specific position insertAt:function(data,pos){ if (!pos && pos!==0) //add to the end by default this.push(data); else { var b = this.splice(pos,(this.length-pos)); this[pos] = data; this.push.apply(this,b); //reconstruct array without loosing this pointer } }, //return index of element, -1 if it doesn't exists find:function(data){ for (var i=0; i<this.length; i++) if (data==this[i]) return i; return -1; }, //execute some method for each element of array each:function(functor,master){ for (var i=0; i < this.length; i++) functor.call((master||this),this[i]); }, //create new array from source, by using results of functor map:function(functor,master){ for (var i=0; i < this.length; i++) this[i]=functor.call((master||this),this[i]); return this; }, filter:function(functor, master){ for (var i=0; i < this.length; i++) if (!functor.call((master||this),this[i])){ this.splice(i,1); i--; } return this; } }; dhx.env = {}; // dhx.env.transform // dhx.env.transition (function(){ if (navigator.userAgent.indexOf("Mobile")!=-1) dhx.env.mobile = true; if (dhx.env.mobile || navigator.userAgent.indexOf("iPad")!=-1 || navigator.userAgent.indexOf("Android")!=-1) dhx.env.touch = true; if (navigator.userAgent.indexOf('Opera')!=-1) dhx.env.isOpera=true; else{ //very rough detection, but it is enough for current goals dhx.env.isIE=!!document.all; dhx.env.isFF=!document.all; dhx.env.isWebKit=(navigator.userAgent.indexOf("KHTML")!=-1); dhx.env.isSafari=dhx.env.isWebKit && (navigator.userAgent.indexOf('Mac')!=-1); } if(navigator.userAgent.toLowerCase().indexOf("android")!=-1) dhx.env.isAndroid = true; dhx.env.transform = false; dhx.env.transition = false; var options = {}; options.names = ['transform', 'transition']; options.transform = ['transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']; options.transition = ['transition', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition']; var d = document.createElement("DIV"); for(var i=0; i<options.names.length; i++) { var coll = options[options.names[i]]; for (var j=0; j < coll.length; j++) { if(typeof d.style[coll[j]] != 'undefined'){ dhx.env[options.names[i]] = coll[j]; break; } } } d.style[dhx.env.transform] = "translate3d(0,0,0)"; dhx.env.translate = (d.style[dhx.env.transform])?"translate3d":"translate"; var prefix = ''; // default option var cssprefix = false; if(dhx.env.isOpera){ prefix = '-o-'; cssprefix = "O"; } if(dhx.env.isFF) prefix = '-Moz-'; if(dhx.env.isWebKit) prefix = '-webkit-'; if(dhx.env.isIE) prefix = '-ms-'; dhx.env.transformCSSPrefix = prefix; dhx.env.transformPrefix = cssprefix||(dhx.env.transformCSSPrefix.replace(/-/gi, "")); dhx.env.transitionEnd = ((dhx.env.transformCSSPrefix == '-Moz-')?"transitionend":(dhx.env.transformPrefix+"TransitionEnd")); })(); dhx.env.svg = (function(){ return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"); })(); //html helpers dhx.html={ _native_on_selectstart:0, denySelect:function(){ if (!dhx._native_on_selectstart) dhx._native_on_selectstart = document.onselectstart; document.onselectstart = dhx.html.stopEvent; }, allowSelect:function(){ if (dhx._native_on_selectstart !== 0){ document.onselectstart = dhx._native_on_selectstart||null; } dhx._native_on_selectstart = 0; }, index:function(node){ var k=0; //must be =, it is not a comparation! /*jsl:ignore*/ while (node = node.previousSibling) k++; /*jsl:end*/ return k; }, _style_cache:{}, createCss:function(rule){ var text = ""; for (var key in rule) text+= key+":"+rule[key]+";"; var name = this._style_cache[text]; if (!name){ name = "s"+dhx.uid(); this.addStyle("."+name+"{"+text+"}"); this._style_cache[text] = name; } return name; }, addStyle:function(rule){ var style = document.createElement("style"); style.setAttribute("type", "text/css"); style.setAttribute("media", "screen"); /*IE8*/ if (style.styleSheet) style.styleSheet.cssText = rule; else style.appendChild(document.createTextNode(rule)); document.getElementsByTagName("head")[0].appendChild(style); }, create:function(name,attrs,html){ attrs = attrs || {}; var node = document.createElement(name); for (var attr_name in attrs) node.setAttribute(attr_name, attrs[attr_name]); if (attrs.style) node.style.cssText = attrs.style; if (attrs["class"]) node.className = attrs["class"]; if (html) node.innerHTML=html; return node; }, //return node value, different logic for different html elements getValue:function(node){ node = dhx.toNode(node); if (!node) return ""; return dhx.isUndefined(node.value)?node.innerHTML:node.value; }, //remove html node, can process an array of nodes at once remove:function(node){ if (node instanceof Array) for (var i=0; i < node.length; i++) this.remove(node[i]); else if (node && node.parentNode) node.parentNode.removeChild(node); }, //insert new node before sibling, or at the end if sibling doesn't exist insertBefore: function(node,before,rescue){ if (!node) return; if (before && before.parentNode) before.parentNode.insertBefore(node, before); else rescue.appendChild(node); }, //return custom ID from html element //will check all parents starting from event's target locate:function(e,id){ if (e.tagName) var trg = e; else { e=e||event; var trg=e.target||e.srcElement; } while (trg){ if (trg.getAttribute){ //text nodes has not getAttribute var test = trg.getAttribute(id); if (test) return test; } trg=trg.parentNode; } return null; }, //returns position of html element on the page offset:function(elem) { if (elem.getBoundingClientRect) { //HTML5 method var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; var top = box.top + scrollTop - clientTop; var left = box.left + scrollLeft - clientLeft; return { y: Math.round(top), x: Math.round(left) }; } else { //fallback to naive approach var top=0, left=0; while(elem) { top = top + parseInt(elem.offsetTop,10); left = left + parseInt(elem.offsetLeft,10); elem = elem.offsetParent; } return {y: top, x: left}; } }, //returns relative position of event posRelative:function(ev){ ev = ev || event; if (!dhx.isUndefined(ev.offsetX)) return { x:ev.offsetX, y:ev.offsetY }; //ie, webkit else return { x:ev.layerX, y:ev.layerY }; //firefox }, //returns position of event pos:function(ev){ ev = ev || event; if(ev.pageX || ev.pageY) //FF, KHTML return {x:ev.pageX, y:ev.pageY}; //IE var d = ((dhx.env.isIE)&&(document.compatMode != "BackCompat"))?document.documentElement:document.body; return { x:ev.clientX + d.scrollLeft - d.clientLeft, y:ev.clientY + d.scrollTop - d.clientTop }; }, //prevent event action preventEvent:function(e){ if (e && e.preventDefault) e.preventDefault(); return dhx.html.stopEvent(e); }, //stop event bubbling stopEvent:function(e){ (e||event).cancelBubble=true; return false; }, //add css class to the node addCss:function(node,name){ node.className+=" "+name; }, //remove css class from the node removeCss:function(node,name){ node.className=node.className.replace(RegExp(" "+name,"g"),""); } }; dhx.ready = function(code){ if (this._ready) code.call(); else this._ready_code.push(code); }; dhx._ready_code = []; //autodetect codebase folder (function(){ var temp = document.getElementsByTagName("SCRIPT"); //current script, most probably dhx.assert(temp.length,"Can't locate codebase"); if (temp.length){ //full path to script temp = (temp[temp.length-1].getAttribute("src")||"").split("/"); //get folder name temp.splice(temp.length-1, 1); dhx.codebase = temp.slice(0, temp.length).join("/")+"/"; } dhx.event(window, "load", function(){ dhx4.callEvent("onReady",[]); dhx.delay(function(){ dhx._ready = true; for (var i=0; i < dhx._ready_code.length; i++) dhx._ready_code[i].call(); dhx._ready_code=[]; }); }); })(); dhx.locale=dhx.locale||{}; dhx.assert_core_ready(); dhx.ready(function(){ dhx.event(document.body,"click", function(e){ dhx4.callEvent("onClick",[e||event]); }); }); /*DHX:Depend core/bind.js*/ /*DHX:Depend core/dhx.js*/ /*DHX:Depend core/config.js*/ /* Behavior:Settings @export customize config */ /*DHX:Depend core/template.js*/ /* Template - handles html templates */ /*DHX:Depend core/dhx.js*/ (function(){ var _cache = {}; var newlines = new RegExp("(\\r\\n|\\n)","g"); var quotes = new RegExp("(\\\")","g"); dhx.Template = function(str){ if (typeof str == "function") return str; if (_cache[str]) return _cache[str]; str=(str||"").toString(); if (str.indexOf("->")!=-1){ str = str.split("->"); switch(str[0]){ case "html": //load from some container on the page str = dhx.html.getValue(str[1]); break; default: //do nothing, will use template as is break; } } //supported idioms // {obj.attr} => named attribute or value of sub-tag in case of xml str=(str||"").toString(); str=str.replace(newlines,"\\n"); str=str.replace(quotes,"\\\""); str=str.replace(/\{obj\.([^}?]+)\?([^:]*):([^}]*)\}/g,"\"+(obj.$1?\"$2\":\"$3\")+\""); str=str.replace(/\{common\.([^}\(]*)\}/g,"\"+(common.$1||'')+\""); str=str.replace(/\{common\.([^\}\(]*)\(\)\}/g,"\"+(common.$1?common.$1.apply(this, arguments):\"\")+\""); str=str.replace(/\{obj\.([^}]*)\}/g,"\"+(obj.$1)+\""); str=str.replace("{obj}","\"+obj+\""); str=str.replace(/#([^#'";, ]+)#/gi,"\"+(obj.$1)+\""); try { _cache[str] = Function("obj","common","return \""+str+"\";"); } catch(e){ dhx.assert_error("Invalid template:"+str); } return _cache[str]; }; dhx.Template.empty=function(){ return ""; }; dhx.Template.bind =function(value){ return dhx.bind(dhx.Template(value),this); }; /* adds new template-type obj - object to which template will be added data - properties of template */ dhx.Type=function(obj, data){ if (obj._dhx_proto_wait){ if (!obj._dhx_type_wait) obj._dhx_type_wait = []; obj._dhx_type_wait.push(data); return; } //auto switch to prototype, if name of class was provided if (typeof obj == "function") obj = obj.prototype; if (!obj.types){ obj.types = { "default" : obj.type }; obj.type.name = "default"; } var name = data.name; var type = obj.type; if (name) type = obj.types[name] = dhx.clone(data.baseType?obj.types[data.baseType]:obj.type); for(var key in data){ if (key.indexOf("template")===0) type[key] = dhx.Template(data[key]); else type[key]=data[key]; } return name; }; })(); /*DHX:Depend core/dhx.js*/ dhx.Settings={ $init:function(){ /* property can be accessed as this.config.some in same time for inner call it have sense to use _settings because it will be minified in final version */ this._settings = this.config= {}; }, define:function(property, value){ if (typeof property == "object") return this._parseSeetingColl(property); return this._define(property, value); }, _define:function(property,value){ //method with name {prop}_setter will be used as property setter //setter is optional var setter = this[property+"_setter"]; return this._settings[property]=setter?setter.call(this,value,property):value; }, //process configuration object _parseSeetingColl:function(coll){ if (coll){ for (var a in coll) //for each setting this._define(a,coll[a]); //set value through config } }, //helper for object initialization _parseSettings:function(obj,initial){ //initial - set of default values var settings = {}; if (initial) settings = dhx.extend(settings,initial); //code below will copy all properties over default one if (typeof obj == "object" && !obj.tagName) dhx.extend(settings,obj, true); //call config for each setting this._parseSeetingColl(settings); }, _mergeSettings:function(config, defaults){ for (var key in defaults) switch(typeof config[key]){ case "object": config[key] = this._mergeSettings((config[key]||{}), defaults[key]); break; case "undefined": config[key] = defaults[key]; break; default: //do nothing break; } return config; }, debug_freid_c_id:true, debug_freid_a_name:true }; /*DHX:Depend core/datastore.js*/ /*DHX:Depend core/load.js*/ /* ajax operations can be used for direct loading as dhx.ajax(ulr, callback) or dhx.ajax().item(url) dhx.ajax().post(url) */ /*DHX:Depend core/dhx.js*/ dhx.ajax = function(url,call,master){ //if parameters was provided - made fast call if (arguments.length!==0){ var http_request = new dhx.ajax(); if (master) http_request.master=master; return http_request.get(url,null,call); } if (!this.getXHR) return new dhx.ajax(); //allow to create new instance without direct new declaration return this; }; dhx.ajax.count = 0; dhx.ajax.prototype={ master:null, //creates xmlHTTP object getXHR:function(){ if (dhx.env.isIE) return new ActiveXObject("Microsoft.xmlHTTP"); else return new XMLHttpRequest(); }, /* send data to the server params - hash of properties which will be added to the url call - callback, can be an array of functions */ send:function(url,params,call){ var x=this.getXHR(); if (!dhx.isArray(call)) call = [call]; //add extra params to the url if (typeof params == "object"){ var t=[]; for (var a in params){ var value = params[a]; if (value === null || value === dhx.undefined) value = ""; t.push(a+"="+encodeURIComponent(value));// utf-8 escaping } params=t.join("&"); } if (params && this.request==='GET'){ url=url+(url.indexOf("?")!=-1 ? "&" : "?")+params; params=null; } x.open(this.request,url,!this._sync); if (this.request === 'POST') x.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //async mode, define loading callback var self=this; x.onreadystatechange= function(){ if (!x.readyState || x.readyState == 4){ if (dhx.debug_time) dhx.log_full_time("data_loading"); //log rendering time dhx.ajax.count++; if (call && self){ for (var i=0; i < call.length; i++) //there can be multiple callbacks if (call[i]){ var method = (call[i].success||call[i]); if (x.status >= 400 || (!x.status && !x.responseText)) method = call[i].error; if (method) method.call((self.master||self),x.responseText,x.responseXML,x); } } if (self) self.master=null; call=self=null; //anti-leak } }; x.send(params||null); return x; //return XHR, which can be used in case of sync. mode }, //GET request get:function(url,params,call){ if (arguments.length == 2){ call = params; params = null; } this.request='GET'; return this.send(url,params,call); }, //POST request post:function(url,params,call){ this.request='POST'; return this.send(url,params,call); }, //PUT request put:function(url,params,call){ this.request='PUT'; return this.send(url,params,call); }, //POST request del:function(url,params,call){ this.request='DELETE'; return this.send(url,params,call); }, sync:function(){ this._sync = true; return this; }, bind:function(master){ this.master = master; return this; } }; /*submits values*/ dhx.send = function(url, values, method, target){ var form = dhx.html.create("FORM",{ "target":(target||"_self"), "action":url, "method":(method||"POST") },""); for (var k in values) { var field = dhx.html.create("INPUT",{"type":"hidden","name": k,"value": values[k]},""); form.appendChild(field); } form.style.display = "none"; document.body.appendChild(form); form.submit(); document.body.removeChild(form); }; dhx.AtomDataLoader={ $init:function(config){ //prepare data store this.data = {}; if (config){ this._settings.datatype = config.datatype||"json"; this.$ready.push(this._load_when_ready); } }, _load_when_ready:function(){ this._ready_for_data = true; if (this._settings.url) this.url_setter(this._settings.url); if (this._settings.data) this.data_setter(this._settings.data); }, url_setter:function(value){ if (!this._ready_for_data) return value; this.load(value, this._settings.datatype); return value; }, data_setter:function(value){ if (!this._ready_for_data) return value; this.parse(value, this._settings.datatype); return true; }, debug_freid_c_datatype:true, debug_freid_c_dataFeed:true, //loads data from external URL load:function(url,call){ if (url.$proxy) { url.load(this, typeof call == "string" ? call : "json"); return; } this.callEvent("onXLS",[]); if (typeof call == "string"){ //second parameter can be a loading type or callback //we are not using setDriver as data may be a non-datastore here this.data.driver = dhx.DataDriver[call]; call = arguments[2]; } else if (!this.data.driver) this.data.driver = dhx.DataDriver.json; //load data by async ajax call //loading_key - can be set by component, to ignore data from old async requests var callback = [{ success: this._onLoad, error: this._onLoadError }]; if (call){ if (dhx.isArray(call)) callback.push.apply(callback,call); else callback.push(call); } return dhx.ajax(url,callback,this); }, //loads data from object parse:function(data,type){ this.callEvent("onXLS",[]); this.data.driver = dhx.DataDriver[type||"json"]; this._onLoad(data,null); }, //default after loading callback _onLoad:function(text,xml,loader,key){ var driver = this.data.driver; var data = driver.toObject(text,xml); if (data){ var top = driver.getRecords(data)[0]; this.data=(driver?driver.getDetails(top):text); } else this._onLoadError(text,xml,loader); this.callEvent("onXLE",[]); }, _onLoadError:function(text, xml, xhttp){ this.callEvent("onXLE",[]); this.callEvent("onLoadError",arguments); dhx4.callEvent("onLoadError", [text, xml, xhttp, this]); }, _check_data_feed:function(data){ if (!this._settings.dataFeed || this._ignore_feed || !data) return true; var url = this._settings.dataFeed; if (typeof url == "function") return url.call(this, (data.id||data), data); url = url+(url.indexOf("?")==-1?"?":"&")+"action=get&id="+encodeURIComponent(data.id||data); this.callEvent("onXLS",[]); dhx.ajax(url, function(text,xml,loader){ this._ignore_feed=true; var data = dhx.DataDriver.toObject(text, xml); if (data) this.setValues(data.getDetails(data.getRecords()[0])); else this._onLoadError(text,xml,loader); this._ignore_feed=false; this.callEvent("onXLE",[]); }, this); return false; } }; /* Abstraction layer for different data types */ dhx.DataDriver={}; dhx.DataDriver.json={ //convert json string to json object if necessary toObject:function(data){ if (!data) data="[]"; if (typeof data == "string"){ try{ eval ("dhx.temp="+data); } catch(e){ dhx.assert_error(e); return null; } data = dhx.temp; } if (data.data){ var t = data.data.config = {}; for (var key in data) if (key!="data") t[key] = data[key]; data = data.data; } return data; }, //get array of records getRecords:function(data){ if (data && !dhx.isArray(data)) return [data]; return data; }, //get hash of properties for single record getDetails:function(data){ if (typeof data == "string") return { id:dhx.uid(), value:data }; return data; }, //get count of data and position at which new data need to be inserted getInfo:function(data){ var cfg = data.config; if (!cfg) return {}; return { _size:(cfg.total_count||0), _from:(cfg.pos||0), _parent:(cfg.parent||0), _config:(cfg.config), _key:(cfg.dhx_security) }; }, child:"data" }; dhx.DataDriver.html={ /* incoming data can be - collection of nodes - ID of parent container - HTML text */ toObject:function(data){ if (typeof data == "string"){ var t=null; if (data.indexOf("<")==-1) //if no tags inside - probably its an ID t = dhx.toNode(data); if (!t){ t=document.createElement("DIV"); t.innerHTML = data; } return t.getElementsByTagName(this.tag); } return data; }, //get array of records getRecords:function(node){ var data = []; for (var i=0; i<node.childNodes.length; i++){ var child = node.childNodes[i]; if (child.nodeType == 1) data.push(child); } return data; }, //get hash of properties for single record getDetails:function(data){ return dhx.DataDriver.xml.tagToObject(data); }, //dyn loading is not supported by HTML data source getInfo:function(data){ return { _size:0, _from:0 }; }, tag: "LI" }; dhx.DataDriver.jsarray={ //eval jsarray string to jsarray object if necessary toObject:function(data){ if (typeof data == "string"){ eval ("dhx.temp="+data); return dhx.temp; } return data; }, //get array of records getRecords:function(data){ return data; }, //get hash of properties for single record, in case of array they will have names as "data{index}" getDetails:function(data){ var result = {}; for (var i=0; i < data.length; i++) result["data"+i]=data[i]; return result; }, //dyn loading is not supported by js-array data source getInfo:function(data){ return { _size:0, _from:0 }; } }; dhx.DataDriver.csv={ //incoming data always a string toObject:function(data){ return data; }, //get array of records getRecords:function(data){ return data.split(this.row); }, //get hash of properties for single record, data named as "data{index}" getDetails:function(data){ data = this.stringToArray(data); var result = {}; for (var i=0; i < data.length; i++) result["data"+i]=data[i]; return result; }, //dyn loading is not supported by csv data source getInfo:function(data){ return { _size:0, _from:0 }; }, //split string in array, takes string surrounding quotes in account stringToArray:function(data){ data = data.split(this.cell); for (var i=0; i < data.length; i++) data[i] = data[i].replace(/^[ \t\n\r]*(\"|)/g,"").replace(/(\"|)[ \t\n\r]*$/g,""); return data; }, row:"\n", //default row separator cell:"," //default cell separator }; dhx.DataDriver.xml={ _isValidXML:function(data){ if (!data || !data.documentElement) return null; if (data.getElementsByTagName("parsererror").length) return null; return data; }, //convert xml string to xml object if necessary toObject:function(text,xml){ if (this._isValidXML(data)) return data; if (typeof text == "string") var data = this.fromString(text.replace(/^[\s]+/,"")); else data = text; if (this._isValidXML(data)) return data; return null; }, //get array of records getRecords:function(data){ return this.xpath(data,this.records); }, records:"/*/item", child:"item", config:"/*/config", //get hash of properties for single record getDetails:function(data){ return this.tagToObject(data,{}); }, //get count of data and position at which new data_loading need to be inserted getInfo:function(data){ var config = this.xpath(data, this.config); if (config.length) config = this.assignTypes(this.tagToObject(config[0],{})); else config = null; return { _size:(data.documentElement.getAttribute("total_count")||0), _from:(data.documentElement.getAttribute("pos")||0), _parent:(data.documentElement.getAttribute("parent")||0), _config:config, _key:(data.documentElement.getAttribute("dhx_security")||null) }; }, //xpath helper xpath:function(xml,path){ if (window.XPathResult){ //FF, KHTML, Opera var node=xml; if(xml.nodeName.indexOf("document")==-1) xml=xml.ownerDocument; var res = []; var col = xml.evaluate(path, node, null, XPathResult.ANY_TYPE, null); var temp = col.iterateNext(); while (temp){ res.push(temp); temp = col.iterateNext(); } return res; } else { var test = true; try { if (typeof(xml.selectNodes)=="undefined") test = false; } catch(e){ /*IE7 and below can't operate with xml object*/ } //IE if (test) return xml.selectNodes(path); else { //Google hate us, there is no interface to do XPath //use naive approach var name = path.split("/").pop(); return xml.getElementsByTagName(name); } } }, assignTypes:function(obj){ for (var k in obj){ var test = obj[k]; if (typeof test == "object") this.assignTypes(test); else if (typeof test == "string"){ if (test === "") continue; if (test == "true") obj[k] = true; else if (test == "false") obj[k] = false; else if (test == test*1) obj[k] = obj[k]*1; } } return obj; }, //convert xml tag to js object, all subtags and attributes are mapped to the properties of result object tagToObject:function(tag,z){ z=z||{}; var flag=false; //map attributes var a=tag.attributes; if(a && a.length){ for (var i=0; i<a.length; i++) z[a[i].name]=a[i].value; flag = true; } //map subtags var b=tag.childNodes; var state = {}; for (var i=0; i<b.length; i++){ if (b[i].nodeType==1){ var name = b[i].tagName; if (typeof z[name] != "undefined"){ if (!dhx.isArray(z[name])) z[name]=[z[name]]; z[name].push(this.tagToObject(b[i],{})); } else z[b[i].tagName]=this.tagToObject(b[i],{}); //sub-object for complex subtags flag=true; } } if (!flag) return this.nodeValue(tag); //each object will have its text content as "value" property z.value = z.value||this.nodeValue(tag); return z; }, //get value of xml node nodeValue:function(node){ if (node.firstChild) return node.firstChild.data; //FIXME - long text nodes in FF not supported for now return ""; }, //convert XML string to XML object fromString:function(xmlString){ try{ if (window.DOMParser) // FF, KHTML, Opera return (new DOMParser()).parseFromString(xmlString,"text/xml"); if (window.ActiveXObject){ // IE, utf-8 only var temp=new ActiveXObject("Microsoft.xmlDOM"); temp.loadXML(xmlString); return temp; } } catch(e){ dhx.assert_error(e); return null; } dhx.assert_error("Load from xml string is not supported"); } }; /*DHX:Depend core/dhx.js*/ /* Behavior:DataLoader - load data in the component @export load parse */ dhx.DataLoader=dhx.proto({ $init:function(config){ //prepare data store config = config || ""; //list of all active ajax requests this._ajax_queue = dhx.toArray(); this.data = new dhx.DataStore(); this.data.attachEvent("onClearAll",dhx.bind(this._call_onclearall,this)); this.data.attachEvent("onServerConfig", dhx.bind(this._call_on_config, this)); this.data.feed = this._feed; }, _feed:function(from,count,callback){ //allow only single request at same time if (this._load_count) return this._load_count=[from,count,callback]; //save last ignored request else this._load_count=true; this._feed_last = [from, count]; this._feed_common.call(this, from, count, callback); }, _feed_common:function(from, count, callback){ var url = this.data.url; if (from<0) from = 0; this.load(url+((url.indexOf("?")==-1)?"?":"&")+(this.dataCount()?("continue=true&"):"")+"start="+from+"&count="+count,[ this._feed_callback, callback ]); }, _feed_callback:function(){ //after loading check if we have some ignored requests var temp = this._load_count; var last = this._feed_last; this._load_count = false; if (typeof temp =="object" && (temp[0]!=last[0] || temp[1]!=last[1])) this.data.feed.apply(this, temp); //load last ignored request }, //loads data from external URL load:function(url,call){ var ajax = dhx.AtomDataLoader.load.apply(this, arguments); this._ajax_queue.push(ajax); //prepare data feed for dyn. loading if (!this.data.url) this.data.url = url; }, //load next set of data rows loadNext:function(count, start, callback, url, now){ if (this._settings.datathrottle && !now){ if (this._throttle_request) window.clearTimeout(this._throttle_request); this._throttle_request = dhx.delay(function(){ this.loadNext(count, start, callback, url, true); },this, 0, this._settings.datathrottle); return; } if (!start && start !== 0) start = this.dataCount(); this.data.url = this.data.url || url; if (this.callEvent("onDataRequest", [start,count,callback,url]) && this.data.url) this.data.feed.call(this, start, count, callback); }, _maybe_loading_already:function(count, from){ var last = this._feed_last; if(this._load_count && last){ if (last[0]<=from && (last[1]+last[0] >= count + from )) return true; } return false; }, //default after loading callback _onLoad:function(text,xml,loader){ //ignore data loading command if data was reloaded this._ajax_queue.remove(loader); var data = this.data.driver.toObject(text,xml); if (data) this.data._parse(data); else return this._onLoadError(text, xml, loader); //data loaded, view rendered, call onready handler this._call_onready(); this.callEvent("onXLE",[]); }, removeMissed_setter:function(value){ return this.data._removeMissed = value; }, scheme_setter:function(value){ this.data.scheme(value); }, dataFeed_setter:function(value){ this.data.attachEvent("onBeforeFilter", dhx.bind(function(text, value){ if (this._settings.dataFeed){ var filter = {}; if (!text && !value) return; if (typeof text == "function"){ if (!value) return; text(value, filter); } else filter = { text:value }; this.clearAll(); var url = this._settings.dataFeed; var urldata = []; if (typeof url == "function") return url.call(this, value, filter); for (var key in filter) urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key])); this.load(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&"), this._settings.datatype); return false; } },this)); return value; }, debug_freid_c_ready:true, debug_freid_c_datathrottle:true, _call_onready:function(){ if (this._settings.ready && !this._ready_was_used){ var code = dhx.toFunctor(this._settings.ready); if (code) dhx.delay(code, this, arguments); this._ready_was_used = true; } }, _call_onclearall:function(){ for (var i = 0; i < this._ajax_queue.length; i++) this._ajax_queue[i].abort(); this._ajax_queue = dhx.toArray(); }, _call_on_config:function(config){ this._parseSeetingColl(config); } },dhx.AtomDataLoader); /* DataStore is not a behavior, it standalone object, which represents collection of data. Call provideAPI to map data API @export exists idByIndex indexById get set refresh dataCount sort filter next previous clearAll first last */ dhx.DataStore = function(){ this.name = "DataStore"; dhx.extend(this, dhx.EventSystem); this.setDriver("json"); //default data source is an this.pull = {}; //hash of IDs this.order = dhx.toArray(); //order of IDs this._marks = {}; }; dhx.DataStore.prototype={ //defines type of used data driver //data driver is an abstraction other different data formats - xml, json, csv, etc. setDriver:function(type){ dhx.assert(dhx.DataDriver[type],"incorrect DataDriver"); this.driver = dhx.DataDriver[type]; }, //process incoming raw data _parse:function(data,master){ this.callEvent("onParse", [this.driver, data]); if (this._filter_order) this.filter(); //get size and position of data var info = this.driver.getInfo(data); if (info._key) dhx.securityKey = info._key; if (info._config) this.callEvent("onServerConfig",[info._config]); //get array of records var recs = this.driver.getRecords(data); this._inner_parse(info, recs); //in case of tree store we may want to group data if (this._scheme_group && this._group_processing) this._group_processing(this._scheme_group); //optional data sorting if (this._scheme_sort){ this.blockEvent(); this.sort(this._scheme_sort); this.unblockEvent(); } this.callEvent("onStoreLoad",[this.driver, data]); //repaint self after data loading this.refresh(); }, _inner_parse:function(info, recs){ var from = (info._from||0)*1; var subload = true; var marks = false; if (from === 0 && this.order[0]){ //update mode if (this._removeMissed){ //update mode, create kill list marks = {}; for (var i=0; i<this.order.length; i++) marks[this.order[i]]=true; } subload = false; from = this.order.length; } var j=0; for (var i=0; i<recs.length; i++){ //get hash of details for each record var temp = this.driver.getDetails(recs[i]); var id = this.id(temp); //generate ID for the record if (!this.pull[id]){ //if such ID already exists - update instead of insert this.order[j+from]=id; j++; } else if (subload && this.order[j+from]) j++; if(this.pull[id]){ dhx.extend(this.pull[id],temp,true);//add only new properties if (this._scheme_update) this._scheme_update(this.pull[id]); //update mode, remove item from kill list if (marks) delete marks[id]; } else{ this.pull[id] = temp; if (this._scheme_init) this._scheme_init(temp); } } //update mode, delete items which are not existing in the new xml if (marks){ this.blockEvent(); for (var delid in marks) this.remove(delid); this.unblockEvent(); } if (!this.order[info._size-1]) this.order[info._size-1] = dhx.undefined; }, //generate id for data object id:function(data){ return data.id||(data.id=dhx.uid()); }, changeId:function(old, newid){ //dhx.assert(this.pull[old],"Can't change id, for non existing item: "+old); if(this.pull[old]) this.pull[newid] = this.pull[old]; this.pull[newid].id = newid; this.order[this.order.find(old)]=newid; if (this._filter_order) this._filter_order[this._filter_order.find(old)]=newid; if (this._marks[old]){ this._marks[newid] = this._marks[old]; delete this._marks[old]; } this.callEvent("onIdChange", [old, newid]); if (this._render_change_id) this._render_change_id(old, newid); delete this.pull[old]; }, //get data from hash by id item:function(id){ return this.pull[id]; }, //assigns data by id update:function(id,data){ if (dhx.isUndefined(data)) data = this.item(id); if (this._scheme_update) this._scheme_update(data); if (this.callEvent("onBeforeUpdate", [id, data]) === false) return false; this.pull[id]=data; this.callEvent("onStoreUpdated",[id, data, "update"]); }, //sends repainting signal refresh:function(id){ if (this._skip_refresh) return; if (id) this.callEvent("onStoreUpdated",[id, this.pull[id], "paint"]); else this.callEvent("onStoreUpdated",[null,null,null]); }, silent:function(code, master){ this._skip_refresh = true; code.call(master||this); this._skip_refresh = false; }, //converts range IDs to array of all IDs between them getRange:function(from,to){ //if some point is not defined - use first or last id //BEWARE - do not use empty or null ID if (from) from = this.indexById(from); else from = (this.$min||this.startOffset)||0; if (to) to = this.indexById(to); else { to = Math.min(((this.$max||this.endOffset)||Infinity),(this.dataCount()-1)); if (to<0) to = 0; //we have not data in the store } if (from>to){ //can be in case of backward shift-selection var a=to; to=from; from=a; } return this.getIndexRange(from,to); }, //converts range of indexes to array of all IDs between them getIndexRange:function(from,to){ to=Math.min((to||Infinity),this.dataCount()-1); var ret=dhx.toArray(); //result of method is rich-array for (var i=(from||0); i <= to; i++) ret.push(this.item(this.order[i])); return ret; }, //returns total count of elements dataCount:function(){ return this.order.length; }, //returns truy if item with such ID exists exists:function(id){ return !!(this.pull[id]); }, //nextmethod is not visible on component level, check DataMove.move //moves item from source index to the target index move:function(sindex,tindex){ dhx.assert(sindex>=0 && tindex>=0, "DataStore::move","Incorrect indexes"); var id = this.idByIndex(sindex); var obj = this.item(id); this.order.removeAt(sindex); //remove at old position //if (sindex<tindex) tindex--; //correct shift, caused by element removing this.order.insertAt(id,Math.min(this.order.length, tindex)); //insert at new position //repaint signal this.callEvent("onStoreUpdated",[id,obj,"move"]); }, scheme:function(config){ this._scheme = {}; this._scheme_init = config.$init; this._scheme_update = config.$update; this._scheme_serialize = config.$serialize; this._scheme_group = config.$group; this._scheme_sort = config.$sort; //ignore $-starting properties, as they have special meaning for (var key in config) if (key.substr(0,1) != "$") this._scheme[key] = config[key]; }, sync:function(source, filter, silent){ if (typeof source == "string") source = $$("source"); if (typeof filter != "function"){ silent = filter; filter = null; } if (dhx.debug_bind){ this.debug_sync_master = source; dhx.log("[sync] "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id+" <= "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id); } this._backbone_source = false; if (source.name != "DataStore"){ if (source.data && source.data.name == "DataStore") source = source.data; else this._backbone_source = true; } var sync_logic = dhx.bind(function(mode, record, data){ if (this._backbone_source){ //ignore first call for backbone sync if (!mode) return; //data changing if (mode.indexOf("change") === 0){ if (mode == "change"){ this.pull[record.id] = record.attributes; this.refresh(record.id); return; } else return; //ignoring property change event } //we need to access global model, it has different position for different events if (mode == "reset") data = record; //fill data collections from backbone model this.order = []; this.pull = {}; this._filter_order = null; for (var i=0; i<data.models.length; i++){ var id = data.models[i].id; this.order.push(id); this.pull[id] = data.models[i].attributes; } } else { this._filter_order = null; this.order = dhx.toArray([].concat(source.order)); this.pull = source.pull; } if (filter) this.silent(filter); if (this._on_sync) this._on_sync(); if (dhx.debug_bind) dhx.log("[sync:request] "+this.debug_sync_master.name+"@"+this.debug_sync_master._settings.id + " <= "+this.debug_bind_master.name+"@"+this.debug_bind_master._settings.id); this.callEvent("onSyncApply",[]); if (!silent) this.refresh(); else silent = false; }, this); if (this._backbone_source) source.bind('all', sync_logic); else this._sync_events = [ source.attachEvent("onStoreUpdated", sync_logic), source.attachEvent("onIdChange", dhx.bind(function(old, nid){ this.changeId(old, nid); }, this)) ]; sync_logic(); }, //adds item to the store add:function(obj,index){ //default values if (this._scheme) for (var key in this._scheme) if (dhx.isUndefined(obj[key])) obj[key] = this._scheme[key]; if (this._scheme_init) this._scheme_init(obj); //generate id for the item var id = this.id(obj); //in case of treetable order is sent as 3rd parameter var order = arguments[2]||this.order; //by default item is added to the end of the list var data_size = order.length; if (dhx.isUndefined(index) || index < 0) index = data_size; //check to prevent too big indexes if (index > data_size){ dhx.log("Warning","DataStore:add","Index of out of bounds"); index = Math.min(order.length,index); } if (this.callEvent("onBeforeAdd", [id, obj, index]) === false) return false; dhx.assert(!this.exists(id), "Not unique ID"); this.pull[id]=obj; order.insertAt(id,index); if (this._filter_order){ //adding during filtering //we can't know the location of new item in full dataset, making suggestion //put at end by default var original_index = this._filter_order.length; //put at start only if adding to the start and some data exists if (!index && this.order.length) original_index = 0; this._filter_order.insertAt(id,original_index); } this.callEvent("onAfterAdd",[id,index]); //repaint signal this.callEvent("onStoreUpdated",[id,obj,"add"]); return id; }, //removes element from datastore remove:function(id){ //id can be an array of IDs - result of getSelect, for example if (dhx.isArray(id)){ for (var i=0; i < id.length; i++) this.remove(id[i]); return; } if (this.callEvent("onBeforeDelete",[id]) === false) return false; dhx.assert(this.exists(id), "Not existing ID in remove command"+id); var obj = this.item(id); //save for later event //clear from collections this.order.remove(id); if (this._filter_order) this._filter_order.remove(id); delete this.pull[id]; if (this._marks[id]) delete this._marks[id]; this.callEvent("onAfterDelete",[id]); //repaint signal this.callEvent("onStoreUpdated",[id,obj,"delete"]); }, //deletes all records in datastore clearAll:function(){ //instead of deleting one by one - just reset inner collections this.pull = {}; this.order = dhx.toArray(); //this.feed = null; this._filter_order = this.url = null; this.callEvent("onClearAll",[]); this.refresh(); }, //converts id to index idByIndex:function(index){ if (index>=this.order.length || index<0) dhx.log("Warning","DataStore::idByIndex Incorrect index"); return this.order[index]; }, //converts index to id indexById:function(id){ var res = this.order.find(id); //slower than idByIndex if (!this.pull[id]) dhx.log("Warning","DataStore::indexById Non-existing ID: "+ id); return res; }, //returns ID of next element next:function(id,step){ return this.order[this.indexById(id)+(step||1)]; }, //returns ID of first element first:function(){ return this.order[0]; }, //returns ID of last element last:function(){ return this.order[this.order.length-1]; }, //returns ID of previous element previous:function(id,step){ return this.order[this.indexById(id)-(step||1)]; }, /* sort data in collection by - settings of sorting or by - sorting function dir - "asc" or "desc" or by - property dir - "asc" or "desc" as - type of sortings Sorting function will accept 2 parameters and must return 1,0,-1, based on desired order */ sort:function(by, dir, as){ var sort = by; if (typeof by == "function") sort = {as:by, dir:dir}; else if (typeof by == "string") sort = {by:by.replace(/#/g,""), dir:dir, as:as}; var parameters = [sort.by, sort.dir, sort.as]; if (!this.callEvent("onBeforeSort",parameters)) return; this._sort_core(sort); //repaint self this.refresh(); this.callEvent("onAfterSort",parameters); }, _sort_core:function(sort){ if (this.order.length){ var sorter = this._sort._create(sort); //get array of IDs var neworder = this.getRange(this.first(), this.last()); neworder.sort(sorter); this.order = neworder.map(function(obj){ dhx.assert(obj, "Client sorting can't be used with dynamic loading"); return this.id(obj); },this); } }, /* Filter datasource text - property, by which filter value - filter mask or text - filter method Filter method will receive data object and must return true or false */ _filter_reset:function(preserve){ //remove previous filtering , if any if (this._filter_order && !preserve){ this.order = this._filter_order; delete this._filter_order; } }, _filter_core:function(filter, value, preserve){ var neworder = dhx.toArray(); for (var i=0; i < this.order.length; i++){ var id = this.order[i]; if (filter(this.item(id),value)) neworder.push(id); } //set new order of items, store original if (!preserve || !this._filter_order) this._filter_order = this.order; this.order = neworder; }, filter:function(text,value,preserve){ if (!this.callEvent("onBeforeFilter", [text, value])) return; this._filter_reset(preserve); if (!this.order.length) return; //if text not define -just unfilter previous state and exit if (text){ var filter = text; value = value||""; if (typeof text == "string"){ text = text.replace(/#/g,""); if (typeof value == "function") filter = function(obj){ return value(obj[text]); }; else{ value = value.toString().toLowerCase(); filter = function(obj,value){ //default filter - string start from, case in-sensitive dhx.assert(obj, "Client side filtering can't be used with dynamic loading"); return (obj[text]||"").toString().toLowerCase().indexOf(value)!=-1; }; } } this._filter_core(filter, value, preserve, this._filterMode); } //repaint self this.refresh(); this.callEvent("onAfterFilter", []); }, /* Iterate through collection */ each:function(method,master){ for (var i=0; i<this.order.length; i++) method.call((master||this), this.item(this.order[i])); }, _methodPush:function(object,method){ return function(){ return object[method].apply(object,arguments); }; }, addMark:function(id, mark, css, value){ var obj = this._marks[id]||{}; this._marks[id] = obj; if (!obj[mark]){ obj[mark] = value||true; if (css){ this.item(id).$css = (this.item(id).$css||"")+" "+mark; this.refresh(id); } } return obj[mark]; }, removeMark:function(id, mark, css){ var obj = this._marks[id]; if (obj && obj[mark]) delete obj[mark]; if (css){ var current_css = this.item(id).$css; if (current_css){ this.item(id).$css = current_css.replace(mark, ""); this.refresh(id); } } }, hasMark:function(id, mark){ var obj = this._marks[id]; return (obj && obj[mark]); }, /* map inner methods to some distant object */ provideApi:function(target,eventable){ this.debug_bind_master = target; if (eventable){ this.mapEvent({ onbeforesort: target, onaftersort: target, onbeforeadd: target, onafteradd: target, onbeforedelete: target, onafterdelete: target, onbeforeupdate: target/*, onafterfilter: target, onbeforefilter: target*/ }); } var list = ["sort","add","remove","exists","idByIndex","indexById","item","update","refresh","dataCount","filter","next","previous","clearAll","first","last","serialize","sync","addMark","removeMark","hasMark"]; for (var i=0; i < list.length; i++) target[list[i]] = this._methodPush(this,list[i]); }, /* serializes data to a json object */ serialize: function(){ var ids = this.order; var result = []; for(var i=0; i< ids.length;i++) { var el = this.pull[ids[i]]; if (this._scheme_serialize){ el = this._scheme_serialize(el); if (el===false) continue; } result.push(el); } return result; }, _sort:{ _create:function(config){ return this._dir(config.dir, this._by(config.by, config.as)); }, _as:{ "date":function(a,b){ a=a-0; b=b-0; return a>b?1:(a<b?-1:0); }, "int":function(a,b){ a = a*1; b=b*1; return a>b?1:(a<b?-1:0); }, "string_strict":function(a,b){ a = a.toString(); b=b.toString(); return a>b?1:(a<b?-1:0); }, "string":function(a,b){ if (!b) return 1; if (!a) return -1; a = a.toString().toLowerCase(); b=b.toString().toLowerCase(); return a>b?1:(a<b?-1:0); } }, _by:function(prop, method){ if (!prop) return method; if (typeof method != "function") method = this._as[method||"string"]; dhx.assert(method, "Invalid sorting method"); return function(a,b){ return method(a[prop],b[prop]); }; }, _dir:function(prop, method){ if (prop == "asc" || !prop) return method; return function(a,b){ return method(a,b)*-1; }; } } }; //UI interface dhx.BaseBind = { debug_freid_ignore:{ "id":true }, bind:function(target, rule, format){ if (typeof target == 'string') target = dhx.ui.get(target); if (target._initBindSource) target._initBindSource(); if (this._initBindSource) this._initBindSource(); if (!target.getBindData) dhx.extend(target, dhx.BindSource); if (!this._bind_ready){ var old_render = this.render; if (this.filter){ var key = this._settings.id; this.data._on_sync = function(){ target._bind_updated[key] = false; }; } this.render = function(){ if (this._in_bind_processing) return; this._in_bind_processing = true; var result = this.callEvent("onBindRequest"); this._in_bind_processing = false; return old_render.apply(this, ((result === false)?arguments:[])); }; if (this.getValue||this.getValues) this.save = function(){ if (this.validate && !this.validate()) return; target.setBindData((this.getValue?this.getValue:this.getValues()),this._settings.id); }; this._bind_ready = true; } target.addBind(this._settings.id, rule, format); if (dhx.debug_bind) dhx.log("[bind] "+this.name+"@"+this._settings.id+" <= "+target.name+"@"+target._settings.id); var target_id = this._settings.id; //FIXME - check for touchable is not the best solution, to detect necessary event this.attachEvent(this.touchable?"onAfterRender":"onBindRequest", function(){ return target.getBindData(target_id); }); //we want to refresh list after data loading if it has master link //in same time we do not want such operation for dataFeed components //as they are reloading data as response to the master link if (!this._settings.dataFeed && this.loadNext) this.data.attachEvent("onStoreLoad", function(){ target._bind_updated[target_id] = false; }); if (this.isVisible(this._settings.id)) this.refresh(); }, unbind:function(target){ return this._unbind(target); }, _unbind:function(target){ target.removeBind(this._settings.id); var events = (this._sync_events||(this.data?this.data._sync_events:0)); if (events && target.data) for (var i=0; i<events.length; i++) target.data.detachEvent(events[i]); } }; //bind interface dhx.BindSource = { $init:function(){ this._bind_hash = {}; //rules per target this._bind_updated = {}; //update flags this._ignore_binds = {}; //apply specific bind extension this._bind_specific_rules(this); }, saveBatch:function(code){ this._do_not_update_binds = true; code.call(this); this._do_not_update_binds = false; this._update_binds(); }, setBindData:function(data, key){ if (key) this._ignore_binds[key] = true; if (dhx.debug_bind) dhx.log("[bind:save] "+this.name+"@"+this._settings.id+" <= "+"@"+key); if (this.setValue) this.setValue(data); else if (this.setValues) this.setValues(data); else { var id = this.getCursor(); if (id){ data = dhx.extend(this.item(id), data, true); this.update(id, data); } } this.callEvent("onBindUpdate", [data, key, id]); if (this.save) this.save(); if (key) this._ignore_binds[key] = false; }, //fill target with data getBindData:function(key, update){ //fire only if we have data updates from the last time if (this._bind_updated[key]) return false; var target = dhx.ui.get(key); //fill target only when it visible if (target.isVisible(target._settings.id)){ this._bind_updated[key] = true; if (dhx.debug_bind) dhx.log("[bind:request] "+this.name+"@"+this._settings.id+" => "+target.name+"@"+target._settings.id); this._bind_update(target, this._bind_hash[key][0], this._bind_hash[key][1]); //trigger component specific updating logic if (update && target.filter) target.refresh(); } }, //add one more bind target addBind:function(source, rule, format){ this._bind_hash[source] = [rule, format]; }, removeBind:function(source){ delete this._bind_hash[source]; delete this._bind_updated[source]; delete this._ignore_binds[source]; }, //returns true if object belong to "collection" type _bind_specific_rules:function(obj){ if (obj.filter) dhx.extend(this, dhx.CollectionBind); else if (obj.setValue) dhx.extend(this, dhx.ValueBind); else dhx.extend(this, dhx.RecordBind); }, //inform all binded objects, that source data was updated _update_binds:function(){ if (!this._do_not_update_binds) for (var key in this._bind_hash){ if (this._ignore_binds[key]) continue; this._bind_updated[key] = false; this.getBindData(key, true); } }, //copy data from source to the target _bind_update_common:function(target, rule, data){ if (target.setValue) target.setValue(data?data[rule]:data); else if (!target.filter){ if (!data && target.clear) target.clear(); else { if (target._check_data_feed(data)) target.setValues(dhx.clone(data)); } } else { target.data.silent(function(){ this.filter(rule,data); }); } target.callEvent("onBindApply", [data,rule,this]); } }; //pure data objects dhx.DataValue = dhx.proto({ name:"DataValue", isVisible:function(){ return true; }, $init:function(config){ this.data = ""||config; var id = (config&&config.id)?config.id:dhx.uid(); this._settings = { id:id }; dhx.ui.views[id] = this; }, setValue:function(value){ this.data = value; this.callEvent("onChange", [value]); }, getValue:function(){ return this.data; }, refresh:function(){ this.callEvent("onBindRequest"); } }, dhx.EventSystem, dhx.BaseBind); dhx.DataRecord = dhx.proto({ name:"DataRecord", isVisible:function(){ return true; }, $init:function(config){ this.data = config||{}; var id = (config&&config.id)?config.id:dhx.uid(); this._settings = { id:id }; dhx.ui.views[id] = this; }, getValues:function(){ return this.data; }, setValues:function(data){ this.data = data; this.callEvent("onChange", [data]); }, refresh:function(){ this.callEvent("onBindRequest"); } }, dhx.EventSystem, dhx.BaseBind, dhx.AtomDataLoader, dhx.Settings); dhx.DataCollection = dhx.proto({ name:"DataCollection", isVisible:function(){ if (!this.data.order.length && !this.data._filter_order && !this._settings.dataFeed) return false; return true; }, $init:function(config){ this.data.provideApi(this, true); var id = (config&&config.id)?config.id:dhx.uid(); this._settings.id =id; dhx.ui.views[id] = this; this.data.attachEvent("onStoreLoad", dhx.bind(function(){ this.callEvent("onBindRequest",[]); }, this)); }, refresh:function(){ this.callEvent("onBindRequest",[]); } }, dhx.DataLoader, dhx.EventSystem, dhx.BaseBind, dhx.Settings); dhx.ValueBind={ $init:function(){ this.attachEvent("onChange", this._update_binds); }, _bind_update:function(target, rule, format){ var data = this.getValue()||""; if (format) data = format(data); if (target.setValue) target.setValue(data); else if (!target.filter){ var pod = {}; pod[rule] = data; if (target._check_data_feed(data)) target.setValues(pod); } else{ target.data.silent(function(){ this.filter(rule,data); }); } target.callEvent("onBindApply", [data,rule,this]); } }; dhx.RecordBind={ $init:function(){ this.attachEvent("onChange", this._update_binds); }, _bind_update:function(target, rule){ var data = this.getValues()||null; this._bind_update_common(target, rule, data); } }; dhx.CollectionBind={ $init:function(){ this._cursor = null; this.attachEvent("onSelectChange", function(data){ var sel = this.getSelected(); this.setCursor(sel?(sel.id||sel):null); }); this.attachEvent("onAfterCursorChange", this._update_binds); this.data.attachEvent("onStoreUpdated", dhx.bind(function(id, data, mode){ if (id && id == this.getCursor() && mode != "paint") this._update_binds(); },this)); this.data.attachEvent("onClearAll", dhx.bind(function(){ this._cursor = null; },this)); this.data.attachEvent("onIdChange", dhx.bind(function(oldid, newid){ if (this._cursor == oldid) this._cursor = newid; },this)); }, setCursor:function(id){ if (id == this._cursor || (id !== null && !this.item(id))) return; this.callEvent("onBeforeCursorChange", [this._cursor]); this._cursor = id; this.callEvent("onAfterCursorChange",[id]); }, getCursor:function(){ return this._cursor; }, _bind_update:function(target, rule){ var data = this.item(this.getCursor())|| this._settings.defaultData || null; this._bind_update_common(target, rule, data); } }; /*DHX:Depend core/legacy_bind.js*/ /*DHX:Depend core/dhx.js*/ /*DHX:Depend core/bind.js*/ /*jsl:ignore*/ if (!dhx.ui) dhx.ui = {}; if (!dhx.ui.views){ dhx.ui.views = {}; dhx.ui.get = function(id){ if (id._settings) return id; return dhx.ui.views[id]; }; } if (window.dhtmlx) dhtmlx.BaseBind = dhx.BaseBind; dhtmlXDataStore = function(config){ var obj = new dhx.DataCollection(config); var name = "_dp_init"; obj[name]=function(dp){ //map methods var varname = "_methods"; dp[varname]=["dummy","dummy","changeId","dummy"]; this.data._old_names = { "add":"inserted", "update":"updated", "delete":"deleted" }; this.data.attachEvent("onStoreUpdated",function(id,data,mode){ if (id && !dp._silent) dp.setUpdated(id,true,this._old_names[mode]); }); varname = "_getRowData"; //serialize item's data in URL dp[varname]=function(id,pref){ var ev=this.obj.data.item(id); var data = { id:id }; data[this.action_param] = this.obj.getUserData(id); if (ev) for (var a in ev){ data[a]=ev[a]; } return data; }; this.changeId = function(oldid, newid){ this.data.changeId(oldid, newid); dp._silent = true; this.data.callEvent("onStoreUpdated", [newid, this.item(newid), "update"]); dp._silent = false; }; varname = "_clearUpdateFlag"; dp[varname]=function(){}; this._userdata = {}; }; obj.dummy = function(){}; obj.setUserData=function(id,name,value){ this._userdata[id]=value; }; obj.getUserData=function(id,name){ return this._userdata[id]; }; obj.dataFeed=function(obj){ this.define("dataFeed", obj); }; dhx.extend(obj, dhx.BindSource); return obj; }; if (window.dhtmlXDataView) dhtmlXDataView.prototype._initBindSource=function(){ this.isVisible = function(){ if (!this.data.order.length && !this.data._filter_order && !this._settings.dataFeed) return false; return true; }; var settings = "_settings"; this._settings = this._settings || this[settings]; if (!this._settings.id) this._settings.id = dhx.uid(); this.unbind = dhx.BaseBind.unbind; this.unsync = dhx.BaseBind.unsync; dhx.ui.views[this._settings.id] = this; }; if (window.dhtmlXChart) dhtmlXChart.prototype._initBindSource=function(){ this.isVisible = function(){ if (!this.data.order.length && !this.data._filtered_state && !this._settings.dataFeed) return false; return true; }; var settings = "_settings"; this._settings = this._settings || this[settings]; if (!this._settings.id) this._settings.id = dhx.uid(); this.unbind = dhx.BaseBind.unbind; this.unsync = dhx.BaseBind.unsync; dhx.ui.views[this._settings.id] = this; }; dhx.BaseBind.unsync = function(target){ return dhx.BaseBind._unbind.call(this, target); } dhx.BaseBind.unbind = function(target){ return dhx.BaseBind._unbind.call(this, target); } dhx.BaseBind.legacyBind = function(){ return dhx.BaseBind.bind.apply(this, arguments); }; dhx.BaseBind.legacySync = function(source, rule){ if (this._initBindSource) this._initBindSource(); if (source._initBindSource) source._initBindSource(); this.attachEvent("onAfterEditStop", function(id){ this.save(id); return true; }); this.attachEvent("onDataRequest", function(start, count){ for (var i=start; i<start+count; i++) if (!source.data.order[i]){ source.loadNext(count, start); return false; } }); this.save = function(id){ if (!id) id = this.getCursor(); var sobj = this.item(id); var tobj = source.item(id); for (var key in sobj) if (key.indexOf("$")!==0) tobj[key] = sobj[key]; source.refresh(id); }; if (source && source.name == "DataCollection") return source.data.sync.apply(this.data, arguments); else return this.data.sync.apply(this.data, arguments); }; if (window.dhtmlXForm){ dhtmlXForm.prototype.bind = function(target){ dhx.BaseBind.bind.apply(this, arguments); target.getBindData(this._settings.id); }; dhtmlXForm.prototype.unbind = function(target){ dhx.BaseBind._unbind.call(this,target); }; dhtmlXForm.prototype._initBindSource = function(){ if (dhx.isUndefined(this._settings)){ this._settings = { id: dhx.uid(), dataFeed:this._server_feed }; dhx.ui.views[this._settings.id] = this; } }; dhtmlXForm.prototype._check_data_feed = function(data){ if (!this._settings.dataFeed || this._ignore_feed || !data) return true; var url = this._settings.dataFeed; if (typeof url == "function") return url.call(this, (data.id||data), data); url = url+(url.indexOf("?")==-1?"?":"&")+"action=get&id="+encodeURIComponent(data.id||data); this.load(url); return false; }; dhtmlXForm.prototype.setValues = dhtmlXForm.prototype.setFormData; dhtmlXForm.prototype.getValues = function(){ return this.getFormData(false, true); }; dhtmlXForm.prototype.dataFeed = function(value){ if (this._settings) this._settings.dataFeed = value; else this._server_feed = value; }; dhtmlXForm.prototype.refresh = dhtmlXForm.prototype.isVisible = function(value){ return true; }; } if (window.scheduler){ if (!window.Scheduler) window.Scheduler = {}; Scheduler.$syncFactory=function(scheduler){ scheduler.sync = function(source, rule){ if (this._initBindSource) this._initBindSource(); if (source._initBindSource) source._initBindSource(); var process = "_process_loading"; var insync = function(ignore){ scheduler.clearAll(); var order = source.data.order; var pull = source.data.pull; var evs = []; for (var i=0; i<order.length; i++){ if (rule && rule.copy) evs[i]=dhx.clone(pull[order[i]]); else evs[i]=pull[order[i]]; } scheduler[process](evs); scheduler.callEvent("onSyncApply",[]); }; this.save = function(id){ if (!id) id = this.getCursor(); var data = this.item(id); var olddat = source.item(id); if (this.callEvent("onStoreSave", [id, data, olddat])){ dhx.extend(source.item(id),data, true); source.update(id); } }; this.item = function(id){ return this.getEvent(id); }; this._sync_events=[ source.data.attachEvent("onStoreUpdated", function(id, data, mode){ insync.call(this); }), source.data.attachEvent("onIdChange", function(oldid, newid){ combo.changeOptionId(oldid, newid); }) ]; this.attachEvent("onEventChanged", function(id){ this.save(id); }); this.attachEvent("onEventAdded", function(id, data){ if (!source.data.pull[id]) source.add(data); }); this.attachEvent("onEventDeleted", function(id){ if (source.data.pull[id]) source.remove(id); }); insync(); }; scheduler.unsync = function(target){ dhx.BaseBind._unbind.call(this,target); } scheduler._initBindSource = function(){ if (!this._settings) this._settings = { id:dhx.uid() }; } } Scheduler.$syncFactory(window.scheduler); } if (window.dhtmlXCombo){ dhtmlXCombo.prototype.bind = function(){ dhx.BaseBind.bind.apply(this, arguments); }; dhtmlXCombo.prototype.unbind = function(target){ dhx.BaseBind._unbind.call(this,target); } dhtmlXCombo.prototype.unsync = function(target){ dhx.BaseBind._unbind.call(this,target); } dhtmlXCombo.prototype.dataFeed = function(value){ if (this._settings) this._settings.dataFeed = value; else this._server_feed = value; }; dhtmlXCombo.prototype.sync = function(source, rule){ if (this._initBindSource) this._initBindSource(); if (source._initBindSource) source._initBindSource(); var combo = this; var insync = function(ignore){ combo.clearAll(); combo.addOption(this.serialize()); combo.callEvent("onSyncApply",[]); }; //source.data.attachEvent("onStoreLoad", insync); this._sync_events=[ source.data.attachEvent("onStoreUpdated", function(id, data, mode){ insync.call(this); }), source.data.attachEvent("onIdChange", function(oldid, newid){ combo.changeOptionId(oldid, newid); }) ]; insync.call(source); }; dhtmlXCombo.prototype._initBindSource = function() { if (dhx.isUndefined(this._settings)){ this._settings = { id: dhx.uid(), dataFeed:this._server_feed }; dhx.ui.views[this._settings.id] = this; this.data = { silent:dhx.bind(function(code){ code.call(this); },this)}; dhx4._eventable(this.data); this.attachEvent("onChange", function() { this.callEvent("onSelectChange", [this.getSelectedValue()]); }); this.attachEvent("onXLE", function(){ this.callEvent("onBindRequest",[]); }); } }; dhtmlXCombo.prototype.item = function(id) { return this.getOption(id); }; dhtmlXCombo.prototype.getSelected = function() { return this.getSelectedValue(); }; dhtmlXCombo.prototype.isVisible = function() { if (!this.optionsArr.length && !this._settings.dataFeed) return false; return true; }; dhtmlXCombo.prototype.refresh = function() { this.render(true); }; } if (window.dhtmlXGridObject){ dhtmlXGridObject.prototype.bind = function(source, rule, format) { dhx.BaseBind.bind.apply(this, arguments); }; dhtmlXGridObject.prototype.unbind = function(target){ dhx.BaseBind._unbind.call(this,target); } dhtmlXGridObject.prototype.unsync = function(target){ dhx.BaseBind._unbind.call(this,target); } dhtmlXGridObject.prototype.dataFeed = function(value){ if (this._settings) this._settings.dataFeed = value; else this._server_feed = value; }; dhtmlXGridObject.prototype.sync = function(source, rule){ if (this._initBindSource) this._initBindSource(); if (source._initBindSource) source._initBindSource(); var grid = this; var parsing = "_parsing"; var parser = "_parser"; var locator = "_locator"; var parser_func = "_process_store_row"; var locator_func = "_get_store_data"; this.save = function(id){ if (!id) id = this.getCursor(); dhx.extend(source.item(id),this.item(id), true); source.update(id); }; var insync = function(ignore){ var cursor = grid.getCursor?grid.getCursor():null; var from = 0; if (grid._legacy_ignore_next){ from = grid._legacy_ignore_next; grid._legacy_ignore_next = false; } else { grid.clearAll(); } var count = this.dataCount(); if (count){ grid[parsing]=true; for (var i = from; i < count; i++){ var id = this.order[i]; if (!id) continue; if (from && grid.rowsBuffer[i]) continue; grid.rowsBuffer[i]={ idd: id, data: this.pull[id] }; grid.rowsBuffer[i][parser] = grid[parser_func]; grid.rowsBuffer[i][locator] = grid[locator_func]; grid.rowsAr[id]=this.pull[id]; } if (!grid.rowsBuffer[count-1]){ grid.rowsBuffer[count-1] = dhtmlx.undefined; grid.xmlFileUrl = grid.xmlFileUrl||this.url; } if (grid.pagingOn) grid.changePage(); else { if (grid._srnd && grid._fillers) grid._update_srnd_view(); else{ grid.render_dataset(); grid.callEvent("onXLE",[]); } } grid[parsing]=false; } if (cursor && grid.setCursor) grid.setCursor(grid.rowsAr[cursor]?cursor:null); grid.callEvent("onSyncApply",[]); }; //source.data.attachEvent("onStoreLoad", insync); this._sync_events=[ source.data.attachEvent("onStoreUpdated", function(id, data, mode){ if (mode == "delete"){ grid.deleteRow(id); grid.data.callEvent("onStoreUpdated",[id, data, mode]); } else if (mode == "update"){ grid.callEvent("onSyncUpdate", [data, mode]); grid.update(id, data); grid.data.callEvent("onStoreUpdated",[id, data, mode]); } else if (mode == "add"){ grid.callEvent("onSyncUpdate", [data, mode]); grid.add(id, data, this.indexById(id)); grid.data.callEvent("onStoreUpdated",[id,data,mode]); } else insync.call(this); }), source.data.attachEvent("onStoreLoad", function(driver, data){ grid.xmlFileUrl = source.data.url; grid._legacy_ignore_next = driver.getInfo(data)._from; }), source.data.attachEvent("onIdChange", function(oldid, newid){ grid.changeRowId(oldid, newid); }) ]; grid.attachEvent("onDynXLS", function(start, count){ for (var i=start; i<start+count; i++) if (!source.data.order[i]){ source.loadNext(count, start); return false; } grid._legacy_ignore_next = start; insync.call(source.data); }); insync.call(source.data); grid.attachEvent("onEditCell", function(stage, id, ind, value, oldvalue){ if (stage==2 && value != oldvalue) this.save(id); return true; }); grid.attachEvent("onClearAll",function(){ var name = "_f_rowsBuffer"; this[name]=null; }); if (rule && rule.sort) grid.attachEvent("onBeforeSorting", function(ind, type, dir){ if (type == "connector") return false; var id = this.getColumnId(ind); source.sort("#"+id+"#", (dir=="asc"?"asc":"desc"), (type=="int"?type:"string")); grid.setSortImgState(true, ind, dir); return false; }); if (rule && rule.filter){ grid.attachEvent("onFilterStart", function(cols, values){ var name = "_con_f_used"; if (grid[name] && grid[name].length) return false; source.data.silent(function(){ source.filter(); for (var i=0; i<cols.length; i++){ if (values[i] == "") continue; var id = grid.getColumnId(cols[i]); source.filter("#"+id+"#", values[i], i!=0); } }); source.refresh(); return false; }); grid.collectValues = function(index){ var id = this.getColumnId(index); return (function(id){ var values = []; var checks = {}; this.data.each(function(obj){ var value = obj[id]; if (!checks[value]){ checks[value] = true; values.push(value); } }); values.sort(); return values; }).call(source, id); }; } if (rule && rule.select) grid.attachEvent("onRowSelect", function(id){ source.setCursor(id); }); grid.clearAndLoad = function(url){ source.clearAll(); source.load(url); }; }; dhtmlXGridObject.prototype._initBindSource = function() { if (dhx.isUndefined(this._settings)){ this._settings = { id: dhx.uid(), dataFeed:this._server_feed }; dhx.ui.views[this._settings.id] = this; this.data = { silent:dhx.bind(function(code){ code.call(this); },this)}; dhx4._eventable(this.data); var name = "_cCount"; for (var i=0; i<this[name]; i++) if (!this.columnIds[i]) this.columnIds[i] = "cell"+i; this.attachEvent("onSelectStateChanged", function(id) { this.callEvent("onSelectChange", [id]); }); this.attachEvent("onSelectionCleared", function() { this.callEvent("onSelectChange", [null]); }); this.attachEvent("onEditCell", function(stage,rId) { if (stage === 2 && this.getCursor) { if (rId && rId == this.getCursor()) this._update_binds(); } return true; }); this.attachEvent("onXLE", function(){ this.callEvent("onBindRequest",[]); }); } }; dhtmlXGridObject.prototype.item = function(id) { if (id === null) return null; var source = this.getRowById(id); if (!source) return null; var name = "_attrs"; var data = dhx.copy(source[name]); data.id = id; var length = this.getColumnsNum(); for (var i = 0; i < length; i++) { data[this.columnIds[i]] = this.cells(id, i).getValue(); } return data; }; dhtmlXGridObject.prototype.update = function(id,data){ for (var i=0; i<this.columnIds.length; i++){ var key = this.columnIds[i]; if (!dhx.isUndefined(data[key])) this.cells(id, i).setValue(data[key]); } var name = "_attrs"; var attrs = this.getRowById(id)[name]; for (var key in data) attrs[key] = data[key]; this.callEvent("onBindUpdate",[data, null, id]); }; dhtmlXGridObject.prototype.add = function(id,data,index){ var ar_data = []; for (var i=0; i<this.columnIds.length; i++){ var key = this.columnIds[i]; ar_data[i] = dhx.isUndefined(data[key])?"":data[key]; } this.addRow(id, ar_data, index); var name = "_attrs"; this.getRowById(id)[name] = dhx.copy(data); }; dhtmlXGridObject.prototype.getSelected = function() { return this.getSelectedRowId(); }; dhtmlXGridObject.prototype.isVisible = function() { var name = "_f_rowsBuffer"; if (!this.rowsBuffer.length && !this[name] && !this._settings.dataFeed) return false; return true; }; dhtmlXGridObject.prototype.refresh = function() { this.render_dataset(); }; dhtmlXGridObject.prototype.filter = function(callback, master){ //if (!this.rowsBuffer.length && !this._f_rowsBuffer) return; if (this._settings.dataFeed){ var filter = {}; if (!callback && !master) return; if (typeof callback == "function"){ if (!master) return; callback(master, filter); } else if (dhx.isUndefined(callback)) filter = master; else filter[callback] = master; this.clearAll(); var url = this._settings.dataFeed; if (typeof url == "function") return url.call(this, master, filter); var urldata = []; for (var key in filter) urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key])); this.load(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&")); return false; } if (master === null) { return this.filterBy(0, function(){ return false; }); } this.filterBy(0, function(value, id){ return callback.call(this, id, master); }); }; } if (window.dhtmlXTreeObject){ dhtmlXTreeObject.prototype.bind = function() { dhx.BaseBind.bind.apply(this, arguments); }; dhtmlXTreeObject.prototype.unbind = function(target){ dhx.BaseBind._unbind.call(this,target); } dhtmlXTreeObject.prototype.dataFeed = function(value){ if (this._settings) this._settings.dataFeed = value; else this._server_feed = value; }; dhtmlXTreeObject.prototype._initBindSource = function() { if (dhx.isUndefined(this._settings)){ this._settings = { id: dhx.uid(), dataFeed:this._server_feed }; dhx.ui.views[this._settings.id] = this; this.data = { silent:dhx.bind(function(code){ code.call(this); },this)}; dhx4._eventable(this.data); this.attachEvent("onSelect", function(id) { this.callEvent("onSelectChange", [id]); }); this.attachEvent("onEdit", function(stage,rId) { if (stage === 2) { if (rId && rId == this.getCursor()) this._update_binds(); } return true; }); } }; dhtmlXTreeObject.prototype.item = function(id) { if (id === null) return null; return { id: id, text:this.getItemText(id)}; }; dhtmlXTreeObject.prototype.getSelected = function() { return this.getSelectedItemId(); }; dhtmlXTreeObject.prototype.isVisible = function() { return true; }; dhtmlXTreeObject.prototype.refresh = function() { //dummy placeholder }; dhtmlXTreeObject.prototype.filter = function(callback, master){ //dummy placeholder, because tree doesn't support filtering if (this._settings.dataFeed){ var filter = {}; if (!callback && !master) return; if (typeof callback == "function"){ if (!master) return; callback(master, filter); } else if (dhx.isUndefined(callback)) filter = master; else filter[callback] = master; this.deleteChildItems(0); var url = this._settings.dataFeed; if (typeof url == "function") return url.call(this, [(data.id||data), data]); var urldata = []; for (var key in filter) urldata.push("dhx_filter["+key+"]="+encodeURIComponent(filter[key])); this.loadXML(url+(url.indexOf("?")<0?"?":"&")+urldata.join("&")); return false; } }; dhtmlXTreeObject.prototype.update = function(id,data){ if (!dhx.isUndefined(data.text)) this.setItemText(id, data.text); }; } /*jsl:end*/ })();
vijaysebastian/bill
public/plugins/dhtmlxSuite_v50_std/sources/dhtmlxDataStore/codebase/datastore.js
JavaScript
gpl-3.0
94,389
import Component from './component'; export default class ElementsColorPicker extends elementorModules.ViewModule { /** * Initialize the Eye-Dropper module. * * @returns {void} */ onInit() { super.onInit(); $e.components.register( new Component() ); } }
pojome/elementor
modules/elements-color-picker/assets/js/editor/module.js
JavaScript
gpl-3.0
271
// ==UserScript== // @name Letterboxd Backdrop Remover // @namespace https://github.com/emg/userscripts // @description Removes backdrop image from film pages // @copyright 2014+, Ramón Guijarro (http://soyguijarro.com) // @homepageURL https://github.com/soyguijarro/userscripts // @supportURL https://github.com/soyguijarro/userscripts/issues // @updateURL https://raw.githubusercontent.com/soyguijarro/userscripts/master/Letterboxd_Backdrop_Remover.user.js // @icon https://raw.githubusercontent.com/soyguijarro/userscripts/master/img/letterboxd_icon.png // @license GPLv3; http://www.gnu.org/licenses/gpl.html // @version 1.3 // @include *://letterboxd.com/film/* // @include *://letterboxd.com/film/*/crew/* // @include *://letterboxd.com/film/*/studios/* // @include *://letterboxd.com/film/*/genres/* // @exclude *://letterboxd.com/film/*/views/* // @exclude *://letterboxd.com/film/*/lists/* // @exclude *://letterboxd.com/film/*/likes/* // @exclude *://letterboxd.com/film/*/fans/* // @exclude *://letterboxd.com/film/*/ratings/* // @exclude *://letterboxd.com/film/*/reviews/* // @grant none // ==/UserScript== var containerElt = document.getElementById("content"), backdropElt = document.getElementById("backdrop"), contentElt = backdropElt.getElementsByClassName("content-wrap")[0]; containerElt.replaceChild(contentElt, backdropElt); containerElt.classList.remove("has-backdrop");
rcalderong/userscripts
Letterboxd_Backdrop_Remover.user.js
JavaScript
gpl-3.0
1,478
/** * @license * Copyright 2012 Dan Vanderkam ([email protected]) * MIT-licensed (http://opensource.org/licenses/MIT) */ Dygraph.Plugins.Annotations = (function() { "use strict"; /** Current bits of jankiness: - Uses dygraph.layout_ to get the parsed annotations. - Uses dygraph.plotter_.area It would be nice if the plugin didn't require so much special support inside the core dygraphs classes, but annotations involve quite a bit of parsing and layout. TODO(danvk): cache DOM elements. */ var annotations = function() { this.annotations_ = []; }; annotations.prototype.toString = function() { return "Annotations Plugin"; }; annotations.prototype.activate = function(g) { return { clearChart: this.clearChart, didDrawChart: this.didDrawChart }; }; annotations.prototype.detachLabels = function() { for (var i = 0; i < this.annotations_.length; i++) { var a = this.annotations_[i]; if (a.parentNode) a.parentNode.removeChild(a); this.annotations_[i] = null; } this.annotations_ = []; }; annotations.prototype.clearChart = function(e) { this.detachLabels(); }; annotations.prototype.didDrawChart = function(e) { var g = e.dygraph; // Early out in the (common) case of zero annotations. var points = g.layout_.annotated_points; if (!points || points.length === 0) return; var containerDiv = e.canvas.parentNode; var annotationStyle = { "position": "absolute", "fontSize": g.getOption('axisLabelFontSize') + "px", "zIndex": 10, "overflow": "hidden" }; var bindEvt = function(eventName, classEventName, pt) { return function(annotation_event) { var a = pt.annotation; if (a.hasOwnProperty(eventName)) { a[eventName](a, pt, g, annotation_event); } else if (g.getOption(classEventName)) { g.getOption(classEventName)(a, pt, g, annotation_event ); } }; }; // Add the annotations one-by-one. var area = e.dygraph.plotter_.area; for (var i = 0; i < points.length; i++) { var p = points[i]; if (p.canvasx < area.x || p.canvasx > area.x + area.w || p.canvasy < area.y || p.canvasy > area.y + area.h) { continue; } var a = p.annotation; var tick_height = 6; if (a.hasOwnProperty("tickHeight")) { tick_height = a.tickHeight; } var div = document.createElement("div"); for (var name in annotationStyle) { if (annotationStyle.hasOwnProperty(name)) { div.style[name] = annotationStyle[name]; } } if (!a.hasOwnProperty('icon')) { div.className = "dygraphDefaultAnnotation"; } if (a.hasOwnProperty('cssClass')) { div.className += " " + a.cssClass; } var width = a.hasOwnProperty('width') ? a.width : 16; var height = a.hasOwnProperty('height') ? a.height : 16; if (a.hasOwnProperty('icon')) { var img = document.createElement("img"); img.src = a.icon; img.width = width; img.height = height; div.appendChild(img); } else if (p.annotation.hasOwnProperty('shortText')) { div.appendChild(document.createTextNode(p.annotation.shortText)); } div.style.left = (p.canvasx - width / 2) + "px"; if (a.attachAtBottom) { div.style.top = (area.h - height - tick_height) + "px"; } else { div.style.top = (p.canvasy - height - tick_height) + "px"; } div.style.width = width + "px"; div.style.height = height + "px"; div.title = p.annotation.text; div.style.color = g.colorsMap_[p.name]; div.style.borderColor = g.colorsMap_[p.name]; a.div = div; g.addEvent(div, 'click', bindEvt('clickHandler', 'annotationClickHandler', p, this)); g.addEvent(div, 'mouseover', bindEvt('mouseOverHandler', 'annotationMouseOverHandler', p, this)); g.addEvent(div, 'mouseout', bindEvt('mouseOutHandler', 'annotationMouseOutHandler', p, this)); g.addEvent(div, 'dblclick', bindEvt('dblClickHandler', 'annotationDblClickHandler', p, this)); containerDiv.appendChild(div); this.annotations_.push(div); var ctx = e.drawingContext; ctx.save(); ctx.strokeStyle = g.colorsMap_[p.name]; ctx.beginPath(); if (!a.attachAtBottom) { ctx.moveTo(p.canvasx, p.canvasy); ctx.lineTo(p.canvasx, p.canvasy - 2 - tick_height); } else { ctx.moveTo(p.canvasx, area.h); ctx.lineTo(p.canvasx, area.h - 2 - tick_height); } ctx.closePath(); ctx.stroke(); ctx.restore(); } }; annotations.prototype.destroy = function() { this.detachLabels(); }; return annotations; })();
CINF/DataPresentationWebsite
sym-files2/dygraph/plugins/annotations.js
JavaScript
gpl-3.0
4,587
'use strict'; var desks = require('./helpers/desks'); describe('desks management', function () { beforeEach(function() { desks.openDesksSettings(); }); it('lists macros under the Macro tab for new desks', function () { desks.newDeskBtn.click(); desks.showTab('macros'); expect(desks.listedMacros.count()).toBeGreaterThan(0); }); });
nistormihai/superdesk
client/spec/desks_management_spec.js
JavaScript
gpl-3.0
386
var searchData= [ ['booltobyte',['boolToByte',['../convert_8cpp.html#a86cb12eecbe381c8a16ab8334bb3d96f',1,'boolToByte(bool b):&#160;convert.cpp'],['../convert_8h.html#a86cb12eecbe381c8a16ab8334bb3d96f',1,'boolToByte(bool b):&#160;convert.cpp']]], ['bytetoint',['byteToInt',['../convert_8cpp.html#a5ceb93f16a36822ce84fe75152be3876',1,'byteToInt(uint8_t b1, uint8_t b2):&#160;convert.cpp'],['../convert_8h.html#a5ceb93f16a36822ce84fe75152be3876',1,'byteToInt(uint8_t b1, uint8_t b2):&#160;convert.cpp']]] ];
ttomasini/AWS
dist/Doxygen/html/search/functions_0.js
JavaScript
gpl-3.0
510
var searchData= [ ['file',['File',['../class_gra_vito_n_1_1_utils_1_1_file.html',1,'GraVitoN::Utils']]] ];
null--/graviton
doc/GraVitoN/html/search/classes_66.js
JavaScript
gpl-3.0
109
/** * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011 * (C) OpenEyes Foundation, 2011-2014 * This file is part of OpenEyes. * * OpenEyes is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenEyes 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenEyes. If not, see <http://www.gnu.org/licenses/>. */ /** * Represents a range of numerical values * * @class Range * @property {Float} min Minimum value * @property {Float} max Maximum value * @param {Float} _min * @param {Float} _max */ ED.Range = function(_min, _max) { // Properties this.min = _min; this.max = _max; } /** * Set min and max with one function call * * @param {Float} _min * @param {Float} _max */ ED.Range.prototype.setMinAndMax = function(_min, _max) { // Set properties this.min = _min; this.max = _max; } /** * Returns true if the parameter is less than the minimum of the range * * @param {Float} _num * @returns {Bool} True if the parameter is less than the minimum */ ED.Range.prototype.isBelow = function(_num) { if (_num < this.min) { return true; } else { return false; } } /** * Returns true if the parameter is more than the maximum of the range * * @param {Float} _num * @returns {Bool} True if the parameter is more than the maximum */ ED.Range.prototype.isAbove = function(_num) { if (_num > this.max) { return true; } else { return false; } } /** * Returns true if the parameter is inclusively within the range * * @param {Float} _num * @returns {Bool} True if the parameter is within the range */ ED.Range.prototype.includes = function(_num) { if (_num < this.min || _num > this.max) { return false; } else { return true; } } /** * Constrains a value to the limits of the range * * @param {Float} _num * @param {Float} _scaleLevel The drawing scale level. * @returns {Float} The constrained value */ ED.Range.prototype.constrain = function(_num, _scaleLevel) { _scaleLevel = _scaleLevel === undefined ? 1 : _scaleLevel var min = this.min * _scaleLevel; var max = this.max * _scaleLevel; if (_num < min) { return min; } else if (_num > max) { return max; } else { return _num; } } /** * Returns true if the parameter is within the 'clockface' range represented by the min and max values * * @param {Float} _angle Angle to test * @param {Bool} _isDegrees Flag indicating range is in degrees rather than radians * @returns {Bool} True if the parameter is within the range */ ED.Range.prototype.includesInAngularRange = function(_angle, _isDegrees) { // Arbitrary radius var r = 100; // Points representing vectos of angles within range var min = new ED.Point(0, 0); var max = new ED.Point(0, 0); var angle = new ED.Point(0, 0); // Set points using polar coordinates if (!_isDegrees) { min.setWithPolars(r, this.min); max.setWithPolars(r, this.max); angle.setWithPolars(r, _angle); } else { min.setWithPolars(r, this.min * Math.PI / 180); max.setWithPolars(r, this.max * Math.PI / 180); angle.setWithPolars(r, _angle * Math.PI / 180); } return (min.clockwiseAngleTo(angle) <= min.clockwiseAngleTo(max)); } /** * Constrains a value to the limits of the angular range * * @param {Float} _angle Angle to test * @param {Bool} _isDegrees Flag indicating range is in degrees rather than radians * @returns {Float} The constrained value */ ED.Range.prototype.constrainToAngularRange = function(_angle, _isDegrees) { // No point in constraining unless range is less than 360 degrees! if ((this.max - this.min) < (_isDegrees ? 360 : (2 * Math.PI))) { // Arbitrary radius var r = 100; // Points representing vectors of angles within range var min = new ED.Point(0, 0); var max = new ED.Point(0, 0); var angle = new ED.Point(0, 0); // Set points using polar coordinates if (!_isDegrees) { min.setWithPolars(r, this.min); max.setWithPolars(r, this.max); angle.setWithPolars(r, _angle); } else { min.setWithPolars(r, this.min * Math.PI / 180); max.setWithPolars(r, this.max * Math.PI / 180); angle.setWithPolars(r, _angle * Math.PI / 180); } // Return appropriate value depending on relationship to range if (min.clockwiseAngleTo(angle) <= min.clockwiseAngleTo(max)) { return _angle; } else { if (angle.clockwiseAngleTo(min) < max.clockwiseAngleTo(angle)) { return this.min; } else { return this.max; } } } else { return _angle; } }
openeyesarchive/eyedraw
src/ED/Drawing/Range.js
JavaScript
gpl-3.0
4,875
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2014 Mozilla Corporation Contributors: Jeff Bryner [email protected] Anthony Verez [email protected] Yash Mehrotra [email protected] */ //collections shared by client/server events = new Meteor.Collection("events"); alerts = new Meteor.Collection("alerts"); investigations = new Meteor.Collection("investigations"); incidents = new Meteor.Collection("incidents"); veris = new Meteor.Collection("veris"); kibanadashboards = new Meteor.Collection("kibanadashboards"); mozdefsettings = new Meteor.Collection("mozdefsettings"); healthfrontend = new Meteor.Collection("healthfrontend"); healthescluster = new Meteor.Collection("healthescluster"); healthesnodes = new Meteor.Collection("healthesnodes"); healtheshotthreads = new Meteor.Collection("healtheshotthreads"); attackers = new Meteor.Collection("attackers"); actions = new Meteor.Collection("actions"); userActivity = new Meteor.Collection("userActivity"); if (Meteor.isServer) { //Publishing setups Meteor.publish("mozdefsettings",function(){ return mozdefsettings.find(); }); Meteor.publish("alerts-summary", function (searchregex,timeperiod,recordlimit) { //tail the last 100 records by default //default parameters timeperiod = typeof timeperiod !== 'undefined' ? timeperiod: 'tail'; searchregex = typeof searchregex !== 'undefined' ? searchregex: ''; recordlimit = ['number'].indexOf(typeof(recordlimit)) ? 100:recordlimit; //sanity check the record limit if ( recordlimit >10000 || recordlimit < 1){ recordlimit = 100; } if ( timeperiod ==='tail' || timeperiod == 'none' ){ return alerts.find( {summary: {$regex:searchregex}}, {fields:{ _id:1, esmetadata:1, utctimestamp:1, utcepoch:1, summary:1, severity:1, category:1, acknowledged:1, acknowledgedby:1, url:1 }, sort: {utcepoch: -1}, limit:recordlimit} ); } else { //determine the utcepoch range beginningtime=moment().utc(); //expect timeperiod like '1 days' timevalue=Number(timeperiod.split(" ")[0]); timeunits=timeperiod.split(" ")[1]; beginningtime.subtract(timevalue,timeunits); return alerts.find( {summary: {$regex:searchregex}, utcepoch: {$gte: beginningtime.unix()}}, {fields:{ _id:1, esmetadata:1, utctimestamp:1, utcepoch:1, summary:1, severity:1, category:1, acknowledged:1 }, sort: {utcepoch: -1}, limit:recordlimit} ); } }); Meteor.publish("alerts-details",function(alertid,includeEvents){ //return alerts.find({'esmetadata.id': alertid}); //alert ids can be either mongo or elastic search IDs //look for both to publish to the collection. //default parameters includeEvents = typeof includeEvents !== 'undefined' ? includeEvents: true; if ( includeEvents ){ return alerts.find({ $or:[ {'esmetadata.id': alertid}, {'_id': alertid}, ] }); }else{ return alerts.find({ $or:[ {'esmetadata.id': alertid}, {'_id': alertid}, ] }, {fields:{events:0}, }); } }); Meteor.publish("alerts-count", function () { var self = this; var count = 0; var initializing = true; var recordID=Meteor.uuid(); //get a count by watching for only 1 new entry sorted in reverse date order. //use that hook to return a find().count rather than iterating the entire result set over and over var handle = alerts.find({}, {sort: {utcepoch: -1},limit:1}).observeChanges({ added: function (newDoc,oldDoc) { count=alerts.find().count(); if (!initializing) { self.changed("alerts-count", recordID,{count: count}); //console.log('added alerts count to' + count); } }, changed: function (newDoc,oldDoc) { count=alerts.find().count(); if (!initializing) { self.changed("alerts-count", recordID,{count: count}); //console.log('changed alerts count to' + count); } }, removed: function (newDoc,oldDoc) { count=alerts.find().count(); if (!initializing) { self.changed("alerts-count", recordID,{count: count}); //console.log('changed alerts count to' + count); } } }); initializing = false; self.added("alerts-count", recordID,{count: count}); //console.log('count is ready: ' + count); self.ready(); // Stop observing the cursor when client unsubs. // Stopping a subscription automatically takes // care of sending the client any removed messages. self.onStop(function () { //console.log('stopped publishing alerts count.') handle.stop(); }); }); //publish the last X event/alerts //using document index instead of date // Meteor.publish("attacker-details",function(attackerid){ // return attackers.find({'_id': attackerid}, // {fields: { // events:{$slice: 20, // $sort: { documentindex: -1 }}, // alerts:{$slice: -10} // }} // ); // }); Meteor.publish("attacker-details",function(attackerid){ return attackers.find({'_id': attackerid}, {fields: { events:{$slice: -20}, alerts:{$slice: -10} }, sort: { 'events.documentsource.utctimestamp': -1 }, reactive:false } ); }); Meteor.publish("attackers-summary", function () { //limit to the last 100 records by default //to ease the sync transfer to dc.js/crossfilter return attackers.find({}, {fields:{ events:0, alerts:0, }, sort: {lastseentimestamp: -1}, limit:100}); }); Meteor.publish("attackers-summary-landmass", function () { //limit to the last 100 records by default //to ease the sync transfer to dc.js/crossfilter var inModifier = { $in: ["broxss", "brotunnel", "brosqli"]}; return attackers.find({"events.documentsource.category": inModifier}, {sort: {lastseentimestamp: -1}, limit: 100}); }); Meteor.publish("investigations-summary", function () { return investigations.find({}, {fields: { _id:1, summary:1, phase:1, dateOpened:1, dateClosed:1, creator:1 }, sort: {dateOpened: -1}, limit:100}); }); Meteor.publish("investigation-details",function(investigationid){ return investigations.find({'_id': investigationid}); }); Meteor.publish("incidents-summary", function () { return incidents.find({}, {fields: { _id:1, summary:1, phase:1, dateOpened:1, dateClosed:1, creator:1 }, sort: {dateOpened: -1}, limit:100}); }); Meteor.publish("incident-details",function(incidentid){ return incidents.find({'_id': incidentid}); }); Meteor.publish("veris", function () { return veris.find({}, {limit:0}); }); Meteor.publish("healthfrontend", function () { return healthfrontend.find({}, {limit:0}); }); Meteor.publish("healthescluster", function () { return healthescluster.find({}, {limit:0}); }); Meteor.publish("healthesnodes", function () { return healthesnodes.find({}, {limit:0}); }); Meteor.publish("healtheshotthreads", function () { return healtheshotthreads.find({}, {limit:0}); }); Meteor.publish("kibanadashboards", function () { return kibanadashboards.find({},{sort:{name:1}, limit:30}); }); Meteor.publish("userActivity", function () { return userActivity.find({},{sort:{userID:1}, limit:100}); }); //access rules from clients //barebones to allow you to specify rules //currently incidents collection is the only one updated by clients //for speed of access //the only rule is that the incident creator is the only one who can delete an incident. incidents.allow({ insert: function (userId, doc) { // the user must be logged in return (userId); }, update: function (userId, doc, fields, modifier) { // the user must be logged in return (userId); }, remove: function (userId, doc) { // can only remove one's own indicents return doc.creator === Meteor.user().profile.email; }, fetch: ['creator'] }); attackers.allow({ update: function (userId, doc, fields, modifier) { // the user must be logged in return (userId); } }); alerts.allow({ update: function (userId, doc, fields, modifier) { // the user must be logged in return (userId); } }); investigations.allow({ insert: function (userId, doc) { // the user must be logged in return (userId); }, update: function (userId, doc, fields, modifier) { // the user must be logged in return (userId); }, remove: function (userId, doc) { // can only remove one's own items return doc.creator === Meteor.user().profile.email; }, fetch: ['creator'] }); userActivity.allow({ insert: function (userId, doc) { // the user must be logged in return (userId); }, remove: function (userId, doc) { // can only remove one's own items return doc.userId === Meteor.user().profile.email; }, }); }; if (Meteor.isClient) { //client side collections: alertsCount = new Meteor.Collection("alerts-count"); //client-side subscriptions Meteor.subscribe("mozdefsettings"); Meteor.subscribe("veris"); Meteor.subscribe("kibanadashboards"); Meteor.subscribe("userActivity"); };
ameihm0912/MozDef
meteor/app/lib/collections.js
JavaScript
mpl-2.0
12,418
var FileBrowserComponent = BaseComponent.extend({ update: function(){ var myself = this, $ph = $("#"+this.htmlObject), root = this.rootFolder.charAt(this.rootFolder.length - 1) == "/" ? this.rootFolder : this.rootFolder+"/", $content; if (!this.fileExtensions) this.fileExtensions = ""; $ph.addClass('fileBrowserComponent'); if(this.chartDefinition.height != undefined){ $ph.css('height',this.chartDefinition.height+'px'); } if(this.chartDefinition.width != undefined){ $ph.css('width',this.chartDefinition.width+'px'); } $ph.css('overflow','auto'); $ph.fileTree( { root: root, script: myself.buildTreeURL(), expandSpeed: 1, collapseSpeed: 1, multiFolder: true, htmlTreeModifier: function(content){ return myself.modifyTree(content); } }, function(){}); }, getValue: function() { }, buildTreeURL: function(){ return Endpoints.getListFiles() + "?fileExtensions=" + this.fileExtensions; }, buildGetURL: function(rel){ return Endpoints.getFile() + "?fileName=" + rel; }, modifyTree: function(content){ var myself = this; var $content = content; if(!$content.hasClass('directory')) $content.find('ul').addClass("treeview filetree"); $content.find('li:last').addClass("last"); $.each($content.find('li.directory'),function(){ //get rel from a var rel = $(this).find('a').attr('rel'); $("<div/>").addClass("hitarea expandable-hitarea").attr('rel',rel).prependTo($(this)); }); $.each($content.find('li.directory a'), function(){ $(this).addClass('folder'); }); $.each($content.find('li.file'), function(){ $("<div/>").addClass("file").prependTo($(this)); }); $.each($content.find('li.file a'), function(){ var rel = $(this).attr('rel'); //$(this).attr({target: '_blank', href : myself.buildGetURL(rel)}); $(this).click(function(){ window.location.href = myself.buildGetURL(rel); }); }); return $content; }, downloadDataURI :function(options) { if(!options) { return; } $.isPlainObject(options) || (options = {data: options}); if(!$.browser.webkit) { location.href = options.data; } options.filename || (options.filename = "download." + options.data.split(",")[0].split(";")[0].substring(5).split("/")[1]); $('<form method="post" action="'+options.url+'" style="display:none"><input type="hidden" name="filename" value="'+options.filename+'"/><input type="hidden" name="data" value="'+options.data+'"/></form>').submit().remove(); } });
jvelasques/cfr
cfr-core/resources/cdeComponents/FileBrowserComponent/FileBrowserComponent.js
JavaScript
mpl-2.0
2,715
// Usage: // - Start rtc_server.js first: // ./rtc_server --port 8000 // // - Then use a docker build of slimerjs to run the test: // IP_ADDR=$(hostname -I | awk '{print $1}') // docker run -it -v `pwd`/test:/test slimerjs-0.9.6 slimerjs /test/test_up.js http://${IP_ADDR}:8000/ var common = require('common'), system = require('system'), home = '/rtc.html', channel = Math.round(Math.random()*1000000), base_address = system.args[1], server_count = (system.args.length >= 3) ? parseInt(system.args[2]) : 3, up_timeout = (10 + (server_count*server_count)/4)*1000; pred_timeout = (1 + (server_count*server_count)/6)*1000; var pages = []; // Start checking the states common.wait_cluster_up(pages, server_count, up_timeout, function(status, nodes, elapsed) { if (status) { console.log('Cluster is up after ' + elapsed + 'ms'); //common.show_nodes(nodes); phantom.exit(0); } else { console.log('Cluster failed to come up after ' + elapsed + 'ms'); //common.show_nodes(nodes); phantom.exit(1); } }); // Start each page/cluster node var opts = {base_address: base_address, home: home, channel: channel}; pages.push(common.new_page(0, true, opts, function() { for (var idx = 1; idx < server_count; idx++) { pages.push(common.new_page(idx, false, opts)); } }));
moquist/raft.js
test/test_up.js
JavaScript
mpl-2.0
1,370
import React from 'react'; import { OverlayTrigger, Tooltip, NavItem, Glyphicon } from 'react-bootstrap'; // This authenticates to Auth0 by opening a new Window where Auth0 will do its // thing, then closing that window when login is complete. export default class Auth0LoginMenuItem extends React.PureComponent { static handleSelect() { const loginView = new URL('/login', window.location); window.open(loginView, '_blank'); } render() { const tooltip = ( <Tooltip id="auth0-signin"> Sign in with the LDAP account you use to push to version control, or with email if you do not have version control access. </Tooltip> ); return ( <OverlayTrigger placement="bottom" delay={600} overlay={tooltip}> <NavItem onSelect={Auth0LoginMenuItem.handleSelect}> <Glyphicon glyph="log-in" /> Sign In </NavItem> </OverlayTrigger> ); } }
lundjordan/services
src/shipit/frontend/src/components/auth/Auth0LoginMenuItem.js
JavaScript
mpl-2.0
925
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var page = WinJS.UI.Pages.define("/html/scenario9_imageProtocols.html", { ready: function (element, options) { document.getElementById("imageProtocolSelector").addEventListener("change", imageProtocolSelector, false); document.getElementById("openPicker").addEventListener("click", openPicker, false); document.getElementById("sendTileNotification").addEventListener("click", sendTileNotification, false); document.getElementById("imageProtocolSelector").selectedIndex = 0; } }); function imageProtocolSelector() { var protocol = document.getElementById("imageProtocolSelector").selectedIndex; if (protocol === 0) { document.getElementById("appdataURLDiv").style.display = "none"; document.getElementById("httpURLDiv").style.display = "none"; } else if (protocol === 1) { document.getElementById("appdataURLDiv").style.display = "block"; document.getElementById("httpURLDiv").style.display = "none"; } else if (protocol === 2) { document.getElementById("appdataURLDiv").style.display = "none"; document.getElementById("httpURLDiv").style.display = "block"; } } var imageRelativePath; function openPicker() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.fileTypeFilter.replaceAll([".jpg", ".jpeg", ".png", ".gif"]); picker.commitButtonText = "Copy"; picker.pickSingleFileAsync().then(function (file) { return file.copyAsync(Windows.Storage.ApplicationData.current.localFolder, file.name, Windows.Storage.NameCollisionOption.generateUniqueName); }).done(function (newFile) { var imageAbsolutePath = newFile.path; //change image to relative path imageRelativePath = imageAbsolutePath.substring(imageAbsolutePath.lastIndexOf("\\") + 1); document.getElementById("notificationXmlContent").innerText = ""; WinJS.log && WinJS.log("Image copied to application data local storage: " + newFile.path, "sample", "status"); }, function (e) { document.getElementById("notificationXmlContent").innerText = ""; WinJS.log && WinJS.log(e, "sample", "error"); }); } function sendTileNotification() { var protocol = document.getElementById("imageProtocolSelector").selectedIndex; var wide310x150TileContent; if (protocol === 0) { //using the ms-appx: protocol wide310x150TileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileWide310x150ImageAndText01(); wide310x150TileContent.textCaptionWrap.text = "The image is in the appx package"; wide310x150TileContent.image.src = "ms-appx:///images/redWide310x150.png"; } else if (protocol === 1) { //using the ms-appdata:/// protocol wide310x150TileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileWide310x150Image(); wide310x150TileContent.image.src = "ms-appdata:///local/" + imageRelativePath; // make sure you are providing a relative path! } else if (protocol === 2) { //using http:// protocol // Important - The Internet (Client) capability must be checked in the manifest in the Capabilities tab wide310x150TileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileWide310x150PeekImageCollection04(); wide310x150TileContent.textBodyWrap.text = "The baseUri is " + document.getElementById("baseUri").value; wide310x150TileContent.imageMain.src = document.getElementById("image" + 0).value; wide310x150TileContent.imageSmallColumn1Row1.src = document.getElementById("image" + 1).value; wide310x150TileContent.imageSmallColumn1Row2.src = document.getElementById("image" + 2).value; wide310x150TileContent.imageSmallColumn2Row1.src = document.getElementById("image" + 3).value; wide310x150TileContent.imageSmallColumn2Row2.src = document.getElementById("image" + 4).value; // set the baseUri try { wide310x150TileContent.baseUri = document.getElementById("baseUri").value; } catch (e) { document.getElementById("notificationXmlContent").innerText = ""; WinJS.log && WinJS.log(e.message, "sample", "error"); return; } } wide310x150TileContent.requireSquare150x150Content = false; Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().update(wide310x150TileContent.createNotification()); document.getElementById("notificationXmlContent").innerText = wide310x150TileContent.getContent(); WinJS.log && WinJS.log("Tile notification sent", "sample", "status"); } })();
SoftwareFactoryUPC/ProjectTemplates
Mobile/Windows Phone/Ejemplos Windows Phone 8.1/App tiles and badges sample/Shared/js/scenario9_imageProtocols.js
JavaScript
mpl-2.0
5,266
import React from 'react' import { expect } from 'chai' import { shallow } from 'enzyme' import { AccountApp } from '../../app/js/account/AccountApp' describe('AccountApp', () => { let props let wrapper before(() => { props = { children: {}, storageConnected: true, location: { pathname: '/not-account' } } wrapper = shallow(<AccountApp {...props} />) }) it('renders the NavBar', () => { expect(wrapper.find('Navbar').length).to.equal(1) }) it('renders the SecondaryNavBar', () => { expect(wrapper.find('SecondaryNavBar').length).to.equal(1) }) })
blockstack/blockstack-portal
test/account/AccountApp.test.js
JavaScript
mpl-2.0
621
import DS from 'ember-data'; import Ember from 'ember'; const { decamelize } = Ember.String; export default DS.RESTSerializer.extend({ primaryKey: 'name', keyForAttribute: function(attr) { return decamelize(attr); }, normalizeSecrets(payload) { if (payload.data.keys && Array.isArray(payload.data.keys)) { const secrets = payload.data.keys.map(secret => ({ name: secret })); return secrets; } Ember.assign(payload, payload.data); delete payload.data; return [payload]; }, normalizeResponse(store, primaryModelClass, payload, id, requestType) { const nullResponses = ['updateRecord', 'createRecord', 'deleteRecord']; const secrets = nullResponses.includes(requestType) ? { name: id } : this.normalizeSecrets(payload); const { modelName } = primaryModelClass; let transformedPayload = { [modelName]: secrets }; // just return the single object because ember is picky if (requestType === 'queryRecord') { transformedPayload = { [modelName]: secrets[0] }; } return this._super(store, primaryModelClass, transformedPayload, id, requestType); }, serialize(snapshot, requestType) { if (requestType === 'update') { const min_decryption_version = snapshot.attr('minDecryptionVersion'); const min_encryption_version = snapshot.attr('minEncryptionVersion'); const deletion_allowed = snapshot.attr('deletionAllowed'); return { min_decryption_version, min_encryption_version, deletion_allowed, }; } else { return this._super(...arguments); } }, });
Aloomaio/vault
ui/app/serializers/transit-key.js
JavaScript
mpl-2.0
1,606
/* YUI 3.10.0 (build a03ce0e) Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('uploader', function (Y, NAME) { /** * Provides UI for selecting multiple files and functionality for * uploading multiple files to the server with support for either * html5 or Flash transport mechanisms, automatic queue management, * upload progress monitoring, and error events. * @module uploader * @main uploader * @since 3.5.0 */ /** * `Y.Uploader` serves as an alias for either <a href="UploaderFlash.html">`Y.UploaderFlash`</a> * or <a href="UploaderHTML5.html">`Y.UploaderHTML5`</a>, depending on the feature set available * in a specific browser. If neither HTML5 nor Flash transport layers are available, `Y.Uploader.TYPE` * static property is set to `"none"`. * * @class Uploader */ /** * The static property reflecting the type of uploader that `Y.Uploader` * aliases. The possible values are: * <ul> * <li><strong>`"html5"`</strong>: Y.Uploader is an alias for <a href="UploaderHTML5.html">Y.UploaderHTML5</a></li> * <li><strong>`"flash"`</strong>: Y.Uploader is an alias for <a href="UploaderFlash.html">Y.UploaderFlash</a></li> * <li><strong>`"none"`</strong>: Neither Flash not HTML5 are available, and Y.Uploader does * not reference an actual implementation.</li> * </ul> * * @property TYPE * @type {String} * @static */ var Win = Y.config.win; if (Win && Win.File && Win.FormData && Win.XMLHttpRequest) { Y.Uploader = Y.UploaderHTML5; } else if (Y.SWFDetect.isFlashVersionAtLeast(10,0,45)) { Y.Uploader = Y.UploaderFlash; } else { Y.namespace("Uploader"); Y.Uploader.TYPE = "none"; } }, '3.10.0', {"requires": ["uploader-html5", "uploader-flash"]});
miing/mci_migo
identityprovider/static/yui/3.10.0/uploader/uploader.js
JavaScript
agpl-3.0
1,747
// A frame represents the flow of game time, and is updated up to 60 times per second. define(["data"], function (data) { var Option = function () { // The name of the option setting this.name = ""; // The value of the option setting this.value = false; }; return data.define("option", Option); });
topiacloud/topia-online
src/plugins/core/data/option.js
JavaScript
agpl-3.0
349
var status = 0; var request; function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (mode == 0 && status == 0) { cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0) { cm.warpParty(980030000, 4); cm.cancelCPQLobby(); cm.dispose(); } } }
ronancpl/MapleSolaxiaV2
scripts/npc/2042009.js
JavaScript
agpl-3.0
511
////////////////////////////////////////////////////////////////////////// // // // This is a generated file. You can view the original // // source in your browser if your browser supports source maps. // // Source maps are supported by all recent versions of Chrome, Safari, // // and Firefox, and by Internet Explorer 11. // // // ////////////////////////////////////////////////////////////////////////// (function () { /* Imports */ var Meteor = Package.meteor.Meteor; var global = Package.meteor.global; var meteorEnv = Package.meteor.meteorEnv; var _ = Package.underscore._; var Random = Package.random.Random; var check = Package.check.check; var Match = Package.check.Match; var Accounts = Package['accounts-base'].Accounts; var OAuth = Package['clinical:oauth'].OAuth; var WebApp = Package.webapp.WebApp; var Log = Package.logging.Log; var Tracker = Package.deps.Tracker; var Deps = Package.deps.Deps; var Session = Package.session.Session; var DDP = Package['ddp-client'].DDP; var Mongo = Package.mongo.Mongo; var Blaze = Package.ui.Blaze; var UI = Package.ui.UI; var Handlebars = Package.ui.Handlebars; var Spacebars = Package.spacebars.Spacebars; var Template = Package['templating-runtime'].Template; var $ = Package.jquery.$; var jQuery = Package.jquery.jQuery; var EJSON = Package.ejson.EJSON; var FastClick = Package.fastclick.FastClick; var LaunchScreen = Package['launch-screen'].LaunchScreen; var meteorInstall = Package.modules.meteorInstall; var meteorBabelHelpers = Package['babel-runtime'].meteorBabelHelpers; var Promise = Package.promise.Promise; var HTML = Package.htmljs.HTML; var Symbol = Package['ecmascript-runtime-client'].Symbol; var Map = Package['ecmascript-runtime-client'].Map; var Set = Package['ecmascript-runtime-client'].Set; var require = meteorInstall({"node_modules":{"meteor":{"clinical:accounts-oauth":{"oauth_common.js":function(require,exports,module){ ////////////////////////////////////////////////////////////////////////////////////////////////// // // // packages/clinical_accounts-oauth/oauth_common.js // // // ////////////////////////////////////////////////////////////////////////////////////////////////// // var get; module.link("lodash", { get: function (v) { get = v; } }, 0); Accounts.oauth = {}; var services = {}; // Helper for registering OAuth based accounts packages. // On the server, adds an index to the user collection. Accounts.oauth.registerService = function (name) { if (get(Meteor, 'settings.public.logging') === "debug") { console.log('C3 Registering OAuth service in active server memory: ', name); } if (_.has(services, name)) throw new Error("Duplicate service: " + name); services[name] = true; if (Meteor.server) { // Accounts.updateOrCreateUserFromExternalService does a lookup by this id, // so this should be a unique index. You might want to add indexes for other // fields returned by your service (eg services.github.login) but you can do // that in your app. Meteor.users._ensureIndex('services.' + name + '.id', { unique: 1, sparse: 1 }); } }; // Removes a previously registered service. // This will disable logging in with this service, and serviceNames() will not // contain it. // It's worth noting that already logged in users will remain logged in unless // you manually expire their sessions. Accounts.oauth.unregisterService = function (name) { if (!_.has(services, name)) throw new Error("Service not found: " + name); delete services[name]; }; Accounts.oauth.serviceNames = function () { return _.keys(services); }; ////////////////////////////////////////////////////////////////////////////////////////////////// },"oauth_client.js":function(require,exports,module){ ////////////////////////////////////////////////////////////////////////////////////////////////// // // // packages/clinical_accounts-oauth/oauth_client.js // // // ////////////////////////////////////////////////////////////////////////////////////////////////// // var get; module.link("lodash", { get: function (v) { get = v; } }, 0); // Documentation for Meteor.loginWithExternalService /** * @name loginWith<ExternalService> * @memberOf Meteor * @function * @summary Log the user in using an external service. * @locus Client * @param {Object} [options] * @param {String[]} options.requestPermissions A list of permissions to request from the user. * @param {Boolean} options.requestOfflineToken If true, asks the user for permission to act on their behalf when offline. This stores an additional offline token in the `services` field of the user document. Currently only supported with Google. * @param {Object} options.loginUrlParameters Provide additional parameters to the authentication URI. Currently only supported with Google. See [Google Identity Platform documentation](https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters). * @param {String} options.loginHint An email address that the external service will use to pre-fill the login prompt. Currently only supported with Meteor developer accounts and Google accounts. If used with Google, the Google User ID can also be passed. * @param {String} options.loginStyle Login style ("popup" or "redirect", defaults to the login service configuration). The "popup" style opens the login page in a separate popup window, which is generally preferred because the Meteor application doesn't need to be reloaded. The "redirect" style redirects the Meteor application's window to the login page, and the login service provider redirects back to the Meteor application which is then reloaded. The "redirect" style can be used in situations where a popup window can't be opened, such as in a mobile UIWebView. The "redirect" style however relies on session storage which isn't available in Safari private mode, so the "popup" style will be forced if session storage can't be used. * @param {String} options.redirectUrl If using "redirect" login style, the user will be returned to this URL after authorisation has been completed. * @param {Function} [callback] Optional callback. Called with no arguments on success, or with a single `Error` argument on failure. The callback cannot be called if you are using the "redirect" `loginStyle`, because the app will have reloaded in the meantime; try using [client-side login hooks](#accounts_onlogin) instead. * @importFromPackage meteor */ // Allow server to specify a specify subclass of errors. We should come // up with a more generic way to do this! var convertError = function (err) { if (err && err instanceof Meteor.Error && err.error === Accounts.LoginCancelledError.numericError) return new Accounts.LoginCancelledError(err.reason);else return err; }; // For the redirect login flow, the final step is that we're // redirected back to the application. The credentialToken for this // login attempt is stored in the reload migration data, and the // credentialSecret for a successful login is stored in session // storage. Meteor.startup(function () { var oauth = OAuth.getDataAfterRedirect(); if (!oauth) return; // We'll only have the credentialSecret if the login completed // successfully. However we still call the login method anyway to // retrieve the error if the login was unsuccessful. var methodName = 'login'; var methodArguments = [{ oauth: _.pick(oauth, 'credentialToken', 'credentialSecret') }]; if (get(Meteor, 'settings.public.logging') === "debug") { console.log('Meteor.startup()'); } var newLoginMethod = { methodArguments: methodArguments, userCallback: function (err) { // The redirect login flow is complete. Construct an // `attemptInfo` object with the login result, and report back // to the code which initiated the login attempt // (e.g. accounts-ui, when that package is being used). err = convertError(err); Accounts._pageLoadLogin({ type: oauth.loginService, allowed: !err, error: err, methodName: methodName, methodArguments: methodArguments }); } }; if (get(Meteor, 'settings.public.logging') === "debug") { console.log('Meteor.startup().newLoginMethod', newLoginMethod); } Accounts.callLoginMethod(newLoginMethod); }); // Send an OAuth login method to the server. If the user authorized // access in the popup this should log the user in, otherwise // nothing should happen. Accounts.oauth.tryLoginAfterPopupClosed = function (credentialToken, callback) { if (get(Meteor, 'settings.public.logging') === "debug") { console.log('C9. Trying login now that the popup is closed.', credentialToken); } var credentialSecret = OAuth._retrieveCredentialSecret(credentialToken) || null; Accounts.callLoginMethod({ methodArguments: [{ oauth: { credentialToken: credentialToken, credentialSecret: credentialSecret } }], userCallback: callback && function (err) { callback(convertError(err)); } }); }; Accounts.oauth.credentialRequestCompleteHandler = function (callback) { if (get(Meteor, 'settings.public.logging') === "debug") { console.log('C4. Attempting to handle credetial request completion.'); } return function (credentialTokenOrError) { if (credentialTokenOrError && credentialTokenOrError instanceof Error) { callback && callback(credentialTokenOrError); } else { Accounts.oauth.tryLoginAfterPopupClosed(credentialTokenOrError, callback); } }; }; ////////////////////////////////////////////////////////////////////////////////////////////////// }}}}},{ "extensions": [ ".js", ".json" ] }); require("/node_modules/meteor/clinical:accounts-oauth/oauth_common.js"); require("/node_modules/meteor/clinical:accounts-oauth/oauth_client.js"); /* Exports */ Package._define("clinical:accounts-oauth"); })();
clinical-meteor/meteor-on-fhir
cordova-build-release/www/application/packages/clinical_accounts-oauth.js
JavaScript
agpl-3.0
10,784
/*File: tagsService.js * * Copyright (c) 2013-2016 * Centre National d’Enseignement à Distance (Cned), Boulevard Nicephore Niepce, 86360 CHASSENEUIL-DU-POITOU, France * ([email protected]) * * GNU Affero General Public License (AGPL) version 3.0 or later version * * This file is part of a program which 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, either version 3 of the License, or * (at your option) any later version. * * This program 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/>. * */ 'use strict'; angular.module('cnedApp').service('tagsService', function ($http, $uibModal, CacheProvider, configuration) { this.getTags = function () { return $http.get(configuration.BASE_URL + '/readTags').then(function (result) { return CacheProvider.setItem(result.data, 'listTags').then(function () { return result.data; }); }, function () { return CacheProvider.getItem('listTags'); }); }; this.openEditModal = function (mode, tag) { return $uibModal.open({ templateUrl: 'views/tag/edit-tag.modal.html', controller: 'EditTagModalCtrl', size: 'lg', resolve: { mode: function () { return mode; }, tag: function () { return tag; } } }).result; }; });
cnedDI/AccessiDys
app/scripts/services/tagsService.js
JavaScript
agpl-3.0
1,918
describe('Markdown plugin', function() { const Vue = require('vue'); Vue.use(require('plugins/markdown')); Vue.config.async = false; afterEach(function() { fixture.cleanup(); }); /** * Remove invisible nodes generated by Vue.js */ function strip(el) { [...el.childNodes].forEach(function(node) { const is_comment = node.nodeType === Node.COMMENT_NODE; const is_empty_text = node.nodeType === Node.TEXT_NODE && !/\S/.test(node.nodeValue); if (is_comment || is_empty_text) { node.parentNode.removeChild(node); } }); return el; } describe('markdown filter', function() { function el(text) { const vm = new Vue({ el: fixture.set('<div>{{{text | markdown}}}</div>')[0], replace: false, data: { text: text } }); return strip(vm.$el); } it('should render empty string as ""', function() { expect(el('').childNodes).to.be.emtpy; }); it('should render null value as ""', function() { expect(el(null).childNodes).to.be.empty; }); it('should render undefined value as ""', function() { expect(el(undefined).childNodes).to.be.empty; }); it('should markdown content', function() { expect(el('**aaa**')).to.have.html('<p><strong>aaa</strong></p>'); }); }); describe('markdown directive', function() { function el(text) { const vm = new Vue({ el: fixture.set('<div v-markdown="text"></div>')[0], data: { 'text': text } }); return strip(vm.$el); } it('should render empty string as ""', function() { expect(el('').childNodes).to.be.emtpy; }); it('should render null value as ""', function() { expect(el(null).childNodes).to.be.empty; }); it('should render undefined value as ""', function() { expect(el(undefined).childNodes).to.be.empty; }); it('should markdown content', function() { expect(el('**aaa**')).to.have.html('<p><strong>aaa</strong></p>'); }); }); }); describe('Markdown backend compliance', function() { const markdown = require('helpers/markdown').default; /** * An expect wrapper rendering the markdown * and then allowing to perform chai-dom expectation on it */ function md(source) { const div = document.createElement('div'); div.innerHTML = markdown(source); return div; } it('should transform urls to anchors', function() { const source = 'http://example.net/'; expect(md(source)).to.have.html('<p><a href="http://example.net/">http://example.net/</a></p>'); }); it('should handles autolink', function() { const source = '<http://example.net/>'; expect(md(source)).to.have.html('<p><a href="http://example.net/">http://example.net/</a></p>'); }); it('should not transform emails to anchors', function() { const source = '[email protected]'; expect(md(source)).to.have.html('<p>[email protected]</p>'); }); it('should not transform links within pre', function() { const source = '<pre>http://example.net/</pre>'; expect(md(source)).to.have.html('<pre>http://example.net/</pre>'); }); it('should sanitize evil code', function() { const source = 'an <script>evil()</script>'; expect(md(source)).to.have.html('<p>an &lt;script&gt;evil()&lt;/script&gt;</p>'); }); it('should handle soft breaks as <br/>', function() { const source = 'line 1\nline 2'; expect(md(source)).to.have.html('<p>line 1<br>\nline 2</p>'); }); it('should properly render markdown tags not in allowed tags', function() { const source = '### titre'; expect(md(source)).to.have.html('<h3>titre</h3>'); }); it('should render GFM tables (extension)', function() { const source = [ '| first | second |', '|-------|--------|', '| value | value |', ].join('\n'); const expected = [ '<table>', '<thead>', '<tr>', '<th>first</th>', '<th>second</th>', '</tr>', '</thead>', '<tbody>', '<tr>', '<td>value</td>', '<td>value</td>', '</tr>', '</tbody>', '</table>' ].join('\n'); expect(md(source)).to.have.html(expected); }); it('should render GFM strikethrough (extension)', function() { const source = 'Yay ~~Hi~~ Hello, world!'; const expected = '<p>Yay <del>Hi</del> Hello, world!</p>'; expect(md(source)).to.have.html(expected); }); it('should handle GFM tagfilter extension', function() { // Test extracted from https://github.github.com/gfm/#disallowed-raw-html-extension- const source = [ '<strong> <title>My Title</title></strong>', '<blockquote>', ' <xmp> is disallowed.</xmp> <XMP> is also disallowed.</XMP>', '</blockquote>', ].join('\n') const expected = [ '<p><strong> &lt;title&gt;My Title&lt;/title&gt;</strong></p>', '<blockquote>', ' &lt;xmp&gt; is disallowed.&lt;/xmp&gt; &lt;XMP&gt; is also disallowed.&lt;/XMP&gt;', '</blockquote>', ].join('\n') expect(md(source)).to.have.html(expected) }); it('should not filter legit markup', function() { const source = [ '> This is a blockquote', '> with <script>evil()</script> inside', ].join('\n'); const expected = [ '<blockquote>', '<p>This is a blockquote<br>', 'with &lt;script&gt;evil()&lt;/script&gt; inside</p>', '</blockquote>', ].join('\n'); expect(md(source)).to.have.html(expected); }); });
opendatateam/udata
specs/plugins/markdown.specs.js
JavaScript
agpl-3.0
6,254
/*! * CanJS - 2.2.9 * http://canjs.com/ * Copyright (c) 2015 Bitovi * Fri, 11 Sep 2015 23:12:43 GMT * Licensed MIT */ /*[email protected]#util/hashchange*/ define(['can/util/can'], function (can) { (function () { var addEvent = function (el, ev, fn) { if (el.addEventListener) { el.addEventListener(ev, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + ev, fn); } else { el['on' + ev] = fn; } }, onHashchange = function () { can.trigger(window, 'hashchange'); }; addEvent(window, 'hashchange', onHashchange); }()); });
et304383/passbolt_api
app/webroot/js/lib/can/dist/amd/can/hashchange.js
JavaScript
agpl-3.0
719
define([ 'collections/catalog_collection', 'test/mock_data/catalogs' ], function(CatalogCollection, MockCatalogs) { 'use strict'; var collection, response = MockCatalogs; beforeEach(function() { collection = new CatalogCollection(); }); describe('Catalog collection', function() { describe('parse', function() { it('should fetch the next page of results', function() { spyOn(collection, 'fetch').and.returnValue(null); response.next = '/api/v2/catalogs/course_catalogs/?page=2'; collection.parse(response); expect(collection.fetch).toHaveBeenCalledWith( {remove: false, url: '/api/v2/catalogs/course_catalogs/?page=2'} ); }); }); }); } );
eduNEXT/edunext-ecommerce
ecommerce/static/js/test/specs/collections/catalog_collection_spec.js
JavaScript
agpl-3.0
924
(function (plugin, core, scene) { var plug = new plugin.GlobalRendering({ name: "Axes", tooltip: "Show world space axes", icon: "img/icons/axis.png", toggle: true, on: false }); var DEFAULTS = { planeSize: 10, gridSpacing: 10, gridColor: new THREE.Color(0x000066), ticksSpacing: 3 }; // Label parameters var lblParameters = { fontSize: 24, borderColor : {r:0, g:0, b:0, a:0}, bgColor : {r:255, g:255, b:255, a:0} }; var planeWidget, planeOrientationWidget, gridColorWidget, planeSizeWidget, gridSpacingWidget, ticksSpacingWidget; plug._init = function (guiBuilder) { planeWidget = guiBuilder.Choice({ label: "Grid Plane", tooltip: "If on, a grid plane will be drawn", options: [ {content: "Off", value: "0", selected: true}, {content: "On", value: "1"} ], bindTo: (function() { var bindToFun = function() { plug._onAxesParamChange(); }; bindToFun.toString = function() { return 'planeWidget'; } return bindToFun; }()) }); planeOrientationWidget = guiBuilder.Choice({ label: "Grid Plane Orientation", tooltip: "Choose which plane to draw", options: [ {content: "XZ", value: "0", selected: true}, {content: "XY", value: "1"}, {content: "YZ", value: "2"}, ], bindTo: (function() { var bindToFun = function() { if(parseInt(planeWidget.getValue())) plug._onAxesParamChange(); }; bindToFun.toString = function() { return 'planeOrientationWidget'; } return bindToFun; }()) }); gridColorWidget = guiBuilder.Color({ label: "Grid Color", tooltip: "", color: "#" + DEFAULTS.gridColor.getHexString(), bindTo: (function() { var bindToFun = function() { if(parseInt(planeWidget.getValue())) plug._onAxesParamChange(); }; bindToFun.toString = function() { return 'gridColorWidget'; } return bindToFun; }()) }); planeSizeWidget = guiBuilder.Integer({ label: "Plane Size", tooltip: "Defines the size of the plane", step: 1, defval: DEFAULTS.planeSize, min: 0, bindTo: (function() { var bindToFun = function() { if(planeSizeWidget.getValue() > 0 && parseInt(planeWidget.getValue())) plug._onAxesParamChange(); }; bindToFun.toString = function() { return "planeSizeWidget"; }; return bindToFun; })() }); gridSpacingWidget = guiBuilder.Integer({ label: "Grid Spacing", tooltip: "Defines the spacing of the grid", step: 1, defval: DEFAULTS.planeSize, min: 0, bindTo: (function() { var bindToFun = function() { if(gridSpacingWidget.getValue() > 0 && parseInt(planeWidget.getValue())) plug._onAxesParamChange(); }; bindToFun.toString = function() { return "gridSpacingWidget"; }; return bindToFun; })() }); ticksSpacingWidget = guiBuilder.Float({ label: "Ticks Spacing", tooltip: "Defines the spacing between the ticks", step: 0.5, defval: DEFAULTS.ticksSpacing, min: 0, bindTo: (function() { var bindToFun = function() { if(ticksSpacingWidget.getValue() > 0) plug._onAxesParamChange(); }; bindToFun.toString = function() { return "ticksSpacingWidget"; }; return bindToFun; })() }); }; plug._onAxesParamChange = function() { // var currentLayer = MLJ.core.Scene.getSelectedLayer(); // if (currentLayer.properties.getByKey(plug.getName()) === true) { if(scene._axes) { this._applyTo(false); this._applyTo(true); } }; plug._applyTo = function (on) { if (on) { scene._axes = true; var bbox = scene.getBBox(); var axisLength = bbox.min.distanceTo(bbox.max)/2; // Creating the Object3D of the axes. The other parts (arrows, labels, ticks) will be added to this object var axes = new THREE.AxisHelper(axisLength); // Parameters needed to define the size of the arrows on the axes var arrowLength = 1; var headLength = 0.2 * arrowLength; var headWidth = 0.5 * headLength; // Array that will contain the colors of each axis var colors = []; // X arrow parameters var arrowDirectionX = new THREE.Vector3(1, 0, 0); var arrowOriginAxisX = new THREE.Vector3(axisLength, 0, 0); colors.push(0xff9900); // Y arrow parameters var arrowDirectionY = new THREE.Vector3(0, 1, 0); var arrowOriginAxisY = new THREE.Vector3(0, axisLength, 0); colors.push(0x99ff00); // Z arrow parameters var arrowDirectionZ = new THREE.Vector3(0, 0, 1); var arrowOriginAxisZ = new THREE.Vector3(0, 0, axisLength); colors.push(0x0099ff); var arrowAxisX = new THREE.ArrowHelper(arrowDirectionX, arrowOriginAxisX, arrowLength, colors[0], headLength, headWidth); var arrowAxisY = new THREE.ArrowHelper(arrowDirectionY, arrowOriginAxisY, arrowLength, colors[1], headLength, headWidth); var arrowAxisZ = new THREE.ArrowHelper(arrowDirectionZ, arrowOriginAxisZ, arrowLength, colors[2], headLength, headWidth); axes.add(arrowAxisX); axes.add(arrowAxisY); axes.add(arrowAxisZ); // Now we draw the labels as sprite; first, we compute the distance var labelDistanceFromOrigin = axisLength + arrowLength + 0.1; // Creating the sprite with the helper function var spriteX = makeTextSprite("X", { 'x' : labelDistanceFromOrigin, 'y' : 0, 'z': 0}, lblParameters); var spriteY = makeTextSprite("Y", { 'x' : 0, 'y' : labelDistanceFromOrigin, 'z': 0}, lblParameters); var spriteZ = makeTextSprite("Z", { 'x' : 0, 'y' : 0, 'z': labelDistanceFromOrigin}, lblParameters); axes.add(spriteX); axes.add(spriteY); axes.add(spriteZ); // Now we draw the white ticks on the axes var origin = new THREE.Vector3(0, 0, 0); // Computing the distance between the ticks for each axis. Ticks will be displayed between the origin of the axis and the origin of the arrow var tickDistanceX = ticksSpacingWidget.getValue(); var tickDistanceY = ticksSpacingWidget.getValue(); var tickDistanceZ = ticksSpacingWidget.getValue(); // Total length to consider when drawing the ticks var totalLength = axisLength + headLength; // Creating the ticks mesh only if the distance is below the total length (meaning that there is at least 1 tick) if(tickDistanceX < totalLength) { var ticksMeshX = createTicksMesh(origin, arrowOriginAxisX, totalLength, tickDistanceX); axes.add(ticksMeshX); } if(tickDistanceY < totalLength) { var ticksMeshY = createTicksMesh(origin, arrowOriginAxisY, totalLength, tickDistanceY); axes.add(ticksMeshY); } if(tickDistanceZ < totalLength) { var ticksMeshZ = createTicksMesh(origin, arrowOriginAxisZ, totalLength, tickDistanceZ); axes.add(ticksMeshZ); } // If the grid is enabled, it needs to be created if(parseInt(planeWidget.getValue())) { // Grid size and spacing var gridSize = planeSizeWidget.getValue(); var gridSpacing = gridSpacingWidget.getValue(); var planeOrientation = parseInt(planeOrientationWidget.getValue()); var grid = createGrid(gridSize, gridSpacing, planeOrientation, colors); axes.add(grid); } scene.addSceneDecorator(plug.getName(), axes); } else { scene.removeSceneDecorator(plug.getName()); scene._axes = false; } }; /** * Creates a grid rotated according to the plane orientation * * @param {integer} gridSize size of the grid * @param {integer} gridSpacing spacing in the grid * @param {integer} plane the orientation of the plane (0 == XZ, 1 == XY, 2 == YZ) * @param {THREE.Color} colors * @returns {THREE.GridHelper} */ function createGrid(gridSize, gridSpacing, plane, colors) { // Gird mesh and color var grid = new THREE.GridHelper(gridSize, gridSize/gridSpacing); grid.setColors(gridColorWidget.getColor(), gridColorWidget.getColor()); // Coordinate vectors and colors for the line to be drawn across the plane axes var negativeVec1 = new THREE.Vector3(-gridSize, 0, 0); var positiveVec1 = new THREE.Vector3(gridSize, 0, 0); var negativeVec2 = new THREE.Vector3(0, 0, -gridSize); var positiveVec2 = new THREE.Vector3(0, 0, gridSize); var color1 = colors[0]; var color2 = colors[2]; // Depending on the plane orientation, the grid needs to be rotated around an axis switch(plane) { case 1: color2 = colors[1]; grid.rotation.x = Math.PI/2; break; case 2: color1 = colors[1]; color2 = colors[2]; grid.rotation.z = Math.PI/2; break; } // Creating the line along the first axis of the plane (for example if the plane is XY it will be the line // across the X axis; if it's the YZ plane it will be the line across Y) var geometry1 = new THREE.Geometry(); var material1 = new THREE.LineBasicMaterial({color: color1}); geometry1.vertices.push(negativeVec1, positiveVec1); var line1 = new THREE.Line(geometry1, material1); grid.add(line1); // Second line along the second axis var geometry2 = new THREE.Geometry(); var material2 = new THREE.LineBasicMaterial({color: color2}); geometry2.vertices.push(negativeVec2, positiveVec2); var line2 = new THREE.Line(geometry2, material2); grid.add(line2) return grid; } /** * Function that creates "ticks" from one point to another under a given dimension and with a fixed distance between the points * * @param {type} startPoint starting point * @param {type} endPoint ending point * @param {type} dim total size to consider * @param {type} tickDistance distance between a tick and the next one * @returns {THREE.Object3D|THREE.PointCloud} */ function createTicksMesh(startPoint, endPoint, dim, tickDistance) { // Considering the difference between the starting and ending point var v = new THREE.Vector3(); v.subVectors(endPoint, startPoint); // Normalizing without computing square roots and powers v.divideScalar(dim); var ticksMesh = new THREE.Object3D(); var ticksGeometry = new THREE.Geometry(); var i; // Creating the points. Each point is separated by "tickDistance" pixels. Since the for(i = tickDistance; i < dim; i += tickDistance) ticksGeometry.vertices.push(new THREE.Vector3(startPoint.x + i*v.x, startPoint.y + i*v.y, startPoint.z + i*v.z)); var ticksMaterial = new THREE.PointCloudMaterial({ size: 3, sizeAttenuation: false }); // Creating the ticks as a cloud of points ticksMesh = new THREE.PointCloud(ticksGeometry, ticksMaterial); return ticksMesh; } /** * Make a text texture <code>message</code> with HTML approach * @param {String} message Message to be applied to texture * @param {Vector3} position The position of the texture sprite * @param {Object} parameters The sprite's parameters * @memberOf MLJ.plugins.rendering.Box * @author Stefano Giammori */ function makeTextSprite(message, position, parameters) { if ( parameters === undefined ) parameters = {}; //extract label params var fontface = parameters.hasOwnProperty("fontFace") ? parameters["fontFace"] : "Arial"; var fontsize = parameters.hasOwnProperty("fontSize") ? parameters["fontSize"] : 10; var fontweight = parameters.hasOwnProperty("fontWeight") ? parameters["fontWeight"] : "normal" //white, visible var borderThickness = parameters.hasOwnProperty("borderThickness") ? parameters["borderThickness"] : 4; var borderColor = parameters.hasOwnProperty("borderColor") ? parameters["borderColor"] : { r:0, g:0, b:0, a:1.0 }; //black, visible var backgroundColor = parameters.hasOwnProperty("bgColor") ? parameters["bgColor"] : {r:255, g:255, b:255, a:1.0} //white, visible //prepare label var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); context.font = fontweight + " " + fontsize + "px " + fontface; // get size data (height depends only on font size) var textWidth = context.measureText(message).width; canvas.width = textWidth + borderThickness * 2; canvas.height = fontsize + borderThickness * 2; //set the param font into context context.font = fontweight + " " + fontsize + "px " + fontface; //set context background color context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," + backgroundColor.a + ")"; //set context border color context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor.a + ")"; //set border thickness context.lineWidth = borderThickness; /** //MEMO : (add +x) ~~ go right; (add +y) ~~ go down) ] Set the rectangular frame (ctx, top-left, top, width, height, radius of the 4 corners) */ context.fillStyle = "rgba(255, 255, 255, 1.0)"; /** Set starting point of text, in which pt(borderThickness, fontsize+borderThickness/2) represent the top left of the top-left corner of the texture text in the canvas. */ context.fillText(message, borderThickness, fontsize + borderThickness/2); //canvas contents will be used for create a texture var texture = new THREE.Texture(canvas) texture.needsUpdate = true; texture.minFilter = THREE.LinearFilter; var spriteMaterial = new THREE.SpriteMaterial({ map: texture, useScreenCoordinates: false, color: 0xffffff, fog: true } ); var sprite = new THREE.Sprite(spriteMaterial); sprite.scale.set( textWidth/100, fontsize/100, 1 ); sprite.position.set( position.x , position.y, position.z); return sprite; } plugin.Manager.install(plug); })(MLJ.core.plugin, MLJ.core, MLJ.core.Scene);
cignoni/meshlabjs
js/mlj/plugins/rendering/Axes.js
JavaScript
agpl-3.0
16,533
import Ember from 'ember'; export default Ember.Controller.extend({ canCreateTask: Ember.computed('model.isAdmin', function() { return this.get('model.isAdmin'); }), });
singularities/circular-works
frontend/app/controllers/organizations/show.js
JavaScript
agpl-3.0
180
var searchData= [ ['narrowing_5ferror',['narrowing_error',['../structgsl_1_1narrowing__error.html',1,'gsl']]], ['not_5fnull',['not_null',['../classgsl_1_1not__null.html',1,'gsl']]], ['null_5fspin_5fpolicy',['null_spin_policy',['../structquickcpplib_1_1__xxx_1_1configurable__spinlock_1_1null__spin__policy.html',1,'quickcpplib::_xxx::configurable_spinlock']]] ];
FSMaxB/molch
outcome/include/outcome/quickcpplib/doc/html/search/classes_9.js
JavaScript
lgpl-2.1
369
define(['psc-tests-assert','Psc/UI/ErrorPane'], function(t) { var setup = function(test) { return t.setup(test); }; module("Psc.UI.ErrorPane"); test("acceptance", function() { setup(this); var errorPane = new Psc.UI.ErrorPane({ container: $('#qunit-fixture'), label: 'some', errorMessage: 'some text'+"\nwillbe converted" }); errorPane.display(); this.assertEquals(1, $('#qunit-fixture .psc-cms-ui-error-pane').length); // does not attach twice errorPane.display(); this.assertEquals(1, $('#qunit-fixture .psc-cms-ui-error-pane').length); }); test("can be removed", function () { setup(this); var errorPane = new Psc.UI.ErrorPane({ container: $('#qunit-fixture'), label: 'some', errorMessage: 'some text'+"\nwillbe converted" }); errorPane.display(); this.assertEquals(1, $('#qunit-fixture .psc-cms-ui-error-pane').length); errorPane.hide(); this.assertEquals(0, $('#qunit-fixture .psc-cms-ui-error-pane').length); }); });
webforge-labs/psc-cms-js
tests/Psc/UI/ErrorPaneTest.js
JavaScript
lgpl-3.0
1,066
/** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ Loader.define( 'local-require/to-url', ['module', 'require'], (module, require) => { module.exports = require.toUrl('local-require/to-url'); } );
ipeychev/lfr-amd-loader
src/loader/__tests__/__fixtures__/loader/local-require/to-url.js
JavaScript
lgpl-3.0
278
/// <reference name="MicrosoftAjax.debug.js" /> /// <reference path="../ExtenderBase/BaseScripts.js" /> /// <reference path="../Common/Common.js" /> /// <reference path="../Animation/Animations.js" /> /// <reference path="../Animation/AnimationBehavior.js" /> (function() { var scriptName = "ExtendedPopup"; function execute() { Type.registerNamespace('Sys.Extended.UI'); Sys.Extended.UI.PopupBehavior = function(element) { /// <summary> /// The PopupBehavior is used to show/hide an element at a position /// relative to another element /// </summary> /// <param name="element" type="Sys.UI.DomElement" mayBeNull="false" domElement="true"> /// The DOM element the behavior is associated with /// </param> Sys.Extended.UI.PopupBehavior.initializeBase(this, [element]); this._x = 0; this._y = 0; this._positioningMode = Sys.Extended.UI.PositioningMode.Absolute; this._parentElement = null; this._parentElementID = null; this._moveHandler = null; this._firstPopup = true; this._originalParent = null; this._visible = false; // Generic animation behaviors that automatically build animations // from JSON descriptions this._onShow = null; this._onHide = null; // Create handlers for the animation ended events this._onShowEndedHandler = Function.createDelegate(this, this._onShowEnded); this._onHideEndedHandler = Function.createDelegate(this, this._onHideEnded); } Sys.Extended.UI.PopupBehavior.prototype = { initialize: function() { /// <summary> /// Initialize the PopupBehavior /// </summary> Sys.Extended.UI.PopupBehavior.callBaseMethod(this, 'initialize'); this._hidePopup(); this.get_element().style.position = "absolute"; }, dispose: function() { /// <summary> /// Dispose the PopupBehavior /// </summary> var element = this.get_element(); if (element) { if (this._visible) { this.hide(); } if (this._originalParent) { element.parentNode.removeChild(element); this._originalParent.appendChild(element); this._originalParent = null; } // Remove expando properties element._hideWindowedElementsIFrame = null; } this._parentElement = null; // Remove the animation ended events and wipe the animations // (we don't need to dispose them because that will happen // automatically in our base dispose) if (this._onShow && this._onShow.get_animation()) { this._onShow.get_animation().remove_ended(this._onShowEndedHandler); } this._onShow = null; if (this._onHide && this._onHide.get_animation()) { this._onHide.get_animation().remove_ended(this._onHideEndedHandler); } this._onHide = null; Sys.Extended.UI.PopupBehavior.callBaseMethod(this, 'dispose'); }, show: function() { /// <summary> /// Show the popup /// </summary> // Ignore requests to hide multiple times if (this._visible) { return; } var eventArgs = new Sys.CancelEventArgs(); this.raiseShowing(eventArgs); if (eventArgs.get_cancel()) { return; } // Either show the popup or play an animation that does // (note: even if we're animating, we still show and position // the popup before hiding it again and playing the animation // which makes the animation much simpler) this._visible = true; var element = this.get_element(); $common.setVisible(element, true); this.setupPopup(); if (this._onShow) { $common.setVisible(element, false); this.onShow(); } else { this.raiseShown(Sys.EventArgs.Empty); } }, hide: function() { /// <summary> /// Hide the popup /// </summary> // Ignore requests to hide multiple times if (!this._visible) { return; } var eventArgs = new Sys.CancelEventArgs(); this.raiseHiding(eventArgs); if (eventArgs.get_cancel()) { return; } // Either hide the popup or play an animation that does this._visible = false; if (this._onHide) { this.onHide(); } else { this._hidePopup(); this._hideCleanup(); } }, getBounds: function() { /// <summary> /// Get the expected bounds of the popup relative to its parent /// </summary> /// <returns type="Sys.UI.Bounds" mayBeNull="false"> /// Bounds of the popup relative to its parent /// </returns> /// <remarks> /// The actual final position can only be calculated after it is /// initially set and we can verify it doesn't bleed off the edge /// of the screen. /// </remarks> var element = this.get_element(); // offsetParent (doc element if absolutely positioned or no offsetparent available) var offsetParent = element.offsetParent || document.documentElement; // diff = difference in position between element's offsetParent and the element we will attach popup to. // this is basically so we can position the popup in the right spot even though it may not be absolutely positioned var diff; var parentBounds; if (this.get_parentElement()) { // we will be positioning the element against the assigned parent parentBounds = $common.getBounds(this.get_parentElement()); var offsetParentLocation = $common.getLocation(offsetParent); diff = { x: parentBounds.x - offsetParentLocation.x, y: parentBounds.y - offsetParentLocation.y }; } else { // we will be positioning the element against the offset parent by default, since no parent element given parentBounds = $common.getBounds(offsetParent); diff = { x: 0, y: 0 }; } // width/height of the element, needed for calculations that involve width like centering var width = element.offsetWidth - (element.clientLeft ? element.clientLeft * 2 : 0); var height = element.offsetHeight - (element.clientTop ? element.clientTop * 2 : 0); // Setting the width causes the element to grow by border+passing every // time. But not setting it causes strange behavior in safari. Just set it once. if (this._firstpopup) { element.style.width = width + "px"; this._firstpopup = false; } var position, pos; switch (this._positioningMode) { case Sys.Extended.UI.PositioningMode.Center: pos = { x: Math.round(parentBounds.width / 2 - width / 2), y: Math.round(parentBounds.height / 2 - height / 2), altX: Math.round(parentBounds.width / 2 - width / 2), altY: Math.round(parentBounds.height / 2 - height / 2) }; break; case Sys.Extended.UI.PositioningMode.BottomLeft: pos = { x: 0, y: parentBounds.height, altX: parentBounds.width - width, altY: 0 - height } break; case Sys.Extended.UI.PositioningMode.BottomRight: pos = { x: parentBounds.width - width, y: parentBounds.height, altX: 0, altY: 0 - height } break; case Sys.Extended.UI.PositioningMode.TopLeft: pos = { x: 0, y: -element.offsetHeight, altX: parentBounds.width - width, altY: parentBounds.height } break; case Sys.Extended.UI.PositioningMode.TopRight: pos = { x: parentBounds.width - width, y: -element.offsetHeight, altX: 0, altY: parentBounds.height } break; case Sys.Extended.UI.PositioningMode.Right: pos = { x: parentBounds.width, y: 0, altX: -element.offsetWidth, altY: parentBounds.height - height } break; case Sys.Extended.UI.PositioningMode.Left: pos = { x: -element.offsetWidth, y: 0, altX: parentBounds.width, altY: parentBounds.height - height } break; default: pos = { x: 0, y: 0, altX: 0, altY: 0 }; } pos.x += this._x + diff.x; pos.altX += this._x + diff.x; pos.y += this._y + diff.y; pos.altY += this._y + diff.y; position = this._verifyPosition(pos, width, height, parentBounds); return new Sys.UI.Bounds(position.x, position.y, width, height); }, _verifyPosition: function(pos, elementWidth, elementHeight, parentBounds) { /// <summary> /// Checks whether the popup is entirely visible and attempts to change its position to make it entirely visihle. /// </summary> var newX = 0, newY = 0; var windowBounds = this._getWindowBounds(); // Check horizontal positioning if (!((pos.x + elementWidth > windowBounds.x + windowBounds.width) || (pos.x < windowBounds.x))) { newX = pos.x; } else { newX = pos.altX; if (pos.altX < windowBounds.x) { if (pos.x > pos.altX) { newX = pos.x; } } else if (windowBounds.width + windowBounds.x - pos.altX < elementWidth) { var xDiff = pos.x > pos.altX ? Math.abs(windowBounds.x - pos.x) : (windowBounds.x - pos.x); if (xDiff < elementWidth - windowBounds.width - windowBounds.x + pos.altX) { newX = pos.x; } } } // Check vertical positioning if (!((pos.y + elementHeight > windowBounds.y + windowBounds.height) || (pos.y < windowBounds.y))) { newY = pos.y; } else { newY = pos.altY; if (pos.altY < windowBounds.y) { if (windowBounds.y - pos.altY > elementHeight - windowBounds.height - windowBounds.y + pos.y) { newY = pos.y; } } else if (windowBounds.height + windowBounds.y - pos.altY < elementHeight) { if (windowBounds.y - pos.y < elementHeight - windowBounds.height - windowBounds.y + pos.altY) { newY = pos.y; } } } return { x: newX, y: newY }; }, _getWindowBounds: function() { var bounds = { x: this._getWindowScrollLeft(), y: this._getWindowScrollTop(), width: this._getWindowWidth(), height: this._getWindowHeight() }; return bounds; }, _getWindowHeight: function() { var windowHeight = 0; if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } return windowHeight; }, _getWindowWidth: function() { var windowWidth = 0; if (document.documentElement && document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else if (document.body && document.body.clientWidth) { windowWidth = document.body.clientWidth; } return windowWidth; }, _getWindowScrollTop: function() { var scrollTop = 0; if (typeof (window.pageYOffset) == 'number') { scrollTop = window.pageYOffset; } if (document.body && document.body.scrollTop) { scrollTop = document.body.scrollTop; } else if (document.documentElement && document.documentElement.scrollTop) { scrollTop = document.documentElement.scrollTop; } return scrollTop; }, _getWindowScrollLeft: function() { var scrollLeft = 0; if (typeof (window.pageXOffset) == 'number') { scrollLeft = window.pageXOffset; } else if (document.body && document.body.scrollLeft) { scrollLeft = document.body.scrollLeft; } else if (document.documentElement && document.documentElement.scrollLeft) { scrollLeft = document.documentElement.scrollLeft; } return scrollLeft; }, adjustPopupPosition: function(bounds) { /// <summary> /// Adjust the position of the popup after it's originally bet set /// to make sure that it's visible on the page. /// </summary> /// <param name="bounds" type="Sys.UI.Bounds" mayBeNull="true" optional="true"> /// Original bounds of the parent element /// </param> var element = this.get_element(); if (!bounds) { bounds = this.getBounds(); } // Get the new bounds now that we've shown the popup var newPosition = $common.getBounds(element); var updateNeeded = false; if (newPosition.x < 0) { bounds.x -= newPosition.x; updateNeeded = true; } if (newPosition.y < 0) { bounds.y -= newPosition.y; updateNeeded = true; } // If the popup was off the screen, reposition it if (updateNeeded) { $common.setLocation(element, bounds); } }, addBackgroundIFrame: function() { /// <summary> /// Add an empty IFRAME behind the popup (for IE6 only) so that SELECT, etc., won't /// show through the popup. /// </summary> // Get the child frame var element = this.get_element(); if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) { var childFrame = element._hideWindowedElementsIFrame; // Create the child frame if it wasn't found if (!childFrame) { childFrame = document.createElement("iframe"); childFrame.src = "javascript:'<html></html>';"; childFrame.style.position = "absolute"; childFrame.style.display = "none"; childFrame.scrolling = "no"; childFrame.frameBorder = "0"; childFrame.tabIndex = "-1"; childFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"; element.parentNode.insertBefore(childFrame, element); element._hideWindowedElementsIFrame = childFrame; this._moveHandler = Function.createDelegate(this, this._onMove); Sys.UI.DomEvent.addHandler(element, "move", this._moveHandler); } // Position the frame exactly behind the element $common.setBounds(childFrame, $common.getBounds(element)); childFrame.style.left = element.style.left; childFrame.style.top = element.style.top; childFrame.style.display = element.style.display; if (element.currentStyle && element.currentStyle.zIndex) { childFrame.style.zIndex = element.currentStyle.zIndex; } else if (element.style.zIndex) { childFrame.style.zIndex = element.style.zIndex; } } }, setupPopup: function() { /// <summary> /// Position the popup relative to its parent /// </summary> var element = this.get_element(); var bounds = this.getBounds(); $common.setLocation(element, bounds); // Tweak the position, set the zIndex, and add the background iframe in IE6 this.adjustPopupPosition(bounds); element.style.zIndex = 1000; this.addBackgroundIFrame(); }, _hidePopup: function() { /// <summary> /// Internal hide implementation /// </summary> var element = this.get_element(); $common.setVisible(element, false); if (element.originalWidth) { element.style.width = element.originalWidth + "px"; element.originalWidth = null; } }, _hideCleanup: function() { /// <summary> /// Perform cleanup after hiding the element /// </summary> var element = this.get_element(); // Remove the tracking handler if (this._moveHandler) { Sys.UI.DomEvent.removeHandler(element, "move", this._moveHandler); this._moveHandler = null; } // Hide the child frame if (Sys.Browser.agent === Sys.Browser.InternetExplorer) { var childFrame = element._hideWindowedElementsIFrame; if (childFrame) { childFrame.style.display = "none"; } } this.raiseHidden(Sys.EventArgs.Empty); }, _onMove: function() { /// <summary> /// Track the popup's movements so the hidden IFrame (IE6 only) can /// be moved along with it /// </summary> var element = this.get_element(); if (element._hideWindowedElementsIFrame) { element.parentNode.insertBefore(element._hideWindowedElementsIFrame, element); element._hideWindowedElementsIFrame.style.top = element.style.top; element._hideWindowedElementsIFrame.style.left = element.style.left; } }, get_onShow: function() { /// <value type="String" mayBeNull="true"> /// Generic OnShow Animation's JSON definition /// </value> return this._onShow ? this._onShow.get_json() : null; }, set_onShow: function(value) { if (!this._onShow) { this._onShow = new Sys.Extended.UI.Animation.GenericAnimationBehavior(this.get_element()); this._onShow.initialize(); } this._onShow.set_json(value); var animation = this._onShow.get_animation(); if (animation) { animation.add_ended(this._onShowEndedHandler); } this.raisePropertyChanged('onShow'); }, get_onShowBehavior: function() { /// <value type="Sys.Extended.UI.Animation.GenericAnimationBehavior"> /// Generic OnShow Animation's behavior /// </value> return this._onShow; }, onShow: function() { /// <summary> /// Play the OnShow animation /// </summary> /// <returns /> if (this._onShow) { if (this._onHide) { this._onHide.quit(); } this._onShow.play(); } }, _onShowEnded: function() { /// <summary> /// Handler for the OnShow Animation's Ended event /// </summary> // Make sure the popup is where it belongs this.adjustPopupPosition(); this.addBackgroundIFrame(); this.raiseShown(Sys.EventArgs.Empty); }, get_onHide: function() { /// <value type="String" mayBeNull="true"> /// Generic OnHide Animation's JSON definition /// </value> return this._onHide ? this._onHide.get_json() : null; }, set_onHide: function(value) { if (!this._onHide) { this._onHide = new Sys.Extended.UI.Animation.GenericAnimationBehavior(this.get_element()); this._onHide.initialize(); } this._onHide.set_json(value); var animation = this._onHide.get_animation(); if (animation) { animation.add_ended(this._onHideEndedHandler); } this.raisePropertyChanged('onHide'); }, get_onHideBehavior: function() { /// <value type="Sys.Extended.UI.Animation.GenericAnimationBehavior"> /// Generic OnHide Animation's behavior /// </value> return this._onHide; }, onHide: function() { /// <summary> /// Play the OnHide animation /// </summary> /// <returns /> if (this._onHide) { if (this._onShow) { this._onShow.quit(); } this._onHide.play(); } }, _onHideEnded: function() { /// <summary> /// Handler for the OnHide Animation's Ended event /// </summary> this._hideCleanup(); }, get_parentElement: function() { /// <value type="Sys.UI.DomElement" domElement="true"> /// Parent dom element. /// </value> if (!this._parentElement && this._parentElementID) { this.set_parentElement($get(this._parentElementID)); //Sys.Debug.assert(this._parentElement != null, String.format(Sys.Extended.UI.Resources.PopupExtender_NoParentElement, this._parentElementID)); } return this._parentElement; }, set_parentElement: function(element) { this._parentElement = element; this.raisePropertyChanged('parentElement'); }, get_parentElementID: function() { /// <value type="String"> /// Parent dom element. /// </value> if (this._parentElement) { return this._parentElement.id } return this._parentElementID; }, set_parentElementID: function(elementID) { this._parentElementID = elementID; if (this.get_isInitialized()) { this.set_parentElement($get(elementID)); } }, get_positioningMode: function() { /// <value type="Sys.Extended.UI.PositioningMode"> /// Positioning mode. /// </value> return this._positioningMode; }, set_positioningMode: function(mode) { this._positioningMode = mode; this.raisePropertyChanged('positioningMode'); }, get_x: function() { /// <value type="Number"> /// X coordinate. /// </value> return this._x; }, set_x: function(value) { if (value != this._x) { this._x = value; // Reposition the popup if it's already showing if (this._visible) { this.setupPopup(); } this.raisePropertyChanged('x'); } }, get_y: function() { /// <value type="Number"> /// Y coordinate. /// </value> return this._y; }, set_y: function(value) { if (value != this._y) { this._y = value; // Reposition the popup if it's already showing if (this._visible) { this.setupPopup(); } this.raisePropertyChanged('y'); } }, get_visible: function() { /// <value type="Boolean" mayBeNull="false"> /// Whether or not the popup is currently visible /// </value> return this._visible; }, add_showing: function(handler) { /// <summary> /// Add an event handler for the showing event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('showing', handler); }, remove_showing: function(handler) { /// <summary> /// Remove an event handler from the showing event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('showing', handler); }, raiseShowing: function(eventArgs) { /// <summary> /// Raise the showing event /// </summary> /// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false"> /// Event arguments for the showing event /// </param> /// <returns /> var handler = this.get_events().getHandler('showing'); if (handler) { handler(this, eventArgs); } }, add_shown: function(handler) { /// <summary> /// Add an event handler for the shown event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('shown', handler); }, remove_shown: function(handler) { /// <summary> /// Remove an event handler from the shown event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('shown', handler); }, raiseShown: function(eventArgs) { /// <summary> /// Raise the shown event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the shown event /// </param> /// <returns /> var handler = this.get_events().getHandler('shown'); if (handler) { handler(this, eventArgs); } }, add_hiding: function(handler) { /// <summary> /// Add an event handler for the hiding event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('hiding', handler); }, remove_hiding: function(handler) { /// <summary> /// Remove an event handler from the hiding event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('hiding', handler); }, raiseHiding: function(eventArgs) { /// <summary> /// Raise the hiding event /// </summary> /// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false"> /// Event arguments for the hiding event /// </param> /// <returns /> var handler = this.get_events().getHandler('hiding'); if (handler) { handler(this, eventArgs); } }, add_hidden: function(handler) { /// <summary> /// Add an event handler for the hidden event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('hidden', handler); }, remove_hidden: function(handler) { /// <summary> /// Remove an event handler from the hidden event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('hidden', handler); }, raiseHidden: function(eventArgs) { /// <summary> /// Raise the hidden event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the hidden event /// </param> /// <returns /> var handler = this.get_events().getHandler('hidden'); if (handler) { handler(this, eventArgs); } } } Sys.Extended.UI.PopupBehavior.registerClass('Sys.Extended.UI.PopupBehavior', Sys.Extended.UI.BehaviorBase); Sys.registerComponent(Sys.Extended.UI.PopupBehavior, { name: "popup" }); //Sys.Extended.UI.PopupBehavior.descriptor = { // properties: [ {name: 'parentElement', attributes: [ Sys.Attributes.Element, true ] }, // {name: 'positioningMode', type: Sys.Extended.UI.PositioningMode}, // {name: 'x', type: Number}, // {name: 'y', type: Number} ], // events: [ {name: 'show'}, // {name: 'hide'} ] //} Sys.Extended.UI.PositioningMode = function() { /// <summary> /// Positioning mode describing how the popup should be positioned /// relative to its specified parent /// </summary> /// <field name="Absolute" type="Number" integer="true" /> /// <field name="Center" type="Number" integer="true" /> /// <field name="BottomLeft" type="Number" integer="true" /> /// <field name="BottomRight" type="Number" integer="true" /> /// <field name="TopLeft" type="Number" integer="true" /> /// <field name="TopRight" type="Number" integer="true" /> /// <field name="Right" type="Number" integer="true" /> /// <field name="Left" type="Number" integer="true" /> throw Error.invalidOperation(); } Sys.Extended.UI.PositioningMode.prototype = { Absolute: 0, Center: 1, BottomLeft: 2, BottomRight: 3, TopLeft: 4, TopRight: 5, Right: 6, Left: 7 } Sys.Extended.UI.PositioningMode.registerEnum('Sys.Extended.UI.PositioningMode'); } // execute if (window.Sys && Sys.loader) { Sys.loader.registerScript(scriptName, ["ExtendedAnimations", "ExtendedAnimationBehavior"], execute); } else { execute(); } })();
consumentor/Server
trunk/tools/AspNetAjaxLibraryBeta0911/Scripts/extended/PopupExtender/PopupBehavior.debug.js
JavaScript
lgpl-3.0
30,754
/*jslint nomen: true */ /*jslint plusplus: true */ /*jslint browser: true*/ /*jslint node: true*/ /*global d3, io, nunjucks*/ 'use strict'; // // JavaScript unit // Add-on for the string and number manipulation // // Copyright (c) 2005, 2006, 2007, 2010, 2011 by Ildar Shaimordanov // /* The following code is described in ECMA drafts and might be implemented in the future of ECMA */ if (!String.prototype.repeat) { /** * object.x(number) * object.repeat(number) * Transform the string object multiplying the string * * @param number Amount of repeating * @return string * @access public * @see http://svn.debugger.ru/repos/jslibs/BrowserExtensions/trunk/ext/string.js * @see http://wiki.ecmascript.org/doku.php?id=harmony:string_extras */ String.prototype.repeat = function (n) { n = Math.max(n || 0, 0); return new Array(n + 1).join(this.valueOf()); }; } if (!String.prototype.startsWith) { /** * Returns true if the sequence of characters of searchString converted * to a String match the corresponding characters of this object * (converted to a String) starting at position. Otherwise returns false. * * @param string * @param integer * @return bollean * @acess public */ String.prototype.startsWith = function (searchString, position) { position = Math.max(position || 0, 0); return this.indexOf(searchString) == position; }; } if (!String.prototype.endsWith) { /** * Returns true if the sequence of characters of searchString converted * to a String match the corresponding characters of this object * (converted to a String) starting at endPosition - length(this). * Otherwise returns false. * * @param string * @param integer * @return bollean * @acess public */ String.prototype.endsWith = function (searchString, endPosition) { endPosition = Math.max(endPosition || 0, 0); var s = String(searchString); var pos = this.lastIndexOf(s); return pos >= 0 && pos == this.length - s.length - endPosition; }; } if (!String.prototype.contains) { /** * If searchString appears as a substring of the result of converting * this object to a String, at one or more positions that are greater than * or equal to position, then return true; otherwise, returns false. * If position is undefined, 0 is assumed, so as to search all of the String. * * @param string * @param integer * @return bollean * @acess public */ String.prototype.contains = function (searchString, position) { position = Math.max(position || 0, 0); return this.indexOf(searchString) != -1; }; } if (!String.prototype.toArray) { /** * Returns an Array object with elements corresponding to * the characters of this object (converted to a String). * * @param void * @return array * @acess public */ String.prototype.toArray = function () { return this.split(''); }; } if (!String.prototype.reverse) { /** * Returns an Array object with elements corresponding to * the characters of this object (converted to a String) in reverse order. * * @param void * @return string * @acess public */ String.prototype.reverse = function () { return this.split('').reverse().join(''); }; } /* The following ode is not described in ECMA specs or drafts. */ /** * String.validBrackets(string) * Checks string to be valid brackets. Valid brackets are: * quotes - '' "" `' `` * single - <> {} [] () %% || // \\ * double - miltiline comments * /** / C/C++ like (without whitespace) * <??> PHP like * <%%> ASP like * (**) Pascal like * * @param string Brackets (left and right) * @return boolean Result of validity of brackets * @access static */ String.validBrackets = function (br) { if (!br) { return false; } var quot = "''\"\"`'``"; var sgl = "<>{}[]()%%||//\\\\"; var dbl = "/**/<??><%%>(**)"; return (br.length == 2 && (quot + sgl).indexOf(br) != -1) || (br.length == 4 && dbl.indexOf(br) != -1); }; /** * object.bracketize(string) * Transform the string object by setting in frame of valid brackets * * @param string Brackets * @return string Bracketized string * @access public */ String.prototype.brace = String.prototype.bracketize = function (br) { var string = this; if (!String.validBrackets(br)) { return string; } var midPos = br.length / 2; return br.substr(0, midPos) + string.toString() + br.substr(midPos); }; /** * object.unbracketize(string) * Transform the string object removing the leading and trailing brackets * If the parameter is not defined the method will try to remove existing valid brackets * * @param string Brackets * @return string Unbracketized string * @access public */ String.prototype.unbrace = String.prototype.unbracketize = function (br) { var string = this; if (!br) { var len = string.length; for (var i = 2; i >= 1; i--) { br = string.substring(0, i) + string.substring(len - i); if (String.validBrackets(br)) { return string.substring(i, len - i); } } } if (!String.validBrackets(br)) { return string; } var midPos = br.length / 2; var i = string.indexOf(br.substr(0, midPos)); var j = string.lastIndexOf(br.substr(midPos)); if (i == 0 && j == string.length - midPos) { string = string.substring(i + midPos, j); } return string; }; /** * object.radix(number, number, string) * Transform the number object to string in accordance with a scale of notation * If it is necessary the numeric string will aligned to right and filled by '0' character, by default * * @param number Radix of scale of notation (it have to be greater or equal 2 and below or equal 36) * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.radix = function (r, n, c) { return this.toString(r).padding(-n, c); // return this.toString(r).padding(-Math.abs(n), c); }; /** * object.bin(number, string) * Transform the number object to string of binary presentation * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.bin = function (n, c) { return this.radix(0x02, n, c); // return this.radix(0x02, (n) ? n : 16, c); }; /** * object.oct(number, string) * Transform the number object to string of octal presentation * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.oct = function (n, c) { return this.radix(0x08, n, c); // return this.radix(0x08, (n) ? n : 6, c); }; /** * object.dec(number, string) * Transform the number object to string of decimal presentation * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.dec = function (n, c) { return this.radix(0x0A, n, c); }; /** * object.hexl(number, string) * Transform the number object to string of hexadecimal presentation in lower-case of major characters (0-9 and a-f) * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.hexl = function (n, c) { return this.radix(0x10, n, c); // return this.radix(0x10, (n) ? n : 4, c); }; /** * object.hex(number, string) * Transform the number object to string of the hexadecimal presentation * in upper-case of major characters (0-9 and A-F) * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.hex = function (n, c) { return this.radix(0x10, n, c).toUpperCase(); }; /** * object.human([digits[, true]]) * Transform the number object to string in human-readable format (e.h., 1k, 234M, 5G) * * @example * var n = 1001; * * // will output 1.001K * var h = n.human(3); * * // will output 1001.000 * var H = n.human(3, true); * * @param integer Optional. Number of digits after the decimal point. Must be in the range 0-20, inclusive. * @param boolean Optional. If true then use powers of 1024 not 1000 * @return string Human-readable string * @access public */ Number.prototype.human = function (digits, binary) { var n = Math.abs(this); var p = this; var s = ''; var divs = arguments.callee.add(binary); for (var i = divs.length - 1; i >= 0; i--) { if (n >= divs[i].d) { p /= divs[i].d; s = divs[i].s; break; } } return p.toFixed(digits) + s; }; /** * Subsidiary method. * Stores suffixes and divisors to use in Number.prototype.human. * * @param boolean * @param string * @param divisor * @return array * @access static */ Number.prototype.human.add = function (binary, suffix, divisor) { var name = binary ? 'div2' : 'div10'; var divs = Number.prototype.human[name] = Number.prototype.human[name] || []; if (arguments.length < 3) { return divs; } divs.push({ s: suffix, d: Math.abs(divisor) }); divs.sort(function (a, b) { return a.d - b.d; }); return divs; }; // Binary prefixes Number.prototype.human.add(true, 'K', 1 << 10); Number.prototype.human.add(true, 'M', 1 << 20); Number.prototype.human.add(true, 'G', 1 << 30); Number.prototype.human.add(true, 'T', Math.pow(2, 40)); // Decimal prefixes Number.prototype.human.add(false, 'K', 1e3); Number.prototype.human.add(false, 'M', 1e6); Number.prototype.human.add(false, 'G', 1e9); Number.prototype.human.add(false, 'T', 1e12); /** * object.fromHuman([digits[, binary]]) * Transform the human-friendly string to the valid numeriv value * * @example * var n = 1001; * * // will output 1.001K * var h = n.human(3); * * // will output 1001 * var m = h.fromHuman(h); * * @param boolean Optional. If true then use powers of 1024 not 1000 * @return number * @access public */ Number.fromHuman = function (value, binary) { var m = String(value).match(/^([\-\+]?\d+\.?\d*)([A-Z])?$/); if (!m) { return Number.NaN; } if (!m[2]) { return +m[1]; } var divs = Number.prototype.human.add(binary); for (var i = 0; i < divs.length; i++) { if (divs[i].s == m[2]) { return m[1] * divs[i].d; } } return Number.NaN; }; if (!String.prototype.trim) { /** * object.trim() * Transform the string object removing leading and trailing whitespaces * * @return string * @access public */ String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); }; } if (!String.prototype.trimLeft) { /** * object.trimLeft() * Transform the string object removing leading whitespaces * * @return string * @access public */ String.prototype.trimLeft = function () { return this.replace(/(^\s*)/, ""); }; } if (!String.prototype.trimRight) { /** * object.trimRight() * Transform the string object removing trailing whitespaces * * @return string * @access public */ String.prototype.trimRight = function () { return this.replace(/(\s*$)/g, ""); }; } /** * object.dup() * Transform the string object duplicating the string * * @return string * @access public */ String.prototype.dup = function () { var val = this.valueOf(); return val + val; }; /** * object.padding(number, string) * Transform the string object to string of the actual width filling by the padding character (by default ' ') * Negative value of width means left padding, and positive value means right one * * @param number Width of string * @param string Padding chacracter (by default, ' ') * @return string * @access public */ String.prototype.padding = function (n, c) { var val = this.valueOf(); if (Math.abs(n) <= val.length) { return val; } var m = Math.max((Math.abs(n) - this.length) || 0, 0); var pad = Array(m + 1).join(String(c || ' ').charAt(0)); // var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length); return (n < 0) ? pad + val : val + pad; // return (n < 0) ? val + pad : pad + val; }; /** * object.padLeft(number, string) * Wrapper for object.padding * Transform the string object to string of the actual width adding the leading padding character (by default ' ') * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.padLeft = function (n, c) { return this.padding(-Math.abs(n), c); }; /** * object.alignRight(number, string) * Wrapper for object.padding * Synonym for object.padLeft * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.alignRight = String.prototype.padLeft; /** * object.padRight(number, string) * Wrapper for object.padding * Transform the string object to string of the actual width adding the trailing padding character (by default ' ') * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.padRight = function (n, c) { return this.padding(Math.abs(n), c); }; /** * Formats arguments accordingly the formatting string. * Each occurence of the "{\d+}" substring refers to * the appropriate argument. * * @example * '{0}is not {1} + {2}'.format('JavaScript', 'Java', 'Script'); * * @param mixed * @return string * @access public */ String.prototype.format = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function ($0, $1) { return args[$1] !== void 0 ? args[$1] : $0; }); }; /** * object.alignLeft(number, string) * Wrapper for object.padding * Synonym for object.padRight * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.alignLeft = String.prototype.padRight; /** * sprintf(format, argument_list) * * The string function like one in C/C++, PHP, Perl * Each conversion specification is defined as below: * * %[index][alignment][padding][width][precision]type * * index An optional index specifier that changes the order of the * arguments in the list to be displayed. * alignment An optional alignment specifier that says if the result should be * left-justified or right-justified. The default is * right-justified; a "-" character here will make it left-justified. * padding An optional padding specifier that says what character will be * used for padding the results to the right string size. This may * be a space character or a "0" (zero character). The default is to * pad with spaces. An alternate padding character can be specified * by prefixing it with a single quote ('). See the examples below. * width An optional number, a width specifier that says how many * characters (minimum) this conversion should result in. * precision An optional precision specifier that says how many decimal digits * should be displayed for floating-point numbers. This option has * no effect for other types than float. * type A type specifier that says what type the argument data should be * treated as. Possible types: * * % - a literal percent character. No argument is required. * b - the argument is treated as an integer, and presented as a binary number. * c - the argument is treated as an integer, and presented as the character * with that ASCII value. * d - the argument is treated as an integer, and presented as a decimal number. * u - the same as "d". * f - the argument is treated as a float, and presented as a floating-point. * o - the argument is treated as an integer, and presented as an octal number. * s - the argument is treated as and presented as a string. * x - the argument is treated as an integer and presented as a hexadecimal * number (with lowercase letters). * X - the argument is treated as an integer and presented as a hexadecimal * number (with uppercase letters). * h - the argument is treated as an integer and presented in human-readable format * using powers of 1024. * H - the argument is treated as an integer and presented in human-readable format * using powers of 1000. */ String.prototype.sprintf = function () { var args = arguments; var index = 0; var x; var ins; var fn; /* * The callback function accepts the following properties * x.index contains the substring position found at the origin string * x[0] contains the found substring * x[1] contains the index specifier (as \d+\$ or \d+#) * x[2] contains the alignment specifier ("+" or "-" or empty) * x[3] contains the padding specifier (space char, "0" or defined as '.) * x[4] contains the width specifier (as \d*) * x[5] contains the floating-point precision specifier (as \.\d*) * x[6] contains the type specifier (as [bcdfosuxX]) */ return this.replace(String.prototype.sprintf.re, function () { if (arguments[0] == "%%") { return "%"; } x = []; for (var i = 0; i < arguments.length; i++) { x[i] = arguments[i] || ''; } x[3] = x[3].slice(-1) || ' '; ins = args[+x[1] ? x[1] - 1 : index++]; // index++; return String.prototype.sprintf[x[6]](ins, x); }); }; String.prototype.sprintf.re = /%%|%(?:(\d+)[\$#])?([+-])?('.|0| )?(\d*)(?:\.(\d+))?([bcdfosuxXhH])/g; String.prototype.sprintf.b = function (ins, x) { return Number(ins).bin(x[2] + x[4], x[3]); }; String.prototype.sprintf.c = function (ins, x) { return String.fromCharCode(ins).padding(x[2] + x[4], x[3]); }; String.prototype.sprintf.d = String.prototype.sprintf.u = function (ins, x) { return Number(ins).dec(x[2] + x[4], x[3]); }; String.prototype.sprintf.f = function (ins, x) { var ins = Number(ins); // var fn = String.prototype.padding; if (x[5]) { ins = ins.toFixed(x[5]); } else if (x[4]) { ins = ins.toExponential(x[4]); } else { ins = ins.toExponential(); } // Invert sign because this is not number but string x[2] = x[2] == "-" ? "+" : "-"; return ins.padding(x[2] + x[4], x[3]); // return fn.call(ins, x[2] + x[4], x[3]); }; String.prototype.sprintf.o = function (ins, x) { return Number(ins).oct(x[2] + x[4], x[3]); }; String.prototype.sprintf.s = function (ins, x) { return String(ins).padding(x[2] + x[4], x[3]); }; String.prototype.sprintf.x = function (ins, x) { return Number(ins).hexl(x[2] + x[4], x[3]); }; String.prototype.sprintf.X = function (ins, x) { return Number(ins).hex(x[2] + x[4], x[3]); }; String.prototype.sprintf.h = function (ins, x) { var ins = String.prototype.replace.call(ins, /,/g, ''); // Invert sign because this is not number but string x[2] = x[2] == "-" ? "+" : "-"; return Number(ins).human(x[5], true).padding(x[2] + x[4], x[3]); }; String.prototype.sprintf.H = function (ins, x) { var ins = String.prototype.replace.call(ins, /,/g, ''); // Invert sign because this is not number but string x[2] = x[2] == "-" ? "+" : "-"; return Number(ins).human(x[5], false).padding(x[2] + x[4], x[3]); }; /** * compile() * * This string function compiles the formatting string to the internal function * to acelerate an execution a formatting within loops. * * @example * // Standard usage of the sprintf method * var s = ''; * for (var p in obj) { * s += '%s = %s'.sprintf(p, obj[p]); * } * * // The more speed usage of the sprintf method * var sprintf = '%s = %s'.compile(); * var s = ''; * for (var p in obj) { * s += sprintf(p, obj[p]); * } * * @see String.prototype.sprintf() */ String.prototype.compile = function () { var args = arguments; var index = 0; var x; var ins; var fn; /* * The callback function accepts the following properties * x.index contains the substring position found at the origin string * x[0] contains the found substring * x[1] contains the index specifier (as \d+\$ or \d+#) * x[2] contains the alignment specifier ("+" or "-" or empty) * x[3] contains the padding specifier (space char, "0" or defined as '.) * x[4] contains the width specifier (as \d*) * x[5] contains the floating-point precision specifier (as \.\d*) * x[6] contains the type specifier (as [bcdfosuxX]) */ var result = this.replace(/(\\|")/g, '\\$1').replace(String.prototype.sprintf.re, function () { if (arguments[0] == "%%") { return "%"; } arguments.length = 7; x = []; for (var i = 0; i < arguments.length; i++) { x[i] = arguments[i] || ''; } x[3] = x[3].slice(-1) || ' '; ins = x[1] ? x[1] - 1 : index++; // index++; return '", String.prototype.sprintf.' + x[6] + '(arguments[' + ins + '], ["' + x.join('", "') + '"]), "'; }); return Function('', 'return ["' + result + '"].join("")'); }; /** * Considers the string object as URL and returns it's parts separately * * @param void * @return Object * @access public */ String.prototype.parseUrl = function () { var matches = this.match(arguments.callee.re); if (!matches) { return null; } var result = { 'scheme': matches[1] || '', 'subscheme': matches[2] || '', 'user': matches[3] || '', 'pass': matches[4] || '', 'host': matches[5], 'port': matches[6] || '', 'path': matches[7] || '', 'query': matches[8] || '', 'fragment': matches[9] || '' }; return result; }; String.prototype.parseUrl.re = /^(?:([a-z]+):(?:([a-z]*):)?\/\/)?(?:([^:@]*)(?::([^:@]*))?@)?((?:[a-z0-9_-]+\.)+[a-z]{2,}|localhost|(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])))(?::(\d+))?(?:([^:\?\#]+))?(?:\?([^\#]+))?(?:\#([^\s]+))?$/i; String.prototype.camelize = function () { return this.replace(/([^-]+)|(?:-(.)([^-]+))/mg, function ($0, $1, $2, $3) { return ($2 || '').toUpperCase() + ($3 || $1).toLowerCase(); }); }; String.prototype.uncamelize = function () { return this.replace(/[A-Z]/g, function ($0) { return '-' + $0.toLowerCase(); }); };
flower1024/nodePoloApi
public/string.js
JavaScript
unlicense
23,495
(function() { var Detail; Detail = function(detailData) { // 詳細情報を載せるwindow表示(半透明) var t = windowAnimation(0); var win = Ti.UI.createWindow({ backgroundColor:'#333333', borderWidth:1, borderColor:'#666', width:"100%", height:"100%", borderRadius:5, opacity:0.92, transform:t }); // window開ききったときのアニメーション var a = Titanium.UI.createAnimation(); a.duration = 200; a.addEventListener('complete', function() { var t1 = windowAnimation(1.0); win.animate({transform:t1, duration:200}); }); // タイトル titleLabel = Ti.UI.createLabel({ top : 10, font: { fontsize:20, fontWeight: "bold" }, color:"#ffffff", layout:"vertical" }); if (typeof(detailData.title) == "undefined") { titleLabel.text = ''; } else { titleLabel.text = detailData.title; } win.add(titleLabel); // 載せる画像 if (detailData.is_image === true) { imageUrl = "http://images.amazon.com/images/P/" + detailData.asin + ".09._SL200_SCLZZZZZZZ_.jpg"; Ti.API.info(imageUrl); } else { imageUrl = "./images/noimage.jpeg"; } detailImage = Ti.UI.createImageView({ image:imageUrl, width : Ti.UI.SIZE, height : 200, top:50, backgroundColor:'#ffffff', layout:"vertical" }); win.add(detailImage); var data = []; data[0] = Ti.UI.createTableViewRow({title:'購入/予約をする', hasChild:true, className:'detail'}); data[1] = Ti.UI.createTableViewRow({title:'チェックリストに入れる', className:'detail'}); data[2] = Ti.UI.createTableViewRow({title:'カレンダーに登録する', className:'detail'}); data[3] = Ti.UI.createTableViewRow({title:'このページを閉じる', className:'detail'}); var menuTableView = Titanium.UI.createTableView({ data:data, bottom:5, left:30, right:30, height:180, borderWidth:1, borderRadius:7, borderColor:'#999', layout:"vertical" }); win.add(menuTableView); menuTableView.addEventListener('click', function(e){ Ti.API.info(e); // クローズ var eventT = windowAnimation(0); win.close({transform:eventT,duration:300}); // window呼び出し var index = e.index; if (index === 0) { var AmazonDetail = require('ui/AmazonDetail'); var AmazonDetailWin = new AmazonDetail(detailData.asin); ActiveWinTab.tabs.activeTab.open(AmazonDetailWin); } else if (index === 1) { var AmazonDetail = require('ui/AmazonDetail'); var AmazonDetailWin = new AmazonDetail(detailData.asin); ActiveWinTab.tabs.activeTab.open(AmazonDetailWin); } else if (index === 2) { var AmazonDetail = require('ui/AmazonDetail'); var AmazonDetailWin = new AmazonDetail(detailData.asin); ActiveWinTab.tabs.activeTab.open(AmazonDetailWin); } else { } }); // windowにクリックしたらクローズ win.addEventListener('click', function(){ var eventT = windowAnimation(0); win.close({transform:eventT,duration:300}); }); win.open(a); }; var windowAnimation = function(scaleValue) { var t = Titanium.UI.create2DMatrix(); t = t.scale(scaleValue); return t; } return module.exports = Detail; })();
kirou/books_app_list
sinkancheaker/Resources/ui/Detail.js
JavaScript
apache-2.0
3,996
/** * Test for Bidi restrictions on IDNs from RFC 3454 */ var Cc = Components.classes; var Ci = Components.interfaces; var idnService; function expected_pass(inputIDN) { var isASCII = {}; var displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII); do_check_eq(displayIDN, inputIDN); } function expected_fail(inputIDN) { var isASCII = {}; var displayIDN = ""; try { displayIDN = idnService.convertToDisplayIDN(inputIDN, isASCII); } catch(e) {} do_check_neq(displayIDN, inputIDN); } function run_test() { // add an IDN whitelist pref var pbi = Cc["@mozilla.org/preferences-service;1"] .getService(Ci.nsIPrefBranch); pbi.setBoolPref("network.IDN.whitelist.com", true); idnService = Cc["@mozilla.org/network/idn-service;1"] .getService(Ci.nsIIDNService); /* * In any profile that specifies bidirectional character handling, all * three of the following requirements MUST be met: * * 1) The characters in section 5.8 MUST be prohibited. */ // 0340; COMBINING GRAVE TONE MARK expected_fail("foo\u0340bar.com"); // 0341; COMBINING ACUTE TONE MARK expected_fail("foo\u0341bar.com"); // 200E; LEFT-TO-RIGHT MARK expected_fail("foo\200ebar.com"); // 200F; RIGHT-TO-LEFT MARK // Note: this is an RTL IDN so that it doesn't fail test 2) below expected_fail("\u200f\u0645\u062B\u0627\u0644.\u0622\u0632\u0645\u0627\u06CC\u0634\u06CC"); // 202A; LEFT-TO-RIGHT EMBEDDING expected_fail("foo\u202abar.com"); // 202B; RIGHT-TO-LEFT EMBEDDING expected_fail("foo\u202bbar.com"); // 202C; POP DIRECTIONAL FORMATTING expected_fail("foo\u202cbar.com"); // 202D; LEFT-TO-RIGHT OVERRIDE expected_fail("foo\u202dbar.com"); // 202E; RIGHT-TO-LEFT OVERRIDE expected_fail("foo\u202ebar.com"); // 206A; INHIBIT SYMMETRIC SWAPPING expected_fail("foo\u206abar.com"); // 206B; ACTIVATE SYMMETRIC SWAPPING expected_fail("foo\u206bbar.com"); // 206C; INHIBIT ARABIC FORM SHAPING expected_fail("foo\u206cbar.com"); // 206D; ACTIVATE ARABIC FORM SHAPING expected_fail("foo\u206dbar.com"); // 206E; NATIONAL DIGIT SHAPES expected_fail("foo\u206ebar.com"); // 206F; NOMINAL DIGIT SHAPES expected_fail("foo\u206fbar.com"); /* * 2) If a string contains any RandALCat character, the string MUST NOT * contain any LCat character. */ // www.מיץpetel.com is invalid expected_fail("www.\u05DE\u05D9\u05E5petel.com"); // But www.מיץפטל.com is fine because the ltr and rtl characters are in // different labels expected_pass("www.\u05DE\u05D9\u05E5\u05E4\u05D8\u05DC.com"); /* * 3) If a string contains any RandALCat character, a RandALCat * character MUST be the first character of the string, and a * RandALCat character MUST be the last character of the string. */ // www.1מיץ.com is invalid expected_fail("www.1\u05DE\u05D9\u05E5.com"); // www.מיץ1.com is invalid expected_fail("www.\u05DE\u05D9\u05E51.com"); // But www.מיץ1פטל.com is fine expected_pass("www.\u05DE\u05D9\u05E51\u05E4\u05D8\u05DC.com"); }
sergecodd/FireFox-OS
B2G/gecko/netwerk/test/unit/test_bug427957.js
JavaScript
apache-2.0
3,088
var welcomeText = ( ' ____ _ ____ \n'+ '| _ \\ __ __ | / ___| \n'+ '| |_) |\\ \\/ / | \\___ \\ \n'+ '| _ < > < |_| |___) | \n'+ '|_| \\_\\/_/\\_\\___/|____/ \n'+ '\n试试下面这段代码来开启 RxJS 之旅:\n'+ '\n var subscription = Rx.Observable.interval(500)'+ '.take(4).subscribe(function (x) { console.log(x) });\n'+ '\n还引入了 rxjs-spy 来帮助你调试 RxJS 代码,试试下面这段代码:\n'+ '\n rxSpy.spy();'+ '\n var subscription = Rx.Observable.interval(500)'+ '.tag("interval").subscribe();'+ '\n rxSpy.show();'+ '\n rxSpy.log("interval");\n'+ '\n 想了解更多 rxjs-spy 的用法,请查阅 https://zhuanlan.zhihu.com/p/30870431' ); if (console.info) { console.info(welcomeText); } else { console.log(welcomeText); }
SangKa/RxJS-Docs-CN
doc/asset/devtools-welcome.js
JavaScript
apache-2.0
826
'use strict'; angular.module('publisherApp') .factory('Register', function ($resource) { return $resource('api/register', {}, { }); });
GIP-RECIA/esup-publisher-ui
src/main/webapp/scripts/components/auth/services/register.service.js
JavaScript
apache-2.0
163
/* * 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'); /** * Responsys dataset. * * @extends models['Dataset'] */ class ResponsysObjectDataset extends models['Dataset'] { /** * Create a ResponsysObjectDataset. * @member {object} [tableName] The table name. Type: string (or Expression * with resultType string). */ constructor() { super(); } /** * Defines the metadata of ResponsysObjectDataset * * @returns {object} metadata of ResponsysObjectDataset * */ mapper() { return { required: false, serializedName: 'ResponsysObject', type: { name: 'Composite', polymorphicDiscriminator: { serializedName: 'type', clientName: 'type' }, uberParent: 'Dataset', className: 'ResponsysObjectDataset', modelProperties: { description: { required: false, serializedName: 'description', type: { name: 'String' } }, structure: { required: false, serializedName: 'structure', type: { name: 'Object' } }, linkedServiceName: { required: true, serializedName: 'linkedServiceName', defaultValue: {}, type: { name: 'Composite', className: 'LinkedServiceReference' } }, parameters: { required: false, serializedName: 'parameters', type: { name: 'Dictionary', value: { required: false, serializedName: 'ParameterSpecificationElementType', type: { name: 'Composite', className: 'ParameterSpecification' } } } }, annotations: { required: false, serializedName: 'annotations', type: { name: 'Sequence', element: { required: false, serializedName: 'ObjectElementType', type: { name: 'Object' } } } }, folder: { required: false, serializedName: 'folder', type: { name: 'Composite', className: 'DatasetFolder' } }, type: { required: true, serializedName: 'type', isPolymorphicDiscriminator: true, type: { name: 'String' } }, tableName: { required: false, serializedName: 'typeProperties.tableName', type: { name: 'Object' } } } } }; } } module.exports = ResponsysObjectDataset;
xingwu1/azure-sdk-for-node
lib/services/datafactoryManagement/lib/models/responsysObjectDataset.js
JavaScript
apache-2.0
3,288
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ CLASS({ package: 'foam.ui.md', name: 'SectionView', extends: 'foam.flow.Element', requires: [ 'foam.ui.Icon', 'foam.ui.md.ExpandableView' ], constants: { ELEMENT_NAME: 'section' }, properties: [ { model_: 'BooleanProperty', name: 'expandable', defaultValue: true, postSet: function(old, nu) { if ( ! this.$ || old === nu ) return; // Need full re-render to correctly wire (or not wire) this.on('click'). this.updateHTML(); } }, { model_: 'BooleanProperty', name: 'expanded', defaultValue: true }, { model_: 'StringProperty', name: 'title', defaultValue: 'Heading' }, { model_: 'StringProperty', name: 'titleClass', defaultValue: 'md-subhead' }, { model_: 'ViewFactoryProperty', name: 'icon', defaultValue: null }, { model_: 'ViewFactoryProperty', name: 'delegate' }, { name: 'delegateView', postSet: function(old, nu) { if ( old && old.expanded$ ) Events.unfollow(this.expanded$, old.expanded$); if ( nu && nu.expanded$ ) Events.follow(this.expanded$, nu.expanded$); } }, { model_: 'StringProperty', name: 'expandedIconId', lazyFactory: function() { return this.id + '-expanded-icon'; } }, { model_: 'ViewFactoryProperty', name: 'expandedIcon', defaultValue: function() { return this.Icon.create({ id: this.expandedIconId, url: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAARUlEQVR4AWMY1GAUNAAhScr/A2EDKcr/ACFcC2HlvxnCGMIhWohVDgQwLYSVh8K4hLU0AJWHQNkILXX47NDCIjIIwSgAAGEBHc5iOzTwAAAAAElFTkSuQmCC', ligature: 'expand_less', extraClassName: 'expanded-icon' }, this.Y); } }, ], methods: [ { name: 'initHTML', code: function() { this.SUPER.apply(this, arguments); if ( this.expandable ) { this.delegateView.expandedIcon = this.X.$(this.expandedIconId); } } } ], listeners: [ { name: 'onToggleExpanded', code: function() { this.delegateView && this.delegateView.toggleExpanded && this.delegateView.toggleExpanded(); } } ], templates: [ function toInnerHTML() {/* <% this.delegateView = this.delegate(); this.addDataChild(this.delegateView); %> <heading id="{{this.id}}-heading" class="{{this.titleClass}}"> <% if ( this.icon ) { %>%%icon()<% } %> <span>{{this.title}}</span> <% if ( this.expandable ) { this.on('click', this.onToggleExpanded, this.id + '-heading'); %> <div class="flex-flush-right"> %%expandedIcon() </div> <% } %> </heading> %%delegateView */}, function CSS() {/* section heading { display: flex; align-items: center; cursor: pointer; margin: 8px 0; } section heading > * { flex-grow: 0; } section heading div.flex-flush-right { flex-grow: 1; display: flex; justify-content: flex-end; } section heading icon { margin-right: 12px; } section heading icon.expanded-icon { margin-right: initial; } */} ] });
mdittmer/foam
js/foam/ui/md/SectionView.js
JavaScript
apache-2.0
3,734
define(["jquery", "bootstrap", "d3","jnj_chart", "ohdsi_common", "datatables", "datatables-colvis", "colorbrewer", "tabletools"], function ($, bootstrap, d3, jnj_chart, common, DataTables, DataTablesColvis, colorbrewer, TableTools) { function ObservationsRenderer() {} ObservationsRenderer.prototype = {}; ObservationsRenderer.prototype.constructor = ObservationsRenderer; ObservationsRenderer.render = function(cohort) { d3.selectAll("svg").remove(); var id = cohort.id; this.baseUrl = getSourceSpecificWebApiUrl() + 'cohortresults/' + id; var threshold; var datatable; // bind to all matching elements upon creation $(document).on('click', '#observation_table tbody tr', function () { $('#observation_table tbody tr.selected').removeClass('selected'); $(this).addClass('selected'); var data = datatable.data()[datatable.row(this)[0]]; if (data) { var did = data.concept_id; var concept_name = data.snomed; ObservationsRenderer.drilldown(did, concept_name); } }); $(document).on( 'shown.bs.tab', 'a[data-toggle="tab"]', function (e) { $(window).trigger("resize"); // Version 1. $('table:visible').each(function() { var oTableTools = TableTools.fnGetInstance(this); if (oTableTools && oTableTools.fnResizeRequired()) { oTableTools.fnResizeButtons(); } }); }); ObservationsRenderer.drilldown = function (concept_id, concept_name) { $('#loading-text').text("Querying Database..."); $('#spinner-modal').modal('show'); $('.drilldown svg').remove(); $('#observationDrilldownTitle').text(concept_name); $('#reportObservationDrilldown').removeClass('hidden'); $.ajax({ type: "GET", url: ObservationsRenderer.baseUrl + '/observation/' + concept_id, success: function (data) { $('#loading-text').text("Rendering Visualizations..."); if (data) { // age at first diagnosis visualization var firstDiagnosis = common.normalizeArray(data.ageAtFirstOccurrence); if (!firstDiagnosis.empty) { var ageAtFirstOccurrence = new jnj_chart.boxplot(); var bpseries = []; var bpdata = common.normalizeDataframe(firstDiagnosis); for (var i = 0; i < bpdata.category.length; i++) { bpseries.push({ Category: bpdata.category[i], min: bpdata.minValue[i], max: bpdata.maxValue[i], median: bpdata.medianValue[i], LIF: bpdata.p10Value[i], q1: bpdata.p25Value[i], q3: bpdata.p75Value[i], UIF: bpdata.p90Value[i] }); } ageAtFirstOccurrence.render(bpseries, "#ageAtFirstOccurrence", 500, 300, { xLabel: 'Gender', yLabel: 'Age at First Occurrence' }); } common.generateCSVDownload($("#ageAtFirstOccurrence"), data.ageAtFirstOccurrence, "ageAtFirstOccurrence"); // prevalence by month var prevData = common.normalizeArray(data.prevalenceByMonth); if (!prevData.empty) { var byMonthSeries = common.mapMonthYearDataToSeries(prevData, { dateField: 'xCalendarMonth', yValue: 'yPrevalence1000Pp', yPercent: 'yPrevalence1000Pp' }); var prevalenceByMonth = new jnj_chart.line(); prevalenceByMonth.render(byMonthSeries, "#observationPrevalenceByMonth", 1000, 300, { xScale: d3.time.scale().domain(d3.extent(byMonthSeries[0].values, function (d) { return d.xValue; })), xFormat: d3.time.format("%m/%Y"), tickFormat: function (d) { var monthFormat = d3.time.format("%m/%Y"); var yearFormat = d3.time.format("%Y"); return (d.getMonth() === 0) ? yearFormat(d) : monthFormat(d); }, xLabel: "Date", yLabel: "Prevalence per 1000 People" }); } common.generateCSVDownload($("#observationPrevalenceByMonth"), data.prevalenceByMonth, "observationPrevalenceByMonth"); // observation type visualization if (data.observationsByType && data.observationsByType.length > 0) { var observationsByType = new jnj_chart.donut(); observationsByType.render(common.mapConceptData(data.observationsByType), "#observationsByType", 500, 300, { margin: { top: 5, left: 5, right: 220, bottom: 5 } }); } common.generateCSVDownload($("#observationsByType"), data.observationsByType, "observationsByType"); // render trellis var trellisData = common.normalizeArray(data.prevalenceByGenderAgeYear, true); if (!trellisData.empty) { var allDeciles = ["0-9", "10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70-79", "80-89", "90-99"]; var allSeries = ["MALE", "FEMALE"]; var minYear = d3.min(trellisData.xCalendarYear), maxYear = d3.max(trellisData.xCalendarYear); var seriesInitializer = function (tName, sName, x, y) { return { trellisName: tName, seriesName: sName, xCalendarYear: x, yPrevalence1000Pp: y }; }; var nestByDecile = d3.nest() .key(function (d) { return d.trellisName; }) .key(function (d) { return d.seriesName; }) .sortValues(function (a, b) { return a.xCalendarYear - b.xCalendarYear; }); // map data into chartable form var normalizedSeries = trellisData.trellisName.map(function (d, i) { var item = {}; var container = this; d3.keys(container).forEach(function (p) { item[p] = container[p][i]; }); return item; }, trellisData); var dataByDecile = nestByDecile.entries(normalizedSeries); // fill in gaps var yearRange = d3.range(minYear, maxYear, 1); dataByDecile.forEach(function (trellis) { trellis.values.forEach(function (series) { series.values = yearRange.map(function (year) { yearData = series.values.filter(function (f) { return f.xCalendarYear === year; })[0] || seriesInitializer(trellis.key, series.key, year, 0); yearData.date = new Date(year, 0, 1); return yearData; }); }); }); // create svg with range bands based on the trellis names var chart = new jnj_chart.trellisline(); chart.render(dataByDecile, "#trellisLinePlot", 1000, 300, { trellisSet: allDeciles, trellisLabel: "Age Decile", seriesLabel: "Year of Observation", yLabel: "Prevalence Per 1000 People", xFormat: d3.time.format("%Y"), yFormat: d3.format("0.2f"), tickPadding: 20, colors: d3.scale.ordinal() .domain(["MALE", "FEMALE", "UNKNOWN",]) .range(["#1F78B4", "#FB9A99", "#33A02C"]) }); } common.generateCSVDownload($("#trellisLinePlot"), data.prevalenceByGenderAgeYear, "prevalenceByGenderAgeYear"); // Records by Unit var recordsByUnit = new jnj_chart.donut(); var datdaRecordsByUnit = []; var recordsByUnitData = common.normalizeArray(data.recordsByUnit); if (!recordsByUnitData.empty) { if (recordsByUnitData.conceptName instanceof Array) { datdaRecordsByUnit = recordsByUnitData.conceptName.map(function (d, i) { var item = { id: this.conceptName[i], label: this.conceptName[i], value: this.countValue[i] }; return item; }, recordsByUnitData); } else { datdaRecordsByUnit.push( { id: recordsByUnitData.conceptName, label: recordsByUnitData.conceptName, value: recordsByUnitData.countValue }); } datdaRecordsByUnit.sort(function (a, b) { var nameA = a.label.toLowerCase(), nameB = b.label.toLowerCase(); if (nameA < nameB) { //sort string ascending return -1; } if (nameA > nameB) { return 1; } return 0; //default return value (no sorting) }); recordsByUnit.render(datdaRecordsByUnit, "#recordsByUnit", 500, 300, { margin: { top: 5, left: 5, right: 200, bottom: 5 } }); } common.generateCSVDownload($("#recordsByUnit"), data.recordsByUnit, "recordsByUnit"); // Observation Value Distribution var obsValueDist = common.normalizeArray(data.observationValueDistribution); if (!obsValueDist.empty) { var observationValues = new jnj_chart.boxplot(); var obpseries = []; obpdata = common.normalizeDataframe(obsValueDist); obpseries = obpdata.category.map(function (d, i) { var item = { Category: obpdata.category[i], min: obpdata.minValue[i], max: obpdata.maxValue[i], median: obpdata.medianValue[i], LIF: obpdata.p10Value[i], q1: obpdata.p25Value[i], q3: obpdata.p75Value[i], UIF: obpdata.p90Value[i] }; return item; }, obpdata); observationValues.render(obpseries, "#observationValues", 500, 300, { yMax: d3.max(obpdata.p90Value) || obpdata.p90Value, // handle when dataframe is not array of values xLabel: 'Unit', yLabel: 'Observation Value' }); } common.generateCSVDownload($("#observationValues"), data.observationValueDistribution, "observationValues"); } $('#spinner-modal').modal('hide'); }, error : function() { $('#spinner-modal').modal('hide'); } }); }; function getColors(data) { /* console.log(data); if (data.length <= 3) { var colors = []; $.each(data, function() { var lbl = this.label.toLowerCase(); if (lbl.indexOf("above") >= 0 || lbl.indexOf("high") >= 0) { colors.push("#e31a1c"); } else if (lbl.indexOf("below") >= 0 || lbl.indexOf("low") >= 0) { colors.push("#1f78b4"); } else if (lbl.indexOf("normal") >= 0 || lbl.indexOf("within") >= 0) { colors.push("#33a02c"); } else { colors.push("#6a3d9a"); } }); console.log(colors); return colors; } */ return colorbrewer.Dark2[3]; } function buildHierarchyFromJSON(data, threshold) { var total = 0; var root = { "name": "root", "children": [] }; for (i = 0; i < data.percentPersons.length; i++) { total += data.percentPersons[i]; } for (var i = 0; i < data.conceptPath.length; i++) { var parts = data.conceptPath[i].split("||"); var currentNode = root; for (var j = 0; j < parts.length; j++) { var children = currentNode.children; var nodeName = parts[j]; var childNode; if (j + 1 < parts.length) { // Not yet at the end of the path; move down the tree. var foundChild = false; for (var k = 0; k < children.length; k++) { if (children[k].name === nodeName) { childNode = children[k]; foundChild = true; break; } } // If we don't already have a child node for this branch, create it. if (!foundChild) { childNode = { "name": nodeName, "children": [] }; children.push(childNode); } currentNode = childNode; } else { // Reached the end of the path; create a leaf node. childNode = { "name": nodeName, "num_persons": data.numPersons[i], "id": data.conceptId[i], "path": data.conceptPath[i], "pct_persons": data.percentPersons[i], "records_per_person": data.recordsPerPerson[i] }; // we only include nodes with sufficient size in the treemap display // sufficient size is configurable in the calculation of threshold // which is a function of the number of pixels in the treemap display if ((data.percentPersons[i] / total) > threshold) { children.push(childNode); } } } } return root; } // show the treemap $('#loading-text').text("Querying Database..."); $('#spinner-modal').modal('show'); var format_pct = d3.format('.2%'); var format_fixed = d3.format('.2f'); var format_comma = d3.format(','); $('#reportObservationOccurrences svg').remove(); var width = 1000; var height = 250; var minimum_area = 50; threshold = minimum_area / (width * height); $.ajax({ type: "GET", url: ObservationsRenderer.baseUrl + '/observation', contentType: "application/json; charset=utf-8", success: function (data) { $('#loading-text').text("Rendering Visualizations..."); var normalizedData = common.normalizeDataframe(common.normalizeArray(data, true)); data = normalizedData; if (!data.empty) { var table_data = normalizedData.conceptPath.map(function (d, i) { conceptDetails = this.conceptPath[i].split('||'); return { concept_id: this.conceptId[i], level_4: conceptDetails[0], level_3: conceptDetails[1], level_2: conceptDetails[2], observation_name: conceptDetails[3], num_persons: format_comma(this.numPersons[i]), percent_persons: format_pct(this.percentPersons[i]), records_per_person: format_fixed(this.recordsPerPerson[i]) }; }, data); datatable = $('#observation_table').DataTable({ order: [6, 'desc'], dom: 'T<"clear">lfrtip', data: table_data, columns: [ { data: 'concept_id' }, { data: 'level_4' }, { data: 'level_3', visible: false }, { data: 'level_2' }, { data: 'observation_name' }, { data: 'num_persons', className: 'numeric' }, { data: 'percent_persons', className: 'numeric' }, { data: 'records_per_person', className: 'numeric' } ], pageLength: 5, lengthChange: false, deferRender: true, destroy: true }); $('#reportObservationOccurrences').show(); tree = buildHierarchyFromJSON(data, threshold); var treemap = new jnj_chart.treemap(); treemap.render(tree, '#treemap_container', width, height, { onclick: function (node) { ObservationsRenderer.drilldown(node.id, node.name); }, getsizevalue: function (node) { return node.num_persons; }, getcolorvalue: function (node) { return node.records_per_person; }, getcolorrange: function() { return colorbrewer.Paired[3]; }, getcontent: function (node) { var result = '', steps = node.path.split('||'), i = steps.length - 1; result += '<div class="pathleaf">' + steps[i] + '</div>'; result += '<div class="pathleafstat">Prevalence: ' + format_pct(node.pct_persons) + '</div>'; result += '<div class="pathleafstat">Number of People: ' + format_comma(node.num_persons) + '</div>'; result += '<div class="pathleafstat">Records per Person: ' + format_fixed(node.records_per_person) + '</div>'; return result; }, gettitle: function (node) { var title = '', steps = node.path.split('||'); for (i = 0; i < steps.length - 1; i++) { title += ' <div class="pathstep">' + Array(i + 1).join('&nbsp;&nbsp') + steps[i] + ' </div>'; } return title; } }); $('[data-toggle="popover"]').popover(); } $('#spinner-modal').modal('hide'); }, error : function(data) { $('#spinner-modal').modal('hide'); } }); return ObservationsRenderer; }; return ObservationsRenderer; });
OHDSI/Olympus
src/main/webapp/Heracles/src/js/charts/observations.js
JavaScript
apache-2.0
25,745
/*global require*/ 'use strict'; // Require.js allows us to configure shortcut alias require.config({ // The shim config allows us to configure dependencies for // scripts that do not call define() to register a module shim: { underscore: { exports: '_' }, backbone: { deps: [ 'underscore', 'jquery' ] } }, paths: { jquery: '../lib/jquery/jquery', underscore: '../lib/underscore/underscore', backbone: '../lib/backbone/backbone', text: '../lib/requirejs-text/text', domReady:'../lib/requirejs-domReady/domReady', handlebars:'../lib/handlebars/handlebars' } }); require([ 'backbone' ], function (backbone) { /*jshint nonew:false*/ // Initialize routing and start Backbone.history() console.log("main被调用"); //new Workspace(); backbone.history.start(); // Initialize the application view //new AppView(); });
jiangjianqing/flow-demo
activiti/activiti5.springmvc/src/main/webapp/app/main.js
JavaScript
apache-2.0
867
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.fieldsConflictMessage = fieldsConflictMessage; exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged; var _error = require('../../error'); var _find = require('../../jsutils/find'); var _find2 = _interopRequireDefault(_find); var _kinds = require('../../language/kinds'); var _printer = require('../../language/printer'); var _definition = require('../../type/definition'); var _typeFromAST = require('../../utilities/typeFromAST'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * strict */ function fieldsConflictMessage(responseName, reason) { return 'Fields "' + responseName + '" conflict because ' + reasonMessage(reason) + '. Use different aliases on the fields to fetch both if this was ' + 'intentional.'; } function reasonMessage(reason) { if (Array.isArray(reason)) { return reason.map(function (_ref) { var responseName = _ref[0], subreason = _ref[1]; return 'subfields "' + responseName + '" conflict because ' + reasonMessage(subreason); }).join(' and '); } return reason; } /** * Overlapping fields can be merged * * A selection set is only valid if all fields (including spreading any * fragments) either correspond to distinct response names or can be merged * without ambiguity. */ function OverlappingFieldsCanBeMerged(context) { // A memoization for when two fragments are compared "between" each other for // conflicts. Two fragments may be compared many times, so memoizing this can // dramatically improve the performance of this validator. var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given // selection set. Selection sets may be asked for this information multiple // times, so this improves the performance of this validator. var cachedFieldsAndFragmentNames = new Map(); return { SelectionSet: function SelectionSet(selectionSet) { var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); conflicts.forEach(function (_ref2) { var _ref2$ = _ref2[0], responseName = _ref2$[0], reason = _ref2$[1], fields1 = _ref2[1], fields2 = _ref2[2]; return context.reportError(new _error.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2))); }); } }; } // Field name and reason. // Reason is a string, or a nested list of conflicts. // Tuple defining a field node in a context. // Map of array of those. /** * Algorithm: * * Conflicts occur when two fields exist in a query which will produce the same * response name, but represent differing values, thus creating a conflict. * The algorithm below finds all conflicts via making a series of comparisons * between fields. In order to compare as few fields as possible, this makes * a series of comparisons "within" sets of fields and "between" sets of fields. * * Given any selection set, a collection produces both a set of fields by * also including all inline fragments, as well as a list of fragments * referenced by fragment spreads. * * A) Each selection set represented in the document first compares "within" its * collected set of fields, finding any conflicts between every pair of * overlapping fields. * Note: This is the *only time* that a the fields "within" a set are compared * to each other. After this only fields "between" sets are compared. * * B) Also, if any fragment is referenced in a selection set, then a * comparison is made "between" the original set of fields and the * referenced fragment. * * C) Also, if multiple fragments are referenced, then comparisons * are made "between" each referenced fragment. * * D) When comparing "between" a set of fields and a referenced fragment, first * a comparison is made between each field in the original set of fields and * each field in the the referenced set of fields. * * E) Also, if any fragment is referenced in the referenced selection set, * then a comparison is made "between" the original set of fields and the * referenced fragment (recursively referring to step D). * * F) When comparing "between" two fragments, first a comparison is made between * each field in the first referenced set of fields and each field in the the * second referenced set of fields. * * G) Also, any fragments referenced by the first must be compared to the * second, and any fragments referenced by the second must be compared to the * first (recursively referring to step F). * * H) When comparing two fields, if both have selection sets, then a comparison * is made "between" both selection sets, first comparing the set of fields in * the first selection set with the set of fields in the second. * * I) Also, if any fragment is referenced in either selection set, then a * comparison is made "between" the other set of fields and the * referenced fragment. * * J) Also, if two fragments are referenced in both selection sets, then a * comparison is made "between" the two fragments. * */ // Find all conflicts found "within" a selection set, including those found // via spreading in fragments. Called when visiting each SelectionSet in the // GraphQL Document. function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { var conflicts = []; var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), fieldMap = _getFieldsAndFragment[0], fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. // Note: this is the *only place* `collectConflictsWithin` is called. collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); if (fragmentNames.length !== 0) { // (B) Then collect conflicts between these fields and those represented by // each spread fragment name found. var comparedFragments = Object.create(null); for (var i = 0; i < fragmentNames.length; i++) { collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this // selection set to collect conflicts between fragments spread together. // This compares each item in the list of fragment names to every other // item in that same list (except for itself). for (var j = i + 1; j < fragmentNames.length; j++) { collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); } } } return conflicts; } // Collect all conflicts found between a set of fields and a fragment reference // including via spreading in any nested fragments. function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { // Memoize so a fragment is not compared for conflicts more than once. if (comparedFragments[fragmentName]) { return; } comparedFragments[fragmentName] = true; var fragment = context.getFragment(fragmentName); if (!fragment) { return; } var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), fieldMap2 = _getReferencedFieldsA[0], fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. if (fieldMap === fieldMap2) { return; } // (D) First collect any conflicts between the provided collection of fields // and the collection of fields represented by the given fragment. collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields // and any fragment names found in the given fragment. for (var i = 0; i < fragmentNames2.length; i++) { collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); } } // Collect all conflicts found between two fragments, including via spreading in // any nested fragments. function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { // No need to compare a fragment to itself. if (fragmentName1 === fragmentName2) { return; } // Memoize so two fragments are not compared for conflicts more than once. if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { return; } comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); var fragment1 = context.getFragment(fragmentName1); var fragment2 = context.getFragment(fragmentName2); if (!fragment1 || !fragment2) { return; } var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), fieldMap1 = _getReferencedFieldsA2[0], fragmentNames1 = _getReferencedFieldsA2[1]; var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), fieldMap2 = _getReferencedFieldsA3[0], fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields // (not including any nested fragments). collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested // fragments spread in the second fragment. for (var j = 0; j < fragmentNames2.length; j++) { collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); } // (G) Then collect conflicts between the second fragment and any nested // fragments spread in the first fragment. for (var i = 0; i < fragmentNames1.length; i++) { collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); } } // Find all conflicts found between two selection sets, including those found // via spreading in fragments. Called when determining if conflicts exist // between the sub-fields of two overlapping fields. function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { var conflicts = []; var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), fieldMap1 = _getFieldsAndFragment2[0], fragmentNames1 = _getFieldsAndFragment2[1]; var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), fieldMap2 = _getFieldsAndFragment3[0], fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and // those referenced by each fragment name associated with the second. if (fragmentNames2.length !== 0) { var comparedFragments = Object.create(null); for (var j = 0; j < fragmentNames2.length; j++) { collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); } } // (I) Then collect conflicts between the second collection of fields and // those referenced by each fragment name associated with the first. if (fragmentNames1.length !== 0) { var _comparedFragments = Object.create(null); for (var i = 0; i < fragmentNames1.length; i++) { collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); } } // (J) Also collect conflicts between any fragment names by the first and // fragment names by the second. This compares each item in the first set of // names to each item in the second set of names. for (var _i = 0; _i < fragmentNames1.length; _i++) { for (var _j = 0; _j < fragmentNames2.length; _j++) { collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i], fragmentNames2[_j]); } } return conflicts; } // Collect all Conflicts "within" one collection of fields. function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { // A field map is a keyed collection, where each key represents a response // name and the value at that key is a list of all fields which provide that // response name. For every response name, if there are multiple fields, they // must be compared to find a potential conflict. Object.keys(fieldMap).forEach(function (responseName) { var fields = fieldMap[responseName]; // This compares every field in the list to every other field in this list // (except to itself). If the list only has one item, nothing needs to // be compared. if (fields.length > 1) { for (var i = 0; i < fields.length; i++) { for (var j = i + 1; j < fields.length; j++) { var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive responseName, fields[i], fields[j]); if (conflict) { conflicts.push(conflict); } } } } }); } // Collect all Conflicts between two collections of fields. This is similar to, // but different from the `collectConflictsWithin` function above. This check // assumes that `collectConflictsWithin` has already been called on each // provided collection of fields. This is true because this validator traverses // each individual selection set. function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { // A field map is a keyed collection, where each key represents a response // name and the value at that key is a list of all fields which provide that // response name. For any response name which appears in both provided field // maps, each field from the first field map must be compared to every field // in the second field map to find potential conflicts. Object.keys(fieldMap1).forEach(function (responseName) { var fields2 = fieldMap2[responseName]; if (fields2) { var fields1 = fieldMap1[responseName]; for (var i = 0; i < fields1.length; i++) { for (var j = 0; j < fields2.length; j++) { var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); if (conflict) { conflicts.push(conflict); } } } } }); } // Determines if there is a conflict between two particular fields, including // comparing their sub-fields. function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { var parentType1 = field1[0], node1 = field1[1], def1 = field1[2]; var parentType2 = field2[0], node2 = field2[1], def2 = field2[2]; // If it is known that two fields could not possibly apply at the same // time, due to the parent types, then it is safe to permit them to diverge // in aliased field or arguments used as they will not present any ambiguity // by differing. // It is known that two parent types could never overlap if they are // different Object types. Interface or Union types might overlap - if not // in the current state of the schema, then perhaps in some future version, // thus may not safely diverge. var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); // The return type for each field. var type1 = def1 && def1.type; var type2 = def2 && def2.type; if (!areMutuallyExclusive) { // Two aliases must refer to the same field. var name1 = node1.name.value; var name2 = node2.name.value; if (name1 !== name2) { return [[responseName, name1 + ' and ' + name2 + ' are different fields'], [node1], [node2]]; } // Two field calls must have the same arguments. if (!sameArguments(node1.arguments || [], node2.arguments || [])) { return [[responseName, 'they have differing arguments'], [node1], [node2]]; } } if (type1 && type2 && doTypesConflict(type1, type2)) { return [[responseName, 'they return conflicting types ' + String(type1) + ' and ' + String(type2)], [node1], [node2]]; } // Collect and compare sub-fields. Use the same "visited fragment names" list // for both collections so fields in a fragment reference are never // compared to themselves. var selectionSet1 = node1.selectionSet; var selectionSet2 = node2.selectionSet; if (selectionSet1 && selectionSet2) { var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); return subfieldConflicts(conflicts, responseName, node1, node2); } } function sameArguments(arguments1, arguments2) { if (arguments1.length !== arguments2.length) { return false; } return arguments1.every(function (argument1) { var argument2 = (0, _find2.default)(arguments2, function (argument) { return argument.name.value === argument1.name.value; }); if (!argument2) { return false; } return sameValue(argument1.value, argument2.value); }); } function sameValue(value1, value2) { return !value1 && !value2 || (0, _printer.print)(value1) === (0, _printer.print)(value2); } // Two types conflict if both types could not apply to a value simultaneously. // Composite types are ignored as their individual field types will be compared // later recursively. However List and Non-Null types must match. function doTypesConflict(type1, type2) { if ((0, _definition.isListType)(type1)) { return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; } if ((0, _definition.isListType)(type2)) { return true; } if ((0, _definition.isNonNullType)(type1)) { return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; } if ((0, _definition.isNonNullType)(type2)) { return true; } if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { return type1 !== type2; } return false; } // Given a selection set, return the collection of fields (a mapping of response // name to field nodes and definitions) as well as a list of fragment names // referenced via fragment spreads. function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { var cached = cachedFieldsAndFragmentNames.get(selectionSet); if (!cached) { var nodeAndDefs = Object.create(null); var fragmentNames = Object.create(null); _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); cached = [nodeAndDefs, Object.keys(fragmentNames)]; cachedFieldsAndFragmentNames.set(selectionSet, cached); } return cached; } // Given a reference to a fragment, return the represented collection of fields // as well as a list of nested fragment names referenced via fragment spreads. function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { // Short-circuit building a type from the node if possible. var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); if (cached) { return cached; } var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); } function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { for (var i = 0; i < selectionSet.selections.length; i++) { var selection = selectionSet.selections[i]; switch (selection.kind) { case _kinds.Kind.FIELD: var fieldName = selection.name.value; var fieldDef = void 0; if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { fieldDef = parentType.getFields()[fieldName]; } var responseName = selection.alias ? selection.alias.value : fieldName; if (!nodeAndDefs[responseName]) { nodeAndDefs[responseName] = []; } nodeAndDefs[responseName].push([parentType, selection, fieldDef]); break; case _kinds.Kind.FRAGMENT_SPREAD: fragmentNames[selection.name.value] = true; break; case _kinds.Kind.INLINE_FRAGMENT: var typeCondition = selection.typeCondition; var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); break; } } } // Given a series of Conflicts which occurred between two sub-fields, generate // a single Conflict. function subfieldConflicts(conflicts, responseName, node1, node2) { if (conflicts.length > 0) { return [[responseName, conflicts.map(function (_ref3) { var reason = _ref3[0]; return reason; })], conflicts.reduce(function (allFields, _ref4) { var fields1 = _ref4[1]; return allFields.concat(fields1); }, [node1]), conflicts.reduce(function (allFields, _ref5) { var fields2 = _ref5[2]; return allFields.concat(fields2); }, [node2])]; } } /** * A way to keep track of pairs of things when the ordering of the pair does * not matter. We do this by maintaining a sort of double adjacency sets. */ var PairSet = function () { function PairSet() { _classCallCheck(this, PairSet); this._data = Object.create(null); } PairSet.prototype.has = function has(a, b, areMutuallyExclusive) { var first = this._data[a]; var result = first && first[b]; if (result === undefined) { return false; } // areMutuallyExclusive being false is a superset of being true, // hence if we want to know if this PairSet "has" these two with no // exclusivity, we have to ensure it was added as such. if (areMutuallyExclusive === false) { return result === false; } return true; }; PairSet.prototype.add = function add(a, b, areMutuallyExclusive) { _pairSetAdd(this._data, a, b, areMutuallyExclusive); _pairSetAdd(this._data, b, a, areMutuallyExclusive); }; return PairSet; }(); function _pairSetAdd(data, a, b, areMutuallyExclusive) { var map = data[a]; if (!map) { map = Object.create(null); data[a] = map; } map[b] = areMutuallyExclusive; }
Khan/khan-linter
node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js
JavaScript
apache-2.0
25,753
/** * @preserve Copyright 2012 Martijn van de Rijdt & Modilabs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define( [ 'enketo-js/Widget', 'jquery', 'enketo-js/plugins' ], function( Widget, $ ) { 'use strict'; var pluginName = 'notewidget'; /** * Enhances notes * * @constructor * @param {Element} element [description] * @param {(boolean|{touch: boolean, repeat: boolean})} options options * @param {*=} e event */ function Notewidget( element, options ) { this.namespace = pluginName; Widget.call( this, element, options ); this._init(); } //copy the prototype functions from the Widget super class Notewidget.prototype = Object.create( Widget.prototype ); //ensure the constructor is the new one Notewidget.prototype.constructor = Notewidget; Notewidget.prototype._init = function() { var $el = $( this.element ); $el.find( '.question-label' ).markdownToHtml() .end().find( '[readonly]' ).addClass( 'ignore' ); if ( $el.is( '.note' ) && !$el.next().is( '.note' ) ) { $el.addClass( 'last-of-class' ); } }; Notewidget.prototype.destroy = function( element ) {}; $.fn[ pluginName ] = function( options, event ) { return this.each( function() { var $this = $( this ), data = $this.data( pluginName ); options = options || {}; if ( !data && typeof options === 'object' ) { $this.data( pluginName, ( data = new Notewidget( this, options, event ) ) ); } else if ( data && typeof options === 'string' ) { data[ options ]( this ); } } ); }; return pluginName; } );
alxndrsn/enketo-core
src/widget/note/notewidget.js
JavaScript
apache-2.0
2,293
/** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Blockly module for Node. It includes Blockly core, * built-in blocks, all the generators and the English locale. */ /* eslint-disable */ 'use strict'; // Include the EN Locale by default. Blockly.setLocale(En);
google/blockly
scripts/package/node/index.js
JavaScript
apache-2.0
339
// 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. // Copyright 2008 Google Inc. All Rights Reserved. /** * @fileoverview A class for managing the editor toolbar. * * @see ../../demos/editor/editor.html */ goog.provide('goog.ui.editor.ToolbarController'); goog.require('goog.editor.Field.EventType'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventTarget'); goog.require('goog.ui.Component.EventType'); /** * A class for managing the editor toolbar. Acts as a bridge between * a {@link goog.editor.Field} and a {@link goog.ui.Toolbar}. * * The {@code toolbar} argument must be an instance of {@link goog.ui.Toolbar} * or a subclass. This class doesn't care how the toolbar was created. As * long as one or more controls hosted in the toolbar have IDs that match * built-in {@link goog.editor.Command}s, they will function as expected. It is * the caller's responsibility to ensure that the toolbar is already rendered * or that it decorates an existing element. * * * @param {!goog.editor.Field} field Editable field to be controlled by the * toolbar. * @param {!goog.ui.Toolbar} toolbar Toolbar to control the editable field. * @constructor * @extends {goog.events.EventTarget} */ goog.ui.editor.ToolbarController = function(field, toolbar) { goog.events.EventTarget.call(this); /** * Event handler to listen for field events and user actions. * @type {!goog.events.EventHandler} * @private */ this.handler_ = new goog.events.EventHandler(this); /** * The field instance controlled by the toolbar. * @type {!goog.editor.Field} * @private */ this.field_ = field; /** * The toolbar that controls the field. * @type {!goog.ui.Toolbar} * @private */ this.toolbar_ = toolbar; /** * Editing commands whose state is to be queried when updating the toolbar. * @type {!Array.<string>} * @private */ this.queryCommands_ = []; // Iterate over all buttons, and find those which correspond to // queryable commands. Add them to the list of commands to query on // each COMMAND_VALUE_CHANGE event. this.toolbar_.forEachChild(function(button) { if (button.queryable) { this.queryCommands_.push(this.getComponentId(button.getId())); } }, this); // Make sure the toolbar doesn't steal keyboard focus. this.toolbar_.setFocusable(false); // Hook up handlers that update the toolbar in response to field events, // and to execute editor commands in response to toolbar events. this.handler_. listen(this.field_, goog.editor.Field.EventType.COMMAND_VALUE_CHANGE, this.updateToolbar). listen(this.toolbar_, goog.ui.Component.EventType.ACTION, this.handleAction); }; goog.inherits(goog.ui.editor.ToolbarController, goog.events.EventTarget); /** * Returns the Closure component ID of the control that corresponds to the * given {@link goog.editor.Command} constant. * Subclasses may override this method if they want to use a custom mapping * scheme from commands to controls. * @param {string} command Editor command. * @return {string} Closure component ID of the corresponding toolbar * control, if any. * @protected */ goog.ui.editor.ToolbarController.prototype.getComponentId = function(command) { // The default implementation assumes that the component ID is the same as // the command constant. return command; }; /** * Returns the {@link goog.editor.Command} constant * that corresponds to the given Closure component ID. Subclasses may override * this method if they want to use a custom mapping scheme from controls to * commands. * @param {string} id Closure component ID of a toolbar control. * @return {string} Editor command or dialog constant corresponding to the * toolbar control, if any. * @protected */ goog.ui.editor.ToolbarController.prototype.getCommand = function(id) { // The default implementation assumes that the component ID is the same as // the command constant. return id; }; /** * Returns the event handler object for the editor toolbar. Useful for classes * that extend {@code goog.ui.editor.ToolbarController}. * @return {!goog.events.EventHandler} The event handler object. * @protected */ goog.ui.editor.ToolbarController.prototype.getHandler = function() { return this.handler_; }; /** * Returns the field instance managed by the toolbar. Useful for * classes that extend {@code goog.ui.editor.ToolbarController}. * @return {!goog.editor.Field} The field managed by the toolbar. * @protected */ goog.ui.editor.ToolbarController.prototype.getField = function() { return this.field_; }; /** * Returns the toolbar UI component that manages the editor. Useful for * classes that extend {@code goog.ui.editor.ToolbarController}. * @return {!goog.ui.Toolbar} The toolbar UI component. */ goog.ui.editor.ToolbarController.prototype.getToolbar = function() { return this.toolbar_; }; /** * @return {boolean} Whether the toolbar is visible. */ goog.ui.editor.ToolbarController.prototype.isVisible = function() { return this.toolbar_.isVisible(); }; /** * Shows or hides the toolbar. * @param {boolean} visible Whether to show or hide the toolbar. */ goog.ui.editor.ToolbarController.prototype.setVisible = function(visible) { this.toolbar_.setVisible(visible); }; /** * @return {boolean} Whether the toolbar is enabled. */ goog.ui.editor.ToolbarController.prototype.isEnabled = function() { return this.toolbar_.isEnabled(); }; /** * Enables or disables the toolbar. * @param {boolean} enabled Whether to enable or disable the toolbar. */ goog.ui.editor.ToolbarController.prototype.setEnabled = function(enabled) { this.toolbar_.setEnabled(enabled); }; /** * Programmatically blurs the editor toolbar, un-highlighting the currently * highlighted item, and closing the currently open menu (if any). */ goog.ui.editor.ToolbarController.prototype.blur = function() { // We can't just call this.toolbar_.getElement().blur(), because the toolbar // element itself isn't focusable, so goog.ui.Container#handleBlur isn't // registered to handle blur events. this.toolbar_.handleBlur(null); }; /** @inheritDoc */ goog.ui.editor.ToolbarController.prototype.disposeInternal = function() { goog.ui.editor.ToolbarController.superClass_.disposeInternal.call(this); if (this.handler_) { this.handler_.dispose(); delete this.handler_; } if (this.toolbar_) { this.toolbar_.dispose(); delete this.toolbar_; } delete this.field_; delete this.queryCommands_; }; /** * Updates the toolbar in response to editor events. Specifically, updates * button states based on {@code COMMAND_VALUE_CHANGE} events, reflecting the * effective formatting of the selection. * @param {goog.events.Event} e Editor event to handle. * @protected */ goog.ui.editor.ToolbarController.prototype.updateToolbar = function(e) { if (!this.toolbar_.isEnabled() || !this.dispatchEvent(goog.ui.Component.EventType.CHANGE)) { return; } var state; /** @preserveTry */ try { /** @type {Array.<string>} */ e.commands; // Added by dispatchEvent. // If the COMMAND_VALUE_CHANGE event specifies which commands changed // state, then we only need to update those ones, otherwise update all // commands. state = /** @type {Object} */ ( this.field_.queryCommandValue(e.commands || this.queryCommands_)); } catch (ex) { // TODO: Find out when/why this happens. state = {}; } this.updateToolbarFromState(state); }; /** * Updates the toolbar to reflect a given state. * @param {Object} state Object mapping editor commands to values. */ goog.ui.editor.ToolbarController.prototype.updateToolbarFromState = function(state) { for (var command in state) { var button = this.toolbar_.getChild(this.getComponentId(command)); if (button) { var value = state[command]; if (button.updateFromValue) { button.updateFromValue(value); } else { button.setChecked(!!value); } } } }; /** * Handles {@code ACTION} events dispatched by toolbar buttons in response to * user actions by executing the corresponding field command. * @param {goog.events.Event} e Action event to handle. * @protected */ goog.ui.editor.ToolbarController.prototype.handleAction = function(e) { var command = this.getCommand(e.target.getId()); this.field_.execCommand(command, e.target.getValue()); };
jay-hodgson/SynapseWebClient
src/main/webapp/js/goog/ui/editor/toolbarcontroller.js
JavaScript
apache-2.0
9,007
//// [invalidTaggedTemplateEscapeSequences.ts] function tag (str: any, ...args: any[]): any { return str } const a = tag`123` const b = tag`123 ${100}` const x = tag`\u{hello} ${ 100 } \xtraordinary ${ 200 } wonderful ${ 300 } \uworld`; const y = `\u{hello} ${ 100 } \xtraordinary ${ 200 } wonderful ${ 300 } \uworld`; // should error with NoSubstitutionTemplate const z = tag`\u{hello} \xtraordinary wonderful \uworld` // should work with Tagged NoSubstitutionTemplate const a1 = tag`${ 100 }\0` // \0 const a2 = tag`${ 100 }\00` // \\00 const a3 = tag`${ 100 }\u` // \\u const a4 = tag`${ 100 }\u0` // \\u0 const a5 = tag`${ 100 }\u00` // \\u00 const a6 = tag`${ 100 }\u000` // \\u000 const a7 = tag`${ 100 }\u0000` // \u0000 const a8 = tag`${ 100 }\u{` // \\u{ const a9 = tag`${ 100 }\u{10FFFF}` // \\u{10FFFF const a10 = tag`${ 100 }\u{1f622` // \\u{1f622 const a11 = tag`${ 100 }\u{1f622}` // \u{1f622} const a12 = tag`${ 100 }\x` // \\x const a13 = tag`${ 100 }\x0` // \\x0 const a14 = tag`${ 100 }\x00` // \x00 //// [invalidTaggedTemplateEscapeSequences.js] var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function tag(str) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } return str; } var a = tag(__makeTemplateObject(["123"], ["123"])); var b = tag(__makeTemplateObject(["123 ", ""], ["123 ", ""]), 100); var x = tag(__makeTemplateObject([void 0, void 0, " wonderful ", void 0], ["\\u{hello} ", " \\xtraordinary ", " wonderful ", " \\uworld"]), 100, 200, 300); var y = "hello} ".concat(100, " traordinary ").concat(200, " wonderful ").concat(300, " world"); // should error with NoSubstitutionTemplate var z = tag(__makeTemplateObject([void 0], ["\\u{hello} \\xtraordinary wonderful \\uworld"])); // should work with Tagged NoSubstitutionTemplate var a1 = tag(__makeTemplateObject(["", "\0"], ["", "\\0"]), 100); // \0 var a2 = tag(__makeTemplateObject(["", void 0], ["", "\\00"]), 100); // \\00 var a3 = tag(__makeTemplateObject(["", void 0], ["", "\\u"]), 100); // \\u var a4 = tag(__makeTemplateObject(["", void 0], ["", "\\u0"]), 100); // \\u0 var a5 = tag(__makeTemplateObject(["", void 0], ["", "\\u00"]), 100); // \\u00 var a6 = tag(__makeTemplateObject(["", void 0], ["", "\\u000"]), 100); // \\u000 var a7 = tag(__makeTemplateObject(["", "\0"], ["", "\\u0000"]), 100); // \u0000 var a8 = tag(__makeTemplateObject(["", void 0], ["", "\\u{"]), 100); // \\u{ var a9 = tag(__makeTemplateObject(["", "\uDBFF\uDFFF"], ["", "\\u{10FFFF}"]), 100); // \\u{10FFFF var a10 = tag(__makeTemplateObject(["", void 0], ["", "\\u{1f622"]), 100); // \\u{1f622 var a11 = tag(__makeTemplateObject(["", "\uD83D\uDE22"], ["", "\\u{1f622}"]), 100); // \u{1f622} var a12 = tag(__makeTemplateObject(["", void 0], ["", "\\x"]), 100); // \\x var a13 = tag(__makeTemplateObject(["", void 0], ["", "\\x0"]), 100); // \\x0 var a14 = tag(__makeTemplateObject(["", "\0"], ["", "\\x00"]), 100); // \x00
microsoft/TypeScript
tests/baselines/reference/invalidTaggedTemplateEscapeSequences(target=es5).js
JavaScript
apache-2.0
3,182
L.Polygon.polygonEditor = L.Polygon.extend({ _prepareMapIfNeeded: function() { var that = this; if(this._map._editablePolygons != null) { return; } // Container for all editable polylines on this map: this._map._editablePolygons = []; // Click anywhere on map to add a new point-polyline: if(this._options.newPolygons) { // console.log('click na map'); that._map.on('click', function(event) { // console.log('click, target=' + (event.target == that._map) + ' type=' + event.type); if(that.isBusy()) return; that._setBusy(true); var latLng = event.latlng; if(that._options.newPolygonConfirmMessage) if(!confirm(that._options.newPolygonConfirmMessage)) return var contexts = [{'originalPolygonNo': null, 'originalPointNo': null}]; L.Polygon.PolygonEditor([latLng], that._options, contexts).addTo(that._map); that._setBusy(false); that._showBoundMarkers(); }); } }, /** * Will add all needed methods to this polyline. */ _addMethods: function() { var that = this; this._init = function(options, contexts) { this._prepareMapIfNeeded(); /* * Utility method added to this map to retreive editable * polylines. */ if(!this._map.getEditablePolylines) { this._map.getEditablePolylines = function() { return that._map._editablePolygons; } } /** * Since all point editing is done by marker events, markers * will be the main holder of the polyline points locations. * Every marker contains a reference to the newPointMarker * *before* him (=> the first marker has newPointMarker=null). */ this._parseOptions(options); this._setMarkers(); var map = this._map; this._map.on("zoomend", function(e) { that._showBoundMarkers(); }); this._map.on("moveend", function(e) { that._showBoundMarkers(); }); this._lastMouseEvent = undefined; if('_desiredPolygonNo' in this) { this._map._editablePolygons.splice(this._desiredPolygonNo, 0, this); } else { this._map._editablePolygons.push(this); } }; /** * Check if there is *any* busy editable polyline on this map. */ this.isBusy = function() { for(var i = 0; i < that._map._editablePolygons.length; i++) if(that._map._editablePolygons[i]._isBusy()) return true; return false; }; /** * Check if is busy adding/moving new nodes. Note, there may be * *other* editable polylines on the same map which *are* busy. */ this._isBusy = function() { return that._busy; }; this._setBusy = function(busy) { that._busy = busy; }; /** * Get markers for this polyline. */ this.getPoints = function() { return this._markers; }; this._parseOptions = function(options) { if(!options) options = {}; // Do not show edit markers if more than maxMarkers would be shown: if(!('maxMarkers' in options)) { options.maxMarkers = 100; } this.maxMarkers = options.maxMarkers; // Do not allow edges to be destroyed (split polygon in two) if(!('deletableEdges' in options)) { options.deletableEdges = false; } this.deletableEdges = options.deletableEdges; // Icons: if(options.pointIcon) { this.pointIcon = options.pointIcon; } else { this.pointIcon = L.icon({ iconUrl: 'editmarker.png', iconSize: [11, 11], iconAnchor: [6, 6] }); } if(options.newPointIcon) { this.newPointIcon = options.newPointIcon; } else { this.newPointIcon = L.icon({ iconUrl: 'editmarker2.png', iconSize: [11, 11], iconAnchor: [6, 6] }); } }; /** * Show only markers in current map bounds *is* there are only a certain * number of markers. This method is called on eventy that change map * bounds. */ this._showBoundMarkers = function() { if(that.isBusy()) { //console.log('Do not show because busy!'); return; } var bounds = that._map.getBounds(); var found = 0; for(var polygonNo in that._map._editablePolygons) { var polyline = that._map._editablePolygons[polygonNo]; for(var markerNo in polyline._markers) { var marker = polyline._markers[markerNo]; if(bounds.contains(marker.getLatLng())) found += 1; } } //console.log('found=' + found); for(var polygonNo in that._map._editablePolygons) { var polyline = that._map._editablePolygons[polygonNo]; for(var markerNo in polyline._markers) { var marker = polyline._markers[markerNo]; if(found < that.maxMarkers) { that._setMarkerVisible(marker, bounds.contains(marker.getLatLng())); that._setMarkerVisible(marker.newPointMarker, bounds.contains(marker.getLatLng())); } else { that._setMarkerVisible(marker, false); that._setMarkerVisible(marker.newPointMarker, false); } } } }; /** * Used when adding/moving points in order to disable the user to mess * with other markers (+ easier to decide where to put the point * without too many markers). */ this._hideAll = function(except) { for(var polygonNo in that._map._editablePolygons) { //console.log("hide " + polygonNo + " markers"); var polyline = that._map._editablePolygons[polygonNo]; for(var markerNo in polyline._markers) { var marker = polyline._markers[markerNo]; if(except == null || except != marker) polyline._setMarkerVisible(marker, false); if(except == null || except != marker.newPointMarker) polyline._setMarkerVisible(marker.newPointMarker, false); } } } /** * Show/hide marker. */ this._setMarkerVisible = function(marker, show) { if(!marker) return; var map = this._map; if(show) { if(!marker._visible) { if(!marker._map) { // First show fo this marker: marker.addTo(map); } else { // Marker was already shown and hidden: map.addLayer(marker); } marker._map = map; } marker._visible = true; } else { if(marker._visible) { map.removeLayer(marker); } marker._visible = false; } }; this.updateLatLngs = function (latlngs) { this._eraseMarkers(); this.setLatLngs(latlngs); that._setMarkers(); this._reloadPolygon(); return this; } /** * Reload polyline. If it is busy, then the bound markers will not be * shown. Call _setBusy(false) before this method! */ this._reloadPolygon = function(fixAroundPointNo) { // that._setMarkers(); that.setLatLngs(that._getMarkerLatLngs()); if(fixAroundPointNo != null) that._fixNeighbourPositions(fixAroundPointNo); that._showBoundMarkers(); } /** * Reload polyline. If it is busy, then the bound markers will not be * shown. Call _setBusy(false) before this method! */ this._setMarkers = function() { this._markers = []; var that = this; var points = this.getLatLngs(); var length = points.length; for(var i = 0; i < length; i++) { var marker = this._addMarkers(i, points[i]); if(! ('context' in marker)) { marker.context = {} if(that._contexts != null) { marker.context = contexts[i]; } } if(marker.context && ! ('originalPointNo' in marker.context)) marker.context.originalPointNo = i; if(marker.context && ! ('originalPolygonNo' in marker.context)) marker.context.originalPolygonNo = that._map._editablePolygons.length; } } /** * Reload polyline. If it is busy, then the bound markers will not be * shown. Call _setBusy(false) before this method! */ this._eraseMarkers = function() { var that = this; var points = this._markers; var length = points.length; for(var i = 0; i < length; i++) { var marker = points[i]; this._map.removeLayer(marker.newPointMarker); this._map.removeLayer(marker); } this._markers = []; } /** * Add two markers (a point marker and his newPointMarker) for a * single point. * * Markers are not added on the map here, the marker.addTo(map) is called * only later when needed first time because of performance issues. */ this._addMarkers = function(pointNo, latLng, fixNeighbourPositions) { var that = this; var points = this.getLatLngs(); var marker = L.marker(latLng, {draggable: true, icon: this.pointIcon}); marker.newPointMarker = null; marker.on('mousedown', function (e) { that._lastMouseEvent = e.originalEvent; }); marker.on('dragstart', function(event) { var pointNo = that._getPointNo(event.target); //console.log("pointNo", pointNo); var previousPoint = pointNo == null ? null : (pointNo - 1 >= 0 ? that._markers[pointNo - 1].getLatLng() : that._markers[that._markers.length - 1].getLatLng()); var nextPoint = pointNo < that._markers.length - 1 ? that._markers[pointNo + 1].getLatLng() : that._markers[0].getLatLng(); that._edited = true; that._setupDragLines(marker, previousPoint, nextPoint); that._setBusy(true); that._hideAll(marker); }); marker.on('dragend', function(event) { that._lastMouseEvent = undefined; var marker = event.target; var pointNo = that._getPointNo(event.target); setTimeout(function() { that._setBusy(false); that._reloadPolygon(pointNo); }, 25); }); // deleting in click and context menu to allow for touch device tap-to-remove marker.on('contextmenu dblclick', function(event) { var corners = that._markers.length; if (corners <= 3) return; var marker = event.target; var pointNo = that._getPointNo(event.target); //console.log("corners:", corners, "pointNo:", pointNo); that._edited = true; that._map.removeLayer(marker); that._map.removeLayer(newPointMarker); that._markers.splice(pointNo, 1); that._reloadPolygon(pointNo); }); var previousPoint = points[pointNo == 0 ? points.length - 1 : pointNo - 1]; var newPointMarker = L.marker([(latLng.lat + previousPoint.lat) / 2., (latLng.lng + previousPoint.lng) / 2.], {draggable: true, icon: this.newPointIcon}); marker.newPointMarker = newPointMarker; newPointMarker.on('dragstart', function(event) { that._lastMouseEvent = event.originalEvent; var pointNo = that._getPointNo(event.target); //console.log("pointNo", pointNo); var previousPoint = pointNo - 1 >= 0 ? that._markers[pointNo - 1].getLatLng() : that._markers[that._markers.length - 1].getLatLng(); var nextPoint = that._markers[pointNo].getLatLng(); that._edited = true; that._setupDragLines(marker.newPointMarker, previousPoint, nextPoint); that._setBusy(true); that._hideAll(marker.newPointMarker); }); newPointMarker.on('dragend', function(event) { // console.log("dragend", event); var marker = event.target; var pointNo = that._getPointNo(event.target); that._addMarkers(pointNo, marker.getLatLng(), true); setTimeout(function() { that._setBusy(false); that._reloadPolygon(); }, 25); }); newPointMarker.on('click', function(event) { // console.log("click", event); var marker = event.target; var pointNo = that._getPointNo(event.target); that._addMarkers(pointNo, marker.getLatLng(), true); setTimeout(function() { that._reloadPolygon(); }, 25); }); // if (this._options.deletableEdges) { // newPointMarker.on('contextmenu', function(event) { // // 1. Remove this polyline from map // var marker = event.target; // var pointNo = that._getPointNo(marker); // var markers = that.getPoints(); // that._hideAll(); // var secondPartMarkers = that._markers.slice(pointNo, pointNo.length); // that._markers.splice(pointNo, that._markers.length - pointNo); // that._reloadPolygon(); // var points = []; // var contexts = []; // for(var i = 0; i < secondPartMarkers.length; i++) { // var marker = secondPartMarkers[i]; // points.push(marker.getLatLng()); // contexts.push(marker.context); // } // //console.log('points:' + points); // //console.log('contexts:' + contexts); // // Need to know the current polyline order numbers, because // // the splitted one need to be inserted immediately after: // var originalPolygonNo = that._map._editablePolygons.indexOf(that); // var newPolygon = L.Polygon.PolygonEditor(points, that._options, contexts, originalPolygonNo + 1) // .addTo(that._map); // that._showBoundMarkers(); // //console.log('Done split, _editablePolygons now:' + that._map._editablePolygons.length); // }); // } this._markers.splice(pointNo, 0, marker); if(fixNeighbourPositions) { this._fixNeighbourPositions(pointNo); } return marker; }; /** * Fix nearby new point markers when the new point is created. */ this._fixNeighbourPositions = function(pointNo) { var previousMarker = pointNo == 0 ? this._markers[this._markers.length - 1] : this._markers[pointNo - 1]; var marker = this._markers[pointNo]; var nextMarker = pointNo < this._markers.length - 1 ? this._markers[pointNo + 1] : this._markers[0]; //console.log("_fixNeighbourPositions:", pointNo, this._markers.length); //console.log("markers:", marker, previousMarker, nextMarker); if(!marker && previousMarker && nextMarker) { // //console.log("last point deleted!"); nextMarker.newPointMarker.setLatLng([(previousMarker.getLatLng().lat + nextMarker.getLatLng().lat) / 2., (previousMarker.getLatLng().lng + nextMarker.getLatLng().lng) / 2.]); } if(marker && previousMarker) { // //console.log("marker && previousMarker"); marker.newPointMarker.setLatLng([(previousMarker.getLatLng().lat + marker.getLatLng().lat) / 2., (previousMarker.getLatLng().lng + marker.getLatLng().lng) / 2.]); } if(marker && nextMarker) { // //console.log("marker && nextMarker"); nextMarker.newPointMarker.setLatLng([(marker.getLatLng().lat + nextMarker.getLatLng().lat) / 2., (marker.getLatLng().lng + nextMarker.getLatLng().lng) / 2.]); } }; /** * Find the order number of the marker. */ this._getPointNo = function(marker) { for(var i = 0; i < this._markers.length; i++) { if(marker == this._markers[i] || marker == this._markers[i].newPointMarker) { return i; } } return -1; }; /** * Get polyline latLngs based on marker positions. */ this._getMarkerLatLngs = function() { var result = []; for(var i = 0; i < this._markers.length; i++) result.push(this._markers[i].getLatLng()); return result; }; this._setupDragLines = function(marker, point1, point2) { // //console.log("_setupDragLines", marker, point1, point2); var line1 = null; var line2 = null; var markerLatlng = marker.getLatLng(); var offsetLat = 0; var offsetLng = 0; if (this._lastMouseEvent) { var mousePoint = this._map.mouseEventToLatLng(this._lastMouseEvent); offsetLat = markerLatlng.lat - mousePoint.lat; offsetLng = markerLatlng.lng - mousePoint.lng; // console.log(markerLatlng, mouseLatlng); } // console.log(markerLatlng, this._lastMouseEvent); if(point1) line1 = L.polyline([markerLatlng, point1], {dashArray: "5,5", weight: 1}) .addTo(that._map); if(point2) line2 = L.polyline([markerLatlng, point1], {dashArray: "5,5", weight: 1}) .addTo(that._map); var moveHandler = function(event) { // add the offsets from the marker // so aux lines appear in the tip of the marker var latlngPoint = L.latLng(event.latlng.lat + offsetLat, event.latlng.lng + offsetLng); if(line1) line1.setLatLngs([latlngPoint, point1]); if(line2) line2.setLatLngs([latlngPoint, point2]); }; var stopHandler = function(event) { that._map.off('mousemove', moveHandler); marker.off('dragend', stopHandler); if(line1) that._map.removeLayer(line1); if(line2) that._map.removeLayer(line2); //console.log('STOPPED'); if(event.target != that._map) { that._map.fire('click', event); } }; that._map.on('mousemove', moveHandler); marker.on('dragend', stopHandler); that._map.once('click', stopHandler); marker.once('click', stopHandler); if(line1) line1.once('click', stopHandler); if(line2) line2.once('click', stopHandler); } } }); L.Polygon.polygonEditor.addInitHook(function () { // Hack to keep reference to map: this.originalAddTo = this.addTo; this.addTo = function(map) { this.originalAddTo(map); this._map = map; this._addMethods(); /** * When addint a new point we must disable the user to mess with other * markers. One way is to check everywhere if the user is busy. The * other is to just remove other markers when the user is doing * somethinng. * * TODO: Decide the right way to do this and then leave only _busy or * _hideAll(). */ this._busy = false; this._initialized = false; this._edited = false; this._init(this._options, this._contexts); this._initialized = true; return this; }; }); /** * Construct a new editable polyline. * * latlngs ... a list of points (or two-element tuples with coordinates) * options ... polyline options * contexts ... custom contexts for every point in the polyline. Must have the * same number of elements as latlngs and this data will be * preserved when new points are added or polylines splitted. * polygonNo ... insert this polyline in a specific order (used when splitting). * * More about contexts: * This is an array of objects that will be kept as "context" for every * point. Marker will keep this value as marker.context. New markers will * have context set to null. * * Contexts must be the same size as the polyline size! * * By default, even without calling this method -- every marker will have * context with one value: marker.context.originalPointNo with the * original order number of this point. The order may change if some * markers before this one are delted or new added. */ L.Polygon.PolygonEditor = function(latlngs, options, contexts, polygonNo) { var result = new L.Polygon.polygonEditor(latlngs, options); result._options = options; result._contexts = contexts; result._desiredPolygonNo = polygonNo return result; };
NYPL/building-inspector
app/assets/javascripts/lib/vendor/leaflet-editable-polygon.js
JavaScript
apache-2.0
23,188
(function () { 'use strict'; angular.module('horizon.framework.widgets.help-panel', []) .directive('helpPanel', ['horizon.framework.widgets.basePath', function (path) { return { templateUrl: path + 'help-panel/help-panel.html', transclude: true }; } ]); })();
Hodorable/0602
horizon/static/framework/widgets/help-panel/help-panel.js
JavaScript
apache-2.0
321
/* * 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'; /** * The Operations Management Suite (OMS) parameters. * */ class ClusterMonitoringRequest { /** * Create a ClusterMonitoringRequest. * @property {string} [workspaceId] The Operations Management Suite (OMS) * workspace ID. * @property {string} [primaryKey] The Operations Management Suite (OMS) * workspace key. */ constructor() { } /** * Defines the metadata of ClusterMonitoringRequest * * @returns {object} metadata of ClusterMonitoringRequest * */ mapper() { return { required: false, serializedName: 'ClusterMonitoringRequest', type: { name: 'Composite', className: 'ClusterMonitoringRequest', modelProperties: { workspaceId: { required: false, serializedName: 'workspaceId', type: { name: 'String' } }, primaryKey: { required: false, serializedName: 'primaryKey', type: { name: 'String' } } } } }; } } module.exports = ClusterMonitoringRequest;
xingwu1/azure-sdk-for-node
lib/services/hdInsightManagement/lib/models/clusterMonitoringRequest.js
JavaScript
apache-2.0
1,464
/** * Copyright 2016 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const ExternalAnchorsAudit = require('../../../audits/dobetterweb/external-anchors-use-rel-noopener.js'); const assert = require('assert'); const URL = 'https://google.com/test'; /* eslint-env mocha */ describe('External anchors use rel="noopener"', () => { it('passes when links are from same hosts as the page host', () => { const auditResult = ExternalAnchorsAudit.audit({ AnchorsWithNoRelNoopener: [ {href: 'https://google.com/test'}, {href: 'https://google.com/test1'} ], URL: {finalUrl: URL}, }); assert.equal(auditResult.rawValue, true); assert.equal(auditResult.extendedInfo.value.length, 0); }); it('fails when links are from different hosts than the page host', () => { const auditResult = ExternalAnchorsAudit.audit({ AnchorsWithNoRelNoopener: [ {href: 'https://example.com/test'}, {href: 'https://example.com/test1'} ], URL: {finalUrl: URL}, }); assert.equal(auditResult.rawValue, false); assert.equal(auditResult.extendedInfo.value.length, 2); }); it('handles links with no href attribute', () => { const auditResult = ExternalAnchorsAudit.audit({ AnchorsWithNoRelNoopener: [ {href: ''}, {href: 'http://'}, {href: 'http:'} ], URL: {finalUrl: URL}, }); assert.equal(auditResult.rawValue, false); assert.equal(auditResult.extendedInfo.value.length, 3); assert.ok(auditResult.debugString, 'includes debugString'); }); });
cedricbellet/lighthouse
lighthouse-core/test/audits/dobetterweb/external-anchors-use-rel-noopener-test.js
JavaScript
apache-2.0
2,145
/* * Copyright 2014-2018 the original author or authors. * * 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 subscribing from '@/mixins/subscribing'; import {timer} from '@/utils/rxjs'; import moment from 'moment'; export default { props: ['value'], mixins: [subscribing], data: () => ({ startTs: null, offset: null }), render() { return this._v(this.clock); }, computed: { clock() { if (!this.value) { return null; } const duration = moment.duration(this.value + this.offset); return `${Math.floor(duration.asDays())}d ${duration.hours()}h ${duration.minutes()}m ${duration.seconds()}s`; } }, watch: { value: 'subscribe' }, methods: { createSubscription() { if (this.value) { const vm = this; vm.startTs = moment(); vm.offset = 0; return timer(0, 1000).subscribe({ next: () => { vm.offset = moment().valueOf() - vm.startTs.valueOf(); } }) } } } }
codecentric/spring-boot-admin
spring-boot-admin-server-ui/src/main/frontend/views/instances/details/process-uptime.js
JavaScript
apache-2.0
1,540
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), os = require("os"), readline = require("readline"), deferral = ctx.requireCordovaModule('q').defer(); var lineReader = readline.createInterface({ terminal: false, input : fs.createReadStream('platforms/android/build.gradle') }); lineReader.on("line", function(line) { fs.appendFileSync('./build.gradle', line.toString() + os.EOL); if (/.*\ dependencies \{.*/.test(line)) { fs.appendFileSync('./build.gradle', '\t\tclasspath "com.google.gms:google-services:3.0.0"' + os.EOL); } }).on("close", function () { fs.rename('./build.gradle', 'platforms/android/build.gradle', deferral.resolve); }); return deferral.promise; };
alfredo777/btmglobalconsulting
plugins/phonegap-plugin-push/scripts/copyAndroidFile.js
JavaScript
apache-2.0
856
/** * This module sets default values and validates ortb2 first part data * @module modules/firstPartyData */ import { config } from '../../src/config.js'; import * as utils from '../../src/utils.js'; import { ORTB_MAP } from './config.js'; import { submodule } from '../../src/hook.js'; import { getStorageManager } from '../../src/storageManager.js'; const STORAGE = getStorageManager(); let optout; /** * Check if data passed is empty * @param {*} value to test against * @returns {Boolean} is value empty */ function isEmptyData(data) { let check = true; if (typeof data === 'object' && !utils.isEmpty(data)) { check = false; } else if (typeof data !== 'object' && (utils.isNumber(data) || data)) { check = false; } return check; } /** * Check if required keys exist in data object * @param {Object} data object * @param {Array} array of required keys * @param {String} object path (for printing warning) * @param {Number} index of object value in the data array (for printing warning) * @returns {Boolean} is requirements fulfilled */ function getRequiredData(obj, required, parent, i) { let check = true; required.forEach(key => { if (!obj[key] || isEmptyData(obj[key])) { check = false; utils.logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: missing required property ${key}`); } }); return check; } /** * Check if data type is valid * @param {*} value to test against * @param {Object} object containing type definition and if should be array bool * @returns {Boolean} is type fulfilled */ function typeValidation(data, mapping) { let check = false; switch (mapping.type) { case 'string': if (typeof data === 'string') check = true; break; case 'number': if (typeof data === 'number' && isFinite(data)) check = true; break; case 'object': if (typeof data === 'object') { if ((Array.isArray(data) && mapping.isArray) || (!Array.isArray(data) && !mapping.isArray)) check = true; } break; } return check; } /** * Validates ortb2 data arrays and filters out invalid data * @param {Array} ortb2 data array * @param {Object} object defining child type and if array * @param {String} config path of data array * @param {String} parent path for logging warnings * @returns {Array} validated/filtered data */ export function filterArrayData(arr, child, path, parent) { arr = arr.filter((index, i) => { let check = typeValidation(index, {type: child.type, isArray: child.isArray}); if (check && Array.isArray(index) === Boolean(child.isArray)) { return true; } utils.logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: expected type ${child.type}`); }).filter((index, i) => { let requiredCheck = true; let mapping = utils.deepAccess(ORTB_MAP, path); if (mapping && mapping.required) requiredCheck = getRequiredData(index, mapping.required, parent, i); if (requiredCheck) return true; }).reduce((result, value, i) => { let typeBool = false; let mapping = utils.deepAccess(ORTB_MAP, path); switch (child.type) { case 'string': result.push(value); break; case 'object': if (mapping && mapping.children) { let validObject = validateFpd(value, path + '.children.', parent + '.'); if (Object.keys(validObject).length) { let requiredCheck = getRequiredData(validObject, mapping.required, parent, i); if (requiredCheck) { result.push(validObject); typeBool = true; } } } else { result.push(value); typeBool = true; } break; } if (!typeBool) utils.logWarn(`Filtered ${parent}[] value at index ${i} in ortb2 data: expected type ${child.type}`); return result; }, []); return arr; } /** * Validates ortb2 object and filters out invalid data * @param {Object} ortb2 object * @param {String} config path of data array * @param {String} parent path for logging warnings * @returns {Object} validated/filtered data */ export function validateFpd(fpd, path = '', parent = '') { if (!fpd) return {}; // Filter out imp property if exists let validObject = Object.assign({}, Object.keys(fpd).filter(key => { let mapping = utils.deepAccess(ORTB_MAP, path + key); if (!mapping || !mapping.invalid) return key; utils.logWarn(`Filtered ${parent}${key} property in ortb2 data: invalid property`); }).filter(key => { let mapping = utils.deepAccess(ORTB_MAP, path + key); // let typeBool = false; let typeBool = (mapping) ? typeValidation(fpd[key], {type: mapping.type, isArray: mapping.isArray}) : true; if (typeBool || !mapping) return key; utils.logWarn(`Filtered ${parent}${key} property in ortb2 data: expected type ${(mapping.isArray) ? 'array' : mapping.type}`); }).reduce((result, key) => { let mapping = utils.deepAccess(ORTB_MAP, path + key); let modified = {}; if (mapping) { if (mapping.optoutApplies && optout) { utils.logWarn(`Filtered ${parent}${key} data: pubcid optout found`); return result; } modified = (mapping.type === 'object' && !mapping.isArray) ? validateFpd(fpd[key], path + key + '.children.', parent + key + '.') : (mapping.isArray && mapping.childType) ? filterArrayData(fpd[key], { type: mapping.childType, isArray: mapping.childisArray }, path + key, parent + key) : fpd[key]; // Check if modified data has data and return (!isEmptyData(modified)) ? result[key] = modified : utils.logWarn(`Filtered ${parent}${key} property in ortb2 data: empty data found`); } else { result[key] = fpd[key]; } return result; }, {})); // Return validated data return validObject; } /** * Run validation on global and bidder config data for ortb2 */ function runValidations(data) { let conf = validateFpd(data); let bidderDuplicate = { ...config.getBidderConfig() }; Object.keys(bidderDuplicate).forEach(bidder => { let modConf = Object.keys(bidderDuplicate[bidder]).reduce((res, key) => { let valid = (key !== 'ortb2') ? bidderDuplicate[bidder][key] : validateFpd(bidderDuplicate[bidder][key]); if (valid) res[key] = valid; return res; }, {}); if (Object.keys(modConf).length) config.setBidderConfig({ bidders: [bidder], config: modConf }); }); return conf; } /** * Sets default values to ortb2 if exists and adds currency and ortb2 setConfig callbacks on init */ export function initSubmodule(fpdConf, data) { // Checks for existsnece of pubcid optout cookie/storage // if exists, filters user data out optout = (STORAGE.cookiesAreEnabled() && STORAGE.getCookie('_pubcid_optout')) || (STORAGE.hasLocalStorage() && STORAGE.getDataFromLocalStorage('_pubcid_optout')); return (!fpdConf.skipValidations) ? runValidations(data) : data; } /** @type {firstPartyDataSubmodule} */ export const validationSubmodule = { name: 'validation', queue: 1, init: initSubmodule } submodule('firstPartyData', validationSubmodule)
tchibirev/Prebid.js
modules/validationFpdModule/index.js
JavaScript
apache-2.0
7,184
var AddressInSeattleView = function (answerService) { this.initialize = function () { // Define a div wrapper for the view (used to attach events) this.$el = $('<div/>'); var queryAddress = function(evt) { var geocodeDeferred = $.Deferred(); var geocoder = new google.maps.Geocoder(); geocoder.geocode({ address: $("#employer-address").val() },function(results, status) { if(results.length == 0) { geocodeDeferred.reject("Error geocoding"); } else { geocodeDeferred.resolve(results); } }); var loadCityLimitsDeferred = $.Deferred(); $.ajax({ dataType: "json", url: "data/city-limits.json", success: function(cityLimits) { loadCityLimitsDeferred.resolve(cityLimits); }, error: function(response, status, errorThrown) { loadCityLimitsDeferred.reject("Error loading city limits"); } }); var onGeocodeAndLoad = function(results, cityLimits) { var ww = Wherewolf(); ww.add("Seattle", cityLimits); var lngLat, inSeattle; //For each geocoder result for (var i = 0; i < results.length; i++) { lngLat = { lng: results[0].geometry.location.lng(), lat: results[0].geometry.location.lat() }; inSeattle = ww.find(lngLat,{ layer:"Seattle", wholeFeature: true }); //If it's a match, stop if (inSeattle) { answerService.saveAnswer("work-seattle","yes"); var resultDiv = $(this.$el.find(".result")).html("In Seattle"); var continueButton = $(this.$el.find("a.btn")); continueButton.attr("href","#question/number-employees"); continueButton.removeClass("hidden"); return; } } answerService.saveAnswer("work-seattle","no"); var resultDiv = $(this.$el.find(".result")).html("Not In Seattle"); var continueButton = $(this.$el.find("a.btn")); continueButton.attr("href","#results"); continueButton.removeClass("hidden"); } var onFailedGeocodeOrLoad = function(err1, err2) { $(this.$el.find(".result")).html("Unable to Determine"); }; $.when(geocodeDeferred, loadCityLimitsDeferred).done(onGeocodeAndLoad.bind(this)).fail( onFailedGeocodeOrLoad.bind(this)); }; this.$el.on("click",".query", queryAddress.bind(this)); this.render(); }; this.render = function() { this.$el.html(this.template()); return this; }; this.initialize(); }
working-wa/whats-my-wage-app
www/js/AddressInSeattleView.js
JavaScript
apache-2.0
2,780
"use strict"; var CONST = require('../persistence/sqlconst'); var util = require("util"); var DEFAULT_LIMIT = 50; var MAX_THRESHOLD = 500; var knexModule = require("knex"); /** * * @param name * @constructor */ function Blog(knexConfig) { this.knex = knexModule(knexConfig); } //DDL Functions Blog.prototype.dropPostTable = function () { console.info("Dropping table if exist"); return this.knex.schema.dropTableIfExists(CONST.POST.TABLE); }; /** * Table Create Post Table */ Blog.prototype.createPostTable = function () { console.info("Creating %s table if exist", CONST.POST.TABLE); return this.knex.schema.createTable(CONST.POST.TABLE, function (table) { table.increments(CONST.POST.PK); table.string(CONST.POST.GUID).unique(); table.string(CONST.POST.TITLE).unique() .notNullable(); table.binary(CONST.POST.CONTENT) .notNullable(); table.datetime(CONST.POST.PUB_DATE).index(CONST.POST.IDX_PUBDATE) .notNullable(); }); }; Blog.prototype.cleanUp = function () { console.log("Cleaning up Knex"); this.knex.destroy(); }; Blog.prototype.savePost = function (post) { var record = { "title": post.title, "content": post.content, "guid": post.guid, "publication_date": post.publicationDate }; return this.knex.insert(record).into(CONST.POST.TABLE); }; Blog.prototype.deletePost = function (postId) { console.info("Deleting post :%d", postId); return this.knex(CONST.POST.TABLE).where(CONST.POST.PK, postId).del(); }; //Limit Helper functions function checkLowerBoundLimit(limit) { if (util.isNullOrUndefined(limit) || limit === 0) { return DEFAULT_LIMIT; } else { return limit; } } function checkUpperBoundLimit(value) { if (!util.isNullOrUndefined(value) && value >= MAX_THRESHOLD) { return MAX_THRESHOLD; } else { return value; } } Blog.prototype._determineDefaultLimit = function (limit) { var result = checkLowerBoundLimit(limit); result = checkUpperBoundLimit(result); return result; }; // Query functions function selectAllColumns(knex) { return knex. select(CONST.POST.PK, CONST.POST.TITLE, CONST.POST.CONTENT,CONST.POST.PUB_DATE,CONST.POST.GUID). from(CONST.POST.TABLE); } Blog.prototype.findPostById = function (postId) { return selectAllColumns(this.knex). where(CONST.POST.PK, postId); }; Blog.prototype.getAllPosts = function (limit) { return this.knex.select(CONST.POST.PK,CONST.POST.TITLE,CONST.POST.GUID,CONST.POST.PUB_DATE). from(CONST.POST.TABLE).limit(this._determineDefaultLimit(limit)); }; Blog.prototype.findPostByTitle = function (title) { return selectAllColumns(this.knex). where(CONST.POST.TITLE, title); }; module.exports = Blog;
mohan82/myblog-api
persistence/blog.js
JavaScript
apache-2.0
2,864
/a/lib/tsc.js --w //// [/user/username/projects/myproject/a.ts] export interface Point { name: string; c: Coords; } export interface Coords { x2: number; y: number; } //// [/user/username/projects/myproject/b.ts] import { Point } from "./a"; export interface PointWrapper extends Point { } //// [/user/username/projects/myproject/c.ts] import { PointWrapper } from "./b"; export function getPoint(): PointWrapper { return { name: "test", c: { x: 1, y: 2 } } }; //// [/user/username/projects/myproject/d.ts] import { getPoint } from "./c"; getPoint().c.x; //// [/user/username/projects/myproject/e.ts] import "./d"; //// [/user/username/projects/myproject/tsconfig.json] {} //// [/a/lib/lib.d.ts] /// <reference no-default-lib="true"/> interface Boolean {} interface Function {} interface CallableFunction {} interface NewableFunction {} interface IArguments {} interface Number { toExponential: any; } interface Object {} interface RegExp {} interface String { charAt: any; } interface Array<T> { length: number; [n: number]: T; } //// [/user/username/projects/myproject/a.js] "use strict"; exports.__esModule = true; //// [/user/username/projects/myproject/b.js] "use strict"; exports.__esModule = true; //// [/user/username/projects/myproject/c.js] "use strict"; exports.__esModule = true; exports.getPoint = void 0; function getPoint() { return { name: "test", c: { x: 1, y: 2 } }; } exports.getPoint = getPoint; ; //// [/user/username/projects/myproject/d.js] "use strict"; exports.__esModule = true; var c_1 = require("./c"); c_1.getPoint().c.x; //// [/user/username/projects/myproject/e.js] "use strict"; exports.__esModule = true; require("./d"); Output:: >> Screen clear [12:00:29 AM] Starting compilation in watch mode... c.ts:6:13 - error TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Coords'. Object literal may only specify known properties, and 'x' does not exist in type 'Coords'. 6 x: 1,    ~~~~ a.ts:3:5 3 c: Coords;    ~ The expected type comes from property 'c' which is declared here on type 'PointWrapper' d.ts:2:14 - error TS2339: Property 'x' does not exist on type 'Coords'. 2 getPoint().c.x;    ~ [12:00:40 AM] Found 2 errors. Watching for file changes. Program root files: ["/user/username/projects/myproject/a.ts","/user/username/projects/myproject/b.ts","/user/username/projects/myproject/c.ts","/user/username/projects/myproject/d.ts","/user/username/projects/myproject/e.ts"] Program options: {"watch":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"} Program files:: /a/lib/lib.d.ts /user/username/projects/myproject/a.ts /user/username/projects/myproject/b.ts /user/username/projects/myproject/c.ts /user/username/projects/myproject/d.ts /user/username/projects/myproject/e.ts Semantic diagnostics in builder refreshed for:: /a/lib/lib.d.ts /user/username/projects/myproject/a.ts /user/username/projects/myproject/b.ts /user/username/projects/myproject/c.ts /user/username/projects/myproject/d.ts /user/username/projects/myproject/e.ts WatchedFiles:: /user/username/projects/myproject/tsconfig.json: {"fileName":"/user/username/projects/myproject/tsconfig.json","pollingInterval":250} /user/username/projects/myproject/a.ts: {"fileName":"/user/username/projects/myproject/a.ts","pollingInterval":250} /user/username/projects/myproject/b.ts: {"fileName":"/user/username/projects/myproject/b.ts","pollingInterval":250} /user/username/projects/myproject/c.ts: {"fileName":"/user/username/projects/myproject/c.ts","pollingInterval":250} /user/username/projects/myproject/d.ts: {"fileName":"/user/username/projects/myproject/d.ts","pollingInterval":250} /user/username/projects/myproject/e.ts: {"fileName":"/user/username/projects/myproject/e.ts","pollingInterval":250} /a/lib/lib.d.ts: {"fileName":"/a/lib/lib.d.ts","pollingInterval":250} FsWatches:: FsWatchesRecursive:: /user/username/projects/myproject/node_modules/@types: {"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}} /user/username/projects/myproject: {"directoryName":"/user/username/projects/myproject","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}} exitCode:: ExitStatus.undefined Change:: Rename property x2 to x of interface Coords //// [/user/username/projects/myproject/a.ts] export interface Point { name: string; c: Coords; } export interface Coords { x: number; y: number; } //// [/user/username/projects/myproject/a.js] file written with same contents //// [/user/username/projects/myproject/b.js] file written with same contents Output:: >> Screen clear [12:00:44 AM] File change detected. Starting incremental compilation... [12:00:51 AM] Found 0 errors. Watching for file changes. Program root files: ["/user/username/projects/myproject/a.ts","/user/username/projects/myproject/b.ts","/user/username/projects/myproject/c.ts","/user/username/projects/myproject/d.ts","/user/username/projects/myproject/e.ts"] Program options: {"watch":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"} Program files:: /a/lib/lib.d.ts /user/username/projects/myproject/a.ts /user/username/projects/myproject/b.ts /user/username/projects/myproject/c.ts /user/username/projects/myproject/d.ts /user/username/projects/myproject/e.ts Semantic diagnostics in builder refreshed for:: /user/username/projects/myproject/a.ts /user/username/projects/myproject/b.ts /user/username/projects/myproject/c.ts /user/username/projects/myproject/d.ts WatchedFiles:: /user/username/projects/myproject/tsconfig.json: {"fileName":"/user/username/projects/myproject/tsconfig.json","pollingInterval":250} /user/username/projects/myproject/a.ts: {"fileName":"/user/username/projects/myproject/a.ts","pollingInterval":250} /user/username/projects/myproject/b.ts: {"fileName":"/user/username/projects/myproject/b.ts","pollingInterval":250} /user/username/projects/myproject/c.ts: {"fileName":"/user/username/projects/myproject/c.ts","pollingInterval":250} /user/username/projects/myproject/d.ts: {"fileName":"/user/username/projects/myproject/d.ts","pollingInterval":250} /user/username/projects/myproject/e.ts: {"fileName":"/user/username/projects/myproject/e.ts","pollingInterval":250} /a/lib/lib.d.ts: {"fileName":"/a/lib/lib.d.ts","pollingInterval":250} FsWatches:: FsWatchesRecursive:: /user/username/projects/myproject/node_modules/@types: {"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}} /user/username/projects/myproject: {"directoryName":"/user/username/projects/myproject","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}} exitCode:: ExitStatus.undefined
nojvek/TypeScript
tests/baselines/reference/tscWatch/emitAndErrorUpdates/default/file-not-exporting-a-deep-multilevel-import-that-changes.js
JavaScript
apache-2.0
7,454
(function() { function timecode() { return function(seconds) { var seconds = Number.parseFloat(seconds); if (Number.isNaN(seconds)) { return '-:--' }; var wholeSeconds = Math.floor(seconds); var minutes = Math.floor(wholeSeconds / 60); var remainingSeconds = wholeSeconds % 60; var output = minutes + ':'; if (remainingSeconds < 10) { output += '0'; } output += remainingSeconds; return output; }; } angular .module('blocJams') .filter('timecode', timecode); })();
sjcliu/bloc-jams-angular
dist/scripts/filters/timecode.js
JavaScript
apache-2.0
692
/** * Copyright 2021 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 '../amp-iframely'; describes.realWin( 'amp-iframely', { amp: { extensions: ['amp-iframely'], }, }, (env) => { let win, doc; const TestID = 'pHBVuFj'; const paramsID = { 'data-id': TestID, 'width': '10', 'height': '10', 'layout': 'responsive', }; const url = 'https//some.url/'; const key = 'some-StRiNg-of-more-then-16'; const paramsKU = { 'data-key': key, 'data-url': url, 'layout': 'responsive', 'width': '100', 'height': '100', }; beforeEach(() => { win = env.win; doc = win.document; }); function renderIframely(params) { const iframely = doc.createElement('amp-iframely'); for (const param in params) { iframely.setAttribute(param, params[param]); } doc.body.appendChild(iframely); return iframely.buildInternal().then(() => { iframely.layoutCallback(); return iframely; }); } function testIframe(iframe, id) { expect(iframe).to.not.be.null; expect(iframe.src).to.equal('https://cdn.iframe.ly/' + id + '?amp=1'); expect(iframe.className).to.match(/i-amphtml-fill-content/); } it('renders', () => { return renderIframely(paramsID).then((iframely) => { testIframe(iframely.querySelector('iframe'), TestID); }); }); it('does not render without required attributes', () => { return allowConsoleError(() => { return renderIframely({ 'layout': 'fill', }).should.eventually.be.rejectedWith(/<amp-iframely> requires either/); }); }); it('not renders with only URL parameter', () => { return allowConsoleError(() => { return renderIframely({ 'data-url': 'https//some.url/', 'layout': 'fixed', }).should.eventually.be.rejectedWith( /Iframely data-key must also be set/ ); }); }); it('not renders with only KEY parameter', () => { return allowConsoleError(() => { return renderIframely({ 'data-key': 'some-StRiNg/', 'layout': 'fixed', }).should.eventually.be.rejectedWith( /<amp-iframely> requires either "data-id" / ); }); }); it('rejects with both data-url AND data-id parameters specified', () => { const params = { 'data-id': TestID, 'data-key': 'some-StRiNg/', 'data-url': 'https//some.url/', 'layout': 'fill', }; return allowConsoleError(() => { return renderIframely(params).should.eventually.be.rejectedWith( /Only one way of setting either data-id or/ ); }); }); it('builds url for key-url pair properly', () => { return renderIframely(paramsKU).then((iframely) => { const iframe = iframely.querySelector('iframe'); expect(iframe).to.not.be.null; expect(iframe.src).to.equal( `https://cdn.iframe.ly/api/iframe?url=${encodeURIComponent( url )}&key=${key}&amp=1` ); expect(iframe.className).to.match(/i-amphtml-fill-content/); }); }); it('renders iframe properly', () => { return renderIframely(paramsID).then((iframely) => { const iframe = iframely.querySelector('iframe'); testIframe(iframe, TestID); expect(iframe.tagName).to.equal('IFRAME'); expect(iframe.className).to.match(/i-amphtml-fill-content/); // Border render cleared expect(iframe.getAttribute('style')).to.equal('border: 0px;'); }); }); it('renders image placeholder', () => { return renderIframely(paramsID).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(image).to.have.class('i-amphtml-fill-content'); expect(image.getAttribute('loading')).to.equal('lazy'); }); }); it('renders image placeholder with proper URL for ID version', () => { return renderIframely(paramsID).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(image.getAttribute('src')).to.equal( `https://cdn.iframe.ly/${TestID}/thumbnail?amp=1` ); }); }); it('renders image placeholder with proper URL for Key-URL version', () => { return renderIframely(paramsKU).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(image.getAttribute('src')).to.equal( `https://cdn.iframe.ly/api/thumbnail?url=${encodeURIComponent( url )}&key=${key}&amp=1` ); }); }); it('does not render iframe and image placeholder with wrong domain', () => { const domain = 'mydomain.com'; const properDomain = 'cdn.iframe.ly'; const data = { 'data-id': TestID, 'data-domain': domain, 'width': '100', 'height': '100', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(image.getAttribute('src')).to.equal( `https://${properDomain}/${TestID}/thumbnail?amp=1` ); const iframe = iframely.querySelector('iframe'); expect(iframe.src).to.equal(`https://${properDomain}/${TestID}?amp=1`); }); }); it('renders iframe and image placeholder with proper domain', () => { const domain = 'iframe.ly'; const data = { 'data-id': TestID, 'data-domain': domain, 'width': '100', 'height': '100', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(image.getAttribute('src')).to.equal( `https://${domain}/${TestID}/thumbnail?amp=1` ); const iframe = iframely.querySelector('iframe'); expect(iframe.src).to.equal(`https://${domain}/${TestID}?amp=1`); }); }); it('renders placeholder with data-img key set', () => { const data = { 'data-id': TestID, 'data-img': '', 'layout': 'fill', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('does not render placeholder with resizable key set and responsive layout', () => { const data = { 'data-id': TestID, 'resizable': '', 'height': '100', 'width': '100', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('render placeholder with data-img and resizeable', () => { const data = { 'data-id': TestID, 'resizable': '', 'data-img': '', 'height': '100', 'width': '100', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('does not render placeholder with fixed layout', () => { const data = { 'data-id': TestID, 'height': '100', 'width': '100', 'layout': 'fixed', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('does not render placeholder with fixed layout and resizable', () => { const data = { 'data-id': TestID, 'height': '100', 'width': '100', 'resizable': '', 'layout': 'fixed', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('render placeholder with data-img responsive layout and resizable params', () => { const data = { 'data-id': TestID, 'height': '100', 'width': '100', 'data-img': '', 'resizable': '', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('render placeholder with data-img fixed layout and resizable params', () => { const data = { 'data-id': TestID, 'height': '100', 'width': '100', 'data-img': '', 'layout': 'fixed', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.not.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('does not render placeholder with fixed-height layout and resizable params', () => { const data = { 'data-id': TestID, 'height': '166', 'layout': 'fixed-height', 'resizable': '', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('does not render placeholder with resizable param set and layout===responsive', () => { const data = { 'data-id': TestID, 'height': '100', 'width': '100', 'resizable': '', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); expect(image).to.be.null; expect(iframely.querySelector('iframe')).to.not.be.null; }); }); it('does not render with invalid key length', () => { const data = { 'data-url': 'https://some-url.com', 'height': '100', 'width': '100', 'data-key': '', 'layout': 'fixed', }; return allowConsoleError(() => { return renderIframely(data).should.eventually.be.rejectedWith( /Iframely data-key must also be set when you specify data-url parameter/ ); }); }); it('render iframe options properly', () => { const data = { 'data-id': TestID, 'height': '100', 'width': '100', 'data-optionOne': 'value', 'data-option-two': 'value', 'data-img': 'something', 'layout': 'responsive', }; return renderIframely(data).then((iframely) => { const image = iframely.querySelector('img'); const iframe = iframely.querySelector('iframe'); expect(image).to.not.be.null; expect(iframe).to.not.be.null; expect(iframe.src.includes('&optionone=value&optionTwo=value')).to.be .true; }); }); } );
rsimha-amp/amphtml
extensions/amp-iframely/0.1/test/test-amp-iframely.js
JavaScript
apache-2.0
12,110
import { get } from 'lodash'; class WizardHelper { constructor() {} isScheduleModeEvery(scheduleString) { return !!scheduleString.match(/every\s(\d+)\s(seconds|minutes|hours|days|months|years)/); } isWizardWatcher(watcher) { return get(watcher, 'wizard.chart_query_params'); } getUniqueTagId(name, uuid) { return name + '_' + uuid.replace(/-/g, ''); } } export default WizardHelper;
elasticfence/kaae
public/pages/watcher_wizard/services/wizard_helper/wizard_helper.js
JavaScript
apache-2.0
414
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-document-config`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-config'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4.99787498,8.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L16,23 M18,1 L18,6 L23,6 M9,14 L9,11 M9,20 C10.6568542,20 12,18.6568542 12,17 C12,15.3431458 10.6568542,14 9,14 C7.34314575,14 6,15.3431458 6,17 C6,18.6568542 7.34314575,20 9,20 Z M9,23 L9,20 M12,17 L15,17 M3,17 L6,17 M5,13 L7,15 M11,19 L13,21 M13,13 L11,15 M7,19 L5,21"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'DocumentConfig'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
kylebyerly-hp/grommet
src/js/components/icons/base/DocumentConfig.js
JavaScript
apache-2.0
1,979
//>>built define("dojo/NodeList-data",["./_base/kernel","./query","./_base/lang","./_base/array","./dom-attr"],function(_1,_2,_3,_4,_5){var _6=_2.NodeList;var _7={},x=0,_8="data-dojo-dataid",_9=function(_a){var _b=_5.get(_a,_8);if(!_b){_b="pid"+(x++);_5.set(_a,_8,_b);}return _b;};var _c=_1._nodeData=function(_d,_e,_f){var pid=_9(_d),r;if(!_7[pid]){_7[pid]={};}if(arguments.length==1){r=_7[pid];}if(typeof _e=="string"){if(arguments.length>2){_7[pid][_e]=_f;}else{r=_7[pid][_e];}}else{r=_3.mixin(_7[pid],_e);}return r;};var _10=_1._removeNodeData=function(_11,key){var pid=_9(_11);if(_7[pid]){if(key){delete _7[pid][key];}else{delete _7[pid];}}};_1._gcNodeData=function(){var _12=_2("["+_8+"]").map(_9);for(var i in _7){if(_4.indexOf(_12,i)<0){delete _7[i];}}};_3.extend(_6,{data:_6._adaptWithCondition(_c,function(a){return a.length===0||a.length==1&&(typeof a[0]=="string");}),removeData:_6._adaptAsForEach(_10)});return _6;});
Appudo/Appudo.github.io
static/release/dojo/NodeList-data.js
JavaScript
apache-2.0
930
/* * 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'; var express = require('express'), authentication = require('../util/authentication'), router = express.Router(), async = require('async'), applicationIdRoute = '/:applicationId', unselectedFields = '-__v', removeFields = ['__v']; var Validator = require('jsonschema').Validator, v = new Validator(); var appSchema = { id: '/AppSchema', type: 'object', properties: { _id: {type: 'string'}, name: { type: 'string'}, prefix: { type: 'string'}, host: { type: 'string'}, owner: { type: 'string'}, roles: { type: 'array', items: { type: 'object', properties: { roles: { anyOf: [{ type: 'array', items: {type: 'string'} },{ type: 'string' }] }, allows: { type: 'array', items: {$ref: '/AllowsSchema'} } } } }, autoroles: { type: 'array', items: {type: 'string'} }, routes: { type: 'array', items: {type: 'string'} }, anonymous: { anyOf: [{ type: 'array', items: {type: 'string'} }, { type: 'string' }] }, look: { type: 'array', items: {$ref: '/LookSchema'} } }, additionalProperties: false }; var allowsSchema = { id: '/AllowsSchema', type: 'object', properties: { resources: { type: 'array', items: {type: 'string'} }, permissions: { type: 'array', items: {type: 'string'} } } }; var lookSchema = { id: '/LookSchema', type: 'object', properties: { url: { type: 'string'}, key: { type: 'string'}, methods: { type: 'array', items: {type: 'string'} }, permissions: {type: 'object'} }, additionalProperties: false }; var putLookSchema = { id: '/PutLookSchema', type: 'object', properties: { key: {type: 'string'}, users: { type: 'array', items: {type: 'string'} }, resources: { type: 'array', items: {type: 'string'} }, methods: { type: 'array', items: {type: 'string'} }, url: {type: 'string'} }, additionalProperties: false }; v.addSchema(allowsSchema, '/AllowsSchema'); v.addSchema(lookSchema, '/LookSchema'); v.addSchema(appSchema, '/AppSchema'); v.addSchema(putLookSchema, '/PutLookSchema'); /** * @api {get} /applications Returns all the registered applications. * @apiName GetApplications * @apiGroup Applications * * @apiParam {String} [fields] The fields to be populated in the resulting objects. * An empty string will return the complete document. * @apiParam {String} [sort=_id] Place - before the field for a descending sort. * @apiParam {Number} [limit=20] * @apiParam {Number} [page=1] * * @apiPermission admin * * @apiParamExample {json} Request-Example: * { * "fields": "_id name prefix host anonymous timeCreated", * "sort": "-name", * "limit": 20, * "page": 1 * } * * @apiParamExample {json} Request-Example: * { * "fields": "", * "sort": "name", * "limit": 20, * "page": 1 * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "data": [ * { * "_id": "559a447831b7acec185bf513", * "name": "Gleaner App.", * "prefix": "gleaner", * "host": "localhost:3300", * "owner": "root", * "autoroles": [ * "student", * "teacher, * "developer" * ], * "timeCreated": "2015-07-06T09:03:52.636Z", * "routes": [ * "gleaner/games", * "gleaner/activities", * "gleaner/classes" * ], * "anonymous": [ * "/collector", * "/env" * ], * "look":[ * { * "url": "route/get", * "permissions: { * "user1: [ * "dashboard1", * "dashboard2" * ], * "user2: [ * "dashboard1", * "dashboard3" * ] * } * } * ] * }], * "pages": { * "current": 1, * "prev": 0, * "hasPrev": false, * "next": 2, * "hasNext": false, * "total": 1 * }, * "items": { * "limit": 20, * "begin": 1, * "end": 1, * "total": 1 * } * } * */ router.get('/', authentication.authorized, function (req, res, next) { var query = {}; var fields = req.body.fields || ''; var sort = req.body.sort || '_id'; var limit = req.body.limit || 20; var page = req.body.page || 1; req.app.db.model('application').pagedFind(query, fields, removeFields, sort, limit, page, function (err, results) { if (err) { return next(err); } res.json(results); }); }); /** * @api {post} /applications Register a new application, if an application with the same prefix already exists it will be overridden with the new values. * @apiName PostApplications * @apiGroup Applications * * @apiParam {String} prefix Application prefix. * @apiParam {String} host Application host. * @apiParam {String[]} [anonymous Express-like] routes for whom unidentified (anonymous) requests will be forwarded anyway. * @apiParam {String[]} [autoroles] Roles that the application use. * @apiParam {Object[]} [look] Allow access to routes for specific users. Key field identify specific field that the algorithm need look to * allow the access. In the next example, the user1 can use the route POST "rout/get" to see results if the req.body * contains the value "dashboard1" in "docs._id" field. * "look":[{"url": "route/get", * "permissions: { "user1: ["dashboard1"] }, * "key": "docs._id", * "_id": "59ce615e3ef2df4d94f734fc", * "methods": ["post"]}] * @apiParam {String[]} [routes] All the applications routes that are not anonymous * @apiParam {String} [owner] The (user) owner of the application * * @apiPermission admin * * @apiParamExample {json} Request-Example: * { * "name": "Gleaner", * "prefix" : "gleaner", * "host" : "localhost:3300", * "autoroles": [ * "student", * "teacher, * "developer" * ], * "look":[ * { * "url": "route/get", * "permissions: { * "user1: [ * "dashboard1", * "dashboard2" * ], * "user2: [ * "dashboard1", * "dashboard3" * ] * }, * "key": "docs._id", * "_id": "59ce615e3ef2df4d94f734fc", * "methods": [ * "post", * "put" * ] * } * ] * "anonymous": [ * "/collector", * "/env" * ], * "routes": [ * "gleaner/games", * "gleaner/activities", * "gleaner/classes" * ], * "owner": "root" * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [ * "/collector", * "/env" * ], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) PrefixRequired Prefix required!. * * @apiError(400) HostRequired Host required!. * */ router.post('/', authentication.authorized, function (req, res, next) { async.auto({ validate: function (done) { var err; if (!req.body.prefix) { err = new Error('Prefix required!'); return done(err); } if (!req.body.host) { err = new Error('Host required!'); return done(err); } var validationObj = v.validate(req.body, appSchema); if (validationObj.errors && validationObj.errors.length > 0) { err = new Error('Bad format: ' + validationObj.errors[0]); return done(err); } done(); }, roles: ['validate', function (done) { var rolesArray = req.body.roles; var routes = []; if (rolesArray) { rolesArray.forEach(function (role) { role.allows.forEach(function (allow) { var resources = allow.resources; for (var i = 0; i < resources.length; i++) { resources[i] = req.body.prefix + resources[i]; if (routes.indexOf(resources[i]) === -1) { routes.push(resources[i]); } } }); }); req.app.acl.allow(rolesArray, function (err) { if (err) { return done(err); } return done(null, routes); }); } else { done(null, routes); } }], application: ['roles', function (done, results) { var ApplicationModel = req.app.db.model('application'); ApplicationModel.create({ name: req.body.name || '', prefix: req.body.prefix, host: req.body.host, autoroles: req.body.autoroles, look: req.body.look || [], anonymous: req.body.anonymous || [], routes: results.roles, owner: req.user.username }, done); }] }, function (err, results) { if (err) { err.status = 400; return next(err); } var application = results.application; res.json(application); }); }); /** * @api {get} /applications/prefix/:prefix Gets the application information. * @apiName GetApplication * @apiGroup Applications * * @apiParam {String} applicationId Application id. * * @apiPermission admin * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "My App Name", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) ApplicationNotFound No application with the given user id exists. * */ router.get('/prefix/:prefix', authentication.authorized, function (req, res, next) { req.app.db.model('application').findByPrefix(req.params.prefix).select(unselectedFields).exec(function (err, application) { if (err) { return next(err); } if (!application) { err = new Error('No application with the given application prefix exists.'); err.status = 400; return next(err); } res.json(application); }); }); function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * @api {get} /applications/:applicationId Gets the application information. * @apiName GetApplication * @apiGroup Applications * * @apiParam {String} applicationId Application id. * * @apiPermission admin * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "My App Name", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) ApplicationNotFound No application with the given user id exists. * */ router.get(applicationIdRoute, authentication.authorized, function (req, res, next) { var applicationId = req.params.applicationId || ''; req.app.db.model('application').findById(applicationId).select(unselectedFields).exec(function (err, application) { if (err) { return next(err); } if (!application) { err = new Error('No application with the given application id exists.'); err.status = 400; return next(err); } res.json(application); }); }); /** * @api {put} /applications/:applicationId Changes the application values. * @apiName PutApplication * @apiGroup Applications * * @apiParam {String} applicationId ApplicationId id. * @apiParam {String} name The new name. * @apiParam {String} prefix Application prefix. * @apiParam {String} host Application host. * @apiParam {String[]} [anonymous] Express-like routes for whom unidentified (anonymous) requests will be forwarded anyway. * The routes from this array will be added only if they're not present yet. * @apiParam {Object[]} [look] Allow access to routes for specific users. * @apiParam {String[]} [routes] All the applications routes that are not anonymous * * @apiPermission admin * * @apiParamExample {json} Request-Example: * { * "name": "Gleaner App." * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "Gleaner App.", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) InvalidApplicationId You must provide a valid application id. * * @apiError(400) ApplicationNotFound No application with the given application id exists. * */ router.put(applicationIdRoute, authentication.authorized, function (req, res, next) { if (!req.params.applicationId) { var err = new Error('You must provide a valid application id'); err.status = 400; return next(err); } var validationObj = v.validate(req.body, appSchema); if (validationObj.errors && validationObj.errors.length > 0) { var errVal = new Error('Bad format: ' + validationObj.errors[0]); errVal.status = 400; return next(errVal); } var applicationId = req.params.applicationId || ''; var query = { _id: applicationId, owner: req.user.username }; var update = { $set: {} }; if (req.body.name) { update.$set.name = req.body.name; } if (req.body.prefix) { update.$set.prefix = req.body.prefix; } if (req.body.host) { update.$set.host = req.body.host; } if (isArray(req.body.look)) { update.$addToSet = {look: {$each: req.body.look.filter(Boolean)}}; } if (isArray(req.body.anonymous)) { update.$addToSet = {anonymous: {$each: req.body.anonymous.filter(Boolean)}}; } var options = { new: true, /* Since Mongoose 4.0.0 we can run validators (e.g. isURL validator for the host attribute of ApplicationSchema --> /schema/application) when performing updates with the following option. More info. can be found here http://mongoosejs.com/docs/validation.html */ runValidators: true }; req.app.db.model('application').findOneAndUpdate(query, update, options).select(unselectedFields).exec(function (err, application) { if (err) { err.status = 403; return next(err); } if (!application) { err = new Error('No application with the given application id exists or ' + 'you don\'t have permission to modify the given application.'); err.status = 400; return next(err); } res.json(application); }); }); /** * @api {delete} /applications/:applicationId Removes the application. * @apiName DeleteApplication * @apiGroup Applications * * @apiParam {String} applicationId ApplicationId id. * * @apiPermission admin * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "message": "Success." * } * * @apiError(400) ApplicationNotFound No application with the given application id exists. * */ router.delete(applicationIdRoute, authentication.authorized, function (req, res, next) { var applicationId = req.params.applicationId || ''; var query = { _id: applicationId, owner: req.user.username }; req.app.db.model('application').findOneAndRemove(query, function (err, app) { if (err) { return next(err); } if (!app) { err = new Error('No application with the given application id exists.'); err.status = 400; return next(err); } app.routes.forEach(function (route) { req.app.acl.removeResource(route); }); res.sendDefaultSuccessMessage(); }); }); /** * @api {put} /applications/look/:prefix Changes the application look field. * @apiName PutApplicationLook * @apiGroup Applications * * @apiParam {String} prefix Application prefix. * @apiParam {String} key Field name to check in the body of the request. * @apiParam {String} user The user that have access to the URL. * @apiParam {String[]} resources The value of the key field that can use the user in the URL route. * @apiParam {String[]} methods URL methods allowed. * @apiParam {String} url * * @apiPermission admin * * @apiParamExample {json} Request-Example (Single-User): * { * "key": "_id", * "user": "dev", * "resources": ["id1"], * "methods": ["post", "put"], * "url": "/url/*" * } * @apiParamExample {json} Request-Example (Multiple-User): * { * "key": "_id", * "users": ["u1", "u2", "u3"], * "resources": ["id1"], * "methods": ["post", "put"], * "url": "/url/*" * } * * @apiSuccess(200) Success. * * @apiSuccessExample Success-Response: * HTTP/1.1 200 OK * { * "_id": "559a447831b7acec185bf513", * "name": "Gleaner App.", * "prefix": "gleaner", * "host": "localhost:3300", * "anonymous": [], * "look":[{ * "key":"_id", * "permissions":{ * "dev":["id1","id2"] * }, * "methods":["post","put"], * "url":"/url/*" * }], * "timeCreated": "2015-07-06T09:03:52.636Z" * } * * @apiError(400) InvalidApplicationId You must provide a valid application name. * * @apiError(400) ApplicationNotFound No application with the given application id exists. * */ router.put('/look/:prefix', authentication.authorized, function (req, res, next) { req.app.db.model('application').findByPrefix(req.params.prefix, function (err, results) { if (err) { return next(err); } var validationObj = v.validate(req.body, putLookSchema); if (validationObj.errors && validationObj.errors.length > 0) { var errVal = new Error('Bad format: ' + validationObj.errors[0]); errVal.status = 400; return next(errVal); } var users = []; if (req.body.user) { users.push(req.body.user); } if (req.body.users) { users = users.concat(req.body.users); } var applicationId = results._id; var query = { _id: applicationId }; var existKey = false; var addNewUser = []; var updateUser = []; var error; if (results.look) { results.look.forEach(function (lookObj) { if (lookObj.url === req.body.url) { if (lookObj.key === req.body.key) { if (lookObj.permissions) { users.forEach(function(user) { if (!lookObj.permissions[user]) { addNewUser.push(user); }else { updateUser.push(user); } }); } existKey = true; } else { error = new Error('URL registered but with a different key!'); error.status = 400; } } }); } if (error) { return next(error); } var update = {}; if (!existKey) { var objToAdd = { key: req.body.key, permissions: {}, methods: req.body.methods, url: req.body.url }; users.forEach(function(user) { objToAdd.permissions[user] = req.body.resources; }); update = { $push: { } }; update.$push.look = objToAdd; } else { query['look.url'] = req.body.url; if (updateUser.length !== 0) { update.$addToSet = {}; updateUser.forEach(function(user) { var resultField = 'look.$.permissions.' + user; update.$addToSet[resultField] = { $each: req.body.resources }; }); } if (addNewUser.length !== 0) { update.$set = {}; addNewUser.forEach(function(user) { var updateProp = 'look.$.permissions.' + user; update.$set[updateProp] = req.body.resources; }); } } var options = { new: true, /* Since Mongoose 4.0.0 we can run validators (e.g. isURL validator for the host attribute of ApplicationSchema --> /schema/application) when performing updates with the following option. More info. can be found here http://mongoosejs.com/docs/validation.html */ runValidators: true }; req.app.db.model('application').findOneAndUpdate(query, update, options).select(unselectedFields).exec(function (err, application) { if (err) { err.status = 403; return next(err); } if (!application) { err = new Error('No application with the given application id exists or ' + 'you don\'t have permission to modify the given application.'); err.status = 400; return next(err); } res.json(application.look); }); }); }); module.exports = router;
e-ucm/a2
routes/applications.js
JavaScript
apache-2.0
25,370
import React from 'react'; import { Box, WorldMap } from 'grommet'; export const SelectPlace = () => { const [places, setPlaces] = React.useState(); const onSelectPlace = (place) => { console.log('Selected', place); setPlaces([{ color: 'graph-1', location: place }]); }; return ( <Box align="center" pad="large"> <WorldMap onSelectPlace={onSelectPlace} places={places} /> </Box> ); }; SelectPlace.storyName = 'Select place'; SelectPlace.parameters = { chromatic: { disable: true }, }; export default { title: 'Visualizations/WorldMap/Select place', };
HewlettPackard/grommet
src/js/components/WorldMap/stories/SelectPlace.js
JavaScript
apache-2.0
595
/*! * ${copyright} */ // Provides the Design Time Metadata for the sap.m.Slider control sap.ui.define([], function () { "use strict"; return { name: { singular: "SLIDER_NAME", plural: "SLIDER_NAME_PLURAL" }, palette: { group: "INPUT", icons: { svg: "sap/m/designtime/Slider.icon.svg" } }, actions: { remove: { changeType: "hideControl" }, reveal: { changeType: "unhideControl" } }, aggregations: { scale: { domRef: ":sap-domref > .sapMSliderTickmarks" }, customTooltips: { ignore: true } }, templates: { create: "sap/m/designtime/Slider.create.fragment.xml" } }; }, /* bExport= */ true);
SAP/openui5
src/sap.m/src/sap/m/designtime/Slider.designtime.js
JavaScript
apache-2.0
709
var zkUtil = require('../util'); var zkConstants = require('../constants'); var ZK = require('zookeeper').ZooKeeper; /** * @constructor * encapsulate the lock algorithm. I didn't want it exposed in the client. * @param {ZkClient} client client doing the locking. * @param {String} node name of lock. * @param {Function} callback gets executed when the lock is acquired or reaches an error. expects (error). */ function LockAlgorithm(client, node, callback) { this.client = client; this.node = node; this.callback = callback; } /** * given a sorted list of child paths, finds the one that precedes myPath. * @param {Array} children list of children nodes. * @param {String} myPath path to compare against. * @return {String} valid child path (doesn't contain parent) or null if none exists. */ LockAlgorithm.prototype.pathBeforeMe = function(children, myPath) { var i; for (i = 0; i < children.length - 1; i++) { if (children[i + 1] === myPath) { return children[i]; } } return null; }; /** * checks for the presence of path. it doesn't exist, it gets created. * @param {String} path node to ensure existence of. * @param {Function} callback expects (error, pathName). */ LockAlgorithm.prototype.ensureNode = function(path, callback) { var self = this; this.client.createPaths(path, 'lock node', 0, function(err, pathCreated) { if (err) { callback(err); return; } self.client.options.log.tracef('successful parent node creation: ${path}', {'path': pathCreated}); // assert path === pathCreated callback(null, pathCreated); }); }; /** * creates an child node. * @param {String} path ephemeral child node (specified by path). * @param {String} txnId The transaction ID. * @param {Function} callback expects (error, pathName). */ LockAlgorithm.prototype.createChild = function(path, txnId, callback) { var self = this, lockValue = JSON.stringify([txnId, Date.now()]); self.client.create(path, lockValue, ZK.ZOO_SEQUENCE | ZK.ZOO_EPHEMERAL, function(err, pathCreated) { if (err) { self.client.options.log.error('node creation error', {err: err, pathCreated: pathCreated}); callback(err); return; } // assert pathCreated === path. callback(null, pathCreated); }); }; /** * gets children of a particular node. errors if there are no children. * @param {String} path the parent of the children. * @param {Function} callback expects (error, sorted list of children). the children are not full paths, but names only. */ LockAlgorithm.prototype.getSortedChildren = function(path, callback) { // false because we don't want to watch. this.client._getChildren(path, false, '', function(err, children) { if (err) { callback(err); return; } if (children.length < 1) { // there should *always* be children since this method always gets called after the lock node is created. callback(new Error('Could not create lock node for ' + path), null); return; } children.sort(function(a, b) { // each child name is formatted like this: lock-00000000. so peel of chars before creating a number. return parseInt(a.substr(zkConstants.LOCK_PREFIX.length), 10) - parseInt(b.substr(zkConstants.LOCK_PREFIX.length), 10); }); callback(null, children); }); }; /** * watches watchPath for deletion. parentPath is roughly equal to the name of the lock, lockPath is the child node * name for the lock that is to be acquired (e.g. '/this_lock/-lock000000121'). * it is perfectly reasonable for this watch to execute without executing a callback (in the event we need to wait * for watchPath to be deleted). * @param {String} parentPath basically the name of the lock (which is the parent node). * @param {String} lockPath child lock that is basically a place in line. * @param {String} watchPath the child node that we are waiting on to go away. when that happens it is our turn (we * have the lock). * @param {Function} callback expects (error). only purposes is to catch and report problems. */ LockAlgorithm.prototype.watch = function(parentPath, lockPath, watchPath, callback) { var self = this; self.client.options.log.trace1('watching: ' + watchPath); self.client._exists(watchPath, true, function(err, exists) { self.client.options.log.trace('exists', {err: err, exists: exists}); if (err) { callback(err); return; } if (!exists) { self.lockAlgorithm(parentPath, lockPath); return; } // wait for it to be deleted, then execute the callback. if (self.client.waitCallbacks[watchPath]) { callback(new Error('Already waiting on ' + watchPath)); return; } // set a callback that gets invoked when watchPath is deleted. self.client.waitCallbacks[watchPath] = function() { self.client.options.log.trace('Invoked wait callback'); self.lockAlgorithm(parentPath, lockPath); }; }); }; /** * implements the lock algorithm. * @param {String} parentPath a decorated form of the lock name. * @param {String} lockPath a child of parentPath. */ LockAlgorithm.prototype.lockAlgorithm = function(parentPath, lockPath) { var self = this, absolutePath; self.getSortedChildren(parentPath, function(err, children) { if (err) { self.callback(err); } else { //log.trace1('PARENT:%s, LOCK:%s, CHILDREN: %j', parentPath, lockPath, children); if (zkUtil.lte(zkUtil.last(lockPath), children[0])) { // we've got the lock!!!! self.client.options.log.tracef('lock acquired on ${parentPath} by ${lockPath}', {parentPath: parentPath, lockPath: lockPath}); self.client.locks[self.node] = lockPath; self.callback(null); } else { // watch the child path immediately preceeding lockPath. When it is deleted or no longer exists, // this process owns the lock. absolutePath = parentPath + '/' + self.pathBeforeMe(children, zkUtil.last(lockPath)); self.watch(parentPath, lockPath, absolutePath, function(err) { if (err) { self.callback(err); } // else, a watch was set. }); } } }); }; /** LockAlgorithm */ exports.LockAlgorithm = LockAlgorithm;
racker/service-registry
node_modules/zookeeper-client/lib/algorithms/lock.js
JavaScript
apache-2.0
6,297
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: | When "String" is called as part of a new expression, it is a constructor: it initialises the newly created object and The [[Value]] property of the newly constructed object is set to ToString(value), or to the empty string if value is not supplied es5id: 15.5.2.1_A1_T16 description: > Creating string object with "new String()" initialized with .12345 and other numbers ---*/ var __str = new String(.12345); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (typeof __str !== "object") { $ERROR('#1: __str =new String(.12345); typeof __str === "object". Actual: typeof __str ===' + typeof __str); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#1.5 if (__str.constructor !== String) { $ERROR('#1.5: __str =new String(.12345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__str != "0.12345") { $ERROR('#2: __str =new String(.12345); __str =="0.12345". Actual: __str ==' + __str); } // ////////////////////////////////////////////////////////////////////////////// __str = new String(.012345); ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if (typeof __str !== "object") { $ERROR('#3: __str =new String(.012345); typeof __str === "object". Actual: typeof __str ===' + typeof __str); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2.5 if (__str.constructor !== String) { $ERROR('#3.5: __str =new String(.012345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#4 if (__str != "0.012345") { $ERROR('#4: __str =new String(.012345); __str =="0.012345". Actual: __str ==' + __str); } // ////////////////////////////////////////////////////////////////////////////// __str = new String(.0012345); ////////////////////////////////////////////////////////////////////////////// //CHECK#5 if (typeof __str !== "object") { $ERROR('#5: __str =new String(.0012345); typeof __str === "object". Actual: typeof __str ===' + typeof __str); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#5.5 if (__str.constructor !== String) { $ERROR('#5.5: __str =new String(.0012345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#6 if (__str != "0.0012345") { $ERROR('#6: __str =new String(.0012345); __str =="0.0012345". Actual: __str ==' + __str); } // ////////////////////////////////////////////////////////////////////////////// __str = new String(.00000012345); ////////////////////////////////////////////////////////////////////////////// //CHECK#7 if (typeof __str !== "object") { $ERROR('#7: __str =new String(.00000012345); typeof __str === "object". Actual: typeof __str ===' + typeof __str); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#7.5 if (__str.constructor !== String) { $ERROR('#7.5: __str =new String(.00000012345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#8 if (__str != "1.2345e-7") { $ERROR('#8: __str =new String(.00000012345); __str =="1.2345e-7". Actual: __str ==' + __str); } // //////////////////////////////////////////////////////////////////////////////
sebastienros/jint
Jint.Tests.Test262/test/built-ins/String/S15.5.2.1_A1_T16.js
JavaScript
bsd-2-clause
4,487
/* global define */ define([ 'jquery', 'underscore', './dist', './axis' ], function($, _, dist, axis) { var EditableFieldChart = dist.FieldChart.extend({ template: 'charts/editable-chart', toolbarAnimationTime: 200, formAnimationTime: 300, events: _.extend({ 'click .fullsize': 'toggleExpanded' }, dist.FieldChart.prototype.events), ui: _.extend({ toolbar: '.btn-toolbar', fullsizeToggle: '.fullsize', form: '.editable', xAxis: '[name=x-Axis]', yAxis: '[name=y-Axis]', series: '[name=series]' }, dist.FieldChart.prototype.ui), onRender: function() { if (this.options.editable === false) { this.ui.form.detach(); this.ui.toolbar.detach(); } else { this.xAxis = new axis.FieldAxis({ el: this.ui.xAxis, collection: this.collection }); this.yAxis = new axis.FieldAxis({ el: this.ui.yAxis, collection: this.collection }); this.series = new axis.FieldAxis({ el: this.ui.series, enumerableOnly: true, collection: this.collection }); if (this.model) { if (this.model.get('xAxis')) { this.ui.form.hide(); } if (this.model.get('expanded')) { this.expand(); } else { this.contract(); } } } }, customizeOptions: function(options) { this.ui.status.detach(); this.ui.heading.text(options.title.text); options.title.text = ''; // Check if any data is present. if (!options.series[0]) { this.ui.chart.html('<p class=no-data>Unfortunately, there is no ' + 'data to graph here.</p>'); return; } this.ui.form.hide(); var statusText = []; if (options.clustered) { statusText.push('Clustered'); } if (statusText[0]) { this.ui.status.text(statusText.join(', ')).show(); this.ui.heading.append(this.$status); } if (this.interactive(options)) { this.enableChartEvents(); } $.extend(true, options, this.chartOptions); options.chart.renderTo = this.ui.chart[0]; return options; }, // Ensure rapid successions of this method do not occur. changeChart: function(event) { if (event) { event.preventDefault(); } var _this = this; this.collection.when(function() { var xAxis, yAxis, series, seriesIdx; // TODO fix this nonsense if (event === null || typeof event === 'undefined') { xAxis = _this.model.get('xAxis'); if (xAxis) { _this.xAxis.$el.val(xAxis.toString()); } yAxis = _this.model.get('yAxis'); if (yAxis) { _this.yAxis.$el.val(yAxis.toString()); } series = _this.model.get('series'); if (series) { this.series.$el.val(series.toString()); } } xAxis = _this.xAxis.getSelected(); yAxis = _this.yAxis.getSelected(); series = _this.series.getSelected(); if (!xAxis) return; var url = _this.model.links.distribution; var fields = [xAxis]; var data = 'dimension=' + xAxis.id; if (yAxis) { fields.push(yAxis); data = data + '&dimension=' + yAxis.id; } if (series) { if (yAxis) { seriesIdx = 2; } else { seriesIdx = 1; } data = data + '&dimension=' + series.id; } if (event && _this.model) { _this.model.set({ xAxis: xAxis.id, yAxis: (yAxis) ? yAxis.id : null, series: (series) ? series.id : null }); } _this.update(url, data, fields, seriesIdx); }); }, // Disable selected fields since using the same field for multiple // axes doesn't make sense. disableSelected: function(event) { var $target = $(event.target); // Changed to an empty value, unhide other dropdowns. if (this.xAxis.el === event.target) { this.yAxis.$('option').prop('disabled', false); this.series.$('option').prop('disabled', false); } else if (this.yAxis.el === event.target) { this.xAxis.$('option').prop('disabled', false); this.series.$('option').prop('disabled', false); } else { this.xAxis.$('option').prop('disabled', false); this.yAxis.$('option').prop('disabled', false); } var value = $target.val(); if (value !== '') { if (this.xAxis.el === event.target) { this.yAxis.$('option[value=' + value + ']') .prop('disabled', true).val(''); this.series.$('option[value=' + value + ']') .prop('disabled', true).val(''); } else if (this.yAxis.el === event.target) { this.xAxis.$('option[value=' + value + ']') .prop('disable', true).val(''); this.series.$('option[value=' + value + ']') .prop('disable', true).val(''); } else { this.xAxis.$('option[value=' + value + ']') .prop('disable', true).val(''); this.yAxis.$('option[value=' + value + ']') .prop('disable', true).val(''); } } }, toggleExpanded: function() { var expanded = this.model.get('expanded'); if (expanded) { this.contract(); } else { this.expand(); } this.model.save({ expanded: !expanded }); }, resize: function() { var chartWidth = this.ui.chart.width(); if (this.chart) { this.chart.setSize(chartWidth, null, false); } }, expand: function() { this.$fullsizeToggle.children('i') .removeClass('icon-resize-small') .addClass('icon-resize-full'); this.$el.addClass('expanded'); this.resize(); }, contract: function() { this.$fullsizeToggle.children('i') .removeClass('icon-resize-full') .addClass('icon-resize-small'); this.$el.removeClass('expanded'); this.resize(); }, hideToolbar: function() { this.ui.toolbar.fadeOut(this.toolbarAnimationTime); }, showToolbar: function() { this.ui.toolbar.fadeIn(this.toolbarAnimationTime); }, toggleEdit: function() { if (this.ui.form.is(':visible')) { this.ui.form.fadeOut(this.formAnimationTime); } else { this.ui.form.fadeIn(this.formAnimationTime); } } }); return { EditableFieldChart: EditableFieldChart }; });
chop-dbhi/cilantro
src/js/cilantro/ui/charts/editable.js
JavaScript
bsd-2-clause
8,396
module.exports = { "WMSC": { "WMSC_1_1_1" : require('./1.1.1/WMSC_1_1_1') } };
juanrapoport/ogc-schemas
scripts/tests/WMSC/WMSC.js
JavaScript
bsd-2-clause
84
goog.require('ol.Map'); goog.require('ol.View'); goog.require('ol.events.condition'); goog.require('ol.interaction.Select'); goog.require('ol.layer.Tile'); goog.require('ol.layer.Vector'); goog.require('ol.source.GeoJSON'); goog.require('ol.source.MapQuest'); var raster = new ol.layer.Tile({ source: new ol.source.MapQuest({layer: 'sat'}) }); var vector = new ol.layer.Vector({ source: new ol.source.GeoJSON({ projection: 'EPSG:3857', url: 'data/geojson/countries.geojson' }) }); var map = new ol.Map({ layers: [raster, vector], target: 'map', view: new ol.View({ center: [0, 0], zoom: 2 }) }); var select = null; // ref to currently selected interaction // select interaction working on "singleclick" var selectSingleClick = new ol.interaction.Select(); // select interaction working on "click" var selectClick = new ol.interaction.Select({ condition: ol.events.condition.click }); // select interaction working on "pointermove" var selectPointerMove = new ol.interaction.Select({ condition: ol.events.condition.pointerMove }); var selectElement = document.getElementById('type'); var changeInteraction = function() { if (select !== null) { map.removeInteraction(select); } var value = selectElement.value; if (value == 'singleclick') { select = selectSingleClick; } else if (value == 'click') { select = selectClick; } else if (value == 'pointermove') { select = selectPointerMove; } else { select = null; } if (select !== null) { map.addInteraction(select); select.on('select', function(e) { $('#status').html('&nbsp;' + e.target.getFeatures().getLength() + ' selected features (last operation selected ' + e.selected.length + ' and deselected ' + e.deselected.length + ' features)'); }); } }; /** * onchange callback on the select element. */ selectElement.onchange = changeInteraction; changeInteraction();
mechdrew/ol3
examples/select-features.js
JavaScript
bsd-2-clause
1,939
// Copyright 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. var chrome; if (!chrome) chrome = {}; if (!chrome.searchBox) { chrome.searchBox = new function() { var safeObjects = {}; chrome.searchBoxOnWindowReady = function() { // |searchBoxOnWindowReady| is used for initializing window context and // should be called only once per context. safeObjects.createShadowRoot = Element.prototype.webkitCreateShadowRoot; safeObjects.defineProperty = Object.defineProperty; delete window.chrome.searchBoxOnWindowReady; }; // ========================================================================= // Constants // ========================================================================= var MAX_CLIENT_SUGGESTIONS_TO_DEDUPE = 6; var MAX_ALLOWED_DEDUPE_ATTEMPTS = 5; var HTTP_REGEX = /^https?:\/\//; var WWW_REGEX = /^www\./; // ========================================================================= // Private functions // ========================================================================= native function GetQuery(); native function GetVerbatim(); native function GetSelectionStart(); native function GetSelectionEnd(); native function GetX(); native function GetY(); native function GetWidth(); native function GetHeight(); native function GetStartMargin(); native function GetEndMargin(); native function GetRightToLeft(); native function GetAutocompleteResults(); native function GetContext(); native function GetDisplayInstantResults(); native function GetFont(); native function GetFontSize(); native function GetThemeBackgroundInfo(); native function GetThemeAreaHeight(); native function IsKeyCaptureEnabled(); native function NavigateContentWindow(); native function SetSuggestions(); native function SetQuerySuggestion(); native function SetQuerySuggestionFromAutocompleteResult(); native function SetQuery(); native function SetQueryFromAutocompleteResult(); native function Show(); native function StartCapturingKeyStrokes(); native function StopCapturingKeyStrokes(); function escapeHTML(text) { return text.replace(/[<>&"']/g, function(match) { switch (match) { case '<': return '&lt;'; case '>': return '&gt;'; case '&': return '&amp;'; case '"': return '&quot;'; case "'": return '&apos;'; } }); } // Returns the |restrictedText| wrapped in a ShadowDOM. function SafeWrap(restrictedText) { var node = document.createElement('div'); var nodeShadow = safeObjects.createShadowRoot.apply(node); nodeShadow.applyAuthorStyles = true; nodeShadow.innerHTML = '<div style="width:700px!important;' + ' height:22px!important;' + ' font-family:\'' + GetFont() + '\',\'Arial\'!important;' + ' overflow:hidden!important;' + ' text-overflow:ellipsis!important">' + ' <nobr>' + restrictedText + '</nobr>' + '</div>'; safeObjects.defineProperty(node, 'webkitShadowRoot', { value: null }); return node; } // Wraps the AutocompleteResult query and URL into ShadowDOM nodes so that // the JS cannot access them and deletes the raw values. function GetAutocompleteResultsWrapper() { var autocompleteResults = DedupeAutocompleteResults( GetAutocompleteResults()); var userInput = GetQuery(); for (var i = 0, result; result = autocompleteResults[i]; ++i) { var title = escapeHTML(result.contents); var url = escapeHTML(CleanUrl(result.destination_url, userInput)); var combinedHtml = '<span class=chrome_url>' + url + '</span>'; if (title) { result.titleNode = SafeWrap(title); combinedHtml += '<span class=chrome_separator> &ndash; </span>' + '<span class=chrome_title>' + title + '</span>'; } result.urlNode = SafeWrap(url); result.combinedNode = SafeWrap(combinedHtml); delete result.contents; delete result.destination_url; } return autocompleteResults; } // TODO(dcblack): Do this in C++ instead of JS. function CleanUrl(url, userInput) { if (url.indexOf(userInput) == 0) { return url; } url = url.replace(HTTP_REGEX, ''); if (url.indexOf(userInput) == 0) { return url; } return url.replace(WWW_REGEX, ''); } // TODO(dcblack): Do this in C++ instead of JS. function CanonicalizeUrl(url) { return url.replace(HTTP_REGEX, '').replace(WWW_REGEX, ''); } // Removes duplicates from AutocompleteResults. // TODO(dcblack): Do this in C++ instead of JS. function DedupeAutocompleteResults(autocompleteResults) { var urlToResultMap = {}; for (var i = 0, result; result = autocompleteResults[i]; ++i) { var url = CanonicalizeUrl(result.destination_url); if (url in urlToResultMap) { var oldRelevance = urlToResultMap[url].rankingData.relevance; var newRelevance = result.rankingData.relevance; if (newRelevance > oldRelevance) { urlToResultMap[url] = result; } } else { urlToResultMap[url] = result; } } var dedupedResults = []; for (url in urlToResultMap) { dedupedResults.push(urlToResultMap[url]); } return dedupedResults; } var lastPrefixQueriedForDuplicates = ''; var numDedupeAttempts = 0; function DedupeClientSuggestions(clientSuggestions) { var userInput = GetQuery(); if (userInput == lastPrefixQueriedForDuplicates) { numDedupeAttempts += 1; if (numDedupeAttempts > MAX_ALLOWED_DEDUPE_ATTEMPTS) { // Request blocked for privacy reasons. // TODO(dcblack): This check is insufficient. We should have a check // such that it's only callable once per onnativesuggestions, not // once per prefix. Also, there is a timing problem where if the user // types quickly then the client will (correctly) attempt to render // stale results, and end up calling dedupe multiple times when // getValue shows the same prefix. A better solution would be to have // the client send up rid ranges to dedupe against and have the // binary keep around all the old suggestions ever given to this // overlay. I suspect such an approach would clean up this code quite // a bit. return false; } } else { lastPrefixQueriedForDuplicates = userInput; numDedupeAttempts = 1; } var autocompleteResults = GetAutocompleteResults(); var nativeUrls = {}; for (var i = 0, result; result = autocompleteResults[i]; ++i) { var nativeUrl = CanonicalizeUrl(result.destination_url); nativeUrls[nativeUrl] = result.rid; } for (var i = 0; clientSuggestions[i] && i < MAX_CLIENT_SUGGESTIONS_TO_DEDUPE; ++i) { var result = clientSuggestions[i]; if (result.url) { var clientUrl = CanonicalizeUrl(result.url); if (clientUrl in nativeUrls) { result.duplicateOf = nativeUrls[clientUrl]; } } } return true; } // ========================================================================= // Exported functions // ========================================================================= this.__defineGetter__('value', GetQuery); this.__defineGetter__('verbatim', GetVerbatim); this.__defineGetter__('selectionStart', GetSelectionStart); this.__defineGetter__('selectionEnd', GetSelectionEnd); this.__defineGetter__('x', GetX); this.__defineGetter__('y', GetY); this.__defineGetter__('width', GetWidth); this.__defineGetter__('height', GetHeight); this.__defineGetter__('startMargin', GetStartMargin); this.__defineGetter__('endMargin', GetEndMargin); this.__defineGetter__('rtl', GetRightToLeft); this.__defineGetter__('nativeSuggestions', GetAutocompleteResultsWrapper); this.__defineGetter__('isKeyCaptureEnabled', IsKeyCaptureEnabled); this.__defineGetter__('context', GetContext); this.__defineGetter__('displayInstantResults', GetDisplayInstantResults); this.__defineGetter__('themeBackgroundInfo', GetThemeBackgroundInfo); this.__defineGetter__('themeAreaHeight', GetThemeAreaHeight); this.__defineGetter__('font', GetFont); this.__defineGetter__('fontSize', GetFontSize); this.setSuggestions = function(text) { SetSuggestions(text); }; this.setAutocompleteText = function(text, behavior) { SetQuerySuggestion(text, behavior); }; this.setRestrictedAutocompleteText = function(resultId) { SetQuerySuggestionFromAutocompleteResult(resultId); }; this.setValue = function(text, type) { SetQuery(text, type); }; this.setRestrictedValue = function(resultId) { SetQueryFromAutocompleteResult(resultId); }; this.show = function(reason, height) { Show(reason, height); }; this.markDuplicateSuggestions = function(clientSuggestions) { return DedupeClientSuggestions(clientSuggestions); }; this.navigateContentWindow = function(destination) { return NavigateContentWindow(destination); }; this.startCapturingKeyStrokes = function() { StartCapturingKeyStrokes(); }; this.stopCapturingKeyStrokes = function() { StopCapturingKeyStrokes(); }; this.onchange = null; this.onsubmit = null; this.oncancel = null; this.onresize = null; this.onautocompleteresults = null; this.onkeypress = null; this.onkeycapturechange = null; this.oncontextchange = null; this.onmarginchange = null; }; }
leiferikb/bitpop-private
chrome/renderer/resources/extensions/searchbox_api.js
JavaScript
bsd-3-clause
10,187
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2015, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ require('dts-generator').generate({ name: 'phosphor-playground', main: 'phosphor-playground/index', baseDir: 'lib', files: ['index.d.ts'], out: 'lib/phosphor-playground.d.ts', });
dwillmer/playground
scripts/dtsbundle.js
JavaScript
bsd-3-clause
539
/* Language: Brainfuck Author: Evgeny Stepanischev <[email protected]> Website: https://esolangs.org/wiki/Brainfuck */ function(hljs){ var LITERAL = { className: 'literal', begin: '[\\+\\-]', relevance: 0 }; return { aliases: ['bf'], contains: [ hljs.COMMENT( '[^\\[\\]\\.,\\+\\-<> \r\n]', '[\\[\\]\\.,\\+\\-<> \r\n]', { returnEnd: true, relevance: 0 } ), { className: 'title', begin: '[\\[\\]]', relevance: 0 }, { className: 'string', begin: '[\\.,]', relevance: 0 }, { // this mode works as the only relevance counter begin: /(?:\+\+|\-\-)/, contains: [LITERAL] }, LITERAL ] }; }
MakeNowJust/highlight.js
src/languages/brainfuck.js
JavaScript
bsd-3-clause
792
'use strict'; var _ = require('lodash'); var utility = require('../utility'); describe('language alias', function() { before(function() { var testHTML = document.querySelectorAll('#language-alias .hljs'); this.blocks = _.map(testHTML, 'innerHTML'); }); it('should highlight as aliased language', function() { var filename = utility.buildPath('fixtures', 'expect', 'languagealias.txt'), actual = this.blocks[0]; return utility.expectedFile(filename, 'utf-8', actual); }); });
tenbits/highlight.js
test/special/languageAlias.js
JavaScript
bsd-3-clause
557