code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
const App = require('./spec/app'); module.exports = config => { const params = { basePath: '', frameworks: [ 'express-http-server', 'jasmine' ], files: [ 'lib/**/*.js' ], colors: true, singleRun: true, logLevel: config.LOG_WARN, browsers: [ 'Chrome', 'PhantomJS' ], concurrency: Infinity, reporters: [ 'spec', 'coverage' ], preprocessors: { 'lib/**/*.js': ['coverage'] }, coverageReporter: { dir: 'coverage/', reporters: [ { type: 'html', subdir: 'report' }, { type: 'lcovonly', subdir: './', file: 'coverage-front.info' }, { type: 'lcov', subdir: '.' } ] }, browserDisconnectTimeout: 15000, browserNoActivityTimeout: 120000, expressHttpServer: { port: 8092, appVisitor: App } }; if (process.env.TRAVIS) { params.browsers = [ 'PhantomJS' ]; } config.set(params); };
kylekatarnls/momentum
karma.conf.js
JavaScript
mit
1,377
"use strict"; let fs = require("fs") , chalk = require("chalk"); module.exports = function(name) { let file = process.env.CONFIG_PATH + "initializers/" + name; if (!fs.existsSync(file + ".js")) console.log(chalk.red("\tInitializer", name + ".js not found, add it on /config/initializers")); return require(file); };
norman784/baxel
lib/module.js
JavaScript
mit
325
"use strict"; // Controller function Avatar(app, req, res) { // HTTP action this.action = (params) => { app.sendFile(res, './storage/users/' + params[0] + '/' + params[1]); }; }; module.exports = Avatar;
taviroquai/NodeVueBootstrapDemo
app/controller/Avatar.js
JavaScript
mit
240
"use strict"; var Response = (function () { function Response(result, childWork) { this.result = result; this.childWork = childWork; } return Response; }()); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Response; //# sourceMappingURL=response.js.map
colinmathews/node-workhorse
dist/lib/models/response.js
JavaScript
mit
313
Package.describe({ name: 'craigslist-utils', summary: 'Npm Craigslist-utils packaged for Meteor.' }); Npm.depends ({ 'craigslist-utils': '0.0.7' }); Package.on_use(function (api) { api.add_files('craigslist-utils.js', ['server']); api.export('CL'); }); Package.on_test(function (api) { api.use('craigslist-utils'); api.use('tinytest'); api.add_files('craigslist-utils_tests.js'); });
premosystems/meteor-craigslist-utils
package.js
JavaScript
mit
409
'use strict'; import Application from '../../core/Application.js'; import Action from '../../core/Action.js'; describe('Action', () => { var app; var action; class ChildAction extends Action { get name() { return 'ChildAction'; } } beforeEach(() => { app = new Application(); action = new ChildAction(app); }); it('has to be defined, be a function and can be instantiated', () => { expect(ChildAction).toBeDefined(); expect(ChildAction).toEqual(jasmine.any(Function)); expect(action instanceof ChildAction).toBe(true); }); it('holds an app instance', () => { var myApp = action.app; expect(myApp).toEqual(jasmine.any(Application)); expect(myApp).toBe(app); }); it('has an execute function that throws an error if it is not implemented', () => { expect(action.execute).toEqual(jasmine.any(Function)); expect(() => action.execute(payload)).toThrow(); }); });
m4n3z40/fluxone
__tests__/core/Action-test.js
JavaScript
mit
1,021
$(document).ready(function() { $('#mostrar_menu').click(function() { $('#sidebar-wrapper').toggle(300); }); });
AnaClaudiaConde/teste-lazyphp
template/vertical/menu.js
JavaScript
mit
135
const { app, BrowserWindow } = require('electron'); const {ipcMain} = require('electron'); // shared to-do list data global.sharedData = { itemList: [ { id: 0, text: "First meet up with David Lau on 5th July", isCompleted: true }, { id: 1, text: "David Bewick meet with David Lau on Monday", isCompleted: true }, { id: 2, text: "David Lau to speak with Kaspar on Wednesday", isCompleted: false } ], itemLatestID: 2 }; // electron main process app.on('ready', () => { const numOfWindows = 3; // number of windows, can grow dynamically var windows = []; for(var i = 0; i < numOfWindows; i++){ const win = new BrowserWindow({ width: 800, height: 600, show: true, }); win.loadURL(`file://${__dirname}/dist/index.html`); // win.openDevTools(); windows.push(win); } ipcMain.on('item-list-update', () => { windows.forEach((win) => { win.webContents.send('refresh-item-data'); }); }); });
davidlau325/bh-todo-list
main.js
JavaScript
mit
1,183
function generalAttack(attacker, receiver, weaponBonus){ //Weapon bonus of one means attacker gets bonus, 0 = neutral, and -1 = penalty if(attacker.attack > receiver.defense){ if(weaponBonus == 1){ receiver.health = receiver.health - ((attacker.attack + 2) - receiver.defense); }else if(weaponBonus == -1){ receiver.health = receiver.health - ((attacker.attack - 2) - receiver.defense); }else{ receiver.health = receiver.health - (attacker.attack - receiver.defense); } }else { receiver.health -= 2; } } function death(){ console.log("should be dead"); hero.alive = false; } // Global variables, we're all going to hell var healthPlaceholder = 0; var damageTaken = 0; var totalDamageDealt = 0; var totalDamageTaken = 0; var totalKills = 0; var totalTurns = 0; function wolvesAttack() { var wolf = new Character(); wolf.health = 30; wolf.attack = 5; wolf.defense = 5; while(wolf.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 20){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(wolf, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A wolf runs up and bites "+hero.name+" for " + damageTaken + " damage"); }else{ print_to_path("A wolf claww "+hero.name+" for " + damageTaken + " damage"); } } else { healthPlaceholder = wolf.health; generalAttack(hero, wolf,0); totalDamageDealt += (healthPlaceholder - wolf.health); print_to_path(hero.name+" attacks the wolf!"); print_to_path("The wolf's health falls to "+wolf.health); } totalTurns += 1; } if(wolf.health <= 0){ console.log("wolf dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function banditsAttack() { var bandit = new Character(); bandit.health = 40; bandit.attack = 10; bandit.defense = 5; while(bandit.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 30){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(bandit, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A clan of bandits knocks "+hero.name+" to the ground dealing " + damageTaken + " Damage"); }else{ print_to_path("A bandit Seaks up from behind stabbs "+hero.name+" dealing " + damageTaken + " Damage"); } } else { healthPlaceholder = bandit.health; if(hero.weapon == "Sword"){ generalAttack(hero, bandit,1); }else if(hero.weapon == "Bow"){ generalAttack(hero, bandit,-1); }else{ generalAttack(hero, bandit,0); } totalDamageDealt += (healthPlaceholder - bandit.health); print_to_path(hero.name+" attacks a bandit!"); print_to_path("The bandit's health falls to "+bandit.health); } totalTurns += 1; } if(bandit.health <= 0){ console.log("bandit dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function trollsAttack() { var troll = new Character(); troll.health = 50; troll.attack = 25; troll.defense = 15; while(troll.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 35){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(troll, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A troll throws a small axe at "+hero.name+" dealing " + damageTaken + " damage"); }else{ print_to_path("A troll smashes "+hero.name+" with his club for " + damageTaken + " damage"); } } else { healthPlaceholder = troll.health; generalAttack(hero, troll); totalDamageDealt += (healthPlaceholder - troll.health); print_to_path(hero.name+" attacks the troll!"); print_to_path("The troll's health falls to "+troll.health); } totalTurns += 1; } if(troll.health <= 0){ console.log("troll dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function golemsAttack() { var golem = new Character(); golem.health = 60; golem.attack = 10; golem.defense = 50; while(golem.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 20){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(golem, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A golem flails its arms, smashing "+hero.name+" into the ground, dealing " + damageTaken + " damage"); }else{ print_to_path("A golem stomps its foot on the ground causing rocks to fall on "+hero.name+" from the nearby mountain. dealing " + damageTaken + " Damage"); } } else { healthPlaceholder = golem.health; if(hero.weapon == "Mace"){ generalAttack(hero, golem,1); }else if(hero.weapon == "Sword"){ generalAttack(hero, golem,-1); }else{ generalAttack(hero, golem,0); } totalDamageDealt += (healthPlaceholder - golem.health); print_to_path(hero.name+" attacks the golem!"); print_to_path("The golem's health falls to "+golem.health); } totalTurns += 1; } if(golem.health <= 0){ console.log("golem dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function dragonAttack() { // atk 30 var dragon = new Character(); dragon.health = 60; dragon.attack = 30; dragon.defense = 30; while(dragon.health > 0 && hero.health > 0) { var chance = Math.floor((Math.random() * 100) + 1); if(chance < 20){ print_to_path(hero.name + " currently has " + hero.health + " health"); healthPlaceholder = hero.health; generalAttack(dragon, hero); damageTaken = healthPlaceholder - hero.health; totalDamageTaken += damageTaken; if(chance % 2 == 0){ print_to_path("A dragon breaths green flames at "+hero.name+" which inflicted a burn, dealing " + damageTaken + " damage"); }else{ print_to_path("A dragon wipes its tail along the floor flinging "+hero.name+" into the wall, dealing " + damageTaken + " damage"); } } else { healthPlaceholder = dragon.health; if(hero.weapon == "Bow"){ generalAttack(hero, dragon,1); }else if(hero.weapon == "Mace"){ generalAttack(hero, dragon,-1); }else{ generalAttack(hero, dragon,0); } totalDamageDealt += (healthPlaceholder - dragon.health); print_to_path(hero.name+" attacks the dragon!"); print_to_path("The dragon's health falls to: "+dragon.health); } totalTurns += 1; } if(dragon.health <= 0){ console.log("dragon dead"); totalKills += 1; } if(hero.health<= 0){ death(); } } function blackSquirrelAttacks() { // I has no Tail D: } function statistics() { print_to_path("<b>Score:</b>"); print_to_path("Total kills: " + totalKills + " | " + "Total turns: " + totalTurns + " | " + "Total damage dealt: " + totalDamageDealt + " | " + "Total damage taken: " + totalDamageTaken ); }
YSUatKHE14/zeroPlayerGame
js/pathFunctions.js
JavaScript
mit
7,261
var draw = SVG('mainPage'); var energyBar = draw.rect(0,5).move(0,598) .fill({ color: '#cc0', opacity: '1' }) .stroke({ color: '#fff', width: '1', opacity: '0.6'}); var port = 25550; var images = "http://"+document.location.hostname+":"+port+"/game/images/"; var localPlayers = new Array(); var localBullets = new Array(); var localBonus = new Array(); var bonusBars = new Array(); function PlayerEntity(mark, text) { this.mark = mark; this.text = text; } // Gestion des joueurs socket.on('refreshPlayers', function (players) { for(var i in players) { // Création des nouveaux joueurs if(typeof(localPlayers[i]) === "undefined") { var ownColor = '#fff'; if(players[i].id == socket.socket.sessionid) { // Attribution d'un marqueur de couleur pour le joueur en cours ownColor = '#c00'; } // Création des éléments var circle = draw.circle(6).move(players[i].x,players[i].y) .fill({ color: ownColor, opacity: '1' }) .stroke({ color: '#fff', width: '1' }); var text = draw.text(players[i].pseudo).font({ size: 12 }) .fill({ color: '#fff', opacity: '0.6' }) .stroke({ color: '#fff', width: '1', opacity: '0.4'}); // Déplacement du texte au dessus du marqueur text.move(players[i].x - text.bbox().width /2, players[i].y - text.bbox().height - 10); // Ajout de l'entité au tableau localPlayers[i] = new PlayerEntity(circle, text); } else { // Déplacement du joueur localPlayers[i].mark.move(players[i].x, players[i].y); localPlayers[i].text.move(players[i].x - localPlayers[i].text.bbox().width /2, players[i].y - localPlayers[i].text.bbox().height - 10); // Actualisation du joueur local if(players[i].id == socket.socket.sessionid) { // Affichage du bouton au bon endroit en fonction du mode if(players[i].spec == false) { document.getElementById("b1").style.display = "none"; document.getElementById("b2").style.display = "block"; } else { document.getElementById("b2").style.display = "none"; document.getElementById("b1").style.display = "block"; } // Actualisation de la barre d'énergie if (players[i].energy > 1) { energyBar.width(((players[i].energy-1)/100)*800); } else { energyBar.width(0); } // Actualisation des barres de bonus for(var j in bonusBars) { switch(bonusBars[j].name) { case "speed": bonusBars[j].bar.width(players[i].bSpeed); break; case "arrow": bonusBars[j].bar.width(players[i].bArrow); break; } } } } } }); // Passage en spectateur function _setSpec() { socket.emit('setSpec', 1); } // Ajout d'une barre de bonus socket.on('newPlayerBonus', function (bonus) { // Vérification de la non existence de la barre for(var i in bonusBars) { if(bonusBars[i].name == bonus.name) { return; } } var rect = draw.rect(0,12).move(0,15*(bonusBars.length+1)) .fill({ color: bonus.color, opacity: '0.4' }); bonusBars.push({name: bonus.name, bar: rect}); }); // Rerait d'un joueur socket.on('removePlayer', function (id) { localPlayers[id].mark.remove(); localPlayers[id].text.remove(); localPlayers.splice(id,1); }); // Affichage d'un bonus socket.on('displayBonus', function (bonus) { for(var i in bonus) { // Création des nouveaux bonus if(typeof(localBonus[i]) === "undefined") { localBonus[i] = draw.image(images+""+bonus[i].image+".png") .move(bonus[i].x,bonus[i].y); } } }); // Retrait d'un bonus socket.on('removeBonus', function (bonusID) { if (bonusID == -1) { for(var i in localBonus) { localBonus[i].remove(); } localBonus = []; } else { localBonus[bonusID].remove(); localBonus.splice(bonusID,1); } }); // Rafraichissement du tableau de scores socket.on('refreshScores', function (players) { // Arrangement du tableau en fonction des scores players = players.sort(function(a,b) { return a.points > b.points; }).reverse(); // Formattage de la liste des joueurs var list = "<b>Joueurs en ligne : </b><br />"; var listSpec = "<b>Spectateurs : </b><br />"; for(var i in players) { if(players[i].spec == 0) { if(players[i].alive == 0) { list = list + "<span style='color:#" + players[i].color + "; float:left;'><s>" + players[i].pseudo + "</s></span><span style='float:right;'>- " + players[i].points + " points</span><br />"; } else { list = list + "<span style='color:#" + players[i].color + "; float:left;'>" + players[i].pseudo + "</span><span style='float:right;'>- " + players[i].points + " points</span><br />"; } } else { listSpec = listSpec + "<span style='color:#" + players[i].color + "; float:left;'>" + players[i].pseudo + "</span><br />"; } } // Mise à jour de l'affichage de la liste des joueurs document.getElementById("scores").innerHTML = list; document.getElementById("specs").innerHTML = listSpec; }); // Ajout des nouvelles balles contenues dans le buffer var max = 0; socket.on('refreshBullets', function (bulletTable) { for(var i in bulletTable) { // Création des traces var length = max + i; if(typeof(localBullets[length]) === "undefined") { localBullets[length] = draw.circle(5/*heignt line*/) .move(bulletTable[i].x,bulletTable[i].y) .fill({ color:'#'+bulletTable[i].color }) .stroke({ color: '#fff', width: '1', opacity: '0.5' }); max++; } } }); // Réinitialisation du terrain socket.on('resetGround', function (e) { for(var i in localBullets) { localBullets[i].remove(); } localBullets = []; }); // Arret du serveur socket.on('stopServer', function (e) { window.location.replace("http://"+document.location.hostname+"/?alert=1"); }); // Kick du joueur socket.on('kickPlayer', function (e) { window.location.replace("http://"+document.location.hostname+"/?kick=1"); }); // Gestion d'un nouveau message socket.on('newMessage', function (e) { var tmp = document.getElementById("comments").innerHTML; document.getElementById("comments").innerHTML = "<b>"+e.pseudo+" : </b>"+e.message+"<br />"+tmp; }); // Affichage d'une alerte socket.on('displayAlert', function(text, color, duration) { if(color == '') { color = "#fff"; } if(duration == '') { duration = 1000; } var appear, disappear, deleteAlert, alert = draw.text(text).font({ size: 36 }); appear = function() { alert.move(400-(alert.bbox().width / 2), 100) .fill({ color: color, opacity: '0' }) .animate(100).fill({ opacity: '1' }) .after(disappear); }; disappear = function() { setTimeout(function() { alert.animate(500).fill({ opacity: '0' }).after(deleteAlert); }, duration); }; deleteAlert = function() { alert.remove(); } appear(); }); // Affichage d'une victoire socket.on('displayVictory', function(pseudo) { var appear, disappear, deleteAlert, alert = draw.text("Victoire de "+pseudo+" !").font({ size: 20 }); appear = function() { alert.move(400-(alert.bbox().width / 2), 50) .fill({ color: '#fff', opacity: '0' }) .animate(100).fill({ opacity: '1' }) .after(disappear); }; disappear = function() { setTimeout(function() { alert.animate(500).fill({ opacity: '0' }).after(deleteAlert); }, 1000); }; deleteAlert = function() { alert.remove(); } appear(); });
wardensfx/E-Tron
game/scripts/events.js
JavaScript
mit
7,363
goog.provide('gmf.DisplayquerygridController'); goog.provide('gmf.displayquerygridDirective'); goog.require('gmf'); goog.require('ngeo.CsvDownload'); goog.require('ngeo.GridConfig'); /** @suppress {extraRequire} */ goog.require('ngeo.gridDirective'); goog.require('ngeo.FeatureOverlay'); goog.require('ngeo.FeatureOverlayMgr'); goog.require('ol.Collection'); goog.require('ol.style.Circle'); goog.require('ol.style.Fill'); goog.require('ol.style.Stroke'); goog.require('ol.style.Style'); ngeo.module.value('gmfDisplayquerygridTemplateUrl', /** * @param {angular.JQLite} element Element. * @param {angular.Attributes} attrs Attributes. * @return {string} Template. */ function(element, attrs) { var templateUrl = attrs['gmfDisplayquerygridTemplateurl']; return templateUrl !== undefined ? templateUrl : gmf.baseTemplateUrl + '/displayquerygrid.html'; }); /** * Provides a directive to display results of the {@link ngeo.queryResult} in a * grid and shows related features on the map using * the {@link ngeo.FeatureOverlayMgr}. * * You can override the default directive's template by setting the * value `gmfDisplayquerygridTemplateUrl`. * * Features displayed on the map use a default style but you can override these * styles by passing ol.style.Style objects as attributes of this directive. * * Example: * * <gmf-displayquerygrid * gmf-displayquerygrid-map="ctrl.map" * gmf-displayquerygrid-featuresstyle="ctrl.styleForAllFeatures" * gmf-displayquerygrid-selectedfeaturestyle="ctrl.styleForTheCurrentFeature"> * </gmf-displayquerygrid> * * @htmlAttribute {boolean} gmf-displayquerygrid-active The active state of the component. * @htmlAttribute {ol.style.Style} gmf-displayquerygrid-featuresstyle A style * object for all features from the result of the query. * @htmlAttribute {ol.style.Style} gmf-displayquerygrid-selectedfeaturestyle A style * object for the currently selected features. * @htmlAttribute {ol.Map} gmf-displayquerygrid-map The map. * @htmlAttribute {boolean?} gmf-displayquerygrid-removeemptycolumns Optional. Should * empty columns be hidden? Default: `false`. * @htmlAttribute {number?} gmf-displayquerygrid-maxrecenterzoom Optional. Maximum * zoom-level to use when zooming to selected features. * @htmlAttribute {gmfx.GridMergeTabs?} gmf-displayquerygrid-gridmergetabas Optional. * Configuration to merge grids with the same attributes into a single grid. * @param {string} gmfDisplayquerygridTemplateUrl URL to a template. * @return {angular.Directive} Directive Definition Object. * @ngInject * @ngdoc directive * @ngname gmfDisplayquerygrid */ gmf.displayquerygridDirective = function( gmfDisplayquerygridTemplateUrl) { return { bindToController: true, controller: 'GmfDisplayquerygridController', controllerAs: 'ctrl', templateUrl: gmfDisplayquerygridTemplateUrl, replace: true, restrict: 'E', scope: { 'active': '=gmfDisplayquerygridActive', 'featuresStyleFn': '&gmfDisplayquerygridFeaturesstyle', 'selectedFeatureStyleFn': '&gmfDisplayquerygridSourceselectedfeaturestyle', 'getMapFn': '&gmfDisplayquerygridMap', 'removeEmptyColumnsFn': '&?gmfDisplayquerygridRemoveemptycolumns', 'maxResultsFn': '&?gmfDisplayquerygridMaxresults', 'maxRecenterZoomFn': '&?gmfDisplayquerygridMaxrecenterzoom', 'mergeTabsFn': '&?gmfDisplayquerygridMergetabs' } }; }; gmf.module.directive('gmfDisplayquerygrid', gmf.displayquerygridDirective); /** * Controller for the query grid. * * @param {!angular.Scope} $scope Angular scope. * @param {ngeox.QueryResult} ngeoQueryResult ngeo query result. * @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr The ngeo feature * overlay manager service. * @param {angular.$timeout} $timeout Angular timeout service. * @param {ngeo.CsvDownload} ngeoCsvDownload CSV download service. * @param {ngeo.Query} ngeoQuery Query service. * @param {angular.JQLite} $element Element. * @constructor * @export * @ngInject * @ngdoc Controller * @ngname GmfDisplayquerygridController */ gmf.DisplayquerygridController = function($scope, ngeoQueryResult, ngeoFeatureOverlayMgr, $timeout, ngeoCsvDownload, ngeoQuery, $element) { /** * @type {!angular.Scope} * @private */ this.$scope_ = $scope; /** * @type {angular.$timeout} * @private */ this.$timeout_ = $timeout; /** * @type {ngeox.QueryResult} * @export */ this.ngeoQueryResult = ngeoQueryResult; /** * @type {ngeo.CsvDownload} * @private */ this.ngeoCsvDownload_ = ngeoCsvDownload; /** * @type {angular.JQLite} * @private */ this.$element_ = $element; /** * @type {number} * @export */ this.maxResults = ngeoQuery.getLimit(); /** * @type {boolean} * @export */ this.active = false; /** * @type {boolean} * @export */ this.pending = false; /** * @type {!Object.<string, gmfx.GridSource>} * @export */ this.gridSources = {}; /** * IDs of the grid sources in the order they were loaded. * @type {Array.<string>} * @export */ this.loadedGridSources = []; /** * The id of the currently shown query source. * @type {string|number|null} * @export */ this.selectedTab = null; /** * @type {boolean} * @private */ this.removeEmptyColumns_ = this['removeEmptyColumnsFn'] ? this['removeEmptyColumnsFn']() === true : false; /** * @type {number|undefined} * @export */ this.maxRecenterZoom = this['maxRecenterZoomFn'] ? this['maxRecenterZoomFn']() : undefined; var mergeTabs = this['mergeTabsFn'] ? this['mergeTabsFn']() : {}; /** * @type {!gmfx.GridMergeTabs} * @private */ this.mergeTabs_ = mergeTabs ? mergeTabs : {}; /** * A mapping between row uid and the corresponding feature for each * source. * @type {!Object.<string, Object.<string, ol.Feature>>} * @private */ this.featuresForSources_ = {}; // Styles for displayed features (features) and selected features // (highlightFeatures_) (user can set both styles). /** * @type {ol.Collection} * @private */ this.features_ = new ol.Collection(); var featuresOverlay = ngeoFeatureOverlayMgr.getFeatureOverlay(); var featuresStyle = this['featuresStyleFn'](); if (featuresStyle !== undefined) { goog.asserts.assertInstanceof(featuresStyle, ol.style.Style); featuresOverlay.setStyle(featuresStyle); } featuresOverlay.setFeatures(this.features_); /** * @type {ngeo.FeatureOverlay} * @private */ this.highlightFeatureOverlay_ = ngeoFeatureOverlayMgr.getFeatureOverlay(); /** * @type {ol.Collection} * @private */ this.highlightFeatures_ = new ol.Collection(); this.highlightFeatureOverlay_.setFeatures(this.highlightFeatures_); var highlightFeatureStyle = this['selectedFeatureStyleFn'](); if (highlightFeatureStyle !== undefined) { goog.asserts.assertInstanceof(highlightFeatureStyle, ol.style.Style); } else { var fill = new ol.style.Fill({color: [255, 0, 0, 0.6]}); var stroke = new ol.style.Stroke({color: [255, 0, 0, 1], width: 2}); highlightFeatureStyle = new ol.style.Style({ fill: fill, image: new ol.style.Circle({fill: fill, radius: 5, stroke: stroke}), stroke: stroke, zIndex: 10 }); } this.highlightFeatureOverlay_.setStyle(highlightFeatureStyle); var map = null; var mapFn = this['getMapFn']; if (mapFn) { map = mapFn(); goog.asserts.assertInstanceof(map, ol.Map); } /** * @type {ol.Map} * @private */ this.map_ = map; // Watch the ngeo query result service. this.$scope_.$watchCollection( function() { return ngeoQueryResult; }, function(newQueryResult, oldQueryResult) { if (newQueryResult !== oldQueryResult) { this.updateData_(); } }.bind(this)); /** * An unregister function returned from `$scope.$watchCollection` for * "on-select" changes (when rows are selected/unselected). * @type {?function()} * @private */ this.unregisterSelectWatcher_ = null; }; /** * Returns a list of grid sources in the order they were loaded. * @export * @return {Array.<gmfx.GridSource>} Grid sources. */ gmf.DisplayquerygridController.prototype.getGridSources = function() { return this.loadedGridSources.map(function(sourceId) { return this.gridSources[sourceId]; }.bind(this)); }; /** * @private */ gmf.DisplayquerygridController.prototype.updateData_ = function() { // close if there are no results if (this.ngeoQueryResult.total === 0 && !this.hasOneWithTooManyResults_()) { var oldActive = this.active; this.clear(); if (oldActive) { // don't close if there are pending queries this.active = this.ngeoQueryResult.pending; this.pending = this.ngeoQueryResult.pending; } return; } this.active = true; this.pending = false; var sources = this.ngeoQueryResult.sources; // merge sources if requested if (Object.keys(this.mergeTabs_).length > 0) { sources = this.getMergedSources_(sources); } // create grids (only for source with features or with too many results) sources.forEach(function(source) { if (source.tooManyResults) { this.makeGrid_(null, source); } else { var features = source.features; if (features.length > 0) { this.collectData_(source); } } }.bind(this)); if (this.loadedGridSources.length == 0) { // if no grids were created, do not show this.active = false; return; } // keep the first existing navigation tab open if (this.selectedTab === null || !(('' + this.selectedTab) in this.gridSources)) { // selecting the tab is done in a timeout, because otherwise in rare cases // `ng-class` might set the `active` class on multiple tabs. this.$timeout_(function() { var firstSourceId = this.loadedGridSources[0]; this.selectTab(this.gridSources[firstSourceId]); this.reflowGrid_(firstSourceId); }.bind(this), 0); } }; /** * @private * @return {boolean} If one of the source has too many results. */ gmf.DisplayquerygridController.prototype.hasOneWithTooManyResults_ = function() { return this.ngeoQueryResult.sources.some(function(source) { return source.tooManyResults; }); }; /** * Returns if the given grid source is selected? * @export * @param {gmfx.GridSource} gridSource Grid source. * @return {boolean} Is selected? */ gmf.DisplayquerygridController.prototype.isSelected = function(gridSource) { return this.selectedTab === gridSource.source.id; }; /** * Try to merge the mergable sources. * @param {Array.<ngeox.QueryResultSource>} sources Sources. * @return {Array.<ngeox.QueryResultSource>} The merged sources. * @private */ gmf.DisplayquerygridController.prototype.getMergedSources_ = function(sources) { var allSources = []; /** @type {Object.<string, ngeox.QueryResultSource>} */ var mergedSources = {}; sources.forEach(function(source) { // check if this source can be merged var mergedSource = this.getMergedSource_(source, mergedSources); if (mergedSource === null) { // this source should not be merged, add as is allSources.push(source); } }.bind(this)); for (var mergedSourceId in mergedSources) { allSources.push(mergedSources[mergedSourceId]); } return allSources; }; /** * Check if the given source should be merged. If so, an artificial source * that will contain the features of all mergable sources is returned. If not, * `null` is returned. * @param {ngeox.QueryResultSource} source Source. * @param {Object.<string, ngeox.QueryResultSource>} mergedSources Merged sources. * @return {?ngeox.QueryResultSource} A merged source of null if the source should * not be merged. * @private */ gmf.DisplayquerygridController.prototype.getMergedSource_ = function(source, mergedSources) { var mergeSourceId = null; for (var currentMergeSourceId in this.mergeTabs_) { var sourceIds = this.mergeTabs_[currentMergeSourceId]; var containsSource = sourceIds.some(function(sourceId) { return sourceId == source.id; }); if (containsSource) { mergeSourceId = currentMergeSourceId; break; } } if (mergeSourceId === null) { // this source should not be merged return null; } /** @type {ngeox.QueryResultSource} */ var mergeSource; if (mergeSourceId in mergedSources) { mergeSource = mergedSources[mergeSourceId]; } else { mergeSource = { features: [], id: mergeSourceId, label: mergeSourceId, pending: false, queried: true, tooManyResults: false, totalFeatureCount: undefined }; mergedSources[mergeSourceId] = mergeSource; } // add features of source to merge source source.features.forEach(function(feature) { mergeSource.features.push(feature); }); // if one of the source has too many results, the resulting merged source will // also be marked with `tooManyResults` and will not contain any features. mergeSource.tooManyResults = mergeSource.tooManyResults || source.tooManyResults; if (mergeSource.tooManyResults) { mergeSource.totalFeatureCount = (mergeSource.totalFeatureCount !== undefined) ? mergeSource.totalFeatureCount + mergeSource.features.length : mergeSource.features.length; mergeSource.features = []; } if (source.totalFeatureCount !== undefined) { mergeSource.totalFeatureCount = (mergeSource.totalFeatureCount !== undefined) ? mergeSource.totalFeatureCount + source.totalFeatureCount : source.totalFeatureCount; } return mergeSource; }; /** * Collect all features in the queryResult object. * @param {ngeox.QueryResultSource} source Result source. * @private */ gmf.DisplayquerygridController.prototype.collectData_ = function(source) { var features = source.features; var allProperties = []; var featureGeometriesNames = []; var featuresForSource = {}; var properties, featureGeometryName; features.forEach(function(feature) { properties = feature.getProperties(); if (properties !== undefined) { // Keeps distinct geometry names to remove theme later. featureGeometryName = feature.getGeometryName(); if (featureGeometriesNames.indexOf(featureGeometryName) === -1) { featureGeometriesNames.push(featureGeometryName); } allProperties.push(properties); featuresForSource[ngeo.GridConfig.getRowUid(properties)] = feature; } }.bind(this)); this.cleanProperties_(allProperties, featureGeometriesNames); if (allProperties.length > 0) { var gridCreated = this.makeGrid_(allProperties, source); if (gridCreated) { this.featuresForSources_['' + source.id] = featuresForSource; } } }; /** * Remove all unwanted columns. * @param {Array.<Object>} allProperties A row. * @param {Array.<string>} featureGeometriesNames Geometry names. * @private */ gmf.DisplayquerygridController.prototype.cleanProperties_ = function( allProperties, featureGeometriesNames) { allProperties.forEach(function(properties) { featureGeometriesNames.forEach(function(featureGeometryName) { delete properties[featureGeometryName]; }); delete properties['boundedBy']; }); if (this.removeEmptyColumns_ === true) { this.removeEmptyColumnsFn_(allProperties); } }; /** * Remove columns that will be completely empty between each properties. * @param {Array.<Object>} allProperties A row. * @private */ gmf.DisplayquerygridController.prototype.removeEmptyColumnsFn_ = function( allProperties) { // Keep all keys that correspond to at least one value in a properties object. var keysToKeep = []; var i, key; for (key in allProperties[0]) { for (i = 0; i < allProperties.length; i++) { if (allProperties[i][key] !== undefined) { keysToKeep.push(key); break; } } } // Get all keys that previously always refers always to an empty value. var keyToRemove; allProperties.forEach(function(properties) { keyToRemove = []; for (key in properties) { if (keysToKeep.indexOf(key) === -1) { keyToRemove.push(key); } } // Remove these keys. keyToRemove.forEach(function(key) { delete properties[key]; }); }); }; /** * @param {?Array.<Object>} data Grid rows. * @param {ngeox.QueryResultSource} source Query source. * @return {boolean} Returns true if a grid was created. * @private */ gmf.DisplayquerygridController.prototype.makeGrid_ = function(data, source) { var sourceId = '' + source.id; var gridConfig = null; if (data !== null) { gridConfig = this.getGridConfiguration_(data); if (gridConfig === null) { return false; } } if (this.loadedGridSources.indexOf(sourceId) == -1) { this.loadedGridSources.push(sourceId); } this.gridSources[sourceId] = { configuration: gridConfig, source: source }; return true; }; /** * @param {Array.<!Object>} data Grid rows. * @return {?ngeo.GridConfig} Grid config. * @private */ gmf.DisplayquerygridController.prototype.getGridConfiguration_ = function( data) { goog.asserts.assert(data.length > 0); var columns = Object.keys(data[0]); /** @type {Array.<ngeox.GridColumnDef>} */ var columnDefs = []; columns.forEach(function(column) { if (column !== 'ol_uid') { columnDefs.push(/** @type {ngeox.GridColumnDef} */ ({ name: column })); } }); if (columnDefs.length > 0) { return new ngeo.GridConfig(data, columnDefs); } else { // no columns, do not show grid return null; } }; /** * Remove the current selected feature and source and remove all features * from the map. * @export */ gmf.DisplayquerygridController.prototype.clear = function() { this.active = false; this.pending = false; this.gridSources = {}; this.loadedGridSources = []; this.selectedTab = null; this.tooManyResults = false; this.features_.clear(); this.highlightFeatures_.clear(); this.featuresForSources_ = {}; if (this.unregisterSelectWatcher_) { this.unregisterSelectWatcher_(); } }; /** * Select the tab for the given grid source. * @param {gmfx.GridSource} gridSource Grid source. * @export */ gmf.DisplayquerygridController.prototype.selectTab = function(gridSource) { var source = gridSource.source; this.selectedTab = source.id; if (this.unregisterSelectWatcher_) { this.unregisterSelectWatcher_(); this.unregisterSelectWatcher_ = null; } if (gridSource.configuration !== null) { this.unregisterSelectWatcher_ = this.$scope_.$watchCollection( function() { return gridSource.configuration.selectedRows; }, function(newSelected, oldSelectedRows) { if (Object.keys(newSelected) !== Object.keys(oldSelectedRows)) { this.onSelectionChanged_(); } }.bind(this)); } this.updateFeatures_(gridSource); }; /** * @private * @param {string|number} sourceId Id of the source that should be refreshed. */ gmf.DisplayquerygridController.prototype.reflowGrid_ = function(sourceId) { // this is a "work-around" to make sure that the grid is rendered correctly. // when a pane is activated by setting `this.selectedTab`, the class `active` // is not yet set on the pane. that's why the class is set manually, and // after the pane is shown (in the next digest loop), the grid table can // be refreshed. var activePane = this.$element_.find('div.tab-pane#' + sourceId); activePane.removeClass('active').addClass('active'); this.$timeout_(function() { activePane.find('div.ngeo-grid-table-container table')['trigger']('reflow'); }); }; /** * Called when the row selection has changed. * @private */ gmf.DisplayquerygridController.prototype.onSelectionChanged_ = function() { if (this.selectedTab === null) { return; } var gridSource = this.gridSources['' + this.selectedTab]; this.updateFeatures_(gridSource); }; /** * @param {gmfx.GridSource} gridSource Grid source * @private */ gmf.DisplayquerygridController.prototype.updateFeatures_ = function(gridSource) { this.features_.clear(); this.highlightFeatures_.clear(); if (gridSource.configuration === null) { return; } var sourceId = '' + gridSource.source.id; var featuresForSource = this.featuresForSources_[sourceId]; var selectedRows = gridSource.configuration.selectedRows; for (var rowId in featuresForSource) { var feature = featuresForSource[rowId]; if (rowId in selectedRows) { this.highlightFeatures_.push(feature); } else { this.features_.push(feature); } } }; /** * Get the currently shown grid source. * @export * @return {gmfx.GridSource|null} Grid source. */ gmf.DisplayquerygridController.prototype.getActiveGridSource = function() { if (this.selectedTab === null) { return null; } else { return this.gridSources['' + this.selectedTab]; } }; /** * Returns if a row of the currently active grid is selected? * @export * @return {boolean} Is one selected? */ gmf.DisplayquerygridController.prototype.isOneSelected = function() { var source = this.getActiveGridSource(); if (source === null || source.configuration === null) { return false; } else { return source.configuration.getSelectedCount() > 0; } }; /** * Returns the number of selected rows of the currently active grid. * @export * @return {number} The number of selected rows. */ gmf.DisplayquerygridController.prototype.getSelectedRowCount = function() { var source = this.getActiveGridSource(); if (source === null || source.configuration === null) { return 0; } else { return source.configuration.getSelectedCount(); } }; /** * Select all rows of the currently active grid. * @export */ gmf.DisplayquerygridController.prototype.selectAll = function() { var source = this.getActiveGridSource(); if (source !== null) { source.configuration.selectAll(); } }; /** * Unselect all rows of the currently active grid. * @export */ gmf.DisplayquerygridController.prototype.unselectAll = function() { var source = this.getActiveGridSource(); if (source !== null) { source.configuration.unselectAll(); } }; /** * Invert the selection of the currently active grid. * @export */ gmf.DisplayquerygridController.prototype.invertSelection = function() { var source = this.getActiveGridSource(); if (source !== null) { source.configuration.invertSelection(); } }; /** * Zoom to the selected features. * @export */ gmf.DisplayquerygridController.prototype.zoomToSelection = function() { var source = this.getActiveGridSource(); if (source !== null) { var extent = ol.extent.createEmpty(); this.highlightFeatures_.forEach(function(feature) { ol.extent.extend(extent, feature.getGeometry().getExtent()); }); var mapSize = this.map_.getSize(); goog.asserts.assert(mapSize !== undefined); this.map_.getView().fit(extent, mapSize, {maxZoom: this.maxRecenterZoom}); } }; /** * Start a CSV download for the selected features. * @export */ gmf.DisplayquerygridController.prototype.downloadCsv = function() { var source = this.getActiveGridSource(); if (source !== null) { var columnDefs = source.configuration.columnDefs; goog.asserts.assert(columnDefs !== undefined); var selectedRows = source.configuration.getSelectedRows(); this.ngeoCsvDownload_.startDownload( selectedRows, columnDefs, 'query-results'); } }; gmf.module.controller('GmfDisplayquerygridController', gmf.DisplayquerygridController);
kalbermattenm/ngeo
contribs/gmf/src/directives/displayquerygrid.js
JavaScript
mit
23,829
var expect = chai.expect; describe("sails", function() { beforeEach(function() { }); afterEach(function() { }); it('should not fail', function() { expect(true).to.be.true; }); });
ioisup/CAMS
test/bootstrap.Spec.js
JavaScript
mit
190
// external imports import axios from 'axios' import { Base64 } from 'js-base64' import path from 'path' import fm from 'front-matter' // local imports import zipObject from '../zipObject' import decrypt from '../decrypt' /** 从github调用并在本地缓存期刊内容,返回Promise。主要函数: * getContent: 调取特定期刊特定内容。如获取第1期“心智”子栏目中第2篇文章正文:getContent(['issues', '1', '心智', '2', 'article.md'])。 * getCurrentIssue: 获取最新期刊号,无需参数。 * getAbstracts: 获取所有文章简介,需要提供期刊号。 */ class magazineStorage { /** * 建立新期刊instance. * @param {string} owner - github项目有所有者 * @param {string} repo - github项目名称 * @param {array} columns - 各子栏目列表 */ constructor(owner = 'Perspicere', repo = 'PerspicereContent', columns = ['心智', '此岸', '梦境']) { // github account settings this.owner = owner this.repo = repo // array of submodules this.columns = columns // grap window storage this.storage = window.sessionStorage // keys to be replaced with content this.urlReplace = ['img', 'image'] // github api this.baseURL = 'https://api.github.com/' // github api // github 禁止使用明文储存access token,此处使用加密token // 新生成token之后可以通过encrypt函数加密 // TODO: use OAuth? this.github = axios.create({ baseURL: this.baseURL, auth: { username: 'guoliu', password: decrypt( '6a1975233d2505057cfced9c0c847f9c99f97f8f54df8f4cd90d4d3949d8dff02afdac79c3dec4a9135fad4a474f8288' ) }, timeout: 10000 }) } // get content from local storage // 总数据大小如果超过5mb限制,需要优化存储 get content() { let content = this.storage.getItem('content') if (!content) { return {} } return JSON.parse(content) } // cache content to local storage set content(tree) { this.storage.setItem('content', JSON.stringify(tree)) } // get current issue number from local storage get currentIssue() { return this.storage.getItem('currentIssue') } // cache current issue number set currentIssue(issue) { this.storage.setItem('currentIssue', issue) } // locate leaf note in a tree static locateLeaf(tree, location) { if (location.length === 0) { return tree } try { return magazineStorage.locateLeaf(tree[location[0]], location.slice(1)) } catch (err) { return null } } // helper function to return tree with an extra leaf node static appendLeaf(tree, location, leaf) { if (location.length === 0) { return leaf } else if (!tree) { tree = {} } return { ...tree, [location[0]]: magazineStorage.appendLeaf(tree[location[0]], location.slice(1), leaf) } } // build url for image imageURL = location => `https://github.com/${this.owner}/${this.repo}/raw/master/${path.join(...location)}` // pull content from github with given path pullContent = async location => { try { const res = await this.github.get(`/repos/${this.owner}/${this.repo}/contents/${path.join(...location)}`) return res.data } catch (err) { console.warn(`Error pulling data from [${location.join(', ')}], null value will be returned instead`, err) return null } } // parse responce, returns an object parseData = data => { if (!data) { return null } // if we get an array, parse every element if (data.constructor === Array) { return data.reduce( (accumulated, current) => ({ ...accumulated, [current.name]: this.parseData(current) }), {} ) } if (data.content) { const ext = path.extname(data.path) const content = Base64.decode(data.content) // if it's a markdown file, parse it and get meta info if (ext === '.md') { const { attributes, body } = fm(content) // replace image paths const bodyWithUrl = body.replace( /(!\[.*?\]\()(.*)(\)\s)/, (_, prev, url, post) => `${prev}${this.imageURL([...data.path.split('/').slice(0, -1), url])}${post}` ) return { ...attributes, body: bodyWithUrl } } if (ext === '.json') { // if it's a json, parse it return JSON.parse(content) } return content } if (data.type === 'dir') { // if we get a directory return {} } return null } /** * 调用期刊内容. * @param {string} location - 内容位置,描述目标文档位置。例如第1期“心智”子栏目中第2篇文章正文:['issues', '1', '心智', '2', 'article.md']。 * @return {object} 目标内容 */ getContent = async location => { // 尝试从本地获取 let contentNode = magazineStorage.locateLeaf(this.content, location) || {} // 本地无值,从远程调用 if (contentNode.constructor === Object && Object.keys(contentNode).length === 0) { const data = await this.pullContent(location) contentNode = this.parseData(data) // 将json中路径替换为url,例如图片 if (contentNode && contentNode.constructor === Object && Object.keys(contentNode).length > 0) { const URLkeys = Object.keys(contentNode).filter(field => this.urlReplace.includes(field)) const URLs = URLkeys.map(key => this.imageURL([...location.slice(0, -1), contentNode[key]])) contentNode = { ...contentNode, ...zipObject(URLkeys, URLs) } } this.content = magazineStorage.appendLeaf(this.content, location, contentNode) } return contentNode } /** * 获取最新期刊号。 * @return {int} 最新期刊号。 */ getCurrentIssue = async () => { if (!this.currentIssue) { const data = await this.getContent(['issues']) this.currentIssue = Object.keys(data) .filter( entry => data[entry] && data[entry].constructor === Object // is a directory ) .reduce((a, b) => Math.max(parseInt(a), parseInt(b))) } return this.currentIssue } /** * 获取期刊所有文章简介。 * @param {int} issue - 期刊号。 * @return {object} 该期所有文章简介。 */ getIssueAbstract = async issue => { // 默认获取最新一期 let issueNumber = issue if (!issue) { issueNumber = await this.getCurrentIssue() } const issueContent = await Promise.all( this.columns.map(async column => { // 栏目文章列表 const articleList = Object.keys(await this.getContent(['issues', issueNumber, column])) // 各文章元信息 const columnContent = await Promise.all( articleList.map(article => this.getContent(['issues', issueNumber, column, article, 'article.md'])) ) return zipObject(articleList, columnContent) }) ) // 本期信息 const meta = await this.getContent(['issues', issueNumber, 'meta.json']) return { ...meta, content: zipObject(this.columns, issueContent) } } /** * 获取期刊所有单篇文章。 * @return {object} 所有单篇文章。 * TODO: 仅返回一定数量各子栏目最新文章 */ getArticleAbstract = async () => { // 各栏目 const articlesContent = await Promise.all( this.columns.map(async column => { // 栏目文章列表 const articleList = Object.keys((await this.getContent(['articles', column])) || {}) // 各文章元信息 const columnContent = await Promise.all( articleList.map(article => this.getContent(['articles', column, article, 'article.md'])) ) return zipObject(articleList, columnContent) }) ) return zipObject(this.columns, articlesContent) } } export default new magazineStorage()
Perspicere/PerspicereMagazine
src/store/actions/utils/magazineStorage/index.js
JavaScript
mit
8,028
export default { navigator: { doc: 'Docs', demo: 'Demo', started: 'Get Started' }, features: { userExperience: { title: 'Optimize Experience', desc: 'To make scroll more smoothly, We support flexible configurations about inertial scrolling, rebound, fade scrollbar, etc. which could optimize user experience obviously.' }, application: { title: 'Rich Features', desc: 'It can be applied to normal scroll list, picker, slide, index list, start guidance, etc. What\'s more, some complicated needs like pull down refresh and pull up load can be implemented much easier.' }, dependence: { title: 'Dependence Free', desc: 'As a plain JavaScript library, BetterScroll doesn\'t depend on any framework, you could use it alone, or with any other MVVM frameworks.' } }, examples: { normalScrollList: 'Normal Scroll List', indexList: 'Index List', picker: 'Picker', slide: 'Slide', startGuidance: 'Start Guidance', freeScroll: 'Free Scroll', formList: 'Form List', verticalScrollImg: 'vertical-scroll-en.jpeg', indexListImg: 'index-list.jpeg', pickerImg: 'picker-en.jpeg', slideImg: 'slide.jpeg', startGuidanceImg: 'full-page-slide.jpeg', freeScrollImg: 'free-scroll.jpeg', formListImg: 'form-list-en.jpeg' }, normalScrollListPage: { desc: 'Nomal scroll list based on BetterScroll', scrollbar: 'Scrollbar', pullDownRefresh: 'Pull Down Refresh', pullUpLoad: 'Pull Up Load', previousTxt: 'I am the No.', followingTxt: ' line', newDataTxt: 'I am new data: ' }, scrollComponent: { defaultLoadTxtMore: 'Load more', defaultLoadTxtNoMore: 'There is no more data', defaultRefreshTxt: 'Refresh success' }, indexListPage: { title: 'Current City: Beijing' }, pickerPage: { desc: 'Picker is a typical choose component at mobile end. And it could dynamic change the data of every column to realize linkage picker.', picker: ' picker', pickerDemo: ' picker demo ...', oneColumn: 'One column', twoColumn: 'Two column', threeColumn: 'Three column', linkage: 'Linkage', confirmTxt: 'confirm | ok', cancelTxt: 'cancel | close' }, slidePage: { desc: 'Slide is a typical component at mobile end, support horizontal move.' }, fullPageSlideComponent: { buttonTxt: 'Start Use' }, freeScrollPage: { desc: 'Free scroll supports horizontal and vertical move at the same time.' }, formListPage: { desc: 'To use form in better-scroll, you need to make sure the option click is configured as false, since some native element events will be prevented when click is true. And in this situation, we recommend to handle click by listening tap event.', previousTxt: 'No.', followingTxt: ' option' } }
neurotoxinvx/better-scroll
example/language/english.js
JavaScript
mit
2,844
/* @flow */ import assert from 'assert'; import { CONVERSION_TABLE } from './06-export'; import type { Unit, UnitValue } from './06-export'; // We didn't cover any edge cases yet, so let's do this now export function convertUnit(from: Unit, to: Unit, value: number): ?number { if (from === to) { return value; } // If there is no conversion possible, return null // Note how we are using '== null' instead of '=== null' // because the first notation will cover both cases, 'null' // and 'undefined', which spares us a lot of extra code. // You will need to set eslint's 'eqeqeq' rule to '[2, "smart"]' if (CONVERSION_TABLE[from] == null || CONVERSION_TABLE[from][to] == null) { return null; } const transform = CONVERSION_TABLE[from][to]; return transform(value); } // Intersection Type for assuming unit to be 'm' // unit cannot be anything but a `Unit`, so we even // prevent errors on definition type MeterUnitValue = { unit: 'm' } & UnitValue; // Convert whole UnitValues instead of single values function convertToKm(unitValue: MeterUnitValue): ?UnitValue { const { unit, value } = unitValue; const converted = convertUnit(unit, 'km', value); if (converted == null) { return null; } return { unit: 'km', value: converted, } } const value = convertToKm({ unit: 'm', value: 1500 }); assert.deepEqual(value, { unit: 'km', value: 1.5 });
runtastic/flow-guide
tutorial/00-basics/08-maybe-and-optionals.js
JavaScript
mit
1,406
$(document).ready(function () { // add classes to check boxes $('#id_notify_at_threshold').addClass('form-control'); $('#id_in_live_deal').addClass('form-control'); $('#id_is_subscription').addClass('form-control'); });
vforgione/dodger
app/static/app/js/sku__create.js
JavaScript
mit
230
import React, { Component } from 'react'; export default React.createClass({ getInitialState: function () { return { title: '', body: '' }; }, handleChangeTitle: function (e) { this.setState({ title: e.target.value }); }, handleChangeBody: function (e) { this.setState({ body: e.target.value }); }, handleSubmit: function (e) { e.preventDefault(); this.props.addPost(this.state); }, render() { return ( <div> <h3>New post</h3> <form onSubmit={this.handleSubmit}> <input type="text" placeholder="sdfsd" value={this.title} placeholder="title" onChange={this.handleChangeTitle} /> <br /> <textarea type="text" placeholder="sdfsd" placeholder="body" onChange={this.handleChangeBody} > {this.body} </textarea> <button>Submit</button> </form> </div> ); }, });
JayMc/react-crud-example
client/components/FormPost.js
JavaScript
mit
988
export default { '/': { component: require('./components/NowPlayingView'), name: 'NowPlaying' } }
SimulatedGREG/Frequency
app/src/routes.js
JavaScript
mit
110
/** Copyright (c) 2007 Bill Orcutt (http://lilyapp.org, http://publicbeta.cx) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Construct a new color object * @class * @constructor * @extends LilyObjectBase */ function $color(arg) { var thisPtr=this; var websafe=arg||false; this.outlet1 = new this.outletClass("outlet1",this,"random color in hexadecimal"); this.inlet1=new this.inletClass("inlet1",this,"\"bang\" outputs random color"); // getRandomColor() // Returns a random hex color. Passing true for safe returns a web safe color //code hijacked from http://www.scottandrew.com/js/js_util.js function getRandomColor(safe) { var vals,r,n; if (safe) { v = "0369CF"; n = 3; } else { v = "0123456789ABCDEF"; n = 6; } var c = "#"; for (var i=0;i<n;i++) { var ch = v.charAt(Math.round(Math.random() * (v.length-1))); c += (safe)?ch+ch:ch; } return c; } function RGBtoHex(R,G,B) { return toHex(R)+toHex(G)+toHex(B); } function toHex(N) { if (N==null) return "00"; N=parseInt(N); if (N==0 || isNaN(N)) return "00"; N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N); return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16); } function HSLtoRGB (h,s,l) { if (s == 0) return [l,l,l] // achromatic h=h*360/255;s/=255;l/=255; if (l <= 0.5) rm2 = l + l * s; else rm2 = l + s - l * s; rm1 = 2.0 * l - rm2; return [toRGB1(rm1, rm2, h + 120.0),toRGB1(rm1, rm2, h),toRGB1(rm1, rm2, h - 120.0)]; } function toRGB1(rm1,rm2,rh) { if (rh > 360.0) rh -= 360.0; else if (rh < 0.0) rh += 360.0; if (rh < 60.0) rm1 = rm1 + (rm2 - rm1) * rh / 60.0; else if (rh < 180.0) rm1 = rm2; else if (rh < 240.0) rm1 = rm1 + (rm2 - rm1) * (240.0 - rh) / 60.0; return Math.round(rm1 * 255); } //output random color this.inlet1["random"]=function() { thisPtr.outlet1.doOutlet(getRandomColor(websafe)); } //convert RGB to hex this.inlet1["RGBtoHEX"]=function(rgb) { var tmp = rgb.split(" "); thisPtr.outlet1.doOutlet("#"+RGBtoHex(tmp[0],tmp[1],tmp[2])); } //convert HSL to hex this.inlet1["HSLtoHEX"]=function(hsl) { var tmp = hsl.split(" "); var rgb = HSLtoRGB(tmp[0],tmp[1],tmp[2]); thisPtr.outlet1.doOutlet("#"+RGBtoHex(rgb[0],rgb[1],rgb[2])); } return this; } var $colorMetaData = { textName:"color", htmlName:"color", objectCategory:"Math", objectSummary:"Various color related utilities", objectArguments:"websafe colors only [false]" }
billorcutt/lily
lily/lily/chrome/content/externals/color.js
JavaScript
mit
3,506
Ext.provide('Phlexible.users.UserWindow'); Ext.require('Ext.ux.TabPanel'); Phlexible.users.UserWindow = Ext.extend(Ext.Window, { title: Phlexible.users.Strings.user, strings: Phlexible.users.Strings, plain: true, iconCls: 'p-user-user-icon', width: 530, minWidth: 530, height: 400, minHeight: 400, layout: 'fit', border: false, modal: true, initComponent: function () { this.addEvents( 'save' ); var panels = Phlexible.PluginRegistry.get('userEditPanels'); this.items = [{ xtype: 'uxtabpanel', tabPosition: 'left', tabStripWidth: 150, activeTab: 0, border: true, deferredRender: false, items: panels }]; this.tbar = new Ext.Toolbar({ hidden: true, cls: 'p-users-disabled', items: [ '->', { iconCls: 'p-user-user_account-icon', text: this.strings.account_is_disabled, handler: function () { this.getComponent(0).setActiveTab(4); }, scope: this }] }); this.buttons = [ { text: this.strings.cancel, handler: this.close, scope: this }, { text: this.strings.save, iconCls: 'p-user-save-icon', handler: this.save, scope: this } ]; Phlexible.users.UserWindow.superclass.initComponent.call(this); }, show: function (user) { this.user = user; if (user.get('username')) { this.setTitle(this.strings.user + ' "' + user.get('username') + '"'); } else { this.setTitle(this.strings.new_user); } Phlexible.users.UserWindow.superclass.show.call(this); this.getComponent(0).items.each(function(p) { if (typeof p.loadUser === 'function') { p.loadUser(user); } }); if (!user.get('enabled')) { this.getTopToolbar().show(); } }, save: function () { var data = {}; var valid = true; this.getComponent(0).items.each(function(p) { if (typeof p.isValid === 'function' && typeof p.getData === 'function') { if (p.isValid()) { Ext.apply(data, p.getData()); } else { valid = false; } } }); if (!valid) { return; } var url, method; if (this.user.get('uid')) { url = Phlexible.Router.generate('users_users_update', {userId: this.user.get('uid')}); method = 'PUT'; } else { url = Phlexible.Router.generate('users_users_create'); method = 'POST'; } Ext.Ajax.request({ url: url, method: method, params: data, success: this.onSaveSuccess, scope: this }); }, onSaveSuccess: function (response) { var data = Ext.decode(response.responseText); if (data.success) { this.uid = data.uid; Phlexible.success(data.msg); this.fireEvent('save', this.uid); this.close(); } else { Ext.Msg.alert('Failure', data.msg); } } });
phlexible/phlexible
src/Phlexible/Bundle/UserBundle/Resources/scripts/window/UserWindow.js
JavaScript
mit
3,587
/** * @license * Copyright (c) 2014 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // @version 0.7.21 "undefined" == typeof WeakMap && !function () { var e = Object.defineProperty, t = Date.now() % 1e9, n = function () { this.name = "__st" + (1e9 * Math.random() >>> 0) + (t++ + "__") }; n.prototype = { set: function (t, n) { var r = t[this.name]; return r && r[0] === t ? r[1] = n : e(t, this.name, {value: [t, n], writable: !0}), this }, get: function (e) { var t; return (t = e[this.name]) && t[0] === e ? t[1] : void 0 }, "delete": function (e) { var t = e[this.name]; return t && t[0] === e ? (t[0] = t[1] = void 0, !0) : !1 }, has: function (e) { var t = e[this.name]; return t ? t[0] === e : !1 } }, window.WeakMap = n }(), window.ShadowDOMPolyfill = {}, function (e) { "use strict"; function t() { if ("undefined" != typeof chrome && chrome.app && chrome.app.runtime)return !1; if (navigator.getDeviceStorage)return !1; try { var e = new Function("return true;"); return e() } catch (t) { return !1 } } function n(e) { if (!e)throw new Error("Assertion failed") } function r(e, t) { for (var n = k(t), r = 0; r < n.length; r++) { var o = n[r]; A(e, o, F(t, o)) } return e } function o(e, t) { for (var n = k(t), r = 0; r < n.length; r++) { var o = n[r]; switch (o) { case"arguments": case"caller": case"length": case"name": case"prototype": case"toString": continue } A(e, o, F(t, o)) } return e } function i(e, t) { for (var n = 0; n < t.length; n++)if (t[n] in e)return t[n] } function a(e, t, n) { B.value = n, A(e, t, B) } function s(e, t) { var n = e.__proto__ || Object.getPrototypeOf(e); if (U)try { k(n) } catch (r) { n = n.__proto__ } var o = R.get(n); if (o)return o; var i = s(n), a = E(i); return v(n, a, t), a } function c(e, t) { m(e, t, !0) } function u(e, t) { m(t, e, !1) } function l(e) { return /^on[a-z]+$/.test(e) } function p(e) { return /^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(e) } function d(e) { return I && p(e) ? new Function("return this.__impl4cf1e782hg__." + e) : function () { return this.__impl4cf1e782hg__[e] } } function f(e) { return I && p(e) ? new Function("v", "this.__impl4cf1e782hg__." + e + " = v") : function (t) { this.__impl4cf1e782hg__[e] = t } } function h(e) { return I && p(e) ? new Function("return this.__impl4cf1e782hg__." + e + ".apply(this.__impl4cf1e782hg__, arguments)") : function () { return this.__impl4cf1e782hg__[e].apply(this.__impl4cf1e782hg__, arguments) } } function w(e, t) { try { return Object.getOwnPropertyDescriptor(e, t) } catch (n) { return q } } function m(t, n, r, o) { for (var i = k(t), a = 0; a < i.length; a++) { var s = i[a]; if ("polymerBlackList_" !== s && !(s in n || t.polymerBlackList_ && t.polymerBlackList_[s])) { U && t.__lookupGetter__(s); var c, u, p = w(t, s); if ("function" != typeof p.value) { var m = l(s); c = m ? e.getEventHandlerGetter(s) : d(s), (p.writable || p.set || V) && (u = m ? e.getEventHandlerSetter(s) : f(s)); var g = V || p.configurable; A(n, s, {get: c, set: u, configurable: g, enumerable: p.enumerable}) } else r && (n[s] = h(s)) } } } function g(e, t, n) { if (null != e) { var r = e.prototype; v(r, t, n), o(t, e) } } function v(e, t, r) { var o = t.prototype; n(void 0 === R.get(e)), R.set(e, t), P.set(o, e), c(e, o), r && u(o, r), a(o, "constructor", t), t.prototype = o } function b(e, t) { return R.get(t.prototype) === e } function y(e) { var t = Object.getPrototypeOf(e), n = s(t), r = E(n); return v(t, r, e), r } function E(e) { function t(t) { e.call(this, t) } var n = Object.create(e.prototype); return n.constructor = t, t.prototype = n, t } function S(e) { return e && e.__impl4cf1e782hg__ } function M(e) { return !S(e) } function T(e) { if (null === e)return null; n(M(e)); var t = e.__wrapper8e3dd93a60__; return null != t ? t : e.__wrapper8e3dd93a60__ = new (s(e, e))(e) } function O(e) { return null === e ? null : (n(S(e)), e.__impl4cf1e782hg__) } function N(e) { return e.__impl4cf1e782hg__ } function j(e, t) { t.__impl4cf1e782hg__ = e, e.__wrapper8e3dd93a60__ = t } function L(e) { return e && S(e) ? O(e) : e } function _(e) { return e && !S(e) ? T(e) : e } function D(e, t) { null !== t && (n(M(e)), n(void 0 === t || S(t)), e.__wrapper8e3dd93a60__ = t) } function C(e, t, n) { G.get = n, A(e.prototype, t, G) } function H(e, t) { C(e, t, function () { return T(this.__impl4cf1e782hg__[t]) }) } function x(e, t) { e.forEach(function (e) { t.forEach(function (t) { e.prototype[t] = function () { var e = _(this); return e[t].apply(e, arguments) } }) }) } var R = new WeakMap, P = new WeakMap, W = Object.create(null), I = t(), A = Object.defineProperty, k = Object.getOwnPropertyNames, F = Object.getOwnPropertyDescriptor, B = { value: void 0, configurable: !0, enumerable: !1, writable: !0 }; k(window); var U = /Firefox/.test(navigator.userAgent), q = { get: function () { }, set: function (e) { }, configurable: !0, enumerable: !0 }, V = function () { var e = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType"); return e && !e.get && !e.set }(), G = {get: void 0, configurable: !0, enumerable: !0}; e.addForwardingProperties = c, e.assert = n, e.constructorTable = R, e.defineGetter = C, e.defineWrapGetter = H, e.forwardMethodsToWrapper = x, e.isIdentifierName = p, e.isWrapper = S, e.isWrapperFor = b, e.mixin = r, e.nativePrototypeTable = P, e.oneOf = i, e.registerObject = y, e.registerWrapper = g, e.rewrap = D, e.setWrapper = j, e.unsafeUnwrap = N, e.unwrap = O, e.unwrapIfNeeded = L, e.wrap = T, e.wrapIfNeeded = _, e.wrappers = W }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t, n) { return {index: e, removed: t, addedCount: n} } function n() { } var r = 0, o = 1, i = 2, a = 3; n.prototype = { calcEditDistances: function (e, t, n, r, o, i) { for (var a = i - o + 1, s = n - t + 1, c = new Array(a), u = 0; a > u; u++)c[u] = new Array(s), c[u][0] = u; for (var l = 0; s > l; l++)c[0][l] = l; for (var u = 1; a > u; u++)for (var l = 1; s > l; l++)if (this.equals(e[t + l - 1], r[o + u - 1]))c[u][l] = c[u - 1][l - 1]; else { var p = c[u - 1][l] + 1, d = c[u][l - 1] + 1; c[u][l] = d > p ? p : d } return c }, spliceOperationsFromEditDistances: function (e) { for (var t = e.length - 1, n = e[0].length - 1, s = e[t][n], c = []; t > 0 || n > 0;)if (0 != t)if (0 != n) { var u, l = e[t - 1][n - 1], p = e[t - 1][n], d = e[t][n - 1]; u = d > p ? l > p ? p : l : l > d ? d : l, u == l ? (l == s ? c.push(r) : (c.push(o), s = l), t--, n--) : u == p ? (c.push(a), t--, s = p) : (c.push(i), n--, s = d) } else c.push(a), t--; else c.push(i), n--; return c.reverse(), c }, calcSplices: function (e, n, s, c, u, l) { var p = 0, d = 0, f = Math.min(s - n, l - u); if (0 == n && 0 == u && (p = this.sharedPrefix(e, c, f)), s == e.length && l == c.length && (d = this.sharedSuffix(e, c, f - p)), n += p, u += p, s -= d, l -= d, s - n == 0 && l - u == 0)return []; if (n == s) { for (var h = t(n, [], 0); l > u;)h.removed.push(c[u++]); return [h] } if (u == l)return [t(n, [], s - n)]; for (var w = this.spliceOperationsFromEditDistances(this.calcEditDistances(e, n, s, c, u, l)), h = void 0, m = [], g = n, v = u, b = 0; b < w.length; b++)switch (w[b]) { case r: h && (m.push(h), h = void 0), g++, v++; break; case o: h || (h = t(g, [], 0)), h.addedCount++, g++, h.removed.push(c[v]), v++; break; case i: h || (h = t(g, [], 0)), h.addedCount++, g++; break; case a: h || (h = t(g, [], 0)), h.removed.push(c[v]), v++ } return h && m.push(h), m }, sharedPrefix: function (e, t, n) { for (var r = 0; n > r; r++)if (!this.equals(e[r], t[r]))return r; return n }, sharedSuffix: function (e, t, n) { for (var r = e.length, o = t.length, i = 0; n > i && this.equals(e[--r], t[--o]);)i++; return i }, calculateSplices: function (e, t) { return this.calcSplices(e, 0, e.length, t, 0, t.length) }, equals: function (e, t) { return e === t } }, e.ArraySplice = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t() { a = !1; var e = i.slice(0); i = []; for (var t = 0; t < e.length; t++)(0, e[t])() } function n(e) { i.push(e), a || (a = !0, r(t, 0)) } var r, o = window.MutationObserver, i = [], a = !1; if (o) { var s = 1, c = new o(t), u = document.createTextNode(s); c.observe(u, {characterData: !0}), r = function () { s = (s + 1) % 2, u.data = s } } else r = window.setTimeout; e.setEndOfMicrotask = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { e.scheduled_ || (e.scheduled_ = !0, h.push(e), w || (l(n), w = !0)) } function n() { for (w = !1; h.length;) { var e = h; h = [], e.sort(function (e, t) { return e.uid_ - t.uid_ }); for (var t = 0; t < e.length; t++) { var n = e[t]; n.scheduled_ = !1; var r = n.takeRecords(); i(n), r.length && n.callback_(r, n) } } } function r(e, t) { this.type = e, this.target = t, this.addedNodes = new d.NodeList, this.removedNodes = new d.NodeList, this.previousSibling = null, this.nextSibling = null, this.attributeName = null, this.attributeNamespace = null, this.oldValue = null } function o(e, t) { for (; e; e = e.parentNode) { var n = f.get(e); if (n)for (var r = 0; r < n.length; r++) { var o = n[r]; o.options.subtree && o.addTransientObserver(t) } } } function i(e) { for (var t = 0; t < e.nodes_.length; t++) { var n = e.nodes_[t], r = f.get(n); if (!r)return; for (var o = 0; o < r.length; o++) { var i = r[o]; i.observer === e && i.removeTransientObservers() } } } function a(e, n, o) { for (var i = Object.create(null), a = Object.create(null), s = e; s; s = s.parentNode) { var c = f.get(s); if (c)for (var u = 0; u < c.length; u++) { var l = c[u], p = l.options; if ((s === e || p.subtree) && ("attributes" !== n || p.attributes) && ("attributes" !== n || !p.attributeFilter || null === o.namespace && -1 !== p.attributeFilter.indexOf(o.name)) && ("characterData" !== n || p.characterData) && ("childList" !== n || p.childList)) { var d = l.observer; i[d.uid_] = d, ("attributes" === n && p.attributeOldValue || "characterData" === n && p.characterDataOldValue) && (a[d.uid_] = o.oldValue) } } } for (var h in i) { var d = i[h], w = new r(n, e); "name" in o && "namespace" in o && (w.attributeName = o.name, w.attributeNamespace = o.namespace), o.addedNodes && (w.addedNodes = o.addedNodes), o.removedNodes && (w.removedNodes = o.removedNodes), o.previousSibling && (w.previousSibling = o.previousSibling), o.nextSibling && (w.nextSibling = o.nextSibling), void 0 !== a[h] && (w.oldValue = a[h]), t(d), d.records_.push(w) } } function s(e) { if (this.childList = !!e.childList, this.subtree = !!e.subtree, "attributes" in e || !("attributeOldValue" in e || "attributeFilter" in e) ? this.attributes = !!e.attributes : this.attributes = !0, "characterDataOldValue" in e && !("characterData" in e) ? this.characterData = !0 : this.characterData = !!e.characterData, !this.attributes && (e.attributeOldValue || "attributeFilter" in e) || !this.characterData && e.characterDataOldValue)throw new TypeError; if (this.characterData = !!e.characterData, this.attributeOldValue = !!e.attributeOldValue, this.characterDataOldValue = !!e.characterDataOldValue, "attributeFilter" in e) { if (null == e.attributeFilter || "object" != typeof e.attributeFilter)throw new TypeError; this.attributeFilter = m.call(e.attributeFilter) } else this.attributeFilter = null } function c(e) { this.callback_ = e, this.nodes_ = [], this.records_ = [], this.uid_ = ++g, this.scheduled_ = !1 } function u(e, t, n) { this.observer = e, this.target = t, this.options = n, this.transientObservedNodes = [] } var l = e.setEndOfMicrotask, p = e.wrapIfNeeded, d = e.wrappers, f = new WeakMap, h = [], w = !1, m = Array.prototype.slice, g = 0; c.prototype = { constructor: c, observe: function (e, t) { e = p(e); var n, r = new s(t), o = f.get(e); o || f.set(e, o = []); for (var i = 0; i < o.length; i++)o[i].observer === this && (n = o[i], n.removeTransientObservers(), n.options = r); n || (n = new u(this, e, r), o.push(n), this.nodes_.push(e)) }, disconnect: function () { this.nodes_.forEach(function (e) { for (var t = f.get(e), n = 0; n < t.length; n++) { var r = t[n]; if (r.observer === this) { t.splice(n, 1); break } } }, this), this.records_ = [] }, takeRecords: function () { var e = this.records_; return this.records_ = [], e } }, u.prototype = { addTransientObserver: function (e) { if (e !== this.target) { t(this.observer), this.transientObservedNodes.push(e); var n = f.get(e); n || f.set(e, n = []), n.push(this) } }, removeTransientObservers: function () { var e = this.transientObservedNodes; this.transientObservedNodes = []; for (var t = 0; t < e.length; t++)for (var n = e[t], r = f.get(n), o = 0; o < r.length; o++)if (r[o] === this) { r.splice(o, 1); break } } }, e.enqueueMutation = a, e.registerTransientObservers = o, e.wrappers.MutationObserver = c, e.wrappers.MutationRecord = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t) { this.root = e, this.parent = t } function n(e, t) { if (e.treeScope_ !== t) { e.treeScope_ = t; for (var r = e.shadowRoot; r; r = r.olderShadowRoot)r.treeScope_.parent = t; for (var o = e.firstChild; o; o = o.nextSibling)n(o, t) } } function r(n) { if (n instanceof e.wrappers.Window, n.treeScope_)return n.treeScope_; var o, i = n.parentNode; return o = i ? r(i) : new t(n, null), n.treeScope_ = o } t.prototype = { get renderer() { return this.root instanceof e.wrappers.ShadowRoot ? e.getRendererForHost(this.root.host) : null }, contains: function (e) { for (; e; e = e.parent)if (e === this)return !0; return !1 } }, e.TreeScope = t, e.getTreeScope = r, e.setTreeScope = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return e instanceof G.ShadowRoot } function n(e) { return A(e).root } function r(e, r) { var s = [], c = e; for (s.push(c); c;) { var u = a(c); if (u && u.length > 0) { for (var l = 0; l < u.length; l++) { var d = u[l]; if (i(d)) { var f = n(d), h = f.olderShadowRoot; h && s.push(h) } s.push(d) } c = u[u.length - 1] } else if (t(c)) { if (p(e, c) && o(r))break; c = c.host, s.push(c) } else c = c.parentNode, c && s.push(c) } return s } function o(e) { if (!e)return !1; switch (e.type) { case"abort": case"error": case"select": case"change": case"load": case"reset": case"resize": case"scroll": case"selectstart": return !0 } return !1 } function i(e) { return e instanceof HTMLShadowElement } function a(t) { return e.getDestinationInsertionPoints(t) } function s(e, t) { if (0 === e.length)return t; t instanceof G.Window && (t = t.document); for (var n = A(t), r = e[0], o = A(r), i = u(n, o), a = 0; a < e.length; a++) { var s = e[a]; if (A(s) === i)return s } return e[e.length - 1] } function c(e) { for (var t = []; e; e = e.parent)t.push(e); return t } function u(e, t) { for (var n = c(e), r = c(t), o = null; n.length > 0 && r.length > 0;) { var i = n.pop(), a = r.pop(); if (i !== a)break; o = i } return o } function l(e, t, n) { t instanceof G.Window && (t = t.document); var o, i = A(t), a = A(n), s = r(n, e), o = u(i, a); o || (o = a.root); for (var c = o; c; c = c.parent)for (var l = 0; l < s.length; l++) { var p = s[l]; if (A(p) === c)return p } return null } function p(e, t) { return A(e) === A(t) } function d(e) { if (!X.get(e) && (X.set(e, !0), h(V(e), V(e.target)), W)) { var t = W; throw W = null, t } } function f(e) { switch (e.type) { case"load": case"beforeunload": case"unload": return !0 } return !1 } function h(t, n) { if (K.get(t))throw new Error("InvalidStateError"); K.set(t, !0), e.renderAllPending(); var o, i, a; if (f(t) && !t.bubbles) { var s = n; s instanceof G.Document && (a = s.defaultView) && (i = s, o = []) } if (!o)if (n instanceof G.Window)a = n, o = []; else if (o = r(n, t), !f(t)) { var s = o[o.length - 1]; s instanceof G.Document && (a = s.defaultView) } return ne.set(t, o), w(t, o, a, i) && m(t, o, a, i) && g(t, o, a, i), J.set(t, re), $["delete"](t, null), K["delete"](t), t.defaultPrevented } function w(e, t, n, r) { var o = oe; if (n && !v(n, e, o, t, r))return !1; for (var i = t.length - 1; i > 0; i--)if (!v(t[i], e, o, t, r))return !1; return !0 } function m(e, t, n, r) { var o = ie, i = t[0] || n; return v(i, e, o, t, r) } function g(e, t, n, r) { for (var o = ae, i = 1; i < t.length; i++)if (!v(t[i], e, o, t, r))return; n && t.length > 0 && v(n, e, o, t, r) } function v(e, t, n, r, o) { var i = z.get(e); if (!i)return !0; var a = o || s(r, e); if (a === e) { if (n === oe)return !0; n === ae && (n = ie) } else if (n === ae && !t.bubbles)return !0; if ("relatedTarget" in t) { var c = q(t), u = c.relatedTarget; if (u) { if (u instanceof Object && u.addEventListener) { var p = V(u), d = l(t, e, p); if (d === a)return !0 } else d = null; Z.set(t, d) } } J.set(t, n); var f = t.type, h = !1; Y.set(t, a), $.set(t, e), i.depth++; for (var w = 0, m = i.length; m > w; w++) { var g = i[w]; if (g.removed)h = !0; else if (!(g.type !== f || !g.capture && n === oe || g.capture && n === ae))try { if ("function" == typeof g.handler ? g.handler.call(e, t) : g.handler.handleEvent(t), ee.get(t))return !1 } catch (v) { W || (W = v) } } if (i.depth--, h && 0 === i.depth) { var b = i.slice(); i.length = 0; for (var w = 0; w < b.length; w++)b[w].removed || i.push(b[w]) } return !Q.get(t) } function b(e, t, n) { this.type = e, this.handler = t, this.capture = Boolean(n) } function y(e, t) { if (!(e instanceof se))return V(T(se, "Event", e, t)); var n = e; return be || "beforeunload" !== n.type || this instanceof O ? void B(n, this) : new O(n) } function E(e) { return e && e.relatedTarget ? Object.create(e, {relatedTarget: {value: q(e.relatedTarget)}}) : e } function S(e, t, n) { var r = window[e], o = function (t, n) { return t instanceof r ? void B(t, this) : V(T(r, e, t, n)) }; if (o.prototype = Object.create(t.prototype), n && k(o.prototype, n), r)try { F(r, o, new r("temp")) } catch (i) { F(r, o, document.createEvent(e)) } return o } function M(e, t) { return function () { arguments[t] = q(arguments[t]); var n = q(this); n[e].apply(n, arguments) } } function T(e, t, n, r) { if (ge)return new e(n, E(r)); var o = q(document.createEvent(t)), i = me[t], a = [n]; return Object.keys(i).forEach(function (e) { var t = null != r && e in r ? r[e] : i[e]; "relatedTarget" === e && (t = q(t)), a.push(t) }), o["init" + t].apply(o, a), o } function O(e) { y.call(this, e) } function N(e) { return "function" == typeof e ? !0 : e && e.handleEvent } function j(e) { switch (e) { case"DOMAttrModified": case"DOMAttributeNameChanged": case"DOMCharacterDataModified": case"DOMElementNameChanged": case"DOMNodeInserted": case"DOMNodeInsertedIntoDocument": case"DOMNodeRemoved": case"DOMNodeRemovedFromDocument": case"DOMSubtreeModified": return !0 } return !1 } function L(e) { B(e, this) } function _(e) { return e instanceof G.ShadowRoot && (e = e.host), q(e) } function D(e, t) { var n = z.get(e); if (n)for (var r = 0; r < n.length; r++)if (!n[r].removed && n[r].type === t)return !0; return !1 } function C(e, t) { for (var n = q(e); n; n = n.parentNode)if (D(V(n), t))return !0; return !1 } function H(e) { I(e, Ee) } function x(t, n, o, i) { e.renderAllPending(); var a = V(Se.call(U(n), o, i)); if (!a)return null; var c = r(a, null), u = c.lastIndexOf(t); return -1 == u ? null : (c = c.slice(0, u), s(c, t)) } function R(e) { return function () { var t = te.get(this); return t && t[e] && t[e].value || null } } function P(e) { var t = e.slice(2); return function (n) { var r = te.get(this); r || (r = Object.create(null), te.set(this, r)); var o = r[e]; if (o && this.removeEventListener(t, o.wrapped, !1), "function" == typeof n) { var i = function (t) { var r = n.call(this, t); r === !1 ? t.preventDefault() : "onbeforeunload" === e && "string" == typeof r && (t.returnValue = r) }; this.addEventListener(t, i, !1), r[e] = {value: n, wrapped: i} } } } var W, I = e.forwardMethodsToWrapper, A = e.getTreeScope, k = e.mixin, F = e.registerWrapper, B = e.setWrapper, U = e.unsafeUnwrap, q = e.unwrap, V = e.wrap, G = e.wrappers, z = (new WeakMap, new WeakMap), X = new WeakMap, K = new WeakMap, Y = new WeakMap, $ = new WeakMap, Z = new WeakMap, J = new WeakMap, Q = new WeakMap, ee = new WeakMap, te = new WeakMap, ne = new WeakMap, re = 0, oe = 1, ie = 2, ae = 3; b.prototype = { equals: function (e) { return this.handler === e.handler && this.type === e.type && this.capture === e.capture }, get removed() { return null === this.handler }, remove: function () { this.handler = null } }; var se = window.Event; se.prototype.polymerBlackList_ = {returnValue: !0, keyLocation: !0}, y.prototype = { get target() { return Y.get(this) }, get currentTarget() { return $.get(this) }, get eventPhase() { return J.get(this) }, get path() { var e = ne.get(this); return e ? e.slice() : [] }, stopPropagation: function () { Q.set(this, !0) }, stopImmediatePropagation: function () { Q.set(this, !0), ee.set(this, !0) } }; var ce = function () { var e = document.createEvent("Event"); return e.initEvent("test", !0, !0), e.preventDefault(), e.defaultPrevented }(); ce || (y.prototype.preventDefault = function () { this.cancelable && (U(this).preventDefault(), Object.defineProperty(this, "defaultPrevented", { get: function () { return !0 }, configurable: !0 })) }), F(se, y, document.createEvent("Event")); var ue = S("UIEvent", y), le = S("CustomEvent", y), pe = { get relatedTarget() { var e = Z.get(this); return void 0 !== e ? e : V(q(this).relatedTarget) } }, de = k({initMouseEvent: M("initMouseEvent", 14)}, pe), fe = k({initFocusEvent: M("initFocusEvent", 5)}, pe), he = S("MouseEvent", ue, de), we = S("FocusEvent", ue, fe), me = Object.create(null), ge = function () { try { new window.FocusEvent("focus") } catch (e) { return !1 } return !0 }(); if (!ge) { var ve = function (e, t, n) { if (n) { var r = me[n]; t = k(k({}, r), t) } me[e] = t }; ve("Event", { bubbles: !1, cancelable: !1 }), ve("CustomEvent", {detail: null}, "Event"), ve("UIEvent", { view: null, detail: 0 }, "Event"), ve("MouseEvent", { screenX: 0, screenY: 0, clientX: 0, clientY: 0, ctrlKey: !1, altKey: !1, shiftKey: !1, metaKey: !1, button: 0, relatedTarget: null }, "UIEvent"), ve("FocusEvent", {relatedTarget: null}, "UIEvent") } var be = window.BeforeUnloadEvent; O.prototype = Object.create(y.prototype), k(O.prototype, { get returnValue() { return U(this).returnValue }, set returnValue(e) { U(this).returnValue = e } }), be && F(be, O); var ye = window.EventTarget, Ee = ["addEventListener", "removeEventListener", "dispatchEvent"]; [Node, Window].forEach(function (e) { var t = e.prototype; Ee.forEach(function (e) { Object.defineProperty(t, e + "_", {value: t[e]}) }) }), L.prototype = { addEventListener: function (e, t, n) { if (N(t) && !j(e)) { var r = new b(e, t, n), o = z.get(this); if (o) { for (var i = 0; i < o.length; i++)if (r.equals(o[i]))return } else o = [], o.depth = 0, z.set(this, o); o.push(r); var a = _(this); a.addEventListener_(e, d, !0) } }, removeEventListener: function (e, t, n) { n = Boolean(n); var r = z.get(this); if (r) { for (var o = 0, i = !1, a = 0; a < r.length; a++)r[a].type === e && r[a].capture === n && (o++, r[a].handler === t && (i = !0, r[a].remove())); if (i && 1 === o) { var s = _(this); s.removeEventListener_(e, d, !0) } } }, dispatchEvent: function (t) { var n = q(t), r = n.type; X.set(n, !1), e.renderAllPending(); var o; C(this, r) || (o = function () { }, this.addEventListener(r, o, !0)); try { return q(this).dispatchEvent_(n) } finally { o && this.removeEventListener(r, o, !0) } } }, ye && F(ye, L); var Se = document.elementFromPoint; e.elementFromPoint = x, e.getEventHandlerGetter = R, e.getEventHandlerSetter = P, e.wrapEventTargetMethods = H, e.wrappers.BeforeUnloadEvent = O, e.wrappers.CustomEvent = le, e.wrappers.Event = y, e.wrappers.EventTarget = L, e.wrappers.FocusEvent = we, e.wrappers.MouseEvent = he, e.wrappers.UIEvent = ue }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t) { Object.defineProperty(e, t, w) } function n(e) { u(e, this) } function r() { this.length = 0, t(this, "length") } function o(e) { for (var t = new r, o = 0; o < e.length; o++)t[o] = new n(e[o]); return t.length = o, t } function i(e) { a.call(this, e) } var a = e.wrappers.UIEvent, s = e.mixin, c = e.registerWrapper, u = e.setWrapper, l = e.unsafeUnwrap, p = e.wrap, d = window.TouchEvent; if (d) { var f; try { f = document.createEvent("TouchEvent") } catch (h) { return } var w = {enumerable: !1}; n.prototype = { get target() { return p(l(this).target) } }; var m = {configurable: !0, enumerable: !0, get: null}; ["clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce"].forEach(function (e) { m.get = function () { return l(this)[e] }, Object.defineProperty(n.prototype, e, m) }), r.prototype = { item: function (e) { return this[e] } }, i.prototype = Object.create(a.prototype), s(i.prototype, { get touches() { return o(l(this).touches) }, get targetTouches() { return o(l(this).targetTouches) }, get changedTouches() { return o(l(this).changedTouches) }, initTouchEvent: function () { throw new Error("Not implemented") } }), c(d, i, f), e.wrappers.Touch = n, e.wrappers.TouchEvent = i, e.wrappers.TouchList = r } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e, t) { Object.defineProperty(e, t, s) } function n() { this.length = 0, t(this, "length") } function r(e) { if (null == e)return e; for (var t = new n, r = 0, o = e.length; o > r; r++)t[r] = a(e[r]); return t.length = o, t } function o(e, t) { e.prototype[t] = function () { return r(i(this)[t].apply(i(this), arguments)) } } var i = e.unsafeUnwrap, a = e.wrap, s = {enumerable: !1}; n.prototype = { item: function (e) { return this[e] } }, t(n.prototype, "item"), e.wrappers.NodeList = n, e.addWrapNodeListMethod = o, e.wrapNodeList = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; e.wrapHTMLCollection = e.wrapNodeList, e.wrappers.HTMLCollection = e.wrappers.NodeList }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { N(e instanceof S) } function n(e) { var t = new T; return t[0] = e, t.length = 1, t } function r(e, t, n) { L(t, "childList", {removedNodes: n, previousSibling: e.previousSibling, nextSibling: e.nextSibling}) } function o(e, t) { L(e, "childList", {removedNodes: t}) } function i(e, t, r, o) { if (e instanceof DocumentFragment) { var i = s(e); B = !0; for (var a = i.length - 1; a >= 0; a--)e.removeChild(i[a]), i[a].parentNode_ = t; B = !1; for (var a = 0; a < i.length; a++)i[a].previousSibling_ = i[a - 1] || r, i[a].nextSibling_ = i[a + 1] || o; return r && (r.nextSibling_ = i[0]), o && (o.previousSibling_ = i[i.length - 1]), i } var i = n(e), c = e.parentNode; return c && c.removeChild(e), e.parentNode_ = t, e.previousSibling_ = r, e.nextSibling_ = o, r && (r.nextSibling_ = e), o && (o.previousSibling_ = e), i } function a(e) { if (e instanceof DocumentFragment)return s(e); var t = n(e), o = e.parentNode; return o && r(e, o, t), t } function s(e) { for (var t = new T, n = 0, r = e.firstChild; r; r = r.nextSibling)t[n++] = r; return t.length = n, o(e, t), t } function c(e) { return e } function u(e, t) { R(e, t), e.nodeIsInserted_() } function l(e, t) { for (var n = _(t), r = 0; r < e.length; r++)u(e[r], n) } function p(e) { R(e, new O(e, null)) } function d(e) { for (var t = 0; t < e.length; t++)p(e[t]) } function f(e, t) { var n = e.nodeType === S.DOCUMENT_NODE ? e : e.ownerDocument; n !== t.ownerDocument && n.adoptNode(t) } function h(t, n) { if (n.length) { var r = t.ownerDocument; if (r !== n[0].ownerDocument)for (var o = 0; o < n.length; o++)e.adoptNodeNoRemove(n[o], r) } } function w(e, t) { h(e, t); var n = t.length; if (1 === n)return W(t[0]); for (var r = W(e.ownerDocument.createDocumentFragment()), o = 0; n > o; o++)r.appendChild(W(t[o])); return r } function m(e) { if (void 0 !== e.firstChild_)for (var t = e.firstChild_; t;) { var n = t; t = t.nextSibling_, n.parentNode_ = n.previousSibling_ = n.nextSibling_ = void 0 } e.firstChild_ = e.lastChild_ = void 0 } function g(e) { if (e.invalidateShadowRenderer()) { for (var t = e.firstChild; t;) { N(t.parentNode === e); var n = t.nextSibling, r = W(t), o = r.parentNode; o && Y.call(o, r), t.previousSibling_ = t.nextSibling_ = t.parentNode_ = null, t = n } e.firstChild_ = e.lastChild_ = null } else for (var n, i = W(e), a = i.firstChild; a;)n = a.nextSibling, Y.call(i, a), a = n } function v(e) { var t = e.parentNode; return t && t.invalidateShadowRenderer() } function b(e) { for (var t, n = 0; n < e.length; n++)t = e[n], t.parentNode.removeChild(t) } function y(e, t, n) { var r; if (r = A(n ? U.call(n, P(e), !1) : q.call(P(e), !1)), t) { for (var o = e.firstChild; o; o = o.nextSibling)r.appendChild(y(o, !0, n)); if (e instanceof F.HTMLTemplateElement)for (var i = r.content, o = e.content.firstChild; o; o = o.nextSibling)i.appendChild(y(o, !0, n)) } return r } function E(e, t) { if (!t || _(e) !== _(t))return !1; for (var n = t; n; n = n.parentNode)if (n === e)return !0; return !1 } function S(e) { N(e instanceof V), M.call(this, e), this.parentNode_ = void 0, this.firstChild_ = void 0, this.lastChild_ = void 0, this.nextSibling_ = void 0, this.previousSibling_ = void 0, this.treeScope_ = void 0 } var M = e.wrappers.EventTarget, T = e.wrappers.NodeList, O = e.TreeScope, N = e.assert, j = e.defineWrapGetter, L = e.enqueueMutation, _ = e.getTreeScope, D = e.isWrapper, C = e.mixin, H = e.registerTransientObservers, x = e.registerWrapper, R = e.setTreeScope, P = e.unsafeUnwrap, W = e.unwrap, I = e.unwrapIfNeeded, A = e.wrap, k = e.wrapIfNeeded, F = e.wrappers, B = !1, U = document.importNode, q = window.Node.prototype.cloneNode, V = window.Node, G = window.DocumentFragment, z = (V.prototype.appendChild, V.prototype.compareDocumentPosition), X = V.prototype.isEqualNode, K = V.prototype.insertBefore, Y = V.prototype.removeChild, $ = V.prototype.replaceChild, Z = /Trident|Edge/.test(navigator.userAgent), J = Z ? function (e, t) { try { Y.call(e, t) } catch (n) { if (!(e instanceof G))throw n } } : function (e, t) { Y.call(e, t) }; S.prototype = Object.create(M.prototype), C(S.prototype, { appendChild: function (e) { return this.insertBefore(e, null) }, insertBefore: function (e, n) { t(e); var r; n ? D(n) ? r = W(n) : (r = n, n = A(r)) : (n = null, r = null), n && N(n.parentNode === this); var o, s = n ? n.previousSibling : this.lastChild, c = !this.invalidateShadowRenderer() && !v(e); if (o = c ? a(e) : i(e, this, s, n), c)f(this, e), m(this), K.call(P(this), W(e), r); else { s || (this.firstChild_ = o[0]), n || (this.lastChild_ = o[o.length - 1], void 0 === this.firstChild_ && (this.firstChild_ = this.firstChild)); var u = r ? r.parentNode : P(this); u ? K.call(u, w(this, o), r) : h(this, o) } return L(this, "childList", {addedNodes: o, nextSibling: n, previousSibling: s}), l(o, this), e }, removeChild: function (e) { if (t(e), e.parentNode !== this) { for (var r = !1, o = (this.childNodes, this.firstChild); o; o = o.nextSibling)if (o === e) { r = !0; break } if (!r)throw new Error("NotFoundError") } var i = W(e), a = e.nextSibling, s = e.previousSibling; if (this.invalidateShadowRenderer()) { var c = this.firstChild, u = this.lastChild, l = i.parentNode; l && J(l, i), c === e && (this.firstChild_ = a), u === e && (this.lastChild_ = s), s && (s.nextSibling_ = a), a && (a.previousSibling_ = s), e.previousSibling_ = e.nextSibling_ = e.parentNode_ = void 0 } else m(this), J(P(this), i); return B || L(this, "childList", {removedNodes: n(e), nextSibling: a, previousSibling: s}), H(this, e), e }, replaceChild: function (e, r) { t(e); var o; if (D(r) ? o = W(r) : (o = r, r = A(o)), r.parentNode !== this)throw new Error("NotFoundError"); var s, c = r.nextSibling, u = r.previousSibling, d = !this.invalidateShadowRenderer() && !v(e); return d ? s = a(e) : (c === e && (c = e.nextSibling), s = i(e, this, u, c)), d ? (f(this, e), m(this), $.call(P(this), W(e), o)) : (this.firstChild === r && (this.firstChild_ = s[0]), this.lastChild === r && (this.lastChild_ = s[s.length - 1]), r.previousSibling_ = r.nextSibling_ = r.parentNode_ = void 0, o.parentNode && $.call(o.parentNode, w(this, s), o)), L(this, "childList", { addedNodes: s, removedNodes: n(r), nextSibling: c, previousSibling: u }), p(r), l(s, this), r }, nodeIsInserted_: function () { for (var e = this.firstChild; e; e = e.nextSibling)e.nodeIsInserted_() }, hasChildNodes: function () { return null !== this.firstChild }, get parentNode() { return void 0 !== this.parentNode_ ? this.parentNode_ : A(P(this).parentNode) }, get firstChild() { return void 0 !== this.firstChild_ ? this.firstChild_ : A(P(this).firstChild) }, get lastChild() { return void 0 !== this.lastChild_ ? this.lastChild_ : A(P(this).lastChild) }, get nextSibling() { return void 0 !== this.nextSibling_ ? this.nextSibling_ : A(P(this).nextSibling) }, get previousSibling() { return void 0 !== this.previousSibling_ ? this.previousSibling_ : A(P(this).previousSibling) }, get parentElement() { for (var e = this.parentNode; e && e.nodeType !== S.ELEMENT_NODE;)e = e.parentNode; return e }, get textContent() { for (var e = "", t = this.firstChild; t; t = t.nextSibling)t.nodeType != S.COMMENT_NODE && (e += t.textContent); return e }, set textContent(e) { null == e && (e = ""); var t = c(this.childNodes); if (this.invalidateShadowRenderer()) { if (g(this), "" !== e) { var n = P(this).ownerDocument.createTextNode(e); this.appendChild(n) } } else m(this), P(this).textContent = e; var r = c(this.childNodes); L(this, "childList", {addedNodes: r, removedNodes: t}), d(t), l(r, this) }, get childNodes() { for (var e = new T, t = 0, n = this.firstChild; n; n = n.nextSibling)e[t++] = n; return e.length = t, e }, cloneNode: function (e) { return y(this, e) }, contains: function (e) { return E(this, k(e)) }, compareDocumentPosition: function (e) { return z.call(P(this), I(e)) }, isEqualNode: function (e) { return X.call(P(this), I(e)) }, normalize: function () { for (var e, t, n = c(this.childNodes), r = [], o = "", i = 0; i < n.length; i++)t = n[i], t.nodeType === S.TEXT_NODE ? e || t.data.length ? e ? (o += t.data, r.push(t)) : e = t : this.removeChild(t) : (e && r.length && (e.data += o, b(r)), r = [], o = "", e = null, t.childNodes.length && t.normalize()); e && r.length && (e.data += o, b(r)) } }), j(S, "ownerDocument"), x(V, S, document.createDocumentFragment()), delete S.prototype.querySelector, delete S.prototype.querySelectorAll, S.prototype = C(Object.create(M.prototype), S.prototype), e.cloneNode = y, e.nodeWasAdded = u, e.nodeWasRemoved = p, e.nodesWereAdded = l, e.nodesWereRemoved = d, e.originalInsertBefore = K, e.originalRemoveChild = Y, e.snapshotNodeList = c, e.wrappers.Node = S }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(t, n, r, o) { for (var i = null, a = null, s = 0, c = t.length; c > s; s++)i = b(t[s]), !o && (a = g(i).root) && a instanceof e.wrappers.ShadowRoot || (r[n++] = i); return n } function n(e) { return String(e).replace(/\/deep\/|::shadow|>>>/g, " ") } function r(e) { return String(e).replace(/:host\(([^\s]+)\)/g, "$1").replace(/([^\s]):host/g, "$1").replace(":host", "*").replace(/\^|\/shadow\/|\/shadow-deep\/|::shadow|\/deep\/|::content|>>>/g, " ") } function o(e, t) { for (var n, r = e.firstElementChild; r;) { if (r.matches(t))return r; if (n = o(r, t))return n; r = r.nextElementSibling } return null } function i(e, t) { return e.matches(t) } function a(e, t, n) { var r = e.localName; return r === t || r === n && e.namespaceURI === D } function s() { return !0 } function c(e, t, n) { return e.localName === n } function u(e, t) { return e.namespaceURI === t } function l(e, t, n) { return e.namespaceURI === t && e.localName === n } function p(e, t, n, r, o, i) { for (var a = e.firstElementChild; a;)r(a, o, i) && (n[t++] = a), t = p(a, t, n, r, o, i), a = a.nextElementSibling; return t } function d(n, r, o, i, a) { var s, c = v(this), u = g(this).root; if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, null); if (c instanceof L)s = M.call(c, i); else { if (!(c instanceof _))return p(this, r, o, n, i, null); s = S.call(c, i) } return t(s, r, o, a) } function f(n, r, o, i, a) { var s, c = v(this), u = g(this).root; if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, a); if (c instanceof L)s = O.call(c, i, a); else { if (!(c instanceof _))return p(this, r, o, n, i, a); s = T.call(c, i, a) } return t(s, r, o, !1) } function h(n, r, o, i, a) { var s, c = v(this), u = g(this).root; if (u instanceof e.wrappers.ShadowRoot)return p(this, r, o, n, i, a); if (c instanceof L)s = j.call(c, i, a); else { if (!(c instanceof _))return p(this, r, o, n, i, a); s = N.call(c, i, a) } return t(s, r, o, !1) } var w = e.wrappers.HTMLCollection, m = e.wrappers.NodeList, g = e.getTreeScope, v = e.unsafeUnwrap, b = e.wrap, y = document.querySelector, E = document.documentElement.querySelector, S = document.querySelectorAll, M = document.documentElement.querySelectorAll, T = document.getElementsByTagName, O = document.documentElement.getElementsByTagName, N = document.getElementsByTagNameNS, j = document.documentElement.getElementsByTagNameNS, L = window.Element, _ = window.HTMLDocument || window.Document, D = "http://www.w3.org/1999/xhtml", C = { querySelector: function (t) { var r = n(t), i = r !== t; t = r; var a, s = v(this), c = g(this).root; if (c instanceof e.wrappers.ShadowRoot)return o(this, t); if (s instanceof L)a = b(E.call(s, t)); else { if (!(s instanceof _))return o(this, t); a = b(y.call(s, t)) } return a && !i && (c = g(a).root) && c instanceof e.wrappers.ShadowRoot ? o(this, t) : a }, querySelectorAll: function (e) { var t = n(e), r = t !== e; e = t; var o = new m; return o.length = d.call(this, i, 0, o, e, r), o } }, H = { matches: function (t) { return t = r(t), e.originalMatches.call(v(this), t) } }, x = { getElementsByTagName: function (e) { var t = new w, n = "*" === e ? s : a; return t.length = f.call(this, n, 0, t, e, e.toLowerCase()), t }, getElementsByClassName: function (e) { return this.querySelectorAll("." + e) }, getElementsByTagNameNS: function (e, t) { var n = new w, r = null; return r = "*" === e ? "*" === t ? s : c : "*" === t ? u : l, n.length = h.call(this, r, 0, n, e || null, t), n } }; e.GetElementsByInterface = x, e.SelectorsInterface = C, e.MatchesInterface = H }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { for (; e && e.nodeType !== Node.ELEMENT_NODE;)e = e.nextSibling; return e } function n(e) { for (; e && e.nodeType !== Node.ELEMENT_NODE;)e = e.previousSibling; return e } var r = e.wrappers.NodeList, o = { get firstElementChild() { return t(this.firstChild) }, get lastElementChild() { return n(this.lastChild) }, get childElementCount() { for (var e = 0, t = this.firstElementChild; t; t = t.nextElementSibling)e++; return e }, get children() { for (var e = new r, t = 0, n = this.firstElementChild; n; n = n.nextElementSibling)e[t++] = n; return e.length = t, e }, remove: function () { var e = this.parentNode; e && e.removeChild(this) } }, i = { get nextElementSibling() { return t(this.nextSibling) }, get previousElementSibling() { return n(this.previousSibling) } }, a = { getElementById: function (e) { return /[ \t\n\r\f]/.test(e) ? null : this.querySelector('[id="' + e + '"]') } }; e.ChildNodeInterface = i, e.NonElementParentNodeInterface = a, e.ParentNodeInterface = o }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r.call(this, e) } var n = e.ChildNodeInterface, r = e.wrappers.Node, o = e.enqueueMutation, i = e.mixin, a = e.registerWrapper, s = e.unsafeUnwrap, c = window.CharacterData; t.prototype = Object.create(r.prototype), i(t.prototype, { get nodeValue() { return this.data }, set nodeValue(e) { this.data = e }, get textContent() { return this.data }, set textContent(e) { this.data = e }, get data() { return s(this).data }, set data(e) { var t = s(this).data; o(this, "characterData", {oldValue: t}), s(this).data = e } }), i(t.prototype, n), a(c, t, document.createTextNode("")), e.wrappers.CharacterData = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return e >>> 0 } function n(e) { r.call(this, e) } var r = e.wrappers.CharacterData, o = (e.enqueueMutation, e.mixin), i = e.registerWrapper, a = window.Text; n.prototype = Object.create(r.prototype), o(n.prototype, { splitText: function (e) { e = t(e); var n = this.data; if (e > n.length)throw new Error("IndexSizeError"); var r = n.slice(0, e), o = n.slice(e); this.data = r; var i = this.ownerDocument.createTextNode(o); return this.parentNode && this.parentNode.insertBefore(i, this.nextSibling), i } }), i(a, n, document.createTextNode("")), e.wrappers.Text = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return i(e).getAttribute("class") } function n(e, t) { a(e, "attributes", {name: "class", namespace: null, oldValue: t}) } function r(t) { e.invalidateRendererBasedOnAttribute(t, "class") } function o(e, o, i) { var a = e.ownerElement_; if (null == a)return o.apply(e, i); var s = t(a), c = o.apply(e, i); return t(a) !== s && (n(a, s), r(a)), c } if (!window.DOMTokenList)return void console.warn("Missing DOMTokenList prototype, please include a compatible classList polyfill such as http://goo.gl/uTcepH."); var i = e.unsafeUnwrap, a = e.enqueueMutation, s = DOMTokenList.prototype.add; DOMTokenList.prototype.add = function () { o(this, s, arguments) }; var c = DOMTokenList.prototype.remove; DOMTokenList.prototype.remove = function () { o(this, c, arguments) }; var u = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function () { return o(this, u, arguments) } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(t, n) { var r = t.parentNode; if (r && r.shadowRoot) { var o = e.getRendererForHost(r); o.dependsOnAttribute(n) && o.invalidate() } } function n(e, t, n) { l(e, "attributes", {name: t, namespace: null, oldValue: n}) } function r(e) { a.call(this, e) } var o = e.ChildNodeInterface, i = e.GetElementsByInterface, a = e.wrappers.Node, s = e.ParentNodeInterface, c = e.SelectorsInterface, u = e.MatchesInterface, l = (e.addWrapNodeListMethod, e.enqueueMutation), p = e.mixin, d = (e.oneOf, e.registerWrapper), f = e.unsafeUnwrap, h = e.wrappers, w = window.Element, m = ["matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector"].filter(function (e) { return w.prototype[e] }), g = m[0], v = w.prototype[g], b = new WeakMap; r.prototype = Object.create(a.prototype), p(r.prototype, { createShadowRoot: function () { var t = new h.ShadowRoot(this); f(this).polymerShadowRoot_ = t; var n = e.getRendererForHost(this); return n.invalidate(), t }, get shadowRoot() { return f(this).polymerShadowRoot_ || null }, setAttribute: function (e, r) { var o = f(this).getAttribute(e); f(this).setAttribute(e, r), n(this, e, o), t(this, e) }, removeAttribute: function (e) { var r = f(this).getAttribute(e); f(this).removeAttribute(e), n(this, e, r), t(this, e) }, get classList() { var e = b.get(this); if (!e) { if (e = f(this).classList, !e)return; e.ownerElement_ = this, b.set(this, e) } return e }, get className() { return f(this).className }, set className(e) { this.setAttribute("class", e) }, get id() { return f(this).id }, set id(e) { this.setAttribute("id", e) } }), m.forEach(function (e) { "matches" !== e && (r.prototype[e] = function (e) { return this.matches(e) }) }), w.prototype.webkitCreateShadowRoot && (r.prototype.webkitCreateShadowRoot = r.prototype.createShadowRoot), p(r.prototype, o), p(r.prototype, i), p(r.prototype, s), p(r.prototype, c), p(r.prototype, u), d(w, r, document.createElementNS(null, "x")), e.invalidateRendererBasedOnAttribute = t, e.matchesNames = m, e.originalMatches = v, e.wrappers.Element = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { switch (e) { case"&": return "&amp;"; case"<": return "&lt;"; case">": return "&gt;"; case'"': return "&quot;"; case" ": return "&nbsp;" } } function n(e) { return e.replace(j, t) } function r(e) { return e.replace(L, t) } function o(e) { for (var t = {}, n = 0; n < e.length; n++)t[e[n]] = !0; return t } function i(e) { if (e.namespaceURI !== C)return !0; var t = e.ownerDocument.doctype; return t && t.publicId && t.systemId } function a(e, t) { switch (e.nodeType) { case Node.ELEMENT_NODE: for (var o, a = e.tagName.toLowerCase(), c = "<" + a, u = e.attributes, l = 0; o = u[l]; l++)c += " " + o.name + '="' + n(o.value) + '"'; return _[a] ? (i(e) && (c += "/"), c + ">") : c + ">" + s(e) + "</" + a + ">"; case Node.TEXT_NODE: var p = e.data; return t && D[t.localName] ? p : r(p); case Node.COMMENT_NODE: return "<!--" + e.data + "-->"; default: throw console.error(e), new Error("not implemented") } } function s(e) { e instanceof N.HTMLTemplateElement && (e = e.content); for (var t = "", n = e.firstChild; n; n = n.nextSibling)t += a(n, e); return t } function c(e, t, n) { var r = n || "div"; e.textContent = ""; var o = T(e.ownerDocument.createElement(r)); o.innerHTML = t; for (var i; i = o.firstChild;)e.appendChild(O(i)) } function u(e) { w.call(this, e) } function l(e, t) { var n = T(e.cloneNode(!1)); n.innerHTML = t; for (var r, o = T(document.createDocumentFragment()); r = n.firstChild;)o.appendChild(r); return O(o) } function p(t) { return function () { return e.renderAllPending(), M(this)[t] } } function d(e) { m(u, e, p(e)) } function f(t) { Object.defineProperty(u.prototype, t, { get: p(t), set: function (n) { e.renderAllPending(), M(this)[t] = n }, configurable: !0, enumerable: !0 }) } function h(t) { Object.defineProperty(u.prototype, t, { value: function () { return e.renderAllPending(), M(this)[t].apply(M(this), arguments) }, configurable: !0, enumerable: !0 }) } var w = e.wrappers.Element, m = e.defineGetter, g = e.enqueueMutation, v = e.mixin, b = e.nodesWereAdded, y = e.nodesWereRemoved, E = e.registerWrapper, S = e.snapshotNodeList, M = e.unsafeUnwrap, T = e.unwrap, O = e.wrap, N = e.wrappers, j = /[&\u00A0"]/g, L = /[&\u00A0<>]/g, _ = o(["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]), D = o(["style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript"]), C = "http://www.w3.org/1999/xhtml", H = /MSIE/.test(navigator.userAgent), x = window.HTMLElement, R = window.HTMLTemplateElement; u.prototype = Object.create(w.prototype), v(u.prototype, { get innerHTML() { return s(this) }, set innerHTML(e) { if (H && D[this.localName])return void(this.textContent = e); var t = S(this.childNodes); this.invalidateShadowRenderer() ? this instanceof N.HTMLTemplateElement ? c(this.content, e) : c(this, e, this.tagName) : !R && this instanceof N.HTMLTemplateElement ? c(this.content, e) : M(this).innerHTML = e; var n = S(this.childNodes); g(this, "childList", {addedNodes: n, removedNodes: t}), y(t), b(n, this) }, get outerHTML() { return a(this, this.parentNode) }, set outerHTML(e) { var t = this.parentNode; if (t) { t.invalidateShadowRenderer(); var n = l(t, e); t.replaceChild(n, this) } }, insertAdjacentHTML: function (e, t) { var n, r; switch (String(e).toLowerCase()) { case"beforebegin": n = this.parentNode, r = this; break; case"afterend": n = this.parentNode, r = this.nextSibling; break; case"afterbegin": n = this, r = this.firstChild; break; case"beforeend": n = this, r = null; break; default: return } var o = l(n, t); n.insertBefore(o, r) }, get hidden() { return this.hasAttribute("hidden") }, set hidden(e) { e ? this.setAttribute("hidden", "") : this.removeAttribute("hidden") } }), ["clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth"].forEach(d), ["scrollLeft", "scrollTop"].forEach(f), ["focus", "getBoundingClientRect", "getClientRects", "scrollIntoView"].forEach(h), E(x, u, document.createElement("b")), e.wrappers.HTMLElement = u, e.getInnerHTML = s, e.setInnerHTML = c }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unsafeUnwrap, a = e.wrap, s = window.HTMLCanvasElement; t.prototype = Object.create(n.prototype), r(t.prototype, { getContext: function () { var e = i(this).getContext.apply(i(this), arguments); return e && a(e) } }), o(s, t, document.createElement("canvas")), e.wrappers.HTMLCanvasElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = window.HTMLContentElement; t.prototype = Object.create(n.prototype), r(t.prototype, { constructor: t, get select() { return this.getAttribute("select") }, set select(e) { this.setAttribute("select", e) }, setAttribute: function (e, t) { n.prototype.setAttribute.call(this, e, t), "select" === String(e).toLowerCase() && this.invalidateShadowRenderer(!0) } }), i && o(i, t), e.wrappers.HTMLContentElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = window.HTMLFormElement; t.prototype = Object.create(n.prototype), r(t.prototype, { get elements() { return i(a(this).elements) } }), o(s, t, document.createElement("form")), e.wrappers.HTMLFormElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r.call(this, e) } function n(e, t) { if (!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function."); var o = i(document.createElement("img")); r.call(this, o), a(o, this), void 0 !== e && (o.width = e), void 0 !== t && (o.height = t) } var r = e.wrappers.HTMLElement, o = e.registerWrapper, i = e.unwrap, a = e.rewrap, s = window.HTMLImageElement; t.prototype = Object.create(r.prototype), o(s, t, document.createElement("img")), n.prototype = t.prototype, e.wrappers.HTMLImageElement = t, e.wrappers.Image = n }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = (e.mixin, e.wrappers.NodeList, e.registerWrapper), o = window.HTMLShadowElement; t.prototype = Object.create(n.prototype), t.prototype.constructor = t, o && r(o, t), e.wrappers.HTMLShadowElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { if (!e.defaultView)return e; var t = p.get(e); if (!t) { for (t = e.implementation.createHTMLDocument(""); t.lastChild;)t.removeChild(t.lastChild); p.set(e, t) } return t } function n(e) { for (var n, r = t(e.ownerDocument), o = c(r.createDocumentFragment()); n = e.firstChild;)o.appendChild(n); return o } function r(e) { if (o.call(this, e), !d) { var t = n(e); l.set(this, u(t)) } } var o = e.wrappers.HTMLElement, i = e.mixin, a = e.registerWrapper, s = e.unsafeUnwrap, c = e.unwrap, u = e.wrap, l = new WeakMap, p = new WeakMap, d = window.HTMLTemplateElement; r.prototype = Object.create(o.prototype), i(r.prototype, { constructor: r, get content() { return d ? u(s(this).content) : l.get(this) } }), d && a(d, r), e.wrappers.HTMLTemplateElement = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.registerWrapper, o = window.HTMLMediaElement; o && (t.prototype = Object.create(n.prototype), r(o, t, document.createElement("audio")), e.wrappers.HTMLMediaElement = t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r.call(this, e) } function n(e) { if (!(this instanceof n))throw new TypeError("DOM object constructor cannot be called as a function."); var t = i(document.createElement("audio")); r.call(this, t), a(t, this), t.setAttribute("preload", "auto"), void 0 !== e && t.setAttribute("src", e) } var r = e.wrappers.HTMLMediaElement, o = e.registerWrapper, i = e.unwrap, a = e.rewrap, s = window.HTMLAudioElement; s && (t.prototype = Object.create(r.prototype), o(s, t, document.createElement("audio")), n.prototype = t.prototype, e.wrappers.HTMLAudioElement = t, e.wrappers.Audio = n) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { return e.replace(/\s+/g, " ").trim() } function n(e) { o.call(this, e) } function r(e, t, n, i) { if (!(this instanceof r))throw new TypeError("DOM object constructor cannot be called as a function."); var a = c(document.createElement("option")); o.call(this, a), s(a, this), void 0 !== e && (a.text = e), void 0 !== t && a.setAttribute("value", t), n === !0 && a.setAttribute("selected", ""), a.selected = i === !0 } var o = e.wrappers.HTMLElement, i = e.mixin, a = e.registerWrapper, s = e.rewrap, c = e.unwrap, u = e.wrap, l = window.HTMLOptionElement; n.prototype = Object.create(o.prototype), i(n.prototype, { get text() { return t(this.textContent) }, set text(e) { this.textContent = t(String(e)) }, get form() { return u(c(this).form) } }), a(l, n, document.createElement("option")), r.prototype = n.prototype, e.wrappers.HTMLOptionElement = n, e.wrappers.Option = r }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unwrap, a = e.wrap, s = window.HTMLSelectElement; t.prototype = Object.create(n.prototype), r(t.prototype, { add: function (e, t) { "object" == typeof t && (t = i(t)), i(this).add(i(e), t) }, remove: function (e) { return void 0 === e ? void n.prototype.remove.call(this) : ("object" == typeof e && (e = i(e)), void i(this).remove(e)) }, get form() { return a(i(this).form) } }), o(s, t, document.createElement("select")), e.wrappers.HTMLSelectElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.unwrap, a = e.wrap, s = e.wrapHTMLCollection, c = window.HTMLTableElement; t.prototype = Object.create(n.prototype), r(t.prototype, { get caption() { return a(i(this).caption) }, createCaption: function () { return a(i(this).createCaption()) }, get tHead() { return a(i(this).tHead) }, createTHead: function () { return a(i(this).createTHead()) }, createTFoot: function () { return a(i(this).createTFoot()) }, get tFoot() { return a(i(this).tFoot) }, get tBodies() { return s(i(this).tBodies) }, createTBody: function () { return a(i(this).createTBody()) }, get rows() { return s(i(this).rows) }, insertRow: function (e) { return a(i(this).insertRow(e)) } }), o(c, t, document.createElement("table")), e.wrappers.HTMLTableElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = e.wrap, c = window.HTMLTableSectionElement; t.prototype = Object.create(n.prototype), r(t.prototype, { constructor: t, get rows() { return i(a(this).rows) }, insertRow: function (e) { return s(a(this).insertRow(e)) } }), o(c, t, document.createElement("thead")), e.wrappers.HTMLTableSectionElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.HTMLElement, r = e.mixin, o = e.registerWrapper, i = e.wrapHTMLCollection, a = e.unwrap, s = e.wrap, c = window.HTMLTableRowElement; t.prototype = Object.create(n.prototype), r(t.prototype, { get cells() { return i(a(this).cells) }, insertCell: function (e) { return s(a(this).insertCell(e)) } }), o(c, t, document.createElement("tr")), e.wrappers.HTMLTableRowElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { switch (e.localName) { case"content": return new n(e); case"shadow": return new o(e); case"template": return new i(e) } r.call(this, e) } var n = e.wrappers.HTMLContentElement, r = e.wrappers.HTMLElement, o = e.wrappers.HTMLShadowElement, i = e.wrappers.HTMLTemplateElement, a = (e.mixin, e.registerWrapper), s = window.HTMLUnknownElement; t.prototype = Object.create(r.prototype), a(s, t), e.wrappers.HTMLUnknownElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.Element, r = e.wrappers.HTMLElement, o = e.registerWrapper, i = (e.defineWrapGetter, e.unsafeUnwrap), a = e.wrap, s = e.mixin, c = "http://www.w3.org/2000/svg", u = window.SVGElement, l = document.createElementNS(c, "title"); if (!("classList" in l)) { var p = Object.getOwnPropertyDescriptor(n.prototype, "classList"); Object.defineProperty(r.prototype, "classList", p), delete n.prototype.classList } t.prototype = Object.create(n.prototype), s(t.prototype, { get ownerSVGElement() { return a(i(this).ownerSVGElement) } }), o(u, t, document.createElementNS(c, "title")), e.wrappers.SVGElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { d.call(this, e) } var n = e.mixin, r = e.registerWrapper, o = e.unwrap, i = e.wrap, a = window.SVGUseElement, s = "http://www.w3.org/2000/svg", c = i(document.createElementNS(s, "g")), u = document.createElementNS(s, "use"), l = c.constructor, p = Object.getPrototypeOf(l.prototype), d = p.constructor; t.prototype = Object.create(p), "instanceRoot" in u && n(t.prototype, { get instanceRoot() { return i(o(this).instanceRoot) }, get animatedInstanceRoot() { return i(o(this).animatedInstanceRoot) } }), r(a, t, u), e.wrappers.SVGUseElement = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.EventTarget, r = e.mixin, o = e.registerWrapper, i = e.unsafeUnwrap, a = e.wrap, s = window.SVGElementInstance; s && (t.prototype = Object.create(n.prototype), r(t.prototype, { get correspondingElement() { return a(i(this).correspondingElement) }, get correspondingUseElement() { return a(i(this).correspondingUseElement) }, get parentNode() { return a(i(this).parentNode) }, get childNodes() { throw new Error("Not implemented") }, get firstChild() { return a(i(this).firstChild) }, get lastChild() { return a(i(this).lastChild) }, get previousSibling() { return a(i(this).previousSibling) }, get nextSibling() { return a(i(this).nextSibling) } }), o(s, t), e.wrappers.SVGElementInstance = t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { o(e, this) } var n = e.mixin, r = e.registerWrapper, o = e.setWrapper, i = e.unsafeUnwrap, a = e.unwrap, s = e.unwrapIfNeeded, c = e.wrap, u = window.CanvasRenderingContext2D; n(t.prototype, { get canvas() { return c(i(this).canvas) }, drawImage: function () { arguments[0] = s(arguments[0]), i(this).drawImage.apply(i(this), arguments) }, createPattern: function () { return arguments[0] = a(arguments[0]), i(this).createPattern.apply(i(this), arguments) } }), r(u, t, document.createElement("canvas").getContext("2d")), e.wrappers.CanvasRenderingContext2D = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { i(e, this) } var n = e.addForwardingProperties, r = e.mixin, o = e.registerWrapper, i = e.setWrapper, a = e.unsafeUnwrap, s = e.unwrapIfNeeded, c = e.wrap, u = window.WebGLRenderingContext; if (u) { r(t.prototype, { get canvas() { return c(a(this).canvas) }, texImage2D: function () { arguments[5] = s(arguments[5]), a(this).texImage2D.apply(a(this), arguments) }, texSubImage2D: function () { arguments[6] = s(arguments[6]), a(this).texSubImage2D.apply(a(this), arguments) } }); var l = Object.getPrototypeOf(u.prototype); l !== Object.prototype && n(l, t.prototype); var p = /WebKit/.test(navigator.userAgent) ? {drawingBufferHeight: null, drawingBufferWidth: null} : {}; o(u, t, p), e.wrappers.WebGLRenderingContext = t } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.Node, r = e.GetElementsByInterface, o = e.NonElementParentNodeInterface, i = e.ParentNodeInterface, a = e.SelectorsInterface, s = e.mixin, c = e.registerObject, u = e.registerWrapper, l = window.DocumentFragment; t.prototype = Object.create(n.prototype), s(t.prototype, i), s(t.prototype, a), s(t.prototype, r), s(t.prototype, o), u(l, t, document.createDocumentFragment()), e.wrappers.DocumentFragment = t; var p = c(document.createComment("")); e.wrappers.Comment = p }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t = p(l(e).ownerDocument.createDocumentFragment()); n.call(this, t), c(t, this); var o = e.shadowRoot; h.set(this, o), this.treeScope_ = new r(this, a(o || e)), f.set(this, e) } var n = e.wrappers.DocumentFragment, r = e.TreeScope, o = e.elementFromPoint, i = e.getInnerHTML, a = e.getTreeScope, s = e.mixin, c = e.rewrap, u = e.setInnerHTML, l = e.unsafeUnwrap, p = e.unwrap, d = e.wrap, f = new WeakMap, h = new WeakMap; t.prototype = Object.create(n.prototype), s(t.prototype, { constructor: t, get innerHTML() { return i(this) }, set innerHTML(e) { u(this, e), this.invalidateShadowRenderer() }, get olderShadowRoot() { return h.get(this) || null }, get host() { return f.get(this) || null }, invalidateShadowRenderer: function () { return f.get(this).invalidateShadowRenderer() }, elementFromPoint: function (e, t) { return o(this, this.ownerDocument, e, t) }, getSelection: function () { return document.getSelection() }, get activeElement() { var e = p(this).ownerDocument.activeElement; if (!e || !e.nodeType)return null; for (var t = d(e); !this.contains(t);) { for (; t.parentNode;)t = t.parentNode; if (!t.host)return null; t = t.host } return t } }), e.wrappers.ShadowRoot = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t = p(e).root; return t instanceof f ? t.host : null } function n(t, n) { if (t.shadowRoot) { n = Math.min(t.childNodes.length - 1, n); var r = t.childNodes[n]; if (r) { var o = e.getDestinationInsertionPoints(r); if (o.length > 0) { var i = o[0].parentNode; i.nodeType == Node.ELEMENT_NODE && (t = i) } } } return t } function r(e) { return e = l(e), t(e) || e } function o(e) { a(e, this) } var i = e.registerWrapper, a = e.setWrapper, s = e.unsafeUnwrap, c = e.unwrap, u = e.unwrapIfNeeded, l = e.wrap, p = e.getTreeScope, d = window.Range, f = e.wrappers.ShadowRoot; o.prototype = { get startContainer() { return r(s(this).startContainer) }, get endContainer() { return r(s(this).endContainer) }, get commonAncestorContainer() { return r(s(this).commonAncestorContainer) }, setStart: function (e, t) { e = n(e, t), s(this).setStart(u(e), t) }, setEnd: function (e, t) { e = n(e, t), s(this).setEnd(u(e), t) }, setStartBefore: function (e) { s(this).setStartBefore(u(e)) }, setStartAfter: function (e) { s(this).setStartAfter(u(e)) }, setEndBefore: function (e) { s(this).setEndBefore(u(e)) }, setEndAfter: function (e) { s(this).setEndAfter(u(e)) }, selectNode: function (e) { s(this).selectNode(u(e)) }, selectNodeContents: function (e) { s(this).selectNodeContents(u(e)) }, compareBoundaryPoints: function (e, t) { return s(this).compareBoundaryPoints(e, c(t)) }, extractContents: function () { return l(s(this).extractContents()) }, cloneContents: function () { return l(s(this).cloneContents()) }, insertNode: function (e) { s(this).insertNode(u(e)) }, surroundContents: function (e) { s(this).surroundContents(u(e)) }, cloneRange: function () { return l(s(this).cloneRange()) }, isPointInRange: function (e, t) { return s(this).isPointInRange(u(e), t) }, comparePoint: function (e, t) { return s(this).comparePoint(u(e), t) }, intersectsNode: function (e) { return s(this).intersectsNode(u(e)) }, toString: function () { return s(this).toString() } }, d.prototype.createContextualFragment && (o.prototype.createContextualFragment = function (e) { return l(s(this).createContextualFragment(e)) }), i(window.Range, o, document.createRange()), e.wrappers.Range = o }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { e.previousSibling_ = e.previousSibling, e.nextSibling_ = e.nextSibling, e.parentNode_ = e.parentNode } function n(n, o, i) { var a = x(n), s = x(o), c = i ? x(i) : null; if (r(o), t(o), i)n.firstChild === i && (n.firstChild_ = i), i.previousSibling_ = i.previousSibling; else { n.lastChild_ = n.lastChild, n.lastChild === n.firstChild && (n.firstChild_ = n.firstChild); var u = R(a.lastChild); u && (u.nextSibling_ = u.nextSibling) } e.originalInsertBefore.call(a, s, c) } function r(n) { var r = x(n), o = r.parentNode; if (o) { var i = R(o); t(n), n.previousSibling && (n.previousSibling.nextSibling_ = n), n.nextSibling && (n.nextSibling.previousSibling_ = n), i.lastChild === n && (i.lastChild_ = n), i.firstChild === n && (i.firstChild_ = n), e.originalRemoveChild.call(o, r) } } function o(e) { W.set(e, []) } function i(e) { var t = W.get(e); return t || W.set(e, t = []), t } function a(e) { for (var t = [], n = 0, r = e.firstChild; r; r = r.nextSibling)t[n++] = r; return t } function s() { for (var e = 0; e < F.length; e++) { var t = F[e], n = t.parentRenderer; n && n.dirty || t.render() } F = [] } function c() { T = null, s() } function u(e) { var t = A.get(e); return t || (t = new f(e), A.set(e, t)), t } function l(e) { var t = D(e).root; return t instanceof _ ? t : null } function p(e) { return u(e.host) } function d(e) { this.skip = !1, this.node = e, this.childNodes = [] } function f(e) { this.host = e, this.dirty = !1, this.invalidateAttributes(), this.associateNode(e) } function h(e) { for (var t = [], n = e.firstChild; n; n = n.nextSibling)E(n) ? t.push.apply(t, i(n)) : t.push(n); return t } function w(e) { if (e instanceof j)return e; if (e instanceof N)return null; for (var t = e.firstChild; t; t = t.nextSibling) { var n = w(t); if (n)return n } return null } function m(e, t) { i(t).push(e); var n = I.get(e); n ? n.push(t) : I.set(e, [t]) } function g(e) { return I.get(e) } function v(e) { I.set(e, void 0) } function b(e, t) { var n = t.getAttribute("select"); if (!n)return !0; if (n = n.trim(), !n)return !0; if (!(e instanceof O))return !1; if (!U.test(n))return !1; try { return e.matches(n) } catch (r) { return !1 } } function y(e, t) { var n = g(t); return n && n[n.length - 1] === e } function E(e) { return e instanceof N || e instanceof j } function S(e) { return e.shadowRoot } function M(e) { for (var t = [], n = e.shadowRoot; n; n = n.olderShadowRoot)t.push(n); return t } var T, O = e.wrappers.Element, N = e.wrappers.HTMLContentElement, j = e.wrappers.HTMLShadowElement, L = e.wrappers.Node, _ = e.wrappers.ShadowRoot, D = (e.assert, e.getTreeScope), C = (e.mixin, e.oneOf), H = e.unsafeUnwrap, x = e.unwrap, R = e.wrap, P = e.ArraySplice, W = new WeakMap, I = new WeakMap, A = new WeakMap, k = C(window, ["requestAnimationFrame", "mozRequestAnimationFrame", "webkitRequestAnimationFrame", "setTimeout"]), F = [], B = new P; B.equals = function (e, t) { return x(e.node) === t }, d.prototype = { append: function (e) { var t = new d(e); return this.childNodes.push(t), t }, sync: function (e) { if (!this.skip) { for (var t = this.node, o = this.childNodes, i = a(x(t)), s = e || new WeakMap, c = B.calculateSplices(o, i), u = 0, l = 0, p = 0, d = 0; d < c.length; d++) { for (var f = c[d]; p < f.index; p++)l++, o[u++].sync(s); for (var h = f.removed.length, w = 0; h > w; w++) { var m = R(i[l++]); s.get(m) || r(m) } for (var g = f.addedCount, v = i[l] && R(i[l]), w = 0; g > w; w++) { var b = o[u++], y = b.node; n(t, y, v), s.set(y, !0), b.sync(s) } p += g } for (var d = p; d < o.length; d++)o[d].sync(s) } } }, f.prototype = { render: function (e) { if (this.dirty) { this.invalidateAttributes(); var t = this.host; this.distribution(t); var n = e || new d(t); this.buildRenderTree(n, t); var r = !e; r && n.sync(), this.dirty = !1 } }, get parentRenderer() { return D(this.host).renderer }, invalidate: function () { if (!this.dirty) { this.dirty = !0; var e = this.parentRenderer; if (e && e.invalidate(), F.push(this), T)return; T = window[k](c, 0) } }, distribution: function (e) { this.resetAllSubtrees(e), this.distributionResolution(e) }, resetAll: function (e) { E(e) ? o(e) : v(e), this.resetAllSubtrees(e) }, resetAllSubtrees: function (e) { for (var t = e.firstChild; t; t = t.nextSibling)this.resetAll(t); e.shadowRoot && this.resetAll(e.shadowRoot), e.olderShadowRoot && this.resetAll(e.olderShadowRoot) }, distributionResolution: function (e) { if (S(e)) { for (var t = e, n = h(t), r = M(t), o = 0; o < r.length; o++)this.poolDistribution(r[o], n); for (var o = r.length - 1; o >= 0; o--) { var i = r[o], a = w(i); if (a) { var s = i.olderShadowRoot; s && (n = h(s)); for (var c = 0; c < n.length; c++)m(n[c], a) } this.distributionResolution(i) } } for (var u = e.firstChild; u; u = u.nextSibling)this.distributionResolution(u) }, poolDistribution: function (e, t) { if (!(e instanceof j))if (e instanceof N) { var n = e; this.updateDependentAttributes(n.getAttribute("select")); for (var r = !1, o = 0; o < t.length; o++) { var e = t[o]; e && b(e, n) && (m(e, n), t[o] = void 0, r = !0) } if (!r)for (var i = n.firstChild; i; i = i.nextSibling)m(i, n) } else for (var i = e.firstChild; i; i = i.nextSibling)this.poolDistribution(i, t) }, buildRenderTree: function (e, t) { for (var n = this.compose(t), r = 0; r < n.length; r++) { var o = n[r], i = e.append(o); this.buildRenderTree(i, o) } if (S(t)) { var a = u(t); a.dirty = !1 } }, compose: function (e) { for (var t = [], n = e.shadowRoot || e, r = n.firstChild; r; r = r.nextSibling)if (E(r)) { this.associateNode(n); for (var o = i(r), a = 0; a < o.length; a++) { var s = o[a]; y(r, s) && t.push(s) } } else t.push(r); return t }, invalidateAttributes: function () { this.attributes = Object.create(null) }, updateDependentAttributes: function (e) { if (e) { var t = this.attributes; /\.\w+/.test(e) && (t["class"] = !0), /#\w+/.test(e) && (t.id = !0), e.replace(/\[\s*([^\s=\|~\]]+)/g, function (e, n) { t[n] = !0 }) } }, dependsOnAttribute: function (e) { return this.attributes[e] }, associateNode: function (e) { H(e).polymerShadowRenderer_ = this } }; var U = /^(:not\()?[*.#[a-zA-Z_|]/; L.prototype.invalidateShadowRenderer = function (e) { var t = H(this).polymerShadowRenderer_; return t ? (t.invalidate(), !0) : !1 }, N.prototype.getDistributedNodes = j.prototype.getDistributedNodes = function () { return s(), i(this) }, O.prototype.getDestinationInsertionPoints = function () { return s(), g(this) || [] }, N.prototype.nodeIsInserted_ = j.prototype.nodeIsInserted_ = function () { this.invalidateShadowRenderer(); var e, t = l(this); t && (e = p(t)), H(this).polymerShadowRenderer_ = e, e && e.invalidate() }, e.getRendererForHost = u, e.getShadowTrees = M, e.renderAllPending = s, e.getDestinationInsertionPoints = g, e.visual = { insertBefore: n, remove: r } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(t) { if (window[t]) { r(!e.wrappers[t]); var c = function (e) { n.call(this, e) }; c.prototype = Object.create(n.prototype), o(c.prototype, { get form() { return s(a(this).form) } }), i(window[t], c, document.createElement(t.slice(4, -7))), e.wrappers[t] = c } } var n = e.wrappers.HTMLElement, r = e.assert, o = e.mixin, i = e.registerWrapper, a = e.unwrap, s = e.wrap, c = ["HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement"]; c.forEach(t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r(e, this) } var n = e.registerWrapper, r = e.setWrapper, o = e.unsafeUnwrap, i = e.unwrap, a = e.unwrapIfNeeded, s = e.wrap, c = window.Selection; t.prototype = { get anchorNode() { return s(o(this).anchorNode) }, get focusNode() { return s(o(this).focusNode) }, addRange: function (e) { o(this).addRange(a(e)) }, collapse: function (e, t) { o(this).collapse(a(e), t) }, containsNode: function (e, t) { return o(this).containsNode(a(e), t) }, getRangeAt: function (e) { return s(o(this).getRangeAt(e)) }, removeRange: function (e) { o(this).removeRange(i(e)) }, selectAllChildren: function (e) { o(this).selectAllChildren(e instanceof ShadowRoot ? o(e.host) : a(e)) }, toString: function () { return o(this).toString() } }, c.prototype.extend && (t.prototype.extend = function (e, t) { o(this).extend(a(e), t) }), n(window.Selection, t, window.getSelection()), e.wrappers.Selection = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { r(e, this) } var n = e.registerWrapper, r = e.setWrapper, o = e.unsafeUnwrap, i = e.unwrapIfNeeded, a = e.wrap, s = window.TreeWalker; t.prototype = { get root() { return a(o(this).root) }, get currentNode() { return a(o(this).currentNode) }, set currentNode(e) { o(this).currentNode = i(e) }, get filter() { return o(this).filter }, parentNode: function () { return a(o(this).parentNode()) }, firstChild: function () { return a(o(this).firstChild()) }, lastChild: function () { return a(o(this).lastChild()) }, previousSibling: function () { return a(o(this).previousSibling()) }, previousNode: function () { return a(o(this).previousNode()) }, nextNode: function () { return a(o(this).nextNode()) } }, n(s, t), e.wrappers.TreeWalker = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { l.call(this, e), this.treeScope_ = new m(this, null) } function n(e) { var n = document[e]; t.prototype[e] = function () { return D(n.apply(L(this), arguments)) } } function r(e, t) { x.call(L(t), _(e)), o(e, t) } function o(e, t) { e.shadowRoot && t.adoptNode(e.shadowRoot), e instanceof w && i(e, t); for (var n = e.firstChild; n; n = n.nextSibling)o(n, t) } function i(e, t) { var n = e.olderShadowRoot; n && t.adoptNode(n) } function a(e) { j(e, this) } function s(e, t) { var n = document.implementation[t]; e.prototype[t] = function () { return D(n.apply(L(this), arguments)) } } function c(e, t) { var n = document.implementation[t]; e.prototype[t] = function () { return n.apply(L(this), arguments) } } var u = e.GetElementsByInterface, l = e.wrappers.Node, p = e.ParentNodeInterface, d = e.NonElementParentNodeInterface, f = e.wrappers.Selection, h = e.SelectorsInterface, w = e.wrappers.ShadowRoot, m = e.TreeScope, g = e.cloneNode, v = e.defineGetter, b = e.defineWrapGetter, y = e.elementFromPoint, E = e.forwardMethodsToWrapper, S = e.matchesNames, M = e.mixin, T = e.registerWrapper, O = e.renderAllPending, N = e.rewrap, j = e.setWrapper, L = e.unsafeUnwrap, _ = e.unwrap, D = e.wrap, C = e.wrapEventTargetMethods, H = (e.wrapNodeList, new WeakMap); t.prototype = Object.create(l.prototype), b(t, "documentElement"), b(t, "body"), b(t, "head"), v(t, "activeElement", function () { var e = _(this).activeElement; if (!e || !e.nodeType)return null; for (var t = D(e); !this.contains(t);) { for (; t.parentNode;)t = t.parentNode; if (!t.host)return null; t = t.host } return t }), ["createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode"].forEach(n); var x = document.adoptNode, R = document.getSelection; M(t.prototype, { adoptNode: function (e) { return e.parentNode && e.parentNode.removeChild(e), r(e, this), e }, elementFromPoint: function (e, t) { return y(this, this, e, t) }, importNode: function (e, t) { return g(e, t, L(this)) }, getSelection: function () { return O(), new f(R.call(_(this))) }, getElementsByName: function (e) { return h.querySelectorAll.call(this, "[name=" + JSON.stringify(String(e)) + "]") } }); var P = document.createTreeWalker, W = e.wrappers.TreeWalker; if (t.prototype.createTreeWalker = function (e, t, n, r) { var o = null; return n && (n.acceptNode && "function" == typeof n.acceptNode ? o = { acceptNode: function (e) { return n.acceptNode(D(e)) } } : "function" == typeof n && (o = function (e) { return n(D(e)) })), new W(P.call(_(this), _(e), t, o, r)) }, document.registerElement) { var I = document.registerElement; t.prototype.registerElement = function (t, n) { function r(e) { return e ? void j(e, this) : i ? document.createElement(i, t) : document.createElement(t) } var o, i; if (void 0 !== n && (o = n.prototype, i = n["extends"]), o || (o = Object.create(HTMLElement.prototype)), e.nativePrototypeTable.get(o))throw new Error("NotSupportedError"); for (var a, s = Object.getPrototypeOf(o), c = []; s && !(a = e.nativePrototypeTable.get(s));)c.push(s), s = Object.getPrototypeOf(s); if (!a)throw new Error("NotSupportedError"); for (var u = Object.create(a), l = c.length - 1; l >= 0; l--)u = Object.create(u); ["createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback"].forEach(function (e) { var t = o[e]; t && (u[e] = function () { D(this) instanceof r || N(this), t.apply(D(this), arguments) }) }); var p = {prototype: u}; i && (p["extends"] = i), r.prototype = o, r.prototype.constructor = r, e.constructorTable.set(u, r), e.nativePrototypeTable.set(o, u); I.call(_(this), t, p); return r }, E([window.HTMLDocument || window.Document], ["registerElement"]) } E([window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement], ["appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild"]), E([window.HTMLBodyElement, window.HTMLHeadElement, window.HTMLHtmlElement], S), E([window.HTMLDocument || window.Document], ["adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "createTreeWalker", "elementFromPoint", "getElementById", "getElementsByName", "getSelection"]), M(t.prototype, u), M(t.prototype, p), M(t.prototype, h), M(t.prototype, d), M(t.prototype, { get implementation() { var e = H.get(this); return e ? e : (e = new a(_(this).implementation), H.set(this, e), e) }, get defaultView() { return D(_(this).defaultView) } }), T(window.Document, t, document.implementation.createHTMLDocument("")), window.HTMLDocument && T(window.HTMLDocument, t), C([window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement]); var A = document.implementation.createDocument; a.prototype.createDocument = function () { return arguments[2] = _(arguments[2]), D(A.apply(L(this), arguments)) }, s(a, "createDocumentType"), s(a, "createHTMLDocument"), c(a, "hasFeature"), T(window.DOMImplementation, a), E([window.DOMImplementation], ["createDocument", "createDocumentType", "createHTMLDocument", "hasFeature"]), e.adoptNodeNoRemove = r, e.wrappers.DOMImplementation = a, e.wrappers.Document = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { n.call(this, e) } var n = e.wrappers.EventTarget, r = e.wrappers.Selection, o = e.mixin, i = e.registerWrapper, a = e.renderAllPending, s = e.unwrap, c = e.unwrapIfNeeded, u = e.wrap, l = window.Window, p = window.getComputedStyle, d = window.getDefaultComputedStyle, f = window.getSelection; t.prototype = Object.create(n.prototype), l.prototype.getComputedStyle = function (e, t) { return u(this || window).getComputedStyle(c(e), t) }, d && (l.prototype.getDefaultComputedStyle = function (e, t) { return u(this || window).getDefaultComputedStyle(c(e), t) }), l.prototype.getSelection = function () { return u(this || window).getSelection() }, delete window.getComputedStyle, delete window.getDefaultComputedStyle, delete window.getSelection, ["addEventListener", "removeEventListener", "dispatchEvent"].forEach(function (e) { l.prototype[e] = function () { var t = u(this || window); return t[e].apply(t, arguments) }, delete window[e] }), o(t.prototype, { getComputedStyle: function (e, t) { return a(), p.call(s(this), c(e), t) }, getSelection: function () { return a(), new r(f.call(s(this))) }, get document() { return u(s(this).document) } }), d && (t.prototype.getDefaultComputedStyle = function (e, t) { return a(), d.call(s(this), c(e), t) }), i(l, t, window), e.wrappers.Window = t }(window.ShadowDOMPolyfill), function (e) { "use strict"; var t = e.unwrap, n = window.DataTransfer || window.Clipboard, r = n.prototype.setDragImage; r && (n.prototype.setDragImage = function (e, n, o) { r.call(this, t(e), n, o) }) }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t; t = e instanceof i ? e : new i(e && o(e)), r(t, this) } var n = e.registerWrapper, r = e.setWrapper, o = e.unwrap, i = window.FormData; i && (n(i, t, new i), e.wrappers.FormData = t) }(window.ShadowDOMPolyfill), function (e) { "use strict"; var t = e.unwrapIfNeeded, n = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function (e) { return n.call(this, t(e)) } }(window.ShadowDOMPolyfill), function (e) { "use strict"; function t(e) { var t = n[e], r = window[t]; if (r) { var o = document.createElement(e), i = o.constructor; window[t] = i } } var n = (e.isWrapperFor, { a: "HTMLAnchorElement", area: "HTMLAreaElement", audio: "HTMLAudioElement", base: "HTMLBaseElement", body: "HTMLBodyElement", br: "HTMLBRElement", button: "HTMLButtonElement", canvas: "HTMLCanvasElement", caption: "HTMLTableCaptionElement", col: "HTMLTableColElement", content: "HTMLContentElement", data: "HTMLDataElement", datalist: "HTMLDataListElement", del: "HTMLModElement", dir: "HTMLDirectoryElement", div: "HTMLDivElement", dl: "HTMLDListElement", embed: "HTMLEmbedElement", fieldset: "HTMLFieldSetElement", font: "HTMLFontElement", form: "HTMLFormElement", frame: "HTMLFrameElement", frameset: "HTMLFrameSetElement", h1: "HTMLHeadingElement", head: "HTMLHeadElement", hr: "HTMLHRElement", html: "HTMLHtmlElement", iframe: "HTMLIFrameElement", img: "HTMLImageElement", input: "HTMLInputElement", keygen: "HTMLKeygenElement", label: "HTMLLabelElement", legend: "HTMLLegendElement", li: "HTMLLIElement", link: "HTMLLinkElement", map: "HTMLMapElement", marquee: "HTMLMarqueeElement", menu: "HTMLMenuElement", menuitem: "HTMLMenuItemElement", meta: "HTMLMetaElement", meter: "HTMLMeterElement", object: "HTMLObjectElement", ol: "HTMLOListElement", optgroup: "HTMLOptGroupElement", option: "HTMLOptionElement", output: "HTMLOutputElement", p: "HTMLParagraphElement", param: "HTMLParamElement", pre: "HTMLPreElement", progress: "HTMLProgressElement", q: "HTMLQuoteElement", script: "HTMLScriptElement", select: "HTMLSelectElement", shadow: "HTMLShadowElement", source: "HTMLSourceElement", span: "HTMLSpanElement", style: "HTMLStyleElement", table: "HTMLTableElement", tbody: "HTMLTableSectionElement", template: "HTMLTemplateElement", textarea: "HTMLTextAreaElement", thead: "HTMLTableSectionElement", time: "HTMLTimeElement", title: "HTMLTitleElement", tr: "HTMLTableRowElement", track: "HTMLTrackElement", ul: "HTMLUListElement", video: "HTMLVideoElement" }); Object.keys(n).forEach(t), Object.getOwnPropertyNames(e.wrappers).forEach(function (t) { window[t] = e.wrappers[t] }) }(window.ShadowDOMPolyfill);
kittuov/go-django
admin/webapp/static/app/bower_components/webcomponentsjs/ShadowDOM.min.js
JavaScript
mit
104,656
/* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ var ALGOLIA_VERSION = '2.8.5'; /* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Algolia Search library initialization * @param applicationID the application ID you have in your admin interface * @param apiKey a valid API key for the service * @param methodOrOptions the hash of parameters for initialization. It can contains: * - method (optional) specify if the protocol used is http or https (http by default to make the first search query faster). * You need to use https is you are doing something else than just search queries. * - hosts (optional) the list of hosts that you have received for the service * - dsn (optional) set to true if your account has the Distributed Search Option * - dsnHost (optional) override the automatic computation of dsn hostname */ var AlgoliaSearch = function(applicationID, apiKey, methodOrOptions, resolveDNS, hosts) { var self = this; this.applicationID = applicationID; this.apiKey = apiKey; this.dsn = true; this.dsnHost = null; this.hosts = []; this.currentHostIndex = 0; this.requestTimeoutInMs = 2000; this.extraHeaders = []; this.jsonp = null; var method; var tld = 'net'; if (typeof methodOrOptions === 'string') { // Old initialization method = methodOrOptions; } else { // Take all option from the hash var options = methodOrOptions || {}; if (!this._isUndefined(options.method)) { method = options.method; } if (!this._isUndefined(options.tld)) { tld = options.tld; } if (!this._isUndefined(options.dsn)) { this.dsn = options.dsn; } if (!this._isUndefined(options.hosts)) { hosts = options.hosts; } if (!this._isUndefined(options.dsnHost)) { this.dsnHost = options.dsnHost; } if (!this._isUndefined(options.requestTimeoutInMs)) { this.requestTimeoutInMs = +options.requestTimeoutInMs; } if (!this._isUndefined(options.jsonp)) { this.jsonp = options.jsonp; } } // If hosts is undefined, initialize it with applicationID if (this._isUndefined(hosts)) { hosts = [ this.applicationID + '-1.algolia.' + tld, this.applicationID + '-2.algolia.' + tld, this.applicationID + '-3.algolia.' + tld ]; } // detect is we use http or https this.host_protocol = 'http://'; if (this._isUndefined(method) || method === null) { this.host_protocol = ('https:' == document.location.protocol ? 'https' : 'http') + '://'; } else if (method === 'https' || method === 'HTTPS') { this.host_protocol = 'https://'; } // Add hosts in random order for (var i = 0; i < hosts.length; ++i) { if (Math.random() > 0.5) { this.hosts.reverse(); } this.hosts.push(this.host_protocol + hosts[i]); } if (Math.random() > 0.5) { this.hosts.reverse(); } // then add Distributed Search Network host if there is one if (this.dsn || this.dsnHost != null) { if (this.dsnHost) { this.hosts.unshift(this.host_protocol + this.dsnHost); } else { this.hosts.unshift(this.host_protocol + this.applicationID + '-dsn.algolia.' + tld); } } }; function AlgoliaExplainResults(hit, titleAttribute, otherAttributes) { function _getHitExplanationForOneAttr_recurse(obj, foundWords) { var res = []; if (typeof obj === 'object' && 'matchedWords' in obj && 'value' in obj) { var match = false; for (var j = 0; j < obj.matchedWords.length; ++j) { var word = obj.matchedWords[j]; if (!(word in foundWords)) { foundWords[word] = 1; match = true; } } if (match) { res.push(obj.value); } } else if (Object.prototype.toString.call(obj) === '[object Array]') { for (var i = 0; i < obj.length; ++i) { var array = _getHitExplanationForOneAttr_recurse(obj[i], foundWords); res = res.concat(array); } } else if (typeof obj === 'object') { for (var prop in obj) { if (obj.hasOwnProperty(prop)){ res = res.concat(_getHitExplanationForOneAttr_recurse(obj[prop], foundWords)); } } } return res; } function _getHitExplanationForOneAttr(hit, foundWords, attr) { var base = hit._highlightResult || hit; if (attr.indexOf('.') === -1) { if (attr in base) { return _getHitExplanationForOneAttr_recurse(base[attr], foundWords); } return []; } var array = attr.split('.'); var obj = base; for (var i = 0; i < array.length; ++i) { if (Object.prototype.toString.call(obj) === '[object Array]') { var res = []; for (var j = 0; j < obj.length; ++j) { res = res.concat(_getHitExplanationForOneAttr(obj[j], foundWords, array.slice(i).join('.'))); } return res; } if (array[i] in obj) { obj = obj[array[i]]; } else { return []; } } return _getHitExplanationForOneAttr_recurse(obj, foundWords); } var res = {}; var foundWords = {}; var title = _getHitExplanationForOneAttr(hit, foundWords, titleAttribute); res.title = (title.length > 0) ? title[0] : ''; res.subtitles = []; if (typeof otherAttributes !== 'undefined') { for (var i = 0; i < otherAttributes.length; ++i) { var attr = _getHitExplanationForOneAttr(hit, foundWords, otherAttributes[i]); for (var j = 0; j < attr.length; ++j) { res.subtitles.push({ attr: otherAttributes[i], value: attr[j] }); } } } return res; } window.AlgoliaSearch = AlgoliaSearch; AlgoliaSearch.prototype = { /* * Delete an index * * @param indexName the name of index to delete * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ deleteIndex: function(indexName, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexName), callback: callback }); }, /** * Move an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ moveIndex: function(srcIndexName, dstIndexName, callback) { var postObj = {operation: 'move', destination: dstIndexName}; this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, callback: callback }); }, /** * Copy an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ copyIndex: function(srcIndexName, dstIndexName, callback) { var postObj = {operation: 'copy', destination: dstIndexName}; this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, callback: callback }); }, /** * Return last log entries. * @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry). * @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000. * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer that contains the task ID */ getLogs: function(callback, offset, length) { if (this._isUndefined(offset)) { offset = 0; } if (this._isUndefined(length)) { length = 10; } this._jsonRequest({ method: 'GET', url: '/1/logs?offset=' + offset + '&length=' + length, callback: callback }); }, /* * List all existing indexes (paginated) * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with index list or error description if success is false. * @param page The page to retrieve, starting at 0. */ listIndexes: function(callback, page) { var params = page ? '?page=' + page : ''; this._jsonRequest({ method: 'GET', url: '/1/indexes' + params, callback: callback }); }, /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ initIndex: function(indexName) { return new this.Index(this, indexName); }, /* * List all existing user keys with their associated ACLs * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ listUserKeys: function(callback) { this._jsonRequest({ method: 'GET', url: '/1/keys', callback: callback }); }, /* * Get ACL of a user key * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ getUserKeyACL: function(key, callback) { this._jsonRequest({ method: 'GET', url: '/1/keys/' + key, callback: callback }); }, /* * Delete an existing user key * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ deleteUserKey: function(key, callback) { this._jsonRequest({ method: 'DELETE', url: '/1/keys/' + key, callback: callback }); }, /* * Add an existing user key * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKey: function(acls, callback) { var aclsObject = {}; aclsObject.acl = acls; this._jsonRequest({ method: 'POST', url: '/1/keys', body: aclsObject, callback: callback }); }, /* * Add an existing user key * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. * @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) { var indexObj = this; var aclsObject = {}; aclsObject.acl = acls; aclsObject.validity = validity; aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour; aclsObject.maxHitsPerQuery = maxHitsPerQuery; this._jsonRequest({ method: 'POST', url: '/1/indexes/' + indexObj.indexName + '/keys', body: aclsObject, callback: callback }); }, /** * Set the extra security tagFilters header * @param {string|array} tags The list of tags defining the current security filters */ setSecurityTags: function(tags) { if (Object.prototype.toString.call(tags) === '[object Array]') { var strTags = []; for (var i = 0; i < tags.length; ++i) { if (Object.prototype.toString.call(tags[i]) === '[object Array]') { var oredTags = []; for (var j = 0; j < tags[i].length; ++j) { oredTags.push(tags[i][j]); } strTags.push('(' + oredTags.join(',') + ')'); } else { strTags.push(tags[i]); } } tags = strTags.join(','); } this.tagFilters = tags; }, /** * Set the extra user token header * @param {string} userToken The token identifying a uniq user (used to apply rate limits) */ setUserToken: function(userToken) { this.userToken = userToken; }, /* * Initialize a new batch of search queries */ startQueriesBatch: function() { this.batch = []; }, /* * Add a search query in the batch * * @param query the full text query * @param args (optional) if set, contains an object with query parameters: * - attributes: an array of object attribute names to retrieve * (if not set all attributes are retrieve) * - attributesToHighlight: an array of object attribute names to highlight * (if not set indexed attributes are highlighted) * - minWordSizefor1Typo: the minimum number of characters to accept one typo. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters to accept two typos. * Defaults to 7. * - getRankingInfo: if set, the result hits will contain ranking information in * _rankingInfo attribute * - page: (pagination parameter) page to retrieve (zero base). Defaults to 0. * - hitsPerPage: (pagination parameter) number of hits per page. Defaults to 10. */ addQueryInBatch: function(indexName, query, args) { var params = 'query=' + encodeURIComponent(query); if (!this._isUndefined(args) && args !== null) { params = this._getSearchParams(args, params); } this.batch.push({ indexName: indexName, params: params }); }, /* * Clear all queries in cache */ clearCache: function() { this.cache = {}; }, /* * Launch the batch of queries using XMLHttpRequest. * (Optimized for browser using a POST query to minimize number of OPTIONS queries) * * @param callback the function that will receive results * @param delay (optional) if set, wait for this delay (in ms) and only send the batch if there was no other in the meantime. */ sendQueriesBatch: function(callback, delay) { var as = this; var params = {requests: []}; for (var i = 0; i < as.batch.length; ++i) { params.requests.push(as.batch[i]); } window.clearTimeout(as.onDelayTrigger); if (!this._isUndefined(delay) && delay !== null && delay > 0) { var onDelayTrigger = window.setTimeout( function() { as._sendQueriesBatch(params, callback); }, delay); as.onDelayTrigger = onDelayTrigger; } else { this._sendQueriesBatch(params, callback); } }, /** * Set the number of milliseconds a request can take before automatically being terminated. * * @param {Number} milliseconds */ setRequestTimeout: function(milliseconds) { if (milliseconds) { this.requestTimeoutInMs = parseInt(milliseconds, 10); } }, /* * Index class constructor. * You should not use this method directly but use initIndex() function */ Index: function(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; }, /** * Add an extra field to the HTTP request * * @param key the header field name * @param value the header field value */ setExtraHeader: function(key, value) { this.extraHeaders.push({ key: key, value: value}); }, _sendQueriesBatch: function(params, callback) { if (this.jsonp === null) { var self = this; this._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/*/queries', body: params, callback: function(success, content) { if (!success) { // retry first with JSONP self.jsonp = true; self._sendQueriesBatch(params, callback); } else { self.jsonp = false; callback && callback(success, content); } } }); } else if (this.jsonp) { var jsonpParams = ''; for (var i = 0; i < params.requests.length; ++i) { var q = '/1/indexes/' + encodeURIComponent(params.requests[i].indexName) + '?' + params.requests[i].params; jsonpParams += i + '=' + encodeURIComponent(q) + '&'; } var pObj = {params: jsonpParams}; this._jsonRequest({ cache: this.cache, method: 'GET', url: '/1/indexes/*', body: pObj, callback: callback }); } else { this._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/*/queries', body: params, callback: callback}); } }, /* * Wrapper that try all hosts to maximize the quality of service */ _jsonRequest: function(opts) { var self = this; var callback = opts.callback; var cache = null; var cacheID = opts.url; if (!this._isUndefined(opts.body)) { cacheID = opts.url + '_body_' + JSON.stringify(opts.body); } if (!this._isUndefined(opts.cache)) { cache = opts.cache; if (!this._isUndefined(cache[cacheID])) { if (!this._isUndefined(callback)) { setTimeout(function () { callback(true, cache[cacheID]); }, 1); } return; } } opts.successiveRetryCount = 0; var impl = function() { if (opts.successiveRetryCount >= self.hosts.length) { if (!self._isUndefined(callback)) { opts.successiveRetryCount = 0; callback(false, { message: 'Cannot connect the Algolia\'s Search API. Please send an email to [email protected] to report the issue.' }); } return; } opts.callback = function(retry, success, res, body) { if (!success && !self._isUndefined(body)) { window.console && console.log('Error: ' + body.message); } if (success && !self._isUndefined(opts.cache)) { cache[cacheID] = body; } if (!success && retry) { self.currentHostIndex = ++self.currentHostIndex % self.hosts.length; opts.successiveRetryCount += 1; impl(); } else { opts.successiveRetryCount = 0; if (!self._isUndefined(callback)) { callback(success, body); } } }; opts.hostname = self.hosts[self.currentHostIndex]; self._jsonRequestByHost(opts); }; impl(); }, _jsonRequestByHost: function(opts) { var self = this; var url = opts.hostname + opts.url; if (this.jsonp) { this._makeJsonpRequestByHost(url, opts); } else { this._makeXmlHttpRequestByHost(url, opts); } }, /** * Make a JSONP request * * @param url request url (includes endpoint and path) * @param opts all request options */ _makeJsonpRequestByHost: function(url, opts) { ////////////////// ////////////////// ///// ///// DISABLED FOR SECURITY PURPOSE ///// ////////////////// ////////////////// opts.callback(true, false, null, { 'message': 'JSONP not allowed.' }); return; // if (opts.method !== 'GET') { // opts.callback(true, false, null, { 'message': 'Method ' + opts.method + ' ' + url + ' is not supported by JSONP.' }); // return; // } // this.jsonpCounter = this.jsonpCounter || 0; // this.jsonpCounter += 1; // var head = document.getElementsByTagName('head')[0]; // var script = document.createElement('script'); // var cb = 'algoliaJSONP_' + this.jsonpCounter; // var done = false; // var ontimeout = null; // window[cb] = function(data) { // opts.callback(false, true, null, data); // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // }; // script.type = 'text/javascript'; // script.src = url + '?callback=' + cb + '&X-Algolia-Application-Id=' + this.applicationID + '&X-Algolia-API-Key=' + this.apiKey; // if (this.tagFilters) { // script.src += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters); // } // if (this.userToken) { // script.src += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken); // } // for (var i = 0; i < this.extraHeaders.length; ++i) { // script.src += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value; // } // if (opts.body && opts.body.params) { // script.src += '&' + opts.body.params; // } // ontimeout = setTimeout(function() { // script.onload = script.onreadystatechange = script.onerror = null; // window[cb] = function(data) { // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // }; // opts.callback(true, false, null, { 'message': 'Timeout - Failed to load JSONP script.' }); // head.removeChild(script); // clearTimeout(ontimeout); // ontimeout = null; // }, this.requestTimeoutInMs); // script.onload = script.onreadystatechange = function() { // clearTimeout(ontimeout); // ontimeout = null; // if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { // done = true; // if (typeof window[cb + '_loaded'] === 'undefined') { // opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' }); // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // } else { // try { delete window[cb + '_loaded']; } catch (e) { window[cb + '_loaded'] = undefined; } // } // script.onload = script.onreadystatechange = null; // Handle memory leak in IE // head.removeChild(script); // } // }; // script.onerror = function() { // clearTimeout(ontimeout); // ontimeout = null; // opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' }); // head.removeChild(script); // try { delete window[cb]; } catch (e) { window[cb] = undefined; } // }; // head.appendChild(script); }, /** * Make a XmlHttpRequest * * @param url request url (includes endpoint and path) * @param opts all request opts */ _makeXmlHttpRequestByHost: function(url, opts) { var self = this; var xmlHttp = window.XMLHttpRequest ? new XMLHttpRequest() : {}; var body = null; var ontimeout = null; if (!this._isUndefined(opts.body)) { body = JSON.stringify(opts.body); } url += ((url.indexOf('?') == -1) ? '?' : '&') + 'X-Algolia-API-Key=' + this.apiKey; url += '&X-Algolia-Application-Id=' + this.applicationID; if (this.userToken) { url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken); } if (this.tagFilters) { url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters); } for (var i = 0; i < this.extraHeaders.length; ++i) { url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value; } if ('withCredentials' in xmlHttp) { xmlHttp.open(opts.method, url, true); xmlHttp.timeout = this.requestTimeoutInMs * (opts.successiveRetryCount + 1); if (body !== null) { /* This content type is specified to follow CORS 'simple header' directive */ xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } } else if (typeof XDomainRequest !== 'undefined') { // Handle IE8/IE9 // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xmlHttp = new XDomainRequest(); xmlHttp.open(opts.method, url); } else { // very old browser, not supported opts.callback(false, false, null, { 'message': 'CORS not supported' }); return; } ontimeout = setTimeout(function() { xmlHttp.abort(); // Prevent Internet Explorer 9, JScript Error c00c023f if (xmlHttp.aborted === true) { stopLoadAnimation(); return; } opts.callback(true, false, null, { 'message': 'Timeout - Could not connect to endpoint ' + url } ); clearTimeout(ontimeout); ontimeout = null; }, this.requestTimeoutInMs * (opts.successiveRetryCount + 1)); xmlHttp.onload = function(event) { clearTimeout(ontimeout); ontimeout = null; if (!self._isUndefined(event) && event.target !== null) { var retry = (event.target.status === 0 || event.target.status === 503); var success = false; var response = null; if (typeof XDomainRequest !== 'undefined') { // Handle CORS requests IE8/IE9 response = event.target.responseText; success = (response && response.length > 0); } else { response = event.target.response; success = (event.target.status === 200 || event.target.status === 201); } opts.callback(retry, success, event.target, response ? JSON.parse(response) : null); } else { opts.callback(false, true, event, JSON.parse(xmlHttp.responseText)); } }; xmlHttp.ontimeout = function(event) { // stop the network call but rely on ontimeout to call opt.callback }; xmlHttp.onerror = function(event) { clearTimeout(ontimeout); ontimeout = null; opts.callback(true, false, null, { 'message': 'Could not connect to host', 'error': event } ); }; xmlHttp.send(body); }, /* * Transform search param object in query string */ _getSearchParams: function(args, params) { if (this._isUndefined(args) || args === null) { return params; } for (var key in args) { if (key !== null && args.hasOwnProperty(key)) { params += (params.length === 0) ? '?' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? JSON.stringify(args[key]) : args[key]); } } return params; }, _isUndefined: function(obj) { return obj === void 0; }, /// internal attributes applicationID: null, apiKey: null, tagFilters: null, userToken: null, hosts: [], cache: {}, extraHeaders: [] }; /* * Contains all the functions related to one index * You should use AlgoliaSearch.initIndex(indexName) to retrieve this object */ AlgoliaSearch.prototype.Index.prototype = { /* * Clear all queries in cache */ clearCache: function() { this.cache = {}; }, /* * Add an object in this index * * @param content contains the javascript object to add inside the index * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains 3 elements: createAt, taskId and objectID * @param objectID (optional) an objectID you want to attribute to this object * (if the attribute already exist the old object will be overwrite) */ addObject: function(content, callback, objectID) { var indexObj = this; if (this.as._isUndefined(objectID)) { this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName), body: content, callback: callback }); } else { this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), body: content, callback: callback }); } }, /* * Add several objects * * @param objects contains an array of objects to add * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ addObjects: function(objects, callback) { var indexObj = this; var postObj = {requests:[]}; for (var i = 0; i < objects.length; ++i) { var request = { action: 'addObject', body: objects[i] }; postObj.requests.push(request); } this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, callback: callback }); }, /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the object to retrieve or the error message if a failure occured * @param attributes (optional) if set, contains the array of attribute names to retrieve */ getObject: function(objectID, callback, attributes) { var indexObj = this; var params = ''; if (!this.as._isUndefined(attributes)) { params = '?attributes='; for (var i = 0; i < attributes.length; ++i) { if (i !== 0) { params += ','; } params += attributes[i]; } } if (this.as.jsonp === null) { this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params, callback: callback }); } else { var pObj = {params: params}; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), callback: callback, body: pObj}); } }, /* * Update partially an object (only update attributes passed in argument) * * @param partialObject contains the javascript attributes to override, the * object must contains an objectID attribute * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains 3 elements: createAt, taskId and objectID */ partialUpdateObject: function(partialObject, callback) { var indexObj = this; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial', body: partialObject, callback: callback }); }, /* * Partially Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ partialUpdateObjects: function(objects, callback) { var indexObj = this; var postObj = {requests:[]}; for (var i = 0; i < objects.length; ++i) { var request = { action: 'partialUpdateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, callback: callback }); }, /* * Override the content of object * * @param object contains the javascript object to save, the object must contains an objectID attribute * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ saveObject: function(object, callback) { var indexObj = this; this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID), body: object, callback: callback }); }, /* * Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that updateAt and taskID */ saveObjects: function(objects, callback) { var indexObj = this; var postObj = {requests:[]}; for (var i = 0; i < objects.length; ++i) { var request = { action: 'updateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, callback: callback }); }, /* * Delete an object from the index * * @param objectID the unique identifier of object to delete * @param callback (optional) the result callback with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains 3 elements: createAt, taskId and objectID */ deleteObject: function(objectID, callback) { if (objectID === null || objectID.length === 0) { callback(false, { message: 'empty objectID'}); return; } var indexObj = this; this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), callback: callback }); }, /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param query the full text query * @param callback the result callback with two arguments: * success: boolean set to true if the request was successfull. If false, the content contains the error. * content: the server answer that contains the list of results. * @param args (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use a string array encoding (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query. * Attributes are separated by a comma. You can also use a string array encoding (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use a string array encoding, for example tagFilters: ["tag1",["tag2","tag3"]] means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use a string array encoding (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Attributes are separated with a comma (for example `"category,author"` ). * You can also use a JSON string array encoding (for example ["category","author"]). * Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should be considered as optional when found in the query. * The list of words is comma separated. * - distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best * one is kept and others are removed. * @param delay (optional) if set, wait for this delay (in ms) and only send the query if there was no other in the meantime. */ search: function(query, callback, args, delay) { var indexObj = this; var params = 'query=' + encodeURIComponent(query); if (!this.as._isUndefined(args) && args !== null) { params = this.as._getSearchParams(args, params); } window.clearTimeout(indexObj.onDelayTrigger); if (!this.as._isUndefined(delay) && delay !== null && delay > 0) { var onDelayTrigger = window.setTimeout( function() { indexObj._search(params, callback); }, delay); indexObj.onDelayTrigger = onDelayTrigger; } else { this._search(params, callback); } }, /* * Browse all index content * * @param page Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9 * @param hitsPerPage: Pagination parameter used to select the number of hits per page. Defaults to 1000. */ browse: function(page, callback, hitsPerPage) { var indexObj = this; var params = '?page=' + page; if (!this.as._isUndefined(hitsPerPage)) { params += '&hitsPerPage=' + hitsPerPage; } this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse' + params, callback: callback }); }, /* * Get a Typeahead.js adapter * @param searchParams contains an object with query parameters (see search for details) */ ttAdapter: function(params) { var self = this; return function(query, cb) { self.search(query, function(success, content) { if (success) { cb(content.hits); } }, params); }; }, /* * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @param callback the result callback with with two arguments: * success: boolean set to true if the request was successfull * content: the server answer that contains the list of results */ waitTask: function(taskID, callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID, callback: function(success, body) { if (success) { if (body.status === 'published') { callback(true, body); } else { setTimeout(function() { indexObj.waitTask(taskID, callback); }, 100); } } else { callback(false, body); } }}); }, /* * This function deletes the index content. Settings and index specific API keys are kept untouched. * * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the settings object or the error message if a failure occured */ clearIndex: function(callback) { var indexObj = this; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear', callback: callback }); }, /* * Get settings of this index * * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the settings object or the error message if a failure occured */ getSettings: function(callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings', callback: callback }); }, /* * Set settings for this index * * @param settigns the settings object that can contains : * - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3). * - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7). * - hitsPerPage: (integer) the number of hits per page (default = 10). * - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects. * If set to null, all attributes are retrieved. * - attributesToHighlight: (array of strings) default list of attributes to highlight. * If set to null, all indexed attributes are highlighted. * - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number of words to return (syntax is attributeName:nbWords). * By default no snippet is computed. If set to null, no snippet is computed. * - attributesToIndex: (array of strings) the list of fields you want to index. * If set to null, all textual and numerical attributes of your objects are indexed, but you should update it to get optimal results. * This parameter has two important uses: * - Limit the attributes to index: For example if you store a binary image in base64, you want to store it and be able to * retrieve it but you don't want to search in the base64 string. * - Control part of the ranking*: (see the ranking parameter for full explanation) Matches in attributes at the beginning of * the list will be considered more important than matches in attributes further down the list. * In one attribute, matching text at the beginning of the attribute will be considered more important than text after, you can disable * this behavior if you add your attribute inside `unordered(AttributeName)`, for example attributesToIndex: ["title", "unordered(text)"]. * - attributesForFaceting: (array of strings) The list of fields you want to use for faceting. * All strings in the attribute selected for faceting are extracted and added as a facet. If set to null, no attribute is used for faceting. * - attributeForDistinct: (string) The attribute name used for the Distinct feature. This feature is similar to the SQL "distinct" keyword: when enabled * in query with the distinct=1 parameter, all hits containing a duplicate value for this attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best one is kept and others are removed. * - ranking: (array of strings) controls the way results are sorted. * We have six available criteria: * - typo: sort according to number of typos, * - geo: sort according to decreassing distance when performing a geo-location based search, * - proximity: sort according to the proximity of query words in hits, * - attribute: sort according to the order of attributes defined by attributesToIndex, * - exact: * - if the user query contains one word: sort objects having an attribute that is exactly the query word before others. * For example if you search for the "V" TV show, you want to find it with the "V" query and avoid to have all popular TV * show starting by the v letter before it. * - if the user query contains multiple words: sort according to the number of words that matched exactly (and not as a prefix). * - custom: sort according to a user defined formula set in **customRanking** attribute. * The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"] * - customRanking: (array of strings) lets you specify part of the ranking. * The syntax of this condition is an array of strings containing attributes prefixed by asc (ascending order) or desc (descending order) operator. * For example `"customRanking" => ["desc(population)", "asc(name)"]` * - queryType: Select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - highlightPreTag: (string) Specify the string that is inserted before the highlighted parts in the query result (default to "<em>"). * - highlightPostTag: (string) Specify the string that is inserted after the highlighted parts in the query result (default to "</em>"). * - optionalWords: (array of strings) Specify a list of words that should be considered as optional when found in the query. * @param callback (optional) the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer or the error message if a failure occured */ setSettings: function(settings, callback) { var indexObj = this; this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings', body: settings, callback: callback }); }, /* * List all existing user keys associated to this index * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ listUserKeys: function(callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', callback: callback }); }, /* * Get ACL of a user key associated to this index * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ getUserKeyACL: function(key, callback) { var indexObj = this; this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, callback: callback }); }, /* * Delete an existing user key associated to this index * * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ deleteUserKey: function(key, callback) { var indexObj = this; this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, callback: callback }); }, /* * Add an existing user key associated to this index * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKey: function(acls, callback) { var indexObj = this; var aclsObject = {}; aclsObject.acl = acls; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', body: aclsObject, callback: callback }); }, /* * Add an existing user key associated to this index * * @param acls the list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour. * @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call. * @param callback the result callback with two arguments * success: boolean set to true if the request was successfull * content: the server answer with user keys list or error description if success is false. */ addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) { var indexObj = this; var aclsObject = {}; aclsObject.acl = acls; aclsObject.validity = validity; aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour; aclsObject.maxHitsPerQuery = maxHitsPerQuery; this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', body: aclsObject, callback: callback }); }, /// /// Internal methods only after this line /// _search: function(params, callback) { var pObj = {params: params}; if (this.as.jsonp === null) { var self = this; this.as._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: pObj, callback: function(success, content) { if (!success) { // retry first with JSONP self.as.jsonp = true; self._search(params, callback); } else { self.as.jsonp = false; callback && callback(success, content); } } }); } else if (this.as.jsonp) { this.as._jsonRequest({ cache: this.cache, method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: pObj, callback: callback }); } else { this.as._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: pObj, callback: callback}); } }, // internal attributes as: null, indexName: null, cache: {}, typeAheadArgs: null, typeAheadValueOption: null, emptyConstructor: function() {} }; /* * Copyright (c) 2014 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function($) { var extend = function(out) { out = out || {}; for (var i = 1; i < arguments.length; i++) { if (!arguments[i]) { continue; } for (var key in arguments[i]) { if (arguments[i].hasOwnProperty(key)) { out[key] = arguments[i][key]; } } } return out; }; /** * Algolia Search Helper providing faceting and disjunctive faceting * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets */ window.AlgoliaSearchHelper = function(client, index, options) { /// Default options var defaults = { facets: [], // list of facets to compute disjunctiveFacets: [], // list of disjunctive facets to compute hitsPerPage: 20 // number of hits per page }; this.init(client, index, extend({}, defaults, options)); }; AlgoliaSearchHelper.prototype = { /** * Initialize a new AlgoliaSearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {hash} options an associative array defining the hitsPerPage, list of facets and list of disjunctive facets * @return {AlgoliaSearchHelper} */ init: function(client, index, options) { this.client = client; this.index = index; this.options = options; this.page = 0; this.refinements = {}; this.disjunctiveRefinements = {}; this.extraQueries = []; }, /** * Perform a query * @param {string} q the user query * @param {function} searchCallback the result callback called with two arguments: * success: boolean set to true if the request was successfull * content: the query answer with an extra 'disjunctiveFacets' attribute */ search: function(q, searchCallback, searchParams) { this.q = q; this.searchCallback = searchCallback; this.searchParams = searchParams || {}; this.page = this.page || 0; this.refinements = this.refinements || {}; this.disjunctiveRefinements = this.disjunctiveRefinements || {}; this._search(); }, /** * Remove all refinements (disjunctive + conjunctive) */ clearRefinements: function() { this.disjunctiveRefinements = {}; this.refinements = {}; }, /** * Ensure a facet refinement exists * @param {string} facet the facet to refine * @param {string} value the associated value */ addDisjunctiveRefine: function(facet, value) { this.disjunctiveRefinements = this.disjunctiveRefinements || {}; this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {}; this.disjunctiveRefinements[facet][value] = true; }, /** * Ensure a facet refinement does not exist * @param {string} facet the facet to refine * @param {string} value the associated value */ removeDisjunctiveRefine: function(facet, value) { this.disjunctiveRefinements = this.disjunctiveRefinements || {}; this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {}; try { delete this.disjunctiveRefinements[facet][value]; } catch (e) { this.disjunctiveRefinements[facet][value] = undefined; // IE compat } }, /** * Ensure a facet refinement exists * @param {string} facet the facet to refine * @param {string} value the associated value */ addRefine: function(facet, value) { var refinement = facet + ':' + value; this.refinements = this.refinements || {}; this.refinements[refinement] = true; }, /** * Ensure a facet refinement does not exist * @param {string} facet the facet to refine * @param {string} value the associated value */ removeRefine: function(facet, value) { var refinement = facet + ':' + value; this.refinements = this.refinements || {}; this.refinements[refinement] = false; }, /** * Toggle refinement state of a facet * @param {string} facet the facet to refine * @param {string} value the associated value * @return {boolean} true if the facet has been found */ toggleRefine: function(facet, value) { for (var i = 0; i < this.options.facets.length; ++i) { if (this.options.facets[i] == facet) { var refinement = facet + ':' + value; this.refinements[refinement] = !this.refinements[refinement]; this.page = 0; this._search(); return true; } } this.disjunctiveRefinements[facet] = this.disjunctiveRefinements[facet] || {}; for (var j = 0; j < this.options.disjunctiveFacets.length; ++j) { if (this.options.disjunctiveFacets[j] == facet) { this.disjunctiveRefinements[facet][value] = !this.disjunctiveRefinements[facet][value]; this.page = 0; this._search(); return true; } } return false; }, /** * Check the refinement state of a facet * @param {string} facet the facet * @param {string} value the associated value * @return {boolean} true if refined */ isRefined: function(facet, value) { var refinement = facet + ':' + value; if (this.refinements[refinement]) { return true; } if (this.disjunctiveRefinements[facet] && this.disjunctiveRefinements[facet][value]) { return true; } return false; }, /** * Go to next page */ nextPage: function() { this._gotoPage(this.page + 1); }, /** * Go to previous page */ previousPage: function() { if (this.page > 0) { this._gotoPage(this.page - 1); } }, /** * Goto a page * @param {integer} page The page number */ gotoPage: function(page) { this._gotoPage(page); }, /** * Configure the page but do not trigger a reload * @param {integer} page The page number */ setPage: function(page) { this.page = page; }, /** * Configure the underlying index name * @param {string} name the index name */ setIndex: function(name) { this.index = name; }, /** * Get the underlying configured index name */ getIndex: function() { return this.index; }, /** * Clear the extra queries added to the underlying batch of queries */ clearExtraQueries: function() { this.extraQueries = []; }, /** * Add an extra query to the underlying batch of queries. Once you add queries * to the batch, the 2nd parameter of the searchCallback will be an object with a `results` * attribute listing all search results. */ addExtraQuery: function(index, query, params) { this.extraQueries.push({ index: index, query: query, params: (params || {}) }); }, ///////////// PRIVATE /** * Goto a page * @param {integer} page The page number */ _gotoPage: function(page) { this.page = page; this._search(); }, /** * Perform the underlying queries */ _search: function() { this.client.startQueriesBatch(); this.client.addQueryInBatch(this.index, this.q, this._getHitsSearchParams()); var disjunctiveFacets = []; var unusedDisjunctiveFacets = {}; for (var i = 0; i < this.options.disjunctiveFacets.length; ++i) { var facet = this.options.disjunctiveFacets[i]; if (this._hasDisjunctiveRefinements(facet)) { disjunctiveFacets.push(facet); } else { unusedDisjunctiveFacets[facet] = true; } } for (var i = 0; i < disjunctiveFacets.length; ++i) { this.client.addQueryInBatch(this.index, this.q, this._getDisjunctiveFacetSearchParams(disjunctiveFacets[i])); } for (var i = 0; i < this.extraQueries.length; ++i) { this.client.addQueryInBatch(this.extraQueries[i].index, this.extraQueries[i].query, this.extraQueries[i].params); } var self = this; this.client.sendQueriesBatch(function(success, content) { if (!success) { self.searchCallback(false, content); return; } var aggregatedAnswer = content.results[0]; aggregatedAnswer.disjunctiveFacets = aggregatedAnswer.disjunctiveFacets || {}; aggregatedAnswer.facetStats = aggregatedAnswer.facetStats || {}; for (var facet in unusedDisjunctiveFacets) { if (aggregatedAnswer.facets[facet] && !aggregatedAnswer.disjunctiveFacets[facet]) { aggregatedAnswer.disjunctiveFacets[facet] = aggregatedAnswer.facets[facet]; try { delete aggregatedAnswer.facets[facet]; } catch (e) { aggregatedAnswer.facets[facet] = undefined; // IE compat } } } for (var i = 0; i < disjunctiveFacets.length; ++i) { for (var facet in content.results[i + 1].facets) { aggregatedAnswer.disjunctiveFacets[facet] = content.results[i + 1].facets[facet]; if (self.disjunctiveRefinements[facet]) { for (var value in self.disjunctiveRefinements[facet]) { if (!aggregatedAnswer.disjunctiveFacets[facet][value] && self.disjunctiveRefinements[facet][value]) { aggregatedAnswer.disjunctiveFacets[facet][value] = 0; } } } } for (var stats in content.results[i + 1].facets_stats) { aggregatedAnswer.facetStats[stats] = content.results[i + 1].facets_stats[stats]; } } if (self.extraQueries.length === 0) { self.searchCallback(true, aggregatedAnswer); } else { var c = { results: [ aggregatedAnswer ] }; for (var i = 0; i < self.extraQueries.length; ++i) { c.results.push(content.results[1 + disjunctiveFacets.length + i]); } self.searchCallback(true, c); } }); }, /** * Build search parameters used to fetch hits * @return {hash} */ _getHitsSearchParams: function() { var facets = []; for (var i = 0; i < this.options.facets.length; ++i) { facets.push(this.options.facets[i]); } for (var i = 0; i < this.options.disjunctiveFacets.length; ++i) { var facet = this.options.disjunctiveFacets[i]; if (!this._hasDisjunctiveRefinements(facet)) { facets.push(facet); } } return extend({}, { hitsPerPage: this.options.hitsPerPage, page: this.page, facets: facets, facetFilters: this._getFacetFilters() }, this.searchParams); }, /** * Build search parameters used to fetch a disjunctive facet * @param {string} facet the associated facet name * @return {hash} */ _getDisjunctiveFacetSearchParams: function(facet) { return extend({}, this.searchParams, { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], facets: facet, facetFilters: this._getFacetFilters(facet) }); }, /** * Test if there are some disjunctive refinements on the facet */ _hasDisjunctiveRefinements: function(facet) { for (var value in this.disjunctiveRefinements[facet]) { if (this.disjunctiveRefinements[facet][value]) { return true; } } return false; }, /** * Build facetFilters parameter based on current refinements * @param {string} facet if set, the current disjunctive facet * @return {hash} */ _getFacetFilters: function(facet) { var facetFilters = []; for (var refinement in this.refinements) { if (this.refinements[refinement]) { facetFilters.push(refinement); } } for (var disjunctiveRefinement in this.disjunctiveRefinements) { if (disjunctiveRefinement != facet) { var refinements = []; for (var value in this.disjunctiveRefinements[disjunctiveRefinement]) { if (this.disjunctiveRefinements[disjunctiveRefinement][value]) { refinements.push(disjunctiveRefinement + ':' + value); } } if (refinements.length > 0) { facetFilters.push(refinements); } } } return facetFilters; } }; })(); /* * Copyright (c) 2014 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ (function($) { /** * Algolia Places API * @param {string} Your application ID * @param {string} Your API Key */ window.AlgoliaPlaces = function(applicationID, apiKey) { this.init(applicationID, apiKey); }; AlgoliaPlaces.prototype = { /** * @param {string} Your application ID * @param {string} Your API Key */ init: function(applicationID, apiKey) { this.client = new AlgoliaSearch(applicationID, apiKey, 'http', true, ['places-1.algolia.io', 'places-2.algolia.io', 'places-3.algolia.io']); this.cache = {}; }, /** * Perform a query * @param {string} q the user query * @param {function} searchCallback the result callback called with two arguments: * success: boolean set to true if the request was successfull * content: the query answer with an extra 'disjunctiveFacets' attribute * @param {hash} the list of search parameters */ search: function(q, searchCallback, searchParams) { var indexObj = this; var params = 'query=' + encodeURIComponent(q); if (!this.client._isUndefined(searchParams) && searchParams != null) { params = this.client._getSearchParams(searchParams, params); } var pObj = {params: params, apiKey: this.client.apiKey, appID: this.client.applicationID}; this.client._jsonRequest({ cache: this.cache, method: 'POST', url: '/1/places/query', body: pObj, callback: searchCallback, removeCustomHTTPHeaders: true }); } }; })();
algolia/github-awesome-autocomplete
code/js/libs/algoliasearch.js
JavaScript
mit
83,838
'use strict'; angular.module('rvplusplus').directive('initFocus', function() { return { restrict: 'A', // only activate on element attribute link: function(scope, element, attrs) { element.focus(); } }; });
theikkila/rvplusplus-client
app/scripts/directives.js
JavaScript
mit
251
/** * @arliteam/arli v0.2.1 * https://github.com/arliteam/arli * * Copyright (c) Mohamed Elkebir (https://getsupercode.com) * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ "use strict"; exports.__esModule = true; /** * Test if a date string is in latin DMY format. * * Date format: DD/MM/YY[YY] DD.MM.YY[YY] DD-MM-YY[YY] DD MM YY[YY] * * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 30/12/2000 | 30/12/99 * 30-12-2000 | 30-12-99 * 30.12.2000 | 30.12.99 * 30 12 2000 | 30 12 99 * * @param date A string of date to be tested */ exports.isDateDMY = function (date) { var pattern = /^(31|30|(?:0[1-9]|[1-2][0-9]))(\/|\.|-| )(12|11|10|0[1-9])(\2)(\d{4}|\d{2})$/; return pattern.test(date); }; /** * Test if a date string is in latin MDY format. * * Date format: MM/DD/YY[YY] MM.DD.YY[YY] MM-DD-YY[YY] MM DD YY[YY] * * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 12/30/2000 | 12/30/99 * 12-30-2000 | 12-30-99 * 12.30.2000 | 12.30.99 * 12 30 2000 | 12 30 99 * * @param date A string of date to be tested */ exports.isDateMDY = function (date) { var pattern = /^(12|11|10|0[1-9])(\/|\.|-| )(31|30|(?:0[1-9]|[1-2][0-9]))(\2)(\d{4}|\d{2})$/; return pattern.test(date); }; /** * Test if a date string is in latin YMD format. * * Date format: YY[YY]/MM/DD YY[YY].MM.DD YY[YY]-MM-DD YY[YY] MM DD * * https://en.wikipedia.org/wiki/Date_format_by_country * * @example * 2000/12/30 | 99/12/30 * 2000-12-30 | 99-12-30 * 2000.12.30 | 99.12.30 * 2000 12 30 | 99 12 30 * * @param date A string of date to be tested */ exports.isDateYMD = function (date) { var pattern = /^(\d{4}|\d{2})(\/|\.|-| )(12|11|10|0[1-9])(\2)(31|30|(?:0[1-9]|[1-2][0-9]))$/; return pattern.test(date); };
elkebirmed/arli
build/lib/dates.js
JavaScript
mit
1,873
import external from '../../../externalModules.js'; import getNumberValues from './getNumberValues.js'; import parseImageId from '../parseImageId.js'; import dataSetCacheManager from '../dataSetCacheManager.js'; import getImagePixelModule from './getImagePixelModule.js'; import getOverlayPlaneModule from './getOverlayPlaneModule.js'; import getLUTs from './getLUTs.js'; import getModalityLUTOutputPixelRepresentation from './getModalityLUTOutputPixelRepresentation.js'; function metaDataProvider(type, imageId) { const { dicomParser } = external; const parsedImageId = parseImageId(imageId); const dataSet = dataSetCacheManager.get(parsedImageId.url); if (!dataSet) { return; } if (type === 'generalSeriesModule') { return { modality: dataSet.string('x00080060'), seriesInstanceUID: dataSet.string('x0020000e'), seriesNumber: dataSet.intString('x00200011'), studyInstanceUID: dataSet.string('x0020000d'), seriesDate: dicomParser.parseDA(dataSet.string('x00080021')), seriesTime: dicomParser.parseTM(dataSet.string('x00080031') || ''), }; } if (type === 'patientStudyModule') { return { patientAge: dataSet.intString('x00101010'), patientSize: dataSet.floatString('x00101020'), patientWeight: dataSet.floatString('x00101030'), }; } if (type === 'imagePlaneModule') { const imageOrientationPatient = getNumberValues(dataSet, 'x00200037', 6); const imagePositionPatient = getNumberValues(dataSet, 'x00200032', 3); const pixelSpacing = getNumberValues(dataSet, 'x00280030', 2); let columnPixelSpacing = null; let rowPixelSpacing = null; if (pixelSpacing) { rowPixelSpacing = pixelSpacing[0]; columnPixelSpacing = pixelSpacing[1]; } let rowCosines = null; let columnCosines = null; if (imageOrientationPatient) { rowCosines = [ parseFloat(imageOrientationPatient[0]), parseFloat(imageOrientationPatient[1]), parseFloat(imageOrientationPatient[2]), ]; columnCosines = [ parseFloat(imageOrientationPatient[3]), parseFloat(imageOrientationPatient[4]), parseFloat(imageOrientationPatient[5]), ]; } return { frameOfReferenceUID: dataSet.string('x00200052'), rows: dataSet.uint16('x00280010'), columns: dataSet.uint16('x00280011'), imageOrientationPatient, rowCosines, columnCosines, imagePositionPatient, sliceThickness: dataSet.floatString('x00180050'), sliceLocation: dataSet.floatString('x00201041'), pixelSpacing, rowPixelSpacing, columnPixelSpacing, }; } if (type === 'imagePixelModule') { return getImagePixelModule(dataSet); } if (type === 'modalityLutModule') { return { rescaleIntercept: dataSet.floatString('x00281052'), rescaleSlope: dataSet.floatString('x00281053'), rescaleType: dataSet.string('x00281054'), modalityLUTSequence: getLUTs( dataSet.uint16('x00280103'), dataSet.elements.x00283000 ), }; } if (type === 'voiLutModule') { const modalityLUTOutputPixelRepresentation = getModalityLUTOutputPixelRepresentation( dataSet ); return { windowCenter: getNumberValues(dataSet, 'x00281050', 1), windowWidth: getNumberValues(dataSet, 'x00281051', 1), voiLUTSequence: getLUTs( modalityLUTOutputPixelRepresentation, dataSet.elements.x00283010 ), }; } if (type === 'sopCommonModule') { return { sopClassUID: dataSet.string('x00080016'), sopInstanceUID: dataSet.string('x00080018'), }; } if (type === 'petIsotopeModule') { const radiopharmaceuticalInfo = dataSet.elements.x00540016; if (radiopharmaceuticalInfo === undefined) { return; } const firstRadiopharmaceuticalInfoDataSet = radiopharmaceuticalInfo.items[0].dataSet; return { radiopharmaceuticalInfo: { radiopharmaceuticalStartTime: dicomParser.parseTM( firstRadiopharmaceuticalInfoDataSet.string('x00181072') || '' ), radionuclideTotalDose: firstRadiopharmaceuticalInfoDataSet.floatString( 'x00181074' ), radionuclideHalfLife: firstRadiopharmaceuticalInfoDataSet.floatString( 'x00181075' ), }, }; } if (type === 'overlayPlaneModule') { return getOverlayPlaneModule(dataSet); } } export default metaDataProvider;
chafey/cornerstoneWADOImageLoader
src/imageLoader/wadouri/metaData/metaDataProvider.js
JavaScript
mit
4,492
import Tablesaw from '../../dist/tablesaw'; console.log( "this should be the tablesaw object: ", Tablesaw );
filamentgroup/tablesaw
demo/webpack/app.js
JavaScript
mit
111
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // // //= require_tree .
devis/email-me
app/assets/javascripts/email_me/application.js
JavaScript
mit
602
(function(){ ///////////////////////////////////////////////////////////////////////// // // // client/helpers/config.js // // // ///////////////////////////////////////////////////////////////////////// // Accounts.ui.config({ // 1 passwordSignupFields: 'USERNAME_ONLY' // 2 }); // ///////////////////////////////////////////////////////////////////////// }).call(this);
SFII/equip
src/.meteor/local/build/programs/web.browser/app/client/helpers/config.js
JavaScript
mit
774
/** * Vector */ (function() { var global = this, nspace = global.Util, Exception = global.Exception, math = global.mathjs(); /** * * @type Vector * @param {Array} basis The basis vectors, ordered correctly, orthonormal and complete */ var Vector = nspace.Vector = function(basis) { if (!basis || ('length' in basis && basis.length === 0)) { throw new Exception.InvalidPreparation('Basis vector cannot be empty'); } // Set basis and init components with same length and value of 1 this.basis = basis; this.components = basis.map(function() { return 1; }); }; /** * Computes the inner product of two vectors, <v1|v2> * * @returns {mathjs} Scalar */ Vector.innerProduct = function(v1, v2) { var basis1 = v1.getBasis(), basis2 = v2.getBasis(); // Must have same basis lengths if (basis1.length !== basis2.length) { throw new Exception.InvalidPreparation('Basis must be same length'); } var comp1 = v1.getComponents(), comp2 = v2.getComponents(); var product = 0; // Essentially a foil operation, but this will support greater than two terms for (var i = 0; i < basis1.length; i++) { for (var j = 0; j < basis2.length; j++) { var comp = math.multiply(math.conj(comp1[i]), comp2[j]); var basis = math.multiply(math.conj(math.transpose(basis1[i])), basis2[j]); product = math.add(product, math.multiply(comp, basis)); } } return product.get([0,0]); }; /** * Computes the outer product of two vectors, * (|v1x><v1x| + |v1y><v1y|)(|v2x> + |v2y>) * * @returns {undefined} */ Vector.outerProduct = function(v1, v2) { var basis1 = v1.getBasis(), basis2 = v2.getBasis(); // Must have same basis lengths if (basis1.length !== basis2.length) { throw new Exception.InvalidPreparation('Basis must be same length'); } var comp1 = v1.getComponents(), comp2 = v2.getComponents(); var product = new Vector(basis1); // Essentially a foil operation, but this will support greater than two terms for (var i = 0; i < basis1.length; i++) { var productComp = 0; for (var j = 0; j < basis2.length; j++) { var comp = math.multiply(math.conj(comp1[i]), comp2[j]); var basis = math.multiply(math.conj(math.transpose(basis1[i])), basis2[j]); productComp = math.add(productComp, math.multiply(comp, basis)); } product.setComponent(i, productComp.get([0,0])); } return product; }; /** * */ Vector.prototype = { basis: null, components: null, /** * * @param {Number} index The basis vector index * @param {Mixed} value * @returns {Vector} */ setComponent: function(index, value) { if (index >= this.components.length) { throw new Exception.InvalidProperty('Invalid basis index'); } this.components[index] = value; return this; }, /** * * @param {Number} index The basis vector index * @returns {Number} */ getComponent: function(index) { if (index >= this.components.length) { throw new Exception.InvalidProperty('Invalid basis index'); } return this.components[index]; }, /** * * @param {Array} values * @returns {Vector} */ setComponents: function(values) { if (values.length !== this.components.length) { throw new Exception.InvalidProperty('Invalid'); } this.components = values; return this; }, /** * * @returns {Number[]} */ getComponents: function() { return this.components; }, /** * * @returns {mathjs} */ getBasis: function() { return this.basis; }, /** * Applies a scalar to the vector components, simulates applying a scalar to * vector mathematically * * @param {Number} scalar * @returns {Vector} */ scale: function(scalar) { this.components = this.components.map(function(component) { return math.multiply(scalar, component); }); return this; }, /** * Determines the magnitude of the vector, sqrt(x*x + y*y) * * @returns {mathjs} */ getMagnitude: function() { var magnitude = 0; for (var i = 0; i < this.components.length; i++) { var c = this.components[i]; magnitude = math.add(magnitude, math.multiply(math.conj(c),c)); } return math.sqrt(magnitude); }, /** * Multiplies the components by a scalar to that makes the magnitude 1 * * @returns {Vector} */ normalize: function() { var magSq = Vector.innerProduct(this, this); // Already normalized if (magSq === 1) { return this; } return this.scale(math.divide(1,math.sqrt(magSq))); }, /** * * @returns {Vector} */ clone: function() { var v = new Vector(this.getBasis()); v.setComponents(this.getComponents()); return v; }, /** * Returns a new vector that is just one basis dir, by index of the basis * set * * @param {Number} index * @returns {Vector} */ getBasisVector: function(index) { var v = this.clone(); // Set all other component values to zero other than the index v.setComponents(this.components.map(function(val, i) { return (i === index) ? val : 0; })); return v.normalize(); } }; })();
bjester/quantum-probability
lib/util/Vector.js
JavaScript
mit
5,940
'use strict'; export default function routes($routeProvider) { 'ngInject'; $routeProvider.when('/new_component', { template: '<about></about>' }); $routeProvider.when('/new_component/:somethingToPrint', { template: '<about></about>' }); }
whoppa/COMP-3705
client/app/Component/new_component.routes.js
JavaScript
mit
259
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'firehon', environment: environment, contentSecurityPolicy: { 'connect-src': "'self' wss://*.firebaseio.com" }, firebase: 'https://firehon.firebaseio.com/', baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
nihey/firehon
config/environment.js
JavaScript
mit
1,201
'use strict'; angular.module('springangularwayApp') .config(function ($stateProvider) { $stateProvider .state('configuration', { parent: 'admin', url: '/configuration', data: { roles: ['ROLE_ADMIN'], pageTitle: 'configuration.title' }, views: { 'content@': { templateUrl: 'scripts/app/admin/configuration/configuration.html', controller: 'ConfigurationController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('configuration'); return $translate.refresh(); }] } }); });
sunilp/spring-angular-way
src/main/webapp/scripts/app/admin/configuration/configuration.js
JavaScript
mit
972
var path = require('path') var webpack = require('webpack') // Phaser webpack config var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/') var phaser = path.join(phaserModule, 'build/custom/phaser-split.js') var pixi = path.join(phaserModule, 'build/custom/pixi.js') var p2 = path.join(phaserModule, 'build/custom/p2.js') var definePlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')) }) module.exports = { entry: { app: [ 'babel-polyfill', path.resolve(__dirname, 'src/main.js') ], vendor: ['pixi', 'p2', 'phaser', 'webfontloader', 'react'] }, output: { path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: 'bundle.js' }, plugins: [ definePlugin, new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.optimize.UglifyJsPlugin({ drop_console: true, minimize: true, output: { comments: false } }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor'/* chunkName= */, filename: 'vendor.bundle.js'/* filename= */}) ], module: { rules: [ { test: /\.js$/, use: ['babel-loader'], include: path.join(__dirname, 'src') }, { test: /pixi\.js/, use: ['expose-loader?PIXI'] }, { test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] }, { test: /p2\.js/, use: ['expose-loader?p2'] }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['react', 'es2015']} } ] }, node: { fs: 'empty', net: 'empty', tls: 'empty' }, resolve: { alias: { 'phaser': phaser, 'pixi': pixi, 'p2': p2 } } }
jtak93/phaser-practice
webpack.production.config.js
JavaScript
mit
1,817
define([ 'base/Module', './show/Controller' ],function(Module, ShowController){ var mod = Module('HeaderModule', {autoStart: false}); var API = { showHeader: function() { var controller = new ShowController({ region: mod.kernel.headerRegion }); controller.showHeader(); } }; mod.on('start', function(){ API.showHeader(); }); });
alexbrouwer/Symfony2
src/Gearbox/ClientBundle/Resources/public/js/modules/header/main.js
JavaScript
mit
435
export function pluralize(count, word) { return count === 1 ? word : word + 's'; } export function classNames(...args) { // based on https://github.com/JedWatson/classnames let classes = ''; args.forEach(arg => { if (arg) { const argType = typeof arg; if (argType === 'string' || argType === 'number') { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames(...arg); } else if (argType === 'object') { Object.keys(arg).forEach(key => { if (arg[key]) { classes += ' ' + key; } }); } } }); return classes.substr(1); } export function uuid() { let i, random; let uuid = ''; for (i = 0; i < 32; i++) { random = Math.random() * 16 | 0; if (i === 8 || i === 12 || i === 16 || i === 20) { uuid += '-'; } uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)) .toString(16); } return uuid; }
bicyclejs/bicycle
example/client/utils.js
JavaScript
mit
981
'use babel'; //showSearch import FoldNavigatorView from './fold-navigator-view'; import fuzzaldrinPlus from 'fuzzaldrin-plus'; import _ from 'lodash'; import { CompositeDisposable } from 'atom'; export default { config: { autofold: { title: 'Autofold on open', description: 'Autofold all folds when you open a document. config.cson key : autofold', type: 'boolean', default: false }, keepFolding: { title: 'Keep code folded.', description: 'Everytime you click on one of the fold navigator element all code folds will be folded before the selected fold opens. Usefull if you want to keep your code folded all the time. Note that if you are using ctrl-alt-cmd-up/down keys to navigate it will not close the folds. Also you can temporarily enable/disable this behaviour by holding down the option key while you click. config.cson key : keepFolding', type: 'boolean', default: false }, showLineNumbers: { title: 'Show line number.', description: 'Show line numbers in fold navigator. config.cson key : showLineNumbers', type: 'boolean', default: true }, indentationCharacter: { title: 'Indentation character.', description: 'The character used for indentation in the fold navigator panel. config.cson key : indentationCharacter', type: 'string', default: 'x' }, maxLineContentLength: { title: 'Maximum line length.', description: 'Fold Navigator will take the line on which the fold is on but if the line is longer than this many characters then it will truncate it. config.cson key : maxLineContentLength', type: 'integer', default: 60 }, minLineLength: { title: 'Minimum line length.', description: 'Sometimes the fold falls on line which contains very little information. Typically comments like /** are meaningless. If the line content is less then this many characters use the next line for the fold description. config.cson key : minLineLength', type: 'integer', default: 6 }, keepFoldingAllTime: { title: 'Keep code folded even on shortcuts.', description: 'It will fold all folds before opening a new one. config.cson key : keepFoldingAllTime', type: 'boolean', default: false }, autoScrollFoldNavigatorPanel: { title: 'Auto scroll fold navigator panel.', description: 'Scrolls the fold navigator panel to the active fold. config.cson key : autoScrollFoldNavigatorPanel', type: 'boolean', default: true }, unfoldAllSubfolds: { title: 'Unfold all subfolds.', description: 'When a fold is selected/active all subfolds will be unfolded as well. When you have lots of subfolds to open this can be sluggish. config.cson key : unfoldAllSubfolds', type: 'boolean', default: true }, maxFoldLevel: { title: 'Maximum fold level fold navigator will list.', description: 'It is possibly not much use listing every single fold. With this option you can limit the fold level depth we list on the panel hopefully giving you a better overview of the code. config.cson key : maxFoldLevel', type: 'integer', default: 10, }, whenMatchedUsePreviousLine: { title: 'Previous line should be used for description.', description: 'Comma separated values. If the content of the line matches any of these values the previous line is going to be used for the fold description. This is so that we avoid listing just a single bracket for example which would be pretty meaningless.', type: 'string', default: '{,{ ', }, log: { title: 'Turn on logging', description: 'It might help to sort out mysterious bugs.', type: 'boolean', default: false, }, }, activate(state) { //console.log(arguments.callee.name); /* this.settings = null; */ this.settings = null; this.iniSettings(); /* this.lines2fold = []; Key is the line number and the value is the line number of the last fold looped through in the document. currently the fold ending are not observed maybe I should change this in the future note that we will work with the line numbers displayed and not the actuall line number which can be 0 */ this.lines2fold = []; /* this.folds = []; array of row numbers where the folds are */ this.folds = []; /* this.visibleFolds = []; same as this.folds but limited by this.settings.maxFoldLevel */ this.visibleFolds = []; /* this.foldObjects = {}; we need this to be able to navigate levels an example bellow see this.parse it should really be a new Map(); { line: i, children: [], parent: parent, indentation: indentLevel, content: '', } */ this.foldObjects = {}; /* exactly the same as this.foldObjects but came later because of fuzzaldrin-plus which only seems to work with arrays as far as I can tell */ this.foldObjectsArray = []; /* this.foldLevels = {}; row numbers of the folds orgenised by level usefull for the commands which fold unfold levels */ this.foldLevels = {}; /* this.history = []; only used as a short term log so that we can navigate fold level down */ this.history = []; /* this.activeFold line number of the fold which we are on this is what gets highlighted on the fold navigator panel item */ this.activeFold = null; // subscriptions this.subscriptions = new CompositeDisposable(); this.onDidChangeCursorPositionSubscription = null; this.foldNavigatorView = new FoldNavigatorView(state.foldNavigatorViewState); // when active pane item changed parse code and change content of navigator panel atom.workspace.observeActivePaneItem((pane) => { this.observeActivePaneItem(pane) }); // parse content of editor each time it stopped changing atom.workspace.observeTextEditors((editor) => { this.observeTextEditors(editor) }); // attach onclick event to the fold navigator lines this.navigatorElementOnClick(); this.registerCommands(); /* this.panel = null; foldnavigator panel */ this.panel = null; this.addNavigatorPanel(); /* this.searchModal */ this.searchModal = null; this.searchModalElement = null; this.searchModalInput = null; this.searchModalItems = null; this.addSearchModal(); }, // observer text editors coming and going observeTextEditors(editor) { //console.log(arguments.callee.name); if (this.settings && this.settings.autofold && editor){ editor.foldAll(); } }, // every time the active pane changes this will get called observeActivePaneItem(pane) { //console.log(arguments.callee.name); var editor = atom.workspace.getActiveTextEditor(); var listener; var editorView; if (!editor) return; //dispose of previous subscription if (this.onDidChangeCursorPositionSubscription) { this.onDidChangeCursorPositionSubscription.dispose(); } // follow cursor in fold navigator register subscription so that we can remove it this.onDidChangeCursorPositionSubscription = editor.onDidChangeCursorPosition( _.debounce((event) => this.onDidChangeCursorPosition(event), 500) ); //dispose of previous subscription if (this.onDidStopChangingSubscription) { this.onDidStopChangingSubscription.dispose(); } // if document changed subscription this.onDidStopChangingSubscription = editor.onDidStopChanging( _.debounce((event) => this.parse(editor), 500) ); this.parse(editor); }, clearSearchModal() { if (!this.searchModal) return; this.searchModalItems.innerHTML = ''; this.searchModalInput.value = ''; }, alignEditorToSearch() { var selectedArr = this.searchModalItems.getElementsByClassName('fold-navigator-search-modal-item-selected'); var selected = selectedArr[0]; var editor = atom.workspace.getActiveTextEditor(); if (selected && selected.dataset.row >= 0) { this.moveCursor(selected.dataset.row, false); } }, searchModalOnClick(event) { var row; var editor = atom.workspace.getActiveTextEditor(); var clicked = null; this.hideSearch(); if (event.target.matches('.fold-navigator-search-modal-item')) { clicked = event.target; } else if (event.target.matches('.fold-navigator-indentation') && event.target.parentNode && event.target.parentNode.matches('.fold-navigator-search-modal-item')) { clicked = event.target.parentNode; } if (!clicked) return; row = clicked.dataset.row; //problem if (!row) return; this.moveCursor(row, false); }, addSearchModal() { this.searchModalElement = document.createElement('div'); this.searchModalElement.classList.add('fold-navigator-search-modal'); this.searchModalElement.classList.add('native-key-bindings'); this.searchModalInput = document.createElement('input'); this.searchModalItems = document.createElement('div'); this.searchModalElement.appendChild(this.searchModalInput); this.searchModalElement.appendChild(this.searchModalItems); this.searchModal = atom.workspace.addModalPanel({ item: this.searchModalElement, visible: false }); // on blur this.searchModalInput.addEventListener('blur', (event) => { // delay hiding because of the on click event won't fire otherwise WHAT an ugly way to solve it :) setTimeout(() => { this.hideSearch(); }, 200); }); // on click this.searchModalElement.addEventListener('click', (event) => { this.searchModalOnClick(event); }, true); // on input this.searchModalInput.addEventListener('input', () => { this.searchModalItems.innerHTML = ''; var query = this.searchModalInput.value; if (!query || query.length < 1) return; var filteredItems = fuzzaldrinPlus.filter(this.foldObjectsArray, query, { key: 'content' }); var html = ''; filteredItems.forEach((item, index) => { let selected = ' fold-navigator-search-modal-item-selected'; if (index > 0) { selected = ''; } //let html2add = '<div id="' + id + '" class="' + classList + '" data-row="' + i + '">' + gutter + lineNumberSpan + indentHtml + content.innerHTML + '</div>'; let indentHtml = ''; for (let j = 0; j < item.indentation; j++) { indentHtml += '<span class="fold-navigator-indentation">' + this.settings.indentationCharacter + '</span>'; } html += '<div class="fold-navigator-search-modal-item fold-navigator-item-indent-' + item.indentation + selected + '" data-row="' + item.line + '">' + indentHtml + item.content + '</div>'; }); this.searchModalItems.innerHTML = html; //var matches = fuzzaldrinPlus.match(displayName, this.searchModalInput.value); //filterQuery box from text input //items ?? // { key: @getFilterKey() } }); this.searchModalElement.addEventListener('keydown', (e) => { var sc = 'fold-navigator-search-modal-item-selected'; if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode == 13 || e.keyCode == 27) { var items = this.searchModalItems.getElementsByClassName('fold-navigator-search-modal-item'); if (!items) return; // remove selected var selectedArr = this.searchModalItems.getElementsByClassName(sc); var selected = selectedArr[0]; if (selected) { selected.classList.remove(sc); } var first = items[0] ? items[0] : false; var last = items[items.length - 1] ? items[items.length - 1] : false; var next = null; if (e.keyCode === 38) { // up if (selected) { next = selected.previousElementSibling; } } else if (e.keyCode === 40) { // down if (selected) { next = selected.nextElementSibling; } } else if (e.keyCode === 27) { // esc this.hideSearch(); } else if (e.keyCode == 13) { // enter if (selected) { if (selected.dataset.row >= 0) { let editor = atom.workspace.getActiveTextEditor(); this.moveCursor(selected.dataset.row, false); this.hideSearch(); } } } // end of line or not selected if (!next) { if (e.keyCode === 38) next = last; else { next = first; } } if (next) { next.classList.add(sc); } } }); //var matches = fuzzaldrinPlus.match(displayName, filterQuery) }, hideSearch() { this.searchModal.hide(); let editor = atom.workspace.getActiveTextEditor(); if (editor) atom.views.getView(editor).focus(); }, showSearch() { if (!editor) return; this.searchModal.show(); this.searchModalInput.focus(); this.searchModalInput.select(); }, toggleSearch() { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if (this.searchModal.isVisible()) { this.searchModal.hide(); atom.views.getView(editor).focus(); } else { this.searchModal.show(); this.searchModalInput.focus(); this.searchModalInput.select(); } }, onDidChangeCursorPosition(event) { //console.log(arguments.callee.name); this.selectRow(event.newBufferPosition.row); }, addNavigatorPanel() { //console.log(arguments.callee.name); var element = this.foldNavigatorView.getElement(); if (atom.config.get('tree-view.showOnRightSide')) { this.panel = atom.workspace.addLeftPanel({ item: element, visible: false }); } else { this.panel = atom.workspace.addRightPanel({ item: element, visible: false }); } }, iniSettings() { //console.log(arguments.callee.name); var editor = atom.workspace.getActiveTextEditor(); var languageSettings = null; if (editor) { let scope = editor.getGrammar().scopeName; languageSettings = atom.config.get('fold-navigator', { 'scope': [scope] }); } this.settings = atom.config.get('fold-navigator'); if (languageSettings){ Object.assign(this.settings, languageSettings); } // parse the comma separated string whenMatchedUsePreviousLine if(this.settings.whenMatchedUsePreviousLine && this.settings.whenMatchedUsePreviousLine.trim() != ''){ this.settings.whenMatchedUsePreviousLineArray = this.settings.whenMatchedUsePreviousLine.split(','); if(this.settings.whenMatchedUsePreviousLineArray.constructor !== Array){ this.settings.whenMatchedUsePreviousLineArray = null; } } }, registerCommands() { //"ctrl-alt-cmd-up": "fold-navigator:previousFoldAtCurrentLevel", //"ctrl-alt-cmd-down": "fold-navigator:nextFoldAtCurrentLevel", //"ctrl-alt-cmd-up": "fold-navigator:previousFold", //"ctrl-alt-cmd-down": "fold-navigator:nextFold", // //console.log(arguments.callee.name); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggle': () => this.toggle() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:open': () => this.open() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:close': () => this.close() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:previousFold': () => this.previousFold() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:nextFold': () => this.nextFold() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:moveLevelUp': () => this.moveLevelUp() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:moveLevelDown': () => this.moveLevelDown() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:nextFoldAtCurrentLevel': () => this.nextFoldAtCurrentLevel() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:previousFoldAtCurrentLevel': () => this.previousFoldAtCurrentLevel() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldSubfolds': () => this.unfoldSubfoldsPublic() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldActive': () => this.foldActivePublic() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel1': () => this.unfoldAtLevel1() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel2': () => this.unfoldAtLevel2() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel3': () => this.unfoldAtLevel3() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel4': () => this.unfoldAtLevel4() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:unfoldAtLevel5': () => this.unfoldAtLevel5() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel1': () => this.foldAtLevel1() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel2': () => this.foldAtLevel2() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel3': () => this.foldAtLevel3() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel4': () => this.foldAtLevel4() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:foldAtLevel5': () => this.foldAtLevel5() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel1': () => this.toggleFoldsLevel1() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel2': () => this.toggleFoldsLevel2() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel3': () => this.toggleFoldsLevel3() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel4': () => this.toggleFoldsLevel4() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleFoldsLevel5': () => this.toggleFoldsLevel5() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleSearch': () => this.toggleSearch() })); this.subscriptions.add(atom.commands.add('atom-workspace', { 'fold-navigator:toggleActiveFold': () => this.toggleActiveFold() })); }, previousFold() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } var folds = this.visibleFolds; if (!folds || folds.length === 0) return; //console.log(arguments.callee.name); this.clearHistory(); var fold = this.foldNavigatorView.getActiveFold(); var index = folds.indexOf(fold); var previous; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if (index !== 0) { previous = folds[index - 1]; } else { previous = folds[folds.length - 1]; } if (previous || previous === 0) { this.moveCursor(previous); } }, nextFold() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } //console.log(arguments.callee.name); this.clearHistory(); var folds = this.visibleFolds; if (!folds || folds.length === 0) return; var fold = this.foldNavigatorView.getActiveFold(); var index = folds.indexOf(fold); var next; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if (folds.length !== (index + 1)) { next = folds[index + 1]; } else { next = folds[0]; } if (next || next === 0) { this.moveCursor(next); } }, previousFoldAtCurrentLevel() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } //console.log(arguments.callee.name); this.clearHistory(); var fold = this.foldNavigatorView.getActiveFold(); var previous; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; var indentation = 0; if (fold || fold === 0) { indentation = editor.indentationForBufferRow(fold); } var level = this.getLevel(indentation); if (!level) return; var index = level.indexOf(fold); if (index !== 0) { previous = level[index - 1]; } else { previous = level[level.length - 1]; } if (previous || previous === 0) { this.moveCursor(previous); } }, nextFoldAtCurrentLevel() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } this.clearHistory(); //console.log(arguments.callee.name); var fold = this.foldNavigatorView.getActiveFold(); var next; var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; var indentation = 0; if (fold || fold === 0) { indentation = editor.indentationForBufferRow(fold); } var level = this.getLevel(indentation); if (!level) return; var index = level.indexOf(fold); if (level.length !== (index + 1)) { next = level[index + 1]; } else { next = level[0]; } if (next || next === 0) { this.moveCursor(next); } }, moveLevelUp() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } var fold = this.foldNavigatorView.getActiveFold(); var foldObj = this.foldObjects[fold] ? this.foldObjects[fold] : false; var editor = atom.workspace.getActiveTextEditor(); var parent; if (!editor || !foldObj) { return; } parent = this.getParentFold(foldObj); if ((parent || parent === 0) && parent !== 'root') { this.moveCursor(parent); this.addToHistory(fold); } }, moveLevelDown() { if (this.searchModal.isVisible()) { this.alignEditorToSearch(); return; } var fold = this.foldNavigatorView.getActiveFold(); var foldObj = this.foldObjects[fold] ? this.foldObjects[fold] : false; var editor = atom.workspace.getActiveTextEditor(); var child; if (!editor || !foldObj || foldObj.children.length === 0) { return; } child = this.getLastFromHistory(); // check if the last item in history actually belongs to this parent if (!child && foldObj.children.indexOf(child) === -1) child = foldObj.children[0]; if (child) { this.moveCursor(child); } }, getParentFold(foldObj) { if (!foldObj) { return false; } // badly indented/formated code - there must be a parent so return the previous fold the next best chance of being the parent if (foldObj.parent === 'root' && foldObj.indentation > 0) { let index = this.folds.indexOf(foldObj.line); let prev = this.folds[index - 1]; if (prev || prev === 0) return prev; return false; } return foldObj.parent; }, addToHistory(fold) { var maxSize = 10; if (!this.history) { this.history = []; } else if (this.history.length > maxSize) { this.history.shift(); } this.history.push(fold); }, getLastFromHistory() { if (!this.history) { return undefined; } return this.history.pop(); }, clearHistory() { if (!this.history) return; this.history.length = 0; }, // gets all folds at indentation level getLevel(level) { //console.log(arguments.callee.name); return this.foldLevels[level]; }, parse(editor) { //console.log(arguments.callee.name); if (!editor) return; // initialize this.iniSettings(); this.clearSearchModal(); this.foldNavigatorView.clearContent(); this.clearHistory(); this.lines2fold = []; this.folds = []; this.visibleFolds = []; this.foldObjects = {}; this.foldObjectsArray = []; // we need this because fuzzaldrin-plus not able to find things in objects only in arrays or I do not know how this.foldLevels = {}; var numberOfRows = editor.getLastBufferRow(); var html = ""; var currentFold = null; var temporarilyLastParent = []; //loop through the lines of the active editor for (var i = 0; numberOfRows > i; i++) { if (editor.isFoldableAtBufferRow(i)) { let indentLevel = editor.indentationForBufferRow(i); let indentHtml = ""; let lineNumberSpan = ""; let lineContent = ""; let lineContentTrimmed = ""; let classList = "fold-navigator-item"; let id = ""; let gutter = '<span class="fold-navigator-gutter"></span>'; let content = ''; let parent; // add this line to folds this.folds.push(i); // add this line to foldLevels if (!this.foldLevels.hasOwnProperty(indentLevel)) { this.foldLevels[indentLevel] = []; } this.foldLevels[indentLevel].push(i); // chop array down - it can not be larger than the current indentLevel temporarilyLastParent.length = parseInt(indentLevel); parent = 'root'; if (temporarilyLastParent[indentLevel - 1] || temporarilyLastParent[indentLevel - 1] === 0) parent = temporarilyLastParent[indentLevel - 1]; if (this.foldObjects[parent]) { this.foldObjects[parent]['children'].push(i); } this.foldObjects[i] = { line: i, children: [], parent: parent, indentation: indentLevel, content: '', }; //temporarilyLastParent temporarilyLastParent[indentLevel] = i; for (let j = 0; j < indentLevel; j++) { indentHtml += '<span class="fold-navigator-indentation">' + this.settings.indentationCharacter + '</span>'; } lineContent = editor.lineTextForBufferRow(i); lineContentTrimmed = lineContent.trim(); // check if the content of the string matches one of those values when the previous line's content should be used instead // see issue here https://github.com/turigeza/fold-navigator/issues/12 if(this.settings.whenMatchedUsePreviousLineArray && this.settings.whenMatchedUsePreviousLineArray.indexOf(lineContentTrimmed) !== -1){ //&& i !== 0 lineContent = editor.lineTextForBufferRow(i - 1); }else if (lineContentTrimmed.length < this.settings.minLineLength) { // check if the line is longer than the minimum in the settings if not grab the next line instead lineContent = editor.lineTextForBufferRow(i + 1); } // default it to string seems to return undefined sometimes most likely only when the first row is { if(!lineContent){ lineContent = ''; } // check if line is too long if (lineContent.length > this.settings.maxLineContentLength) { lineContent = lineContent.substring(0, this.settings.maxLineContentLength) + '...'; } /* maybe in the future we should check for lines which are too short and grab the next row */ if (this.settings.showLineNumbers) { lineNumberSpan = '<span class="fold-navigator-line-number ">' + (i + 1) + '</span>'; } id = 'fold-navigator-item-' + i; classList += ' fold-navigator-item-' + i; classList += ' fold-navigator-item-indent-' + indentLevel; // escape html // add content to navigator if (indentLevel <= this.settings.maxFoldLevel) { currentFold = i; content = document.createElement('div'); content.appendChild(document.createTextNode(lineContent)); html += '<div id="' + id + '" class="' + classList + '" data-row="' + i + '">' + gutter + lineNumberSpan + indentHtml + content.innerHTML + '</div>'; this.foldObjects[i]['content'] = lineContent.trim(); this.foldObjectsArray.push(this.foldObjects[i]); this.visibleFolds.push(i); } } // add this fold to the line2fold lookup array this.lines2fold[i] = currentFold; } this.foldNavigatorView.setContent(html); this.selectRow(editor.getCursorBufferPosition().row); }, /* called every time onCursorChange */ selectRow(row) { //console.log(arguments.callee.name); var fold = this.lines2fold[row]; var line = this.foldNavigatorView.selectFold(fold); // autoscroll navigator panel if ((line) && !this.wasItOnClick && this.settings.autoScrollFoldNavigatorPanel) { line.scrollIntoViewIfNeeded(false); if(this.settings.log){ console.log(line); } } if (line) { this.wasItOnClick = false; } }, // not yet used idea stolen from tree view resizeStarted() { document.onmousemove = () => { this.resizePanel() }; document.onmouseup = () => { this.resizeStopped() }; }, // not yet used idea stolen from tree view resizeStopped() { document.offmousemove = () => { this.resizePanel() }; document.offmouseup = () => { this.resizeStopped() }; }, // not yet used idea stolen from tree view resizePanel(d) { var pageX = d.pageX; var which = d.which; if (which !== 1) { return this.resizeStopped(); } }, toggle() { return (this.panel.isVisible() ? this.panel.hide() : this.panel.show()); }, open() { var editor = atom.workspace.getActiveTextEditor(); return this.panel.show(); }, close() { return this.panel.hide(); }, moveCursor(row, wasItOnClick = false) { //console.log(arguments.callee.name); this.wasItOnClick = wasItOnClick; // setCursorBufferPosition dies if row is string row = parseInt(row); var editor = atom.workspace.getActiveTextEditor(); if (!editor || row < 0) return; //editor.unfoldBufferRow(row); if (this.settings.keepFoldingAllTime && !wasItOnClick) { editor.foldAll(); } this.unfoldSubfolds(row); editor.setCursorBufferPosition([row, 0]); editor.scrollToCursorPosition({ center: true }); }, navigatorElementOnClick() { //console.log(arguments.callee.name); var element = this.foldNavigatorView.getElement(); element.onclick = (event) => { var clicked = null; var row; var editor = atom.workspace.getActiveTextEditor(); if (event.target.matches('.fold-navigator-item')) { clicked = event.target; } else if (event.target.matches('.fold-navigator-indentation') && event.target.parentNode && event.target.parentNode.matches('.fold-navigator-item')) { clicked = event.target.parentNode; } if (!clicked) return; row = clicked.dataset.row; //problem if (!row) return; if (editor && ((this.settings.keepFolding && !event.metaKey) || (!this.settings.keepFolding && event.metaKey))) { // fold all code before anything else sadly this triggers a lot of onDidChangeCursorPosition events editor.foldAll(); } this.moveCursor(row, true); }; }, foldActivePublic() { //console.log(arguments.callee.name); var fold = this.foldNavigatorView.getActiveFold(); var editor = atom.workspace.getActiveTextEditor(); if ((!fold && fold !== 0) || !editor) return; editor.foldBufferRow(fold); }, unfoldSubfoldsPublic() { //console.log(arguments.callee.name); this.unfoldSubfolds(false, false, true); }, unfoldSubfolds(row = false, editor = false, force = false) { //console.log(arguments.callee.name); var fold = (row || row === 0) ? row : this.foldNavigatorView.getActiveFold(); if (!fold && fold !== 0) return; var foldObj = this.foldObjects[fold]; var editor = editor ? editor : atom.workspace.getActiveTextEditor(); if (!foldObj || !editor) return; editor.unfoldBufferRow(fold); if (!this.settings.unfoldAllSubfolds && !force) return; if (foldObj.children.length > 0) { foldObj.children.forEach( (value) => { this.unfoldSubfolds(value, editor) } ); } }, toggleActiveFold() { //console.log(arguments.callee.name); var fold = this.foldNavigatorView.getActiveFold(); var editor = atom.workspace.getActiveTextEditor(); if ((!fold && fold !== 0) || !editor) return; if (editor.isFoldedAtBufferRow(fold)) { this.unfoldSubfolds(fold, editor, true); } else { editor.foldBufferRow(fold); } }, unfoldAtLevel(level) { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if ([1, 2, 3, 4, 5].indexOf(level) < 0) return; var lev = this.getLevel(level - 1); if (lev) { lev.forEach((fold) => { editor.unfoldBufferRow(fold); }); editor.scrollToCursorPosition({ center: true }); } }, foldAtLevel(level) { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if ([1, 2, 3, 4, 5].indexOf(level) < 0) return; var lev = this.getLevel(level - 1); if (lev) { lev.forEach((fold) => { editor.foldBufferRow(fold); }); editor.scrollToCursorPosition({ center: true }); } }, toggleFoldsLevel(level) { var editor = atom.workspace.getActiveTextEditor(); if (!editor) return; if ([1, 2, 3, 4, 5].indexOf(level) < 0) return; var lev = this.getLevel(level - 1); if (!lev) return; var first = lev[0]; if (!first && first !== 0) return; if (editor.isFoldedAtBufferRow(first)) { this.unfoldAtLevel(level); } else { this.foldAtLevel(level); } }, unfoldAtLevel1() { this.unfoldAtLevel(1); }, unfoldAtLevel2() { this.unfoldAtLevel(2); }, unfoldAtLevel3() { this.unfoldAtLevel(3); }, unfoldAtLevel4() { this.unfoldAtLevel(4); }, unfoldAtLevel5() { this.unfoldAtLevel(5); }, foldAtLevel1() { this.foldAtLevel(1); }, foldAtLevel2() { this.foldAtLevel(2); }, foldAtLevel3() { this.foldAtLevel(3); }, foldAtLevel4() { this.foldAtLevel(4); }, foldAtLevel5() { this.foldAtLevel(5); }, toggleFoldsLevel1() { this.toggleFoldsLevel(1); }, toggleFoldsLevel2() { this.toggleFoldsLevel(2); }, toggleFoldsLevel3() { this.toggleFoldsLevel(3); }, toggleFoldsLevel4() { this.toggleFoldsLevel(4); }, toggleFoldsLevel5() { this.toggleFoldsLevel(5); }, startTime() { this.time = new Date(); }, showTime(text) { console.log(text); console.log(new Date() - this.time); }, deactivate() { //console.log(arguments.callee.name); this.panel.destroy(); this.subscriptions.dispose(); this.foldNavigatorView.destroy(); if (this.onDidChangeCursorPositionSubscription) { this.onDidChangeCursorPositionSubscription.dispose(); } if (this.onDidStopChangingSubscription) { this.onDidStopChangingSubscription.dispose(); } //delete(this.searchModalElement); //delete(this.searchModalItems); //delete(this.searchModalInput); if (this.searchModal) { this.searchModal.destroy(); } }, /* we don't need this */ serialize() {} };
turigeza/fold-navigator
lib/fold-navigator.js
JavaScript
mit
41,379
/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */ 'use strict'; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); const vscode_1 = require("vscode"); const vscode_languageserver_protocol_1 = require("vscode-languageserver-protocol"); const c2p = require("./codeConverter"); const p2c = require("./protocolConverter"); const Is = require("./utils/is"); const async_1 = require("./utils/async"); const UUID = require("./utils/uuid"); const progressPart_1 = require("./progressPart"); __export(require("vscode-languageserver-protocol")); class ConsoleLogger { error(message) { console.error(message); } warn(message) { console.warn(message); } info(message) { console.info(message); } log(message) { console.log(message); } } function createConnection(input, output, errorHandler, closeHandler) { let logger = new ConsoleLogger(); let connection = vscode_languageserver_protocol_1.createProtocolConnection(input, output, logger); connection.onError((data) => { errorHandler(data[0], data[1], data[2]); }); connection.onClose(closeHandler); let result = { listen: () => connection.listen(), sendRequest: (type, ...params) => connection.sendRequest(Is.string(type) ? type : type.method, ...params), onRequest: (type, handler) => connection.onRequest(Is.string(type) ? type : type.method, handler), sendNotification: (type, params) => connection.sendNotification(Is.string(type) ? type : type.method, params), onNotification: (type, handler) => connection.onNotification(Is.string(type) ? type : type.method, handler), onProgress: connection.onProgress, sendProgress: connection.sendProgress, trace: (value, tracer, sendNotificationOrTraceOptions) => { const defaultTraceOptions = { sendNotification: false, traceFormat: vscode_languageserver_protocol_1.TraceFormat.Text }; if (sendNotificationOrTraceOptions === void 0) { connection.trace(value, tracer, defaultTraceOptions); } else if (Is.boolean(sendNotificationOrTraceOptions)) { connection.trace(value, tracer, sendNotificationOrTraceOptions); } else { connection.trace(value, tracer, sendNotificationOrTraceOptions); } }, initialize: (params) => connection.sendRequest(vscode_languageserver_protocol_1.InitializeRequest.type, params), shutdown: () => connection.sendRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, undefined), exit: () => connection.sendNotification(vscode_languageserver_protocol_1.ExitNotification.type), onLogMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, handler), onShowMessage: (handler) => connection.onNotification(vscode_languageserver_protocol_1.ShowMessageNotification.type, handler), onTelemetry: (handler) => connection.onNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, handler), didChangeConfiguration: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, params), didChangeWatchedFiles: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, params), didOpenTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, params), didChangeTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params), didCloseTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, params), didSaveTextDocument: (params) => connection.sendNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, params), onDiagnostics: (handler) => connection.onNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, handler), dispose: () => connection.dispose() }; return result; } /** * An action to be performed when the connection is producing errors. */ var ErrorAction; (function (ErrorAction) { /** * Continue running the server. */ ErrorAction[ErrorAction["Continue"] = 1] = "Continue"; /** * Shutdown the server. */ ErrorAction[ErrorAction["Shutdown"] = 2] = "Shutdown"; })(ErrorAction = exports.ErrorAction || (exports.ErrorAction = {})); /** * An action to be performed when the connection to a server got closed. */ var CloseAction; (function (CloseAction) { /** * Don't restart the server. The connection stays closed. */ CloseAction[CloseAction["DoNotRestart"] = 1] = "DoNotRestart"; /** * Restart the server. */ CloseAction[CloseAction["Restart"] = 2] = "Restart"; })(CloseAction = exports.CloseAction || (exports.CloseAction = {})); class DefaultErrorHandler { constructor(name) { this.name = name; this.restarts = []; } error(_error, _message, count) { if (count && count <= 3) { return ErrorAction.Continue; } return ErrorAction.Shutdown; } closed() { this.restarts.push(Date.now()); if (this.restarts.length < 5) { return CloseAction.Restart; } else { let diff = this.restarts[this.restarts.length - 1] - this.restarts[0]; if (diff <= 3 * 60 * 1000) { vscode_1.window.showErrorMessage(`The ${this.name} server crashed 5 times in the last 3 minutes. The server will not be restarted.`); return CloseAction.DoNotRestart; } else { this.restarts.shift(); return CloseAction.Restart; } } } } var RevealOutputChannelOn; (function (RevealOutputChannelOn) { RevealOutputChannelOn[RevealOutputChannelOn["Info"] = 1] = "Info"; RevealOutputChannelOn[RevealOutputChannelOn["Warn"] = 2] = "Warn"; RevealOutputChannelOn[RevealOutputChannelOn["Error"] = 3] = "Error"; RevealOutputChannelOn[RevealOutputChannelOn["Never"] = 4] = "Never"; })(RevealOutputChannelOn = exports.RevealOutputChannelOn || (exports.RevealOutputChannelOn = {})); var State; (function (State) { State[State["Stopped"] = 1] = "Stopped"; State[State["Starting"] = 3] = "Starting"; State[State["Running"] = 2] = "Running"; })(State = exports.State || (exports.State = {})); var ClientState; (function (ClientState) { ClientState[ClientState["Initial"] = 0] = "Initial"; ClientState[ClientState["Starting"] = 1] = "Starting"; ClientState[ClientState["StartFailed"] = 2] = "StartFailed"; ClientState[ClientState["Running"] = 3] = "Running"; ClientState[ClientState["Stopping"] = 4] = "Stopping"; ClientState[ClientState["Stopped"] = 5] = "Stopped"; })(ClientState || (ClientState = {})); const SupportedSymbolKinds = [ vscode_languageserver_protocol_1.SymbolKind.File, vscode_languageserver_protocol_1.SymbolKind.Module, vscode_languageserver_protocol_1.SymbolKind.Namespace, vscode_languageserver_protocol_1.SymbolKind.Package, vscode_languageserver_protocol_1.SymbolKind.Class, vscode_languageserver_protocol_1.SymbolKind.Method, vscode_languageserver_protocol_1.SymbolKind.Property, vscode_languageserver_protocol_1.SymbolKind.Field, vscode_languageserver_protocol_1.SymbolKind.Constructor, vscode_languageserver_protocol_1.SymbolKind.Enum, vscode_languageserver_protocol_1.SymbolKind.Interface, vscode_languageserver_protocol_1.SymbolKind.Function, vscode_languageserver_protocol_1.SymbolKind.Variable, vscode_languageserver_protocol_1.SymbolKind.Constant, vscode_languageserver_protocol_1.SymbolKind.String, vscode_languageserver_protocol_1.SymbolKind.Number, vscode_languageserver_protocol_1.SymbolKind.Boolean, vscode_languageserver_protocol_1.SymbolKind.Array, vscode_languageserver_protocol_1.SymbolKind.Object, vscode_languageserver_protocol_1.SymbolKind.Key, vscode_languageserver_protocol_1.SymbolKind.Null, vscode_languageserver_protocol_1.SymbolKind.EnumMember, vscode_languageserver_protocol_1.SymbolKind.Struct, vscode_languageserver_protocol_1.SymbolKind.Event, vscode_languageserver_protocol_1.SymbolKind.Operator, vscode_languageserver_protocol_1.SymbolKind.TypeParameter ]; const SupportedCompletionItemKinds = [ vscode_languageserver_protocol_1.CompletionItemKind.Text, vscode_languageserver_protocol_1.CompletionItemKind.Method, vscode_languageserver_protocol_1.CompletionItemKind.Function, vscode_languageserver_protocol_1.CompletionItemKind.Constructor, vscode_languageserver_protocol_1.CompletionItemKind.Field, vscode_languageserver_protocol_1.CompletionItemKind.Variable, vscode_languageserver_protocol_1.CompletionItemKind.Class, vscode_languageserver_protocol_1.CompletionItemKind.Interface, vscode_languageserver_protocol_1.CompletionItemKind.Module, vscode_languageserver_protocol_1.CompletionItemKind.Property, vscode_languageserver_protocol_1.CompletionItemKind.Unit, vscode_languageserver_protocol_1.CompletionItemKind.Value, vscode_languageserver_protocol_1.CompletionItemKind.Enum, vscode_languageserver_protocol_1.CompletionItemKind.Keyword, vscode_languageserver_protocol_1.CompletionItemKind.Snippet, vscode_languageserver_protocol_1.CompletionItemKind.Color, vscode_languageserver_protocol_1.CompletionItemKind.File, vscode_languageserver_protocol_1.CompletionItemKind.Reference, vscode_languageserver_protocol_1.CompletionItemKind.Folder, vscode_languageserver_protocol_1.CompletionItemKind.EnumMember, vscode_languageserver_protocol_1.CompletionItemKind.Constant, vscode_languageserver_protocol_1.CompletionItemKind.Struct, vscode_languageserver_protocol_1.CompletionItemKind.Event, vscode_languageserver_protocol_1.CompletionItemKind.Operator, vscode_languageserver_protocol_1.CompletionItemKind.TypeParameter ]; function ensure(target, key) { if (target[key] === void 0) { target[key] = {}; } return target[key]; } var DynamicFeature; (function (DynamicFeature) { function is(value) { let candidate = value; return candidate && Is.func(candidate.register) && Is.func(candidate.unregister) && Is.func(candidate.dispose) && candidate.messages !== void 0; } DynamicFeature.is = is; })(DynamicFeature || (DynamicFeature = {})); class DocumentNotifiactions { constructor(_client, _event, _type, _middleware, _createParams, _selectorFilter) { this._client = _client; this._event = _event; this._type = _type; this._middleware = _middleware; this._createParams = _createParams; this._selectorFilter = _selectorFilter; this._selectors = new Map(); } static textDocumentFilter(selectors, textDocument) { for (const selector of selectors) { if (vscode_1.languages.match(selector, textDocument)) { return true; } } return false; } register(_message, data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = this._event(this.callback, this); } this._selectors.set(data.id, data.registerOptions.documentSelector); } callback(data) { if (!this._selectorFilter || this._selectorFilter(this._selectors.values(), data)) { if (this._middleware) { this._middleware(data, (data) => this._client.sendNotification(this._type, this._createParams(data))); } else { this._client.sendNotification(this._type, this._createParams(data)); } this.notificationSent(data); } } notificationSent(_data) { } unregister(id) { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } getProvider(document) { for (const selector of this._selectors.values()) { if (vscode_1.languages.match(selector, document)) { return { send: (data) => { this.callback(data); } }; } } throw new Error(`No provider available for the given text document`); } } class DidOpenTextDocumentFeature extends DocumentNotifiactions { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidOpenTextDocument, vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, client.clientOptions.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get messages() { return vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(message, data) { super.register(message, data); if (!data.registerOptions.documentSelector) { return; } let documentSelector = data.registerOptions.documentSelector; vscode_1.workspace.textDocuments.forEach((textDocument) => { let uri = textDocument.uri.toString(); if (this._syncedDocuments.has(uri)) { return; } if (vscode_1.languages.match(documentSelector, textDocument)) { let middleware = this._client.clientOptions.middleware; let didOpen = (textDocument) => { this._client.sendNotification(this._type, this._createParams(textDocument)); }; if (middleware.didOpen) { middleware.didOpen(textDocument, didOpen); } else { didOpen(textDocument); } this._syncedDocuments.set(uri, textDocument); } }); } notificationSent(textDocument) { super.notificationSent(textDocument); this._syncedDocuments.set(textDocument.uri.toString(), textDocument); } } class DidCloseTextDocumentFeature extends DocumentNotifiactions { constructor(client, _syncedDocuments) { super(client, vscode_1.workspace.onDidCloseTextDocument, vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, client.clientOptions.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), DocumentNotifiactions.textDocumentFilter); this._syncedDocuments = _syncedDocuments; } get messages() { return vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } notificationSent(textDocument) { super.notificationSent(textDocument); this._syncedDocuments.delete(textDocument.uri.toString()); } unregister(id) { let selector = this._selectors.get(id); // The super call removed the selector from the map // of selectors. super.unregister(id); let selectors = this._selectors.values(); this._syncedDocuments.forEach((textDocument) => { if (vscode_1.languages.match(selector, textDocument) && !this._selectorFilter(selectors, textDocument)) { let middleware = this._client.clientOptions.middleware; let didClose = (textDocument) => { this._client.sendNotification(this._type, this._createParams(textDocument)); }; this._syncedDocuments.delete(textDocument.uri.toString()); if (middleware.didClose) { middleware.didClose(textDocument, didClose); } else { didClose(textDocument); } } }); } } class DidChangeTextDocumentFeature { constructor(_client) { this._client = _client; this._changeData = new Map(); this._forcingDelivery = false; } get messages() { return vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').dynamicRegistration = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== void 0 && textDocumentSyncOptions.change !== vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change }) }); } } register(_message, data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = vscode_1.workspace.onDidChangeTextDocument(this.callback, this); } this._changeData.set(data.id, { documentSelector: data.registerOptions.documentSelector, syncKind: data.registerOptions.syncKind }); } callback(event) { // Text document changes are send for dirty changes as well. We don't // have dirty / undirty events in the LSP so we ignore content changes // with length zero. if (event.contentChanges.length === 0) { return; } for (const changeData of this._changeData.values()) { if (vscode_1.languages.match(changeData.documentSelector, event.document)) { let middleware = this._client.clientOptions.middleware; if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental) { let params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event); if (middleware.didChange) { middleware.didChange(event, () => this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params)); } else { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, params); } } else if (changeData.syncKind === vscode_languageserver_protocol_1.TextDocumentSyncKind.Full) { let didChange = (event) => { if (this._changeDelayer) { if (this._changeDelayer.uri !== event.document.uri.toString()) { // Use this force delivery to track boolean state. Otherwise we might call two times. this.forceDelivery(); this._changeDelayer.uri = event.document.uri.toString(); } this._changeDelayer.delayer.trigger(() => { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document)); }); } else { this._changeDelayer = { uri: event.document.uri.toString(), delayer: new async_1.Delayer(200) }; this._changeDelayer.delayer.trigger(() => { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document)); }, -1); } }; if (middleware.didChange) { middleware.didChange(event, didChange); } else { didChange(event); } } } } } unregister(id) { this._changeData.delete(id); if (this._changeData.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._changeDelayer = undefined; this._forcingDelivery = false; this._changeData.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } forceDelivery() { if (this._forcingDelivery || !this._changeDelayer) { return; } try { this._forcingDelivery = true; this._changeDelayer.delayer.forceDelivery(); } finally { this._forcingDelivery = false; } } getProvider(document) { for (const changeData of this._changeData.values()) { if (vscode_1.languages.match(changeData.documentSelector, document)) { return { send: (event) => { this.callback(event); } }; } } throw new Error(`No provider available for the given text document`); } } class WillSaveFeature extends DocumentNotifiactions { constructor(client) { super(client, vscode_1.workspace.onWillSaveTextDocument, vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, client.clientOptions.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (selectors, willSaveEvent) => DocumentNotifiactions.textDocumentFilter(selectors, willSaveEvent.document)); } get messages() { return vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization'); value.willSave = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } } class WillSaveWaitUntilFeature { constructor(_client) { this._client = _client; this._selectors = new Map(); } get messages() { return vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type; } fillClientCapabilities(capabilities) { let value = ensure(ensure(capabilities, 'textDocument'), 'synchronization'); value.willSaveWaitUntil = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } register(_message, data) { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = vscode_1.workspace.onWillSaveTextDocument(this.callback, this); } this._selectors.set(data.id, data.registerOptions.documentSelector); } callback(event) { if (DocumentNotifiactions.textDocumentFilter(this._selectors.values(), event.document)) { let middleware = this._client.clientOptions.middleware; let willSaveWaitUntil = (event) => { return this._client.sendRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then((edits) => { let vEdits = this._client.protocol2CodeConverter.asTextEdits(edits); return vEdits === void 0 ? [] : vEdits; }); }; event.waitUntil(middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event)); } } unregister(id) { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } dispose() { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } } class DidSaveTextDocumentFeature extends DocumentNotifiactions { constructor(client) { super(client, vscode_1.workspace.onDidSaveTextDocument, vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, client.clientOptions.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), DocumentNotifiactions.textDocumentFilter); } get messages() { return vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'textDocument'), 'synchronization').didSave = true; } initialize(capabilities, documentSelector) { let textDocumentSyncOptions = capabilities.resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { includeText: !!textDocumentSyncOptions.save.includeText }) }); } } register(method, data) { this._includeText = !!data.registerOptions.includeText; super.register(method, data); } } class FileSystemWatcherFeature { constructor(_client, _notifyFileEvent) { this._client = _client; this._notifyFileEvent = _notifyFileEvent; this._watchers = new Map(); } get messages() { return vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeWatchedFiles').dynamicRegistration = true; } initialize(_capabilities, _documentSelector) { } register(_method, data) { if (!Array.isArray(data.registerOptions.watchers)) { return; } let disposeables = []; for (let watcher of data.registerOptions.watchers) { if (!Is.string(watcher.globPattern)) { continue; } let watchCreate = true, watchChange = true, watchDelete = true; if (watcher.kind !== void 0 && watcher.kind !== null) { watchCreate = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Create) !== 0; watchChange = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Change) !== 0; watchDelete = (watcher.kind & vscode_languageserver_protocol_1.WatchKind.Delete) !== 0; } let fileSystemWatcher = vscode_1.workspace.createFileSystemWatcher(watcher.globPattern, !watchCreate, !watchChange, !watchDelete); this.hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete); disposeables.push(fileSystemWatcher); } this._watchers.set(data.id, disposeables); } registerRaw(id, fileSystemWatchers) { let disposeables = []; for (let fileSystemWatcher of fileSystemWatchers) { this.hookListeners(fileSystemWatcher, true, true, true, disposeables); } this._watchers.set(id, disposeables); } hookListeners(fileSystemWatcher, watchCreate, watchChange, watchDelete, listeners) { if (watchCreate) { fileSystemWatcher.onDidCreate((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Created }), null, listeners); } if (watchChange) { fileSystemWatcher.onDidChange((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Changed }), null, listeners); } if (watchDelete) { fileSystemWatcher.onDidDelete((resource) => this._notifyFileEvent({ uri: this._client.code2ProtocolConverter.asUri(resource), type: vscode_languageserver_protocol_1.FileChangeType.Deleted }), null, listeners); } } unregister(id) { let disposeables = this._watchers.get(id); if (disposeables) { for (let disposable of disposeables) { disposable.dispose(); } } } dispose() { this._watchers.forEach((disposeables) => { for (let disposable of disposeables) { disposable.dispose(); } }); this._watchers.clear(); } } class TextDocumentFeature { constructor(_client, _message) { this._client = _client; this._message = _message; this._registrations = new Map(); } get messages() { return this._message; } register(message, data) { if (message.method !== this.messages.method) { throw new Error(`Register called on wrong feature. Requested ${message.method} but reached feature ${this.messages.method}`); } if (!data.registerOptions.documentSelector) { return; } let registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], data, provider: registration[1] }); } unregister(id) { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } dispose() { this._registrations.forEach((value) => { value.disposable.dispose(); }); this._registrations.clear(); } getRegistration(documentSelector, capability) { if (!capability) { return [undefined, undefined]; } else if (vscode_languageserver_protocol_1.TextDocumentRegistrationOptions.is(capability)) { const id = vscode_languageserver_protocol_1.StaticRegistrationOptions.hasId(capability) ? capability.id : UUID.generateUuid(); const selector = capability.documentSelector || documentSelector; if (selector) { return [id, Object.assign({}, capability, { documentSelector: selector })]; } } else if (Is.boolean(capability) && capability === true || vscode_languageserver_protocol_1.WorkDoneProgressOptions.is(capability)) { if (!documentSelector) { return [undefined, undefined]; } let options = (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })); return [UUID.generateUuid(), options]; } return [undefined, undefined]; } getRegistrationOptions(documentSelector, capability) { if (!documentSelector || !capability) { return undefined; } return (Is.boolean(capability) && capability === true ? { documentSelector } : Object.assign({}, capability, { documentSelector })); } getProvider(textDocument) { for (const registration of this._registrations.values()) { let selector = registration.data.registerOptions.documentSelector; if (selector !== null && vscode_1.languages.match(selector, textDocument)) { return registration.provider; } } throw new Error(`The feature has no registration for the provided text document ${textDocument.uri.toString()}`); } } exports.TextDocumentFeature = TextDocumentFeature; class WorkspaceFeature { constructor(_client, _message) { this._client = _client; this._message = _message; this._registrations = new Map(); } get messages() { return this._message; } register(message, data) { if (message.method !== this.messages.method) { throw new Error(`Register called on wron feature. Requested ${message.method} but reached feature ${this.messages.method}`); } const registration = this.registerLanguageProvider(data.registerOptions); this._registrations.set(data.id, { disposable: registration[0], provider: registration[1] }); } unregister(id) { let registration = this._registrations.get(id); if (registration !== undefined) { registration.disposable.dispose(); } } dispose() { this._registrations.forEach((registration) => { registration.disposable.dispose(); }); this._registrations.clear(); } getProviders() { const result = []; for (const registration of this._registrations.values()) { result.push(registration.provider); } return result; } } class CompletionItemFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CompletionRequest.type); } fillClientCapabilities(capabilites) { let completion = ensure(ensure(capabilites, 'textDocument'), 'completion'); completion.dynamicRegistration = true; completion.contextSupport = true; completion.completionItem = { snippetSupport: true, commitCharactersSupport: true, documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText], deprecatedSupport: true, preselectSupport: true, tagSupport: { valueSet: [vscode_languageserver_protocol_1.CompletionItemTag.Deprecated] } }; completion.completionItemKind = { valueSet: SupportedCompletionItemKinds }; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.completionProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const triggerCharacters = options.triggerCharacters || []; const provider = { provideCompletionItems: (document, position, token, context) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const provideCompletionItems = (document, position, context, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionRequest.type, client.code2ProtocolConverter.asCompletionParams(document, position, context), token).then(client.protocol2CodeConverter.asCompletionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CompletionRequest.type, error); return Promise.resolve([]); }); }; return middleware.provideCompletionItem ? middleware.provideCompletionItem(document, position, context, token, provideCompletionItems) : provideCompletionItems(document, position, context, token); }, resolveCompletionItem: options.resolveProvider ? (item, token) => { const client = this._client; const middleware = this._client.clientOptions.middleware; const resolveCompletionItem = (item, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, client.code2ProtocolConverter.asCompletionItem(item), token).then(client.protocol2CodeConverter.asCompletionItem, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, error); return Promise.resolve(item); }); }; return middleware.resolveCompletionItem ? middleware.resolveCompletionItem(item, token, resolveCompletionItem) : resolveCompletionItem(item, token); } : undefined }; return [vscode_1.languages.registerCompletionItemProvider(options.documentSelector, provider, ...triggerCharacters), provider]; } } class HoverFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.HoverRequest.type); } fillClientCapabilities(capabilites) { const hoverCapability = (ensure(ensure(capabilites, 'textDocument'), 'hover')); hoverCapability.dynamicRegistration = true; hoverCapability.contentFormat = [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText]; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.hoverProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideHover: (document, position, token) => { const client = this._client; const provideHover = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.HoverRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asHover, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.HoverRequest.type, error); return Promise.resolve(null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideHover ? middleware.provideHover(document, position, token, provideHover) : provideHover(document, position, token); } }; return [vscode_1.languages.registerHoverProvider(options.documentSelector, provider), provider]; } } class SignatureHelpFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.SignatureHelpRequest.type); } fillClientCapabilities(capabilites) { let config = ensure(ensure(capabilites, 'textDocument'), 'signatureHelp'); config.dynamicRegistration = true; config.signatureInformation = { documentationFormat: [vscode_languageserver_protocol_1.MarkupKind.Markdown, vscode_languageserver_protocol_1.MarkupKind.PlainText] }; config.signatureInformation.parameterInformation = { labelOffsetSupport: true }; config.contextSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.signatureHelpProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideSignatureHelp: (document, position, token, context) => { const client = this._client; const providerSignatureHelp = (document, position, context, token) => { return client.sendRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, client.code2ProtocolConverter.asSignatureHelpParams(document, position, context), token).then(client.protocol2CodeConverter.asSignatureHelp, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, error); return Promise.resolve(null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideSignatureHelp ? middleware.provideSignatureHelp(document, position, context, token, providerSignatureHelp) : providerSignatureHelp(document, position, context, token); } }; let disposable; if (options.retriggerCharacters === undefined) { const triggerCharacters = options.triggerCharacters || []; disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, ...triggerCharacters); } else { const metaData = { triggerCharacters: options.triggerCharacters || [], retriggerCharacters: options.retriggerCharacters || [] }; disposable = vscode_1.languages.registerSignatureHelpProvider(options.documentSelector, provider, metaData); } return [disposable, provider]; } } class DefinitionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DefinitionRequest.type); } fillClientCapabilities(capabilites) { let definitionSupport = ensure(ensure(capabilites, 'textDocument'), 'definition'); definitionSupport.dynamicRegistration = true; definitionSupport.linkSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.definitionProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDefinition: (document, position, token) => { const client = this._client; const provideDefinition = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDefinitionResult, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, error); return Promise.resolve(null); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDefinition ? middleware.provideDefinition(document, position, token, provideDefinition) : provideDefinition(document, position, token); } }; return [vscode_1.languages.registerDefinitionProvider(options.documentSelector, provider), provider]; } } class ReferencesFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.ReferencesRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'references').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.referencesProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideReferences: (document, position, options, token) => { const client = this._client; const _providerReferences = (document, position, options, token) => { return client.sendRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, client.code2ProtocolConverter.asReferenceParams(document, position, options), token).then(client.protocol2CodeConverter.asReferences, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideReferences ? middleware.provideReferences(document, position, options, token, _providerReferences) : _providerReferences(document, position, options, token); } }; return [vscode_1.languages.registerReferenceProvider(options.documentSelector, provider), provider]; } } class DocumentHighlightFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentHighlightRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'documentHighlight').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentHighlightProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentHighlights: (document, position, token) => { const client = this._client; const _provideDocumentHighlights = (document, position, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, client.code2ProtocolConverter.asTextDocumentPositionParams(document, position), token).then(client.protocol2CodeConverter.asDocumentHighlights, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentHighlights ? middleware.provideDocumentHighlights(document, position, token, _provideDocumentHighlights) : _provideDocumentHighlights(document, position, token); } }; return [vscode_1.languages.registerDocumentHighlightProvider(options.documentSelector, provider), provider]; } } class DocumentSymbolFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentSymbolRequest.type); } fillClientCapabilities(capabilites) { let symbolCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentSymbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; symbolCapabilities.hierarchicalDocumentSymbolSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentSymbolProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentSymbols: (document, token) => { const client = this._client; const _provideDocumentSymbols = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, client.code2ProtocolConverter.asDocumentSymbolParams(document), token).then((data) => { if (data === null) { return undefined; } if (data.length === 0) { return []; } else { let element = data[0]; if (vscode_languageserver_protocol_1.DocumentSymbol.is(element)) { return client.protocol2CodeConverter.asDocumentSymbols(data); } else { return client.protocol2CodeConverter.asSymbolInformations(data); } } }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentSymbols ? middleware.provideDocumentSymbols(document, token, _provideDocumentSymbols) : _provideDocumentSymbols(document, token); } }; return [vscode_1.languages.registerDocumentSymbolProvider(options.documentSelector, provider), provider]; } } class WorkspaceSymbolFeature extends WorkspaceFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type); } fillClientCapabilities(capabilites) { let symbolCapabilities = ensure(ensure(capabilites, 'workspace'), 'symbol'); symbolCapabilities.dynamicRegistration = true; symbolCapabilities.symbolKind = { valueSet: SupportedSymbolKinds }; } initialize(capabilities) { if (!capabilities.workspaceSymbolProvider) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: capabilities.workspaceSymbolProvider === true ? { workDoneProgress: false } : capabilities.workspaceSymbolProvider }); } registerLanguageProvider(_options) { const provider = { provideWorkspaceSymbols: (query, token) => { const client = this._client; const provideWorkspaceSymbols = (query, token) => { return client.sendRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, { query }, token).then(client.protocol2CodeConverter.asSymbolInformations, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideWorkspaceSymbols ? middleware.provideWorkspaceSymbols(query, token, provideWorkspaceSymbols) : provideWorkspaceSymbols(query, token); } }; return [vscode_1.languages.registerWorkspaceSymbolProvider(provider), provider]; } } class CodeActionFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeActionRequest.type); } fillClientCapabilities(capabilites) { const cap = ensure(ensure(capabilites, 'textDocument'), 'codeAction'); cap.dynamicRegistration = true; cap.isPreferredSupport = true; cap.codeActionLiteralSupport = { codeActionKind: { valueSet: [ vscode_languageserver_protocol_1.CodeActionKind.Empty, vscode_languageserver_protocol_1.CodeActionKind.QuickFix, vscode_languageserver_protocol_1.CodeActionKind.Refactor, vscode_languageserver_protocol_1.CodeActionKind.RefactorExtract, vscode_languageserver_protocol_1.CodeActionKind.RefactorInline, vscode_languageserver_protocol_1.CodeActionKind.RefactorRewrite, vscode_languageserver_protocol_1.CodeActionKind.Source, vscode_languageserver_protocol_1.CodeActionKind.SourceOrganizeImports ] } }; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.codeActionProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideCodeActions: (document, range, context, token) => { const client = this._client; const _provideCodeActions = (document, range, context, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), context: client.code2ProtocolConverter.asCodeActionContext(context) }; return client.sendRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, params, token).then((values) => { if (values === null) { return undefined; } const result = []; for (let item of values) { if (vscode_languageserver_protocol_1.Command.is(item)) { result.push(client.protocol2CodeConverter.asCommand(item)); } else { result.push(client.protocol2CodeConverter.asCodeAction(item)); } } return result; }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideCodeActions ? middleware.provideCodeActions(document, range, context, token, _provideCodeActions) : _provideCodeActions(document, range, context, token); } }; return [vscode_1.languages.registerCodeActionsProvider(options.documentSelector, provider, (options.codeActionKinds ? { providedCodeActionKinds: this._client.protocol2CodeConverter.asCodeActionKinds(options.codeActionKinds) } : undefined)), provider]; } } class CodeLensFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.CodeLensRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'codeLens').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.codeLensProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideCodeLenses: (document, token) => { const client = this._client; const provideCodeLenses = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, client.code2ProtocolConverter.asCodeLensParams(document), token).then(client.protocol2CodeConverter.asCodeLenses, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideCodeLenses ? middleware.provideCodeLenses(document, token, provideCodeLenses) : provideCodeLenses(document, token); }, resolveCodeLens: (options.resolveProvider) ? (codeLens, token) => { const client = this._client; const resolveCodeLens = (codeLens, token) => { return client.sendRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, client.code2ProtocolConverter.asCodeLens(codeLens), token).then(client.protocol2CodeConverter.asCodeLens, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, error); return codeLens; }); }; const middleware = client.clientOptions.middleware; return middleware.resolveCodeLens ? middleware.resolveCodeLens(codeLens, token, resolveCodeLens) : resolveCodeLens(codeLens, token); } : undefined }; return [vscode_1.languages.registerCodeLensProvider(options.documentSelector, provider), provider]; } } class DocumentFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'formatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentFormattingProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentFormattingEdits: (document, options, token) => { const client = this._client; const provideDocumentFormattingEdits = (document, options, token) => { const params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentFormattingEdits ? middleware.provideDocumentFormattingEdits(document, options, token, provideDocumentFormattingEdits) : provideDocumentFormattingEdits(document, options, token); } }; return [vscode_1.languages.registerDocumentFormattingEditProvider(options.documentSelector, provider), provider]; } } class DocumentRangeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'rangeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentRangeFormattingProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentRangeFormattingEdits: (document, range, options, token) => { const client = this._client; const provideDocumentRangeFormattingEdits = (document, range, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), range: client.code2ProtocolConverter.asRange(range), options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, error); return Promise.resolve([]); }); }; let middleware = client.clientOptions.middleware; return middleware.provideDocumentRangeFormattingEdits ? middleware.provideDocumentRangeFormattingEdits(document, range, options, token, provideDocumentRangeFormattingEdits) : provideDocumentRangeFormattingEdits(document, range, options, token); } }; return [vscode_1.languages.registerDocumentRangeFormattingEditProvider(options.documentSelector, provider), provider]; } } class DocumentOnTypeFormattingFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type); } fillClientCapabilities(capabilites) { ensure(ensure(capabilites, 'textDocument'), 'onTypeFormatting').dynamicRegistration = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentOnTypeFormattingProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideOnTypeFormattingEdits: (document, position, ch, options, token) => { const client = this._client; const provideOnTypeFormattingEdits = (document, position, ch, options, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), ch: ch, options: client.code2ProtocolConverter.asFormattingOptions(options) }; return client.sendRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, params, token).then(client.protocol2CodeConverter.asTextEdits, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideOnTypeFormattingEdits ? middleware.provideOnTypeFormattingEdits(document, position, ch, options, token, provideOnTypeFormattingEdits) : provideOnTypeFormattingEdits(document, position, ch, options, token); } }; const moreTriggerCharacter = options.moreTriggerCharacter || []; return [vscode_1.languages.registerOnTypeFormattingEditProvider(options.documentSelector, provider, options.firstTriggerCharacter, ...moreTriggerCharacter), provider]; } } class RenameFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.RenameRequest.type); } fillClientCapabilities(capabilites) { let rename = ensure(ensure(capabilites, 'textDocument'), 'rename'); rename.dynamicRegistration = true; rename.prepareSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.renameProvider); if (!options) { return; } if (Is.boolean(capabilities.renameProvider)) { options.prepareProvider = false; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideRenameEdits: (document, position, newName, token) => { const client = this._client; const provideRenameEdits = (document, position, newName, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), newName: newName }; return client.sendRequest(vscode_languageserver_protocol_1.RenameRequest.type, params, token).then(client.protocol2CodeConverter.asWorkspaceEdit, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.RenameRequest.type, error); return Promise.reject(new Error(error.message)); }); }; const middleware = client.clientOptions.middleware; return middleware.provideRenameEdits ? middleware.provideRenameEdits(document, position, newName, token, provideRenameEdits) : provideRenameEdits(document, position, newName, token); }, prepareRename: options.prepareProvider ? (document, position, token) => { const client = this._client; const prepareRename = (document, position, token) => { let params = { textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), position: client.code2ProtocolConverter.asPosition(position), }; return client.sendRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, params, token).then((result) => { if (vscode_languageserver_protocol_1.Range.is(result)) { return client.protocol2CodeConverter.asRange(result); } else if (result && vscode_languageserver_protocol_1.Range.is(result.range)) { return { range: client.protocol2CodeConverter.asRange(result.range), placeholder: result.placeholder }; } // To cancel the rename vscode API expects a rejected promise. return Promise.reject(new Error(`The element can't be renamed.`)); }, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, error); return Promise.reject(new Error(error.message)); }); }; const middleware = client.clientOptions.middleware; return middleware.prepareRename ? middleware.prepareRename(document, position, token, prepareRename) : prepareRename(document, position, token); } : undefined }; return [vscode_1.languages.registerRenameProvider(options.documentSelector, provider), provider]; } } class DocumentLinkFeature extends TextDocumentFeature { constructor(client) { super(client, vscode_languageserver_protocol_1.DocumentLinkRequest.type); } fillClientCapabilities(capabilites) { const documentLinkCapabilities = ensure(ensure(capabilites, 'textDocument'), 'documentLink'); documentLinkCapabilities.dynamicRegistration = true; documentLinkCapabilities.tooltipSupport = true; } initialize(capabilities, documentSelector) { const options = this.getRegistrationOptions(documentSelector, capabilities.documentLinkProvider); if (!options) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: options }); } registerLanguageProvider(options) { const provider = { provideDocumentLinks: (document, token) => { const client = this._client; const provideDocumentLinks = (document, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, client.code2ProtocolConverter.asDocumentLinkParams(document), token).then(client.protocol2CodeConverter.asDocumentLinks, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, error); return Promise.resolve([]); }); }; const middleware = client.clientOptions.middleware; return middleware.provideDocumentLinks ? middleware.provideDocumentLinks(document, token, provideDocumentLinks) : provideDocumentLinks(document, token); }, resolveDocumentLink: options.resolveProvider ? (link, token) => { const client = this._client; let resolveDocumentLink = (link, token) => { return client.sendRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, client.code2ProtocolConverter.asDocumentLink(link), token).then(client.protocol2CodeConverter.asDocumentLink, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, error); return Promise.resolve(link); }); }; const middleware = client.clientOptions.middleware; return middleware.resolveDocumentLink ? middleware.resolveDocumentLink(link, token, resolveDocumentLink) : resolveDocumentLink(link, token); } : undefined }; return [vscode_1.languages.registerDocumentLinkProvider(options.documentSelector, provider), provider]; } } class ConfigurationFeature { constructor(_client) { this._client = _client; this._listeners = new Map(); } get messages() { return vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'didChangeConfiguration').dynamicRegistration = true; } initialize() { let section = this._client.clientOptions.synchronize.configurationSection; if (section !== void 0) { this.register(this.messages, { id: UUID.generateUuid(), registerOptions: { section: section } }); } } register(_message, data) { let disposable = vscode_1.workspace.onDidChangeConfiguration((event) => { this.onDidChangeConfiguration(data.registerOptions.section, event); }); this._listeners.set(data.id, disposable); if (data.registerOptions.section !== void 0) { this.onDidChangeConfiguration(data.registerOptions.section, undefined); } } unregister(id) { let disposable = this._listeners.get(id); if (disposable) { this._listeners.delete(id); disposable.dispose(); } } dispose() { for (let disposable of this._listeners.values()) { disposable.dispose(); } this._listeners.clear(); } onDidChangeConfiguration(configurationSection, event) { let sections; if (Is.string(configurationSection)) { sections = [configurationSection]; } else { sections = configurationSection; } if (sections !== void 0 && event !== void 0) { let affected = sections.some((section) => event.affectsConfiguration(section)); if (!affected) { return; } } let didChangeConfiguration = (sections) => { if (sections === void 0) { this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: null }); return; } this._client.sendNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, { settings: this.extractSettingsInformation(sections) }); }; let middleware = this.getMiddleware(); middleware ? middleware(sections, didChangeConfiguration) : didChangeConfiguration(sections); } extractSettingsInformation(keys) { function ensurePath(config, path) { let current = config; for (let i = 0; i < path.length - 1; i++) { let obj = current[path[i]]; if (!obj) { obj = Object.create(null); current[path[i]] = obj; } current = obj; } return current; } let resource = this._client.clientOptions.workspaceFolder ? this._client.clientOptions.workspaceFolder.uri : undefined; let result = Object.create(null); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let index = key.indexOf('.'); let config = null; if (index >= 0) { config = vscode_1.workspace.getConfiguration(key.substr(0, index), resource).get(key.substr(index + 1)); } else { config = vscode_1.workspace.getConfiguration(key, resource); } if (config) { let path = keys[i].split('.'); ensurePath(result, path)[path[path.length - 1]] = config; } } return result; } getMiddleware() { let middleware = this._client.clientOptions.middleware; if (middleware.workspace && middleware.workspace.didChangeConfiguration) { return middleware.workspace.didChangeConfiguration; } else { return undefined; } } } class ExecuteCommandFeature { constructor(_client) { this._client = _client; this._commands = new Map(); } get messages() { return vscode_languageserver_protocol_1.ExecuteCommandRequest.type; } fillClientCapabilities(capabilities) { ensure(ensure(capabilities, 'workspace'), 'executeCommand').dynamicRegistration = true; } initialize(capabilities) { if (!capabilities.executeCommandProvider) { return; } this.register(this.messages, { id: UUID.generateUuid(), registerOptions: Object.assign({}, capabilities.executeCommandProvider) }); } register(_message, data) { const client = this._client; const middleware = client.clientOptions.middleware; const executeCommand = (command, args) => { let params = { command, arguments: args }; return client.sendRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, params).then(undefined, (error) => { client.logFailedRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, error); }); }; if (data.registerOptions.commands) { const disposeables = []; for (const command of data.registerOptions.commands) { disposeables.push(vscode_1.commands.registerCommand(command, (...args) => { return middleware.executeCommand ? middleware.executeCommand(command, args, executeCommand) : executeCommand(command, args); })); } this._commands.set(data.id, disposeables); } } unregister(id) { let disposeables = this._commands.get(id); if (disposeables) { disposeables.forEach(disposable => disposable.dispose()); } } dispose() { this._commands.forEach((value) => { value.forEach(disposable => disposable.dispose()); }); this._commands.clear(); } } var MessageTransports; (function (MessageTransports) { function is(value) { let candidate = value; return candidate && vscode_languageserver_protocol_1.MessageReader.is(value.reader) && vscode_languageserver_protocol_1.MessageWriter.is(value.writer); } MessageTransports.is = is; })(MessageTransports = exports.MessageTransports || (exports.MessageTransports = {})); class OnReady { constructor(_resolve, _reject) { this._resolve = _resolve; this._reject = _reject; this._used = false; } get isUsed() { return this._used; } resolve() { this._used = true; this._resolve(); } reject(error) { this._used = true; this._reject(error); } } class BaseLanguageClient { constructor(id, name, clientOptions) { this._traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; this._features = []; this._method2Message = new Map(); this._dynamicFeatures = new Map(); this._id = id; this._name = name; clientOptions = clientOptions || {}; this._clientOptions = { documentSelector: clientOptions.documentSelector || [], synchronize: clientOptions.synchronize || {}, diagnosticCollectionName: clientOptions.diagnosticCollectionName, outputChannelName: clientOptions.outputChannelName || this._name, revealOutputChannelOn: clientOptions.revealOutputChannelOn || RevealOutputChannelOn.Error, stdioEncoding: clientOptions.stdioEncoding || 'utf8', initializationOptions: clientOptions.initializationOptions, initializationFailedHandler: clientOptions.initializationFailedHandler, progressOnInitialization: !!clientOptions.progressOnInitialization, errorHandler: clientOptions.errorHandler || new DefaultErrorHandler(this._name), middleware: clientOptions.middleware || {}, uriConverters: clientOptions.uriConverters, workspaceFolder: clientOptions.workspaceFolder }; this._clientOptions.synchronize = this._clientOptions.synchronize || {}; this.state = ClientState.Initial; this._connectionPromise = undefined; this._resolvedConnection = undefined; this._initializeResult = undefined; if (clientOptions.outputChannel) { this._outputChannel = clientOptions.outputChannel; this._disposeOutputChannel = false; } else { this._outputChannel = undefined; this._disposeOutputChannel = true; } this._traceOutputChannel = clientOptions.traceOutputChannel; this._listeners = undefined; this._providers = undefined; this._diagnostics = undefined; this._fileEvents = []; this._fileEventDelayer = new async_1.Delayer(250); this._onReady = new Promise((resolve, reject) => { this._onReadyCallbacks = new OnReady(resolve, reject); }); this._onStop = undefined; this._telemetryEmitter = new vscode_languageserver_protocol_1.Emitter(); this._stateChangeEmitter = new vscode_languageserver_protocol_1.Emitter(); this._tracer = { log: (messageOrDataObject, data) => { if (Is.string(messageOrDataObject)) { this.logTrace(messageOrDataObject, data); } else { this.logObjectTrace(messageOrDataObject); } }, }; this._c2p = c2p.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.code2Protocol : undefined); this._p2c = p2c.createConverter(clientOptions.uriConverters ? clientOptions.uriConverters.protocol2Code : undefined); this._syncedDocuments = new Map(); this.registerBuiltinFeatures(); } get state() { return this._state; } set state(value) { let oldState = this.getPublicState(); this._state = value; let newState = this.getPublicState(); if (newState !== oldState) { this._stateChangeEmitter.fire({ oldState, newState }); } } getPublicState() { if (this.state === ClientState.Running) { return State.Running; } else if (this.state === ClientState.Starting) { return State.Starting; } else { return State.Stopped; } } get initializeResult() { return this._initializeResult; } sendRequest(type, ...params) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { return this._resolvedConnection.sendRequest(type, ...params); } catch (error) { this.error(`Sending request ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onRequest(type, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { this._resolvedConnection.onRequest(type, handler); } catch (error) { this.error(`Registering request handler ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } sendNotification(type, params) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { this._resolvedConnection.sendNotification(type, params); } catch (error) { this.error(`Sending notification ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onNotification(type, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { this._resolvedConnection.onNotification(type, handler); } catch (error) { this.error(`Registering notification handler ${Is.string(type) ? type : type.method} failed.`, error); throw error; } } onProgress(type, token, handler) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } try { return this._resolvedConnection.onProgress(type, token, handler); } catch (error) { this.error(`Registering progress handler for token ${token} failed.`, error); throw error; } } sendProgress(type, token, value) { if (!this.isConnectionActive()) { throw new Error('Language client is not ready yet'); } this.forceDocumentSync(); try { this._resolvedConnection.sendProgress(type, token, value); } catch (error) { this.error(`Sending progress for token ${token} failed.`, error); throw error; } } get clientOptions() { return this._clientOptions; } get protocol2CodeConverter() { return this._p2c; } get code2ProtocolConverter() { return this._c2p; } get onTelemetry() { return this._telemetryEmitter.event; } get onDidChangeState() { return this._stateChangeEmitter.event; } get outputChannel() { if (!this._outputChannel) { this._outputChannel = vscode_1.window.createOutputChannel(this._clientOptions.outputChannelName ? this._clientOptions.outputChannelName : this._name); } return this._outputChannel; } get traceOutputChannel() { if (this._traceOutputChannel) { return this._traceOutputChannel; } return this.outputChannel; } get diagnostics() { return this._diagnostics; } createDefaultErrorHandler() { return new DefaultErrorHandler(this._name); } set trace(value) { this._trace = value; this.onReady().then(() => { this.resolveConnection().then((connection) => { connection.trace(this._trace, this._tracer, { sendNotification: false, traceFormat: this._traceFormat }); }); }, () => { }); } data2String(data) { if (data instanceof vscode_languageserver_protocol_1.ResponseError) { const responseError = data; return ` Message: ${responseError.message}\n Code: ${responseError.code} ${responseError.data ? '\n' + responseError.data.toString() : ''}`; } if (data instanceof Error) { if (Is.string(data.stack)) { return data.stack; } return data.message; } if (Is.string(data)) { return data; } return data.toString(); } info(message, data) { this.outputChannel.appendLine(`[Info - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Info) { this.showNotificationMessage(); } } warn(message, data) { this.outputChannel.appendLine(`[Warn - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Warn) { this.showNotificationMessage(); } } error(message, data) { this.outputChannel.appendLine(`[Error - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.outputChannel.appendLine(this.data2String(data)); } if (this._clientOptions.revealOutputChannelOn <= RevealOutputChannelOn.Error) { this.showNotificationMessage(); } } showNotificationMessage() { vscode_1.window.showInformationMessage('A request has failed. See the output for more information.', 'Go to output').then(() => { this.outputChannel.show(true); }); } logTrace(message, data) { this.traceOutputChannel.appendLine(`[Trace - ${(new Date().toLocaleTimeString())}] ${message}`); if (data) { this.traceOutputChannel.appendLine(this.data2String(data)); } } logObjectTrace(data) { if (data.isLSPMessage && data.type) { this.traceOutputChannel.append(`[LSP - ${(new Date().toLocaleTimeString())}] `); } else { this.traceOutputChannel.append(`[Trace - ${(new Date().toLocaleTimeString())}] `); } if (data) { this.traceOutputChannel.appendLine(`${JSON.stringify(data)}`); } } needsStart() { return this.state === ClientState.Initial || this.state === ClientState.Stopping || this.state === ClientState.Stopped; } needsStop() { return this.state === ClientState.Starting || this.state === ClientState.Running; } onReady() { return this._onReady; } isConnectionActive() { return this.state === ClientState.Running && !!this._resolvedConnection; } start() { if (this._onReadyCallbacks.isUsed) { this._onReady = new Promise((resolve, reject) => { this._onReadyCallbacks = new OnReady(resolve, reject); }); } this._listeners = []; this._providers = []; // If we restart then the diagnostics collection is reused. if (!this._diagnostics) { this._diagnostics = this._clientOptions.diagnosticCollectionName ? vscode_1.languages.createDiagnosticCollection(this._clientOptions.diagnosticCollectionName) : vscode_1.languages.createDiagnosticCollection(); } this.state = ClientState.Starting; this.resolveConnection().then((connection) => { connection.onLogMessage((message) => { switch (message.type) { case vscode_languageserver_protocol_1.MessageType.Error: this.error(message.message); break; case vscode_languageserver_protocol_1.MessageType.Warning: this.warn(message.message); break; case vscode_languageserver_protocol_1.MessageType.Info: this.info(message.message); break; default: this.outputChannel.appendLine(message.message); } }); connection.onShowMessage((message) => { switch (message.type) { case vscode_languageserver_protocol_1.MessageType.Error: vscode_1.window.showErrorMessage(message.message); break; case vscode_languageserver_protocol_1.MessageType.Warning: vscode_1.window.showWarningMessage(message.message); break; case vscode_languageserver_protocol_1.MessageType.Info: vscode_1.window.showInformationMessage(message.message); break; default: vscode_1.window.showInformationMessage(message.message); } }); connection.onRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, (params) => { let messageFunc; switch (params.type) { case vscode_languageserver_protocol_1.MessageType.Error: messageFunc = vscode_1.window.showErrorMessage; break; case vscode_languageserver_protocol_1.MessageType.Warning: messageFunc = vscode_1.window.showWarningMessage; break; case vscode_languageserver_protocol_1.MessageType.Info: messageFunc = vscode_1.window.showInformationMessage; break; default: messageFunc = vscode_1.window.showInformationMessage; } let actions = params.actions || []; return messageFunc(params.message, ...actions); }); connection.onTelemetry((data) => { this._telemetryEmitter.fire(data); }); connection.listen(); // Error is handled in the initialize call. return this.initialize(connection); }).then(undefined, (error) => { this.state = ClientState.StartFailed; this._onReadyCallbacks.reject(error); this.error('Starting client failed', error); vscode_1.window.showErrorMessage(`Couldn't start client ${this._name}`); }); return new vscode_1.Disposable(() => { if (this.needsStop()) { this.stop(); } }); } resolveConnection() { if (!this._connectionPromise) { this._connectionPromise = this.createConnection(); } return this._connectionPromise; } initialize(connection) { this.refreshTrace(connection, false); let initOption = this._clientOptions.initializationOptions; let rootPath = this._clientOptions.workspaceFolder ? this._clientOptions.workspaceFolder.uri.fsPath : this._clientGetRootPath(); let initParams = { processId: process.pid, clientInfo: { name: 'vscode', version: vscode_1.version }, rootPath: rootPath ? rootPath : null, rootUri: rootPath ? this._c2p.asUri(vscode_1.Uri.file(rootPath)) : null, capabilities: this.computeClientCapabilities(), initializationOptions: Is.func(initOption) ? initOption() : initOption, trace: vscode_languageserver_protocol_1.Trace.toString(this._trace), workspaceFolders: null }; this.fillInitializeParams(initParams); if (this._clientOptions.progressOnInitialization) { const token = UUID.generateUuid(); const part = new progressPart_1.ProgressPart(connection, token); initParams.workDoneToken = token; return this.doInitialize(connection, initParams).then((result) => { part.done(); return result; }, (error) => { part.cancel(); throw error; }); } else { return this.doInitialize(connection, initParams); } } doInitialize(connection, initParams) { return connection.initialize(initParams).then((result) => { this._resolvedConnection = connection; this._initializeResult = result; this.state = ClientState.Running; let textDocumentSyncOptions = undefined; if (Is.number(result.capabilities.textDocumentSync)) { if (result.capabilities.textDocumentSync === vscode_languageserver_protocol_1.TextDocumentSyncKind.None) { textDocumentSyncOptions = { openClose: false, change: vscode_languageserver_protocol_1.TextDocumentSyncKind.None, save: undefined }; } else { textDocumentSyncOptions = { openClose: true, change: result.capabilities.textDocumentSync, save: { includeText: false } }; } } else if (result.capabilities.textDocumentSync !== void 0 && result.capabilities.textDocumentSync !== null) { textDocumentSyncOptions = result.capabilities.textDocumentSync; } this._capabilities = Object.assign({}, result.capabilities, { resolvedTextDocumentSync: textDocumentSyncOptions }); connection.onDiagnostics(params => this.handleDiagnostics(params)); connection.onRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params => this.handleRegistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/registerFeature', params => this.handleRegistrationRequest(params)); connection.onRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params => this.handleUnregistrationRequest(params)); // See https://github.com/Microsoft/vscode-languageserver-node/issues/199 connection.onRequest('client/unregisterFeature', params => this.handleUnregistrationRequest(params)); connection.onRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params => this.handleApplyWorkspaceEdit(params)); connection.sendNotification(vscode_languageserver_protocol_1.InitializedNotification.type, {}); this.hookFileEvents(connection); this.hookConfigurationChanged(connection); this.initializeFeatures(connection); this._onReadyCallbacks.resolve(); return result; }).then(undefined, (error) => { if (this._clientOptions.initializationFailedHandler) { if (this._clientOptions.initializationFailedHandler(error)) { this.initialize(connection); } else { this.stop(); this._onReadyCallbacks.reject(error); } } else if (error instanceof vscode_languageserver_protocol_1.ResponseError && error.data && error.data.retry) { vscode_1.window.showErrorMessage(error.message, { title: 'Retry', id: 'retry' }).then(item => { if (item && item.id === 'retry') { this.initialize(connection); } else { this.stop(); this._onReadyCallbacks.reject(error); } }); } else { if (error && error.message) { vscode_1.window.showErrorMessage(error.message); } this.error('Server initialization failed.', error); this.stop(); this._onReadyCallbacks.reject(error); } throw error; }); } _clientGetRootPath() { let folders = vscode_1.workspace.workspaceFolders; if (!folders || folders.length === 0) { return undefined; } let folder = folders[0]; if (folder.uri.scheme === 'file') { return folder.uri.fsPath; } return undefined; } stop() { this._initializeResult = undefined; if (!this._connectionPromise) { this.state = ClientState.Stopped; return Promise.resolve(); } if (this.state === ClientState.Stopping && this._onStop) { return this._onStop; } this.state = ClientState.Stopping; this.cleanUp(false); // unhook listeners return this._onStop = this.resolveConnection().then(connection => { return connection.shutdown().then(() => { connection.exit(); connection.dispose(); this.state = ClientState.Stopped; this.cleanUpChannel(); this._onStop = undefined; this._connectionPromise = undefined; this._resolvedConnection = undefined; }); }); } cleanUp(channel = true, diagnostics = true) { if (this._listeners) { this._listeners.forEach(listener => listener.dispose()); this._listeners = undefined; } if (this._providers) { this._providers.forEach(provider => provider.dispose()); this._providers = undefined; } if (this._syncedDocuments) { this._syncedDocuments.clear(); } for (let handler of this._dynamicFeatures.values()) { handler.dispose(); } if (channel) { this.cleanUpChannel(); } if (diagnostics && this._diagnostics) { this._diagnostics.dispose(); this._diagnostics = undefined; } } cleanUpChannel() { if (this._outputChannel && this._disposeOutputChannel) { this._outputChannel.dispose(); this._outputChannel = undefined; } } notifyFileEvent(event) { var _a; const client = this; function didChangeWatchedFile(event) { client._fileEvents.push(event); client._fileEventDelayer.trigger(() => { client.onReady().then(() => { client.resolveConnection().then(connection => { if (client.isConnectionActive()) { client.forceDocumentSync(); connection.didChangeWatchedFiles({ changes: client._fileEvents }); } client._fileEvents = []; }); }, (error) => { client.error(`Notify file events failed.`, error); }); }); } const workSpaceMiddleware = (_a = this.clientOptions.middleware) === null || _a === void 0 ? void 0 : _a.workspace; (workSpaceMiddleware === null || workSpaceMiddleware === void 0 ? void 0 : workSpaceMiddleware.didChangeWatchedFile) ? workSpaceMiddleware.didChangeWatchedFile(event, didChangeWatchedFile) : didChangeWatchedFile(event); } forceDocumentSync() { this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type.method).forceDelivery(); } handleDiagnostics(params) { if (!this._diagnostics) { return; } let uri = this._p2c.asUri(params.uri); let diagnostics = this._p2c.asDiagnostics(params.diagnostics); let middleware = this.clientOptions.middleware; if (middleware.handleDiagnostics) { middleware.handleDiagnostics(uri, diagnostics, (uri, diagnostics) => this.setDiagnostics(uri, diagnostics)); } else { this.setDiagnostics(uri, diagnostics); } } setDiagnostics(uri, diagnostics) { if (!this._diagnostics) { return; } this._diagnostics.set(uri, diagnostics); } createConnection() { let errorHandler = (error, message, count) => { this.handleConnectionError(error, message, count); }; let closeHandler = () => { this.handleConnectionClosed(); }; return this.createMessageTransports(this._clientOptions.stdioEncoding || 'utf8').then((transports) => { return createConnection(transports.reader, transports.writer, errorHandler, closeHandler); }); } handleConnectionClosed() { // Check whether this is a normal shutdown in progress or the client stopped normally. if (this.state === ClientState.Stopping || this.state === ClientState.Stopped) { return; } try { if (this._resolvedConnection) { this._resolvedConnection.dispose(); } } catch (error) { // Disposing a connection could fail if error cases. } let action = CloseAction.DoNotRestart; try { action = this._clientOptions.errorHandler.closed(); } catch (error) { // Ignore errors coming from the error handler. } this._connectionPromise = undefined; this._resolvedConnection = undefined; if (action === CloseAction.DoNotRestart) { this.error('Connection to server got closed. Server will not be restarted.'); this.state = ClientState.Stopped; this.cleanUp(false, true); } else if (action === CloseAction.Restart) { this.info('Connection to server got closed. Server will restart.'); this.cleanUp(false, false); this.state = ClientState.Initial; this.start(); } } handleConnectionError(error, message, count) { let action = this._clientOptions.errorHandler.error(error, message, count); if (action === ErrorAction.Shutdown) { this.error('Connection to server is erroring. Shutting down server.'); this.stop(); } } hookConfigurationChanged(connection) { vscode_1.workspace.onDidChangeConfiguration(() => { this.refreshTrace(connection, true); }); } refreshTrace(connection, sendNotification = false) { let config = vscode_1.workspace.getConfiguration(this._id); let trace = vscode_languageserver_protocol_1.Trace.Off; let traceFormat = vscode_languageserver_protocol_1.TraceFormat.Text; if (config) { const traceConfig = config.get('trace.server', 'off'); if (typeof traceConfig === 'string') { trace = vscode_languageserver_protocol_1.Trace.fromString(traceConfig); } else { trace = vscode_languageserver_protocol_1.Trace.fromString(config.get('trace.server.verbosity', 'off')); traceFormat = vscode_languageserver_protocol_1.TraceFormat.fromString(config.get('trace.server.format', 'text')); } } this._trace = trace; this._traceFormat = traceFormat; connection.trace(this._trace, this._tracer, { sendNotification, traceFormat: this._traceFormat }); } hookFileEvents(_connection) { let fileEvents = this._clientOptions.synchronize.fileEvents; if (!fileEvents) { return; } let watchers; if (Is.array(fileEvents)) { watchers = fileEvents; } else { watchers = [fileEvents]; } if (!watchers) { return; } this._dynamicFeatures.get(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type.method).registerRaw(UUID.generateUuid(), watchers); } registerFeatures(features) { for (let feature of features) { this.registerFeature(feature); } } registerFeature(feature) { this._features.push(feature); if (DynamicFeature.is(feature)) { let messages = feature.messages; if (Array.isArray(messages)) { for (let message of messages) { this._method2Message.set(message.method, message); this._dynamicFeatures.set(message.method, feature); } } else { this._method2Message.set(messages.method, messages); this._dynamicFeatures.set(messages.method, feature); } } } getFeature(request) { return this._dynamicFeatures.get(request); } registerBuiltinFeatures() { this.registerFeature(new ConfigurationFeature(this)); this.registerFeature(new DidOpenTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new DidChangeTextDocumentFeature(this)); this.registerFeature(new WillSaveFeature(this)); this.registerFeature(new WillSaveWaitUntilFeature(this)); this.registerFeature(new DidSaveTextDocumentFeature(this)); this.registerFeature(new DidCloseTextDocumentFeature(this, this._syncedDocuments)); this.registerFeature(new FileSystemWatcherFeature(this, (event) => this.notifyFileEvent(event))); this.registerFeature(new CompletionItemFeature(this)); this.registerFeature(new HoverFeature(this)); this.registerFeature(new SignatureHelpFeature(this)); this.registerFeature(new DefinitionFeature(this)); this.registerFeature(new ReferencesFeature(this)); this.registerFeature(new DocumentHighlightFeature(this)); this.registerFeature(new DocumentSymbolFeature(this)); this.registerFeature(new WorkspaceSymbolFeature(this)); this.registerFeature(new CodeActionFeature(this)); this.registerFeature(new CodeLensFeature(this)); this.registerFeature(new DocumentFormattingFeature(this)); this.registerFeature(new DocumentRangeFormattingFeature(this)); this.registerFeature(new DocumentOnTypeFormattingFeature(this)); this.registerFeature(new RenameFeature(this)); this.registerFeature(new DocumentLinkFeature(this)); this.registerFeature(new ExecuteCommandFeature(this)); } fillInitializeParams(params) { for (let feature of this._features) { if (Is.func(feature.fillInitializeParams)) { feature.fillInitializeParams(params); } } } computeClientCapabilities() { let result = {}; ensure(result, 'workspace').applyEdit = true; let workspaceEdit = ensure(ensure(result, 'workspace'), 'workspaceEdit'); workspaceEdit.documentChanges = true; workspaceEdit.resourceOperations = [vscode_languageserver_protocol_1.ResourceOperationKind.Create, vscode_languageserver_protocol_1.ResourceOperationKind.Rename, vscode_languageserver_protocol_1.ResourceOperationKind.Delete]; workspaceEdit.failureHandling = vscode_languageserver_protocol_1.FailureHandlingKind.TextOnlyTransactional; let diagnostics = ensure(ensure(result, 'textDocument'), 'publishDiagnostics'); diagnostics.relatedInformation = true; diagnostics.versionSupport = false; diagnostics.tagSupport = { valueSet: [vscode_languageserver_protocol_1.DiagnosticTag.Unnecessary, vscode_languageserver_protocol_1.DiagnosticTag.Deprecated] }; for (let feature of this._features) { feature.fillClientCapabilities(result); } return result; } initializeFeatures(_connection) { let documentSelector = this._clientOptions.documentSelector; for (let feature of this._features) { feature.initialize(this._capabilities, documentSelector); } } handleRegistrationRequest(params) { return new Promise((resolve, reject) => { for (let registration of params.registrations) { const feature = this._dynamicFeatures.get(registration.method); if (!feature) { reject(new Error(`No feature implementation for ${registration.method} found. Registration failed.`)); return; } const options = registration.registerOptions || {}; options.documentSelector = options.documentSelector || this._clientOptions.documentSelector; const data = { id: registration.id, registerOptions: options }; feature.register(this._method2Message.get(registration.method), data); } resolve(); }); } handleUnregistrationRequest(params) { return new Promise((resolve, reject) => { for (let unregistration of params.unregisterations) { const feature = this._dynamicFeatures.get(unregistration.method); if (!feature) { reject(new Error(`No feature implementation for ${unregistration.method} found. Unregistration failed.`)); return; } feature.unregister(unregistration.id); } resolve(); }); } handleApplyWorkspaceEdit(params) { // This is some sort of workaround since the version check should be done by VS Code in the Workspace.applyEdit. // However doing it here adds some safety since the server can lag more behind then an extension. let workspaceEdit = params.edit; let openTextDocuments = new Map(); vscode_1.workspace.textDocuments.forEach((document) => openTextDocuments.set(document.uri.toString(), document)); let versionMismatch = false; if (workspaceEdit.documentChanges) { for (const change of workspaceEdit.documentChanges) { if (vscode_languageserver_protocol_1.TextDocumentEdit.is(change) && change.textDocument.version && change.textDocument.version >= 0) { let textDocument = openTextDocuments.get(change.textDocument.uri); if (textDocument && textDocument.version !== change.textDocument.version) { versionMismatch = true; break; } } } } if (versionMismatch) { return Promise.resolve({ applied: false }); } return Is.asPromise(vscode_1.workspace.applyEdit(this._p2c.asWorkspaceEdit(params.edit)).then((value) => { return { applied: value }; })); } logFailedRequest(type, error) { // If we get a request cancel or a content modified don't log anything. if (error instanceof vscode_languageserver_protocol_1.ResponseError && (error.code === vscode_languageserver_protocol_1.ErrorCodes.RequestCancelled || error.code === vscode_languageserver_protocol_1.ErrorCodes.ContentModified)) { return; } this.error(`Request ${type.method} failed.`, error); } } exports.BaseLanguageClient = BaseLanguageClient;
karan/dotfiles
.vscode/extensions/ms-vscode.go-0.14.1/node_modules/vscode-languageclient/lib/client.js
JavaScript
mit
119,699
Marker = function({ settings, rad }) { const long = settings.longMarker ? 'protractor-extension-marker-long' : ""; this.theta = rad - Math.PI / 2; this.phi = settings.phi; this.settings = settings; this.node = document.createElement('div'); this.node.className = `protractor-extension-marker ${long}`; this.node.style.borderBottom = `20px solid ${settings.markerFill}`; PubSub.subscribe(Channels.MOVE_CONTAINER, this); PubSub.subscribe(Channels.MOVE_HANDLE_ROTATE, this); return this.node; }; Marker.prototype = { onRotate: function(msg) { this.rotation += msg.phi; }, onUpdate: function(chan, msg) { switch(chan) { case Channels.MOVE_CONTAINER: this.onMoveContainer(msg); break; case Channels.MOVE_HANDLE_ROTATE: this.onMoveHandleRotate(msg); break; } }, onMoveContainer: function(msg) { this.node.style.height = `${msg.radius + 10}px`; if (this.settings.longMarker) { const rgba = this.settings.markerFill.replace('1)', '0.4)'); this.node.style.borderTop = `${msg.radius - 10}px solid ${rgba}`; } this.transform(); }, onMoveHandleRotate: function(msg) { this.phi = msg.phi; this.transform(); }, transform: function() { this.node.style.transform = `rotate(${this.theta + this.phi}rad)`; }, setMode: function() { this.node.className = (msg.mode === "lock" ? 'protractor-extension-marker protractor-extension-marker-locked' : 'protractor-extension-marker'); }, };
ben-burlingham/protractor
public/scripts/marker.js
JavaScript
mit
1,607
"use strict"; import React from 'react' import Course from '../partials/Course.js' import Modal from '../partials/Modal.js' import MetricModal from '../partials/MetricModal.js' export default class Courses extends React.Component { constructor(props) { super(props); this.state = { course: props.course, sections: props.course.sections, showModal: false, showMetricModal: false, modalInfo: { modalType: "ADD_QUIZ", title: "Add Quiz" } }; } componentDidMount() { this.getCoursesAndSections(this.state.course.id); } componentWillReceiveProps(newProps) { if(newProps.course != undefined) { this.getCoursesAndSections(newProps.course.id); } } getCoursesAndSections(courseId) { if(courseId == -1) return; var me = this; $.when( $.post("/course/find", {id: courseId}), $.post("/section/find", {course: courseId}) ).then(function(course, sections) { console.log("course", course[0]); console.log("sections", sections[0]); if(course == undefined) return; // if there are no courses, then there are no sections me.setState({ course: course[0], sections: sections[0] }); }); } closeModal() { this.setState({ showModal: false, showMetricModal: false }); } showMetricModal(quiz) { console.log("showMetricModal!", quiz); var modalInfo = this.state.modalInfo; modalInfo.title = quiz.title; this.setState({ showModal: false, showMetricModal: true, modalInfo: modalInfo }); } showCourseModal() { var modalInfo = this.state.modalInfo; modalInfo.modalType = "ADD_COURSE"; modalInfo.title = "Add Course or Section"; this.setState({ showModal: true, showMetricModal: false, modalInfo: modalInfo }); } showQuizModal(quizIndex) { var modalInfo = this.state.modalInfo; modalInfo.title = "Add Quiz"; modalInfo.modalType = "ADD_QUIZ"; modalInfo.quizIndex = quizIndex; this.setState({ showModal: true, showMetricModal: false, modalInfo: modalInfo }); } showQuizInModal(quizIndex) { console.log("showQuizInModal::quizIndex", quizIndex); this.showQuizModal(quizIndex); } showStudentsModal(section) { var modalInfo = this.state.modalInfo; modalInfo.modalType = "ADD_STUDENTS"; modalInfo.title = "Add Students"; modalInfo.section = section; this.setState({ showModal: true, showMetricModal: false, modalInfo: modalInfo }); } addQuizToCourse(quiz, quizIndex) { console.log("Adding quiz '" + quiz.title + "' in course " + this.props.course.title); var me = this; if(quizIndex > -1) { $.post('/quiz/update/' + quiz.id, { title: quiz.title }) .then(function(quiz) { console.log(quiz); var course = me.state.course; course.quizzes[quizIndex] = quiz; me.setState({course: course}); me.closeModal(); }); } else { $.post('/quiz/create/', { title: quiz.title, course: me.props.course.id } ) .then(function(quiz) { console.log(quiz); var course = me.state.course; course.quizzes.push(quiz); me.setState({course: course}); me.closeModal(); }); } } addSectionToCourse(section) { var me = this; if(section.title == '') { return; } $.post('/section/create/', { title: section.title, course: me.state.course.id }) .then(function(section) { console.log("created section", section); var sections = me.state.sections; sections.push(section); me.setState({sections: sections}); me.closeModal(); }); } addCourseToProfessor(course, term) { var me = this; this.props.addCourseToProfessor(course, term) .then(function(newCourse) { me.setState({course: newCourse}); me.closeModal(); }); } addStudentsToSection(sectionId, studentIds) { var me = this; this.props.addStudentsToSection(sectionId, studentIds) .then(function() { me.closeModal(); }); } deleteSectionFromCourse(sectionIndex) { var me = this; var sections = me.state.sections; if(sections[sectionIndex] == undefined) return $.when(null); $.post('/section/destroy/' + sections[sectionIndex].id) .then(function(section) { console.log("section", section); sections.splice(sectionIndex, 1); me.setState({sections: sections}); me.closeModal(); }); } deleteQuizFromCourse(quizIndex) { var me = this; var quizzes = this.state.course.quizzes; $.post('/quiz/find/' + quizzes[quizIndex].id) .then(function(quiz) { return $.post('/quiz/destroy/' + quizzes[quizIndex].id); }) // .then(function(quiz) { // if(quiz.questions.length == 0) return $.when(null); // var questionIds = quiz.questions.map(function(question){return question.id;}); // return $.post('/question/multidestroy', {ids: questionIds}); // }) .then(function() { quizzes.splice(quizIndex, 1); var course = me.state.course; course.quizzes = quizzes; me.setState({course: course}); me.closeModal(); }); } deleteCourseFromProfessor(course) { var me = this; this.props.deleteCourseFromProfessor(course) .then(function() { var course = { id: -1, title: "FAKE 101", quizzes: [], sections: [] }; me.setState({course: course}); }); } render() { return ( <div> <div id="courses" className="quizzlyContent"> {(() => { if(this.state.course.id > -1) { return ( <Course course={this.state.course} isCourse={true} ref={'course'} showQuizModal={this.showQuizModal.bind(this)} showQuizInModal={this.showQuizInModal.bind(this)} showMetricModal={this.showMetricModal.bind(this)} deleteQuizFromCourse={this.deleteQuizFromCourse.bind(this)} sectionIndex={-1} deleteCourseFromProfessor={this.deleteCourseFromProfessor.bind(this)} deleteSectionFromCourse={this.deleteSectionFromCourse.bind(this)} /> ); } })()} {this.state.sections.map(function(section, sectionIndex) { // this is section, not course! return ( <Course section={section} sectionIndex={sectionIndex} course={this.state.course} isCourse={false} key={sectionIndex} showQuizInModal={this.showQuizInModal.bind(this)} showMetricModal={this.showMetricModal.bind(this)} showStudentsModal={this.showStudentsModal.bind(this)} deleteSectionFromCourse={this.deleteSectionFromCourse.bind(this)} /> ); }, this)} <div className="addEntityButton" onClick={this.showCourseModal.bind(this)}>+</div> </div> {(() => { if(this.state.showModal) return ( <Modal modalInfo={this.state.modalInfo} showModal={this.state.showModal} course={this.state.course} quizzes={this.state.course.quizzes} key={this.state.showModal} closeModal={this.closeModal.bind(this)} addQuizToCourse={this.addQuizToCourse.bind(this)} addCourseToProfessor={this.addCourseToProfessor.bind(this)} addSectionToCourse={this.addSectionToCourse.bind(this)} addStudentsToSection={this.addStudentsToSection.bind(this)} /> ); })()} {(() => { if(this.state.showMetricModal) return ( <MetricModal modalInfo={this.state.modalInfo} showMetricModal={this.state.showMetricModal} key={this.state.showMetricModal} closeModal={this.closeModal.bind(this)} /> ); })()} </div> ); } }
freyconner24/Quizzly
components/pages/Courses.js
JavaScript
mit
8,389
import Vue from 'vue' import Kanban from './components/kanban-app.vue' import store from './store.js' new Vue({ el: '#app', store, render: h => h(Kanban) })
drayah/xerpa-kanban
src/main.js
JavaScript
mit
164
import {observable, runInAction, computed, action, reaction, autorun} from "mobx"; import LynlpApi from "../common/lynlp-api" import _ from "lodash"; class EntityExtractStore { @observable isFetching = false; @observable currentItem = '图形展示'; @observable entity = {}; @action fetchData(content) { this.isFetching = true; LynlpApi.entity(content).then((result)=>{ this.entity = result; this.isFetching = false; }) } } const entityExtractStore = new EntityExtractStore(); export default entityExtractStore
wangpengzsx/lynlp1
src/mobx/entity-extract-store.js
JavaScript
mit
533
(window.webpackJsonp=window.webpackJsonp||[]).push([[88],{499:function(t,e,s){"use strict";s.r(e);var a=s(0),n=Object(a.a)({},(function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h2",{attrs:{id:"examples"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#examples"}},[t._v("#")]),t._v(" Examples")]),t._v(" "),s("p",[t._v("Spreadsheets: Edit a cell in the sheet")]),t._v(" "),s("h2",{attrs:{id:"solutions"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#solutions"}},[t._v("#")]),t._v(" Solutions")]),t._v(" "),s("p",[s("strong",[t._v("Data Curator")]),s("br"),t._v("\nEdit CSV and XLS files without unintentionally changing the raw data. Also, automatically detects the schema for every file.")]),t._v(" "),s("p",[s("strong",[t._v("Delimiter")]),s("br"),t._v("\nEdit and sync CSV files with GitHub directly in the browser.")])])}),[],!1,null,null,null);e.default=n.exports}}]);
anelda/website
assets/js/88.10da411c.js
JavaScript
mit
967
'use strict'; const async = require('async'); const getApp = require('../utils/utils.js').getApp; module.exports = function(Worker) { //Worker.validatesPresenceOf('title'); Worker.upsertItem = (data, cb) => { let res = {}; getApp(Worker) .then((app) => { if (!!!data.person) cb({errCode: 'ERR_WORKER_NO_PERSON'}); if (!!!data.cargos || data.cargos.length === 0 ) cb({errCode: 'ERR_WORKER_NO_CARGO'}); console.log(data); return (!!!data.person.id ? app.models.person.create(data.person) : Promise.resolve(data.person) ) .then((result) => { res.person = result; return app.models.worker.upsert({ personId: res.person.id }); }) .then(results => { res.worker = results; res.cargoMapping = []; return new Promise((resolve, reject) => async.each(data.cargos, (cargoId, cbInner) => app.models.cargoMapping.create({ cargoId: cargoId, workerId: res.worker.id }) .then(r => cbInner(null, res.cargoMapping.push(r))) .catch(err => async.each(res.cargoMapping, (itemInner, cbInner2) => cbInner2(null, itemInner.destroy()), err => cbInner({ errCode: 'ERR_WORKER_FAIL_CARGOS', message: 'problem to save cargo in worker' }) )), err => !!err ? reject(err) : resolve(res) )); }) .then(res => { cb(null, res); }) .catch(err => { if (!!res.person) res.person.destroy(); if (!!res.worker) res.worker.destroy(); cb({errCode: 'ERR_WORKER_NO_SAVE'}); }); }); }; Worker.remoteMethod('upsertItem', { description: 'upsert client ', http: {verb: 'post'}, accepts: { arg: 'data', type: 'object', description: 'data from form to upsert client', http: {source: 'body'}, required: true }, returns: { arg: 'res', type: 'object', root: true } }); };
skeiter9/traru
app/common/models/worker.js
JavaScript
mit
2,093
import { combineReducers } from 'redux' import auth from './auth' import watt from './watt' import locations from './locations' export default combineReducers({ auth, watt, locations })
tombatossals/energy
src/reducers/index.js
JavaScript
mit
193
'use strict'; require('./components/dropdown'); require('./components/active-link');
ravisuhag/jolly
assets/scripts/index.js
JavaScript
mit
88
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; /* Copyright 2013 jQuery Foundation and other contributors Released under the MIT license. http://jquery.org/license */ define(["ojs/ojcore","jquery","ojdnd","ojs/ojlistview"],function(a,g){a.jb=function(a){this.Ja=a};o_("ListViewDndContext",a.jb,a);a.f.xa(a.jb,a.f,"oj.ListViewDndContext");a.jb.nra=67;a.jb.rT=86;a.jb.tT=88;a.jb.prototype.reset=function(){this.t1();this.un=this.SI=this.XI=this.jR=null};a.jb.prototype.CX=function(a){var b=this.Ja.Jd("dnd");return null!=b&&b[a]?b[a].items:null};a.jb.prototype.WM=function(){return this.CX("drag")};a.jb.prototype.DX=function(){return this.CX("drop")};a.jb.prototype.ps= function(){return"enabled"==this.CX("reorder")};a.jb.prototype.Vg=function(a){return this.Ja.On(a)};a.jb.prototype.sN=function(){var a,b,d,e;a=[];if(this.Ja.Pc())for(b=this.Ja.Jd("selection"),d=0;d<b.length;d++)e=this.Ja.Se(b[d]),null==e||this.Ja.vj(g(e))||a.push(e);else e=this.dca(),null!=e&&a.push(e);null!=this.kz&&0<this.kz.length&&-1==a.indexOf(this.kz.get(0))&&a.push(this.kz.get(0));return a};a.jb.prototype.dca=function(){return null==this.Ja.V?null:this.Ja.V.elem[0]};a.jb.prototype.hz=function(a){var b; g(a).hasClass(this.Ja.eg())||(a=a.firstElementChild);a=g(a).find(".oj-listview-drag-handle");null!=a&&0<a.length&&(b=a.attr("aria-labelledby"),null==b?a.attr("aria-labelledby",this.Ja.qx("instr")):a.attr("aria-labelledby",b+" "+this.Ja.qx("instr")),this.Ja.Um()&&a.attr("draggable","true"))};a.jb.prototype.t1=function(){this.ooa&&g.each(this.ooa,function(a,b){g(b).removeClass("oj-draggable")})};a.jb.prototype.CTa=function(){var a=[],b,d,e;this.t1();b=this.Ja.Jd("selection");for(d=0;d<b.length;d++)e= this.Ja.Se(b[d]),null==e||this.Ja.vj(g(e))||(a.push(e),g(e).addClass("oj-draggable"));this.ooa=a};a.jb.prototype.Wia=function(a){var b;b=a.find(".oj-listview-drag-handle");if(null!=b&&0<b.length)return!0;a.addClass("oj-draggable");return!1};a.jb.prototype.WMa=function(a){a.removeClass("oj-draggable")};a.jb.prototype.Sia=function(a){var b,d;if(null!=this.WM()||this.ps()){if(a.hasClass("oj-listview-drag-handle"))b=g(a);else{a=this.Vg(a);if(null!=a&&(d=this.Wia(a)))return;d=this.sN();0<d.length&&(null!= a&&-1<d.indexOf(a[0])?b=a:g(d[0]).removeClass("oj-draggable"))}null!=b&&b.attr("draggable",!0)}};a.jb.prototype.uka=function(a){if(null!=this.WM()||this.ps())a=a.hasClass("oj-listview-drag-handle")?g(a):this.Vg(a),null!=a&&a.removeAttr("draggable")};a.jb.prototype.wo=function(c,b,d,e){var f;if(c="drag"===c?this.WM():this.DX())if((b=c[b])&&"function"==typeof b)try{d.dataTransfer=d.originalEvent.dataTransfer,f=b(d,e)}catch(g){a.F.error("Error: "+g)}else return-1;return f};a.jb.prototype.ZKa=function(a, b,d){var e,f=[],g;for(e=0;e<d.length;e++)(g=this.Ja.tca(d[e]))&&(g.innerHTML&&g.tagName&&"LI"==g.tagName?f.push(g.innerHTML):f.push(g));return 0<f.length?(this.YKa(a.originalEvent,b,f),this.$Ka(a.originalEvent,d),{items:f}):null};a.jb.prototype.YKa=function(a,b,d){var e;a=a.dataTransfer;d=JSON.stringify(d);if("string"==typeof b)a.setData(b,d);else if(b)for(e=0;e<b.length;e++)a.setData(b[e],d);a.setData("text/ojlistview-dragsource-id",this.Ja.element.get(0).id)};a.jb.prototype.$Ka=function(a,b){var d, e,f=Number.MAX_VALUE,h,k,l,m=0,p=0;d=a.target;if(1<b.length){d=g(document.createElement("ul"));d.get(0).className=this.Ja.element.get(0).className;d.addClass("oj-listview-drag-image").css({width:this.Ja.element.css("width"),height:this.Ja.element.css("height")});for(e=0;e<b.length;e++)f=Math.min(f,b[e].offsetTop);for(e=0;e<b.length;e++)h=b[e].offsetTop-f,k=b[e].offsetWidth,l=g(b[e].cloneNode(!0)),l.removeClass("oj-selected oj-focus oj-hover").css({position:"absolute",top:h,width:k}),d.append(l)}else g(d).hasClass("oj-listview-drag-handle")&& (h=0,g.contains(b[0],d.offsetParent)&&(h=d.offsetTop),m=Math.max(0,d.offsetLeft-b[0].offsetLeft)+d.offsetWidth/2,p=h+d.offsetHeight/2),l=g(b[0].cloneNode(!0)),l.removeClass("oj-selected oj-focus oj-hover").addClass("oj-drag"),d=g(document.createElement("ul")),d.get(0).className=this.Ja.element.get(0).className,d.addClass("oj-listview-drag-image").css({width:this.Ja.element.css("width"),height:2*b[0].offsetHeight}).append(l);g("body").append(d);this.XI=d;a.dataTransfer.setDragImage(d.get(0),m,p)}; a.jb.prototype.OY=function(a){var b,d,e;b=this.WM();if(null!=b||this.ps())if(d=null!=b?b.dataTypes:"text/ojlistview-items-data",g(a.target).hasClass("oj-listview-drag-handle")?(e=[],e.push(this.Vg(a.target)[0])):e=this.sN(),0<e.length){if(null==b&&1<e.length)return!1;this.un=e;this.SI=g(e[0]);if(b=this.ZKa(a,d,e)){if(a=this.wo("drag","dragStart",a,b),-1!==a)return a}else return!1}};a.jb.prototype.EDa=function(a){return this.wo("drag","drag",a)};a.jb.prototype.oM=function(){null!=this.XI&&(this.XI.remove(), this.XI=null)};a.jb.prototype.KY=function(a){var b;if(null!=this.SI&&null!=this.un)for(this.SI.find(".oj-listview-drag-handle").removeAttr("draggable"),this.SI.removeClass("oj-drag oj-draggable").removeAttr("draggable"),b=0;b<this.un.length;b++)g(this.un[b]).removeClass("oj-listview-drag-item");this.lF();this.oM();this.t1();this.wo("drag","dragEnd",a);this.jR=this.un;this.un=this.SI=this.XI=null};a.jb.prototype.WZ=function(a){var b,d;b=this.DX();if(this.ps()&&null==b)return!0;if(b&&b.dataTypes)for(b= b.dataTypes,b="string"==typeof b?[b]:b,a=a.originalEvent.dataTransfer.types,d=0;d<a.length;d++)if(0<=b.indexOf(a[d]))return!0;return!1};a.jb.prototype.xo=function(a,b,d){a=this.wo("drop",a,b,d);(void 0===a||-1===a)&&this.WZ(b)&&b.preventDefault();return a};a.jb.prototype.vaa=function(a){var b;null==this.Sj&&(b=g(a.get(0).cloneNode(!1)),b.addClass("oj-drop").removeClass("oj-drag oj-draggable oj-hover oj-focus oj-selected").css({display:"block",height:a.outerHeight()}),this.Sj=b);return this.Sj};a.jb.prototype.R$= function(){null!=this.cj&&-1===this.pD&&this.cj.children("."+this.Ja.dg()).removeClass("oj-drop")};a.jb.prototype.Q$=function(){null!=this.cj&&this.cj.hasClass("oj-listview-no-data-message")&&(this.cj.removeClass("oj-drop"),this.cj.get(0).textContent=this.Ja.zca())};a.jb.prototype.lF=function(){null!=this.Sj&&(this.Sj.css("height","0"),this.Sj.remove(),this.Sj=null);this.Q$();this.R$()};a.jb.prototype.LY=function(a){var b;b=this.Vg(a.target);a=this.xo("dragEnter",a,{item:b.get(0)});if(-1!=a)return a}; a.jb.prototype.l0=function(a){null!=this.cj&&this.cj.removeClass("oj-valid-drop oj-invalid-drop");this.cj=a;this.cj.addClass("oj-valid-drop")};a.jb.prototype.Iia=function(a,b){var d;d=a.attr("aria-label");null==d&&(d=a.text());d=this.Ja.ea.R("accessibleReorder"+b.charAt(0).toUpperCase()+b.substr(1)+"Item",{item:d});this.Ja.Ch(d)};a.jb.prototype.owa=function(){null==this.Koa&&this.Ja.Um()&&(this.Ja.element.find("ul."+this.Ja.fh()).each(function(){g(this).attr("oldMaxHeight",g(this).css("maxHeight").toString()); g(this).css("maxHeight",1E4)}),this.Koa="adjusted")};a.jb.prototype.uia=function(){this.Ja.Um()&&this.Ja.element.find("ul."+this.Ja.fh()).each(function(){g(this).css("maxHeight",parseInt(g(this).attr("oldMaxHeight"),10));g(this).removeAttr("oldMaxHeight")});this.Koa=null};a.jb.prototype.NY=function(a){var b,d,e,f;if(null!=this.DX()||this.ps()){this.owa();if(null!=this.un&&"none"!=g(this.un[0]).css("display")){b=g(this.un[0]);d=this.vaa(b);for(a=0;a<this.un.length;a++)g(this.un[a]).addClass("oj-listview-drag-item"); d.insertBefore(b);this.pD=d.index()}else b=this.Vg(a.target),null!=b&&0<b.length?(e=this.xo("dragOver",a,{item:b.get(0)}),-1===e&&this.ps()||!1===e||a.isDefaultPrevented()?(b.hasClass(this.Ja.eg())?(this.R$(),b.hasClass("oj-drop")||(d=this.vaa(b),f=b.index(),null==this.pD||this.pD<f?(d.insertAfter(b),this.oD="after"):(d.insertBefore(b),this.oD="before"),this.Iia(b,this.oD),this.l0(b),this.pD=d.index())):(this.lF(),b.children("."+this.Ja.dg()).addClass("oj-drop"),this.l0(b),this.pD=-1,this.oD="inside", this.Iia(b,this.oD)),a.preventDefault()):g(a.target).hasClass(this.Ja.fh())||(b.addClass("oj-invalid-drop"),this.lF())):(b=this.Ja.element.children(".oj-listview-no-data-message"),null!=b&&0<b.length&&(b.addClass("oj-drop"),b.get(0).textContent="",this.l0(b),a.preventDefault()));return e}};a.jb.prototype.ZN=function(a,b){var d,e;d=b.getBoundingClientRect();e=a.originalEvent;return e.clientX>=d.left&&e.clientX<d.right&&e.clientY>=d.top&&e.clientY<d.bottom};a.jb.prototype.MY=function(a){var b,d;if(null!= this.cj&&(b=this.Vg(a.target),null!=b&&0<b.length?(b.removeClass("oj-valid-drop oj-invalid-drop"),d=this.xo("dragLeave",a,{item:b.get(0)}),this.ZN(a,a.currentTarget)||(this.lF(),this.uia())):this.ZN(a,a.currentTarget)||this.Q$(),-1!=d))return d};a.jb.prototype.PY=function(a){var b,d;if(null!=this.cj&&(b=a.originalEvent.dataTransfer.getData("text/ojlistview-dragsource-id"),d=this.cj.hasClass("oj-listview-no-data-message")?{}:{item:this.cj.get(0),position:this.oD},this.ps()&&b===this.Ja.element.get(0).id? d.reorder=!0:d.reorder=!1,b=this.xo("drop",a,d),d.reorder&&(d.items=null==this.jR?this.un:this.jR,d.reference=d.item,this.Ja.Bl("reorder",a,d),a.preventDefault()),null!=this.cj&&this.cj.removeClass("oj-valid-drop"),this.lF(),this.uia(),this.oM(),this.cj=null,this.pD=-1,this.jR=this.oD=null,-1!==b))return b};a.jb.prototype.ANa=function(a){var b=this,d,e;this.ps()&&(void 0==a&&(a=this.Ja.Jd("contextMenu")),null!=a&&(null==this.xn&&(this.xn=[]),a=g(a),d=a.find("[data-oj-command]"),e=[],d.each(function(){var a, c;0===g(this).children("a").length?0==g(this).attr("data-oj-command").indexOf("oj-listview-")&&(a=g(this).attr("data-oj-command").substring(12),c=b.tk(a),c.get(0).className=g(this).get(0).className,g(this).replaceWith(c)):(a=g(this).attr("data-oj-command"),"pasteBefore"==a?a="paste-before":"pasteAfter"==a&&(a="paste-after"));null!=a&&e.push(a)}),this.xn=e,0<e.length&&(a.data("oj-ojMenu")&&a.ojMenu("refresh"),a.on("ojbeforeopen",this.vDa.bind(this)),a.on("ojselect",this.Vl.bind(this)))))};a.jb.prototype.tk= function(a){return"paste-before"===a?this.Sg("pasteBefore"):"paste-after"===a?this.Sg("pasteAfter"):this.Sg(a)};a.jb.prototype.Sg=function(a){var b=g("\x3cli\x3e\x3c/li\x3e");b.attr("data-oj-command",a);b.append(this.fF(a));return b};a.jb.prototype.fF=function(a){a="label"+a.charAt(0).toUpperCase()+a.slice(1);return g('\x3ca href\x3d"#"\x3e\x3c/a\x3e').text(this.Ja.ea.R(a))};a.jb.prototype.iG=function(a){var b;null!=this.Yo&&g(this.Yo).removeClass("oj-listview-cut");b=this.sN();g(b).addClass("oj-listview-cut"); this.Yo=b;this.Ja.Bl("cut",a,{items:b})};a.jb.prototype.dea=function(a){var b;null!=this.Yo&&g(this.Yo).removeClass("oj-listview-cut");this.Yo=b=this.sN();this.Ja.Bl("copy",a,{items:b})};a.jb.prototype.kG=function(a,b,d){this.Ja.Bl("paste",a,{item:b.get(0)});g(this.Yo).removeClass("oj-listview-cut");this.Ja.Bl("reorder",a,{items:this.Yo,position:d,reference:b.get(0)});this.Yo=null};a.jb.prototype.Vl=function(a,b){if(null!=this.kz)switch(b.item.attr("data-oj-command")){case "cut":this.iG(a);break; case "copy":this.dea(a);break;case "paste":var d=!0;case "pasteBefore":var e=!0;case "pasteAfter":var f="after";d?f="inside":e&&(f="before");this.kG(a,this.kz,f);this.kz=null}};a.jb.prototype.XE=function(a,b){null!=this.xn&&("paste-before"==b?b="pasteBefore":"paste-after"==b&&(b="pasteAfter"),a.find("[data-oj-command\x3d'"+b+"']").removeClass("oj-disabled"))};a.jb.prototype.vDa=function(a,b){var d,e;d=g(a.target);d.find("[data-oj-command]").addClass("oj-disabled");e=b.openOptions.launcher;null==e|| null==this.xn||0==this.xn.length?d.ojMenu("refresh"):(e.children().first().hasClass(this.Ja.dg())?null!=this.Yo&&this.XE(d,"paste"):(this.XE(d,"cut"),this.XE(d,"copy"),null!=this.Yo&&(this.XE(d,"paste-before"),this.XE(d,"paste-after"))),d.ojMenu("refresh"),this.kz=e)};a.jb.prototype.SJ=function(c){var b,d;if(!this.ps()||null==this.xn||0==this.xn.length)return!1;if(c.ctrlKey||c.metaKey){b=c.keyCode;if(b===a.jb.tT&&-1<this.xn.indexOf("cut"))return this.iG(c),!0;if(b===a.jb.nra&&-1<this.xn.indexOf("copy"))return this.dea(c), !0;if(b===a.jb.rT&&null!=this.Yo&&(b=g(this.dca()),b.children().first().hasClass(this.Ja.dg())?-1<this.xn.indexOf("paste")&&(d="inside"):-1<this.xn.indexOf("paste-before")?d="before":-1<this.xn.indexOf("paste-after")&&(d="after"),null!=d))return this.kG(c,b,d),!0}return!1}});
crmouli/crmouli.github.io
js/libs/oj/v3.0.0/min/ojlistviewdnd.js
JavaScript
mit
12,304
/* eslint-env mocha */ 'use strict' const chai = require('chai') chai.use(require('dirty-chai')) const expect = chai.expect const parallel = require('async/parallel') const createNode = require('./utils/create-node.js') const echo = require('./utils/echo') describe('ping', () => { let nodeA let nodeB before((done) => { parallel([ (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeA = node node.handle('/echo/1.0.0', echo) node.start(cb) }), (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeB = node node.handle('/echo/1.0.0', echo) node.start(cb) }) ], done) }) after((done) => { parallel([ (cb) => nodeA.stop(cb), (cb) => nodeB.stop(cb) ], done) }) it('should be able to ping another node', (done) => { nodeA.ping(nodeB.peerInfo, (err, ping) => { expect(err).to.not.exist() ping.once('ping', (time) => { expect(time).to.exist() ping.stop() done() }) ping.start() }) }) it('should be not be able to ping when stopped', (done) => { nodeA.stop(() => { nodeA.ping(nodeB.peerInfo, (err) => { expect(err).to.exist() done() }) }) }) })
diasdavid/js-libp2p
test/ping.node.js
JavaScript
mit
1,347
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; $scope.create = function() { var article = new Articles({ title: this.title, content: this.content }); article.$save(function(response) { $location.path('articles/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); this.title = ''; this.content = ''; }; $scope.remove = function(article) { if (article) { article.$remove(); for (var i in $scope.articles) { if ($scope.articles[i] === article) { $scope.articles.splice(i, 1); } } } else { $scope.article.$remove(function() { $location.path('articles'); }); } }; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.find = function() { $scope.articles = Articles.query(); }; $scope.findOne = function () { $scope.article = Articles.get({ articleId: $stateParams.articleId }); }; } ]);
rodrigowirth/IELTS
public/modules/articles/controllers/articles.client.controller.js
JavaScript
mit
1,352
require('..').config({namespace:'NVM'}) .read({}) .on('read', function(ENV){ console.log(JSON.stringify(ENV, null, 4)); });
goliatone/treehugger
examples/read.js
JavaScript
mit
146
const express = require("express"); const app = express(); app.set('port', (process.env.PORT || 3000)); const getData = require('./src/server/api/getData'); const setup = require('./src/server/api/setupApi'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use('/assets', express.static('build')); app.use('/', require('./src/server/routers/index')); app.get('/api/:chrom', getData); const server = app.listen(app.get('port')); setup(server);
ragingsquirrel3/vrdb
server.js
JavaScript
mit
483
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Category Schema */ var CategorySchema = new Schema({ name: { type: String, default: '', required: 'Please fill Category name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Category', CategorySchema);
andela-osogunle/storefront.io
app/models/category.server.model.js
JavaScript
mit
488
var searchData= [ ['index',['index',['../d8/d33/structsvm__sample.html#a008f6b24c7c76af103e84245fb271506',1,'svm_sample']]], ['initlibirwls',['initLIBIRWLS',['../d4/d54/pythonmodule_8c.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c'],['../d0/da7/pythonmodule_8h.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c']]], ['initmemory',['initMemory',['../d0/d98/ParallelAlgorithms_8h.html#aa6df8c3f4f455d5692b3cb220fc205c7',1,'ParallelAlgorithms.h']]], ['iostructures_2ec',['IOStructures.c',['../dc/dfc/IOStructures_8c.html',1,'']]], ['iostructures_2eh',['IOStructures.h',['../de/d79/IOStructures_8h.html',1,'']]], ['irwlspar',['IRWLSpar',['../d4/d49/budgeted-train_8h.html#ad51d9a46645ad0b0bedb1113a3807d24',1,'budgeted-train.h']]] ];
RobeDM/LIBIRWLS
docs/html/search/all_7.js
JavaScript
mit
812
module.exports = { options: { templateCompilerPath: 'bower_components/ember/ember-template-compiler.js', handlebarsPath: 'bower_components/handlebars/handlebars.js', preprocess: function (source) { return source.replace(/\s+/g, ' '); }, templateName: function (sourceFile) { /* These are how templates will be named based on their folder structure. components/[name].hbs ==> components/[name] partials/[name].hbs ==> _[name] modules/application/templates/[name].hbs ==> [name] modules/application/partials/[name].hbs ==> _[name] modules/[moduleName]/templates/[moduleName].hbs ==> [moduleName] modules/[moduleName]/templates/[name].hbs ==> [moduleName]/[name] modules/[moduleName]/partials/[name].hbs ==> [moduleName]/_[name] Additionally any template that is nested deeper will have that structure added as well. modules/[moduleName]/templates/[folder1]/[folder2]/[name] ==> [moduleName]/[folder1]/[folder2]/[name] */ var matches = sourceFile.match(new RegExp('(?:app/modules/(.*?)/|app/)(templates|partials)?/?(.*)')), moduleName = matches[1], isAppModule = (moduleName === 'application'), isPartial = (matches[2] === 'partials'), fileName = matches[3], prefix = (isPartial ? '_' : ''), templateName = ''; if (moduleName && !isAppModule) { if (fileName === moduleName) { templateName = moduleName; } else { templateName = moduleName + '/' + prefix + fileName; } } else { templateName = prefix + fileName; } console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green); return templateName; } }, compile: { files: { 'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}'] } } };
geekingreen/generator-anthracite
app/templates/grunt/emberTemplates.js
JavaScript
mit
1,794
module.exports = api => { api.cache(true); return { presets: [ [ '@babel/preset-env', { targets: { node: '12' } } ] ] }; };
srod/node-minify
babel.config.js
JavaScript
mit
207
'use strict'; function UserListController(userList) { var vm = this; console.log('UserListController'); vm.userList = userList; } module.exports = UserListController;
byskr/sample-angular
src/components/user/controller/user-list-controller.js
JavaScript
mit
181
import log from 'log'; import Ember from 'ember'; import {registerComponent} from 'ember-utils'; import layout from './confirm-toolbar.hbs!'; export var RheaConfirmToolbar = Ember.Component.extend({ layout, tagName: '', actions: { confirm: function(opID) { this.sendAction('confirm'); }, cancel: function(opID) { this.sendAction('cancel'); } } }); registerComponent('rhea-confirm-toolbar', RheaConfirmToolbar);
rhea/rhea
src/components/confirm-toolbar/confirm-toolbar.js
JavaScript
mit
451
/** * 乘法操作符 */ define( function ( require, exports, modules ) { var kity = require( "kity" ); return kity.createClass( 'MultiplicationOperator', { base: require( "operator/binary-opr/left-right" ), constructor: function () { var ltr = new kity.Rect( 0, 20, 43, 3, 3 ).fill( "black"), rtl = new kity.Rect( 20, 0, 3, 43, 3 ).fill( "black" ); this.callBase( "Multiplication" ); this.addOperatorShape( ltr.setAnchor( 22, 22 ).rotate( 45 ) ); this.addOperatorShape( rtl.setAnchor( 22, 22 ).rotate( 45 ) ); } } ); } );
Inzaghi2012/formula
src/operator/binary-opr/multiplication.js
JavaScript
mit
636
/** xxHash64 implementation in pure Javascript Copyright (C) 2016, Pierre Curto MIT license */ var UINT64 = require('cuint').UINT64 /* * Constants */ var PRIME64_1 = UINT64( '11400714785074694791' ) var PRIME64_2 = UINT64( '14029467366897019727' ) var PRIME64_3 = UINT64( '1609587929392839161' ) var PRIME64_4 = UINT64( '9650029242287828579' ) var PRIME64_5 = UINT64( '2870177450012600261' ) /** * Convert string to proper UTF-8 array * @param str Input string * @returns {Uint8Array} UTF8 array is returned as uint8 array */ function toUTF8Array (str) { var utf8 = [] for (var i=0, n=str.length; i < n; i++) { var charcode = str.charCodeAt(i) if (charcode < 0x80) utf8.push(charcode) else if (charcode < 0x800) { utf8.push(0xc0 | (charcode >> 6), 0x80 | (charcode & 0x3f)) } else if (charcode < 0xd800 || charcode >= 0xe000) { utf8.push(0xe0 | (charcode >> 12), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)) } // surrogate pair else { i++; // UTF-16 encodes 0x10000-0x10FFFF by // subtracting 0x10000 and splitting the // 20 bits of 0x0-0xFFFFF into two halves charcode = 0x10000 + (((charcode & 0x3ff)<<10) | (str.charCodeAt(i) & 0x3ff)) utf8.push(0xf0 | (charcode >>18), 0x80 | ((charcode>>12) & 0x3f), 0x80 | ((charcode>>6) & 0x3f), 0x80 | (charcode & 0x3f)) } } return new Uint8Array(utf8) } /** * XXH64 object used as a constructor or a function * @constructor * or * @param {Object|String} input data * @param {Number|UINT64} seed * @return ThisExpression * or * @return {UINT64} xxHash */ function XXH64 () { if (arguments.length == 2) return new XXH64( arguments[1] ).update( arguments[0] ).digest() if (!(this instanceof XXH64)) return new XXH64( arguments[0] ) init.call(this, arguments[0]) } /** * Initialize the XXH64 instance with the given seed * @method init * @param {Number|Object} seed as a number or an unsigned 32 bits integer * @return ThisExpression */ function init (seed) { this.seed = seed instanceof UINT64 ? seed.clone() : UINT64(seed) this.v1 = this.seed.clone().add(PRIME64_1).add(PRIME64_2) this.v2 = this.seed.clone().add(PRIME64_2) this.v3 = this.seed.clone() this.v4 = this.seed.clone().subtract(PRIME64_1) this.total_len = 0 this.memsize = 0 this.memory = null return this } XXH64.prototype.init = init /** * Add data to be computed for the XXH64 hash * @method update * @param {String|Buffer|ArrayBuffer} input as a string or nodejs Buffer or ArrayBuffer * @return ThisExpression */ XXH64.prototype.update = function (input) { var isArrayBuffer // Convert all strings to utf-8 first (issue #5) if (typeof input == 'string') { input = toUTF8Array(input) isArrayBuffer = true } if (typeof ArrayBuffer !== "undefined" && input instanceof ArrayBuffer) { isArrayBuffer = true input = new Uint8Array(input); } var p = 0 var len = input.length var bEnd = p + len if (len == 0) return this this.total_len += len if (this.memsize == 0) { if (isArrayBuffer) { this.memory = new Uint8Array(32) } else { this.memory = new Buffer(32) } } if (this.memsize + len < 32) // fill in tmp buffer { // XXH64_memcpy(this.memory + this.memsize, input, len) if (isArrayBuffer) { this.memory.set( input.subarray(0, len), this.memsize ) } else { input.copy( this.memory, this.memsize, 0, len ) } this.memsize += len return this } if (this.memsize > 0) // some data left from previous update { // XXH64_memcpy(this.memory + this.memsize, input, 16-this.memsize); if (isArrayBuffer) { this.memory.set( input.subarray(0, 32 - this.memsize), this.memsize ) } else { input.copy( this.memory, this.memsize, 0, 32 - this.memsize ) } var p64 = 0 var other other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v1.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p64 += 8 other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v2.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p64 += 8 other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v3.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p64 += 8 other = UINT64( (this.memory[p64+1] << 8) | this.memory[p64] , (this.memory[p64+3] << 8) | this.memory[p64+2] , (this.memory[p64+5] << 8) | this.memory[p64+4] , (this.memory[p64+7] << 8) | this.memory[p64+6] ) this.v4.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 32 - this.memsize this.memsize = 0 } if (p <= bEnd - 32) { var limit = bEnd - 32 do { var other other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v1.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v2.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v3.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 other = UINT64( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) this.v4.add( other.multiply(PRIME64_2) ).rotl(31).multiply(PRIME64_1); p += 8 } while (p <= limit) } if (p < bEnd) { // XXH64_memcpy(this.memory, p, bEnd-p); if (isArrayBuffer) { this.memory.set( input.subarray(p, bEnd), this.memsize ) } else { input.copy( this.memory, this.memsize, p, bEnd ) } this.memsize = bEnd - p } return this } /** * Finalize the XXH64 computation. The XXH64 instance is ready for reuse for the given seed * @method digest * @return {UINT64} xxHash */ XXH64.prototype.digest = function () { var input = this.memory var p = 0 var bEnd = this.memsize var h64, h var u = new UINT64 if (this.total_len >= 32) { h64 = this.v1.clone().rotl(1) h64.add( this.v2.clone().rotl(7) ) h64.add( this.v3.clone().rotl(12) ) h64.add( this.v4.clone().rotl(18) ) h64.xor( this.v1.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) h64.xor( this.v2.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) h64.xor( this.v3.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) h64.xor( this.v4.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) ) h64.multiply(PRIME64_1).add(PRIME64_4) } else { h64 = this.seed.clone().add( PRIME64_5 ) } h64.add( u.fromNumber(this.total_len) ) while (p <= bEnd - 8) { u.fromBits( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , (input[p+5] << 8) | input[p+4] , (input[p+7] << 8) | input[p+6] ) u.multiply(PRIME64_2).rotl(31).multiply(PRIME64_1) h64 .xor(u) .rotl(27) .multiply( PRIME64_1 ) .add( PRIME64_4 ) p += 8 } if (p + 4 <= bEnd) { u.fromBits( (input[p+1] << 8) | input[p] , (input[p+3] << 8) | input[p+2] , 0 , 0 ) h64 .xor( u.multiply(PRIME64_1) ) .rotl(23) .multiply( PRIME64_2 ) .add( PRIME64_3 ) p += 4 } while (p < bEnd) { u.fromBits( input[p++], 0, 0, 0 ) h64 .xor( u.multiply(PRIME64_5) ) .rotl(11) .multiply(PRIME64_1) } h = h64.clone().shiftRight(33) h64.xor(h).multiply(PRIME64_2) h = h64.clone().shiftRight(29) h64.xor(h).multiply(PRIME64_3) h = h64.clone().shiftRight(32) h64.xor(h) // Reset the state this.init( this.seed ) return h64 } module.exports = XXH64
pierrec/js-xxhash
lib/xxhash64.js
JavaScript
mit
8,389
'use strict'; var _ = require('underscore'); module.exports = _.extend( require('./env/all'), require('./env/' + process.env.NODE_ENV) || {} );
ajthor/generator-mean
server/templates/config/config.js
JavaScript
mit
153
<canvas id="drawing" width="200" height="200">A drawing of something.</canvas>
msfrisbie/pjwd-src
Chapter18AnimationAndGraphicsWithCanvas/BasicCanvasUsage/BasicCanvasUsageExample01.js
JavaScript
mit
79
// instanciando módulos var gulp = require('gulp'); var watch = require('gulp-watch'); var del = require('del'); var shell = require('gulp-shell'); var connect = require('gulp-connect'); gulp.task('run:pelican', shell.task([ 'pelican content -s pelicanconf.py' ])); gulp.task('clean:pelican', function () { return del([ 'output/*' ]); }); gulp.task('connect', function(){ connect.server({ root: ['output'], port: 1337, livereload: true }); }); gulp.task('reload:output', function () { connect.reload(); }); gulp.task('watch', function(){ // watch('content/*', gulp.series('run:pelican', 'reload:output')); // watch('*', gulp.series('run:pelican', 'reload:output')); // watch('theme/*', gulp.series('run:pelican', 'reload:output')); // watch('theme/templates/*', gulp.series('run:pelican', 'reload:output')); // watch('theme/static/css/*', gulp.series('run:pelican', 'reload:output')); // watch('theme/static/js/*', gulp.series('run:pelican', 'reload:output')); }) gulp.task('serve', gulp.parallel('connect','run:pelican', 'watch'));
gustavofoa/blog.musicasparamissa.com.br
gulpfile.js
JavaScript
mit
1,080
var smidig = smidig || {}; smidig.voter = (function($) { var talk_id, $form, $notice, $loader; function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function save_vote($form, talk_id) { var votes = JSON.parse(localStorage.getItem("votes")) || {}; votes[talk_id] = true; localStorage.setItem("votes", JSON.stringify(votes)); finished($form); } function bind($form, talk_id) { $form.find("input[name='commit']").click(function() { var data = $form.serializeObject(); if(!data["feedback_vote[vote]"]) { alert("Du må gi minst 1 stjerne!"); return; } $form.find(".inputs").hide(); $form.find(".ajaxloader").show(); $form.find(".ajaxloader").css("visibility", "visible") $.ajax({ type: "POST", url: $form.attr("action"), dataType: 'json', data: data, complete: function(xhr) { if (xhr.readyState == 4) { if (xhr.status == 201) { smidig.voter.save_vote($form, talk_id); } } else { alert("Det skjedde noe galt ved lagring. Prøv igjen"); $form.find(".ajaxloader").hide(); $form.find(".inputs").show(); } } }); //cancel submit event.. return false; }); } function init($form, talk_id) { if(!supports_html5_storage()) { $notice.text("Din enhet støttes ikke"); finished($form); } var votes = JSON.parse(localStorage.getItem("votes")) || {}; if(votes[talk_id]) { finished($form); } else { bind($form, talk_id); } } function finished($form) { $form.empty(); $form.append("<em>(Du har stemt)</em>"); $form.show(); } return { init: init, save_vote: save_vote }; })(jQuery); //Document on load! $(function() { $(".talk").each(function() { var talk_id = $(this).data("talkid"); if(talk_id) { var voteTmpl = $("#tmplVote").tmpl({talk_id: talk_id}); voteTmpl.find("input.star").rating(); $(this).find(".description").append(voteTmpl); smidig.voter.init(voteTmpl, talk_id); } }); }); //Extensions to serialize a form to a js-object. $.fn.serializeObject = function(){ var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };
smidig/smidig-conference
public/javascripts/feedback_vote.js
JavaScript
mit
2,755
import express from 'express'; import LessonController from '../controllers/LessonController'; const router = express.Router(); /* eslint-disable no-unused-vars */ const LessonsPath = '/api/lessonplans'; const teacherName = 'yonderWay'; const subjectName = 'theatre1'; const lessonNumber = '/:id'; // the data access should look something like this: // '/api/teachers/{name}/{class}/{lesson#}' router.post(LessonsPath, LessonController.create); router.get(LessonsPath, LessonController.list); router.get(LessonsPath + '/:id', LessonController.listOne); router.put(LessonsPath + '/:id', LessonController.update); router.delete(LessonsPath + '/:id', LessonController.delete); export default router;
HippErger/LessonPlanDemo
src/routers/LessonRouter.js
JavaScript
mit
702
export { default, email } from '@abcum/ember-helpers/helpers/email';
abcum/ember-helpers
app/helpers/email.js
JavaScript
mit
69
module.exports = (function () { 'use strict'; var strings = require('../../strings').dead, style = require('../../style'); return { create: function(){ this.game.world.width = this.game.canvas.width; this.game.world.height = this.game.canvas.height; this.game.camera.reset(); this.game.stage.backgroundColor = style.color.three; var deadText = this.game.add.text( this.game.world.centerX, 200, strings.gregory, { font: 'bold 60px ' + style.font.regular, fill: style.color.white, align: 'center' } ); deadText.anchor.setTo(0.5); this.game.stage.backgroundColor = style.color.three; var face = this.game.add.text( this.game.world.centerX, 320, strings.face, { font: 'bold 85px ' + style.font.regular, fill: style.color.white, align: 'center' } ); face.anchor.setTo(0.5); this.game.stage.backgroundColor = style.color.three; var instructions = this.game.add.text( this.game.world.centerX, 430, strings.instructions, { font: 'bold 20px ' + style.font.regular, fill: style.color.white, align: 'center' } ); instructions.anchor.setTo(0.5); }, capabilities: { 'revive': function(){this.game.state.start('map');} } }; })();
bericp1/capstone
public/game/play/states/dead.js
JavaScript
mit
1,451
// We only need to import the modules necessary for initial render import CoreLayout from '../layouts/CoreLayout'; import Home from './Home'; import CounterRoute from './Counter'; /* Note: Instead of using JSX, we recommend using react-router PlainRoute objects to build route definitions. */ export const createRoutes = () => ({ path : '/', component : CoreLayout, indexRoute : Home, childRoutes : [ CounterRoute ] }); /* Note: childRoutes can be chunked or otherwise loaded programmatically using getChildRoutes with the following signature: getChildRoutes (location, cb) { require.ensure([], (require) => { cb(null, [ // Remove imports! require('./Counter').default(store) ]) }) } However, this is not necessary for code-splitting! It simply provides an API for async route definitions. Your code splitting should occur inside the route `getComponent` function, since it is only invoked when the route exists and matches. */ export default createRoutes;
Rodjers/gitletask-web
src/routes/index.js
JavaScript
mit
1,071
import Colors from './Colors'; import Fonts from './Fonts'; import Metrics from './Metrics'; import Images from './Images'; import ApplicationStyles from './ApplicationStyles'; export { Colors, Fonts, Images, Metrics, ApplicationStyles };
nikolay-radkov/EBudgie
src/themes/index.js
JavaScript
mit
240
import React from 'react'; import PropTypes from 'prop-types'; import Tooltip from '../Tooltip'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './Input.scss'; class InputErrorSuffix extends React.Component { render() { return ( <Tooltip dataHook="input-tooltip" disabled={this.props.errorMessage.length === 0} placement="top" alignment="center" textAlign="left" content={this.props.errorMessage} overlay="" theme="dark" maxWidth="230px" hideDelay={150} > <div className={styles.exclamation}><SvgExclamation width={2} height={11}/></div> </Tooltip> ); } } InputErrorSuffix.propTypes = { theme: PropTypes.oneOf(['normal', 'paneltitle', 'material', 'amaterial']), errorMessage: PropTypes.string.isRequired, focused: PropTypes.bool }; export default InputErrorSuffix;
skyiea/wix-style-react
src/Input/InputErrorSuffix.js
JavaScript
mit
919
const fs = require("fs"); const path = require("path"); const {template} = require("lodash"); const minimist = require("minimist"); const yaml = require("js-yaml"); const argv = minimist(process.argv.slice(2)); const conf = {}; try { const src = fs.readFileSync(path.resolve(__dirname, "../deploy-config.yml")); const yml = yaml.safeLoad(src); Object.assign(conf, yml); if (argv.env && yml[argv.env]) Object.assign(conf, yml[argv.env]); else if (yml.env && yml[yml.env]) Object.assign(conf, yml[yml.env]); } catch(e) { if (e.code !== "ENOENT") console.error(e); } Object.assign(conf, argv); function walkfs(file, exts, fn) { const stat = fs.statSync(file); if (stat.isDirectory()) { fs.readdirSync(file).forEach(name => { walkfs(path.join(file, name), exts, fn); }); } else if (exts.includes(path.extname(file))) { const src = fs.readFileSync(file, "utf-8"); fn(src, file); } } function build(dir, out, exts, join="", mode) { const result = []; walkfs(dir, exts, (src, file) => { const data = Object.assign({}, conf, { __filename: file, __dirname: path.dirname(file) }); const opts = { variable: "$", imports: {} }; result.push(template(src, opts)(data).trim() + "\n"); }); if (result) { fs.writeFileSync(out, result.join(join + "\n"), { mode }); } } build( path.join(__dirname, "kube-conf"), path.resolve(__dirname, "../kubernetes.yml"), [ ".yml" ], "---" );
tyler-johnson/shorturl
.deploy/build.js
JavaScript
mit
1,479
var set = new HashSet(); //Array size var arrElementWidth = 150; var arrElementHeight = 40; //Key size var keyWidth = 50; var keyMargin = 5; var width = 800; var height = DEFAULT_TABLE_SIZE * (arrElementHeight + 5); //Hash function block size var blockWidth = keyWidth + keyMargin + arrElementWidth; var blockHeight = DEFAULT_TABLE_SIZE * (arrElementHeight + 5); var blockMargin = 30; var codeDisplayManager = new CodeDisplayManager('javascript', 'hashSet'); var drawingArea; var hashFunctionBlock; var bucket; var keys; var newestElement; var arrow; //Panning var pan; $(document).ready(function () { drawingArea = d3.select("#hash") .append("svg:svg") .attr("width", $('#graphics').width()) .attr("height", $('#graphics').height()) .append('g'); hashFunctionBlock = drawingArea.append("g"); keys = drawingArea.append("g"); bucket = drawingArea.append("g"); hashFunctionBlock.attr("id", "hashFunctionBlock"); keys.attr("id", "keys"); bucket.attr("id", "bucket"); hashFunctionBlock.append("rect") .attr("width", blockWidth) .attr("height", blockHeight) .attr("x", width - arrElementWidth - keyWidth - blockWidth - blockMargin) .attr("fill", "cornflowerBlue"); hashFunctionBlock.append("text") .attr("width", blockWidth) .attr("height", blockHeight) .attr("y", blockHeight - 10) .attr("x", width + 10 - arrElementWidth - keyWidth - blockWidth - blockMargin) .text("") .attr("class", 'noselect'); createKeysAndBuckets(DEFAULT_TABLE_SIZE, "1"); // arrow marker drawingArea.append('defs').append('marker') .attr('id', 'end-arrow') .attr('viewBox', '0 -5 10 10') .attr('refX', 6) .attr('markerWidth', 3) .attr('markerHeight', 3) .attr('orient', 'auto') .append('svg:path') .attr('d', 'M0,-5L10,0L0,5') .attr('fill', 'red'); arrow = drawingArea.append("path") .attr("id", "arrow") .attr("fill", "none") .attr("stroke", "red") .attr("stroke-width", "4") .attr("opacity", "0") .style('marker-end', 'url(#end-arrow)'); pan = d3.zoom() .scaleExtent([1 / 10, 1]) .on("zoom", panning); drawingArea.call(pan); drawingArea.attr("transform", "translate(50,20) scale(0.70)"); }); function runAdd(x, probing, hashFunc) { set.probingType = probing == "Quadratic" ? "quadratic" : "linear"; set.hashFunc = hashFunc == "Simple" ? getSimpleHashCode : getHashCode; codeDisplayManager.loadFunctions('add', 'rehash'); codeDisplayManager.changeFunction('add'); set.add(x); } function runRemove(x) { codeDisplayManager.loadFunctions('remove', 'rehash', 'add'); codeDisplayManager.changeFunction('remove'); set.remove(x); } function panning() { drawingArea.attr("transform", d3.event.transform); } function updateArrow(index) { unhighlightKey(); var targetY = index * (arrElementHeight + 5); var lineData = [{ "x": arrElementWidth, "y": height / 2 + arrElementHeight / 2 }, { "x": width + 30 - blockWidth - arrElementWidth - keyWidth - blockMargin, "y": height / 2 + arrElementHeight / 2 }, { "x": width - 30 - arrElementWidth - keyWidth - blockMargin, "y": targetY + arrElementHeight / 2 }, { "x": width - arrElementWidth - keyWidth - keyMargin, "y": targetY + arrElementHeight / 2 }]; var lineFunction = d3.line() .x(function (d) { return d.x; }) .y(function (d) { return d.y; }); appendAnimation(null, [{ e: '#arrow', p: { attr: { d: lineFunction(lineData), opacity: 1 } }, o: { duration: 1 } }], null); highlightKey(index); } function clearHighlight(array) { appendAnimation(null, [{ e: $(array + " rect"), p: { attr: { fill: "cornflowerBlue" } }, o: { duration: 1 } }], null); } function add(value) { prevOffset = 0; hideHash(); newestElement = bucket.append("svg:g") .attr("transform", "translate(0," + height / 2 + ")") .attr("class", "newElement") .attr("opacity", 0); newestElement.append("rect") .attr("width", arrElementWidth) .attr("height", arrElementHeight) .attr("fill", "#9c6dfc"); newestElement.append("text") .style("text-anchor", "middle") .attr("x", arrElementWidth / 2) .attr("y", arrElementHeight / 2 + 7) .text(value) .style("font-size", "22px") .style("font-weight", "bold"); appendAnimation(null, [{ e: newestElement.node(), p: { attr: { opacity: "1" } }, o: { duration: 1 } }], null); } function moveToHashFunctionBlock() { appendAnimation(null, [ { e: newestElement.node(), p: { x: width + 10 - blockWidth - arrElementWidth - keyWidth - blockMargin }, o: { duration: 1 } }, { e: $("#arrow"), p: { attr: { opacity: 0, d: "" } }, o: { duration: 1, position: '-=1' } } ], null); } function replaceElement(index) { moveToHashFunctionBlock(); appendAnimation(6, [ { e: $("#bucket").filter(".element" + index), p: { attr: { opacity: 0 } }, o: { duration: 1 } }, { e: newestElement.node(), p: { x: width - arrElementWidth, y: index * (arrElementHeight + 5) }, o: { duration: 1, position: '-=1' } }, ], codeDisplayManager); $("#bucket").filter(".element" + index).attr("class", "removed"); $(newestElement).attr("class", "element" + index); } function highlightKey(index) { appendAnimation(null, [{ e: $("#keys rect").filter(".key" + index), p: { attr: { stroke: "red" } }, o: { duration: 1 } }], null); } function unhighlightKey() { appendAnimation(null, [{ e: $("#keys rect"), p: { attr: { stroke: "none" } }, o: { duration: 1 } }], null); } function removeElement(index) { appendAnimation(4, [ { e: $(".element" + index), p: { attr: { stroke: "red", "stroke-width": "2" } }, o: { duration: 1 } }, { e: $("#arrow"), p: { attr: { opacity: 0, d: "" } }, o: { duration: 1, position: '-=1' } } ], codeDisplayManager); } var prevOffset = 0; function displayHash(hashValue, length, offset) { var hashString; if (set.probingType != "quadratic") { if (offset == 0) { hashString = hashValue + " % " + length + " = " + Math.abs(hashValue % length); } prevOffset += offset; hashString = hashValue + " % " + length + " + " + prevOffset + " = " + (Math.abs(hashValue % length) + prevOffset); } else { if (offset == 0) { hashString = hashValue + " % " + length + " = " + Math.abs(hashValue % length); } prevOffset += offset; hashString = hashValue + " % " + length + " + " + offset + " * " + offset + " = " + (Math.abs(hashValue % length) + offset * offset); } appendAnimation(null, [ { e: $("#hashFunctionBlock text"), p: { attr: { stroke: "red" }, text: hashString }, o: { duration: 1 } }, { e: $("#hashFunctionBlock text"), p: { attr: { stroke: "black" } }, o: { duration: 1 } } ], null); } function hideHash() { appendAnimation(null, [{ e: $("#hashFunctionBlock text"), p: { text: "" }, o: { duration: 1 } }], null); } function renewTable(length) { appendAnimation(null, [ { e: $("#bucket, #bucket *"), p: { attr: { opacity: 0 } }, o: { duration: 1 } }, { e: $("#keys, #keys *"), p: { attr: { opacity: 0 } }, o: { duration: 1, position: '-=1' } } ], null); $("#bucket *").attr("class", "removed"); $("#keys *").attr("class", "removed"); createKeysAndBuckets(length, "0"); appendAnimation(3, [ { e: $("#bucket, #bucket *").filter(":not(.removed)"), p: { attr: { opacity: 1 } }, o: { duration: 1 } }, { e: $("#keys, #keys *").filter(":not(.removed)"), p: { attr: { opacity: 1 } }, o: { duration: 1, position: '-=1' } } ], codeDisplayManager); } function createKeysAndBuckets(length, opacity) { for (var i = 0; i < length; i++) { //Key var keyPosX = width - arrElementWidth - keyWidth - keyMargin; var keyPosY = i * (arrElementHeight + 5); var keyGroup = keys.append("svg:g") .attr("transform", "translate(" + keyPosX + "," + keyPosY + ")"); keyGroup.append("svg:rect") .attr("height", arrElementHeight) .attr("width", keyWidth) .attr("fill", "cornflowerBlue") .attr("opacity", opacity) .attr("class", "key" + i); keyGroup.append("svg:text") .text(i) .attr("x", keyWidth / 2) .attr("y", arrElementHeight / 2 + 7) .attr("opacity", opacity) .attr("text-anchor", "middle") .style("font-size", "22px") .style("font-weight", "bold"); //Bucket var valueGroup = bucket.append("svg:g") .attr("transform", "translate(" + (width - arrElementWidth) + "," + i * (arrElementHeight + 5) + ")") .attr("class", "element" + i) .attr("opacity", opacity); valueGroup.append("svg:rect") .attr("width", arrElementWidth) .attr("height", arrElementHeight) .attr("fill", "cornflowerBlue"); valueGroup.append("svg:text") .style("text-anchor", "middle") .attr("x", arrElementWidth / 2) .attr("y", arrElementHeight / 2 + 7) .style("font-size", "22px") .style("font-weight", "bold"); } } function highlightCode(lines, functionName) { if (functionName) codeDisplayManager.changeFunction(functionName); appendCodeLines(lines, codeDisplayManager); }
DAT200-Visualization-Team/DAT200-Visualization
js/visualization/HashVisualization.js
JavaScript
mit
9,652
"use strict"; function Wall(layer, id) { powerupjs.GameObject.call(this, layer, id); // Some physical properties of the wall this.strokeColor = 'none'; this.fillColor = 'none'; this.scoreFrontColor = "#FFC800"; this.scoreSideColor = "#B28C00"; this.defaultFrontColor = '#0018FF'; this.defaultSideColor = '#0010B2'; this.frontColor = this.defaultFrontColor; this.sideColor = this.defaultSideColor; this._minVelocity = -250; this._minDiameterY = 200; this._maxDiameterY = 300; this.diameterX = 100; this.diameterY = 200; this.wallWidth = this.diameterX; this.wallThickness = this.wallWidth / 9; this.smartWall = false; this.smartWallRate = 2; this.initX = powerupjs.Game.size.x + 100; this.position = this.randomHolePosition(); this.velocity = new powerupjs.Vector2(this._minVelocity, 0); } Wall.prototype = Object.create(powerupjs.GameObject.prototype); Object.defineProperty(Wall.prototype, "minDiameterY", { get: function () { return this._minDiameterY; } }); Object.defineProperty(Wall.prototype, "maxDiameterY", { get: function () { return this._maxDiameterY; } }); Object.defineProperty(Wall.prototype, "resetXOffset", { get: function () { return this.initX - this.diameterX / 2; } }); Object.defineProperty(Wall.prototype, "boundingBox", { get: function () { return new powerupjs.Rectangle(this.position.x - this.diameterX / 2, this.position.y - this.diameterY / 2, this.diameterX, this.diameterY); } }); Wall.prototype.reset = function() { var playingState = powerupjs.GameStateManager.get(ID.game_state_playing); this.frontColor = this.defaultFrontColor; this.sideColor = this.defaultSideColor; this.diameterY = this.randomHoleSize(); this.position = this.randomHolePosition(); this.scored = false; // Smart wall = moving hole if (playingState.score.score >= playingState.initSmartWallScore ) this.smartWall = true; else this.smartWall = false; }; Wall.prototype.update = function(delta) { //GameObject.prototype.update.call(this,delta); // Contains all playing objects var playingState = powerupjs.GameStateManager.get(ID.game_state_playing); // If wall goes off screen if (playingState.isOutsideWorld(this)) { this.reset(); //this.velocity = new Vector2(this._minVelocity - (20 * score.score), 0); } // Move the hole if (this.smartWall) this.moveHole(delta); // Determine if user collides with wall. if (this.position.x <= playingState.user.boundingBox.right && this.position.x > playingState.user.boundingBox.center.x) { if (this.isColliding(playingState.user)) { playingState.lives -= 1; playingState.isDying = true; } // If no collision and wall is behind user, score it. } else if (this.position.x <= playingState.user.boundingBox.center.x && !this.scored) { playingState.score.score += 1; this.frontColor = this.scoreFrontColor; this.sideColor = this.scoreSideColor; this.scored = true; sounds.beep.play(); } // Add moving hole //this.position.y += 1; }; Wall.prototype.draw = function() { powerupjs.Canvas2D.drawPath(this.calculateWallPath('topFront'), this.frontColor, this.strokeColor); powerupjs.Canvas2D.drawPath(this.calculateWallPath('holeLeft'), this.frontColor, this.strokeColor); powerupjs.Canvas2D.drawPath(this.calculateWallPath('bottomFront'), this.frontColor, this.strokeColor); powerupjs.Canvas2D.drawPath(this.calculateWallPath('holeSide'), this.sideColor, this.strokeColor); }; Wall.prototype.moveHole = function(delta) { if (this.boundingBox.bottom > powerupjs.Game.size.y || this.boundingBox.top < 0) this.smartWallRate *= -1; this.position.y += this.smartWallRate; }; Wall.prototype.isColliding = function(user) { var userCenter = { x : user.boundingBox.center.x, y : user.boundingBox.center.y}; var holeTop = this.position.y - this.diameterY / 2; var holeBottom = this.position.y + this.diameterY / 2; var overlap = this.position.x - userCenter.x; var theta = Math.acos(overlap / (user.width / 2)); var userTop = userCenter.y - (user.height / 2) * Math.sin(theta); var userBottom = (user.height / 2) * Math.sin(theta) + userCenter.y; if (userTop > holeTop && userBottom < holeBottom) { return false; } else { return true; } }; Wall.prototype.randomHoleSize = function() { //console.log(Math.floor(Math.random() * (this.maxDiameterY - this.minDiameterY)) + this.minDiameterY); return Math.floor(Math.random() * (this.maxDiameterY - this.minDiameterY)) + this.minDiameterY; }; Wall.prototype.randomHolePosition = function() { var newY = Math.random() * (powerupjs.Game.size.y - this.diameterY) + this.diameterY / 2; return new powerupjs.Vector2(this.initX, newY); }; /*Wall.prototype.calculateRandomPosition = function() { //var calcNewY = this.calculateRandomY; var enemy = this.root.find(ID.enemy1); if (enemy) { console.log("here"); var newY = null; while (! newY || (((newY - this.diameterY / 2) <= enemy.position.y + enemy.height) && ((newY + this.diameterY / 2) >= enemy.position.y) )) { newY = this.calculateRandomY(); console.log(newY); } return new powerupjs.Vector2(this.initX, newY); } else { return new powerupjs.Vector2(this.initX, this.calculateRandomY()); } };*/ Wall.prototype.calculateWallPath = function(type) { var xPoints = []; var yPoints = []; var pathType = []; // Default values // Wall bounds var thick = this.wallThickness; var left = this.position.x - this.diameterX / 2; var right = this.position.x + (this.diameterX / 2) + thick; var shiftedCenter = left + (this.diameterX / 2) + thick; var top = 0; var bottom = powerupjs.Game.size.y; // Circle bounds var cBase = this.position.y + this.diameterY / 2; var cTop = this.position.y - this.diameterY / 2; var cLeft = shiftedCenter - this.diameterX / 2; var cRight = shiftedCenter + this.diameterX / 2; switch(type){ case "holeLeft" : top = cTop - 5; bottom = cBase + 5; right = shiftedCenter; xPoints = [left, left, right, right, [cLeft, cLeft, right], right, left]; yPoints = [top, bottom, bottom, cBase, [cBase, cTop, cTop], top, top]; pathType = ['line','line','line','bezierCurve','line', 'line']; break; case "holeRight" : top = cTop - 1; bottom = cBase + 1; left = shiftedCenter; xPoints = [left, left, [cRight, cRight, left], left, right, right, left]; yPoints = [top, cTop, [cTop, cBase, cBase], bottom, bottom, top, top]; pathType = ['line','bezierCurve','line', 'line', 'line', 'line']; break; case "holeSide" : thick = thick; right = shiftedCenter; xPoints = [right - thick, [cLeft - thick, cLeft - thick, right - thick], right, [cLeft, cLeft, right], right - thick]; yPoints = [cTop, [cTop, cBase, cBase], cBase, [cBase, cTop, cTop], cTop]; pathType = ['bezierCurve','line','bezierCurve','line']; break; case "topFront" : bottom = cTop; //right = shiftedCenter + 5; xPoints = [left, left, right, right, left]; yPoints = [top, bottom, bottom, top, top]; pathType = ['line','line','line','line']; break; case "bottomFront" : top = cBase; //right = shiftedCenter + 5; xPoints = [left, left, right, right, left]; yPoints = [top, bottom, bottom, top, top]; pathType = ['line','line','line','line']; break; case "rightSide" : right = right - 1; left = right; right = right + thick; xPoints = [left, left, right, right, left]; yPoints = [top, bottom, bottom, top, top]; pathType = ['line','line','line','line']; break; } return { xPoints : xPoints, yPoints : yPoints, pathType : pathType }; };
rseigel/ballsy-javascript-game
ballsy/js/gameobjects/Wall.js
JavaScript
mit
7,813
export default function createRegistry(repositories) { const storage = { ...repositories }; const registry = { register(repositoryName, repository) { storage[repositoryName] = repository; return registry; }, has(repositoryName) { return !!storage[repositoryName]; }, get(repositoryName) { return storage[repositoryName]; }, reduce(reducer, initialValue) { return Object .keys(storage) .reduce((previous, repositoryName) => reducer( previous, storage[repositoryName], repositoryName, ), initialValue); }, }; return registry; }
RobinBressan/json-git-redux
src/createRegistry.js
JavaScript
mit
780
/** * Created by cc on 15-8-1. */ angular.module('app.services').factory('loginWithCode', ['app.api.http', '$ionicPopup','Storage','ENV','$state', function (http, $ionicPopup,Storage,ENV,$state) { var dataJSON = {} function login(){ if(ENV.code){ http.get('loginWithCode', {code:ENV.code}).success(function (data, status, headers, config) { console.log("loginWithCode:回调返回数据:"+JSON.stringify(data)) if(data.status == 200){ openIdLogin(data) } }) } } function openIdLogin(data){ if(data.user){ Storage.setUserInfo(data.user); } if(data.authInfo){ Storage.setAccessToken(data.authInfo); } if(data.openId){ Storage.set("openId",{openId:data.openId}) dataJSON['openId'] = data.openId } //自动登陆后,如果在登陆,注册,或忘记密码页面则跳到个人中心 if(data.user && data.authInfo && ($state.$current.name == 'forgetPass' || $state.$current.name == 'login' || $state.$current.name == 'signup')){ $state.go('tabs.usercenterMine') } } return { login:function(){ login() }, addOpenId:function(params){ console.log("addOpenId:"+JSON.stringify(params)) return angular.extend({openId:dataJSON.openId},params) } } }]);
honeyzhaoAliyun/als-wechat
www/client/js/services/loginWithCode.js
JavaScript
mit
1,522
import React, { PropTypes, Component } from 'react'; import { View, ScrollView, Text, TouchableOpacity, Keyboard, ListView, Platform, AsyncStorage } from 'react-native'; import getEmojiData from './data'; import ScrollableTabView from 'react-native-scrollable-tab-view'; const STORAGE_KEY = 'RNEI-latest'; class EmojiSelector extends Component { constructor(props) { super(props); this.state = { visible: props.defaultVisible || false, height: (props.defaultVisible || false) ? props.containerHeight : 0, emoji: [], latest: [], counts: {} }; } componentWillMount() { this.setState({ emoji: getEmojiData() }); if (this.props.history) { AsyncStorage.getItem(STORAGE_KEY).then( value => { if (value) { var counts = JSON.parse(value); this.setState({ counts: counts || {} }, () => { this.refreshLatest() }) } }); } } saveCounts() { if (this.props.history) { AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(this.state.counts)); } } render() { const { headerStyle, containerBackgroundColor, emojiSize, onPick, tabBorderColor } = this.props; return ( <View style={[{height: this.state.height, overflow: 'hidden'}]}> <ScrollableTabView tabBarUnderlineStyle={{ backgroundColor: this.props.tabBorderColor }} tabBarTextStyle={styles.tabBarText} style={styles.picker} > {this.state.latest.length? <EmojiCategory key={'latest'} tabLabel={'🕰'} emojiSize={emojiSize} items={this.state.latest} onPick={this.onPress.bind(this)} /> :null} {this.state.emoji.map((category, idx) => ( <EmojiCategory key={idx} tabLabel={category.items[0]} headerStyle={headerStyle} emojiSize={emojiSize} name={category.category} items={category.items} onPick={this.onPress.bind(this)} /> ))} </ScrollableTabView> </View> ); } onPress(em) { if (this.props.onPick) { this.props.onPick(em); } else if (this.onPick) { this.onPick(em); } this.increaseCount(em); } show() { this.setState({visible: true, height: this.props.containerHeight}); } hide() { this.setState({visible: false, height: 0}); } increaseCount(em) { if (!this.props.history) return; var counts = this.state.counts; if (!counts[em]) { counts[em] = 0; } counts[em] ++ ; this.setState({ counts }, () => { this.refreshLatest(); this.saveCounts(); }) } refreshLatest() { if (!this.props.history) return; var latest = this.state.latest; var counts = this.state.counts; var sortable = []; Object.keys(counts).map(em => { sortable.push([em, counts[em]]); }); sortable.sort((a, b) => { return b[1] - a[1]; }); latest = sortable.map(s => { return s[0]; }); this.setState({ latest }) } } EmojiSelector.propTypes = { onPick: PropTypes.func, headerStyle: PropTypes.object, containerHeight: PropTypes.number.isRequired, containerBackgroundColor: PropTypes.string.isRequired, emojiSize: PropTypes.number.isRequired, }; EmojiSelector.defaultProps = { containerHeight: 240, containerBackgroundColor: 'rgba(0, 0, 0, 0.1)', tabBorderColor: "#09837d", emojiSize: 40, history: true }; class EmojiCategory extends Component { constructor(props) { super(props); this.state={ items:[...props.items] }; } componentDidMount() { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.setState({ dataSource: ds.cloneWithRows(this.props.items) }); } componentWillReceiveProps(nextProps) { if (nextProps.items!=this.state.items) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(nextProps.items), items: [...nextProps.items] }); } } render() { if (!this.state.dataSource) { return null; } const { emojiSize, name, items, onPick } = this.props; return ( <View style={styles.categoryTab}> <ListView contentContainerStyle={styles.categoryItems} dataSource={this.state.dataSource} renderRow={this._renderRow.bind(this)} initialListSize={1000} /> </View> ); } _renderRow(item) { var size = this.props.emojiSize; // const fontSize = Platform.OS == 'android' ? size / 5 * 3 : size / 4 * 3; const fontSize = Platform.OS == 'android' ? size / 4 * 3 : size / 4 * 3; const width = Platform.OS == 'android' ? size + 8 : size; return ( <TouchableOpacity style={{ flex: 0, height: size, width }} onPress={() => this.props.onPick(item)}> <View style={{ flex: 0, height: size, width, justifyContent: 'center' }}> <Text style={{ flex: 0, fontSize, paddingBottom: 2, color: 'black' }}> {item} </Text> </View> </TouchableOpacity> ) } } const styles = { picker: { // flex: 1, borderTopWidth: 1, borderTopColor: "#ddd", }, categoryTab: { flex: 1, paddingHorizontal: 5, justifyContent: 'center' // paddingLeft: Platform.OS=='android' ? 20 : 5, // paddingTop: 42, }, categoryItems: { // flex: 1, flexDirection: 'row', flexWrap: 'wrap', }, tabBarText: { fontSize: Platform.OS == 'android' ? 26 : 24, } }; export default EmojiSelector;
camlahoud/react-native-emoji-input
lib/selector.js
JavaScript
mit
6,921
version https://git-lfs.github.com/spec/v1 oid sha256:07f4bf13ba69118ebd88b07b6c66f211f610acc3cdf0a9322352a6b8100ba3ce size 682
yogeshsaroya/new-cdnjs
ajax/libs/codemirror/3.22.0/addon/selection/active-line.min.js
JavaScript
mit
128
import * as React from 'react'; import {Items,Item,Row,Col,Table,Code} from 'yrui'; let thead=[{ key:'key', value:'参数', },{ key:'expr', value:'说明', },{ key:'type', value:'类型', },{ key:'values', value:'可选值', },{ key:'default', value:'默认值', }]; // let route=[{ key:'url', expr:'路径', type:'string', values:'-', default:'-', },{ key:'component', expr:'页面组件', type:'object|function', values:'-', default:'-', },{ key:'asyncComponent', expr:'按需加载组件', type:'function', values:'-', default:'-', },{ key:'name', expr:'标题', type:'string', values:'-', default:'-', },{ key:'icon', expr:'路由左侧图标', type:'string', values:'-', default:'-', },{ key:'noMenu', expr:'不显示菜单栏', type:'boolean', values:'-', default:'false', },{ key:'noFrame', expr:'不显框架信息', type:'boolean', values:'-', default:'false', },{ key:'child', expr:'子路由', type:'array', values:'-', default:'-', }]; // let brand=[{ key:'logo', expr:'是否在brand上显示logo', type:'string', values:'-', default:'-', },{ key:'title', expr:'标题', type:'string', values:'-', default:'-', },{ key:'subtitle', expr:'副标题', type:'string', values:'-', default:'-', }]; // let navbar=[{ key:'leftNav', expr:'头部左侧内容', type:'array', values:'-', default:'-', },{ key:'rightNav', expr:'头部右侧内容', type:'array', values:'-', default:'-', },{ key:'click', expr:'返回当前点击nav的数据(click(v))', type:'function', values:'-', default:'-', },{ key:'collapse', expr:'左侧菜单栏切换事件', type:'function', values:'-', default:'-', }]; // let leftNav=[{ key:'name', expr:'下拉菜单名', type:'string', values:'-', default:'-', },{ key:'icon', expr:'下拉菜单图标', type:'string', values:'-', default:'-', },{ key:'img', expr:'下拉菜单图标', type:'string', values:'-', default:'-', },{ key:'animate', expr:'下拉菜单动画', type:'string', values:'up/down/left/right', default:'up', },{ key:'msg', expr:'下拉菜单消息提示', type:'string', values:'-', default:'-', },{ key:'drop', expr:'下拉菜单内容', type:'function|string', values:'-', default:'-', },{ key:'url', expr:'菜单链接', type:'string', values:'-', default:'javascript:;', }]; // let sidebar=[{ key:'projectList', expr:'项目列表', type:'array', values:'-', default:'-', },{ key:'showSidebarTitle', expr:'是否隐藏侧边栏title', type:'boolean', values:'true/false', default:'false', },{ key:'userInfo', expr:'用户信息展示', type:'object', values:'-', default:'-', }]; let userinfo=[{ key:'name', expr:'已登陆用户名', type:'string', values:'-', default:'-', },{ key:'logo', expr:'已登陆用户头像', type:'string|object', values:'-', default:'-', },{ key:'email', expr:'已登陆用户邮箱', type:'string', values:'-', default:'-', }]; // let main=[{ key:'showBreadcrumb', expr:'是否显示面包屑', type:'boolean', values:'true/false', default:'true', },{ key:'showPagetitle', expr:'是否显示面包屑上面标题', type:'boolean', values:'true/false', default:'false', }]; // let routers=[{ key:'routers', expr:'路由表', type:'array', values:'-', default:'-', },{ key:'horizontal', expr:'是否为水平菜单栏', type:'boolean', values:'true/false', default:'false', },{ key:'brand', expr:'头部brand配置', type:'object', values:'-', default:'-', },{ key:'navbar', expr:'头部nav配置', type:'object', values:'-', default:'-', },{ key:'main', expr:'主页面头部配置', type:'object', values:'-', default:'-', },{ key:'sidebar', expr:'左侧边栏配置', type:'object', values:'-', default:'-', },{ key:'rightbar', expr:'右侧边栏配置', type:'object|string', values:'-', default:'-', },{ key:'footer', expr:'底部栏配置', type:'object|string', values:'-', default:'-', },{ key:'browserRouter', expr:'是否是真实路径', type:'boolean', values:'true/false', default:'false', },{ key:'routeAnimate', expr:'路由切换动画', type:'string', values:'scale/down/right/no', default:'scale', },{ key:'theme', expr:'用户自定义主题', type:'string', values:'-', default:'-', }]; // let others=[{ key:'rightbar', expr:'右侧边栏', type:'object|string', values:'-', default:'-', },{ key:'footer', expr:'底部栏配置', type:'object|string', values:'-', default:'-', },{ key:'browserRouter', expr:'是否是真实路径', type:'boolean', values:'true/false', default:'false', },{ key:'routeAnimate', expr:'路由切换动画', type:'string', values:'scale/down/right/no', default:'scale', },{ key:'horizontal', expr:'是否为水平菜单栏', type:'boolean', values:'true/false', default:'false', },{ key:'theme', expr:'用户自定义主题', type:'string', values:'-', default:'-', }]; const t=`const app={ brand:{ title:'Phoenix',// subtitle:'UI Demo',// logo:require('./styles/images/usr.jpg'),// }, navbar:{ leftNav:null, rightNav:null, click:(v)=>{console.log(v);},//点击头部菜单事件 collapse:()=>{console.log('collapse');},//左侧菜单栏切换事件 }, sidebar:{ projectList:null,//菜单项目列表,可忽略 showSidebarTitle:false,//显示侧边栏标题 userInfo:null,//用户信息 }, rightbar:'<h2>111</h2>',//右侧边栏component main:{ showBreadcrumb:true,//显示面包屑 showPagetitle:false,//显示头部标题 }, footer:'<p>版权所有 &copy; 2017-2020 Phoenix 团队</p>',//底部栏component routers:sidebarMenu,//侧边栏,路由 routeAnimate:'scale',//路由切换动画,设置为'no'取消动画效果 browserRouter:false,//是否使用真实路径 horizontal:false,//是否为水平菜单栏 theme:'',//用户自定义主题 }; <Router {...app} /> `; export default class Frame extends React.Component { render() { return ( <Items> <Item> <Row> <Col span={12}> <h2>routers配置</h2> <Table thead={thead} tbody={routers} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <div className="txt-area"> <h2>配置</h2> {/*<p>brand navbar sidebar rightbar main</p>*/} <Code title="demo" code={t} /> </div> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>route配置</h2> <Table thead={thead} tbody={route} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>brand配置</h2> <Table thead={thead} tbody={brand} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>navbar配置</h2> <Table thead={thead} tbody={navbar} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>sidebar配置</h2> <Table thead={thead} tbody={sidebar} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>userinfo配置</h2> <Table thead={thead} tbody={userinfo} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>main配置</h2> <Table thead={thead} tbody={main} /> </Col> </Row> <Row gutter={8}> <Col span={12}> <h2>leftNav、leftNav配置</h2> <Table thead={thead} tbody={leftNav} /> </Col> </Row> </Item> </Items> ); } }
ahyiru/phoenix-boilerplate
app/api/frame.js
JavaScript
mit
8,134
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Product = mongoose.model('Product'), multiparty = require('multiparty'), uuid = require('node-uuid'), fs = require('fs'), _ = require('lodash'); /** * Create a Product */ exports.create = function(req, res, next) { var form = new multiparty.Form(); form.parse(req, function(err, fields, files) { var file = files.file[0]; var contentType = file.headers['content-type']; var tmpPath = file.path; var extIndex = tmpPath.lastIndexOf('.'); var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex); // uuid is for generating unique filenames. var fileName = uuid.v4() + extension; var destPath = '/home/blaze/Sites/github/yaltashop/uploads/' + fileName; //fs.rename(tmpPath, destPath, function(err) { if (err) { console.log('there was an error during saving file'); next(err); } var product = new Product(fields); file.name = file.originalFilename; product.photo.file = file; product.user = req.user; product.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); //}); }); }; /** * Show the current Product */ exports.read = function(req, res) { res.jsonp(req.product); }; /** * Update a Product */ exports.update = function(req, res) { var product = req.product ; product = _.extend(product , req.body); product.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); }; /** * Delete an Product */ exports.delete = function(req, res) { var product = req.product ; product.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); }; /** * List of Products */ exports.list = function(req, res) { Product.find().sort('-created').populate('user', 'displayName').exec(function(err, products) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(products); } }); }; /** * Product middleware */ exports.productByID = function(req, res, next, id) { Product.findById(id).populate('user', 'displayName').exec(function(err, product) { if (err) return next(err); if (! product) return next(new Error('Failed to load Product ' + id)); req.product = product ; next(); }); }; /** * Product authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.product.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
B1aZer/yaltatoys
app/controllers/products.server.controller.js
JavaScript
mit
2,922
/*! jQuery UI - v1.10.4 - 2018-06-10 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional["en-GB"]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional["en-GB"])});
yeahsmaggy/Slim-Tour-CMS
public/css/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-en-GB.min.js
JavaScript
mit
806
var mongoose = require('mongoose'); var BaseModel = require("./base_model"); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var UserFollowSchema = new Schema({ user_id: { type: ObjectId }, kind: { type: String }, object_id: { type: ObjectId }, create_at: { type: Date, default: Date.now } }); UserFollowSchema.plugin(BaseModel); UserFollowSchema.index({user_id: 1, object_id: 1}, {unique: true}); mongoose.model('UserFollow', UserFollowSchema);
493326889/imwebclub
server/models/user_follow.js
JavaScript
mit
476
'use strict' const path = require('path') const webpack = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') const ManifestPlugin = require('webpack-manifest-plugin') const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin') const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin') const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin') const paths = require('./paths') const getClientEnvironment = require('./env') // Webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. const publicPath = paths.servedPath // Some apps do not use client-side routing with pushState. // For these, "homepage" can be set to "." to enable relative asset paths. const shouldUseRelativeAssetPaths = publicPath === './' // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. const publicUrl = publicPath.slice(0, -1) // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl) // Assert this just to be safe. // Development builds of React are slow and not intended for production. if (env.stringified['process.env'].NODE_ENV !== '"production"') { throw new Error('Production builds must have NODE_ENV=production.') } // Note: defined here because it will be used more than once. const cssFilename = 'static/css/[name].[contenthash:8].css' // ExtractTextPlugin expects the build output to be flat. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27) // However, our output is structured with css, js and media folders. // To have this structure working with relative paths, we have to use custom options. const extractTextPluginOptions = shouldUseRelativeAssetPaths // Making sure that the publicPath goes back to to build folder. ? { publicPath: Array(cssFilename.split('/').length).join('../') } : {} // This is the production configuration. // It compiles slowly and is focused on producing a fast and minimal bundle. // The development configuration is different and lives in a separate file. module.exports = { // Don't attempt to continue if there are any errors. bail: true, // We generate sourcemaps in production. This is slow but gives good results. // You can exclude the *.map files from the build during deployment. devtool: 'source-map', // In production, we only want to load the polyfills and the app code. entry: [require.resolve('./polyfills'), paths.appIndexJs], output: { // The build folder. path: paths.appBuild, // Generated JS file names (with nested folders). // There will be one main bundle, and one file per asynchronous chunk. // We don't currently advertise code splitting but Webpack supports it. filename: 'static/js/[name].[chunkhash:8].js', chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', // We inferred the "public path" (such as / or /my-project) from homepage. publicPath: publicPath, // Point sourcemap entries to original disk location devtoolModuleFilenameTemplate: info => path.relative(paths.appSrc, info.absoluteResourcePath) }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We placed these paths second because we want `node_modules` to "win" // if there are any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 modules: ['node_modules', paths.appNodeModules].concat( // It is guaranteed to exist because we tweak it in `env.js` process.env.NODE_PATH.split(path.delimiter).filter(Boolean) ), // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 extensions: ['.js', '.json', '.jsx'], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', Components: path.resolve(__dirname, '../src/components'), Util: path.resolve(__dirname, '../src/util'), Actions: path.resolve(__dirname, '../src/actions'), Selectors: path.resolve(__dirname, '../src/selectors') }, plugins: [ // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc) ] }, module: { strictExportPresence: true, rules: [ // TODO: Disable require.ensure as it's not a standard language feature. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. // { parser: { requireEnsure: false } }, // First, run the linter. // It's important to do this before Babel processes the JS. { test: /\.(js|jsx)$/, enforce: 'pre', loader: 'standard-loader', options: { error: true }, include: paths.appSrc }, // ** ADDING/UPDATING LOADERS ** // The "file" loader handles all assets unless explicitly excluded. // The `exclude` list *must* be updated with every change to loader extensions. // When adding a new loader, you must add its `test` // as a new entry in the `exclude` list in the "file" loader. // "file" loader makes sure those assets end up in the `build` folder. // When you `import` an asset, you get its filename. { exclude: [ /\.html$/, /\.(js|jsx)$/, /\.css$/, /\.scss$/, /\.json$/, /\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/ ], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash:8].[ext]' } }, // "url" loader works just like "file" loader but it also embeds // assets smaller than specified size as data URLs to avoid requests. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } }, // Process JS with Babel. { test: /\.(js|jsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader') }, // The notation here is somewhat confusing. // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader normally turns CSS into JS modules injecting <style>, // but unlike in development configuration, we do something different. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders // (second argument), then grabs the result CSS and puts it into a // separate file in our build process. This way we actually ship // a single CSS file in production instead of JS code injecting <style> // tags. If you use code splitting, however, any async bundles will still // use the "style" loader inside the async code so CSS from them won't be // in the main CSS file. { test: /\.css$/, loader: ExtractTextPlugin.extract( Object.assign( { fallback: require.resolve('style-loader'), use: [ { loader: require.resolve('css-loader'), options: { importLoaders: 1, minimize: true, sourceMap: true } } // { // loader: require.resolve('postcss-loader'), // options: { // ident: 'postcss', // https://webpack.js.org/guides/migrating/#complex-options // plugins: () => [ // require('postcss-flexbugs-fixes'), // autoprefixer({ // browsers: [ // '>1%', // 'last 4 versions', // 'Firefox ESR', // 'not ie < 9', // React doesn't support IE8 anyway // ], // flexbox: 'no-2009', // }), // ], // }, // }, ] }, extractTextPluginOptions ) ) // Note: this won't work without `new ExtractTextPlugin()` in `plugins`. } // ** STOP ** Are you adding a new loader? // Remember to add the new extension(s) to the "file" loader exclusion list. ] }, plugins: [ // Makes some environment variables available in index.html. // The public URL is available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In production, it will be an empty string unless you specify "homepage" // in `package.json`, in which case it will be the pathname of that URL. new InterpolateHtmlPlugin(env.raw), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true } }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. // It is absolutely essential that NODE_ENV was set to production here. // Otherwise React will be compiled in the very slow development mode. new webpack.DefinePlugin(env.stringified), // Minify the code. new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, // This feature has been reported as buggy a few times, such as: // https://github.com/mishoo/UglifyJS2/issues/1964 // We'll wait with enabling it by default until it is more solid. reduce_vars: false }, output: { comments: false }, sourceMap: true }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. new ExtractTextPlugin({ filename: cssFilename }), // Generate a manifest file which contains a mapping of all asset filenames // to their corresponding output file so that tools can pick it up without // having to parse `index.html`. new ManifestPlugin({ fileName: 'asset-manifest.json' }), // Generate a service worker script that will precache, and keep up to date, // the HTML & assets that are part of the Webpack build. new SWPrecacheWebpackPlugin({ // By default, a cache-busting query parameter is appended to requests // used to populate the caches, to ensure the responses are fresh. // If a URL is already hashed by Webpack, then there is no concern // about it being stale, and the cache-busting can be skipped. dontCacheBustUrlsMatching: /\.\w{8}\./, filename: 'service-worker.js', logger (message) { if (message.indexOf('Total precache size is') === 0) { // This message occurs for every build and is a bit too noisy. return } console.log(message) }, minify: true, navigateFallback: publicUrl + '/index.html', staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/], // Work around Windows path issue in SWPrecacheWebpackPlugin: // https://github.com/facebookincubator/create-react-app/issues/2235 stripPrefix: paths.appBuild.replace(/\\/g, '/') + '/' }), // Moment.js is an extremely popular library that bundles large locale files // by default due to how Webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack // You can remove this if you don't use Moment.js: new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { fs: 'empty', net: 'empty', tls: 'empty' } }
antoinechalifour/Reddix
config/webpack.config.prod.js
JavaScript
mit
13,420
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { color :pink }", description: "space only before", }, { code: "a { color : pink }", description: "space before and after", }, { code: "a { color :\npink }", description: "space before and newline after", }, { code: "a { color :\r\npink }", description: "space before and CRLF after", }, { code: "$map:(key:value)", description: "SCSS map with no newlines", }, { code: "$list:('value1', 'value2')", description: "SCSS list with no newlines", }, { code: "a { background : url(data:application/font-woff;...); }", description: "data URI", } ], reject: [ { code: "a { color: pink; }", description: "no space before", message: messages.expectedBefore(), line: 1, column: 11, }, { code: "a { color : pink; }", description: "two spaces before", message: messages.expectedBefore(), line: 1, column: 11, }, { code: "a { color\t: pink; }", description: "tab before", message: messages.expectedBefore(), line: 1, column: 11, }, { code: "a { color\n: pink; }", description: "newline before", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { color\r\n: pink; }", description: "CRLF before", message: messages.expectedBefore(), line: 1, column: 11, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { color:pink }", description: "no space before and after", }, { code: "a { color: pink }", description: "no space before and space after", }, { code: "a { color:\npink }", description: "no space before and newline after", }, { code: "a { color:\r\npink }", description: "no space before and CRLF after", }, { code: "$map :(key :value)", description: "SCSS map with no newlines", } ], reject: [ { code: "a { color : pink; }", description: "space before", message: messages.rejectedBefore(), line: 1, column: 11, }, { code: "a { color : pink; }", description: "two spaces before", message: messages.rejectedBefore(), line: 1, column: 11, }, { code: "a { color\t: pink; }", description: "tab before", message: messages.rejectedBefore(), line: 1, column: 11, }, { code: "a { color\n: pink; }", description: "newline before", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { color\r\n: pink; }", description: "CRLF before", message: messages.rejectedBefore(), line: 1, column: 11, } ], })
hudochenkov/stylelint
lib/rules/declaration-colon-space-before/__tests__/index.js
JavaScript
mit
2,837
var scene; var camera; var renderer; var stats; var geometry; var material; var line; var ambientLight; var loader; var cow; var cowMixer; var walkCow; var walkCowMixer; var cowStatus = "walkings"; // none standing walking cowCur = "walking"; // standing var milk; var loopAnim; var loopFallMilk; // 循环滴落奶 var grass; var grassMixer; var grass2; var grass3; var grassList = [ { mesh: undefined, x: 300, y: 120, z: -50 }, { mesh: undefined, x: -160, y: 120, z: -300 }, { mesh: undefined, x: 200, y: 120, z: -600 }, { mesh: undefined, x: -400, y: 120, z: -1400 }, ] var clock = new THREE.Clock(); var webglContainer = document.getElementById('webgl-container'); var $cowNaz = $('#cow-naz'); var milkBoxStatus = 0; // 装满级别 1 2 3 var milkBoxLoading = false; var timeHandle; var cowFile; var walkCowFile; var grassFile; // 函数定义--------------------------------- function init() { var scalePoint = 1; var animations; var animation; //- 创建场景 scene = new THREE.Scene(); //- 创建相机 camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000000 ); camera.position.z = 550; camera.position.y = 380; camera.position.x = 30; // camera.lookAt(scene.position); //- 渲染 renderer = new THREE.WebGLRenderer({antialias: false, alpha: true}); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.domElement.className = 'webgl-container'; webglContainer.appendChild(renderer.domElement); // - 平面坐標系 var CoSystem = new THREEex.CoSystem(500, 50, 0x000000); line = CoSystem.create(); scene.add(line); //- gltf 3d模型导入 loader = new THREE.GLTFLoader(); loader.setCrossOrigin('https://ossgw.alicdn.com'); var shanurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/51ff6704e19375613c3d4d3563348b7f.gltf'; var grassurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/5e6c2c4bb052ef7562b52654c5635127.gltf' var bburl = 'https://ossgw.alicdn.com/tmall-c3/tmx/7554d11d494d79413fc665e9ef140aa6.gltf' // var walkCowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/3972247d3c4e96d1ac7e83a173e3a331.gltf'; // 1 // var walkCowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/95628df6d8a8dc3adc3c41b97ba2e49c.gltf'; // 2 var walkCowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/15e972f4cc71db07fee122da7a125e5b.gltf'; // 3 var cowurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/2f17ddef947a7b6c702af69ff0e5b95f.gltf'; var doorurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/203247ec660952407695fdfaf45812af.gltf'; var demourl = 'https://ossgw.alicdn.com/tmall-c3/tmx/25ed65d4e9684567962230671512f731.gltf' var lanurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/1e1dfc4da8dfe2d7f14f23f0996c7feb.gltf' var daiurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/e68183de37ea4bed1787f6051b1d1f94.gltf' var douurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/0ca2926cbf4bc664ff00b03c1a5d1f66.gltf' var fishurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/03807648cf70d99a7c1d3d634a2d4ea3.gltf'; var fishActiveurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/bb90ddfe2542267c142e892ab91f60ad.gltf'; var fishBowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/c5e934aae17373e927fe98aaf1f71767.gltf' // cow // loader.load(cowurl, function(data) { // var scalePoint = 1; // var animations; // var animation; // gltf = data; // cow = gltf.scene; // cow.position.set(650, 240, 180); // // cow.position.set(0, 0, -240); // cow.rotation.y = -Math.PI / 2; // cow.scale.set(scalePoint, scalePoint, scalePoint); // animations = data.animations; // if (animations && animations.length) { // cowMixer = new THREE.AnimationMixer(cow); // for (var i = 0; i < animations.length; i++) { // var animation = animations[i]; // cowMixer.clipAction(animation).play(); // } // } // // scene.add(cow); // }) cow = cowFile.scene; cow.position.set(650, 240, 180); // cow.position.set(0, 0, -240); cow.rotation.y = -Math.PI / 2; cow.scale.set(scalePoint, scalePoint, scalePoint); animations = cowFile.animations; if (animations && animations.length) { cowMixer = new THREE.AnimationMixer(cow); for (var i = 0; i < animations.length; i++) { var animation = animations[i]; cowMixer.clipAction(animation).play(); } } // loader.load(walkCowUrl, function(data) { // var scalePoint = 1; // var animations; // var animation; // gltf = data; // walkCow = gltf.scene; // walkCow.position.set(650, 240, 180); // walkCow.rotation.y = -Math.PI / 2; // walkCow.scale.set(scalePoint, scalePoint, scalePoint); // animations = data.animations; // if (animations && animations.length) { // walkCowMixer = new THREE.AnimationMixer(walkCow); // for (var i = 0; i < animations.length; i++) { // var animation = animations[i]; // walkCowMixer.clipAction(animation).play(); // } // } // scene.add(walkCow); // cowWalkIn(); // }) walkCow = walkCowFile.scene; walkCow.position.set(650, 240, 180); walkCow.rotation.y = -Math.PI / 2; walkCow.scale.set(scalePoint, scalePoint, scalePoint); animations = walkCowFile.animations; if (animations && animations.length) { walkCowMixer = new THREE.AnimationMixer(walkCow); for (var i = 0; i < animations.length; i++) { var animation = animations[i]; walkCowMixer.clipAction(animation).play(); } } scene.add(walkCow); cowWalkIn(); // loader.load(grassurl, function(data) { // var scalePoint = .005; // var animations; // var animation; // gltf = data; // grass = gltf.scene; // window.wgrass = grass; // grass.scale.set(scalePoint, scalePoint, scalePoint); // for (var i = grassList.length - 1; i >= 0; i--) { // grassList[i].mesh = grass.clone(); // grassList[i].mesh.position.set(grassList[i].x, grassList[i].y, grassList[i].z) // scene.add(grassList[i].mesh); // } // // 草从小变大 // new TWEEN.Tween({scalePoint: .01}) // .to({scalePoint: .4}, 2000) // .onUpdate(function() { // // console.log('scalePoint loop: ', this); // var scalePoint = this.scalePoint; // for (var i = grassList.length - 1; i >= 0; i--) { // grassList[i].mesh.scale.set(scalePoint, scalePoint, scalePoint); // } // }) // .start(); // new TWEEN.Tween(this) // .to({}, 4000) // .onUpdate(function() { // render(); // }) // .start(); // }) scalePoint = 0.005; grass = grassFile.scene; grass.scale.set(scalePoint, scalePoint, scalePoint); for (var i = grassList.length - 1; i >= 0; i--) { grassList[i].mesh = grass.clone(); grassList[i].mesh.position.set(grassList[i].x, grassList[i].y, grassList[i].z) scene.add(grassList[i].mesh); } // 草从小变大 new TWEEN.Tween({scalePoint: .01}) .to({scalePoint: .4}, 2000) .onUpdate(function() { // console.log('scalePoint loop: ', this); var scalePoint = this.scalePoint; for (var i = grassList.length - 1; i >= 0; i--) { grassList[i].mesh.scale.set(scalePoint, scalePoint, scalePoint); } }) .start(); new TWEEN.Tween(this) .to({}, 4000) .onUpdate(function() { render(); }) .start(); //- 环境灯 ambientLight = new THREE.AmbientLight(0xffffff); scene.add(ambientLight); //- 直射灯 // var directionalLight = new THREE.DirectionalLight( 0xdddddd ); // directionalLight.position.set( 0, 0, 1 ).normalize(); // scene.add( directionalLight ); // //- 点灯 // var light = new THREE.PointLight(0xFFFFFF); // light.position.set(50000, 50000, 50000); // scene.add(light); //- 绑定窗口大小,自适应 var threeexResize = new THREEex.WindowResize(renderer, camera); //- threejs 的控制器 // var controls = new THREE.OrbitControls( camera, renderer.domElement ); // controls.target = new THREE.Vector3(0,15,0); //- controls.maxPolarAngle = Math.PI / 2; //- controls.addEventListener( 'change', function() { renderer.render(scene, camera); } ); // add this only if there is no animation loop (requestAnimationFrame) // 监听挤奶事件 $cowNaz.on('click', function() { console.log('click naz', milkBoxLoading); if (milkBoxLoading === true) return; milkBoxLoading = true; milkBoxStatus++; // console.log('click milk', milkBoxStatus); // addMilk(); addMilk2(); startFallMilk(); }) } // 显示空白瓶子 function showEmptyMilk() { var $milkBox = $('.milkbox'); $milkBox.animate({ bottom: '-140px' }, 2000); } // 显示挤奶那妞 function showCowNaz() { $cowNaz.show(); } // showCowNaz(); // showEmptyMilk(); function cowWalkIn() { cowStatus = 'walking'; // 头部先进 最后到 var headIn = new TWEEN.Tween(walkCow.position) .to({ x: 320 }, 6000) .delay(1000) // .easing(TWEEN.Easing.Exponential.InOut) var legIn = new TWEEN.Tween(walkCow.position) .to({ x: -250 }, 3500) .onComplete(function() { cowStatus = 'standing' }) .delay(2000); var downCamera = new TWEEN.Tween(camera.position) .to({ z: 540, y: 250, x: 0 }, 1000) .easing(TWEEN.Easing.Exponential.InOut) .onStart(function() { showEmptyMilk(); }) .onComplete(function() { showCowNaz() }) legIn.chain(downCamera); headIn.chain(legIn); headIn.start(); new TWEEN.Tween(this) .to({}, 4000 * 2) .onUpdate(function() { render(); }) .start(); } // 合并图挤奶 function addMilk2() { var anim; var milkID = '#milkbox' + milkBoxStatus; $('.milkbox').addClass('hide'); $('' + milkID).removeClass('hide'); if (loopAnim) { loopAnim.stop(); } anim = frameAnimation.anims($('' + milkID), 5625, 25, 2, 1, function() { if (milkBoxStatus === 3) { $('.milkbox').hide(); $('#milkink').hide(); $cowNaz.hide(); showJinDian(); } if (milkBoxStatus !== 3) { loopMilk(); } stopFallMilk(); milkBoxLoading = false; }); anim.start(); } // 循环播放最后8帧 function loopMilk() { var milkID = '#milkbox' + milkBoxStatus; if (loopAnim) { loopAnim.stop(); } console.log('loopMilk:', milkID); loopAnim = frameAnimation.anims($('' + milkID), 5625, 25, 3, 0, function() {}, 18); loopAnim.start(); } // 滴落奶 function startFallMilk() { $('#milkink').removeClass('hide'); if (!loopFallMilk) { loopFallMilk = frameAnimation.anims($('#milkink'), 1875, 25, 1, 0); } loopFallMilk.start(); } window.startFallMilk = startFallMilk; function stopFallMilk() { $('#milkink').addClass('hide'); loopFallMilk.stop(true); } function showJinDian() { TWEEN.removeAll(); new TWEEN.Tween(camera.position) .to({ z: 4000 }, 4000) .onUpdate(function() { var op = 1 - this.z / 4000; $(webglContainer).css({opacity: op}); render(); }) .onComplete(function() { var $milk = $("#milk"); $(webglContainer).hide(); $milk.animate({'bottom': '250px'}, 600); }) .start(); } function animate() { requestAnimationFrame(animate); // camera.lookAt(scene.position); if (cowStatus === 'walking' && cowCur !== 'walking') { walkCow.position = cow.position; scene.add(walkCow); scene.remove(cow); cowCur = 'walking' } if (cowStatus === 'standing' && cowCur !== 'standing') { // console.log('walkCow.position:', walkCow.position, cow.position); cow.position = walkCow.position; cow.position.x = walkCow.position.x; cow.position.y = walkCow.position.y; cow.position.z = walkCow.position.z; scene.add(cow); scene.remove(walkCow); cowCur = 'standing'; // console.log('walkCow.position:', walkCow.position, cow.position); } if (cowMixer && cowCur === 'standing') { cowMixer.update(clock.getDelta()); } if (walkCowMixer && cowCur === 'walking') { walkCowMixer.update(clock.getDelta()); } TWEEN.update(); // stats.begin(); render(); // stats.end(); } //- 循环体-渲染 function render() { renderer.render( scene, camera ); } // 加载图片 function preLoadImg(url) { var def = $.Deferred(); var img = new Image(); img.src = url; if (img.complete) { def.resolve({ img: img, url: url }) } img.onload = function() { def.resolve({ img: img, url: url }); } img.onerror = function() { def.resolve({ img: null, url: url }) } return def.promise(); } // 加载单张图片 function loadImage(url, callback) { var img = new Image(); //创建一个Image对象,实现图片的预下载 img.src = url; if (img.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数 callback.call(img); return; // 直接返回,不用再处理onload事件 } img.onload = function () { //图片下载完毕时异步调用callback函数。 callback.call(img);//将回调函数的this替换为Image对象 }; } // 加载所有图片 function loadAllImage(imgList) { var defList = []; var i = 0; var len; var def = $.Deferred(); for (i = 0, len = imgList.length; i < len; i++) { defList[i] = preLoadImg(imgList[i]) } $.when.apply(this, defList) .then(function() { var retData = Array.prototype.slice.apply(arguments); def.resolve(retData); }) return def.promise(); } // 隐藏加载 function hideLoading() { $('#loading').hide(); } // 3d模型def 加载 function loadGltf(url) { var def = $.Deferred(); var loader = new THREE.GLTFLoader(); loader.setCrossOrigin('https://ossgw.alicdn.com'); loader.load(url, function(data) { def.resolve(data); }) return def.promise(); } // 加载所有3d模型 function loadAllGltf(list) { var defList = []; var i = 0; var len; var def = $.Deferred(); for (i = 0, len = list.length; i < len; i++) { defList[i] = loadGltf(list[i]) } $.when.apply(this, defList) .then(function() { var retData = Array.prototype.slice.apply(arguments); def.resolve(retData); }) return def.promise(); } // 加载雪山 function loadCowGltf() { var def = $.Deferred(); var shanurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/51ff6704e19375613c3d4d3563348b7f.gltf'; var grassurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/5e6c2c4bb052ef7562b52654c5635127.gltf' var bburl = 'https://ossgw.alicdn.com/tmall-c3/tmx/7554d11d494d79413fc665e9ef140aa6.gltf' // var walkCowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/3972247d3c4e96d1ac7e83a173e3a331.gltf'; // 1 var walkCowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/95628df6d8a8dc3adc3c41b97ba2e49c.gltf'; // 2 // var walkCowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/15e972f4cc71db07fee122da7a125e5b.gltf'; // 3 var cowurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/2f17ddef947a7b6c702af69ff0e5b95f.gltf'; var doorurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/203247ec660952407695fdfaf45812af.gltf'; var demourl = 'https://ossgw.alicdn.com/tmall-c3/tmx/25ed65d4e9684567962230671512f731.gltf' var lanurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/1e1dfc4da8dfe2d7f14f23f0996c7feb.gltf' var daiurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/e68183de37ea4bed1787f6051b1d1f94.gltf' var douurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/0ca2926cbf4bc664ff00b03c1a5d1f66.gltf' var fishurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/03807648cf70d99a7c1d3d634a2d4ea3.gltf'; var fishActiveurl = 'https://ossgw.alicdn.com/tmall-c3/tmx/bb90ddfe2542267c142e892ab91f60ad.gltf'; var fishBowUrl = 'https://ossgw.alicdn.com/tmall-c3/tmx/c5e934aae17373e927fe98aaf1f71767.gltf' $.when(loadGltf(cowurl), loadGltf(walkCowUrl), loadGltf(grassurl)) .then(function(cowData, walkCowData, grassData) { cowFile = cowData; walkCowFile = walkCowData; grassFile = grassData def.resolve([cowurl, walkCowUrl, grassurl]); }) return def.promise(); } // 函数定义--------------------------------- // 开始----------------------- var imgList = [ '/threejs/static/img/canvas_milk_out.png', '/threejs/static/img/canvas_milk1.png', '/threejs/static/img/canvas_milk2.png', '/threejs/static/img/canvas_milk3.png', '/threejs/static/img/box.png', '/threejs/static/img/fly.png' ] loadAllImage(imgList) .then(function(imgData) { loadCowGltf() .then(function(gltfdata) { hideLoading(); main(); }) }) function main() { init(); animate(); } // 开始-----------------------
chenjsh36/ThreeJSForFun
threejs_gallary/front/src/script/canvas_cow_game_cow2url.js
JavaScript
mit
18,316
version https://git-lfs.github.com/spec/v1 oid sha256:012c0c10efb1958941ed2fd9f393df39f1ae6f76369bf56e500e39ade0496295 size 8392
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/widget/widget-min.js
JavaScript
mit
129
/** * Инициализация модуля. */ /*global define*/ define(['./poke-control', './poke-history', 'jquery'], function (pokeControl, pokeHistory, $) { 'use strict'; var pokeSettings = { pokeControl: { selector: '.poke-control-container', template: '<form class="form"><div class="form-group"><label for="bdoChannel">Канал:</label><select class="form-control" name="bdoChannel" id="bdoChannel"></select></div><div class="form-group"><label for="bdoQuest">Квест:</label><select class="form-control" name="bdoQuest" id="bdoQuest"></select></div><button class="btn btn-success">Отправить</button></form>' }, pokeHistory: { selector: '.poke-history-container', template: '<table id="eventsHistory" class="table table-condensed table-hover table-striped"><thead><tr><th data-column-id="startDate">Начало</th><th data-column-id="channel" data-type="numeric">Канал</th><th data-column-id="event">Событие</th></tr></thead></table>', tableSelector: '#eventsHistory' } }, create; create = function (options) { pokeSettings = $.extend(pokeSettings, options); pokeControl.initialize(pokeSettings.pokeControl); pokeHistory.initialize(pokeSettings.pokeHistory); }; return { create: create }; });
inngvar/planner
js-plugin/js/bdo-poke.js
JavaScript
mit
1,436
var list = { "Manual": { "Getting Started": { "Creating a scene": "manual/introduction/Creating-a-scene", "Import via modules": "manual/introduction/Import-via-modules", "Browser support": "manual/introduction/Browser-support", "WebGL compatibility check": "manual/introduction/WebGL-compatibility-check", "How to run things locally": "manual/introduction/How-to-run-things-locally", "Drawing Lines": "manual/introduction/Drawing-lines", "Creating Text": "manual/introduction/Creating-text", "Migration Guide": "manual/introduction/Migration-guide", "Code Style Guide": "manual/introduction/Code-style-guide", "FAQ": "manual/introduction/FAQ", "Useful links": "manual/introduction/Useful-links" }, "Next Steps": { "How to update things": "manual/introduction/How-to-update-things", "Matrix transformations": "manual/introduction/Matrix-transformations", "Animation System": "manual/introduction/Animation-system" }, "Build Tools": { "Testing with NPM": "manual/buildTools/Testing-with-NPM" } }, "Reference": { "Animation": { "AnimationAction": "api/animation/AnimationAction", "AnimationClip": "api/animation/AnimationClip", "AnimationMixer": "api/animation/AnimationMixer", "AnimationObjectGroup": "api/animation/AnimationObjectGroup", "AnimationUtils": "api/animation/AnimationUtils", "KeyframeTrack": "api/animation/KeyframeTrack", "PropertyBinding": "api/animation/PropertyBinding", "PropertyMixer": "api/animation/PropertyMixer" }, "Animation / Tracks": { "BooleanKeyframeTrack": "api/animation/tracks/BooleanKeyframeTrack", "ColorKeyframeTrack": "api/animation/tracks/ColorKeyframeTrack", "NumberKeyframeTrack": "api/animation/tracks/NumberKeyframeTrack", "QuaternionKeyframeTrack": "api/animation/tracks/QuaternionKeyframeTrack", "StringKeyframeTrack": "api/animation/tracks/StringKeyframeTrack", "VectorKeyframeTrack": "api/animation/tracks/VectorKeyframeTrack" }, "Audio": { "Audio": "api/audio/Audio", "AudioAnalyser": "api/audio/AudioAnalyser", "AudioContext": "api/audio/AudioContext", "AudioListener": "api/audio/AudioListener", "PositionalAudio": "api/audio/PositionalAudio" }, "Cameras": { "Camera": "api/cameras/Camera", "CubeCamera": "api/cameras/CubeCamera", "OrthographicCamera": "api/cameras/OrthographicCamera", "PerspectiveCamera": "api/cameras/PerspectiveCamera", "StereoCamera": "api/cameras/StereoCamera" }, "Constants": { "Animation": "api/constants/Animation", "Core": "api/constants/Core", "CustomBlendingEquation": "api/constants/CustomBlendingEquations", "DrawModes": "api/constants/DrawModes", "Materials": "api/constants/Materials", "Renderer": "api/constants/Renderer", "Textures": "api/constants/Textures" }, "Core": { "BufferAttribute": "api/core/BufferAttribute", "BufferGeometry": "api/core/BufferGeometry", "Clock": "api/core/Clock", "DirectGeometry": "api/core/DirectGeometry", "EventDispatcher": "api/core/EventDispatcher", "Face3": "api/core/Face3", "Geometry": "api/core/Geometry", "InstancedBufferAttribute": "api/core/InstancedBufferAttribute", "InstancedBufferGeometry": "api/core/InstancedBufferGeometry", "InstancedInterleavedBuffer": "api/core/InstancedInterleavedBuffer", "InterleavedBuffer": "api/core/InterleavedBuffer", "InterleavedBufferAttribute": "api/core/InterleavedBufferAttribute", "Layers": "api/core/Layers", "Object3D": "api/core/Object3D", "Raycaster": "api/core/Raycaster", "Uniform": "api/core/Uniform" }, "Core / BufferAttributes": { "BufferAttribute Types": "api/core/bufferAttributeTypes/BufferAttributeTypes" }, "Deprecated": { "DeprecatedList": "api/deprecated/DeprecatedList" }, "Extras": { "Earcut": "api/extras/Earcut", "ShapeUtils": "api/extras/ShapeUtils" }, "Extras / Core": { "Curve": "api/extras/core/Curve", "CurvePath": "api/extras/core/CurvePath", "Font": "api/extras/core/Font", "Interpolations": "api/extras/core/Interpolations", "Path": "api/extras/core/Path", "Shape": "api/extras/core/Shape", "ShapePath": "api/extras/core/ShapePath" }, "Extras / Curves": { "ArcCurve": "api/extras/curves/ArcCurve", "CatmullRomCurve3": "api/extras/curves/CatmullRomCurve3", "CubicBezierCurve": "api/extras/curves/CubicBezierCurve", "CubicBezierCurve3": "api/extras/curves/CubicBezierCurve3", "EllipseCurve": "api/extras/curves/EllipseCurve", "LineCurve": "api/extras/curves/LineCurve", "LineCurve3": "api/extras/curves/LineCurve3", "QuadraticBezierCurve": "api/extras/curves/QuadraticBezierCurve", "QuadraticBezierCurve3": "api/extras/curves/QuadraticBezierCurve3", "SplineCurve": "api/extras/curves/SplineCurve" }, "Extras / Objects": { "ImmediateRenderObject": "api/extras/objects/ImmediateRenderObject", }, "Geometries": { "BoxBufferGeometry": "api/geometries/BoxBufferGeometry", "BoxGeometry": "api/geometries/BoxGeometry", "CircleBufferGeometry": "api/geometries/CircleBufferGeometry", "CircleGeometry": "api/geometries/CircleGeometry", "ConeBufferGeometry": "api/geometries/ConeBufferGeometry", "ConeGeometry": "api/geometries/ConeGeometry", "CylinderBufferGeometry": "api/geometries/CylinderBufferGeometry", "CylinderGeometry": "api/geometries/CylinderGeometry", "DodecahedronBufferGeometry": "api/geometries/DodecahedronBufferGeometry", "DodecahedronGeometry": "api/geometries/DodecahedronGeometry", "EdgesGeometry": "api/geometries/EdgesGeometry", "ExtrudeBufferGeometry": "api/geometries/ExtrudeBufferGeometry", "ExtrudeGeometry": "api/geometries/ExtrudeGeometry", "IcosahedronBufferGeometry": "api/geometries/IcosahedronBufferGeometry", "IcosahedronGeometry": "api/geometries/IcosahedronGeometry", "LatheBufferGeometry": "api/geometries/LatheBufferGeometry", "LatheGeometry": "api/geometries/LatheGeometry", "OctahedronBufferGeometry": "api/geometries/OctahedronBufferGeometry", "OctahedronGeometry": "api/geometries/OctahedronGeometry", "ParametricBufferGeometry": "api/geometries/ParametricBufferGeometry", "ParametricGeometry": "api/geometries/ParametricGeometry", "PlaneBufferGeometry": "api/geometries/PlaneBufferGeometry", "PlaneGeometry": "api/geometries/PlaneGeometry", "PolyhedronBufferGeometry": "api/geometries/PolyhedronBufferGeometry", "PolyhedronGeometry": "api/geometries/PolyhedronGeometry", "RingBufferGeometry": "api/geometries/RingBufferGeometry", "RingGeometry": "api/geometries/RingGeometry", "ShapeBufferGeometry": "api/geometries/ShapeBufferGeometry", "ShapeGeometry": "api/geometries/ShapeGeometry", "SphereBufferGeometry": "api/geometries/SphereBufferGeometry", "SphereGeometry": "api/geometries/SphereGeometry", "TetrahedronBufferGeometry": "api/geometries/TetrahedronBufferGeometry", "TetrahedronGeometry": "api/geometries/TetrahedronGeometry", "TextBufferGeometry": "api/geometries/TextBufferGeometry", "TextGeometry": "api/geometries/TextGeometry", "TorusBufferGeometry": "api/geometries/TorusBufferGeometry", "TorusGeometry": "api/geometries/TorusGeometry", "TorusKnotBufferGeometry": "api/geometries/TorusKnotBufferGeometry", "TorusKnotGeometry": "api/geometries/TorusKnotGeometry", "TubeBufferGeometry": "api/geometries/TubeBufferGeometry", "TubeGeometry": "api/geometries/TubeGeometry", "WireframeGeometry": "api/geometries/WireframeGeometry" }, "Helpers": { "ArrowHelper": "api/helpers/ArrowHelper", "AxesHelper": "api/helpers/AxesHelper", "BoxHelper": "api/helpers/BoxHelper", "Box3Helper": "api/helpers/Box3Helper", "CameraHelper": "api/helpers/CameraHelper", "DirectionalLightHelper": "api/helpers/DirectionalLightHelper", "FaceNormalsHelper": "api/helpers/FaceNormalsHelper", "GridHelper": "api/helpers/GridHelper", "PolarGridHelper": "api/helpers/PolarGridHelper", "HemisphereLightHelper": "api/helpers/HemisphereLightHelper", "PlaneHelper": "api/helpers/PlaneHelper", "PointLightHelper": "api/helpers/PointLightHelper", "RectAreaLightHelper": "api/helpers/RectAreaLightHelper", "SkeletonHelper": "api/helpers/SkeletonHelper", "SpotLightHelper": "api/helpers/SpotLightHelper", "VertexNormalsHelper": "api/helpers/VertexNormalsHelper" }, "Lights": { "AmbientLight": "api/lights/AmbientLight", "DirectionalLight": "api/lights/DirectionalLight", "HemisphereLight": "api/lights/HemisphereLight", "Light": "api/lights/Light", "PointLight": "api/lights/PointLight", "RectAreaLight": "api/lights/RectAreaLight", "SpotLight": "api/lights/SpotLight" }, "Lights / Shadows": { "DirectionalLightShadow": "api/lights/shadows/DirectionalLightShadow", "LightShadow": "api/lights/shadows/LightShadow", "SpotLightShadow": "api/lights/shadows/SpotLightShadow" }, "Loaders": { "AnimationLoader": "api/loaders/AnimationLoader", "AudioLoader": "api/loaders/AudioLoader", "BufferGeometryLoader": "api/loaders/BufferGeometryLoader", "Cache": "api/loaders/Cache", "CompressedTextureLoader": "api/loaders/CompressedTextureLoader", "CubeTextureLoader": "api/loaders/CubeTextureLoader", "DataTextureLoader": "api/loaders/DataTextureLoader", "FileLoader": "api/loaders/FileLoader", "FontLoader": "api/loaders/FontLoader", "ImageBitmapLoader": "api/loaders/ImageBitmapLoader", "ImageLoader": "api/loaders/ImageLoader", "JSONLoader": "api/loaders/JSONLoader", "Loader": "api/loaders/Loader", "LoaderUtils": "api/loaders/LoaderUtils", "MaterialLoader": "api/loaders/MaterialLoader", "ObjectLoader": "api/loaders/ObjectLoader", "TextureLoader": "api/loaders/TextureLoader" }, "Loaders / Managers": { "DefaultLoadingManager": "api/loaders/managers/DefaultLoadingManager", "LoadingManager": "api/loaders/managers/LoadingManager" }, "Materials": { "LineBasicMaterial": "api/materials/LineBasicMaterial", "LineDashedMaterial": "api/materials/LineDashedMaterial", "Material": "api/materials/Material", "MeshBasicMaterial": "api/materials/MeshBasicMaterial", "MeshDepthMaterial": "api/materials/MeshDepthMaterial", "MeshLambertMaterial": "api/materials/MeshLambertMaterial", "MeshNormalMaterial": "api/materials/MeshNormalMaterial", "MeshPhongMaterial": "api/materials/MeshPhongMaterial", "MeshPhysicalMaterial": "api/materials/MeshPhysicalMaterial", "MeshStandardMaterial": "api/materials/MeshStandardMaterial", "MeshToonMaterial": "api/materials/MeshToonMaterial", "PointsMaterial": "api/materials/PointsMaterial", "RawShaderMaterial": "api/materials/RawShaderMaterial", "ShaderMaterial": "api/materials/ShaderMaterial", "ShadowMaterial": "api/materials/ShadowMaterial", "SpriteMaterial": "api/materials/SpriteMaterial" }, "Math": { "Box2": "api/math/Box2", "Box3": "api/math/Box3", "Color": "api/math/Color", "Cylindrical": "api/math/Cylindrical", "Euler": "api/math/Euler", "Frustum": "api/math/Frustum", "Interpolant": "api/math/Interpolant", "Line3": "api/math/Line3", "Math": "api/math/Math", "Matrix3": "api/math/Matrix3", "Matrix4": "api/math/Matrix4", "Plane": "api/math/Plane", "Quaternion": "api/math/Quaternion", "Ray": "api/math/Ray", "Sphere": "api/math/Sphere", "Spherical": "api/math/Spherical", "Triangle": "api/math/Triangle", "Vector2": "api/math/Vector2", "Vector3": "api/math/Vector3", "Vector4": "api/math/Vector4" }, "Math / Interpolants": { "CubicInterpolant": "api/math/interpolants/CubicInterpolant", "DiscreteInterpolant": "api/math/interpolants/DiscreteInterpolant", "LinearInterpolant": "api/math/interpolants/LinearInterpolant", "QuaternionLinearInterpolant": "api/math/interpolants/QuaternionLinearInterpolant" }, "Objects": { "Bone": "api/objects/Bone", "Group": "api/objects/Group", "Line": "api/objects/Line", "LineLoop": "api/objects/LineLoop", "LineSegments": "api/objects/LineSegments", "LOD": "api/objects/LOD", "Mesh": "api/objects/Mesh", "Points": "api/objects/Points", "Skeleton": "api/objects/Skeleton", "SkinnedMesh": "api/objects/SkinnedMesh", "Sprite": "api/objects/Sprite" }, "Renderers": { "WebGLRenderer": "api/renderers/WebGLRenderer", "WebGLRenderTarget": "api/renderers/WebGLRenderTarget", "WebGLRenderTargetCube": "api/renderers/WebGLRenderTargetCube" }, "Renderers / Shaders": { "ShaderChunk": "api/renderers/shaders/ShaderChunk", "ShaderLib": "api/renderers/shaders/ShaderLib", "UniformsLib": "api/renderers/shaders/UniformsLib", "UniformsUtils": "api/renderers/shaders/UniformsUtils" }, "Scenes": { "Fog": "api/scenes/Fog", "FogExp2": "api/scenes/FogExp2", "Scene": "api/scenes/Scene" }, "Textures": { "CanvasTexture": "api/textures/CanvasTexture", "CompressedTexture": "api/textures/CompressedTexture", "CubeTexture": "api/textures/CubeTexture", "DataTexture": "api/textures/DataTexture", "DepthTexture": "api/textures/DepthTexture", "Texture": "api/textures/Texture", "VideoTexture": "api/textures/VideoTexture" } }, "Examples": { "Controls": { "OrbitControls": "examples/controls/OrbitControls" }, "Geometries": { "ConvexBufferGeometry": "examples/geometries/ConvexBufferGeometry", "ConvexGeometry": "examples/geometries/ConvexGeometry", "DecalGeometry": "examples/geometries/DecalGeometry" }, "Loaders": { "BabylonLoader": "examples/loaders/BabylonLoader", "GLTFLoader": "examples/loaders/GLTFLoader", "MTLLoader": "examples/loaders/MTLLoader", "OBJLoader": "examples/loaders/OBJLoader", "OBJLoader2": "examples/loaders/OBJLoader2", "LoaderSupport": "examples/loaders/LoaderSupport", "PCDLoader": "examples/loaders/PCDLoader", "PDBLoader": "examples/loaders/PDBLoader", "SVGLoader": "examples/loaders/SVGLoader", "TGALoader": "examples/loaders/TGALoader", "PRWMLoader": "examples/loaders/PRWMLoader" }, "Objects": { "Lensflare": "examples/objects/Lensflare", }, "Exporters": { "GLTFExporter": "examples/exporters/GLTFExporter" }, "Plugins": { "LookupTable": "examples/Lut", "SpriteCanvasMaterial": "examples/SpriteCanvasMaterial" }, "QuickHull": { "Face": "examples/quickhull/Face", "HalfEdge": "examples/quickhull/HalfEdge", "QuickHull": "examples/quickhull/QuickHull", "VertexNode": "examples/quickhull/VertexNode", "VertexList": "examples/quickhull/VertexList" }, "Renderers": { "CanvasRenderer": "examples/renderers/CanvasRenderer", "CSS3DRenderer": "examples/renderers/CSS3DRenderer", "CSS2DRenderer": "examples/renderers/CSS2DRenderer" }, "Utils": { "BufferGeometryUtils": "examples/BufferGeometryUtils", "SceneUtils": "examples/utils/SceneUtils" } }, "Developer Reference": { "Polyfills": { "Polyfills": "api/Polyfills" }, "WebGLRenderer": { "WebGLProgram": "api/renderers/webgl/WebGLProgram", "WebGLShader": "api/renderers/webgl/WebGLShader", "WebGLState": "api/renderers/webgl/WebGLState" }, "WebGLRenderer / Plugins": { "SpritePlugin": "api/renderers/webgl/plugins/SpritePlugin" } } };
shinate/three.js
docs/list.js
JavaScript
mit
15,279
db.groups.update( {lname: "marrasputki"}, {$set:{users: ["Jörö"], description: "Marrasputki 2018"}})
jrosti/ontrail
groupaddjs/updatemarras.js
JavaScript
mit
110
document.body.onkeydown = function( e ) { var keys = { 37: 'left', 39: 'right', 40: 'down', 38: 'rotate', 80: 'pause' }; if ( typeof keys[ e.keyCode ] != 'undefined' ) { keyPress( keys[ e.keyCode ] ); render(); } };
ThomasBower/ChatApp
public/games/tetris/controller.js
JavaScript
mit
288
module.exports = { 'plugins': { 'local': { 'browsers': [ 'chrome', 'firefox' ] } } }
SimplaElements/simpla-collection
wct.conf.js
JavaScript
mit
103
// JScript File var borderstyle function editorOn(divid){ $('#'+divid).parent().parent().find(' >*:last-child img').css('visibility','hidden'); borderstyle = $('#'+divid).parent().parent().css('border'); $('#'+divid).parent().parent().css('border','') } function editorOff(divid){ $('#'+divid).parent().parent().find(' >*:last-child img').css('visibility',''); $('#'+divid).parent().parent().css('border',borderstyle); }
Micmaz/DTIControls
Rotator/Rotator/Rotator/editorFunctions.js
JavaScript
mit
426
(function () { 'use strict'; // var matcher = require('../../lib/matchUsers'); angular .module('chat.routes') .config(routeConfig); routeConfig.$inject = ['$stateProvider']; var c = "/room";// need to make this somehow return the correct room function routeConfig($stateProvider) { $stateProvider .state('chat', { url: c, templateUrl: '/modules/chat/client/views/chat.client.view.html', controller: 'ChatController', controllerAs: 'vm', data: { roles: ['user', 'admin'], pageTitle: 'Chat' } }); } }());
Hkurtis/capstone
modules/chat/client/config/chat.client.routes.js
JavaScript
mit
608
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import sinon from 'sinon'; import RadioInput from './'; describe('RadioInput', () => { let wrapper; let value; let style; let onChange; beforeEach(() => { value = 'test'; style = { backgroundColor: 'blue' }; onChange = sinon.spy(); wrapper = shallow( <RadioInput style={style} value={value} onChange={onChange} /> ); }); it('should render a radio tag', () => { expect(wrapper.find('radio')).to.have.length(1); }); it('should have a style value set via the style prop', () => { expect(wrapper.find('radio')).to.have.style('background-color', 'blue'); }); it('should have a value set via the value prop', () => { expect(wrapper.find('radio').text()).to.equal(value); }); it('should call onChange on change', () => { wrapper.find('radio').simulate('change'); expect(onChange.calledOnce).to.equal(true); }); });
bjlaa/facebook-clone
src/components/RadioInput/RadioInput.spec.js
JavaScript
mit
1,012
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('ttwebapp generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
times/generator-ttwebapp
test/test-load.js
JavaScript
mit
272
//setup Dependencies var connect = require('connect'); //Setup Express var express = require('express'); var path = require('path'); let app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); var keypress = require('keypress'); var port = (process.env.PORT || 8081); var muted = false; const debug = true; app.set("view engine", "pug"); app.set("views", path.join(__dirname, "views")); app.use(express.static(path.join(__dirname, "public"))); app.set('env', 'development'); server.listen(port); var message = ''; var main_socket; var auksalaq_mode = 'chatMode'; //Setup Socket.IO io.on('connection', function(socket){ if(debug){ console.log('Client Connected'); } main_socket = socket; //start time setInterval(sendTime, 1000); //ceiling socket.on('ceiling_newuser', function (data) { if(debug){ console.log('new user added! ' + data.username); console.log(data); } socket.emit('ceiling_user_confirmed', data); socket.broadcast.emit('ceiling_user_confirmed', data); }); //see NomadsMobileClient.js for data var socket.on('ceiling_message', function(data){ socket.broadcast.emit('ceiling_proc_update',data); //send data to all clients for processing sketch socket.broadcast.emit('ceiling_client_update',data); //send data back to all clients? if(debug){ console.log(data); } }); //auksalaq socket.on('auksalaq_newuser', function (data) { if(debug){ console.log('new user added! ' + data.username); console.log(data); } data.mode = auksalaq_mode; data.muted = muted; socket.emit('auksalaq_user_confirmed', data); socket.broadcast.emit('auksalaq_user_confirmed', data); }); //see NomadsMobileClient.js for data var socket.on('auksalaq_message', function(data){ //socket.broadcast.emit('auksalaq_proc_update',data); //send data to all clients for processing sketch socket.broadcast.emit('auksalaq_client_update',data); socket.emit('auksalaq_client_update',data); if(debug){ console.log(data); } }); //mode change from controller socket.on('auksalaq_mode', function(data){ socket.broadcast.emit('auksalaq_mode', data); auksalaq_mode = data; if(debug){ console.log(data); } }); socket.on('mute_state', function(data){ muted = data; socket.broadcast.emit('mute_state', data); console.log(data); }); //clocky socket.on('clock_start', function(data){ socket.broadcast.emit('clock_start', data); if(debug){ console.log(data); } }); socket.on('clock_stop', function(data){ socket.broadcast.emit('clock_stop', data); if(debug){ console.log(data); } }); socket.on('clock_reset', function(data){ socket.broadcast.emit('clock_reset', data); if(debug){ console.log("resettting clock"); } }); /* socket.on('begin_ceiling', function(){ ; }); socket.on('begin_auksalak', function(){ ; }); socket.on('stop_ceiling', function(){ ; }); socket.on('stop_auksalak', function(){ ; }); */ socket.on('disconnect', function(){ if(debug){ console.log('Client Disconnected.'); } }); }); /////////////////////////////////////////// // Routes // /////////////////////////////////////////// /////// ADD ALL YOUR ROUTES HERE ///////// app.get('/', function(req,res){ //res.send('hello world'); res.render('index.pug', { locals : { title : 'Nomads' ,description: 'Nomads System' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' ,cache: 'false' } }); }); // The Ceiling Floats Away Routes app.get('/ceiling', function(req,res){ res.render('ceiling/ceiling_client.pug', { locals : { title : 'The Ceiling Floats Away' ,description: 'The Ceiluing Floats Away' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); app.get('/ceiling_display', function(req,res){ res.render('ceiling/ceiling_display.pug', { locals : { title : 'The Ceiling Floats Away' ,description: 'Ceiling Nomads message disply' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); app.get('/ceiling_control', function(req,res){ res.render('ceiling/ceiling_control.pug', { locals : { title : 'The Ceiling Floats Away Control' ,description: 'Ceiling Nomads System Control' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); // Auksalaq Routes app.get('/auksalaq', function(req,res){ res.render('auksalaq/auksalaq_client.pug', { locals : { title : 'Auksalaq' ,description: 'Auksalaq Nomads System' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); app.get('/auksalaq_display', function(req,res){ res.render('auksalaq/auksalaq_display.pug', { locals : { title : 'Auksalaq' ,description: 'Auksalaq Nomads message disply' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); app.get('/auksalaq_control', function(req,res){ res.render('auksalaq/auksalaq_control.pug', { locals : { title : 'Auksalaq Control' ,description: 'Auksalaq Nomads System Control' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); app.get('/auksalaq_clock', function(req,res){ res.render('auksalaq/auksalaq_clock.pug', { locals : { title : 'Auksalaq Clock' ,description: 'Auksalaq Nomads System Clock' ,author: 'TThatcher' ,analyticssiteid: 'XXXXXXX' } }); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found '+req); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // very basic! if(debug){ console.error(err.stack); } // render the error page res.status(err.status || 500); res.render('404'); }); function NotFound(msg){ this.name = 'NotFound'; Error.call(this, msg); Error.captureStackTrace(this, arguments.callee); } if(debug){ console.log('Listening on http://127.0.0.1:' + port ); } //for testing sendChat = function(data, type){ if(debug) console.log("sending data ", data); var messageToSend = {}; messageToSend.id = 123; messageToSend.username = "Nomads_Server"; messageToSend.type = type; messageToSend.messageText = data; messageToSend.location = 0; messageToSend.latitude = 0; messageToSend.longitude = 0; messageToSend.x = 0; messageToSend.y = 0; var date = new Date(); d = date.getMonth()+1+"."+date.getDate()+"."+date.getFullYear()+ " at " + date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); messageToSend.timestamp = d; main_socket.broadcast.emit('auksalaq_client_update', messageToSend); } sendTime = function(){ var d = new Date(); main_socket.broadcast.emit('clock_update', d.getTime()); }
nomads2/new-nomads
server.js
JavaScript
mit
7,491
/** * Created by Tivie on 12-11-2014. */ module.exports = function (grunt) { // Project configuration. var config = { pkg: grunt.file.readJSON('package.json'), concat: { options: { sourceMap: true, banner: ';/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n(function(){\n', footer: '}).call(this);' }, dist: { src: [ 'src/showdown.js', 'src/helpers.js', 'src/converter.js', 'src/subParsers/*.js', 'src/loader.js' ], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { sourceMap: true, banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { options: { jshintrc: '.jshintrc' }, files: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ] }, jscs: { options: { config: '.jscs.json' }, files: { src: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ] } }, changelog: { options: { repository: 'http://github.com/showdownjs/showdown', dest: 'CHANGELOG.md' } }, bump: { options: { files: ['package.json'], updateConfigs: [], commit: true, commitMessage: 'Release version %VERSION%', commitFiles: ['package.json'], createTag: true, tagName: '%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'upstream', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d', globalReplace: false, prereleaseName: 'alpha', regExp: false } }, simplemocha: { node: { src: 'test/node/**/*.js', options: { globals: ['should'], timeout: 3000, ignoreLeaks: false, reporter: 'spec' } }, karlcow: { src: 'test/node/testsuite.karlcow.js', options: { globals: ['should'], timeout: 3000, ignoreLeaks: false, reporter: 'spec' } }, browser: { src: 'test/browser/**/*.js', options: { reporter: 'spec' } } } }; grunt.initConfig(config); require('load-grunt-tasks')(grunt); grunt.registerTask('concatenate', ['concat']); grunt.registerTask('lint', ['jshint', 'jscs']); grunt.registerTask('test', ['lint', 'concat', 'simplemocha:node']); grunt.registerTask('test-without-building', ['simplemocha:node']); grunt.registerTask('build', ['test', 'uglify']); grunt.registerTask('prep-release', ['build', 'changelog']); // Default task(s). grunt.registerTask('default', ['test']); };
pramithprakash/Blog
node_modules/showdown/Gruntfile.js
JavaScript
mit
3,101
// Export modules to global scope as necessary (only for testing) if (typeof process !== 'undefined' && process.title === 'node') { // We are in node. Require modules. expect = require('chai').expect; sinon = require('sinon'); num = require('..'); isBrowser = false; } else { // We are in the browser. Set up variables like above using served js files. expect = chai.expect; // num and sinon already exported globally in the browser. isBrowser = true; }
rayjlim/spyfall
tests/setup.js
JavaScript
mit
483
export var lusolveDocs = { name: 'lusolve', category: 'Algebra', syntax: ['x=lusolve(A, b)', 'x=lusolve(lu, b)'], description: 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.', examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lusolve(a, b)'], seealso: ['lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse'] };
Michayal/michayal.github.io
node_modules/mathjs/es/expression/embeddedDocs/function/algebra/lusolve.js
JavaScript
mit
371
/* Copyright (c) 2017, Dogan Yazar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Remove commonly used diacritic marks from a string as these * are not used in a consistent manner. Leave only ä, ö, å. */ var remove_diacritics = function(text) { text = text.replace('à', 'a'); text = text.replace('À', 'A'); text = text.replace('á', 'a'); text = text.replace('Á', 'A'); text = text.replace('è', 'e'); text = text.replace('È', 'E'); text = text.replace('é', 'e'); text = text.replace('É', 'E'); return text; }; // export the relevant stuff. exports.remove_diacritics = remove_diacritics;
Hugo-ter-Doest/natural
lib/natural/normalizers/normalizer_sv.js
JavaScript
mit
1,642
import { StyleSheet } from "react-native"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "flex-start", alignItems: "center", backgroundColor: "#669999" }, buttons: { // flex: 0.15, flexDirection: "row", alignItems: "center", marginVertical: 20 }, button: { marginHorizontal: 20, padding: 20, backgroundColor: "#0D4D4D", color: "white", textAlign: "center" }, selectedButton: { backgroundColor: "#006699" }, body: { // flex: 0.8, justifyContent: "flex-start", alignItems: "center" }, subTitle: { marginVertical: 10 }, viewport: { // flex: 1, alignSelf: "center", backgroundColor: "white" } }); export default styles;
machadogj/react-native-layout-tester
styles.js
JavaScript
mit
869
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Express' }); }); //test canvas router.get('/canvas', function (req, res, next) { res.render('canvas'); }); module.exports = router;
davidbull931997/NL_ChatWebApp
routes/index.js
JavaScript
mit
299
'use strict'; module.exports = { "definitions": { "validation-error": { "type": "object", "description": "Validation error", "properties": { "param": { "type": "string", "description": "The parameter in error" }, "msg": { "type": "string", "enum": ["invalid","required"], "description": "The error code" } } }, "validation-errors": { "type": "array", "description": "Validation errors", "items": { "$ref": "#/definitions/validation-error" } }, "system-error": { "type": "object", "description": "System error", "properties": { "error": { "type": "string", "description": "The error message" } } } } };
dennoa/node-api-seed
server/api/swagger/error-definitions.js
JavaScript
mit
828