code
stringlengths
2
1.05M
var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var ProvidePlugin = require('webpack/lib/ProvidePlugin'); var helpers = require('./helpers'); module.exports = { entry: { 'polyfills': './src/polyfills.ts', 'vendor': './src/vendor.ts', 'app': './src/main.ts' }, resolve: { extensions: ['', '.js', '.ts'] }, module: { loaders: [ { test: /\.ts$/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'] }, { test: /\.html$/, loader: 'html' }, { test: /\.(eot(\?v=\d+\.\d+\.\d+)?|(woff|woff2)(\?v=\d+\.\d+\.\d+)?|ttf(\?v=\d+\.\d+\.\d+)?|svg(\?v=\d+\.\d+\.\d+)?|png|jpe?g|gif|ico)$/, loader: 'file?name=assets/[name].[hash].[ext]' }, { test: /\.css$/, exclude: helpers.root('src', 'app'), loader: ExtractTextPlugin.extract('style', 'css?sourceMap') }, { test: /\.css$/, include: helpers.root('src', 'app'), loader: 'raw' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor', 'polyfills'] }), new HtmlWebpackPlugin({ template: 'src/index.html' }), new ProvidePlugin({ jQuery: 'jquery', $: 'jquery', jquery: 'jquery', "Tether": 'tether', "window.Tether": "tether" }) ] };
{ "type": "cbml", "nodes": [ { "type": "block", "pos": 0, "endpos": 112, "value": "/*<jdists encoding=\"base64\">*/\nhello world!\n /*<jdists encoding=\"quoted\">*/\n 123\n /*</jdists>*/\n/*</jdists>*/", "tag": "jdists", "language": "c", "attrs": { "encoding": "base64" }, "line": 1, "col": 1, "nodes": [ { "type": "text", "pos": 30, "endpos": 46, "value": "\nhello world!\n ", "line": 1, "col": 31 }, { "type": "block", "pos": 46, "endpos": 98, "value": "/*<jdists encoding=\"quoted\">*/\n 123\n /*</jdists>*/", "tag": "jdists", "language": "c", "attrs": { "encoding": "quoted" }, "line": 3, "col": 3, "nodes": [ { "type": "text", "pos": 76, "endpos": 85, "value": "\n 123\n ", "line": 3, "col": 33 } ], "content": "\n 123\n ", "prefix": "/*<jdists encoding=\"quoted\">*/", "suffix": "/*</jdists>*/" }, { "type": "text", "pos": 98, "endpos": 99, "value": "\n", "line": 5, "col": 16 } ], "content": "\nhello world!\n /*<jdists encoding=\"quoted\">*/\n 123\n /*</jdists>*/\n", "prefix": "/*<jdists encoding=\"base64\">*/", "suffix": "/*</jdists>*/" } ], "endpos": 112 }
import template from './absolutePanel.html'; import moment from 'moment'; function absolutePanel($timeout) { return { restrict: 'E', replace: true, scope: { observer: '=', dictionary: '=', hideTimeUnit: '=', singleDate: '=' }, template: template, link: function (scope) { /** * After a user selects an option that includes a date range or sets a date range with the double calendar, * this function verifies which time units are available to select from (hours and days). * Up to 36 hours the only time unit available is hours. * More than 36 hours and up to 7 days can be retrieved by hours and days. * For more days than that the only available unit is days. * @param from * @param to */ // FIXME: max resolution is now hardcoded to 200 (because of highcharts performance issues), it should be configurable function setupAvailableTimeUnits () { var hours = moment(scope.internalRange.to).diff(moment(scope.internalRange.from), 'hours'); if (hours > 36 && hours < 200) { scope.internalRange.selectedRange.timeUnits = [ 'hour', 'day' ]; } else if (hours > 1 && hours < 4) { scope.internalRange.selectedRange.timeUnits = [ 'minute', 'hour' ]; } else { delete scope.internalRange.selectedRange.timeUnits; } } /** * Executes when a range is selected and emitted by any of the other components * @param range */ function onRangeSet(range) { scope.internalRange = range; setupAvailableTimeUnits(); } $timeout(function () { scope.observer.subscribe('absolutePanel', onRangeSet); }); /** * Executes when a user selects an available range. * @param range */ scope.selectRangeOption = function (range) { const newDate = scope.internalRange.changeWithRangeOption(range); scope.internalRange = newDate; setupAvailableTimeUnits(); scope.observer.emit('absolutePanel', newDate); }; scope.selectTimeUnit = function (unit) { const newDate = scope.internalRange.changeWithTimeUnit(unit); scope.internalRange = newDate; scope.observer.emit('absolutePanel', newDate); }; scope.updateFrom = function (value) { const newDate = scope.internalRange.changeFrom(value); scope.internalRange = newDate; setupAvailableTimeUnits(); scope.observer.emit('absolutePanel', newDate); }; scope.updateTo = function (value) { const newDate = scope.internalRange.changeTo(value); scope.internalRange = newDate; setupAvailableTimeUnits(); scope.observer.emit('absolutePanel', newDate); }; } } } export default absolutePanel;
#!/usr/bin/env node require('./proof')(1, function (parseEqual) { parseEqual("b128", [ { signed: false , bits: 128 , endianness: "b" , bytes: 16 , type: "a" , exploded: true , arrayed: false , repeat: 1 } ], "parse a number greater than 64 bits with no type."); });
angular.module("MyApp") .filter('sortViews', function() { var prevActiveView = 0; var orderedView = []; return function(views, active) { if(Object.keys(views).length ===0 ) { orderedView = [] return orderedView; } if (active !== prevActiveView||(Object.keys(views).length ===1)) { orderedView = []; for (i in views) { if (parseInt(i) !== active) { orderedView.push(views[i]); } } orderedView.push(views[active]); prevActiveView=active; return orderedView; } else { return orderedView; } return []; }; });
import React from 'react' import {render} from 'react-dom'; import 'babel-polyfill'; import {Provider} from 'react-redux'; import './css/index.css' import './css/simplemde.css' let rootDocument=document.getElementById('app'); import {store} from './redux/store' import RouterContent from './router' render( <Provider store={store}> <RouterContent/> </Provider> ,rootDocument);
'use strict'; const path = require('path'); const ScenarioOutlineNumbering = require(path.resolve('lib/builtIn/ScenarioOutlineNumbering.js')); const expect = require('chai').expect; const API = require(path.resolve('lib')); describe('builtIn.ScenarioOutlineNumbering', () => { it('should be available through API', () => { expect(API.builtIn.ScenarioOutlineNumbering).to.equal(ScenarioOutlineNumbering); }); it('should add order of example row', () => { const baseAst = API.load('test/data/input/scenarioOutlineNumbering.feature'); const expectedAst = API.load('test/data/output/scenarioOutlineNumbering.1.feature'); const resultAst = API.process(baseAst, new ScenarioOutlineNumbering({ addNumbering: true, addParameters: false })); expect(resultAst).to.eql(expectedAst); }); it('should add variables of example table', () => { const baseAst = API.load('test/data/input/scenarioOutlineNumbering.feature'); const expectedAst = API.load('test/data/output/scenarioOutlineNumbering.2.feature'); const resultAst = API.process(baseAst, new ScenarioOutlineNumbering({ addNumbering: false, addParameters: true })); expect(resultAst).to.eql(expectedAst); }); it('should support custom configuration', () => { const baseAst = API.load('test/data/input/scenarioOutlineNumbering.feature'); const expectedAst = API.load('test/data/output/scenarioOutlineNumbering.3.feature'); const resultAst = API.process(baseAst, new ScenarioOutlineNumbering({ addNumbering: true, numberingFormat: '${name} / ${i}', addParameters: true, parameterDelimiter: '|', parameterFormat: '${name} (${parameters})' })); expect(resultAst).to.eql(expectedAst); }); });
/** * Module dependencies */ var Item = require('./entity/item'); var Equipment = require('./entity/equipment'); var dataApi = require('../util/dataApi'); var area = require('./area/area'); var messageService = require('./messageService'); /** * Expose 'taskReward' */ var taskReward = module.exports; /** * Player get rewards after task is completed. * the rewards contain equipments and exprience, according to table of figure * * @param {Player} player * @param {Array} ids * @api public */ taskReward.reward = function(player, ids) { if (ids.length < 1) { return; } var i, l; var tasks = player.curTasks; var pos = player.getState(); var totalItems = [], totalExp = 0; for (i = 0, l=ids.length; i < l; i++) { var id = ids[i]; var task = tasks[id]; var items = task.item.split(';'); var exp = task.exp; for (var j = 0; j < items.length; j++) { totalItems.push(items[j]); } totalExp += exp; } var equipments = this._rewardItem(totalItems, pos); this._rewardExp(player, totalExp); for (i = 0, l=equipments.length; i < l; i ++) { area.addEntity(equipments[i]); } messageService.pushMessageToPlayer({uid:player.userId, sid : player.serverId}, { route:'onDropItems', dropItems: equipments }); }; /** * Rewards of equipments. * * @param {Array} items * @param {Object} pos * @return {Object} * @api private */ taskReward._rewardItem = function(items, pos) { var length = items.length; var equipments = []; if (length > 0) { for (var i = 0; i < length; i++) { var itemId = items[i]; var itemData = dataApi.equipment.findById(itemId); var equipment = new Equipment({ kindId: itemData.id, x: pos.x + Math.random() * 50, y: pos.y + Math.random() * 50, kindName: itemData.name, name: itemData.name, desc: itemData.desc, kind: itemData.kind, attackValue: itemData.attackValue, defenceValue: itemData.defenceValue, price: itemData.price, color: itemData.color, imgId: itemData.imgId, heroLevel: itemData.heroLevel, playerId: itemData.playerId }); equipments.push(equipment); } return equipments; } }; /** * Rewards of exprience. * * @param {Player} player * @param {Number} exprience * @api private */ taskReward._rewardExp = function(player, exprience) { player.addExperience(exprience); };
var q = require('q'); var powerdrill = require('powerdrill'); /** * A bridge between le-email-service and Mandrill * @class EmailProvider * @param {string} apiKey the mandrill api key * @returns {service} */ var EmailProvider = function (apiKey) { if (!apiKey) { throw new Error('API key required'); } var _api = powerdrill(apiKey); var handleResponse = function (err, resp, deferred) { if (err) { deferred.reject(err); } else if (resp.status === 'error') { deferred.reject(new Error(resp.message)); } else if (resp[0] && resp[0].status === 'invalid') { deferred.reject(new Error('Invalid email')); } else if (resp[0] && resp[0].status === 'rejected') { deferred.reject(new Error('Email rejected')); } else if (resp[0] && resp[0].status === 'sent') { deferred.resolve(); } else { deferred.reject(new Error('Uknown error')); } } /** * Sends an email with html content * @function sendHtml * @memberof EmailProvider * @instance * @param {string} from the email address of the sender * @param {string} to the email address of the recipient * @param {string} subject the subject line of the email * @param {string} html the html content * @param {string} replyTo (optional) the reply-to email address * @returns {promise} */ this.sendHtml = function (from, to, subject, html, replyTo) { return q.resolve(); }; /** * Sends a template email * @function sendTemplate * @memberof EmailProvider * @instance * @param {string} from the email address of the sender * @param {string} to the email address of the recipient * @param {string} id the unique identifier of the template * @param {string} data the key/value pairs to inject * @param {string} replyTo (optional) the reply-to email address * @param {string} subject (optional) the subject * @returns {promise} */ this.sendTemplate = function (from, to, id, data, replyTo, subject) { return q.resolve(); }; } module.exports = EmailProvider;
const https = require('https'); const FileSystem = require('fs'); module.exports = { update: function(callback) { if (global.isDevMode()) { var list = []; var request = https.get({ host: 'api.github.com', path: '/repos/TheBusyBiscuit/CompanionLauncher/contributors', headers: { 'User-Agent': 'CompanionLauncher' } } , function(response) { var code = response.statusCode; log('contributors.json (' + code + ')'); if (code == 200) { var body = ''; response.on('data', function(data) { body += data; }); response.on('end', function() { var contributors = JSON.parse(body); log('Contributors'); for (var i = 0; i < contributors.length; i++) { log(' ' + contributors[i].login + ' (' + contributors[i].contributions + ')'); list.push({ name: contributors[i].login, amount: contributors[i].contributions }); } list.sort(function(a,b) { return b.amount - a.amount; }) FileSystem.writeFile(__dirname + '/../../assets/contributors.json', JSON.stringify(list, null, 2), function(err) { if (err) log(err); else { var text = ''; for (var i = 0; i < list.length; i++) { if (text == '') text = list[i].name; else text += ', ' + list[i].name; } global.authors = text; callback(); } }); }); } }).on('error', function(err) { log(err); }); } else { FileSystem.readFile(__dirname + '/../../assets/contributors.min.json', function(err, data) { if (err) log(err); else { var list = JSON.parse(data); var text = ''; for (var i = 0; i < list.length; i++) { if (text == '') text = list[i].name; else text += ', ' + list[i].name; } global.authors = text; callback(); } }); } } } function log(message) { global.log('Main', message); }
export const judgements = [ // window (ms), label, continue combo (true) or break (false) { threshold: 50, label: 'Perfect', className: 'perfect', keepCombo: true, hp: 4 }, { threshold: 100, label: 'Great', className: 'great', keepCombo: true, hp: 2 }, { threshold: 135, label: 'Decent', className: 'decent', keepCombo: true, hp: 1 }, { threshold: 180, label: 'Way Off', className: 'way-off', keepCombo: false, hp: -2 }, ]; export const missedJudgement = { label: 'Miss', className: 'miss', keepCombo: false, hp: -6, }; // Map keyCodes to columns export const keyCodeColMap = { '83': 0, '68': 1, '70': 2, '32': 3, '74': 4, '75': 5, '76': 6 }; // Map keys (as seen by Mousetrap) to columns export const keyColMap = { 's': 0, 'd': 1, 'f': 2, 'space': 3, 'j': 4, 'k': 5, 'l': 6 }; // [fill, stroke] const editorColors = { color1: ['white', 'black'], color2: ['rgb(255,0,255)', 'black'], centerColor: ['red', 'black'], separatorStyle: 'rgba(0,0,0,0)', beatLineStyle: 'black', offsetBarFillStyle: '#4A90E2', }; const playerColors = { color1: ['white', 'rgba(0,0,0,0)'], color2: ['rgb(255,0,255)', 'rgba(0,0,0,0)'], centerColor: ['red', 'rgba(0,0,0,0)'], separatorStyle: 'white', beatLineStyle: 'rgba(0,0,0,0)', offsetBarFillStyle: '#4A90E2', }; [editorColors, playerColors].forEach((colors) => { const {color1, color2, centerColor} = colors; colors.noteColors = [ color1, color2, color1, centerColor, color1, color2, color1 ]; }); export {playerColors, editorColors};
angular.module('data-model-mapper', []) .factory('ngDataModelMapper', [ function () { return function (fields) { var map = function (obj) { var result = {}; angular.forEach(fields, function (field) { var dest = angular.isArray(field.dest) ? field.dest : [field.dest]; var args = _.values(_.pick(obj, field.src)); if (angular.isFunction(field.map)) { args = field.map.apply(null, args); } if (!angular.isArray(args)) args = [args]; angular.forEach(dest, function (name, index) { result[name] = args[index]; }); }); return result; }; var revert = function (obj) { var result = {}; angular.forEach(fields, function (field) { var src = angular.isArray(field.src) ? field.src : [field.src]; var args = _.values(_.pick(obj, field.dest)); if (angular.isFunction(field.revert)) { args = field.revert.apply(null, args); } if (!angular.isArray(args)) args = [args]; angular.forEach(src, function (name, index) { result[name] = args[index]; }); }); return result; }; return { map: map, revert: revert }; }; } ]);
import composedFetch from '../src/lib/composedFetch'; describe(`Method: composedFetch`, () => { it(`should be undefined when id is incorrect but not blocked`, async () => { const request = await composedFetch(global.BPOST_ID_FALSE); expect(request).toBeUndefined(); }); it(`should throw if the id param is incorrect and blocked`, async () => { const request = await composedFetch(`eval();`); expect(request).toThrow(); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:17e4b1a3f61572a8893c2be3c8eb35091f1bd79045900b4eaf7637007157e481 size 2544
{ "metadata" : { "formatVersion" : 3.1, "generatedBy" : "Blender 2.65 Exporter", "vertices" : 12, "faces" : 10, "normals" : 2, "colors" : 0, "uvs" : [12], "materials" : 1, "morphTargets" : 0, "bones" : 0 }, "scale" : 1.000000, "materials" : [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "default", "vertexColors" : false }], "vertices" : [-0.561909,3.19738e-07,-0.511665,0.316187,-3.8847e-07,0.861746,0.850629,3.19738e-07,-0.511665,0.35522,-3.12615e-07,0.39615,0.730545,1.22876e-06,-0.144139,0.750596,-1.97462e-07,-0.310653,-0.20659,1.2644e-07,0.674791,-0.497447,-3.18065e-07,0.4296,-0.701938,2.25857e-07,0.064573,-0.739964,2.67611e-07,-0.191709,-0.0118749,-4.22016e-06,0.592125,-0.172532,1.49839e-07,0.53117], "morphTargets" : [], "normals" : [0,-1,0,0,-0.999969,0], "colors" : [], "uvs" : [[0.443312,0,0.617104,0,0.421405,0.069984,0.604797,0.043967,0.60233,0.080389,0.556152,0.198566,0.551349,0.300405,0.510986,0.241431,0.49122,0.228099,0.487029,0.259513,0.451244,0.205882,0.426084,0.12604]], "faces" : [42,0,2,9,0,0,1,2,0,0,0,42,5,4,3,0,3,4,5,0,0,0,42,3,1,10,0,5,6,7,0,0,0,42,11,6,7,0,8,9,10,0,0,0,42,7,8,9,0,10,11,2,0,1,0,42,2,5,9,0,1,3,2,0,0,0,42,5,3,10,0,3,5,7,0,0,0,42,11,7,9,0,8,10,2,0,0,0,42,5,10,9,0,3,7,2,0,0,0,42,10,11,9,0,7,8,2,0,0,0], "bones" : [], "skinIndices" : [], "skinWeights" : [], "animations" : [] }
var tc = require('tough-cookie'); var noop = function(){}; var modifiable = [ 'key' , 'value' , 'expires' , 'maxAge' , 'domain' , 'path' , 'secure' , 'httpOnly' , 'extensions' ]; var readOnly = [ 'hostOnly' , 'creation' , 'lastAccessed' , 'pathIsDefault' ]; /** * HTTP Cookie * @constructor * @param {String|Object} data can be a cookie header string or a json object */ var Cookie = function(data) { var self = this; this._cookie = new tc.Cookie(); modifiable.map(function(attribute) { Object.defineProperty(self, attribute, { enumerable: true , get: function() { return self._cookie[attribute]; } , set: function(val) { self._cookie[attribute] = val; } }); }); readOnly.map(function(attribute) { Object.defineProperty(self, attribute, { get: function(){ return this._cookie[attribute]; } , set: noop , enumerable: true }); }); this.set(data); }; /** * Get cookie as a cookie header string * @return {String} */ Cookie.prototype.getCookieHeaderString = function() { return this._cookie.cookieString(); }; /** * Set multiple cookie properties at once * @param {String|Object} data */ Cookie.prototype.set = function(data) { if (!data) return; if (typeof data === 'string') { this._cookie = tc.Cookie.parse(data); return; } if (typeof data === 'object') { for (key in data) { if (!data.hasOwnProperty(key)) continue; if (modifiable.indexOf(key) < 0) continue; this[key] = data[key]; } return; } throw Error("data parameter must be string or object."); }; /** * Get cookie as a JSON object * @return {Object} */ Cookie.prototype.toJSON = function() { return { key: this.key , value: this.value , expires: this.expires , maxAge: this.maxAge , domain: this.domain , path: this.path , secure: this.secure , httpOnly: this.httpOnly , extensions: this.extensions }; }; module.exports = Cookie;
module.exports = function(Vue) { var OS = require(__dirname + "/../../Helpers/OS.js"); var Utils = require(__dirname + "/../../Helpers/Utilities.js"); Vue.component("os", { data: function() { return { allCpus: false, allNetworkInterfaces: false }; }, methods: { openHomedir: function() { require('child_process').exec('start "" "' + this.homedir + '"'); } }, computed: { networkInterfaces: function() { if (!this.allNetworkInterfaces) { var interfaces = OS.getAllNetworkInterfaces(); var pool = {}; for (var i in interfaces) { pool[i] = {}; pool[i][interfaces[i][0].family] = interfaces[i][0].address; pool[i][interfaces[i][1].family] = interfaces[i][1].address; } this.allNetworkInterfaces = pool; } return this.allNetworkInterfaces; }, cpus: function() { if (!this.allCpus) { this.allCpus = OS.getAllCpus().map(function(el) { if (el.model) { return el.model; } }); } return this.allCpus; }, architecture: function() { return OS.getArchitecture(); }, platform: function() { return OS.getPlatform(); }, type: function() { return OS.getType(); }, release: function() { return OS.getRelease(); }, uptime: function() { return Utils.round(OS.getUptime() / 60 / 60); }, EOL: function() { return OS.getEOL(); }, hostname: function() { return OS.getHostname(); }, homedir: function() { return OS.getHomeDir(); } } }); };
'use strict'; var tests = ["async","core","destroy","dir","engine","fs","global","helpers","mo","paths","plugins","settings","timers","util"];
/** * @author dforrer / https://github.com/dforrer * Developed as part of a project at University of Applied Sciences and Arts Northwestern Switzerland (www.fhnw.ch) */ /** * @param object THREE.Object3D * @param newMaterial THREE.Material * @constructor */ var SetMaterialCommand = function ( object, newMaterial ) { Command.call( this ); this.type = 'SetMaterialCommand'; this.name = 'New Material'; this.object = object; this.oldMaterial = ( object !== undefined ) ? object.material : undefined; this.newMaterial = newMaterial; }; SetMaterialCommand.prototype = { execute: function () { this.object.material = this.newMaterial; this.show.signals.materialChanged.dispatch( this.object.material ); }, undo: function () { this.object.material = this.oldMaterial; this.show.signals.materialChanged.dispatch( this.object.material ); } };
// TODO(fcarriedo): Find a sensible solution to 'same origin policy' // other than jQuery's '?callback=?'. See how the twitter JS libraries // are doing it. (Maybe the '?callback=?' is a sensible solution. // See: http://en.wikipedia.org/wiki/Same_origin_policy function ConvoreAPI( authCxt ) { // To guard against calls without 'new' if( !(this instanceof arguments.callee) ) { return new arguments.callee(arguments); } var convoreApiUrl = 'https://convore.com/api'; var liveCursor = null; var self = this; var settings = { authUsr: '', authPswd: '', onAuthError: null }; // TODO: Do something like jQuery plugin 'extend' settings.authUsr = authCxt.username; settings.authPswd = authCxt.password; settings.onAuthError = authCxt.onAuthError; $.ajaxSetup({ username: settings.authUsr, password: settings.authPswd }); /* * Use this method to check if the user is properly logged in. * If successfuly verified, 'onSuccessCallback' will receive the * logged in user details. */ self.verifyAccount = function(onSuccessCallback, onErrorCallback) { var verifyAccountUrl = convoreApiUrl + '/account/verify.json'; $.ajax({ url: verifyAccountUrl, username: settings.authUsr, password: settings.authPswd, success: function(data) { if( !data.error ) { if(onSuccessCallback) { onSuccessCallback.call(this, data); } } else { if(onErrorCallback) { onErrorCallback.call(this, data); } } }, error: function(jqXHR, textStatus, errorThrown) { if(onErrorCallback) { onErrorCallback.call(this, errorThrown); } else if(settings.onAuthError) { settings.onAuthError.call(); } console.log('error: ' + errorThrown); } }); } self.listenToLiveFeed = function( callback ) { var url = convoreApiUrl + '/live.json'; setTimeout(function() { // For non-blocknig the first time since long polls. $.ajax({ url: url, dataType: 'json', data: {cursor: self.liveCursor}, success: function(data) { if( data && data.messages ) { var msgsLength = data.messages.length; if( msgsLength > 0 ) { self.liveCursor = data.messages[msgsLength-1]._id // TODO(fcarriedo): Check if best to grab the last elem _id. } // Perform the callback. callback.call(this, data.messages); } // Calls itself again ad infinitum. (Long polling encouraged [see api docs]). // Reconnects as fast as the browser allows. setTimeout( function() { self.listenToLiveFeed(callback); }, 0 ); }, error: function( xmlHttpRequest ) { self.liveCursor = null; // TODO(fcarriedo): We should set it to null on an errorCode basis. setTimeout( function() { self.listenToLiveFeed(callback); }, 3000 ); // We try again after 3 seconds. } }); }, 0); } self.fetchGroups = function( callback ) { var url = convoreApiUrl + '/groups.json'; $.getJSON(url, function(data) { callback.call(this, data.groups ); }); } self.fetchGroupDetails = function( groupId, callback ) { var url = convoreApiUrl + '/groups/' + groupId + '.json?callback=?'; $.getJSON(url, function(data) { callback.call(this, data.group ); }); } self.fetchGroupTopics = function( groupId , callback ) { var url = convoreApiUrl + '/groups/' + groupId + '/topics.json'; $.getJSON(url, function(data) { callback.call(this, data.topics ); }); } // https://convore.com/api/#group-mark-read // Mark all messages in the group as read. self.markGroupAllRead = function( groupId , callback ) { var url = convoreApiUrl + '/groups/' + groupId + '/mark_read.json'; $.post(url, function(data) { callback.call( this , data ); }); } self.fetchTopicMessages = function( topicId , callback ) { var url = convoreApiUrl + '/topics/' + topicId + '/messages.json'; $.getJSON(url, function(data) { callback.call(this, data.messages ); }); } // https://convore.com/api/#topic-mark-read // Mark all messages in a topic as read. self.markTopicAllRead = function( topicId , callback ) { var url = convoreApiUrl + '/topics/' + topicId + '/mark_read.json'; $.post(url, function(data) { callback.call( this , data ); }); } // https://convore.com/api/#messages // Gets a list of direct message conversations for the current user. // // TODO(fcarriedo): Mmmm naming kind of inconsistent (are they private // messages or conversations or just plain messages?) Rename. self.fetchPrivateConversations = function( callback ) { var url = convoreApiUrl + '/messages.json'; $.getJSON(url, function(data) { callback.call(this, data.conversations ); }); } self.fetchMentions = function( callback ) { var url = convoreApiUrl + '/account/mentions.json'; $.getJSON(url, function(data) { callback.call(this, data.unread , data.mentions ); }); } self.postMessage = function( topicId , message , callback ) { var url = convoreApiUrl + '/topics/' + topicId + '/messages/create.json'; $.post(url, {message: message}, function(data) { callback.call( this , data.message ); }); } self.createNewGroup = function( newGroup , callback ) { var url = convoreApiUrl + '/groups/create.json'; $.post(url, {name: newGroup.name, kind: newGroup.kind }, function(data) { callback.call( this , data.group ); }); } self.createNewTopic = function( groupId , newTopic , callback ) { var url = convoreApiUrl + '/groups/' + groupId + '/topics/create.json'; $.post(url, {name: newTopic.name}, function(data) { callback.call( this , data.topic ); }); } self.starMessage = function( msgId , callback ) { var url = convoreApiUrl + '/messages/' + msgId + '/star.json'; $.post(url, function(data) { callback.call( this , data ); }); } }
var webpack = require('webpack'); var path = require('path'); var ExtractText = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var VENDOR_LIBS = [ 'react' ]; var config = { entry: { bundle: './src/client/index.js', vendor: VENDOR_LIBS }, output: { path: path.join(__dirname, 'dist/client'), // bundle.js && vendor.js output name + hash filename: '[name].[chunkhash].js' }, module: { // Babel config rules: [ { test: /\.js$/, use: { loader: 'babel-loader' }, exclude: /(node_modules)/ }, // Sass config { test: /\.scss$/, use: ExtractText.extract({ fallback: 'style-loader', use: ['css-loader', 'sass-loader'] }) }, // Image & url config { test: /\.(jpe?g|png|gif|svg)$/, use: [ { loader: 'file-loader', options: { limit: 40000 } }, 'image-webpack-loader' ] } ] }, plugins: [ // Create style file from the JS files what import fragments of SCSS or CSS new ExtractText('style.css'), // Load from cache vendor file new webpack.optimize.CommonsChunkPlugin({ name: ['vendor', 'manifest'] }), // Generate index.html with bundle & vendor files new HtmlWebpackPlugin({ template: 'src/client/index.html' }), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) }), ] }; module.exports = config;
const settings = require('./../../settings.json'); const Discord = require('discord.js'); /** * This method should return the response directly to the channel * @param {*string array} params * @param {*message} message */ async function command(params, message) { const guild = message.guild; let embed = new Discord.MessageEmbed() .setThumbnail(guild.iconURL) .setTitle(guild.name) .setAuthor(guild.owner.user.username, guild.owner.user.displayAvatarURL) .setTimestamp(guild.createdAt) .addField('Members: ', guild.memberCount, true) .addField('Online: ', guild.presences.map(p => p.status != 'offline').length, true) .addField('Region: ', guild.region, true); let r = '__**Roles**__:\n' guild.roles.map((role) => { if (role.name != '@everyone') r = r + "**" + role.name + "**: " + role.members.size + '\n'; }); embed.setDescription(r); message.channel.send('', { embed: embed }).catch(message.channel.send); return true; } /** * description of the command */ const description = "Shows server stats"; /** * Define Exports */ module.exports = { execute: command, description: description, fun: true };
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ Records Per Page" } } ); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).addClass('pagination').append( '<ul>'+ '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, iLen=an.length ; i<iLen ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); }
'use strict'; /* Controllers */ var controllers = angular.module('myApp.controllers'); controllers.controller('EditSettlementController', ['$scope', '$location', '$routeParams', 'BLAPI', 'utils', function ($scope, $location, $routeParams, BLAPI, utils) { var self = this; //Set Active Links utils.setActiveLinks('TS', 'Edit'); //Set new TrustSettlementID $scope.TrustSettlementID = utils.setTrustSettlementID($routeParams.TrustSettlementID); //Variables var newClientID = -1; var newHeirID = -1; var newID = -1; //Testing $scope.myDate = new Date(); //Add variables for binding to the $scope $scope.data = {}; $scope.Settlements = []; $scope.Settlement = {}; $scope.hasSettlement = false; var settlementDateFields = ['DateRetained','DateClosed','Birthdate', 'DateOfDeath','DateOfTrust','DateOfTrustExecution','DateOfTrustRestatement','P15409HearingDate','RetainerReceived','DueDate','FirstDeathDOD']; var SettlementBooleanFields = ['IsArchived']; $scope.Trustors = {}; var TrustorsBooleanFields = ['IsMale']; $scope.Clients = {}; var ClientsDateFields = ['Birthdate']; var ClientsBooleanFields = ['IsMale','IsPrimary','IsTrustor']; $scope.Heirs = {}; var HeirsDateFields = ['Birthdate']; var HeirsBooleanFields = ['IsMale','IsMinor','IsDisinherited','IsCharity','IsSpecificBequest']; $scope.Preparers = []; $scope.Attorneys = []; $scope.Notaries = []; $scope.Paralegals = []; $scope.selectedPreparer = {}; $scope.selectedAttorney = {}; $scope.selectedNotary = {}; $scope.selectedParalegal = {}; $scope.Courthouses = []; $scope.SelectedCourthouse = null; $scope.TrustTypes = []; $scope.SelectedTrustType = null; //ui.date $scope.uiDateOptions = { changeYear: true, changeMonth: true, yearRange: '1900:+1' } $scope.settlementChanged = function () { // console.log('changed'); var TrustSettlementID = $scope.Settlement.TrustSettlementID; $scope.TrustSettlementID = TrustSettlementID; $location.search('TrustSettlementID', TrustSettlementID); utils.setTrustSettlementID(TrustSettlementID); self.getData(); }; //Courthouse Stuff $scope.courthouseChanged = function () { console.log($scope.SelectedCourthouse); if($scope.SelectedCourthouse != null && $scope.SelectedCourthouse.CourthouseID != null){ $scope.Settlement.P15409CourthouseID = $scope.SelectedCourthouse.CourthouseID; }else{ $scope.Settlement.P15409CourthouseID = null; } }; //Grid // $scope.myData = [{name: "Moroni", age: 50}, // {name: "Tiancum", age: 43}, // {name: "Jacob", age: 27}, // {name: "Nephi", age: 29}, // {name: "Enos", age: 34}]; // $scope.gridOptions = { // data: 'myData', // enableCellSelection: true, // enableRowSelection: false, // enableCellEdit: true, // columnDefs: [ // { field: 'name', displayName: 'Name', width: 200 }, // { field: 'age', displayName: 'Age', width: 200 } // ] // }; // StreetAddress, // City, // State, // Zip, // Phone, // Email, // Gender $scope.trustorGridOptions = { data: 'Trustors', enableCellSelection: true, enableRowSelection: false, enableCellEditOnFocus: true, columnDefs: [ { field: '', displayName: '', enableCellEdit: false, sortable: false, groupable: false, width: 24, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><i ng-click="deleteTrustor(row.entity)" title="Delete Trustor" class="link glyphicon glyphicon-remove"></i></div>' }, { field: 'IsMale', displayName: 'Male?', width: 60, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'Name', displayName: 'Name', width: 110 } ], plugins: [new ngGridFlexibleHeightPlugin()] }; $scope.clientGridOptions = { data: 'Clients', enableCellSelection: true, enableRowSelection: false, enableCellEditOnFocus: true, columnDefs: [ { field: '', displayName: '', enableCellEdit: false, sortable: false, groupable: false, width: 24, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><i ng-click="deleteClient(row.entity)" title="Delete Client" class="link glyphicon glyphicon-remove"></i></div>' }, { field: 'IsPrimary', displayName: 'Primary', width: 65, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' // editableCellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" ng-model="row.entity.IsPrimary" /></div>' }, { field: 'IsMale', displayName: 'Male?', width: 60, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'IsTrustor', displayName: 'Trustor', width: 65, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'FirstName', displayName: 'First Name', width: 110 }, { field: 'MiddleName', displayName: 'Middle', width: 70 }, { field: 'LastName', displayName: 'Last Name', width: 110 }, { field: 'RelationshipToDecedent', displayName: 'Relationship', width: 200 }, { field: 'StreetAddress', displayName: 'Address', width: 200 }, { field: 'City', displayName: 'City', width: 120 }, { field: 'State', displayName: 'State', width: 50 }, { field: 'Zip', displayName: 'Zip', width: 100 }, { field: 'County', displayName: 'County', width: 100 }, { field: 'Country', displayName: 'Country (if not USA)', width: 150 }, { field: 'SSN', displayName: 'SSN', width: 100 }, { field: 'Phone', displayName: 'Phone', width: 140 }, { field: 'Phone2', displayName: 'Phone 2', width: 140 }, { field: 'Email', displayName: 'Email', width: 200 }, { field: '_Birthdate', displayName: 'Birthdate', width: 100, enableCellEdit: false, cellTemplate: '<div ng-class="col.colIndex()"><input type="text" ui-date="uiDateOptions" class="ngCellDateInput" ng-model="COL_FIELD" /></div>' } ], plugins: [new ngGridFlexibleHeightPlugin()] }; $scope.heirGridOptions = { data: 'Heirs', enableCellSelection: true, enableRowSelection: false, enableCellEditOnFocus: true, columnDefs: [ { field: 'TSHeirID', displayName: '', enableCellEdit: false, sortable: false, groupable: false, width: 24, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><i ng-click="deleteHeir(row.entity)" title="Delete Heir" class="link glyphicon glyphicon-remove"></i></div>' }, { field: 'IsMinor', displayName: 'Minor', width: 55, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'IsMale', displayName: 'Male', width: 50, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'IsCharity', displayName: 'Charity', width: 60, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'FirstName', displayName: 'First Name / Charity Name', width: 230 }, { field: 'MiddleName', displayName: 'Middle', width: 70 }, { field: 'LastName', displayName: 'Last Name', width: 110 }, { field: 'RelationshipToDecedent', displayName: 'Relationship', width: 200 }, { field: 'StreetAddress', displayName: 'Address', width: 250 }, { field: 'City', displayName: 'City', width: 120 }, { field: 'State', displayName: 'State', width: 100 }, { field: 'Zip', displayName: 'Zip', width: 100 }, { field: 'Country', displayName: 'Country (if not USA)', width: 150 }, { field: 'IsDisinherited', displayName: 'Disinherit', width: 80, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'IsSpecificBequest', displayName: 'Spec. Beq.', width: 90, enableCellEdit: false, cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><input type="checkbox" style="margin: 5px;" ng-model="COL_FIELD" /></div>' }, { field: 'SpecificGift', displayName: 'Specific Gift Description', width: 200 }, { field: 'SSN', displayName: 'SSN', width: 100 }, { field: 'Phone', displayName: 'Phone', width: 120 }, { field: 'Phone2', displayName: 'Phone 2', width: 120 }, { field: 'Email', displayName: 'Email', width: 200 }, { field: '_Birthdate', displayName: 'Birthdate', width: 100, enableCellEdit: false, cellTemplate: '<div ng-class="col.colIndex()"><input type="text" ui-date="uiDateOptions" class="ngCellDateInput" ng-model="COL_FIELD" /></div>' } ], plugins: [new ngGridFlexibleHeightPlugin()] }; //Scope and Watches self.addWatches = function(){ $scope.$watch('selectedPreparer', function(newValue, oldValue){ $scope.Settlement.PreparerID = newValue.EmployeeID; }); $scope.$watch('selectedAttorney', function(newValue, oldValue){ $scope.Settlement.AttorneyID = newValue.EmployeeID; }); $scope.$watch('selectedNotary', function(newValue, oldValue){ $scope.Settlement.NotaryID = newValue.EmployeeID; }); $scope.$watch('selectedParalegal', function(newValue, oldValue){ $scope.Settlement.ParalegalID = newValue.EmployeeID; }); }; //Getting Initial data self.init = function () { self.addWatches(); self.getData(); }; self.getData = function () { //Get All data in one shot var trustSettlementID = $scope.TrustSettlementID; if (trustSettlementID == null){ trustSettlementID = -1; } BLAPI.get('TrustSettlements/Edit?TrustSettlementID=' + trustSettlementID, function (data) { var Settlement = data.Settlement; var Settlements = data.Settlements; // var TrustSettlementID = $scope.TrustSettlementID; // if (TrustSettlementID != null) { // var Settlement = _.find(Settlements, function (item) { // //Do only == since the TrustSettlementID routeParam is a string (e.g. '1') // return item.TrustSettlementID == TrustSettlementID; // }); // } //Employees $scope.Preparers = data.Employees.Preparers; $scope.Attorneys = data.Employees.Attorneys; $scope.Paralegals = data.Employees.Paralegals; $scope.Notaries = data.Employees.Notaries; //Courthouses data.Courthouses.splice(0,0,{P15409CourthouseID: null}); $scope.Courthouses = data.Courthouses; $scope.Settlements = Settlements; if (Settlement != null){ utils.createShadowDateProperties(Settlement, settlementDateFields); utils.setBooleanProperties(Settlement, SettlementBooleanFields); $scope.Settlement = Settlement; $scope.hasSettlement = true; //The selected Preparer is the one save to the database, otherwise set it to the default var PreparerID = Settlement.PreparerID; if (PreparerID != null){ $scope.selectedPreparer = _.find($scope.Preparers, function(item){ return item.EmployeeID === PreparerID; }); }else{ $scope.selectedPreparer = _.find($scope.Preparers, function(item){ return item.IsDefaultForRole == true; }); } var AttorneyID = Settlement.AttorneyID; if (AttorneyID != null){ $scope.selectedAttorney = _.find($scope.Attorneys, function(item){ return item.EmployeeID === AttorneyID; }); }else{ $scope.selectedAttorney = _.find($scope.Attorneys, function(item){ return item.IsDefaultForRole == true; }); } var NotaryID = Settlement.NotaryID; if (NotaryID != null){ $scope.selectedNotary = _.find($scope.Notaries, function(item){ return item.EmployeeID === NotaryID; }); }else{ $scope.selectedNotary = _.find($scope.Notaries, function(item){ return item.IsDefaultForRole == true; }); } var ParalegalID = Settlement.ParalegalID; if (ParalegalID != null){ $scope.selectedParalegal = _.find($scope.Paralegals, function(item){ return item.EmployeeID === ParalegalID; }); }else{ $scope.selectedParalegal = _.find($scope.Paralegals, function(item){ return item.IsDefaultForRole == true; }); } //Courthouse selection var P15409CourthouseID = Settlement.P15409CourthouseID; if (P15409CourthouseID != null){ $scope.SelectedCourthouse = _.find($scope.Courthouses, function(item){ return item.CourthouseID === P15409CourthouseID; }); } }else{ $scope.hasSettlement = false; } //Clients var Clients = data.Clients; for(var i = 0; i < Clients.length; i++){ var item = Clients[i]; utils.setBooleanProperties(item, ClientsBooleanFields); utils.createShadowDateProperties(item, ClientsDateFields); } //Add a dummy row if empty if (Clients.length == 0){ Clients.push( { TSClientID: newClientID--, TrustSettlementID: $scope.TrustSettlementID, IsMale: false, IsPrimary: true } ); } $scope.Clients = Clients; //Heirs var Heirs = data.Heirs; utils.setBooleanProperties(Heirs, HeirsBooleanFields); utils.createShadowDateProperties(Heirs, HeirsDateFields); // for(var i = 0; i < Heirs.length; i++){ // var item = Heirs[i]; // utils.setBooleanProperties(item, HeirsBooleanFields); // utils.createShadowDateProperties(item, HeirsDateFields); // } //Add a dummy row if empty $scope.Heirs = Heirs; //Trustors var Trustors = data.Trustors; utils.setBooleanProperties(Trustors, TrustorsBooleanFields); $scope.Trustors = data.Trustors; $scope.settlementEmptyOption = 'Please Select a Settlement'; $scope.data = data; }); //end getData callback };//end getData self.validateSettlement = function(settlement){ var isValid = utils.hasValidTextFields(settlement, ['FileName', 'DecedentFirstName', 'DecedentLastName']); //console.log('here ' + isValid); // isValid = isValid && utils.hasValidDateFields(settlement, ['DateOfDeath']); return isValid; }; //Other Handlers $scope.saveSettlement = function () { if (utils.canProcess()){ var Settlement = $scope.Settlement; var Clients = $scope.Clients; var Heirs = $scope.Heirs; utils.mergeShadowDateProperties(Settlement, settlementDateFields); utils.mergeShadowDateProperties(Clients, ClientsDateFields); utils.mergeShadowDateProperties(Heirs, HeirsDateFields); var isValid = self.validateSettlement(Settlement); if (isValid) { // var postData = { // Settlement: Settlement, // Clients: Clients, // Heirs: Heirs, // Trustors: $scope.Trustors // }; var postData = $scope.data; BLAPI.post('TrustSettlements/Edit', postData, function (data) { utils.setMessage('Saved'); self.getData(); }); }else{ utils.setMessage('Cannot save. Missing fields!', 'warning'); } } }; $scope.addClient = function(){ if (utils.canProcess()){ $scope.Clients.push( { TSClientID: newClientID--, TrustSettlementID: $scope.TrustSettlementID, IsMale: false, IsPrimary: $scope.Clients.length == 0 ? true : false } ); } }; $scope.deleteClient = function(client){ if (utils.canProcess()){ var TSClientID = client.TSClientID; //console.log(TSClientID); if (TSClientID > 0){ var confirmDelete = confirm('Are you sure you want to delete the client?'); if (confirmDelete){ var postData = { FilterType: 'Delete', TSClientID: TSClientID }; BLAPI.post('TrustSettlements/Client', postData, function(data){ utils.setMessage('Client deleted') self.getData(); }); } }else { $scope.Clients = _.pull($scope.Clients, client); } //dlg = $dialogs.notify('Something Happened!','Something happened that I need to tell you.'); } }; //Trustors $scope.addTrustor = function(){ if (utils.canProcess()){ $scope.Trustors.push( { TSTrustorID: newID--, TrustSettlementID: $scope.TrustSettlementID, IsMale: false } ); } }; $scope.deleteTrustor = function(obj){ if (utils.canProcess()){ var TSTrustorID = obj.TSTrustorID; //console.log(TSTrustorID); if (TSTrustorID > 0){ var confirmDelete = confirm('Are you sure you want to delete the client?'); if (confirmDelete){ var postData = { FilterType: 'Delete', TSTrustorID: TSTrustorID }; BLAPI.post('TrustSettlements/Trustor?FilterType=Delete', postData, function(data){ utils.setMessage('Trustor deleted') self.getData(); }); } }else { $scope.Trustors = _.pull($scope.Trustors, client); } //dlg = $dialogs.notify('Something Happened!','Something happened that I need to tell you.'); } }; $scope.addHeir = function(){ if (utils.canProcess()){ $scope.Heirs.push( { TSHeirID: newHeirID--, TrustSettlementID: $scope.TrustSettlementID, IsMale: false, IsMinor: false, IsDisinherited: false } ); } }; $scope.deleteHeir = function(heir){ if (utils.canProcess()){ var TSHeirID = heir.TSHeirID; if (TSHeirID > 0){ var confirmDelete = confirm('Are you sure you want to delete the beneficiary?'); if (confirmDelete){ var postData = { FilterType: 'Delete', TSHeirID: TSHeirID }; BLAPI.post('TrustSettlements/Heirs?FilterType=Delete', postData, function(data){ utils.setMessage('Beneficiary deleted') self.getData(); }); } }else { $scope.Heirs = _.pull($scope.Heirs, heir); } } }; //Always call initialize self.init(); }]);
'use strict'; angular.module('mgcrea.ngStrap.select', ['mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.parseOptions']) .provider('$select', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'select', placement: 'bottom-left', template: 'partials/AngularStrap/select.tpl.html', trigger: 'focus', container: false, keyboard: true, html: false, delay: 0, multiple: false, sort: true, caretHtml: '&nbsp;<span class="caret"></span>', placeholder: 'Choose among the following...' }; this.$get = function($window, $document, $rootScope, $tooltip) { var bodyEl = angular.element($window.document.body); var isTouch = 'createTouch' in $window.document; function SelectFactory(element, controller, config) { var $select = {}; // Common vars var options = angular.extend({}, defaults, config); $select = $tooltip(element, options); var parentScope = config.scope; var scope = $select.$scope; scope.$matches = []; scope.$activeIndex = 0; scope.$isMultiple = options.multiple; scope.$activate = function(index) { scope.$$postDigest(function() { $select.activate(index); }); }; scope.$select = function(index, evt) { scope.$$postDigest(function() { $select.select(index); }); }; scope.$isVisible = function() { return $select.$isVisible(); }; scope.$isActive = function(index) { return $select.$isActive(index); }; // Public methods $select.update = function(matches) { scope.$matches = matches; $select.$updateActiveIndex(); }; $select.activate = function(index) { if(options.multiple) { scope.$activeIndex.sort(); $select.$isActive(index) ? scope.$activeIndex.splice(scope.$activeIndex.indexOf(index), 1) : scope.$activeIndex.push(index); if(options.sort) scope.$activeIndex.sort(); } else { scope.$activeIndex = index; } return scope.$activeIndex; }; $select.select = function(index) { var value = scope.$matches[index].value; $select.activate(index); if(options.multiple) { controller.$setViewValue(scope.$activeIndex.map(function(index) { return scope.$matches[index].value; })); } else { controller.$setViewValue(value); } controller.$render(); if(parentScope) parentScope.$digest(); // Hide if single select if(!options.multiple) { if(options.trigger === 'focus') element[0].blur(); else if($select.$isShown) $select.hide(); } // Emit event scope.$emit('$select.select', value, index); }; // Protected methods $select.$updateActiveIndex = function() { if(controller.$modelValue && scope.$matches.length) { if(options.multiple && angular.isArray(controller.$modelValue)) { scope.$activeIndex = controller.$modelValue.map(function(value) { return $select.$getIndex(value); }); } else { scope.$activeIndex = $select.$getIndex(controller.$modelValue); } } else if(scope.$activeIndex >= scope.$matches.length) { scope.$activeIndex = options.multiple ? [] : 0; } }; $select.$isVisible = function() { if(!options.minLength || !controller) { return scope.$matches.length; } // minLength support return scope.$matches.length && controller.$viewValue.length >= options.minLength; }; $select.$isActive = function(index) { if(options.multiple) { return scope.$activeIndex.indexOf(index) !== -1; } else { return scope.$activeIndex === index; } }; $select.$getIndex = function(value) { var l = scope.$matches.length, i = l; if(!l) return; for(i = l; i--;) { if(scope.$matches[i].value === value) break; } if(i < 0) return; return i; }; $select.$onElementMouseDown = function(evt) { evt.preventDefault(); evt.stopPropagation(); if($select.$isShown) { element[0].blur(); } else { element[0].focus(); } }; $select.$onMouseDown = function(evt) { // Prevent blur on mousedown on .dropdown-menu evt.preventDefault(); evt.stopPropagation(); // Emulate click for mobile devices if(isTouch) { var targetEl = angular.element(evt.target); targetEl.triggerHandler('click'); } }; $select.$onKeyDown = function(evt) { if (!/(38|40|13)/.test(evt.keyCode)) return; evt.preventDefault(); evt.stopPropagation(); // Select with enter if(evt.keyCode === 13) { return $select.select(scope.$activeIndex); } // Navigate with keyboard if(evt.keyCode === 38 && scope.$activeIndex > 0) scope.$activeIndex--; else if(evt.keyCode === 40 && scope.$activeIndex < scope.$matches.length - 1) scope.$activeIndex++; else if(angular.isUndefined(scope.$activeIndex)) scope.$activeIndex = 0; scope.$digest(); }; // Overrides var _init = $select.init; $select.init = function() { _init(); element.on(isTouch ? 'touchstart' : 'mousedown', $select.$onElementMouseDown); }; var _destroy = $select.destroy; $select.destroy = function() { _destroy(); element.off(isTouch ? 'touchstart' : 'mousedown', $select.$onElementMouseDown); }; var _show = $select.show; $select.show = function() { _show(); if(options.multiple) { $select.$element.addClass('select-multiple'); } setTimeout(function() { $select.$element.on(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); if(options.keyboard) { element.on('keydown', $select.$onKeyDown); } }); }; var _hide = $select.hide; $select.hide = function() { $select.$element.off(isTouch ? 'touchstart' : 'mousedown', $select.$onMouseDown); if(options.keyboard) { element.off('keydown', $select.$onKeyDown); } _hide(); }; return $select; } SelectFactory.defaults = defaults; return SelectFactory; }; }) .directive('bsSelect', function($window, $parse, $q, $select, $parseOptions) { var defaults = $select.defaults; return { restrict: 'EAC', require: 'ngModel', link: function postLink(scope, element, attr, controller) { // Directive options var options = {scope: scope}; angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'placeholder', 'multiple'], function(key) { if(angular.isDefined(attr[key])) options[key] = attr[key]; }); // if(element[0].nodeName.toLowerCase() === 'select') { // var inputEl = element; // inputEl.css('display', 'none'); // element = angular.element('<div class="btn btn-default"></div>'); // inputEl.after(element); // } // Build proper ngOptions var parsedOptions = $parseOptions(attr.ngOptions); // Initialize select var select = $select(element, controller, options); // Watch ngOptions values before filtering for changes var watchedOptions = parsedOptions.$match[7].replace(/\|.+/, '').trim(); scope.$watch(watchedOptions, function(newValue, oldValue) { // console.warn('scope.$watch(%s)', watchedOptions, newValue, oldValue); parsedOptions.valuesFn(scope, controller) .then(function(values) { select.update(values); controller.$render(); }); }, true); // Watch model for changes scope.$watch(attr.ngModel, function(newValue, oldValue) { // console.warn('scope.$watch(%s)', attr.ngModel, newValue, oldValue); select.$updateActiveIndex(); }, true); // Model rendering in view controller.$render = function () { // console.warn('$render', element.attr('ng-model'), 'controller.$modelValue', typeof controller.$modelValue, controller.$modelValue, 'controller.$viewValue', typeof controller.$viewValue, controller.$viewValue); var selected, index; if(options.multiple && angular.isArray(controller.$modelValue)) { selected = controller.$modelValue.map(function(value) { index = select.$getIndex(value); return angular.isDefined(index) ? select.$scope.$matches[index].label : false; }).filter(angular.isDefined).join(', '); } else { index = select.$getIndex(controller.$modelValue); selected = angular.isDefined(index) ? select.$scope.$matches[index].label : false; } element.html((selected ? selected : attr.placeholder || defaults.placeholder) + defaults.caretHtml); }; // Garbage collection scope.$on('$destroy', function() { select.destroy(); options = null; select = null; }); } }; });
/*! * Elbit Jesse James Pub Project v0.0.1 (http://elbit.com.br/) * Copyright 2013-2017 Elbit Developers * Licensed under MIT (https://github.com/elbitdigital/base/blob/master/LICENSE) */
var bitset_8h = [ [ "reduce", "namespacehryky.html#af7b750a06d6c5b780d3473e3fa1e7bf9", null ], [ "swap", "namespacehryky.html#a73dbc149899a54cca88e0c14c00bb173", null ] ];
/*global app*/ app.service('UtilService', ['$rootScope', '$localStorage', function($rootScope, $localStorage){ 'use strict'; var service = {}; service.setSessionUser = function(user){ $localStorage.user = { id: user.usu_id, name: user.usu_nome, email: user.usu_email, telefon: user.usu_fone }; //$rootScope.$broadcast('headerMenuBroadcast'); }; service.clearStorage = function(){ $localStorage.user = undefined; $rootScope.$broadcast('headerMenuBroadcast'); }; service.setCurrentMenu = function($scope, $location){ $scope.location = $location; $scope.$watch('location.url()', getTitle); function getTitle() { $scope.pageTitle = $location.url().substring(1); } $rootScope.$broadcast('headerSeCurrentMenuBroadcast', $scope.location.$$path); }; return service; }]);
var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { if (typeof parent.__extend == 'function') return parent.__extend(child); for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; if (typeof parent.extended == 'function') parent.extended(child); return child; }; App.Tasklist = (function(_super) { var Tasklist; function Tasklist() { return Tasklist.__super__.constructor.apply(this, arguments); } Tasklist = __extends(Tasklist, _super); Tasklist.field('title', { type: 'String' }); Tasklist.belongsTo('project', { type: 'Project' }); Tasklist.hasMany('tasks'); Tasklist.timestamps(); Tasklist.belongsTo('user', { type: 'User' }); return Tasklist; })(Tower.Model);
// This object will be sent everytime you submit a message in the sendMessage function. var clientInformation = { username: new Date().getTime().toString() // You can add more information in a static object }; // START SOCKET CONFIG /** * Note that you need to change the "sandbox" for the URL of your project. * According to the configuration in Sockets/Chat.php , change the port if you need to. * @type WebSocket */ var conn = new WebSocket('ws://localhost:8081/chatserv'); conn.onopen = function(e) { console.info("Connection established succesfully"); }; conn.onmessage = function(e) { var data = JSON.parse(e.data); Chat.appendMessage(data.username, data.message); console.log(data); }; conn.onerror = function(e){ // TODO: Change error showing method alert("Error: something went wrong with the socket."); console.error(e); }; // END SOCKET CONFIG /// Some code to add the messages to the list element and the message submit. document.getElementById("form-submit").addEventListener("click",function(){ var msg = document.getElementById("form-message").value; if(!msg){ alert("Please send something on the chat"); } Chat.sendMessage(msg); // Empty text area document.getElementById("form-message").value = ""; }, false); // Mini API to send a message with the socket and append a message in a UL element. var Chat = { appendMessage: function(username,message){ var from; if(username === clientInformation.username){ from = "me"; }else{ from = clientInformation.username; } // Append List Item var ul = document.getElementById("chat-list"); var li = document.createElement("li"); li.appendChild(document.createTextNode(from + " : "+ message)); ul.appendChild(li); }, sendMessage: function(text){ clientInformation.message = text; // Send info as JSON conn.send(JSON.stringify(clientInformation)); // Add my own message to the list this.appendMessage(clientInformation.username, clientInformation.message); } };
/** * Hilo 1.0.0 for cmd * Copyright 2016 alibaba.com * Licensed under the MIT License */ define(function(require, exports, module){ var Hilo = require('hilo/core/Hilo'); var Class = require('hilo/core/Class'); var View = require('hilo/view/View'); var Drawable = require('hilo/view/Drawable'); /** * Hilo * Copyright 2015 alibaba.com * Licensed under the MIT License */ /** * <iframe src='../../../examples/DOMElement.html?noHeader' width = '330' height = '250' scrolling='no'></iframe> * <br/> * 使用示例: * <pre> * var domView = new Hilo.DOMElement({ * element: Hilo.createElement('div', { * style: { * backgroundColor: '#004eff', * position: 'absolute' * } * }), * width: 100, * height: 100, * x: 50, * y: 70 * }).addTo(stage); * </pre> * @name DOMElement * @class DOMElement是dom元素的包装。 * @augments View * @param {Object} properties 创建对象的属性参数。可包含此类所有可写属性。特殊属性有: * <ul> * <li><b>element</b> - 要包装的dom元素。必需。</li> * </ul> * @module hilo/view/DOMElement * @requires hilo/core/Hilo * @requires hilo/core/Class * @requires hilo/view/View * @requires hilo/view/Drawable */ var DOMElement = Class.create(/** @lends DOMElement.prototype */{ Extends: View, constructor: function(properties){ properties = properties || {}; this.id = this.id || properties.id || Hilo.getUid("DOMElement"); DOMElement.superclass.constructor.call(this, properties); this.drawable = new Drawable(); var elem = this.drawable.domElement = properties.element || Hilo.createElement('div'); elem.id = this.id; }, /** * 覆盖渲染方法。 * @private */ _render: function(renderer, delta){ if(!this.onUpdate || this.onUpdate(delta) !== false){ renderer.transform(this); if(this.visible && this.alpha > 0){ this.render(renderer, delta); } } }, /** * 覆盖渲染方法。 * @private */ render: function(renderer, delta){ var canvas = renderer.canvas; if(canvas.getContext){ var elem = this.drawable.domElement, depth = this.depth, nextElement = canvas.nextSibling, nextDepth; if(elem.parentNode) return; //draw dom element just after stage canvas while(nextElement && nextElement.nodeType != 3){ nextDepth = parseInt(nextElement.style.zIndex) || 0; if(nextDepth <= 0 || nextDepth > depth){ break; } nextElement = nextElement.nextSibling; } canvas.parentNode.insertBefore(this.drawable.domElement, nextElement); }else{ renderer.draw(this); } } }); return DOMElement; });
var gulp = require('gulp'); var autoprefixer = require('gulp-autoprefixer'); var bust = require('gulp-buster'); var clean = require('gulp-clean-css'); var concat = require('gulp-concat'); var jshint = require('gulp-jshint'); var livereload = require('gulp-livereload'); var rename = require('gulp-rename'); var stylus = require('gulp-stylus'); var uglify = require('gulp-uglify'); // Copy tasks. gulp.task('copy:normalize-css', function () { return gulp.src('node_modules/normalize.css/normalize.css') .pipe(gulp.dest('public/styles')); }); gulp.task('copy:fonts', function () { return gulp.src('node_modules/font-awesome/fonts/*') .pipe(gulp.dest('public/fonts')); }); gulp.task('copy:fonts-css', function () { return gulp.src('node_modules/font-awesome/css/font-awesome.css') .pipe(gulp.dest('public/styles')); }); gulp.task('copy:velocity', function () { return gulp.src('node_modules/velocity-animate/velocity.js') .pipe(gulp.dest('public/scripts')); }); gulp.task('copy:flatpickr:scripts', function () { return gulp.src('node_modules/flatpickr/dist/flatpickr.js') .pipe(gulp.dest('public/scripts')); }); gulp.task('copy:flatpickr:styles', function () { return gulp.src('node_modules/flatpickr/dist/flatpickr.css') .pipe(gulp.dest('public/styles')); }); // Build tasks. gulp.task('build:normalize-css', function () { return gulp.src('public/styles/normalize.css') .pipe(rename('normalize.min.css')) .pipe(clean({ compatibility: 'ie8' })) .pipe(gulp.dest('public/styles')); }); gulp.task('build:fonts-css', function () { return gulp.src('node_modules/font-awesome/css/font-awesome.min.css') .pipe(gulp.dest('public/styles')); }); gulp.task('build:velocity', function () { return gulp.src('node_modules/velocity-animate/velocity.min.js') .pipe(gulp.dest('public/scripts')); }); gulp.task('build:flatpickr:scripts', function () { return gulp.src('node_modules/flatpickr/dist/flatpickr.min.js') .pipe(gulp.dest('public/scripts')); }); gulp.task('build:flatpickr:styles', function () { return gulp.src('node_modules/flatpickr/dist/flatpickr.min.css') .pipe(gulp.dest('public/styles')); }); gulp.task('jshint', function () { return gulp.src('scripts/*') .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); gulp.task('build:scripts', ['jshint'], function () { return gulp.src('scripts/*') .pipe(concat('main.js')) .pipe(gulp.dest('public/scripts')) .pipe(livereload()) .pipe(rename('main.min.js')) .pipe(uglify()) .pipe(gulp.dest('public/scripts')); }); gulp.task('build:styles', function () { return gulp.src('styles/main.styl') .pipe(stylus({ 'include css': true })) .pipe(autoprefixer({ browsers: ['last 2 version', 'ie 8', 'ie 9'], cascade: false, remove: false })) .pipe(gulp.dest('public/styles')) .pipe(livereload()) .pipe(rename('main.min.css')) .pipe(clean({ compatibility: 'ie8' })) .pipe(gulp.dest('public/styles')); }); // Cachebusting. function bustCache() { return gulp.src(['public/scripts/*', 'public/styles/*']) .pipe(bust({ fileName: 'cachebuster.php', formatter: function (hashes) { var file = '<?php // Generated file; do not edit.\n'; file += 'return array(\n'; for (var path in hashes) { if (!hashes.hasOwnProperty(path)) { continue; } var hash = hashes[path]; path = path.replace(/(scripts|styles)\//, ''); file += '\'' + path + '\' => \'' + hash + '\',\n'; } file += ');\n'; return file; }, relativePath: 'public' })) .pipe(gulp.dest('')); } gulp.task('bust:scripts', ['build:scripts'], bustCache); gulp.task('bust:styles', ['build:styles'], bustCache); // Watch task. gulp.task('watch', function () { livereload.listen({quiet: true}); gulp.watch('scripts/*', ['bust:scripts']); gulp.watch('styles/**/*', ['bust:styles']); }); // Default task (copy, build, cachebust). gulp.task('default', [ 'copy:normalize-css', 'copy:fonts', 'copy:fonts-css', 'copy:velocity', 'copy:flatpickr:scripts', 'copy:flatpickr:styles', 'build:normalize-css', 'build:fonts-css', 'build:velocity', 'build:flatpickr:scripts', 'build:flatpickr:styles', 'build:scripts', 'build:styles' ], bustCache );
;(function ( $, window, document, undefined ) { var pluginName = "propertySelect", defaults = { }; function Plugin( element, options ) { this.element = element; this.options = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function() { var plugin = this; $(this.element).append("<img src='"+this.options.tool.icon+"' style='max-height:30px'/><span>"+this.options.tool.label+"</span>"); if (this.options.tool.toggle){ $(this.element).addClass('toggle'); } $(this.element).click(function(){ DisconnectHandlers(toolhandlers); if($(".selectpanel").length == 0){ plugin.addSelectPanel($(this).offset().top, $(this).offset().left, $(this).width()+10); }else{ $(".selectpanel").toggle(); MoveZoomSlider($("#tools").width() + $(".selectpanel").width()+60); } plugin.activateSelectDrawToolbar(); }); }, addSelectPanel:function (top, left, width){ var plugin = this; //var selectpanel = $("<ul class='selectpanel' style='background:#666;position:absolute;top:"+top+"px;left:"+(left+width)+"px;max-width:80px;font-size:12px'><li class='selectli' value='point'><img src='./img/select_point_default.png'>Point</img></li><li class='selectli' value='multipoint'><img src='./img/select_multi_default.png'>Multi-Point</img></li><li class='selectli' value='polygon'><img src='./img/select_polygon_default.png'>Polygon</img></li><li><input id='buffercheck' type='checkbox'><label for='buffercheck' class='checklabel' style='font-size:10px;margin-bottom:5px'>Buffer?</label></input></input> <input id='bufferdist' type='number' value='0'></input><p/></li><li><input id='selectFreehand' type='checkbox' checked='checked'></input><label for='selectFreehand' class='checklabel' style='font-size:10px'>Freehand?</label></li></ul>"); var selectpanel = $("<ul class='selectpanel' style='background:#666;position:absolute;top:"+top+"px;left:"+(left+width)+"px;max-width:80px;font-size:12px'><li class='selectli' value='point'><img src='./img/select_point_default.png'>Point</img></li><li class='selectli' value='multipoint'><img src='./img/select_multi_default.png'>Multi-Point</img></li><li class='selectli' value='polygon'><img src='./img/select_polygon_default.png'>Polygon</img></li><li><button id='buffercheck' type='button' class='btn btn-danger btn-xs'>Buffer?</button><input id='bufferdist' type='number' value='0'></input><p/></li><li><button id='selectFreehand' type='button' class='btn btn-success btn-xs'>Freehand?</button></li></ul>"); $("body").append(selectpanel); $("#bufferdist").kendoNumericTextBox({ format:"# ft", min:0, max:5000, step:50 }); $("#bufferdist").closest(".k-widget").css("width","80px"); $("#bufferdist").closest(".k-widget").css("display","none"); $("#bufferdist").closest(".k-numerictextbox").css("background-color","#ffffff"); /* $("#buffercheck").button().click(function(){ $("#bufferdist").closest(".k-widget").toggle(); });*/ $("#buffercheck").on('click', function () { if ($(this).hasClass('btn-success')) { $(this).removeClass('btn-success').addClass('btn-danger'); } else { $(this).removeClass('btn-danger').addClass('btn-success'); } $("#bufferdist").closest(".k-widget").toggle(); }); //$("#selectFreehand").button().click(function(){ // plugin.activateSelectDrawToolbar(this)}); $("#selectFreehand").on('click', function() { if ($(this).hasClass('btn-success')) { $(this).removeClass('btn-success').addClass('btn-danger'); } else { $(this).removeClass('btn-danger').addClass('btn-success'); } plugin.activateSelectDrawToolbar(this); }); $(".selectli").click(function(){ plugin.activateSelectDrawToolbar(this); }); $("#tools h3").click(function(){ if ($("#tools").hasClass('collapsed')) { $(".selectpanel").hide(); } else { if($(".tool.toggle.active span").html() === "Select") { $(".selectpanel").show(); } } if($(".selectpanel").css("display") == "none"){ MoveZoomSlider($("#tools").width()+30); }else{ MoveZoomSlider($("#tools").width() + $(".selectpanel").width()+60); } }); MoveZoomSlider($("#tools").width() + $(".selectpanel").width()+60); }, selectDrawEnd:function(geometry){ var plugin = this; var distance = $("#bufferdist").val(); /* if (!$("#buffercheck").prop("checked")){ distance = 0; }*/ if (!$("#buffercheck").hasClass('btn-success')) { distance = 0; } if (parseInt(distance) > 0){ require(["esri/tasks/BufferParameters"], function (BufferParameters) { var params = new BufferParameters(); params.distances = [parseInt(distance)]; params.bufferSpatialReference = map.spatialReference; params.outSpatialReference = map.spatialReference; params.unit = 9002; if (geometry.type === "polygon"){ geomService.simplify([geometry], function(geometries){ params.geometries = geometries; }); }else{ params.geometries = [geometry]; } geomService.buffer(params, function(geometries){ plugin.selectBufferComplete(geometries); }); }); }else{ this.addSelectGraphicToMap([geometry]); this.selectPropertyByGeometry([geometry]); } }, activateSelectDrawToolbar:function(element){ var plugin = this; if($(element).hasClass("selectli")){ this.changeSelectPanelItem(element); } drawtoolbar.deactivate(); DisconnectHandlers(drawhandlers); drawhandlers = []; if ($(".selectli.selected").length > 0){ var drawmode = $(".selectli.selected").attr("value"); //if($("#selectFreehand").is(":checked") && (drawmode == "polygon" || drawmode == "polyline")){ if($("#selectFreehand").hasClass("btn-success") && (drawmode == "polygon" || drawmode == "polyline")){ drawmode = "freehand"+drawmode; }else{ drawmode = drawmode.replace("freehand"); } drawtoolbar.activate(drawmode); drawhandlers.push(dojo.connect(drawtoolbar, "onDrawEnd", function(geometry){ plugin.selectDrawEnd(geometry); })); } }, changeSelectPanelItem:function(item){ $(".selectpanel li").each(function(i, tool){ if ($("img", tool).length > 0){ $("img", tool).attr("src",$("img", tool).attr("src").replace("_selected", "_default")); } $(tool).removeClass("selected"); }); $("img", item).attr("src",$("img", item).attr("src").replace("_default", "_selected")); $(item).addClass("selected"); }, selectPropertyByGeometry:function(geometries){ require(["esri/tasks/query", "esri/tasks/QueryTask"], function (Query, QueryTask) { var query = new Query(); query.geometry = geometries[0]; query.returnGeometry = false; query.outFields = ['PIN_NUM']; var qt = new QueryTask("http://maps.raleighnc.gov/arcgis/rest/services/Parcels/MapServer/0"); qt.execute(query, function(featureset){ var pins = []; $(featureset.features).each(function(i, feature){ pins.push(feature.attributes.PIN_NUM); }); var search = $("#accordion").propertySearch().data("plugin_propertySearch"); search.searchRealEstateAccounts(dojo.toJson(pins), "pin", false); }, function(error){ }); }); }, selectBufferComplete:function(geometries){ //this.addSelectGraphicToMap(geometries); this.selectPropertyByGeometry(geometries); map.setExtent(geometries[0].getExtent(), true); }, addSelectGraphicToMap:function(geometries){ require(["esri/graphic", "esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol", "esri/Color"], function (Graphic, SimpleFillSymbol, SimpleLineSymbol, Color){ var symbol = new SimpleFillSymbol( SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol( SimpleLineSymbol.STYLE_SOLID, new Color([255,0,0,0.65]), 2 ), new Color([255,0,0,0.35]) ); map.getLayer("selectgl").clear(); $(geometries).each(function(i, geometry){ map.getLayer("selectgl").add(new Graphic(geometry, symbol)); }); }); }, showProgress: function(options, message){ var dialog = $("#"+options.progressid); var messagediv = $("#"+options.messageid); if(dialog.length > 0 && messagediv.length > 0){ messagediv.html(message); dialog.dialog("open"); } }, hideProgress: function(options){ var dialog = $("#"+options.progressid); if(dialog.length > 0){ dialog.dialog("close"); } } }; $.fn[pluginName] = function ( options ) { return this.each(function () { //if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin( this, options )); //} }); }; })( jQuery, window, document );
import debugModule from 'debug'; import assert from 'assert'; const debug = debugModule('geteventstore:removeProjection'); const baseErr = 'Remove Projection - '; export default (config, httpClient) => async (name, deleteCheckpointStream, deleteStateStream) => { assert(name, `${baseErr}Name not provided`); deleteCheckpointStream = deleteCheckpointStream || false; deleteStateStream = deleteStateStream || false; const options = { url: `${config.baseUrl}/projection/${name}`, method: 'DELETE', params: { deleteCheckpointStream: deleteCheckpointStream ? 'yes' : 'no', deleteStateStream: deleteStateStream ? 'yes' : 'no' } }; debug('', 'Options: %j', options); const response = await httpClient(options); debug('', 'Response: %j', response.data); return response.data; };
/*jshint node: true*/ 'use strict'; module.exports = require('./lib/MetaInfo.js');
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "19", cy: "3", r: "3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M6 8V6h9.03c-1.21-1.6-1.08-3.21-.92-4H4.01c-1.1 0-2 .89-2 2L2 22l4-4h14c1.1 0 2-.9 2-2V6.97C21.16 7.61 20.13 8 19 8H6zm8 6H6v-2h8v2zm4-3H6V9h12v2z" }, "1")], 'MarkUnreadChatAlt'); exports.default = _default;
"use strict"; module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars ecs.add(function(entity, context) { // eslint-disable-line no-unused-vars context.fillStyle = "#006886"; context.fillRect(0, 0, data.canvas.width, data.canvas.height); }); };
<Form> <Form.Group controlId="exampleForm.ControlInput1"> <Form.Label>Email address</Form.Label> <Form.Control type="email" placeholder="name@example.com" /> </Form.Group> <Form.Group controlId="exampleForm.ControlSelect1"> <Form.Label>Example select</Form.Label> <Form.Control as="select"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </Form.Control> </Form.Group> <Form.Group controlId="exampleForm.ControlSelect2"> <Form.Label>Example multiple select</Form.Label> <Form.Control as="select" multiple> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </Form.Control> </Form.Group> <Form.Group controlId="exampleForm.ControlTextarea1"> <Form.Label>Example textarea</Form.Label> <Form.Control as="textarea" rows="3" /> </Form.Group> </Form>;
function Car(params) { this.make = params.make; this.model = params.model; this.color = params.color; this.passengers = params.passengers; this.convertible = params.convertible; this.mileage = params.mileage; this.started = false; this.start = function () { this.started = true; }; this.stop = function () { this.started = false; }; this.drive = function () { if (this.started) { console.log(this.make + " " + this.model + " goes zoom zoom!"); } else { console.log("Start the engine first."); } }; } function Dog(name, breed, weight) { this.name = name; this.breed = breed; this.weight = weight; this.bark = function() { if (this.weight > 25) { console.log(this.name + " says Woof!"); } else { console.log(this.name + " says Yip!"); } } } var limoParams = { make: "Webville Motors", model: "limo", year: 1983, color: "black", passengers: 12, convertible: true, mileage: 21120 }; var limo = new Car(limoParams); var limoDog = new Dog("Rhapsody In Blue", "Poodle", 40); console.log(limo.make + " " + limo.model + " is a " + typeof limo); console.log(limoDog.name + " is a " + typeof limoDog);
'use strict'; import React from 'react'; class Ping extends React.Component { constructor(props) { super(props); this.state = { text: 'nothing' }; this.myHeaders = new Headers(); this.myInit = { method: 'GET', headers: this.myHeaders, mode: 'cors', cache: 'default' }; } render() { return <div className="Ping">Response - {this.state.data}</div>; } componentDidMount() { console.log("Ping is working and will make an ajax invocation"); fetch('/admitone/services/administration/ping', this.myInit) .then( (response) => { console.log("Response: " + response.ok); return (response.ok) ? response.json() : {status: 'Failure'}; }) .then( (json) => { console.log("we are done: " + json.status); this.setState({data: json.status}); }); } } export default Ping;
define(function(require) { function init() { console.log('this is case-insensitive-bar init'); } return {init: init}; });
/** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import assert from "assert"; import * as leap from "./leap"; import * as meta from "./meta"; import * as util from "./util"; let hasOwn = Object.prototype.hasOwnProperty; function Emitter(contextId) { assert.ok(this instanceof Emitter); util.getTypes().assertIdentifier(contextId); // Used to generate unique temporary names. this.nextTempId = 0; // In order to make sure the context object does not collide with // anything in the local scope, we might have to rename it, so we // refer to it symbolically instead of just assuming that it will be // called "context". this.contextId = contextId; // An append-only list of Statements that grows each time this.emit is // called. this.listing = []; // A sparse array whose keys correspond to locations in this.listing // that have been marked as branch/jump targets. this.marked = [true]; this.insertedLocs = new Set(); // The last location will be marked when this.getDispatchLoop is // called. this.finalLoc = this.loc(); // A list of all leap.TryEntry statements emitted. this.tryEntries = []; // Each time we evaluate the body of a loop, we tell this.leapManager // to enter a nested loop context that determines the meaning of break // and continue statements therein. this.leapManager = new leap.LeapManager(this); } let Ep = Emitter.prototype; exports.Emitter = Emitter; // Offsets into this.listing that could be used as targets for branches or // jumps are represented as numeric Literal nodes. This representation has // the amazingly convenient benefit of allowing the exact value of the // location to be determined at any time, even after generating code that // refers to the location. Ep.loc = function() { const l = util.getTypes().numericLiteral(-1) this.insertedLocs.add(l); return l; } Ep.getInsertedLocs = function() { return this.insertedLocs; } Ep.getContextId = function() { return util.getTypes().clone(this.contextId); } // Sets the exact value of the given location to the offset of the next // Statement emitted. Ep.mark = function(loc) { util.getTypes().assertLiteral(loc); let index = this.listing.length; if (loc.value === -1) { loc.value = index; } else { // Locations can be marked redundantly, but their values cannot change // once set the first time. assert.strictEqual(loc.value, index); } this.marked[index] = true; return loc; }; Ep.emit = function(node) { const t = util.getTypes(); if (t.isExpression(node)) { node = t.expressionStatement(node); } t.assertStatement(node); this.listing.push(node); }; // Shorthand for emitting assignment statements. This will come in handy // for assignments to temporary variables. Ep.emitAssign = function(lhs, rhs) { this.emit(this.assign(lhs, rhs)); return lhs; }; // Shorthand for an assignment statement. Ep.assign = function(lhs, rhs) { const t = util.getTypes(); return t.expressionStatement( t.assignmentExpression("=", t.cloneDeep(lhs), rhs)); }; // Convenience function for generating expressions like context.next, // context.sent, and context.rval. Ep.contextProperty = function(name, computed) { const t = util.getTypes(); return t.memberExpression( this.getContextId(), computed ? t.stringLiteral(name) : t.identifier(name), !!computed ); }; // Shorthand for setting context.rval and jumping to `context.stop()`. Ep.stop = function(rval) { if (rval) { this.setReturnValue(rval); } this.jump(this.finalLoc); }; Ep.setReturnValue = function(valuePath) { util.getTypes().assertExpression(valuePath.value); this.emitAssign( this.contextProperty("rval"), this.explodeExpression(valuePath) ); }; Ep.clearPendingException = function(tryLoc, assignee) { const t = util.getTypes(); t.assertLiteral(tryLoc); let catchCall = t.callExpression( this.contextProperty("catch", true), [t.clone(tryLoc)] ); if (assignee) { this.emitAssign(assignee, catchCall); } else { this.emit(catchCall); } }; // Emits code for an unconditional jump to the given location, even if the // exact value of the location is not yet known. Ep.jump = function(toLoc) { this.emitAssign(this.contextProperty("next"), toLoc); this.emit(util.getTypes().breakStatement()); }; // Conditional jump. Ep.jumpIf = function(test, toLoc) { const t = util.getTypes(); t.assertExpression(test); t.assertLiteral(toLoc); this.emit(t.ifStatement( test, t.blockStatement([ this.assign(this.contextProperty("next"), toLoc), t.breakStatement() ]) )); }; // Conditional jump, with the condition negated. Ep.jumpIfNot = function(test, toLoc) { const t = util.getTypes(); t.assertExpression(test); t.assertLiteral(toLoc); let negatedTest; if (t.isUnaryExpression(test) && test.operator === "!") { // Avoid double negation. negatedTest = test.argument; } else { negatedTest = t.unaryExpression("!", test); } this.emit(t.ifStatement( negatedTest, t.blockStatement([ this.assign(this.contextProperty("next"), toLoc), t.breakStatement() ]) )); }; // Returns a unique MemberExpression that can be used to store and // retrieve temporary values. Since the object of the member expression is // the context object, which is presumed to coexist peacefully with all // other local variables, and since we just increment `nextTempId` // monotonically, uniqueness is assured. Ep.makeTempVar = function() { return this.contextProperty("t" + this.nextTempId++); }; Ep.getContextFunction = function(id) { const t = util.getTypes(); return t.functionExpression( id || null/*Anonymous*/, [this.getContextId()], t.blockStatement([this.getDispatchLoop()]), false, // Not a generator anymore! false // Nor an expression. ); }; // Turns this.listing into a loop of the form // // while (1) switch (context.next) { // case 0: // ... // case n: // return context.stop(); // } // // Each marked location in this.listing will correspond to one generated // case statement. Ep.getDispatchLoop = function() { const self = this; const t = util.getTypes(); let cases = []; let current; // If we encounter a break, continue, or return statement in a switch // case, we can skip the rest of the statements until the next case. let alreadyEnded = false; self.listing.forEach(function(stmt, i) { if (self.marked.hasOwnProperty(i)) { cases.push(t.switchCase( t.numericLiteral(i), current = [])); alreadyEnded = false; } if (!alreadyEnded) { current.push(stmt); if (t.isCompletionStatement(stmt)) alreadyEnded = true; } }); // Now that we know how many statements there will be in this.listing, // we can finally resolve this.finalLoc.value. this.finalLoc.value = this.listing.length; cases.push( t.switchCase(this.finalLoc, [ // Intentionally fall through to the "end" case... ]), // So that the runtime can jump to the final location without having // to know its offset, we provide the "end" case as a synonym. t.switchCase(t.stringLiteral("end"), [ // This will check/clear both context.thrown and context.rval. t.returnStatement( t.callExpression(this.contextProperty("stop"), []) ) ]) ); return t.whileStatement( t.numericLiteral(1), t.switchStatement( t.assignmentExpression( "=", this.contextProperty("prev"), this.contextProperty("next") ), cases ) ); }; Ep.getTryLocsList = function() { if (this.tryEntries.length === 0) { // To avoid adding a needless [] to the majority of runtime.wrap // argument lists, force the caller to handle this case specially. return null; } const t = util.getTypes(); let lastLocValue = 0; return t.arrayExpression( this.tryEntries.map(function(tryEntry) { let thisLocValue = tryEntry.firstLoc.value; assert.ok(thisLocValue >= lastLocValue, "try entries out of order"); lastLocValue = thisLocValue; let ce = tryEntry.catchEntry; let fe = tryEntry.finallyEntry; let locs = [ tryEntry.firstLoc, // The null here makes a hole in the array. ce ? ce.firstLoc : null ]; if (fe) { locs[2] = fe.firstLoc; locs[3] = fe.afterLoc; } return t.arrayExpression(locs.map(loc => loc && t.clone(loc))); }) ); }; // All side effects must be realized in order. // If any subexpression harbors a leap, all subexpressions must be // neutered of side effects. // No destructive modification of AST nodes. Ep.explode = function(path, ignoreResult) { const t = util.getTypes(); let node = path.node; let self = this; t.assertNode(node); if (t.isDeclaration(node)) throw getDeclError(node); if (t.isStatement(node)) return self.explodeStatement(path); if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); switch (node.type) { case "Program": return path.get("body").map( self.explodeStatement, self ); case "VariableDeclarator": throw getDeclError(node); // These node types should be handled by their parent nodes // (ObjectExpression, SwitchStatement, and TryStatement, respectively). case "Property": case "SwitchCase": case "CatchClause": throw new Error( node.type + " nodes should be handled by their parents"); default: throw new Error( "unknown Node of type " + JSON.stringify(node.type)); } }; function getDeclError(node) { return new Error( "all declarations should have been transformed into " + "assignments before the Exploder began its work: " + JSON.stringify(node)); } Ep.explodeStatement = function(path, labelId) { const t = util.getTypes(); let stmt = path.node; let self = this; let before, after, head; t.assertStatement(stmt); if (labelId) { t.assertIdentifier(labelId); } else { labelId = null; } // Explode BlockStatement nodes even if they do not contain a yield, // because we don't want or need the curly braces. if (t.isBlockStatement(stmt)) { path.get("body").forEach(function (path) { self.explodeStatement(path); }); return; } if (!meta.containsLeap(stmt)) { // Technically we should be able to avoid emitting the statement // altogether if !meta.hasSideEffects(stmt), but that leads to // confusing generated code (for instance, `while (true) {}` just // disappears) and is probably a more appropriate job for a dedicated // dead code elimination pass. self.emit(stmt); return; } switch (stmt.type) { case "ExpressionStatement": self.explodeExpression(path.get("expression"), true); break; case "LabeledStatement": after = this.loc(); // Did you know you can break from any labeled block statement or // control structure? Well, you can! Note: when a labeled loop is // encountered, the leap.LabeledEntry created here will immediately // enclose a leap.LoopEntry on the leap manager's stack, and both // entries will have the same label. Though this works just fine, it // may seem a bit redundant. In theory, we could check here to // determine if stmt knows how to handle its own label; for example, // stmt happens to be a WhileStatement and so we know it's going to // establish its own LoopEntry when we explode it (below). Then this // LabeledEntry would be unnecessary. Alternatively, we might be // tempted not to pass stmt.label down into self.explodeStatement, // because we've handled the label here, but that's a mistake because // labeled loops may contain labeled continue statements, which is not // something we can handle in this generic case. All in all, I think a // little redundancy greatly simplifies the logic of this case, since // it's clear that we handle all possible LabeledStatements correctly // here, regardless of whether they interact with the leap manager // themselves. Also remember that labels and break/continue-to-label // statements are rare, and all of this logic happens at transform // time, so it has no additional runtime cost. self.leapManager.withEntry( new leap.LabeledEntry(after, stmt.label), function() { self.explodeStatement(path.get("body"), stmt.label); } ); self.mark(after); break; case "WhileStatement": before = this.loc(); after = this.loc(); self.mark(before); self.jumpIfNot(self.explodeExpression(path.get("test")), after); self.leapManager.withEntry( new leap.LoopEntry(after, before, labelId), function() { self.explodeStatement(path.get("body")); } ); self.jump(before); self.mark(after); break; case "DoWhileStatement": let first = this.loc(); let test = this.loc(); after = this.loc(); self.mark(first); self.leapManager.withEntry( new leap.LoopEntry(after, test, labelId), function() { self.explode(path.get("body")); } ); self.mark(test); self.jumpIf(self.explodeExpression(path.get("test")), first); self.mark(after); break; case "ForStatement": head = this.loc(); let update = this.loc(); after = this.loc(); if (stmt.init) { // We pass true here to indicate that if stmt.init is an expression // then we do not care about its result. self.explode(path.get("init"), true); } self.mark(head); if (stmt.test) { self.jumpIfNot(self.explodeExpression(path.get("test")), after); } else { // No test means continue unconditionally. } self.leapManager.withEntry( new leap.LoopEntry(after, update, labelId), function() { self.explodeStatement(path.get("body")); } ); self.mark(update); if (stmt.update) { // We pass true here to indicate that if stmt.update is an // expression then we do not care about its result. self.explode(path.get("update"), true); } self.jump(head); self.mark(after); break; case "TypeCastExpression": return self.explodeExpression(path.get("expression")); case "ForInStatement": head = this.loc(); after = this.loc(); let keyIterNextFn = self.makeTempVar(); self.emitAssign( keyIterNextFn, t.callExpression( util.runtimeProperty("keys"), [self.explodeExpression(path.get("right"))] ) ); self.mark(head); let keyInfoTmpVar = self.makeTempVar(); self.jumpIf( t.memberExpression( t.assignmentExpression( "=", keyInfoTmpVar, t.callExpression(t.cloneDeep(keyIterNextFn), []) ), t.identifier("done"), false ), after ); self.emitAssign( stmt.left, t.memberExpression( t.cloneDeep(keyInfoTmpVar), t.identifier("value"), false ) ); self.leapManager.withEntry( new leap.LoopEntry(after, head, labelId), function() { self.explodeStatement(path.get("body")); } ); self.jump(head); self.mark(after); break; case "BreakStatement": self.emitAbruptCompletion({ type: "break", target: self.leapManager.getBreakLoc(stmt.label) }); break; case "ContinueStatement": self.emitAbruptCompletion({ type: "continue", target: self.leapManager.getContinueLoc(stmt.label) }); break; case "SwitchStatement": // Always save the discriminant into a temporary variable in case the // test expressions overwrite values like context.sent. let disc = self.emitAssign( self.makeTempVar(), self.explodeExpression(path.get("discriminant")) ); after = this.loc(); let defaultLoc = this.loc(); let condition = defaultLoc; let caseLocs = []; // If there are no cases, .cases might be undefined. let cases = stmt.cases || []; for (let i = cases.length - 1; i >= 0; --i) { let c = cases[i]; t.assertSwitchCase(c); if (c.test) { condition = t.conditionalExpression( t.binaryExpression("===", t.cloneDeep(disc), c.test), caseLocs[i] = this.loc(), condition ); } else { caseLocs[i] = defaultLoc; } } let discriminant = path.get("discriminant"); util.replaceWithOrRemove(discriminant, condition); self.jump(self.explodeExpression(discriminant)); self.leapManager.withEntry( new leap.SwitchEntry(after), function() { path.get("cases").forEach(function(casePath) { let i = casePath.key; self.mark(caseLocs[i]); casePath.get("consequent").forEach(function (path) { self.explodeStatement(path); }); }); } ); self.mark(after); if (defaultLoc.value === -1) { self.mark(defaultLoc); assert.strictEqual(after.value, defaultLoc.value); } break; case "IfStatement": let elseLoc = stmt.alternate && this.loc(); after = this.loc(); self.jumpIfNot( self.explodeExpression(path.get("test")), elseLoc || after ); self.explodeStatement(path.get("consequent")); if (elseLoc) { self.jump(after); self.mark(elseLoc); self.explodeStatement(path.get("alternate")); } self.mark(after); break; case "ReturnStatement": self.emitAbruptCompletion({ type: "return", value: self.explodeExpression(path.get("argument")) }); break; case "WithStatement": throw new Error("WithStatement not supported in generator functions."); case "TryStatement": after = this.loc(); let handler = stmt.handler; let catchLoc = handler && this.loc(); let catchEntry = catchLoc && new leap.CatchEntry( catchLoc, handler.param ); let finallyLoc = stmt.finalizer && this.loc(); let finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); let tryEntry = new leap.TryEntry( self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry ); self.tryEntries.push(tryEntry); self.updateContextPrevLoc(tryEntry.firstLoc); self.leapManager.withEntry(tryEntry, function() { self.explodeStatement(path.get("block")); if (catchLoc) { if (finallyLoc) { // If we have both a catch block and a finally block, then // because we emit the catch block first, we need to jump over // it to the finally block. self.jump(finallyLoc); } else { // If there is no finally block, then we need to jump over the // catch block to the fall-through location. self.jump(after); } self.updateContextPrevLoc(self.mark(catchLoc)); let bodyPath = path.get("handler.body"); let safeParam = self.makeTempVar(); self.clearPendingException(tryEntry.firstLoc, safeParam); bodyPath.traverse(catchParamVisitor, { getSafeParam: () => t.cloneDeep(safeParam), catchParamName: handler.param.name }); self.leapManager.withEntry(catchEntry, function() { self.explodeStatement(bodyPath); }); } if (finallyLoc) { self.updateContextPrevLoc(self.mark(finallyLoc)); self.leapManager.withEntry(finallyEntry, function() { self.explodeStatement(path.get("finalizer")); }); self.emit(t.returnStatement(t.callExpression( self.contextProperty("finish"), [finallyEntry.firstLoc] ))); } }); self.mark(after); break; case "ThrowStatement": self.emit(t.throwStatement( self.explodeExpression(path.get("argument")) )); break; case "ClassDeclaration": self.emit(self.explodeClass(path)); break; default: throw new Error( "unknown Statement of type " + JSON.stringify(stmt.type)); } }; let catchParamVisitor = { Identifier: function(path, state) { if (path.node.name === state.catchParamName && util.isReference(path)) { util.replaceWithOrRemove(path, state.getSafeParam()); } }, Scope: function(path, state) { if (path.scope.hasOwnBinding(state.catchParamName)) { // Don't descend into nested scopes that shadow the catch // parameter with their own declarations. path.skip(); } } }; Ep.emitAbruptCompletion = function(record) { if (!isValidCompletion(record)) { assert.ok( false, "invalid completion record: " + JSON.stringify(record) ); } assert.notStrictEqual( record.type, "normal", "normal completions are not abrupt" ); const t = util.getTypes(); let abruptArgs = [t.stringLiteral(record.type)]; if (record.type === "break" || record.type === "continue") { t.assertLiteral(record.target); abruptArgs[1] = this.insertedLocs.has(record.target) ? record.target : t.cloneDeep(record.target); } else if (record.type === "return" || record.type === "throw") { if (record.value) { t.assertExpression(record.value); abruptArgs[1] = this.insertedLocs.has(record.value) ? record.value : t.cloneDeep(record.value); } } this.emit( t.returnStatement( t.callExpression( this.contextProperty("abrupt"), abruptArgs ) ) ); }; function isValidCompletion(record) { let type = record.type; if (type === "normal") { return !hasOwn.call(record, "target"); } if (type === "break" || type === "continue") { return !hasOwn.call(record, "value") && util.getTypes().isLiteral(record.target); } if (type === "return" || type === "throw") { return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); } return false; } // Not all offsets into emitter.listing are potential jump targets. For // example, execution typically falls into the beginning of a try block // without jumping directly there. This method returns the current offset // without marking it, so that a switch case will not necessarily be // generated for this offset (I say "not necessarily" because the same // location might end up being marked in the process of emitting other // statements). There's no logical harm in marking such locations as jump // targets, but minimizing the number of switch cases keeps the generated // code shorter. Ep.getUnmarkedCurrentLoc = function() { return util.getTypes().numericLiteral(this.listing.length); }; // The context.prev property takes the value of context.next whenever we // evaluate the switch statement discriminant, which is generally good // enough for tracking the last location we jumped to, but sometimes // context.prev needs to be more precise, such as when we fall // successfully out of a try block and into a finally block without // jumping. This method exists to update context.prev to the freshest // available location. If we were implementing a full interpreter, we // would know the location of the current instruction with complete // precision at all times, but we don't have that luxury here, as it would // be costly and verbose to set context.prev before every statement. Ep.updateContextPrevLoc = function(loc) { const t = util.getTypes(); if (loc) { t.assertLiteral(loc); if (loc.value === -1) { // If an uninitialized location literal was passed in, set its value // to the current this.listing.length. loc.value = this.listing.length; } else { // Otherwise assert that the location matches the current offset. assert.strictEqual(loc.value, this.listing.length); } } else { loc = this.getUnmarkedCurrentLoc(); } // Make sure context.prev is up to date in case we fell into this try // statement without jumping to it. TODO Consider avoiding this // assignment when we know control must have jumped here. this.emitAssign(this.contextProperty("prev"), loc); }; // In order to save the rest of explodeExpression from a combinatorial // trainwreck of special cases, explodeViaTempVar is responsible for // deciding when a subexpression needs to be "exploded," which is my // very technical term for emitting the subexpression as an assignment // to a temporary variable and the substituting the temporary variable // for the original subexpression. Think of exploded view diagrams, not // Michael Bay movies. The point of exploding subexpressions is to // control the precise order in which the generated code realizes the // side effects of those subexpressions. Ep.explodeViaTempVar = function(tempVar, childPath, hasLeapingChildren, ignoreChildResult) { assert.ok( !ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?" ); const t = util.getTypes(); let result = this.explodeExpression(childPath, ignoreChildResult); if (ignoreChildResult) { // Side effects already emitted above. } else if (tempVar || (hasLeapingChildren && !t.isLiteral(result))) { // If tempVar was provided, then the result will always be assigned // to it, even if the result does not otherwise need to be assigned // to a temporary variable. When no tempVar is provided, we have // the flexibility to decide whether a temporary variable is really // necessary. Unfortunately, in general, a temporary variable is // required whenever any child contains a yield expression, since it // is difficult to prove (at all, let alone efficiently) whether // this result would evaluate to the same value before and after the // yield (see #206). One narrow case where we can prove it doesn't // matter (and thus we do not need a temporary variable) is when the // result in question is a Literal value. result = this.emitAssign( tempVar || this.makeTempVar(), result ); } return result; }; Ep.explodeExpression = function(path, ignoreResult) { const t = util.getTypes(); let expr = path.node; if (expr) { t.assertExpression(expr); } else { return expr; } let self = this; let result; // Used optionally by several cases below. let after; function finish(expr) { t.assertExpression(expr); if (ignoreResult) { self.emit(expr); } return expr; } // If the expression does not contain a leap, then we either emit the // expression as a standalone statement or return it whole. if (!meta.containsLeap(expr)) { return finish(expr); } // If any child contains a leap (such as a yield or labeled continue or // break statement), then any sibling subexpressions will almost // certainly have to be exploded in order to maintain the order of their // side effects relative to the leaping child(ren). let hasLeapingChildren = meta.containsLeap.onlyChildren(expr); // If ignoreResult is true, then we must take full responsibility for // emitting the expression with all its side effects, and we should not // return a result. switch (expr.type) { case "MemberExpression": return finish(t.memberExpression( self.explodeExpression(path.get("object")), expr.computed ? self.explodeViaTempVar(null, path.get("property"), hasLeapingChildren) : expr.property, expr.computed )); case "CallExpression": let calleePath = path.get("callee"); let argsPath = path.get("arguments"); let newCallee; let newArgs; let hasLeapingArgs = argsPath.some( argPath => meta.containsLeap(argPath.node) ); let injectFirstArg = null; if (t.isMemberExpression(calleePath.node)) { if (hasLeapingArgs) { // If the arguments of the CallExpression contained any yield // expressions, then we need to be sure to evaluate the callee // before evaluating the arguments, but if the callee was a member // expression, then we must be careful that the object of the // member expression still gets bound to `this` for the call. let newObject = self.explodeViaTempVar( // Assign the exploded callee.object expression to a temporary // variable so that we can use it twice without reevaluating it. self.makeTempVar(), calleePath.get("object"), hasLeapingChildren ); let newProperty = calleePath.node.computed ? self.explodeViaTempVar(null, calleePath.get("property"), hasLeapingChildren) : calleePath.node.property; injectFirstArg = newObject; newCallee = t.memberExpression( t.memberExpression( t.cloneDeep(newObject), newProperty, calleePath.node.computed ), t.identifier("call"), false ); } else { newCallee = self.explodeExpression(calleePath); } } else { newCallee = self.explodeViaTempVar(null, calleePath, hasLeapingChildren); if (t.isMemberExpression(newCallee)) { // If the callee was not previously a MemberExpression, then the // CallExpression was "unqualified," meaning its `this` object // should be the global object. If the exploded expression has // become a MemberExpression (e.g. a context property, probably a // temporary variable), then we need to force it to be unqualified // by using the (0, object.property)(...) trick; otherwise, it // will receive the object of the MemberExpression as its `this` // object. newCallee = t.sequenceExpression([ t.numericLiteral(0), t.cloneDeep(newCallee) ]); } } if (hasLeapingArgs) { newArgs = argsPath.map(argPath => self.explodeViaTempVar(null, argPath, hasLeapingChildren)); if (injectFirstArg) newArgs.unshift(injectFirstArg); newArgs = newArgs.map(arg => t.cloneDeep(arg)); } else { newArgs = path.node.arguments; } return finish(t.callExpression(newCallee, newArgs)); case "NewExpression": return finish(t.newExpression( self.explodeViaTempVar(null, path.get("callee"), hasLeapingChildren), path.get("arguments").map(function(argPath) { return self.explodeViaTempVar(null, argPath, hasLeapingChildren); }) )); case "ObjectExpression": return finish(t.objectExpression( path.get("properties").map(function(propPath) { if (propPath.isObjectProperty()) { return t.objectProperty( propPath.node.key, self.explodeViaTempVar(null, propPath.get("value"), hasLeapingChildren), propPath.node.computed ); } else { return propPath.node; } }) )); case "ArrayExpression": return finish(t.arrayExpression( path.get("elements").map(function(elemPath) { if (elemPath.isSpreadElement()) { return t.spreadElement( self.explodeViaTempVar(null, elemPath.get("argument"), hasLeapingChildren) ); } else { return self.explodeViaTempVar(null, elemPath, hasLeapingChildren); } }) )); case "SequenceExpression": let lastIndex = expr.expressions.length - 1; path.get("expressions").forEach(function(exprPath) { if (exprPath.key === lastIndex) { result = self.explodeExpression(exprPath, ignoreResult); } else { self.explodeExpression(exprPath, true); } }); return result; case "LogicalExpression": after = this.loc(); if (!ignoreResult) { result = self.makeTempVar(); } let left = self.explodeViaTempVar(result, path.get("left"), hasLeapingChildren); if (expr.operator === "&&") { self.jumpIfNot(left, after); } else { assert.strictEqual(expr.operator, "||"); self.jumpIf(left, after); } self.explodeViaTempVar(result, path.get("right"), hasLeapingChildren, ignoreResult); self.mark(after); return result; case "ConditionalExpression": let elseLoc = this.loc(); after = this.loc(); let test = self.explodeExpression(path.get("test")); self.jumpIfNot(test, elseLoc); if (!ignoreResult) { result = self.makeTempVar(); } self.explodeViaTempVar(result, path.get("consequent"), hasLeapingChildren, ignoreResult); self.jump(after); self.mark(elseLoc); self.explodeViaTempVar(result, path.get("alternate"), hasLeapingChildren, ignoreResult); self.mark(after); return result; case "UnaryExpression": return finish(t.unaryExpression( expr.operator, // Can't (and don't need to) break up the syntax of the argument. // Think about delete a[b]. self.explodeExpression(path.get("argument")), !!expr.prefix )); case "BinaryExpression": return finish(t.binaryExpression( expr.operator, self.explodeViaTempVar(null, path.get("left"), hasLeapingChildren), self.explodeViaTempVar(null, path.get("right"), hasLeapingChildren) )); case "AssignmentExpression": if (expr.operator === "=") { // If this is a simple assignment, the left hand side does not need // to be read before the right hand side is evaluated, so we can // avoid the more complicated logic below. return finish(t.assignmentExpression( expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")) )); } const lhs = self.explodeExpression(path.get("left")); const temp = self.emitAssign(self.makeTempVar(), lhs); // For example, // // x += yield y // // becomes // // context.t0 = x // x = context.t0 += yield y // // so that the left-hand side expression is read before the yield. // Fixes https://github.com/facebook/regenerator/issues/345. return finish(t.assignmentExpression( "=", t.cloneDeep(lhs), t.assignmentExpression( expr.operator, t.cloneDeep(temp), self.explodeExpression(path.get("right")) ) )); case "UpdateExpression": return finish(t.updateExpression( expr.operator, self.explodeExpression(path.get("argument")), expr.prefix )); case "YieldExpression": after = this.loc(); let arg = expr.argument && self.explodeExpression(path.get("argument")); if (arg && expr.delegate) { let result = self.makeTempVar(); let ret = t.returnStatement(t.callExpression( self.contextProperty("delegateYield"), [ arg, t.stringLiteral(result.property.name), after ] )); ret.loc = expr.loc; self.emit(ret); self.mark(after); return result; } self.emitAssign(self.contextProperty("next"), after); let ret = t.returnStatement(t.cloneDeep(arg) || null); // Preserve the `yield` location so that source mappings for the statements // link back to the yield properly. ret.loc = expr.loc; self.emit(ret); self.mark(after); return self.contextProperty("sent"); case "ClassExpression": return finish(self.explodeClass(path)); default: throw new Error( "unknown Expression of type " + JSON.stringify(expr.type)); } }; Ep.explodeClass = function(path) { const explodingChildren = []; if (path.node.superClass) { explodingChildren.push(path.get("superClass")); } path.get("body.body").forEach(member => { if (member.node.computed) { explodingChildren.push(member.get("key")); } }); const hasLeapingChildren = explodingChildren.some( child => meta.containsLeap(child)); for (let i = 0; i < explodingChildren.length; i++) { const child = explodingChildren[i]; const isLast = i === explodingChildren.length - 1; if (isLast) { child.replaceWith(this.explodeExpression(child)); } else { child.replaceWith(this.explodeViaTempVar(null, child, hasLeapingChildren)); } } return path.node; };
const webpack = require('webpack'); const conf = require('./gulp.conf'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const FailPlugin = require('webpack-fail-plugin'); const autoprefixer = require('autoprefixer'); module.exports = { module: { loaders: [ { test: /\.json$/, loaders: [ 'json-loader' ] }, { test: /\.js$/, exclude: /node_modules/, loader: 'eslint-loader', enforce: 'pre' }, { test: /\.(css|scss)$/, loaders: [ 'style-loader', 'css-loader', 'sass-loader', 'postcss-loader' ] }, { test: /\.js$/, exclude: /node_modules/, loaders: [ 'react-hot-loader', 'babel-loader' ] } ] }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.NoEmitOnErrorsPlugin(), FailPlugin, new HtmlWebpackPlugin({ template: conf.path.src('index.html') }), new webpack.HotModuleReplacementPlugin(), new webpack.LoaderOptionsPlugin({ options: { postcss: () => [autoprefixer] }, debug: true }) ], devtool: 'source-map', output: { path: path.join(process.cwd(), conf.paths.tmp), filename: 'index.js' }, entry: [ 'webpack/hot/dev-server', 'webpack-hot-middleware/client', `./${conf.path.src('index')}` ] };
/*global cosh, tanh, toRadians*/ function getSpeedWithoutAirResistance(f_Res, weight, init_velo, terrain_length, points_max) { "use strict"; var i = 1, acceleration = f_Res / weight, max_time = (-init_velo + Math.sqrt(init_velo * init_velo + 2 * acceleration * terrain_length)) / acceleration, //max_time = (-init_velo / acceleration) + Math.sqrt(init_velo * init_velo + 2 * acceleration * terrain_length / (acceleration * acceleration)), res = []; res[0] = {}; res[0].time = 0; res[0].speed = init_velo; res[0].path = 0; for (i; i <= points_max - 1; i = i + 1) { res[i] = {}; res[i].time = max_time / (points_max) * (i + 1); res[i].speed = acceleration * res[i].time + init_velo; res[i].path = 0.5 * acceleration * res[i].time * res[i].time + init_velo * res[i].time; } res[res.length - 1].path = terrain_length; return res; } function getSpeedApproximateAirResistance(steps, f_Res, wheight, init_velo, terrain_length, area, density, cw, f_Gleit, f_Hangab) { "use strict"; var i = 1, acceleration = f_Res / wheight, last_velo = init_velo, pastPath = 0, pastSpeed = 0, f_Air = 0, res = []; res[0] = {}; res[0].time = 0; res[0].speed = init_velo; res[0].path = 0; do { res[i] = {}; res[i].time = (i + 1) * steps; res[i].speed = acceleration * steps + last_velo; res[i].path = pastPath + 0.5 * acceleration * steps * steps + last_velo * steps; last_velo = res[i].speed; f_Air = area * density * cw * res[i].speed * res[i].speed / 2; f_Res = f_Hangab - f_Air - f_Gleit; acceleration = f_Res / wheight; pastPath = res[i].path; i = i + 1; } while (res[res.length - 1].path < terrain_length); res[res.length - 1].path = terrain_length; return res; } function getWithAirResistance(steps, f_Res, weight, init_velo, area, density, cw, terrain_length) { "use strict"; var i = 1, res = []; res[0] = {}; res[0].time = 0; res[0].speed = init_velo; res[0].path = 0; do { res[i] = {}; res[i].time = (i + 1) * steps; res[i].speed = init_velo + Math.sqrt(f_Res / (0.5 * area * cw * density)) * tanh(res[i].time * Math.sqrt((f_Res / weight) * 0.5 * area * cw * density / weight)); res[i].path = weight / (0.5 * area * cw * density) * Math.log(cosh(res[i].time * Math.sqrt((f_Res / weight) * 0.5 * area * cw * density / weight))); i = i + 1; } while (res[res.length - 1].path < terrain_length); res[res.length - 1].path = terrain_length; return res; } function analyze(requestJSon) { "use strict"; var res = { forRequestID: requestJSon.requestID }, f_Gewicht = 0, f_Hangab = 0, f_Normal = 0, f_Haft = 0, f_Gleit = 0, f_Air = 0, f_Res = 0; if (!isNaN(requestJSon.terrain.angle) && !isNaN(requestJSon.terrain.gravitation) && !isNaN(requestJSon.terrain.length) && !isNaN(requestJSon.subject.weight) && !isNaN(requestJSon.subject.area) && !isNaN(requestJSon.subject.cw) && !isNaN(requestJSon.subject.init_velo) && !isNaN(requestJSon.subject.force) && !isNaN(requestJSon.resistance.stationary) && !isNaN(requestJSon.resistance.underway) && !isNaN(requestJSon.fluid.density) && !isNaN(requestJSon.points.max) && !isNaN(requestJSon.points.steps) && (requestJSon.points.steps > 0)) { f_Gewicht = requestJSon.subject.weight * requestJSon.terrain.gravitation; //Gewichtskraft in Newton [N] f_Hangab = f_Gewicht * Math.sin(toRadians(requestJSon.terrain.angle)); //Hangabtriebskraft in [N] f_Normal = f_Gewicht * Math.cos(toRadians(requestJSon.terrain.angle)); //Normalkraft in [N] f_Haft = f_Normal * requestJSon.resistance.stationary; //Haftreibungskraft in [N] f_Gleit = f_Normal * requestJSon.resistance.underway; //Gleitreibungskraft in [N] f_Air = requestJSon.subject.area * requestJSon.fluid.density * requestJSon.subject.cw * requestJSon.subject.init_velo * requestJSon.subject.init_velo / 2; f_Res = f_Hangab - f_Haft; if (requestJSon.subject.init_velo > 0 || f_Res > 0) { f_Res = f_Hangab - f_Gleit + requestJSon.subject.force; res.withoutAirResistance = getSpeedWithoutAirResistance(f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.terrain.length, requestJSon.points.max); f_Res = f_Hangab - f_Air - f_Haft; if (f_Res > 0) { f_Res = f_Hangab - f_Air - f_Gleit + requestJSon.subject.force; res.approximateAirResistance = getSpeedApproximateAirResistance(requestJSon.points.steps, f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.terrain.length, requestJSon.subject.area, requestJSon.fluid.density, requestJSon.subject.cw, f_Gleit, f_Hangab); f_Res = requestJSon.subject.force + f_Hangab - f_Gleit; res.withAirResistance = getWithAirResistance(requestJSon.points.steps, f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.subject.area, requestJSon.fluid.density, requestJSon.subject.cw, requestJSon.terrain.length); } } } if (res.approximateAirResistance === null) { res.approximateAirResistance = []; res.approximateAirResistance = [{ speed: 0, path: 0, time: 0 }]; } if (res.withAirResistance === null) { res.withAirResistance = [{ speed: 0, path: 0, time: 0 }]; } if (res.withoutAirResistance === null) { res.withoutAirResistance = [{ speed: 0, path: 0, time: 0 }]; } return res; }
import React from './react' export default { React: React }
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('accordion-item', 'Unit | Component | accordion item', { // Specify the other units that are required for this test // needs: ['component:foo', 'helper:bar'] }); test('it renders', function(assert) { assert.expect(2); // Creates the component instance var component = this.subject(); assert.equal(component._state, 'preRender'); // Renders the component to the page this.render(); assert.equal(component._state, 'inDOM'); });
autocomplete = function() { $( ".autocomplete" ).autocomplete({source: "/autocomplete"}); }
describe("XEP-0082", function(){ describe("Singleton method", function(){ describe("toDate", function(){ it("should convert Date string to Date object", function(){ var r = Frabjous.Xep0082.toDate("1985-03-29"); expect(r.toUTCString()).toEqual("Fri, 29 Mar 1985 00:00:00 GMT"); }); it("should convert DateTime string to Date object", function(){ var r = Frabjous.Xep0082.toDate("1985-03-29T08:45:12Z"); expect(r.toUTCString()).toEqual("Fri, 29 Mar 1985 08:45:12 GMT"); }); it("should convert DateTime string with milliseconds string to Date object", function(){ var r = Frabjous.Xep0082.toDate("1985-03-29T08:45:12.034Z"); expect(r.toUTCString()).toEqual("Fri, 29 Mar 1985 08:45:12 GMT"); expect(r.getUTCMilliseconds()).toEqual(34); }); it("should convert DateTime string with negative timezone to Date object", function(){ var r = Frabjous.Xep0082.toDate("1985-03-29T08:45:12+01:30"); expect(r.toUTCString()).toEqual("Fri, 29 Mar 1985 07:15:12 GMT"); }); it("should convert DateTime string with positive timezone to Date object", function(){ var r = Frabjous.Xep0082.toDate("1985-03-29T08:45:12-01:00"); expect(r.toUTCString()).toEqual("Fri, 29 Mar 1985 09:45:12 GMT"); }); }); describe("toString", function(){ it("should convert Date that is at midnight to Date string", function(){ var d = new Date(Date.UTC(1985, 2, 29)); var string = Frabjous.Xep0082.toString(d); expect(string).toEqual("1985-03-29"); }); it("should convert Date that is not on midnight to DateTime string", function(){ var d = new Date(Date.UTC(1985, 2, 29, 3, 15, 59)); var string = Frabjous.Xep0082.toString(d); expect(string).toEqual("1985-03-29T03:15:59Z"); }); it("should convert Date that has milliseconds to DateTime string with milliseconds", function(){ var d = new Date(Date.UTC(1985, 2, 29, 0, 0, 0, 1)); var string = Frabjous.Xep0082.toString(d); expect(string).toEqual("1985-03-29T00:00:00.001Z"); }); it("should convert Date that is for locale timezone to UTC", function(){ // Test only useful when browser is not in UTC locale var d = new Date(1985, 2, 29, 10, 0,43); var string = Frabjous.Xep0082.toString(d); expect(string).toMatch(new RegExp("1985-03-29T0?"+d.getUTCHours()+":0?"+d.getUTCMinutes()+":43Z")); }); }); }); });
'use strict'; const path = require('path'); const electron = require('electron'); module.exports = function showMainWindow() { const windowStateKeeper = require('electron-window-state'); const window = require('electron-window'); // Load the previous state with fallback to defaults const mainWindowState = windowStateKeeper({ width: 750, height: 530 }); const mainWindow = window.createWindow({ 'x': mainWindowState.x, 'y': mainWindowState.y, 'width': mainWindowState.width, 'height': mainWindowState.height }); if (process.platform !== 'darwin') { mainWindow.setMenu( electron.Menu.buildFromTemplate([]) ); } mainWindowState.manage(mainWindow); const indexPath = path.resolve( __dirname, 'src/index.html' ); mainWindow.showUrl(indexPath, {}); };
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'fakeobjects', 'ms', { anchor: 'Anchor', // MISSING flash: 'Flash Animation', // MISSING hiddenfield: 'Hidden Field', // MISSING iframe: 'IFrame', // MISSING unknown: 'Unknown Object' // MISSING } );
import React from 'react' import { Router, Route, Link } from 'react-router' import App from './containers/App' import About from './containers/About' // <Route path="/Users/yhisamatsu/_/js-dev/electron-redux-boilerplate/build/renderer/index.html" component={App}> // 一番はじめのパスは上記のようになるので、*/で待ち構えている // それ以外は基本的に相対パス、相対パスを使わないとパスの構造が変化して、画面遷移ができなくなるため export default ( <Router> {/* for electron */} <Route path="/" component={App}> </Route> {/* for web */} <Route path="/index.html" component={App}> </Route> <Route path="/routing" component={About}> </Route> </Router> )
#!/usr/bin/env node "use strict"; var debug = require("debug")("tile-squirrel-add-tile"), QueueWriter = require("../lib/queueWriter"), path = require("path"); var nomnom = require("nomnom") .options({ source: { position: 0, help: "Source to queue" }, tile: { position: 1, help: "Tile to queue" }, config: { abbr: "c", metavar: "CONFIG", help: "Provide a configuration file. Configuration file is not needed," + " but if it is provided sources will be verified to exist in config." }, version: { abbr: "v", flag: true, help: "Show version info", callback: function() { return "tile-squirrel v" + require("../package.json").version; } } }) .help("Queue a single tile"); var opts = nomnom.parse(); if (!opts.source || !opts.tile) { nomnom.print(nomnom.getUsage()); } //Check if source exists if a config was specified if (opts.config) { var config = require(path.resolve(opts.config)); if (!config[opts.source]) { console.log("Source " + opts.source + " not found in config"); process.exit(-1); } } new QueueWriter([opts.source], {}, function(err, queueWriter) { queueWriter.putTile(opts.tile, function() { queueWriter.tileStream.end(); }); });
var nconf = require('nconf'); var pg = require('pg'); var readFile = require('fs').readFile; var url = require('url'); function parseUri (uri) { var u = url.parse(uri, true); var userPass = u.auth ? u.auth.split(':') : []; u.user = userPass[0]; u.password = userPass[1]; u.database = u.pathname.split('/').join(''); u.host = u.hostname; u.ssl = true; return u; } module.exports = function(filename, userParams, cb) { var client = new pg.Client(parseUri(nconf.get('POSTGRES_URL'))); client.connect(function(e) { if(e) return handleError(e); readFile('sql/' + filename + '.sql', function(e, data) { if(e) return handleError(e); client.query(data.toString(), userParams || [], function(e, result) { if(e) return handleError(e); client.end(); cb(null, result); }); }); }); function handleError(e) { client.end(); return cb(e); } };
var newContext = require('./context'); var newPromise = require('./promise'); module.exports = function() { var c = {}; var context = newContext(); c.promise = newPromise(context); c.resolve = function() { context.resolved = [].slice.call(arguments); context.completed = true; return c.promise; }; c.reject = function() { context.rejected = [].slice.call(arguments); context.completed = true; return c.promise; }; if (arguments.length > 0) return c.resolve.apply(null, arguments); return c; };
ScalaJS.data.scala_scalajs_js_EvalError$ = new ScalaJS.ClassTypeData({ scala_scalajs_js_EvalError$: 0 }, false, "scala.scalajs.js.EvalError$", ScalaJS.data.scala_scalajs_js_Object, { scala_scalajs_js_EvalError$: 1, scala_scalajs_js_Object: 1, scala_scalajs_js_Any: 1, java_lang_Object: 1 }); //@ sourceMappingURL=EvalError$.js.map
var React = require('react'), Input = require('react-input-autosize'), classes = require('classnames'), Value = require('./Value'); var requestId = 0; var Select = React.createClass({ displayName: 'Select', propTypes: { value: React.PropTypes.any, // initial field value multi: React.PropTypes.bool, // multi-value input disabled: React.PropTypes.bool, // whether the Select is disabled or not options: React.PropTypes.array, // array of options delimiter: React.PropTypes.string, // delimiter to use to join multiple values asyncOptions: React.PropTypes.func, // function to call to get options autoload: React.PropTypes.bool, // whether to auto-load the default async options set placeholder: React.PropTypes.string, // field placeholder, displayed when there's no value noResultsText: React.PropTypes.string, // placeholder displayed when there are no matching search results clearable: React.PropTypes.bool, // should it be possible to reset value clearValueText: React.PropTypes.string, // title for the "clear" control clearAllText: React.PropTypes.string, // title for the "clear" control when multi: true searchable: React.PropTypes.bool, // whether to enable searching feature or not searchPromptText: React.PropTypes.string, // label to prompt for search input name: React.PropTypes.string, // field name, for hidden <input /> tag onChange: React.PropTypes.func, // onChange handler: function(newValue) {} onFocus: React.PropTypes.func, // onFocus handler: function(event) {} onBlur: React.PropTypes.func, // onBlur handler: function(event) {} className: React.PropTypes.string, // className for the outer element filterOption: React.PropTypes.func, // method to filter a single option: function(option, filterString) filterOptions: React.PropTypes.func, // method to filter the options array: function([options], filterString, [values]) matchPos: React.PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: React.PropTypes.string, // (any|label|value) which option property to filter on inputProps: React.PropTypes.object, // custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} /* * Allow user to make option label clickable. When this handler is defined we should * wrap label into <a>label</a> tag. * * onOptionLabelClick handler: function (value, event) {} * */ onOptionLabelClick: React.PropTypes.func }, getDefaultProps: function() { return { value: undefined, options: undefined, disabled: false, delimiter: ',', asyncOptions: undefined, autoload: true, placeholder: 'Select...', noResultsText: 'No results found', clearable: true, clearValueText: 'Clear value', clearAllText: 'Clear all', searchable: true, searchPromptText: 'Type to search', name: undefined, onChange: undefined, className: undefined, matchPos: 'any', matchProp: 'any', inputProps: {}, onOptionLabelClick: undefined }; }, getInitialState: function() { return { /* * set by getStateFromValue on componentWillMount: * - value * - values * - filteredOptions * - inputValue * - placeholder * - focusedOption */ options: this.props.options, isFocused: false, isOpen: false, isLoading: false }; }, componentWillMount: function() { this._optionsCache = {}; this._optionsFilterString = ''; this.setState(this.getStateFromValue(this.props.value)); if (this.props.asyncOptions && this.props.autoload) { this.autoloadAsyncOptions(); } this._closeMenuIfClickedOutside = function(event) { if (!this.state.isOpen) { return; } var menuElem = this.refs.selectMenuContainer.getDOMNode(); var controlElem = this.refs.control.getDOMNode(); var eventOccuredOutsideMenu = this.clickedOutsideElement(menuElem, event); var eventOccuredOutsideControl = this.clickedOutsideElement(controlElem, event); // Hide dropdown menu if click occurred outside of menu if (eventOccuredOutsideMenu && eventOccuredOutsideControl) { this.setState({ isOpen: false }, this._unbindCloseMenuIfClickedOutside); } }.bind(this); this._bindCloseMenuIfClickedOutside = (function() { document.addEventListener('click', this._closeMenuIfClickedOutside); }).bind(this); this._unbindCloseMenuIfClickedOutside = (function() { document.removeEventListener('click', this._closeMenuIfClickedOutside); }).bind(this); }, componentWillUnmount: function() { clearTimeout(this._blurTimeout); clearTimeout(this._focusTimeout); if(this.state.isOpen) { this._unbindCloseMenuIfClickedOutside(); } }, componentWillReceiveProps: function(newProps) { if (JSON.stringify(newProps.options) !== JSON.stringify(this.props.options)) { this.setState({ options: newProps.options, filteredOptions: this.filterOptions(newProps.options) }); } if (newProps.value !== this.state.value) { this.setState(this.getStateFromValue(newProps.value, newProps.options)); } }, componentDidUpdate: function() { if (!this.props.disabled && this._focusAfterUpdate) { clearTimeout(this._blurTimeout); this._focusTimeout = setTimeout(function() { this.getInputNode().focus(); this._focusAfterUpdate = false; }.bind(this), 50); } if (this._focusedOptionReveal) { if (this.refs.focused && this.refs.menu) { var focusedDOM = this.refs.focused.getDOMNode(); var menuDOM = this.refs.menu.getDOMNode(); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = (focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight); } } this._focusedOptionReveal = false; } }, clickedOutsideElement: function(element, event) { var eventTarget = (event.target) ? event.target : event.srcElement; while (eventTarget != null) { if (eventTarget === element) return false; eventTarget = eventTarget.offsetParent; } return true; }, getStateFromValue: function(value, options) { if (!options) { options = this.state.options; } // reset internal filter string this._optionsFilterString = ''; var values = this.initValuesArray(value, options), filteredOptions = this.filterOptions(options, values); return { value: values.map(function(v) { return v.value; }).join(this.props.delimiter), values: values, inputValue: '', filteredOptions: filteredOptions, placeholder: !this.props.multi && values.length ? values[0].label : this.props.placeholder, focusedOption: !this.props.multi && values.length ? values[0] : filteredOptions[0] }; }, initValuesArray: function(values, options) { if (!Array.isArray(values)) { if (typeof values === 'string') { values = values.split(this.props.delimiter); } else { values = values ? [values] : []; } } return values.map(function(val) { if (typeof val === 'string') { for (var key in options) { if (options.hasOwnProperty(key) && options[key] && options[key].value === val) { return options[key]; } } return { value: val, label: val }; } else { return val; } }); }, setValue: function(value) { this._focusAfterUpdate = true; var newState = this.getStateFromValue(value); newState.isOpen = false; this.fireChangeEvent(newState); this.setState(newState); }, selectValue: function(value) { if (!this.props.multi) { this.setValue(value); } else if (value) { this.addValue(value); } this._unbindCloseMenuIfClickedOutside(); }, addValue: function(value) { this.setValue(this.state.values.concat(value)); }, popValue: function() { this.setValue(this.state.values.slice(0, this.state.values.length - 1)); }, removeValue: function(valueToRemove) { this.setValue(this.state.values.filter(function(value) { return value !== valueToRemove; })); }, clearValue: function(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } this.setValue(null); }, resetValue: function() { this.setValue(this.state.value); }, getInputNode: function () { var input = this.refs.input; return this.props.searchable ? input : input.getDOMNode(); }, fireChangeEvent: function(newState) { if (newState.value !== this.state.value && this.props.onChange) { this.props.onChange(newState.value, newState.values); } }, handleMouseDown: function(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || (event.type === 'mousedown' && event.button !== 0)) { return; } event.stopPropagation(); event.preventDefault(); if (this.state.isFocused) { this.setState({ isOpen: true }, this._bindCloseMenuIfClickedOutside); } else { this._openAfterFocus = true; this.getInputNode().focus(); } }, handleInputFocus: function(event) { var newIsOpen = this.state.isOpen || this._openAfterFocus; this.setState({ isFocused: true, isOpen: newIsOpen }, function() { if(newIsOpen) { this._bindCloseMenuIfClickedOutside(); } else { this._unbindCloseMenuIfClickedOutside(); } }); this._openAfterFocus = false; if (this.props.onFocus) { this.props.onFocus(event); } }, handleInputBlur: function(event) { this._blurTimeout = setTimeout(function() { if (this._focusAfterUpdate) return; this.setState({ isFocused: false }); }.bind(this), 50); if (this.props.onBlur) { this.props.onBlur(event); } }, handleKeyDown: function(event) { if (this.state.disabled) return; switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue) { this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.state.focusedOption) { return; } this.selectFocusedOption(); break; case 13: // enter this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.resetValue(); } else { this.clearValue(); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; default: return; } event.preventDefault(); }, // Ensures that the currently focused option is available in filteredOptions. // If not, returns the first available option. _getNewFocusedOption: function(filteredOptions) { for (var key in filteredOptions) { if (filteredOptions.hasOwnProperty(key) && filteredOptions[key] === this.state.focusedOption) { return filteredOptions[key]; } } return filteredOptions[0]; }, handleInputChange: function(event) { // assign an internal variable because we need to use // the latest value before setState() has completed. this._optionsFilterString = event.target.value; if (this.props.asyncOptions) { this.setState({ isLoading: true, inputValue: event.target.value }); this.loadAsyncOptions(event.target.value, { isLoading: false, isOpen: true }, this._bindCloseMenuIfClickedOutside); } else { var filteredOptions = this.filterOptions(this.state.options); this.setState({ isOpen: true, inputValue: event.target.value, filteredOptions: filteredOptions, focusedOption: this._getNewFocusedOption(filteredOptions) }, this._bindCloseMenuIfClickedOutside); } }, autoloadAsyncOptions: function() { var self = this; this.loadAsyncOptions('', {}, function () { // update with fetched self.setValue(self.props.value); }); }, loadAsyncOptions: function(input, state, callback) { var thisRequestId = this._currentRequestId = requestId++; for (var i = 0; i <= input.length; i++) { var cacheKey = input.slice(0, i); if (this._optionsCache[cacheKey] && (input === cacheKey || this._optionsCache[cacheKey].complete)) { var options = this._optionsCache[cacheKey].options; var filteredOptions = this.filterOptions(options); var newState = { options: options, filteredOptions: filteredOptions, focusedOption: this._getNewFocusedOption(filteredOptions) }; for (var key in state) { if (state.hasOwnProperty(key)) { newState[key] = state[key]; } } this.setState(newState); if(callback) callback({}); return; } } this.props.asyncOptions(input, function(err, data) { if (err) throw err; this._optionsCache[input] = data; if (thisRequestId !== this._currentRequestId) { return; } var filteredOptions = this.filterOptions(data.options); var newState = { options: data.options, filteredOptions: filteredOptions, focusedOption: this._getNewFocusedOption(filteredOptions) }; for (var key in state) { if (state.hasOwnProperty(key)) { newState[key] = state[key]; } } this.setState(newState); if(callback) callback({}); }.bind(this)); }, filterOptions: function(options, values) { if (!this.props.searchable) { return options; } var filterValue = this._optionsFilterString; var exclude = (values || this.state.values).map(function(i) { return i.value; }); if (this.props.filterOptions) { return this.props.filterOptions.call(this, options, filterValue, exclude); } else { var filterOption = function(op) { if (this.props.multi && exclude.indexOf(op.value) > -1) return false; if (this.props.filterOption) return this.props.filterOption.call(this, op, filterValue); var valueTest = String(op.value), labelTest = String(op.label); return !filterValue || (this.props.matchPos === 'start') ? ( (this.props.matchProp !== 'label' && valueTest.toLowerCase().substr(0, filterValue.length) === filterValue) || (this.props.matchProp !== 'value' && labelTest.toLowerCase().substr(0, filterValue.length) === filterValue) ) : ( (this.props.matchProp !== 'label' && valueTest.toLowerCase().indexOf(filterValue.toLowerCase()) >= 0) || (this.props.matchProp !== 'value' && labelTest.toLowerCase().indexOf(filterValue.toLowerCase()) >= 0) ); }; return (options || []).filter(filterOption, this); } }, selectFocusedOption: function() { return this.selectValue(this.state.focusedOption); }, focusOption: function(op) { this.setState({ focusedOption: op }); }, focusNextOption: function() { this.focusAdjacentOption('next'); }, focusPreviousOption: function() { this.focusAdjacentOption('previous'); }, focusAdjacentOption: function(dir) { this._focusedOptionReveal = true; var ops = this.state.filteredOptions; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this.state.focusedOption || ops[dir === 'next' ? 0 : ops.length - 1] }, this._bindCloseMenuIfClickedOutside); return; } if (!ops.length) { return; } var focusedIndex = -1; for (var i = 0; i < ops.length; i++) { if (this.state.focusedOption === ops[i]) { focusedIndex = i; break; } } var focusedOption = ops[0]; if (dir === 'next' && focusedIndex > -1 && focusedIndex < ops.length - 1) { focusedOption = ops[focusedIndex + 1]; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedOption = ops[focusedIndex - 1]; } else { focusedOption = ops[ops.length - 1]; } } this.setState({ focusedOption: focusedOption }); }, unfocusOption: function(op) { if (this.state.focusedOption === op) { this.setState({ focusedOption: null }); } }, buildMenu: function() { var focusedValue = this.state.focusedOption ? this.state.focusedOption.value : null; if(this.state.filteredOptions.length > 0) { focusedValue = focusedValue == null ? this.state.filteredOptions[0] : focusedValue; } var ops = Object.keys(this.state.filteredOptions).map(function(key) { var op = this.state.filteredOptions[key]; var isFocused = focusedValue === op.value; var optionClass = classes({ 'Select-option': true, 'is-focused': isFocused, 'is-disabled': op.disabled }); var ref = isFocused ? 'focused' : null; var mouseEnter = this.focusOption.bind(this, op), mouseLeave = this.unfocusOption.bind(this, op), mouseDown = this.selectValue.bind(this, op); if(op.disabled) { return <div ref={ref} key={'option-' + op.value} className={optionClass}>{op.label}</div>; } else { return <div ref={ref} key={'option-' + op.value} className={optionClass} onMouseEnter={mouseEnter} onMouseLeave={mouseLeave} onMouseDown={mouseDown} onClick={mouseDown}>{op.label}</div>; } }, this); return ops.length ? ops : ( <div className="Select-noresults"> {this.props.asyncOptions && !this.state.inputValue ? this.props.searchPromptText : this.props.noResultsText} </div> ); }, handleOptionLabelClick: function (value, event) { var handler = this.props.onOptionLabelClick; if (handler) { handler(value, event); } }, render: function() { var selectClass = classes('Select', this.props.className, { 'is-multi': this.props.multi, 'is-searchable': this.props.searchable, 'is-open': this.state.isOpen, 'is-focused': this.state.isFocused, 'is-loading': this.state.isLoading, 'is-disabled': this.props.disabled, 'has-value': this.state.value }); var value = []; if (this.props.multi) { this.state.values.forEach(function(val) { var props = { key: val.value, optionLabelClick: !!this.props.onOptionLabelClick, onOptionLabelClick: this.handleOptionLabelClick.bind(this, val), onRemove: this.removeValue.bind(this, val) }; for (var key in val) { if (val.hasOwnProperty(key)) { props[key] = val[key]; } } value.push(<Value {...props} />); }, this); } if (this.props.disabled || (!this.state.inputValue && (!this.props.multi || !value.length))) { value.push(<div className="Select-placeholder" key="placeholder">{this.state.placeholder}</div>); } var loading = this.state.isLoading ? <span className="Select-loading" aria-hidden="true" /> : null; var clear = this.props.clearable && this.state.value && !this.props.disabled ? <span className="Select-clear" title={this.props.multi ? this.props.clearAllText : this.props.clearValueText} aria-label={this.props.multi ? this.props.clearAllText : this.props.clearValueText} onMouseDown={this.clearValue} onClick={this.clearValue} dangerouslySetInnerHTML={{ __html: '&times;' }} /> : null; var menu; var menuProps; if (this.state.isOpen) { menuProps = { ref: 'menu', className: 'Select-menu' }; if (this.props.multi) { menuProps.onMouseDown = this.handleMouseDown; } menu = ( <div ref="selectMenuContainer" className="Select-menu-outer"> <div {...menuProps}>{this.buildMenu()}</div> </div> ); } var input; var inputProps = { ref: 'input', className: 'Select-input', tabIndex: this.props.tabIndex || 0, onFocus: this.handleInputFocus, onBlur: this.handleInputBlur }; for (var key in this.props.inputProps) { if (this.props.inputProps.hasOwnProperty(key)) { inputProps[key] = this.props.inputProps[key]; } } if (this.props.searchable && !this.props.disabled) { input = <Input value={this.state.inputValue} onChange={this.handleInputChange} minWidth="5" {...inputProps} />; } else { input = <div {...inputProps}>&nbsp;</div>; } return ( <div ref="wrapper" className={selectClass}> <input type="hidden" ref="value" name={this.props.name} value={this.state.value} disabled={this.props.disabled} /> <div className="Select-control" ref="control" onKeyDown={this.handleKeyDown} onMouseDown={this.handleMouseDown} onTouchEnd={this.handleMouseDown}> {value} {input} <span className="Select-arrow" /> {loading} {clear} </div> {menu} </div> ); } }); module.exports = Select;
/* eslint-disable no-param-reassign */ import { isThereStillWorkToDo, isThisWorkUnitFinished, purgeCurrentWorkUnit, addWorkUnit, } from './scheduler'; import { havePropsChanged, updateProps, } from './props'; import { createTextDomNode, createDomNode, } from './domNodes'; import { createDomMarker, shiftCursor, } from './domMarker'; const WORK_TYPES = { DIFF: 'DIFF', APPEND: 'APPEND', }; function createUnitOfWork(workType, parentVNode, nextTree, currentTree, domMarker, treeCursor = 0) { return { workType, parentVNode, nextTree, currentTree, treeCursor, domMarker, currentWorkStage: {}, state: 'SCHEDULED', }; } function createDiffUnitOfWork(nextTree, currentTree, domMarker, parentVNode) { return createUnitOfWork(WORK_TYPES.DIFF, parentVNode, nextTree, currentTree, domMarker); } function createAppendUnitOfWork(nextTree, domMarker, parentVNode) { return createUnitOfWork(WORK_TYPES.APPEND, parentVNode, nextTree, [], domMarker); } function performsWorkUnit(workUnit, scheduler) { const { domMarker = {}, nextTree, currentTree, treeCursor, } = workUnit; const nextNode = nextTree[treeCursor]; const currentNode = currentTree[treeCursor]; if (typeof nextNode === 'object') { if (nextNode.nodeType === 'container') { let newElementsTree = nextNode.type({ ...nextNode.props, children: nextNode.children, }); newElementsTree = Array.isArray(newElementsTree) ? newElementsTree : [newElementsTree]; nextNode.subTree = newElementsTree; } else { nextNode.subTree = nextNode.children; } } switch (workUnit.workType) { case WORK_TYPES.APPEND: { if (workUnit.state === 'IN_PROGRESS') { if (nextNode !== null && nextNode !== undefined) { if (typeof nextNode === 'object') { if (nextNode.nodeType === 'container') { // use sub tree addWorkUnit( createAppendUnitOfWork(nextNode.subTree, domMarker, nextNode.parentVNode), scheduler, ); } else if (Array.isArray(nextNode)) { // use node as sub tree addWorkUnit( createAppendUnitOfWork(nextNode, domMarker), scheduler, ); } else { const createdNode = createDomNode(nextNode); // evaluate subtree if (nextNode.subTree && nextNode.subTree.length) { // put the work unit on hold until the children have been created // and save the createdNode into the currentWorkStage workUnit.state = 'ON_HOLD'; workUnit.currentWorkStage.createdNode = createdNode; addWorkUnit( createAppendUnitOfWork( nextNode.subTree, createDomMarker(createdNode), nextNode.parentVNode, ), scheduler, ); } else { domMarker.parent.appendChild(createdNode); } } } else { domMarker.parent.appendChild(createTextDomNode(nextNode)); } } } if (workUnit.state === 'ON_HOLD') { workUnit.state = 'IN_PROGRESS'; domMarker.parent.appendChild(workUnit.currentWorkStage.createdNode); } break; } case WORK_TYPES.DIFF: { if (nextNode === undefined) { // remove current node } else if (currentNode === undefined) { // create a new unit of work of type ADD // using the tree from the current cursor on // based on the assumption that if the current node // is undefined, we don't need to check the rest of this tree // since it would all end up in an ADD operation addWorkUnit( createAppendUnitOfWork(nextTree.slice(treeCursor), domMarker, nextNode.parentVNode), scheduler, ); } else if (typeof nextNode === 'object') { const { nodeType: nextNodeType, type: nextType, props: nextProps, } = nextNode || {}; const { nodeType: currentNodeType, type: currentType, props: currentProps, } = currentNode || {}; if ( nextNodeType !== currentNodeType || nextType !== currentType ) { // schedule replace } else if (havePropsChanged(currentProps, nextProps)) { // update props only if it's an element if (nextNodeType !== 'container') { updateProps(domMarker.cursor, nextProps, currentProps); } } if (Array.isArray(nextNode.subTree) && nextNode.subTree.length) { const subDomMarker = nextNodeType === 'container' ? domMarker : createDomMarker(domMarker.cursor); addWorkUnit( createDiffUnitOfWork(nextNode.subTree, currentNode.subTree, subDomMarker, nextNode), scheduler, ); } } else if (nextNode !== currentNode) { domMarker.parent.replaceChild( createTextDomNode(nextNode), domMarker.cursor, ); } break; } default: { throw new Error('batchUpdates: Unknown workType'); } } // move the dom cursor if the parsed node is of type element if (typeof nextNode === 'object' && nextNode.nodeType === 'element') { shiftCursor(workUnit.domMarker); } // determine if the current unit is finished if (workUnit.state === 'IN_PROGRESS') { const nextTreeCursor = treeCursor + 1; if (nextTree[nextTreeCursor] === undefined && currentTree[nextTreeCursor] === undefined) { workUnit.state = 'FINISHED'; } else { workUnit.treeCursor = nextTreeCursor; } } } export default function batchUpdates(newTree, oldTree, container, scheduler = []) { scheduler.push(createDiffUnitOfWork(newTree, oldTree, createDomMarker(container))); let stillWorkToDo = true; while (stillWorkToDo) { const currentWorkUnit = scheduler[0]; if (currentWorkUnit.state === 'SCHEDULED') { currentWorkUnit.state = 'IN_PROGRESS'; } performsWorkUnit(currentWorkUnit, scheduler); if (isThisWorkUnitFinished(currentWorkUnit)) { purgeCurrentWorkUnit(currentWorkUnit, scheduler); } if (!isThereStillWorkToDo(scheduler)) { stillWorkToDo = false; } } }
'use strict' import React, { Component } from 'react' export default class Home extends Component { render () { return ( <div> <h1>Welcome home</h1> </div> ) } }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@firebase/app')) : typeof define === 'function' && define.amd ? define(['exports', '@firebase/app'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.firebase = global.firebase || {}, global.firebase.performance = global.firebase.performance || {}), global.firebase.app)); }(this, (function (exports, firebase) { 'use strict'; try { (function() { function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var firebase__default = /*#__PURE__*/_interopDefaultLegacy(firebase); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /** * This method checks if indexedDB is supported by current browser/service worker context * @return true if indexedDB is supported by current browser/service worker context */ function isIndexedDBAvailable() { return 'indexedDB' in self && indexedDB != null; } /** * This method validates browser context for indexedDB by opening a dummy indexedDB database and reject * if errors occur during the database open operation. */ function validateIndexedDBOpenable() { return new Promise(function (resolve, reject) { try { var preExist_1 = true; var DB_CHECK_NAME_1 = 'validate-browser-context-for-indexeddb-analytics-module'; var request_1 = window.indexedDB.open(DB_CHECK_NAME_1); request_1.onsuccess = function () { request_1.result.close(); // delete database only when it doesn't pre-exist if (!preExist_1) { window.indexedDB.deleteDatabase(DB_CHECK_NAME_1); } resolve(true); }; request_1.onupgradeneeded = function () { preExist_1 = false; }; request_1.onerror = function () { var _a; reject(((_a = request_1.error) === null || _a === void 0 ? void 0 : _a.message) || ''); }; } catch (error) { reject(error); } }); } /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var ERROR_NAME = 'FirebaseError'; // Based on code from: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types var FirebaseError = /** @class */ (function (_super) { __extends(FirebaseError, _super); function FirebaseError(code, message, customData) { var _this = _super.call(this, message) || this; _this.code = code; _this.customData = customData; _this.name = ERROR_NAME; // Fix For ES5 // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work Object.setPrototypeOf(_this, FirebaseError.prototype); // Maintains proper stack trace for where our error was thrown. // Only available on V8. if (Error.captureStackTrace) { Error.captureStackTrace(_this, ErrorFactory.prototype.create); } return _this; } return FirebaseError; }(Error)); var ErrorFactory = /** @class */ (function () { function ErrorFactory(service, serviceName, errors) { this.service = service; this.serviceName = serviceName; this.errors = errors; } ErrorFactory.prototype.create = function (code) { var data = []; for (var _i = 1; _i < arguments.length; _i++) { data[_i - 1] = arguments[_i]; } var customData = data[0] || {}; var fullCode = this.service + "/" + code; var template = this.errors[code]; var message = template ? replaceTemplate(template, customData) : 'Error'; // Service Name: Error message (service/code). var fullMessage = this.serviceName + ": " + message + " (" + fullCode + ")."; var error = new FirebaseError(fullCode, fullMessage, customData); return error; }; return ErrorFactory; }()); function replaceTemplate(template, data) { return template.replace(PATTERN, function (_, key) { var value = data[key]; return value != null ? String(value) : "<" + key + "?>"; }); } var PATTERN = /\{\$([^}]+)}/g; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __spreadArrays$1() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _a; /** * The JS SDK supports 5 log levels and also allows a user the ability to * silence the logs altogether. * * The order is a follows: * DEBUG < VERBOSE < INFO < WARN < ERROR * * All of the log types above the current log level will be captured (i.e. if * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and * `VERBOSE` logs will not) */ var LogLevel; (function (LogLevel) { LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; LogLevel[LogLevel["INFO"] = 2] = "INFO"; LogLevel[LogLevel["WARN"] = 3] = "WARN"; LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; })(LogLevel || (LogLevel = {})); var levelStringToEnum = { 'debug': LogLevel.DEBUG, 'verbose': LogLevel.VERBOSE, 'info': LogLevel.INFO, 'warn': LogLevel.WARN, 'error': LogLevel.ERROR, 'silent': LogLevel.SILENT }; /** * The default log level */ var defaultLogLevel = LogLevel.INFO; /** * By default, `console.debug` is not displayed in the developer console (in * chrome). To avoid forcing users to have to opt-in to these logs twice * (i.e. once for firebase, and once in the console), we are sending `DEBUG` * logs to the `console.log` function. */ var ConsoleMethod = (_a = {}, _a[LogLevel.DEBUG] = 'log', _a[LogLevel.VERBOSE] = 'log', _a[LogLevel.INFO] = 'info', _a[LogLevel.WARN] = 'warn', _a[LogLevel.ERROR] = 'error', _a); /** * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR * messages on to their corresponding console counterparts (if the log method * is supported by the current log level) */ var defaultLogHandler = function (instance, logType) { var args = []; for (var _i = 2; _i < arguments.length; _i++) { args[_i - 2] = arguments[_i]; } if (logType < instance.logLevel) { return; } var now = new Date().toISOString(); var method = ConsoleMethod[logType]; if (method) { console[method].apply(console, __spreadArrays$1(["[" + now + "] " + instance.name + ":"], args)); } else { throw new Error("Attempted to log a message with an invalid logType (value: " + logType + ")"); } }; var Logger = /** @class */ (function () { /** * Gives you an instance of a Logger to capture messages according to * Firebase's logging scheme. * * @param name The name that the logs will be associated with */ function Logger(name) { this.name = name; /** * The log level of the given Logger instance. */ this._logLevel = defaultLogLevel; /** * The main (internal) log handler for the Logger instance. * Can be set to a new function in internal package code but not by user. */ this._logHandler = defaultLogHandler; /** * The optional, additional, user-defined log handler for the Logger instance. */ this._userLogHandler = null; } Object.defineProperty(Logger.prototype, "logLevel", { get: function () { return this._logLevel; }, set: function (val) { if (!(val in LogLevel)) { throw new TypeError("Invalid value \"" + val + "\" assigned to `logLevel`"); } this._logLevel = val; }, enumerable: false, configurable: true }); // Workaround for setter/getter having to be the same type. Logger.prototype.setLogLevel = function (val) { this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; }; Object.defineProperty(Logger.prototype, "logHandler", { get: function () { return this._logHandler; }, set: function (val) { if (typeof val !== 'function') { throw new TypeError('Value assigned to `logHandler` must be a function'); } this._logHandler = val; }, enumerable: false, configurable: true }); Object.defineProperty(Logger.prototype, "userLogHandler", { get: function () { return this._userLogHandler; }, set: function (val) { this._userLogHandler = val; }, enumerable: false, configurable: true }); /** * The functions below are all based on the `console` interface */ Logger.prototype.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays$1([this, LogLevel.DEBUG], args)); this._logHandler.apply(this, __spreadArrays$1([this, LogLevel.DEBUG], args)); }; Logger.prototype.log = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays$1([this, LogLevel.VERBOSE], args)); this._logHandler.apply(this, __spreadArrays$1([this, LogLevel.VERBOSE], args)); }; Logger.prototype.info = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays$1([this, LogLevel.INFO], args)); this._logHandler.apply(this, __spreadArrays$1([this, LogLevel.INFO], args)); }; Logger.prototype.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays$1([this, LogLevel.WARN], args)); this._logHandler.apply(this, __spreadArrays$1([this, LogLevel.WARN], args)); }; Logger.prototype.error = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this._userLogHandler && this._userLogHandler.apply(this, __spreadArrays$1([this, LogLevel.ERROR], args)); this._logHandler.apply(this, __spreadArrays$1([this, LogLevel.ERROR], args)); }; return Logger; }()); /** * Component for service name T, e.g. `auth`, `auth-internal` */ var Component = /** @class */ (function () { /** * * @param name The public service name, e.g. app, auth, firestore, database * @param instanceFactory Service factory responsible for creating the public interface * @param type whether the service provided by the component is public or private */ function Component(name, instanceFactory, type) { this.name = name; this.instanceFactory = instanceFactory; this.type = type; this.multipleInstances = false; /** * Properties to be added to the service namespace */ this.serviceProps = {}; this.instantiationMode = "LAZY" /* LAZY */; } Component.prototype.setInstantiationMode = function (mode) { this.instantiationMode = mode; return this; }; Component.prototype.setMultipleInstances = function (multipleInstances) { this.multipleInstances = multipleInstances; return this; }; Component.prototype.setServiceProps = function (props) { this.serviceProps = props; return this; }; return Component; }()); function toArray(arr) { return Array.prototype.slice.call(arr); } function promisifyRequest(request) { return new Promise(function(resolve, reject) { request.onsuccess = function() { resolve(request.result); }; request.onerror = function() { reject(request.error); }; }); } function promisifyRequestCall(obj, method, args) { var request; var p = new Promise(function(resolve, reject) { request = obj[method].apply(obj, args); promisifyRequest(request).then(resolve, reject); }); p.request = request; return p; } function promisifyCursorRequestCall(obj, method, args) { var p = promisifyRequestCall(obj, method, args); return p.then(function(value) { if (!value) return; return new Cursor(value, p.request); }); } function proxyProperties(ProxyClass, targetProp, properties) { properties.forEach(function(prop) { Object.defineProperty(ProxyClass.prototype, prop, { get: function() { return this[targetProp][prop]; }, set: function(val) { this[targetProp][prop] = val; } }); }); } function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) { properties.forEach(function(prop) { if (!(prop in Constructor.prototype)) return; ProxyClass.prototype[prop] = function() { return promisifyRequestCall(this[targetProp], prop, arguments); }; }); } function proxyMethods(ProxyClass, targetProp, Constructor, properties) { properties.forEach(function(prop) { if (!(prop in Constructor.prototype)) return; ProxyClass.prototype[prop] = function() { return this[targetProp][prop].apply(this[targetProp], arguments); }; }); } function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) { properties.forEach(function(prop) { if (!(prop in Constructor.prototype)) return; ProxyClass.prototype[prop] = function() { return promisifyCursorRequestCall(this[targetProp], prop, arguments); }; }); } function Index(index) { this._index = index; } proxyProperties(Index, '_index', [ 'name', 'keyPath', 'multiEntry', 'unique' ]); proxyRequestMethods(Index, '_index', IDBIndex, [ 'get', 'getKey', 'getAll', 'getAllKeys', 'count' ]); proxyCursorRequestMethods(Index, '_index', IDBIndex, [ 'openCursor', 'openKeyCursor' ]); function Cursor(cursor, request) { this._cursor = cursor; this._request = request; } proxyProperties(Cursor, '_cursor', [ 'direction', 'key', 'primaryKey', 'value' ]); proxyRequestMethods(Cursor, '_cursor', IDBCursor, [ 'update', 'delete' ]); // proxy 'next' methods ['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) { if (!(methodName in IDBCursor.prototype)) return; Cursor.prototype[methodName] = function() { var cursor = this; var args = arguments; return Promise.resolve().then(function() { cursor._cursor[methodName].apply(cursor._cursor, args); return promisifyRequest(cursor._request).then(function(value) { if (!value) return; return new Cursor(value, cursor._request); }); }); }; }); function ObjectStore(store) { this._store = store; } ObjectStore.prototype.createIndex = function() { return new Index(this._store.createIndex.apply(this._store, arguments)); }; ObjectStore.prototype.index = function() { return new Index(this._store.index.apply(this._store, arguments)); }; proxyProperties(ObjectStore, '_store', [ 'name', 'keyPath', 'indexNames', 'autoIncrement' ]); proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [ 'put', 'add', 'delete', 'clear', 'get', 'getAll', 'getKey', 'getAllKeys', 'count' ]); proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [ 'openCursor', 'openKeyCursor' ]); proxyMethods(ObjectStore, '_store', IDBObjectStore, [ 'deleteIndex' ]); function Transaction(idbTransaction) { this._tx = idbTransaction; this.complete = new Promise(function(resolve, reject) { idbTransaction.oncomplete = function() { resolve(); }; idbTransaction.onerror = function() { reject(idbTransaction.error); }; idbTransaction.onabort = function() { reject(idbTransaction.error); }; }); } Transaction.prototype.objectStore = function() { return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments)); }; proxyProperties(Transaction, '_tx', [ 'objectStoreNames', 'mode' ]); proxyMethods(Transaction, '_tx', IDBTransaction, [ 'abort' ]); function UpgradeDB(db, oldVersion, transaction) { this._db = db; this.oldVersion = oldVersion; this.transaction = new Transaction(transaction); } UpgradeDB.prototype.createObjectStore = function() { return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments)); }; proxyProperties(UpgradeDB, '_db', [ 'name', 'version', 'objectStoreNames' ]); proxyMethods(UpgradeDB, '_db', IDBDatabase, [ 'deleteObjectStore', 'close' ]); function DB(db) { this._db = db; } DB.prototype.transaction = function() { return new Transaction(this._db.transaction.apply(this._db, arguments)); }; proxyProperties(DB, '_db', [ 'name', 'version', 'objectStoreNames' ]); proxyMethods(DB, '_db', IDBDatabase, [ 'close' ]); // Add cursor iterators // TODO: remove this once browsers do the right thing with promises ['openCursor', 'openKeyCursor'].forEach(function(funcName) { [ObjectStore, Index].forEach(function(Constructor) { // Don't create iterateKeyCursor if openKeyCursor doesn't exist. if (!(funcName in Constructor.prototype)) return; Constructor.prototype[funcName.replace('open', 'iterate')] = function() { var args = toArray(arguments); var callback = args[args.length - 1]; var nativeObject = this._store || this._index; var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1)); request.onsuccess = function() { callback(request.result); }; }; }); }); // polyfill getAll [Index, ObjectStore].forEach(function(Constructor) { if (Constructor.prototype.getAll) return; Constructor.prototype.getAll = function(query, count) { var instance = this; var items = []; return new Promise(function(resolve) { instance.iterateCursor(query, function(cursor) { if (!cursor) { resolve(items); return; } items.push(cursor.value); if (count !== undefined && items.length == count) { resolve(items); return; } cursor.continue(); }); }); }; }); function openDb(name, version, upgradeCallback) { var p = promisifyRequestCall(indexedDB, 'open', [name, version]); var request = p.request; if (request) { request.onupgradeneeded = function(event) { if (upgradeCallback) { upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction)); } }; } return p.then(function(db) { return new DB(db); }); } var name = "@firebase/installations"; var version = "0.4.19"; /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var PENDING_TIMEOUT_MS = 10000; var PACKAGE_VERSION = "w:" + version; var INTERNAL_AUTH_VERSION = 'FIS_v2'; var INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1'; var TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour var SERVICE = 'installations'; var SERVICE_NAME = 'Installations'; /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _a$1; var ERROR_DESCRIPTION_MAP = (_a$1 = {}, _a$1["missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */] = 'Missing App configuration value: "{$valueName}"', _a$1["not-registered" /* NOT_REGISTERED */] = 'Firebase Installation is not registered.', _a$1["installation-not-found" /* INSTALLATION_NOT_FOUND */] = 'Firebase Installation not found.', _a$1["request-failed" /* REQUEST_FAILED */] = '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"', _a$1["app-offline" /* APP_OFFLINE */] = 'Could not process request. Application offline.', _a$1["delete-pending-registration" /* DELETE_PENDING_REGISTRATION */] = "Can't delete installation while there is a pending registration request.", _a$1); var ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP); /** Returns true if error is a FirebaseError that is based on an error from the server. */ function isServerError(error) { return (error instanceof FirebaseError && error.code.includes("request-failed" /* REQUEST_FAILED */)); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function getInstallationsEndpoint(_a) { var projectId = _a.projectId; return INSTALLATIONS_API_URL + "/projects/" + projectId + "/installations"; } function extractAuthTokenInfoFromResponse(response) { return { token: response.token, requestStatus: 2 /* COMPLETED */, expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn), creationTime: Date.now() }; } function getErrorFromResponse(requestName, response) { return __awaiter(this, void 0, void 0, function () { var responseJson, errorData; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, response.json()]; case 1: responseJson = _a.sent(); errorData = responseJson.error; return [2 /*return*/, ERROR_FACTORY.create("request-failed" /* REQUEST_FAILED */, { requestName: requestName, serverCode: errorData.code, serverMessage: errorData.message, serverStatus: errorData.status })]; } }); }); } function getHeaders(_a) { var apiKey = _a.apiKey; return new Headers({ 'Content-Type': 'application/json', Accept: 'application/json', 'x-goog-api-key': apiKey }); } function getHeadersWithAuth(appConfig, _a) { var refreshToken = _a.refreshToken; var headers = getHeaders(appConfig); headers.append('Authorization', getAuthorizationHeader(refreshToken)); return headers; } /** * Calls the passed in fetch wrapper and returns the response. * If the returned response has a status of 5xx, re-runs the function once and * returns the response. */ function retryIfServerError(fn) { return __awaiter(this, void 0, void 0, function () { var result; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, fn()]; case 1: result = _a.sent(); if (result.status >= 500 && result.status < 600) { // Internal Server Error. Retry request. return [2 /*return*/, fn()]; } return [2 /*return*/, result]; } }); }); } function getExpiresInFromResponseExpiresIn(responseExpiresIn) { // This works because the server will never respond with fractions of a second. return Number(responseExpiresIn.replace('s', '000')); } function getAuthorizationHeader(refreshToken) { return INTERNAL_AUTH_VERSION + " " + refreshToken; } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function createInstallationRequest(appConfig, _a) { var fid = _a.fid; return __awaiter(this, void 0, void 0, function () { var endpoint, headers, body, request, response, responseValue, registeredInstallationEntry; return __generator(this, function (_b) { switch (_b.label) { case 0: endpoint = getInstallationsEndpoint(appConfig); headers = getHeaders(appConfig); body = { fid: fid, authVersion: INTERNAL_AUTH_VERSION, appId: appConfig.appId, sdkVersion: PACKAGE_VERSION }; request = { method: 'POST', headers: headers, body: JSON.stringify(body) }; return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })]; case 1: response = _b.sent(); if (!response.ok) return [3 /*break*/, 3]; return [4 /*yield*/, response.json()]; case 2: responseValue = _b.sent(); registeredInstallationEntry = { fid: responseValue.fid || fid, registrationStatus: 2 /* COMPLETED */, refreshToken: responseValue.refreshToken, authToken: extractAuthTokenInfoFromResponse(responseValue.authToken) }; return [2 /*return*/, registeredInstallationEntry]; case 3: return [4 /*yield*/, getErrorFromResponse('Create Installation', response)]; case 4: throw _b.sent(); } }); }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Returns a promise that resolves after given time passes. */ function sleep(ms) { return new Promise(function (resolve) { setTimeout(resolve, ms); }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function bufferToBase64UrlSafe(array) { var b64 = btoa(String.fromCharCode.apply(String, __spread(array))); return b64.replace(/\+/g, '-').replace(/\//g, '_'); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var VALID_FID_PATTERN = /^[cdef][\w-]{21}$/; var INVALID_FID = ''; /** * Generates a new FID using random values from Web Crypto API. * Returns an empty string if FID generation fails for any reason. */ function generateFid() { try { // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5 // bytes. our implementation generates a 17 byte array instead. var fidByteArray = new Uint8Array(17); var crypto_1 = self.crypto || self.msCrypto; crypto_1.getRandomValues(fidByteArray); // Replace the first 4 random bits with the constant FID header of 0b0111. fidByteArray[0] = 112 + (fidByteArray[0] % 16); var fid = encode(fidByteArray); return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID; } catch (_a) { // FID generation errored return INVALID_FID; } } /** Converts a FID Uint8Array to a base64 string representation. */ function encode(fidByteArray) { var b64String = bufferToBase64UrlSafe(fidByteArray); // Remove the 23rd character that was added because of the extra 4 bits at the // end of our 17 byte array, and the '=' padding. return b64String.substr(0, 22); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Returns a string key that can be used to identify the app. */ function getKey(appConfig) { return appConfig.appName + "!" + appConfig.appId; } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var fidChangeCallbacks = new Map(); /** * Calls the onIdChange callbacks with the new FID value, and broadcasts the * change to other tabs. */ function fidChanged(appConfig, fid) { var key = getKey(appConfig); callFidChangeCallbacks(key, fid); broadcastFidChange(key, fid); } function addCallback(appConfig, callback) { // Open the broadcast channel if it's not already open, // to be able to listen to change events from other tabs. getBroadcastChannel(); var key = getKey(appConfig); var callbackSet = fidChangeCallbacks.get(key); if (!callbackSet) { callbackSet = new Set(); fidChangeCallbacks.set(key, callbackSet); } callbackSet.add(callback); } function removeCallback(appConfig, callback) { var key = getKey(appConfig); var callbackSet = fidChangeCallbacks.get(key); if (!callbackSet) { return; } callbackSet.delete(callback); if (callbackSet.size === 0) { fidChangeCallbacks.delete(key); } // Close broadcast channel if there are no more callbacks. closeBroadcastChannel(); } function callFidChangeCallbacks(key, fid) { var e_1, _a; var callbacks = fidChangeCallbacks.get(key); if (!callbacks) { return; } try { for (var callbacks_1 = __values(callbacks), callbacks_1_1 = callbacks_1.next(); !callbacks_1_1.done; callbacks_1_1 = callbacks_1.next()) { var callback = callbacks_1_1.value; callback(fid); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (callbacks_1_1 && !callbacks_1_1.done && (_a = callbacks_1.return)) _a.call(callbacks_1); } finally { if (e_1) throw e_1.error; } } } function broadcastFidChange(key, fid) { var channel = getBroadcastChannel(); if (channel) { channel.postMessage({ key: key, fid: fid }); } closeBroadcastChannel(); } var broadcastChannel = null; /** Opens and returns a BroadcastChannel if it is supported by the browser. */ function getBroadcastChannel() { if (!broadcastChannel && 'BroadcastChannel' in self) { broadcastChannel = new BroadcastChannel('[Firebase] FID Change'); broadcastChannel.onmessage = function (e) { callFidChangeCallbacks(e.data.key, e.data.fid); }; } return broadcastChannel; } function closeBroadcastChannel() { if (fidChangeCallbacks.size === 0 && broadcastChannel) { broadcastChannel.close(); broadcastChannel = null; } } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var DATABASE_NAME = 'firebase-installations-database'; var DATABASE_VERSION = 1; var OBJECT_STORE_NAME = 'firebase-installations-store'; var dbPromise = null; function getDbPromise() { if (!dbPromise) { dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, function (upgradeDB) { // We don't use 'break' in this switch statement, the fall-through // behavior is what we want, because if there are multiple versions between // the old version and the current version, we want ALL the migrations // that correspond to those versions to run, not only the last one. // eslint-disable-next-line default-case switch (upgradeDB.oldVersion) { case 0: upgradeDB.createObjectStore(OBJECT_STORE_NAME); } }); } return dbPromise; } /** Assigns or overwrites the record for the given key with the given value. */ function set(appConfig, value) { return __awaiter(this, void 0, void 0, function () { var key, db, tx, objectStore, oldValue; return __generator(this, function (_a) { switch (_a.label) { case 0: key = getKey(appConfig); return [4 /*yield*/, getDbPromise()]; case 1: db = _a.sent(); tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); objectStore = tx.objectStore(OBJECT_STORE_NAME); return [4 /*yield*/, objectStore.get(key)]; case 2: oldValue = _a.sent(); return [4 /*yield*/, objectStore.put(value, key)]; case 3: _a.sent(); return [4 /*yield*/, tx.complete]; case 4: _a.sent(); if (!oldValue || oldValue.fid !== value.fid) { fidChanged(appConfig, value.fid); } return [2 /*return*/, value]; } }); }); } /** Removes record(s) from the objectStore that match the given key. */ function remove(appConfig) { return __awaiter(this, void 0, void 0, function () { var key, db, tx; return __generator(this, function (_a) { switch (_a.label) { case 0: key = getKey(appConfig); return [4 /*yield*/, getDbPromise()]; case 1: db = _a.sent(); tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); return [4 /*yield*/, tx.objectStore(OBJECT_STORE_NAME).delete(key)]; case 2: _a.sent(); return [4 /*yield*/, tx.complete]; case 3: _a.sent(); return [2 /*return*/]; } }); }); } /** * Atomically updates a record with the result of updateFn, which gets * called with the current value. If newValue is undefined, the record is * deleted instead. * @return Updated value */ function update(appConfig, updateFn) { return __awaiter(this, void 0, void 0, function () { var key, db, tx, store, oldValue, newValue; return __generator(this, function (_a) { switch (_a.label) { case 0: key = getKey(appConfig); return [4 /*yield*/, getDbPromise()]; case 1: db = _a.sent(); tx = db.transaction(OBJECT_STORE_NAME, 'readwrite'); store = tx.objectStore(OBJECT_STORE_NAME); return [4 /*yield*/, store.get(key)]; case 2: oldValue = _a.sent(); newValue = updateFn(oldValue); if (!(newValue === undefined)) return [3 /*break*/, 4]; return [4 /*yield*/, store.delete(key)]; case 3: _a.sent(); return [3 /*break*/, 6]; case 4: return [4 /*yield*/, store.put(newValue, key)]; case 5: _a.sent(); _a.label = 6; case 6: return [4 /*yield*/, tx.complete]; case 7: _a.sent(); if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) { fidChanged(appConfig, newValue.fid); } return [2 /*return*/, newValue]; } }); }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Updates and returns the InstallationEntry from the database. * Also triggers a registration request if it is necessary and possible. */ function getInstallationEntry(appConfig) { return __awaiter(this, void 0, void 0, function () { var registrationPromise, installationEntry; var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, update(appConfig, function (oldEntry) { var installationEntry = updateOrCreateInstallationEntry(oldEntry); var entryWithPromise = triggerRegistrationIfNecessary(appConfig, installationEntry); registrationPromise = entryWithPromise.registrationPromise; return entryWithPromise.installationEntry; })]; case 1: installationEntry = _b.sent(); if (!(installationEntry.fid === INVALID_FID)) return [3 /*break*/, 3]; _a = {}; return [4 /*yield*/, registrationPromise]; case 2: // FID generation failed. Waiting for the FID from the server. return [2 /*return*/, (_a.installationEntry = _b.sent(), _a)]; case 3: return [2 /*return*/, { installationEntry: installationEntry, registrationPromise: registrationPromise }]; } }); }); } /** * Creates a new Installation Entry if one does not exist. * Also clears timed out pending requests. */ function updateOrCreateInstallationEntry(oldEntry) { var entry = oldEntry || { fid: generateFid(), registrationStatus: 0 /* NOT_STARTED */ }; return clearTimedOutRequest(entry); } /** * If the Firebase Installation is not registered yet, this will trigger the * registration and return an InProgressInstallationEntry. * * If registrationPromise does not exist, the installationEntry is guaranteed * to be registered. */ function triggerRegistrationIfNecessary(appConfig, installationEntry) { if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) { if (!navigator.onLine) { // Registration required but app is offline. var registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */)); return { installationEntry: installationEntry, registrationPromise: registrationPromiseWithError }; } // Try registering. Change status to IN_PROGRESS. var inProgressEntry = { fid: installationEntry.fid, registrationStatus: 1 /* IN_PROGRESS */, registrationTime: Date.now() }; var registrationPromise = registerInstallation(appConfig, inProgressEntry); return { installationEntry: inProgressEntry, registrationPromise: registrationPromise }; } else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) { return { installationEntry: installationEntry, registrationPromise: waitUntilFidRegistration(appConfig) }; } else { return { installationEntry: installationEntry }; } } /** This will be executed only once for each new Firebase Installation. */ function registerInstallation(appConfig, installationEntry) { return __awaiter(this, void 0, void 0, function () { var registeredInstallationEntry, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 7]); return [4 /*yield*/, createInstallationRequest(appConfig, installationEntry)]; case 1: registeredInstallationEntry = _a.sent(); return [2 /*return*/, set(appConfig, registeredInstallationEntry)]; case 2: e_1 = _a.sent(); if (!(isServerError(e_1) && e_1.customData.serverCode === 409)) return [3 /*break*/, 4]; // Server returned a "FID can not be used" error. // Generate a new ID next time. return [4 /*yield*/, remove(appConfig)]; case 3: // Server returned a "FID can not be used" error. // Generate a new ID next time. _a.sent(); return [3 /*break*/, 6]; case 4: // Registration failed. Set FID as not registered. return [4 /*yield*/, set(appConfig, { fid: installationEntry.fid, registrationStatus: 0 /* NOT_STARTED */ })]; case 5: // Registration failed. Set FID as not registered. _a.sent(); _a.label = 6; case 6: throw e_1; case 7: return [2 /*return*/]; } }); }); } /** Call if FID registration is pending in another request. */ function waitUntilFidRegistration(appConfig) { return __awaiter(this, void 0, void 0, function () { var entry, _a, installationEntry, registrationPromise; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, updateInstallationRequest(appConfig)]; case 1: entry = _b.sent(); _b.label = 2; case 2: if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5]; // createInstallation request still in progress. return [4 /*yield*/, sleep(100)]; case 3: // createInstallation request still in progress. _b.sent(); return [4 /*yield*/, updateInstallationRequest(appConfig)]; case 4: entry = _b.sent(); return [3 /*break*/, 2]; case 5: if (!(entry.registrationStatus === 0 /* NOT_STARTED */)) return [3 /*break*/, 7]; return [4 /*yield*/, getInstallationEntry(appConfig)]; case 6: _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise; if (registrationPromise) { return [2 /*return*/, registrationPromise]; } else { // if there is no registrationPromise, entry is registered. return [2 /*return*/, installationEntry]; } case 7: return [2 /*return*/, entry]; } }); }); } /** * Called only if there is a CreateInstallation request in progress. * * Updates the InstallationEntry in the DB based on the status of the * CreateInstallation request. * * Returns the updated InstallationEntry. */ function updateInstallationRequest(appConfig) { return update(appConfig, function (oldEntry) { if (!oldEntry) { throw ERROR_FACTORY.create("installation-not-found" /* INSTALLATION_NOT_FOUND */); } return clearTimedOutRequest(oldEntry); }); } function clearTimedOutRequest(entry) { if (hasInstallationRequestTimedOut(entry)) { return { fid: entry.fid, registrationStatus: 0 /* NOT_STARTED */ }; } return entry; } function hasInstallationRequestTimedOut(installationEntry) { return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ && installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function generateAuthTokenRequest(_a, installationEntry) { var appConfig = _a.appConfig, platformLoggerProvider = _a.platformLoggerProvider; return __awaiter(this, void 0, void 0, function () { var endpoint, headers, platformLogger, body, request, response, responseValue, completedAuthToken; return __generator(this, function (_b) { switch (_b.label) { case 0: endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry); headers = getHeadersWithAuth(appConfig, installationEntry); platformLogger = platformLoggerProvider.getImmediate({ optional: true }); if (platformLogger) { headers.append('x-firebase-client', platformLogger.getPlatformInfoString()); } body = { installation: { sdkVersion: PACKAGE_VERSION } }; request = { method: 'POST', headers: headers, body: JSON.stringify(body) }; return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })]; case 1: response = _b.sent(); if (!response.ok) return [3 /*break*/, 3]; return [4 /*yield*/, response.json()]; case 2: responseValue = _b.sent(); completedAuthToken = extractAuthTokenInfoFromResponse(responseValue); return [2 /*return*/, completedAuthToken]; case 3: return [4 /*yield*/, getErrorFromResponse('Generate Auth Token', response)]; case 4: throw _b.sent(); } }); }); } function getGenerateAuthTokenEndpoint(appConfig, _a) { var fid = _a.fid; return getInstallationsEndpoint(appConfig) + "/" + fid + "/authTokens:generate"; } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Returns a valid authentication token for the installation. Generates a new * token if one doesn't exist, is expired or about to expire. * * Should only be called if the Firebase Installation is registered. */ function refreshAuthToken(dependencies, forceRefresh) { if (forceRefresh === void 0) { forceRefresh = false; } return __awaiter(this, void 0, void 0, function () { var tokenPromise, entry, authToken, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, update(dependencies.appConfig, function (oldEntry) { if (!isEntryRegistered(oldEntry)) { throw ERROR_FACTORY.create("not-registered" /* NOT_REGISTERED */); } var oldAuthToken = oldEntry.authToken; if (!forceRefresh && isAuthTokenValid(oldAuthToken)) { // There is a valid token in the DB. return oldEntry; } else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) { // There already is a token request in progress. tokenPromise = waitUntilAuthTokenRequest(dependencies, forceRefresh); return oldEntry; } else { // No token or token expired. if (!navigator.onLine) { throw ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */); } var inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry); tokenPromise = fetchAuthTokenFromServer(dependencies, inProgressEntry); return inProgressEntry; } })]; case 1: entry = _b.sent(); if (!tokenPromise) return [3 /*break*/, 3]; return [4 /*yield*/, tokenPromise]; case 2: _a = _b.sent(); return [3 /*break*/, 4]; case 3: _a = entry.authToken; _b.label = 4; case 4: authToken = _a; return [2 /*return*/, authToken]; } }); }); } /** * Call only if FID is registered and Auth Token request is in progress. * * Waits until the current pending request finishes. If the request times out, * tries once in this thread as well. */ function waitUntilAuthTokenRequest(dependencies, forceRefresh) { return __awaiter(this, void 0, void 0, function () { var entry, authToken; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)]; case 1: entry = _a.sent(); _a.label = 2; case 2: if (!(entry.authToken.requestStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 5]; // generateAuthToken still in progress. return [4 /*yield*/, sleep(100)]; case 3: // generateAuthToken still in progress. _a.sent(); return [4 /*yield*/, updateAuthTokenRequest(dependencies.appConfig)]; case 4: entry = _a.sent(); return [3 /*break*/, 2]; case 5: authToken = entry.authToken; if (authToken.requestStatus === 0 /* NOT_STARTED */) { // The request timed out or failed in a different call. Try again. return [2 /*return*/, refreshAuthToken(dependencies, forceRefresh)]; } else { return [2 /*return*/, authToken]; } } }); }); } /** * Called only if there is a GenerateAuthToken request in progress. * * Updates the InstallationEntry in the DB based on the status of the * GenerateAuthToken request. * * Returns the updated InstallationEntry. */ function updateAuthTokenRequest(appConfig) { return update(appConfig, function (oldEntry) { if (!isEntryRegistered(oldEntry)) { throw ERROR_FACTORY.create("not-registered" /* NOT_REGISTERED */); } var oldAuthToken = oldEntry.authToken; if (hasAuthTokenRequestTimedOut(oldAuthToken)) { return __assign(__assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } }); } return oldEntry; }); } function fetchAuthTokenFromServer(dependencies, installationEntry) { return __awaiter(this, void 0, void 0, function () { var authToken, updatedInstallationEntry, e_1, updatedInstallationEntry; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 3, , 8]); return [4 /*yield*/, generateAuthTokenRequest(dependencies, installationEntry)]; case 1: authToken = _a.sent(); updatedInstallationEntry = __assign(__assign({}, installationEntry), { authToken: authToken }); return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)]; case 2: _a.sent(); return [2 /*return*/, authToken]; case 3: e_1 = _a.sent(); if (!(isServerError(e_1) && (e_1.customData.serverCode === 401 || e_1.customData.serverCode === 404))) return [3 /*break*/, 5]; // Server returned a "FID not found" or a "Invalid authentication" error. // Generate a new ID next time. return [4 /*yield*/, remove(dependencies.appConfig)]; case 4: // Server returned a "FID not found" or a "Invalid authentication" error. // Generate a new ID next time. _a.sent(); return [3 /*break*/, 7]; case 5: updatedInstallationEntry = __assign(__assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } }); return [4 /*yield*/, set(dependencies.appConfig, updatedInstallationEntry)]; case 6: _a.sent(); _a.label = 7; case 7: throw e_1; case 8: return [2 /*return*/]; } }); }); } function isEntryRegistered(installationEntry) { return (installationEntry !== undefined && installationEntry.registrationStatus === 2 /* COMPLETED */); } function isAuthTokenValid(authToken) { return (authToken.requestStatus === 2 /* COMPLETED */ && !isAuthTokenExpired(authToken)); } function isAuthTokenExpired(authToken) { var now = Date.now(); return (now < authToken.creationTime || authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER); } /** Returns an updated InstallationEntry with an InProgressAuthToken. */ function makeAuthTokenRequestInProgressEntry(oldEntry) { var inProgressAuthToken = { requestStatus: 1 /* IN_PROGRESS */, requestTime: Date.now() }; return __assign(__assign({}, oldEntry), { authToken: inProgressAuthToken }); } function hasAuthTokenRequestTimedOut(authToken) { return (authToken.requestStatus === 1 /* IN_PROGRESS */ && authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function getId(dependencies) { return __awaiter(this, void 0, void 0, function () { var _a, installationEntry, registrationPromise; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, getInstallationEntry(dependencies.appConfig)]; case 1: _a = _b.sent(), installationEntry = _a.installationEntry, registrationPromise = _a.registrationPromise; if (registrationPromise) { registrationPromise.catch(console.error); } else { // If the installation is already registered, update the authentication // token if needed. refreshAuthToken(dependencies).catch(console.error); } return [2 /*return*/, installationEntry.fid]; } }); }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function getToken(dependencies, forceRefresh) { if (forceRefresh === void 0) { forceRefresh = false; } return __awaiter(this, void 0, void 0, function () { var authToken; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, completeInstallationRegistration(dependencies.appConfig)]; case 1: _a.sent(); return [4 /*yield*/, refreshAuthToken(dependencies, forceRefresh)]; case 2: authToken = _a.sent(); return [2 /*return*/, authToken.token]; } }); }); } function completeInstallationRegistration(appConfig) { return __awaiter(this, void 0, void 0, function () { var registrationPromise; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getInstallationEntry(appConfig)]; case 1: registrationPromise = (_a.sent()).registrationPromise; if (!registrationPromise) return [3 /*break*/, 3]; // A createInstallation request is in progress. Wait until it finishes. return [4 /*yield*/, registrationPromise]; case 2: // A createInstallation request is in progress. Wait until it finishes. _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function deleteInstallationRequest(appConfig, installationEntry) { return __awaiter(this, void 0, void 0, function () { var endpoint, headers, request, response; return __generator(this, function (_a) { switch (_a.label) { case 0: endpoint = getDeleteEndpoint(appConfig, installationEntry); headers = getHeadersWithAuth(appConfig, installationEntry); request = { method: 'DELETE', headers: headers }; return [4 /*yield*/, retryIfServerError(function () { return fetch(endpoint, request); })]; case 1: response = _a.sent(); if (!!response.ok) return [3 /*break*/, 3]; return [4 /*yield*/, getErrorFromResponse('Delete Installation', response)]; case 2: throw _a.sent(); case 3: return [2 /*return*/]; } }); }); } function getDeleteEndpoint(appConfig, _a) { var fid = _a.fid; return getInstallationsEndpoint(appConfig) + "/" + fid; } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function deleteInstallation(dependencies) { return __awaiter(this, void 0, void 0, function () { var appConfig, entry; return __generator(this, function (_a) { switch (_a.label) { case 0: appConfig = dependencies.appConfig; return [4 /*yield*/, update(appConfig, function (oldEntry) { if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) { // Delete the unregistered entry without sending a deleteInstallation request. return undefined; } return oldEntry; })]; case 1: entry = _a.sent(); if (!entry) return [3 /*break*/, 6]; if (!(entry.registrationStatus === 1 /* IN_PROGRESS */)) return [3 /*break*/, 2]; // Can't delete while trying to register. throw ERROR_FACTORY.create("delete-pending-registration" /* DELETE_PENDING_REGISTRATION */); case 2: if (!(entry.registrationStatus === 2 /* COMPLETED */)) return [3 /*break*/, 6]; if (!!navigator.onLine) return [3 /*break*/, 3]; throw ERROR_FACTORY.create("app-offline" /* APP_OFFLINE */); case 3: return [4 /*yield*/, deleteInstallationRequest(appConfig, entry)]; case 4: _a.sent(); return [4 /*yield*/, remove(appConfig)]; case 5: _a.sent(); _a.label = 6; case 6: return [2 /*return*/]; } }); }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Sets a new callback that will get called when Installation ID changes. * Returns an unsubscribe function that will remove the callback when called. */ function onIdChange(_a, callback) { var appConfig = _a.appConfig; addCallback(appConfig, callback); return function () { removeCallback(appConfig, callback); }; } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function extractAppConfig(app) { var e_1, _a; if (!app || !app.options) { throw getMissingValueError('App Configuration'); } if (!app.name) { throw getMissingValueError('App Name'); } // Required app config keys var configKeys = [ 'projectId', 'apiKey', 'appId' ]; try { for (var configKeys_1 = __values(configKeys), configKeys_1_1 = configKeys_1.next(); !configKeys_1_1.done; configKeys_1_1 = configKeys_1.next()) { var keyName = configKeys_1_1.value; if (!app.options[keyName]) { throw getMissingValueError(keyName); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (configKeys_1_1 && !configKeys_1_1.done && (_a = configKeys_1.return)) _a.call(configKeys_1); } finally { if (e_1) throw e_1.error; } } return { appName: app.name, projectId: app.options.projectId, apiKey: app.options.apiKey, appId: app.options.appId }; } function getMissingValueError(valueName) { return ERROR_FACTORY.create("missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */, { valueName: valueName }); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function registerInstallations(instance) { var installationsName = 'installations'; instance.INTERNAL.registerComponent(new Component(installationsName, function (container) { var app = container.getProvider('app').getImmediate(); // Throws if app isn't configured properly. var appConfig = extractAppConfig(app); var platformLoggerProvider = container.getProvider('platform-logger'); var dependencies = { appConfig: appConfig, platformLoggerProvider: platformLoggerProvider }; var installations = { app: app, getId: function () { return getId(dependencies); }, getToken: function (forceRefresh) { return getToken(dependencies, forceRefresh); }, delete: function () { return deleteInstallation(dependencies); }, onIdChange: function (callback) { return onIdChange(dependencies, callback); } }; return installations; }, "PUBLIC" /* PUBLIC */)); instance.registerVersion(name, version); } registerInstallations(firebase__default['default']); var name$1 = "@firebase/performance-exp"; var version$1 = "0.0.900"; /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var SDK_VERSION = version$1; /** The prefix for start User Timing marks used for creating Traces. */ var TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START'; /** The prefix for stop User Timing marks used for creating Traces. */ var TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP'; /** The prefix for User Timing measure used for creating Traces. */ var TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE'; /** The prefix for out of the box page load Trace name. */ var OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_'; var FIRST_PAINT_COUNTER_NAME = '_fp'; var FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp'; var FIRST_INPUT_DELAY_COUNTER_NAME = '_fid'; var CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config'; var CONFIG_EXPIRY_LOCAL_STORAGE_KEY = '@firebase/performance/configexpire'; var SERVICE$1 = 'performance'; var SERVICE_NAME$1 = 'Performance'; /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _a$2; var ERROR_DESCRIPTION_MAP$1 = (_a$2 = {}, _a$2["trace started" /* TRACE_STARTED_BEFORE */] = 'Trace {$traceName} was started before.', _a$2["trace stopped" /* TRACE_STOPPED_BEFORE */] = 'Trace {$traceName} is not running.', _a$2["nonpositive trace startTime" /* NONPOSITIVE_TRACE_START_TIME */] = 'Trace {$traceName} startTime should be positive.', _a$2["nonpositive trace duration" /* NONPOSITIVE_TRACE_DURATION */] = 'Trace {$traceName} duration should be positive.', _a$2["no window" /* NO_WINDOW */] = 'Window is not available.', _a$2["no app id" /* NO_APP_ID */] = 'App id is not available.', _a$2["no project id" /* NO_PROJECT_ID */] = 'Project id is not available.', _a$2["no api key" /* NO_API_KEY */] = 'Api key is not available.', _a$2["invalid cc log" /* INVALID_CC_LOG */] = 'Attempted to queue invalid cc event', _a$2["FB not default" /* FB_NOT_DEFAULT */] = 'Performance can only start when Firebase app instance is the default one.', _a$2["RC response not ok" /* RC_NOT_OK */] = 'RC response is not ok', _a$2["invalid attribute name" /* INVALID_ATTRIBUTE_NAME */] = 'Attribute name {$attributeName} is invalid.', _a$2["invalid attribute value" /* INVALID_ATTRIBUTE_VALUE */] = 'Attribute value {$attributeValue} is invalid.', _a$2["invalid custom metric name" /* INVALID_CUSTOM_METRIC_NAME */] = 'Custom metric name {$customMetricName} is invalid', _a$2["invalid String merger input" /* INVALID_STRING_MERGER_PARAMETER */] = 'Input for String merger is invalid, contact support team to resolve.', _a$2); var ERROR_FACTORY$1 = new ErrorFactory(SERVICE$1, SERVICE_NAME$1, ERROR_DESCRIPTION_MAP$1); /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var consoleLogger = new Logger(SERVICE_NAME$1); consoleLogger.logLevel = LogLevel.INFO; /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var apiInstance; var windowInstance; /** * This class holds a reference to various browser related objects injected by * set methods. */ var Api = /** @class */ (function () { function Api(window) { this.window = window; if (!window) { throw ERROR_FACTORY$1.create("no window" /* NO_WINDOW */); } this.performance = window.performance; this.PerformanceObserver = window.PerformanceObserver; this.windowLocation = window.location; this.navigator = window.navigator; this.document = window.document; if (this.navigator && this.navigator.cookieEnabled) { // If user blocks cookies on the browser, accessing localStorage will // throw an exception. this.localStorage = window.localStorage; } if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) { this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay; } } Api.prototype.getUrl = function () { // Do not capture the string query part of url. return this.windowLocation.href.split('?')[0]; }; Api.prototype.mark = function (name) { if (!this.performance || !this.performance.mark) { return; } this.performance.mark(name); }; Api.prototype.measure = function (measureName, mark1, mark2) { if (!this.performance || !this.performance.measure) { return; } this.performance.measure(measureName, mark1, mark2); }; Api.prototype.getEntriesByType = function (type) { if (!this.performance || !this.performance.getEntriesByType) { return []; } return this.performance.getEntriesByType(type); }; Api.prototype.getEntriesByName = function (name) { if (!this.performance || !this.performance.getEntriesByName) { return []; } return this.performance.getEntriesByName(name); }; Api.prototype.getTimeOrigin = function () { // Polyfill the time origin with performance.timing.navigationStart. return (this.performance && (this.performance.timeOrigin || this.performance.timing.navigationStart)); }; Api.prototype.requiredApisAvailable = function () { if (!fetch || !Promise || !this.navigator || !this.navigator.cookieEnabled) { consoleLogger.info('Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.'); return false; } if (!isIndexedDBAvailable()) { consoleLogger.info('IndexedDB is not supported by current browswer'); return false; } return true; }; Api.prototype.setupObserver = function (entryType, callback) { if (!this.PerformanceObserver) { return; } var observer = new this.PerformanceObserver(function (list) { for (var _i = 0, _a = list.getEntries(); _i < _a.length; _i++) { var entry = _a[_i]; // `entry` is a PerformanceEntry instance. callback(entry); } }); // Start observing the entry types you care about. observer.observe({ entryTypes: [entryType] }); }; Api.getInstance = function () { if (apiInstance === undefined) { apiInstance = new Api(windowInstance); } return apiInstance; }; return Api; }()); function setupApi(window) { windowInstance = window; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var iid; function getIidPromise(installationsService) { var iidPromise = installationsService.getId(); // eslint-disable-next-line @typescript-eslint/no-floating-promises iidPromise.then(function (iidVal) { iid = iidVal; }); return iidPromise; } // This method should be used after the iid is retrieved by getIidPromise method. function getIid() { return iid; } function getAuthTokenPromise(installationsService) { var authTokenPromise = installationsService.getToken(); // eslint-disable-next-line @typescript-eslint/no-floating-promises authTokenPromise.then(function (authTokenVal) { }); return authTokenPromise; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function mergeStrings(part1, part2) { var sizeDiff = part1.length - part2.length; if (sizeDiff < 0 || sizeDiff > 1) { throw ERROR_FACTORY$1.create("invalid String merger input" /* INVALID_STRING_MERGER_PARAMETER */); } var resultArray = []; for (var i = 0; i < part1.length; i++) { resultArray.push(part1.charAt(i)); if (part2.length > i) { resultArray.push(part2.charAt(i)); } } return resultArray.join(''); } /** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var settingsServiceInstance; var SettingsService = /** @class */ (function () { function SettingsService() { // The variable which controls logging of automatic traces and HTTP/S network monitoring. this.instrumentationEnabled = true; // The variable which controls logging of custom traces. this.dataCollectionEnabled = true; // Configuration flags set through remote config. this.loggingEnabled = false; // Sampling rate between 0 and 1. this.tracesSamplingRate = 1; this.networkRequestsSamplingRate = 1; // Address of logging service. this.logEndPointUrl = 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto'; // Performance event transport endpoint URL which should be compatible with proto3. // New Address for transport service, not configurable via Remote Config. this.flTransportEndpointUrl = mergeStrings('hts/frbslgigp.ogepscmv/ieo/eaylg', 'tp:/ieaeogn-agolai.o/1frlglgc/o'); this.transportKey = mergeStrings('AzSC8r6ReiGqFMyfvgow', 'Iayx0u-XT3vksVM-pIV'); // Source type for performance event logs. this.logSource = 462; // Flags which control per session logging of traces and network requests. this.logTraceAfterSampling = false; this.logNetworkAfterSampling = false; // TTL of config retrieved from remote config in hours. this.configTimeToLive = 12; } SettingsService.prototype.getFlTransportFullUrl = function () { return this.flTransportEndpointUrl.concat('?key=', this.transportKey); }; SettingsService.getInstance = function () { if (settingsServiceInstance === undefined) { settingsServiceInstance = new SettingsService(); } return settingsServiceInstance; }; return SettingsService; }()); /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var VisibilityState; (function (VisibilityState) { VisibilityState[VisibilityState["UNKNOWN"] = 0] = "UNKNOWN"; VisibilityState[VisibilityState["VISIBLE"] = 1] = "VISIBLE"; VisibilityState[VisibilityState["HIDDEN"] = 2] = "HIDDEN"; })(VisibilityState || (VisibilityState = {})); var RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_']; var ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\w*$'); var MAX_ATTRIBUTE_NAME_LENGTH = 40; var MAX_ATTRIBUTE_VALUE_LENGTH = 100; function getServiceWorkerStatus() { var navigator = Api.getInstance().navigator; if ('serviceWorker' in navigator) { if (navigator.serviceWorker.controller) { return 2 /* CONTROLLED */; } else { return 3 /* UNCONTROLLED */; } } else { return 1 /* UNSUPPORTED */; } } function getVisibilityState() { var document = Api.getInstance().document; var visibilityState = document.visibilityState; switch (visibilityState) { case 'visible': return VisibilityState.VISIBLE; case 'hidden': return VisibilityState.HIDDEN; default: return VisibilityState.UNKNOWN; } } function getEffectiveConnectionType() { var navigator = Api.getInstance().navigator; var navigatorConnection = navigator.connection; var effectiveType = navigatorConnection && navigatorConnection.effectiveType; switch (effectiveType) { case 'slow-2g': return 1 /* CONNECTION_SLOW_2G */; case '2g': return 2 /* CONNECTION_2G */; case '3g': return 3 /* CONNECTION_3G */; case '4g': return 4 /* CONNECTION_4G */; default: return 0 /* UNKNOWN */; } } function isValidCustomAttributeName(name) { if (name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) { return false; } var matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(function (prefix) { return name.startsWith(prefix); }); return !matchesReservedPrefix && !!name.match(ATTRIBUTE_FORMAT_REGEX); } function isValidCustomAttributeValue(value) { return value.length !== 0 && value.length <= MAX_ATTRIBUTE_VALUE_LENGTH; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function getAppId(firebaseApp) { var _a; var appId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.appId; if (!appId) { throw ERROR_FACTORY$1.create("no app id" /* NO_APP_ID */); } return appId; } function getProjectId(firebaseApp) { var _a; var projectId = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.projectId; if (!projectId) { throw ERROR_FACTORY$1.create("no project id" /* NO_PROJECT_ID */); } return projectId; } function getApiKey(firebaseApp) { var _a; var apiKey = (_a = firebaseApp.options) === null || _a === void 0 ? void 0 : _a.apiKey; if (!apiKey) { throw ERROR_FACTORY$1.create("no api key" /* NO_API_KEY */); } return apiKey; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var REMOTE_CONFIG_SDK_VERSION = '0.0.1'; // These values will be used if the remote config object is successfully // retrieved, but the template does not have these fields. var DEFAULT_CONFIGS = { loggingEnabled: true }; var FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH'; function getConfig(performanceController, iid) { var config = getStoredConfig(); if (config) { processConfig(config); return Promise.resolve(); } return getRemoteConfig(performanceController, iid) .then(processConfig) .then(function (config) { return storeConfig(config); }, /** Do nothing for error, use defaults set in settings service. */ function () { }); } function getStoredConfig() { var localStorage = Api.getInstance().localStorage; if (!localStorage) { return; } var expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY); if (!expiryString || !configValid(expiryString)) { return; } var configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY); if (!configStringified) { return; } try { var configResponse = JSON.parse(configStringified); return configResponse; } catch (_a) { return; } } function storeConfig(config) { var localStorage = Api.getInstance().localStorage; if (!config || !localStorage) { return; } localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config)); localStorage.setItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY, String(Date.now() + SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000)); } var COULD_NOT_GET_CONFIG_MSG = 'Could not fetch config, will use default configs'; function getRemoteConfig(performanceController, iid) { // Perf needs auth token only to retrieve remote config. return getAuthTokenPromise(performanceController.installations) .then(function (authToken) { var projectId = getProjectId(performanceController.app); var apiKey = getApiKey(performanceController.app); var configEndPoint = "https://firebaseremoteconfig.googleapis.com/v1/projects/" + projectId + "/namespaces/fireperf:fetch?key=" + apiKey; var request = new Request(configEndPoint, { method: 'POST', headers: { Authorization: FIS_AUTH_PREFIX + " " + authToken }, /* eslint-disable camelcase */ body: JSON.stringify({ app_instance_id: iid, app_instance_id_token: authToken, app_id: getAppId(performanceController.app), app_version: SDK_VERSION, sdk_version: REMOTE_CONFIG_SDK_VERSION }) /* eslint-enable camelcase */ }); return fetch(request).then(function (response) { if (response.ok) { return response.json(); } // In case response is not ok. This will be caught by catch. throw ERROR_FACTORY$1.create("RC response not ok" /* RC_NOT_OK */); }); }) .catch(function () { consoleLogger.info(COULD_NOT_GET_CONFIG_MSG); return undefined; }); } /** * Processes config coming either from calling RC or from local storage. * This method only runs if call is successful or config in storage * is valid. */ function processConfig(config) { if (!config) { return config; } var settingsServiceInstance = SettingsService.getInstance(); var entries = config.entries || {}; if (entries.fpr_enabled !== undefined) { // TODO: Change the assignment of loggingEnabled once the received type is // known. settingsServiceInstance.loggingEnabled = String(entries.fpr_enabled) === 'true'; } else { // Config retrieved successfully, but there is no fpr_enabled in template. // Use secondary configs value. settingsServiceInstance.loggingEnabled = DEFAULT_CONFIGS.loggingEnabled; } if (entries.fpr_log_source) { settingsServiceInstance.logSource = Number(entries.fpr_log_source); } if (entries.fpr_log_endpoint_url) { settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url; } // Key from Remote Config has to be non-empty string, otherwsie use local value. if (entries.fpr_log_transport_key) { settingsServiceInstance.transportKey = entries.fpr_log_transport_key; } if (entries.fpr_vc_network_request_sampling_rate !== undefined) { settingsServiceInstance.networkRequestsSamplingRate = Number(entries.fpr_vc_network_request_sampling_rate); } if (entries.fpr_vc_trace_sampling_rate !== undefined) { settingsServiceInstance.tracesSamplingRate = Number(entries.fpr_vc_trace_sampling_rate); } // Set the per session trace and network logging flags. settingsServiceInstance.logTraceAfterSampling = shouldLogAfterSampling(settingsServiceInstance.tracesSamplingRate); settingsServiceInstance.logNetworkAfterSampling = shouldLogAfterSampling(settingsServiceInstance.networkRequestsSamplingRate); return config; } function configValid(expiry) { return Number(expiry) > Date.now(); } function shouldLogAfterSampling(samplingRate) { return Math.random() <= samplingRate; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var initializationStatus = 1 /* notInitialized */; var initializationPromise; function getInitializationPromise(performanceController) { initializationStatus = 2 /* initializationPending */; initializationPromise = initializationPromise || initializePerf(performanceController); return initializationPromise; } function isPerfInitialized() { return initializationStatus === 3 /* initialized */; } function initializePerf(performanceController) { return getDocumentReadyComplete() .then(function () { return getIidPromise(performanceController.installations); }) .then(function (iid) { return getConfig(performanceController, iid); }) .then(function () { return changeInitializationStatus(); }, function () { return changeInitializationStatus(); }); } /** * Returns a promise which resolves whenever the document readystate is complete or * immediately if it is called after page load complete. */ function getDocumentReadyComplete() { var document = Api.getInstance().document; return new Promise(function (resolve) { if (document && document.readyState !== 'complete') { var handler_1 = function () { if (document.readyState === 'complete') { document.removeEventListener('readystatechange', handler_1); resolve(); } }; document.addEventListener('readystatechange', handler_1); } else { resolve(); } }); } function changeInitializationStatus() { initializationStatus = 3 /* initialized */; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var DEFAULT_SEND_INTERVAL_MS = 10 * 1000; var INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000; // If end point does not work, the call will be tried for these many times. var DEFAULT_REMAINING_TRIES = 3; var MAX_EVENT_COUNT_PER_REQUEST = 1000; var remainingTries = DEFAULT_REMAINING_TRIES; /* eslint-enable camelcase */ var queue = []; var isTransportSetup = false; function setupTransportService() { if (!isTransportSetup) { processQueue(INITIAL_SEND_TIME_DELAY_MS); isTransportSetup = true; } } function processQueue(timeOffset) { setTimeout(function () { // If there is no remainingTries left, stop retrying. if (remainingTries === 0) { return; } // If there are no events to process, wait for DEFAULT_SEND_INTERVAL_MS and try again. if (!queue.length) { return processQueue(DEFAULT_SEND_INTERVAL_MS); } dispatchQueueEvents(); }, timeOffset); } function dispatchQueueEvents() { // Extract events up to the maximum cap of single logRequest from top of "official queue". // The staged events will be used for current logRequest attempt, remaining events will be kept // for next attempt. var staged = queue.splice(0, MAX_EVENT_COUNT_PER_REQUEST); /* eslint-disable camelcase */ // We will pass the JSON serialized event to the backend. var log_event = staged.map(function (evt) { return ({ source_extension_json_proto3: evt.message, event_time_ms: String(evt.eventTime) }); }); var data = { request_time_ms: String(Date.now()), client_info: { client_type: 1, js_client_info: {} }, log_source: SettingsService.getInstance().logSource, log_event: log_event }; /* eslint-enable camelcase */ sendEventsToFl(data, staged).catch(function () { // If the request fails for some reason, add the events that were attempted // back to the primary queue to retry later. queue = __spreadArrays(staged, queue); remainingTries--; consoleLogger.info("Tries left: " + remainingTries + "."); processQueue(DEFAULT_SEND_INTERVAL_MS); }); } function sendEventsToFl(data, staged) { return postToFlEndpoint(data) .then(function (res) { if (!res.ok) { consoleLogger.info('Call to Firebase backend failed.'); } return res.json(); }) .then(function (res) { // Find the next call wait time from the response. var transportWait = Number(res.nextRequestWaitMillis); var requestOffset = DEFAULT_SEND_INTERVAL_MS; if (!isNaN(transportWait)) { requestOffset = Math.max(transportWait, requestOffset); } // Delete request if response include RESPONSE_ACTION_UNKNOWN or DELETE_REQUEST action. // Otherwise, retry request using normal scheduling if response include RETRY_REQUEST_LATER. var logResponseDetails = res.logResponseDetails; if (Array.isArray(logResponseDetails) && logResponseDetails.length > 0 && logResponseDetails[0].responseAction === 'RETRY_REQUEST_LATER') { queue = __spreadArrays(staged, queue); consoleLogger.info("Retry transport request later."); } remainingTries = DEFAULT_REMAINING_TRIES; // Schedule the next process. processQueue(requestOffset); }); } function postToFlEndpoint(data) { var flTransportFullUrl = SettingsService.getInstance().getFlTransportFullUrl(); return fetch(flTransportFullUrl, { method: 'POST', body: JSON.stringify(data) }); } function addToQueue(evt) { if (!evt.eventTime || !evt.message) { throw ERROR_FACTORY$1.create("invalid cc log" /* INVALID_CC_LOG */); } // Add the new event to the queue. queue = __spreadArrays(queue, [evt]); } /** Log handler for cc service to send the performance logs to the server. */ function transportHandler( // eslint-disable-next-line @typescript-eslint/no-explicit-any serializer) { return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var message = serializer.apply(void 0, args); addToQueue({ message: message, eventTime: Date.now() }); }; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-enble camelcase */ var logger; // This method is not called before initialization. function sendLog(resource, resourceType) { if (!logger) { logger = transportHandler(serializer); } logger(resource, resourceType); } function logTrace(trace) { var settingsService = SettingsService.getInstance(); // Do not log if trace is auto generated and instrumentation is disabled. if (!settingsService.instrumentationEnabled && trace.isAuto) { return; } // Do not log if trace is custom and data collection is disabled. if (!settingsService.dataCollectionEnabled && !trace.isAuto) { return; } // Do not log if required apis are not available. if (!Api.getInstance().requiredApisAvailable()) { return; } // Only log the page load auto traces if page is visible. if (trace.isAuto && getVisibilityState() !== VisibilityState.VISIBLE) { return; } if (isPerfInitialized()) { sendTraceLog(trace); } else { // Custom traces can be used before the initialization but logging // should wait until after. getInitializationPromise(trace.performanceController).then(function () { return sendTraceLog(trace); }, function () { return sendTraceLog(trace); }); } } function sendTraceLog(trace) { if (!getIid()) { return; } var settingsService = SettingsService.getInstance(); if (!settingsService.loggingEnabled || !settingsService.logTraceAfterSampling) { return; } setTimeout(function () { return sendLog(trace, 1 /* Trace */); }, 0); } function logNetworkRequest(networkRequest) { var settingsService = SettingsService.getInstance(); // Do not log network requests if instrumentation is disabled. if (!settingsService.instrumentationEnabled) { return; } // Do not log the js sdk's call to transport service domain to avoid unnecessary cycle. // Need to blacklist both old and new endpoints to avoid migration gap. var networkRequestUrl = networkRequest.url; // Blacklist old log endpoint and new transport endpoint. // Because Performance SDK doesn't instrument requests sent from SDK itself. var logEndpointUrl = settingsService.logEndPointUrl.split('?')[0]; var flEndpointUrl = settingsService.flTransportEndpointUrl.split('?')[0]; if (networkRequestUrl === logEndpointUrl || networkRequestUrl === flEndpointUrl) { return; } if (!settingsService.loggingEnabled || !settingsService.logNetworkAfterSampling) { return; } setTimeout(function () { return sendLog(networkRequest, 0 /* NetworkRequest */); }, 0); } function serializer(resource, resourceType) { if (resourceType === 0 /* NetworkRequest */) { return serializeNetworkRequest(resource); } return serializeTrace(resource); } function serializeNetworkRequest(networkRequest) { var networkRequestMetric = { url: networkRequest.url, http_method: networkRequest.httpMethod || 0, http_response_code: 200, response_payload_bytes: networkRequest.responsePayloadBytes, client_start_time_us: networkRequest.startTimeUs, time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs, time_to_response_completed_us: networkRequest.timeToResponseCompletedUs }; var perfMetric = { application_info: getApplicationInfo(networkRequest.performanceController.app), network_request_metric: networkRequestMetric }; return JSON.stringify(perfMetric); } function serializeTrace(trace) { var traceMetric = { name: trace.name, is_auto: trace.isAuto, client_start_time_us: trace.startTimeUs, duration_us: trace.durationUs }; if (Object.keys(trace.counters).length !== 0) { traceMetric.counters = trace.counters; } var customAttributes = trace.getAttributes(); if (Object.keys(customAttributes).length !== 0) { traceMetric.custom_attributes = customAttributes; } var perfMetric = { application_info: getApplicationInfo(trace.performanceController.app), trace_metric: traceMetric }; return JSON.stringify(perfMetric); } function getApplicationInfo(firebaseApp) { return { google_app_id: getAppId(firebaseApp), app_instance_id: getIid(), web_app_info: { sdk_version: SDK_VERSION, page_url: Api.getInstance().getUrl(), service_worker_status: getServiceWorkerStatus(), visibility_state: getVisibilityState(), effective_connection_type: getEffectiveConnectionType() }, application_process_state: 0 }; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var MAX_METRIC_NAME_LENGTH = 100; var RESERVED_AUTO_PREFIX = '_'; var oobMetrics = [ FIRST_PAINT_COUNTER_NAME, FIRST_CONTENTFUL_PAINT_COUNTER_NAME, FIRST_INPUT_DELAY_COUNTER_NAME ]; /** * Returns true if the metric is custom and does not start with reserved prefix, or if * the metric is one of out of the box page load trace metrics. */ function isValidMetricName(name, traceName) { if (name.length === 0 || name.length > MAX_METRIC_NAME_LENGTH) { return false; } return ((traceName && traceName.startsWith(OOB_TRACE_PAGE_LOAD_PREFIX) && oobMetrics.indexOf(name) > -1) || !name.startsWith(RESERVED_AUTO_PREFIX)); } /** * Converts the provided value to an integer value to be used in case of a metric. * @param providedValue Provided number value of the metric that needs to be converted to an integer. * * @returns Converted integer number to be set for the metric. */ function convertMetricValueToInteger(providedValue) { var valueAsInteger = Math.floor(providedValue); if (valueAsInteger < providedValue) { consoleLogger.info("Metric value should be an Integer, setting the value as : " + valueAsInteger + "."); } return valueAsInteger; } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var Trace = /** @class */ (function () { /** * @param performanceController The performance controller running. * @param name The name of the trace. * @param isAuto If the trace is auto-instrumented. * @param traceMeasureName The name of the measure marker in user timing specification. This field * is only set when the trace is built for logging when the user directly uses the user timing * api (performance.mark and performance.measure). */ function Trace(performanceController, name, isAuto, traceMeasureName) { if (isAuto === void 0) { isAuto = false; } this.performanceController = performanceController; this.name = name; this.isAuto = isAuto; this.state = 1 /* UNINITIALIZED */; this.customAttributes = {}; this.counters = {}; this.api = Api.getInstance(); this.randomId = Math.floor(Math.random() * 1000000); if (!this.isAuto) { this.traceStartMark = TRACE_START_MARK_PREFIX + "-" + this.randomId + "-" + this.name; this.traceStopMark = TRACE_STOP_MARK_PREFIX + "-" + this.randomId + "-" + this.name; this.traceMeasure = traceMeasureName || TRACE_MEASURE_PREFIX + "-" + this.randomId + "-" + this.name; if (traceMeasureName) { // For the case of direct user timing traces, no start stop will happen. The measure object // is already available. this.calculateTraceMetrics(); } } } /** * Starts a trace. The measurement of the duration starts at this point. */ Trace.prototype.start = function () { if (this.state !== 1 /* UNINITIALIZED */) { throw ERROR_FACTORY$1.create("trace started" /* TRACE_STARTED_BEFORE */, { traceName: this.name }); } this.api.mark(this.traceStartMark); this.state = 2 /* RUNNING */; }; /** * Stops the trace. The measurement of the duration of the trace stops at this point and trace * is logged. */ Trace.prototype.stop = function () { if (this.state !== 2 /* RUNNING */) { throw ERROR_FACTORY$1.create("trace stopped" /* TRACE_STOPPED_BEFORE */, { traceName: this.name }); } this.state = 3 /* TERMINATED */; this.api.mark(this.traceStopMark); this.api.measure(this.traceMeasure, this.traceStartMark, this.traceStopMark); this.calculateTraceMetrics(); logTrace(this); }; /** * Records a trace with predetermined values. If this method is used a trace is created and logged * directly. No need to use start and stop methods. * @param startTime Trace start time since epoch in millisec * @param duration The duraction of the trace in millisec * @param options An object which can optionally hold maps of custom metrics and custom attributes */ Trace.prototype.record = function (startTime, duration, options) { if (startTime <= 0) { throw ERROR_FACTORY$1.create("nonpositive trace startTime" /* NONPOSITIVE_TRACE_START_TIME */, { traceName: this.name }); } if (duration <= 0) { throw ERROR_FACTORY$1.create("nonpositive trace duration" /* NONPOSITIVE_TRACE_DURATION */, { traceName: this.name }); } this.durationUs = Math.floor(duration * 1000); this.startTimeUs = Math.floor(startTime * 1000); if (options && options.attributes) { this.customAttributes = __assign({}, options.attributes); } if (options && options.metrics) { for (var _i = 0, _a = Object.keys(options.metrics); _i < _a.length; _i++) { var metric = _a[_i]; if (!isNaN(Number(options.metrics[metric]))) { this.counters[metric] = Number(Math.floor(options.metrics[metric])); } } } logTrace(this); }; /** * Increments a custom metric by a certain number or 1 if number not specified. Will create a new * custom metric if one with the given name does not exist. The value will be floored down to an * integer. * @param counter Name of the custom metric * @param numAsInteger Increment by value */ Trace.prototype.incrementMetric = function (counter, numAsInteger) { if (numAsInteger === void 0) { numAsInteger = 1; } if (this.counters[counter] === undefined) { this.putMetric(counter, numAsInteger); } else { this.putMetric(counter, this.counters[counter] + numAsInteger); } }; /** * Sets a custom metric to a specified value. Will create a new custom metric if one with the * given name does not exist. The value will be floored down to an integer. * @param counter Name of the custom metric * @param numAsInteger Set custom metric to this value */ Trace.prototype.putMetric = function (counter, numAsInteger) { if (isValidMetricName(counter, this.name)) { this.counters[counter] = convertMetricValueToInteger(numAsInteger); } else { throw ERROR_FACTORY$1.create("invalid custom metric name" /* INVALID_CUSTOM_METRIC_NAME */, { customMetricName: counter }); } }; /** * Returns the value of the custom metric by that name. If a custom metric with that name does * not exist will return zero. * @param counter */ Trace.prototype.getMetric = function (counter) { return this.counters[counter] || 0; }; /** * Sets a custom attribute of a trace to a certain value. * @param attr * @param value */ Trace.prototype.putAttribute = function (attr, value) { var isValidName = isValidCustomAttributeName(attr); var isValidValue = isValidCustomAttributeValue(value); if (isValidName && isValidValue) { this.customAttributes[attr] = value; return; } // Throw appropriate error when the attribute name or value is invalid. if (!isValidName) { throw ERROR_FACTORY$1.create("invalid attribute name" /* INVALID_ATTRIBUTE_NAME */, { attributeName: attr }); } if (!isValidValue) { throw ERROR_FACTORY$1.create("invalid attribute value" /* INVALID_ATTRIBUTE_VALUE */, { attributeValue: value }); } }; /** * Retrieves the value a custom attribute of a trace is set to. * @param attr */ Trace.prototype.getAttribute = function (attr) { return this.customAttributes[attr]; }; Trace.prototype.removeAttribute = function (attr) { if (this.customAttributes[attr] === undefined) { return; } delete this.customAttributes[attr]; }; Trace.prototype.getAttributes = function () { return __assign({}, this.customAttributes); }; Trace.prototype.setStartTime = function (startTime) { this.startTimeUs = startTime; }; Trace.prototype.setDuration = function (duration) { this.durationUs = duration; }; /** * Calculates and assigns the duration and start time of the trace using the measure performance * entry. */ Trace.prototype.calculateTraceMetrics = function () { var perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure); var perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0]; if (perfMeasureEntry) { this.durationUs = Math.floor(perfMeasureEntry.duration * 1000); this.startTimeUs = Math.floor((perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000); } }; /** * @param navigationTimings A single element array which contains the navigationTIming object of * the page load * @param paintTimings A array which contains paintTiming object of the page load * @param firstInputDelay First input delay in millisec */ Trace.createOobTrace = function (performanceController, navigationTimings, paintTimings, firstInputDelay) { var route = Api.getInstance().getUrl(); if (!route) { return; } var trace = new Trace(performanceController, OOB_TRACE_PAGE_LOAD_PREFIX + route, true); var timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000); trace.setStartTime(timeOriginUs); // navigationTimings includes only one element. if (navigationTimings && navigationTimings[0]) { trace.setDuration(Math.floor(navigationTimings[0].duration * 1000)); trace.putMetric('domInteractive', Math.floor(navigationTimings[0].domInteractive * 1000)); trace.putMetric('domContentLoadedEventEnd', Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000)); trace.putMetric('loadEventEnd', Math.floor(navigationTimings[0].loadEventEnd * 1000)); } var FIRST_PAINT = 'first-paint'; var FIRST_CONTENTFUL_PAINT = 'first-contentful-paint'; if (paintTimings) { var firstPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_PAINT; }); if (firstPaint && firstPaint.startTime) { trace.putMetric(FIRST_PAINT_COUNTER_NAME, Math.floor(firstPaint.startTime * 1000)); } var firstContentfulPaint = paintTimings.find(function (paintObject) { return paintObject.name === FIRST_CONTENTFUL_PAINT; }); if (firstContentfulPaint && firstContentfulPaint.startTime) { trace.putMetric(FIRST_CONTENTFUL_PAINT_COUNTER_NAME, Math.floor(firstContentfulPaint.startTime * 1000)); } if (firstInputDelay) { trace.putMetric(FIRST_INPUT_DELAY_COUNTER_NAME, Math.floor(firstInputDelay * 1000)); } } logTrace(trace); }; Trace.createUserTimingTrace = function (performanceController, measureName) { var trace = new Trace(performanceController, measureName, false, measureName); logTrace(trace); }; return Trace; }()); /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ function createNetworkRequestEntry(performanceController, entry) { var performanceEntry = entry; if (!performanceEntry || performanceEntry.responseStart === undefined) { return; } var timeOrigin = Api.getInstance().getTimeOrigin(); var startTimeUs = Math.floor((performanceEntry.startTime + timeOrigin) * 1000); var timeToResponseInitiatedUs = performanceEntry.responseStart ? Math.floor((performanceEntry.responseStart - performanceEntry.startTime) * 1000) : undefined; var timeToResponseCompletedUs = Math.floor((performanceEntry.responseEnd - performanceEntry.startTime) * 1000); // Remove the query params from logged network request url. var url = performanceEntry.name && performanceEntry.name.split('?')[0]; var networkRequest = { performanceController: performanceController, url: url, responsePayloadBytes: performanceEntry.transferSize, startTimeUs: startTimeUs, timeToResponseInitiatedUs: timeToResponseInitiatedUs, timeToResponseCompletedUs: timeToResponseCompletedUs }; logNetworkRequest(networkRequest); } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var FID_WAIT_TIME_MS = 5000; function setupOobResources(performanceController) { // Do not initialize unless iid is available. if (!getIid()) { return; } // The load event might not have fired yet, and that means performance navigation timing // object has a duration of 0. The setup should run after all current tasks in js queue. setTimeout(function () { return setupOobTraces(performanceController); }, 0); setTimeout(function () { return setupNetworkRequests(performanceController); }, 0); setTimeout(function () { return setupUserTimingTraces(performanceController); }, 0); } function setupNetworkRequests(performanceController) { var api = Api.getInstance(); var resources = api.getEntriesByType('resource'); for (var _i = 0, resources_1 = resources; _i < resources_1.length; _i++) { var resource = resources_1[_i]; createNetworkRequestEntry(performanceController, resource); } api.setupObserver('resource', function (entry) { return createNetworkRequestEntry(performanceController, entry); }); } function setupOobTraces(performanceController) { var api = Api.getInstance(); var navigationTimings = api.getEntriesByType('navigation'); var paintTimings = api.getEntriesByType('paint'); // If First Input Desly polyfill is added to the page, report the fid value. // https://github.com/GoogleChromeLabs/first-input-delay if (api.onFirstInputDelay) { // If the fid call back is not called for certain time, continue without it. // eslint-disable-next-line @typescript-eslint/no-explicit-any var timeoutId_1 = setTimeout(function () { Trace.createOobTrace(performanceController, navigationTimings, paintTimings); timeoutId_1 = undefined; }, FID_WAIT_TIME_MS); api.onFirstInputDelay(function (fid) { if (timeoutId_1) { clearTimeout(timeoutId_1); Trace.createOobTrace(performanceController, navigationTimings, paintTimings, fid); } }); } else { Trace.createOobTrace(performanceController, navigationTimings, paintTimings); } } function setupUserTimingTraces(performanceController) { var api = Api.getInstance(); // Run through the measure performance entries collected up to this point. var measures = api.getEntriesByType('measure'); for (var _i = 0, measures_1 = measures; _i < measures_1.length; _i++) { var measure = measures_1[_i]; createUserTimingTrace(performanceController, measure); } // Setup an observer to capture the measures from this point on. api.setupObserver('measure', function (entry) { return createUserTimingTrace(performanceController, entry); }); } function createUserTimingTrace(performanceController, measure) { var measureName = measure.name; // Do not create a trace, if the user timing marks and measures are created by the sdk itself. if (measureName.substring(0, TRACE_MEASURE_PREFIX.length) === TRACE_MEASURE_PREFIX) { return; } Trace.createUserTimingTrace(performanceController, measureName); } /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var PerformanceController = /** @class */ (function () { function PerformanceController(app, installations) { this.app = app; this.installations = installations; this.initialized = false; } /** * This method *must* be called internally as part of creating a * PerformanceController instance. * * Currently it's not possible to pass the settings object through the * constructor using Components, so this method exists to be called with the * desired settings, to ensure nothing is collected without the user's * consent. */ PerformanceController.prototype._init = function (settings) { var _this = this; if (this.initialized) { return; } if ((settings === null || settings === void 0 ? void 0 : settings.dataCollectionEnabled) !== undefined) { this.dataCollectionEnabled = settings.dataCollectionEnabled; } if ((settings === null || settings === void 0 ? void 0 : settings.instrumentationEnabled) !== undefined) { this.instrumentationEnabled = settings.instrumentationEnabled; } if (Api.getInstance().requiredApisAvailable()) { validateIndexedDBOpenable() .then(function (isAvailable) { if (isAvailable) { setupTransportService(); getInitializationPromise(_this).then(function () { return setupOobResources(_this); }, function () { return setupOobResources(_this); }); _this.initialized = true; } }) .catch(function (error) { consoleLogger.info("Environment doesn't support IndexedDB: " + error); }); } else { consoleLogger.info('Firebase Performance cannot start if the browser does not support ' + '"Fetch" and "Promise", or cookies are disabled.'); } }; Object.defineProperty(PerformanceController.prototype, "instrumentationEnabled", { get: function () { return SettingsService.getInstance().instrumentationEnabled; }, set: function (val) { SettingsService.getInstance().instrumentationEnabled = val; }, enumerable: false, configurable: true }); Object.defineProperty(PerformanceController.prototype, "dataCollectionEnabled", { get: function () { return SettingsService.getInstance().dataCollectionEnabled; }, set: function (val) { SettingsService.getInstance().dataCollectionEnabled = val; }, enumerable: false, configurable: true }); return PerformanceController; }()); /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var DEFAULT_ENTRY_NAME = '[DEFAULT]'; /** * Returns a FirebasePerformance instance for the given app. * @param app - The FirebaseApp to use. * @param settings - Optional settings for the Performance instance. * @public */ function getPerformance(app, settings) { var provider = firebase._getProvider(app, 'performance-exp'); var perfInstance = provider.getImmediate(); perfInstance._init(settings); return perfInstance; } /** * Returns a new PerformanceTrace instance. * @param performance - The FirebasePerformance instance to use. * @param name - The name of the trace. * @public */ function trace(performance, name) { return new Trace(performance, name); } var factory = function (container) { // Dependencies var app = container.getProvider('app-exp').getImmediate(); var installations = container .getProvider('installations-exp-internal') .getImmediate(); if (app.name !== DEFAULT_ENTRY_NAME) { throw ERROR_FACTORY$1.create("FB not default" /* FB_NOT_DEFAULT */); } if (typeof window === 'undefined') { throw ERROR_FACTORY$1.create("no window" /* NO_WINDOW */); } setupApi(window); return new PerformanceController(app, installations); }; function registerPerformance() { firebase._registerComponent(new Component('performance-exp', factory, "PUBLIC" /* PUBLIC */)); } registerPerformance(); firebase.registerVersion(name$1, version$1); exports.getPerformance = getPerformance; exports.trace = trace; Object.defineProperty(exports, '__esModule', { value: true }); }).apply(this, arguments); } catch(err) { console.error(err); throw new Error( 'Cannot instantiate firebase-performance.js - ' + 'be sure to load firebase-app.js first.' ); } }))); //# sourceMappingURL=firebase-performance.js.map
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'div', 'et', { IdInputLabel: 'ID', advisoryTitleInputLabel: 'Soovitatav pealkiri', cssClassInputLabel: 'Stiililehe klassid', edit: 'Muuda Div', inlineStyleInputLabel: 'Reasisene stiil', langDirLTRLabel: 'Vasakult paremale (LTR)', langDirLabel: 'Keele suund', langDirRTLLabel: 'Paremalt vasakule (RTL)', languageCodeInputLabel: ' Keelekood', remove: 'Eemalda Div', styleSelectLabel: 'Stiil', title: 'Div-konteineri loomine', toolbar: 'Div-konteineri loomine' } );
//TODO CLI: pass target language //TODO compile only newer files ///TODO phantom.exit(code) does not return code value ///TODO phantom.injectJs or require?? require('./cli_setup.js'); CLI.retrieveOptions(); require('./dependencies.js'); //TODO quick and dirty workaround a 'Realtime' concept added since last sync w/ repository (next 2 lines) Blockly.Realtime = {}; Blockly.Realtime.isEnabled = function() { return false; }; window.BLOCKLY_BOOT(); Blockly.Xml.domToWorkspace = function(workspace, xml) { for (var x = 0, xmlChild; xmlChild = xml.childNodes[x]; x++) { if (xmlChild.nodeName.toLowerCase() == 'block') { Blockly.Xml.domToBlock(workspace, xmlChild); } } }; Blockly.mainWorkspace = new Blockly.Workspace(false); Blockly.mainWorkspace.createDom(); CLI.inputFiles.forEach(function (file) { var xmlDoc; var xmlText = fs.read(file); var outputFile = CLI.outputFile(file); try { xmlDoc = Blockly.Xml.textToDom(xmlText); } catch (e) { console.error('Error parsing XML:\n' + e); phantom.exit(3); } try { Blockly.mainWorkspace.clear(); Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xmlDoc); var code = Blockly.Ruby.workspaceToCode(); if (CLI.verbose) { console.info("Wrote " + CLI.outputFile(file)); } fs.write(CLI.outputFile(file), code, 'w'); } catch (e) { console.error('Errors:\n' + e); phantom.exit(3); } }); phantom.exit();
/*! * Searchable Map Template with Google Fusion Tables * http://derekeder.com/searchable_map_template/ * * Copyright 2012, Derek Eder * Licensed under the MIT license. * https://github.com/derekeder/FusionTable-Map-Template/wiki/License * * Date: 12/10/2012 * */ // Enable the visual refresh google.maps.visualRefresh = true; var MapsLib = MapsLib || {}; var MapsLib = { //Setup section - put your Fusion Table details here //Using the v1 Fusion Tables API. See https://developers.google.com/fusiontables/docs/v1/migration_guide for more info //the encrypted Table ID of your Fusion Table (found under File => About) //NOTE: numeric IDs will be depricated soon fusionTableId: "1bsNj6llGWWr7rGYmjAF5aEfLp8__9RtHqegTjxU", //*New Fusion Tables Requirement* API key. found at https://code.google.com/apis/console/ //*Important* this key is for demonstration purposes. please register your own. googleApiKey: "AIzaSyD_JUx-4hkNn5bqllP4OyninnBp-YtOPbg", //name of the location column in your Fusion Table. //NOTE: if your location column name has spaces in it, surround it with single quotes //example: locationColumn: "'my location'", locationColumn: "Location", map_centroid: new google.maps.LatLng(39.8282, -98.5795), //center that your map defaults to locationScope: "United States", //geographical area appended to all address searches recordName: "result", //for showing number of results recordNamePlural: "results", searchRadius: 805, //in meters ~ 1/2 mile defaultZoom: 4, //zoom level when map is loaded (bigger is more zoomed in) addrMarkerImage: 'http://derekeder.com/images/icons/blue-pushpin.png', currentPinpoint: null, initialize: function() { $( "#result_count" ).html(""); geocoder = new google.maps.Geocoder(); var myOptions = { zoom: MapsLib.defaultZoom, center: MapsLib.map_centroid, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map($("#map_canvas")[0],myOptions); // maintains map centerpoint for responsive design google.maps.event.addDomListener(map, 'idle', function() { MapsLib.calculateCenter(); }); google.maps.event.addDomListener(window, 'resize', function() { map.setCenter(MapsLib.map_centroid); }); MapsLib.searchrecords = null; //reset filters $("#search_address").val(MapsLib.convertToPlainString($.address.parameter('address'))); var loadRadius = MapsLib.convertToPlainString($.address.parameter('radius')); if (loadRadius != "") $("#search_radius").val(loadRadius); else $("#search_radius").val(MapsLib.searchRadius); $(":checkbox").attr("checked", "checked"); $("#result_count").hide(); //-----custom initializers------- //-----end of custom initializers------- //run the default search MapsLib.doSearch(); }, doSearch: function(location) { MapsLib.clearSearch(); var address = $("#search_address").val(); MapsLib.searchRadius = $("#search_radius").val(); var whereClause = MapsLib.locationColumn + " not equal to ''"; //-----custom filters------- //-------end of custom filters-------- if (address != "") { if (address.toLowerCase().indexOf(MapsLib.locationScope) == -1) address = address + " " + MapsLib.locationScope; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { MapsLib.currentPinpoint = results[0].geometry.location; $.address.parameter('address', encodeURIComponent(address)); $.address.parameter('radius', encodeURIComponent(MapsLib.searchRadius)); map.setCenter(MapsLib.currentPinpoint); map.setZoom(14); MapsLib.addrMarker = new google.maps.Marker({ position: MapsLib.currentPinpoint, map: map, icon: MapsLib.addrMarkerImage, animation: google.maps.Animation.DROP, title:address }); whereClause += " AND ST_INTERSECTS(" + MapsLib.locationColumn + ", CIRCLE(LATLNG" + MapsLib.currentPinpoint.toString() + "," + MapsLib.searchRadius + "))"; MapsLib.drawSearchRadiusCircle(MapsLib.currentPinpoint); MapsLib.submitSearch(whereClause, map, MapsLib.currentPinpoint); } else { alert("We could not find your address: " + status); } }); } else { //search without geocoding callback MapsLib.submitSearch(whereClause, map); } }, submitSearch: function(whereClause, map, location) { //get using all filters //NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows //you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables //for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles MapsLib.searchrecords = new google.maps.FusionTablesLayer({ query: { from: MapsLib.fusionTableId, select: MapsLib.locationColumn, where: whereClause }, styleId: 2, templateId: 2 }); MapsLib.searchrecords.setMap(map); MapsLib.getCount(whereClause); }, clearSearch: function() { if (MapsLib.searchrecords != null) MapsLib.searchrecords.setMap(null); if (MapsLib.addrMarker != null) MapsLib.addrMarker.setMap(null); if (MapsLib.searchRadiusCircle != null) MapsLib.searchRadiusCircle.setMap(null); }, findMe: function() { // Try W3C Geolocation (Preferred) var foundLocation; if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { foundLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); MapsLib.addrFromLatLng(foundLocation); }, null); } else { alert("Sorry, we could not find your location."); } }, addrFromLatLng: function(latLngPoint) { geocoder.geocode({'latLng': latLngPoint}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { $('#search_address').val(results[1].formatted_address); $('.hint').focus(); MapsLib.doSearch(); } } else { alert("Geocoder failed due to: " + status); } }); }, drawSearchRadiusCircle: function(point) { var circleOptions = { strokeColor: "#4b58a6", strokeOpacity: 0.3, strokeWeight: 1, fillColor: "#4b58a6", fillOpacity: 0.05, map: map, center: point, clickable: false, zIndex: -1, radius: parseInt(MapsLib.searchRadius) }; MapsLib.searchRadiusCircle = new google.maps.Circle(circleOptions); }, query: function(selectColumns, whereClause, callback) { var queryStr = []; queryStr.push("SELECT " + selectColumns); queryStr.push(" FROM " + MapsLib.fusionTableId); queryStr.push(" WHERE " + whereClause); var sql = encodeURIComponent(queryStr.join(" ")); $.ajax({url: "https://www.googleapis.com/fusiontables/v1/query?sql="+sql+"&callback="+callback+"&key="+MapsLib.googleApiKey, dataType: "jsonp"}); }, handleError: function(json) { if (json["error"] != undefined) { var error = json["error"]["errors"] console.log("Error in Fusion Table call!"); for (var row in error) { console.log(" Domain: " + error[row]["domain"]); console.log(" Reason: " + error[row]["reason"]); console.log(" Message: " + error[row]["message"]); } } }, getCount: function(whereClause) { var selectColumns = "Count()"; MapsLib.query(selectColumns, whereClause,"MapsLib.displaySearchCount"); }, displaySearchCount: function(json) { MapsLib.handleError(json); var numRows = 0; if (json["rows"] != null) numRows = json["rows"][0]; var name = MapsLib.recordNamePlural; if (numRows == 1) name = MapsLib.recordName; $( "#result_count" ).fadeOut(function() { $( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " found"); }); $( "#result_count" ).fadeIn(); }, addCommas: function(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; }, // maintains map centerpoint for responsive design calculateCenter: function() { center = map.getCenter(); }, //converts a slug or query string in to readable text convertToPlainString: function(text) { if (text == undefined) return ''; return decodeURIComponent(text); } //-----custom functions------- // NOTE: if you add custom functions, make sure to append each one with a comma, except for the last one. // This also applies to the convertToPlainString function above //-----end of custom functions------- }
var bearcat = require('../../../lib/bearcat'); var Bus = function() { bearcat.call("car", this, 100); this.$id = "bus"; this.num1 = 12; } bearcat.extend("bus", ["car"]); // bearcat.extend("bus", ["car", "tank"]); Bus.prototype.run = function() { this._super(); console.log("bus run %d ...", this.num1); } module.exports = Bus;
import _ from 'lodash' const DAMAGE_DICE = ['d4', 'd6', 'd8', 'd10', 'd12'] export default class MonsterFactory { constructor(answers) { this.answers = answers this.monster = new Monster({ called: this.answers.called, moves: [this.answers.known_to_do], instinct: this.answers.instinct }) } make() { this.calculateFightMethodEffects() this.calculateSizeEffects() this.calculateDefenseEffects() this.calculateKnownForEffects() this.calculateCommonAttackEffects() this.calculateDescriptionEffects() return this.monster } calculateFightMethodEffects() { switch (this.answers.hunt_or_fight) { case 'In large groups': this.monster.tags.organization.push('horde') this.monster.damage_die = 'd6' this.monster.hp = 3 break case 'In small groups, about 2-5': this.monster.tags.organization.push('group') this.monster.damage_die = 'd8' this.monster.hp = 6 break case 'All by its lonesome': this.monster.tags.organization.push('solitary') this.monster.damage_die = 'd10' this.monster.hp = 12 break } } calculateSizeEffects() { switch (this.answers.size) { case 'Smaller than a house cat': this.monster.tags.size.push('tiny') this.monster.tags.attack.push('hand') this.monster.damage_modifier = -2 break case 'Halfling-esque': this.monster.tags.size.push('small') this.monster.tags.attack.push('close') break case 'About human size': this.monster.tags.attack.push('close') break case 'As big as a cart': this.monster.tags.size.push('large') this.monster.tags.attack.push('close') this.monster.tags.attack.push('reach') this.monster.damage_modifier = 1 this.monster.hp += 4 break case 'Much larger than a cart': this.monster.tags.size.push('huge') this.monster.tags.attack.push('reach') this.monster.damage_modifier = 3 this.monster.hp += 8 break } } calculateDefenseEffects() { switch (this.answers.defense) { case 'Cloth or flesh': // 0 armor break case 'Leathers or thick hide': this.monster.armor = 1 break case 'Mail or scales': this.monster.armor = 2 break case 'Plate or bone': this.monster.armor = 3 break case 'Permanent magical protection': this.monster.tags.basic.push('magical') this.monster.armor = 4 break } } calculateKnownForEffects() { if (this.answers.unrelenting_strength) { this.monster.tags.attack.push('forceful') this.monster.damage_modifier += 2 } if (this.answers.skill_in_offense) { this.monster.roll_twice_take = 'best' } if (this.answers.skill_in_defense) { this.monster.armor += 1 } if (this.answers.deft_strikes) { this.monster.piercing = 1 } if (this.answers.uncanny_endurance) { this.monster.hp += 4 } if (this.answers.deceit_and_trickery) { this.monster.tags.basic.push('stealthy') this.monster.moves.push('Write a move about dirty tricks') } if (this.answers.useful_adaptaton) { this.monster.special_qualities.push('Write a special quality for the adaptation') } if (this.answers.favor_of_gods_lethal) { this.monster.tags.basic.push('divine') this.monster.damage_modifier += 2 } if (this.answers.favor_of_gods_durable) { this.monster.tags.basic.push('divine') this.monster.hp += 2 } if (this.answers.spells_and_magic) { this.monster.tags.basic.push('magical') this.monster.moves.push('Write a move about its spells') } } calculateCommonAttackEffects() { this.monster.attack = this.answers.common_form_of_attack if (this.answers.armaments_vicious_and_obvious) { this.monster.damage_modifier += 2 } if (this.answers.keeps_others_at_bay) { this.monster.tags.attack.push('reach') } if (this.answers.armaments_are_small_and_weak) { this.decreaseDamageDie() } if (this.answers.armaments_can_slice_pierce_metal) { this.monster.tags.attack.push('messy') this.monster.piercing += 1 } if (this.answers.armaments_can_tear_metal_apart) { this.monster.piercing += 3 } if (this.answers.armor_wont_help) { this.monster.tags.attack.push('ignores armor') } if (this.answers.attacks_at_range_near) { this.monster.tags.attack.push('near') } if (this.answers.attacks_at_range_far) { this.monster.tags.attack.push('far') } } calculateDescriptionEffects() { if (this.answers.dangerous_other_reasons) { this.monster.tags.basic.push('devious') this.decreaseDamageDie() this.monster.moves.push('Write a move about why its dangerous') } if (this.answers.larger_group_support) { this.monster.tags.basic.push('organized') this.monster.moves.push('Write a move about calling on others for help') } if (this.answers.smart_as_human) { this.monster.tags.basic.push('intelligent') } if (this.answers.actively_defends) { this.monster.tags.basic.push('cautious') this.monster.armor += 1 } if (this.answers.collects_trinkets) { this.monster.tags.basic.push('hoarder') } if (this.answers.beyond_this_world) { this.monster.tags.basic.push('planar') this.monster.moves.push('Write a move about using its otherworldly knowledge and power') } if (this.answers.alive_beyond_biology) { this.monster.hp += 4 } if (this.answers.made_by_someone) { this.monster.tags.basic.push('construct') this.monster.special_qualities.push('Give it a special quality or two about its construction or purpose') } if (this.answers.disturbing) { this.monster.tags.basic.push('terrifying') this.monster.special_qualities.push("Write a special quality about why it's so horrendous") } if (this.answers.no_organs) { this.monster.tags.basic.push('amorphous') this.monster.hp += 3 this.monster.armor += 1 } if (this.answers.ancient) { this.increaseDamageDie() } if (this.answers.abhors_violence) { this.monster.roll_twice_take = 'worst' } } decreaseDamageDie() { let index = DAMAGE_DICE.indexOf(this.monster.damage_die) this.monster.damage_die = DAMAGE_DICE[index-1] } increaseDamageDie() { let index = DAMAGE_DICE.indexOf(this.monster.damage_die) this.monster.damage_die = DAMAGE_DICE[index+1] } } class Monster { constructor(attributes = {}) { this.damage_die = 'd6' this.damage_modifier = 0 this.piercing = 0 this.hp = 0 this.armor = 0 this.tags = { attack: [], basic: [], organization: [], size: [] } this.moves = [] this.special_qualities = [] _.each(attributes, (value, property) => { this[property] = value }) } }
"use strict"; var stamp = require('..'); var VV = stamp.VV; var AnchoredVV = stamp.AnchoredVV; var tape = require('tap').test; tape ('stamp.02.A VV basics', function (tap) { var vec = '!7AM0f+gritzko!0longago+krdkv!7AMTc+aleksisha!some+garbage'; var vv = new VV(vec); tap.ok(vv.covers('7AM0f+gritzko')); tap.ok(!vv.covers('7AMTd+aleksisha')); tap.ok(!vv.covers('6AMTd+maxmaxmax')); tap.equal(vv.toString(), '!some+garbage!7AMTc+aleksisha!7AM0f+gritzko!0longago+krdkv'); var map2 = new VV("!1QDpv03+anon000qO!1P7AE05+anon000Bu"); tap.equal(map2.covers('1P7AE05+anon000Bu'), true, 'covers the border'); var one = new VV('!1+one!2+two!0+three'); var two = new VV('!0+two'); var three = '!3+three'; var add = one.addAll(two).addAll(three); tap.equal(add.toString(), '!3+three!2+two!1+one'); tap.end(); }); tape ('stamp.02.B basic anchored syntax', function (tap) { var an1 = new AnchoredVV( 'time0+sourceA!time2+sourceB!time3+sourceC!time4+sourceC' ); tap.equal(an1.anchor, 'time0+sourceA'); tap.equal(an1.vv.get('sourceB'), 'time2+sourceB'); tap.equal(an1.vv.get('something+sourceC'), 'time4+sourceC'); tap.equal(an1.vv.has('sourceC'), true); tap.equal(an1.vv.has('sourceB'), true); tap.equal(an1.vv.has('sourceA'), false); tap.equal(an1.toString(), 'time0+sourceA!time4+sourceC!time2+sourceB'); tap.end(); }); tape ('stamp.02.C zero vector', function (tap) { var empty = new VV(); tap.equal(empty.toString(), '!0', 'empty vector is !0'); tap.ok(empty.covers('0'), '!0 covers 0'); tap.ok(!empty.covers('1+a'), '!0 covers nothing'); var empty2 = new VV('!0'); tap.equal(empty2.toString(), '!0'); var empty3 = new VV('!a+b!c+d'); empty3 = empty3.remove('b').remove('c+d'); tap.equal(empty3.toString(), '!0'); tap.end(); }); tape ('stamp.02.D mutations', function (tap) { var an = new AnchoredVV(); tap.equal(an.toString(), '0'); an.setAnchor('time1+srcA'); an.addTip('time0+srcA'); tap.equal(an.toString(), 'time1+srcA!time0+srcA', 'anchor eats'); // TODO anchor eats!!!! an.addTip('time4+srcB'); an.addTip('time3+srcB'); tap.equal(an.toString(), 'time1+srcA!time4+srcB!time0+srcA', 'vv grows'); tap.equal(an.getTip('srcB'), 'time4+srcB', 'get tip entries'); tap.equal(an.getTip('srcC'), '0'); tap.equal(an.vv.covers('time4+srcB'), true, 'covers()'); tap.equal(an.vv.covers('time+srcA'), true); tap.equal(an.vv.covers('time2+srcA'), false); tap.equal(an.vv.covers('time5+srcB'), false); an.addTip('time1+srcA'); tap.equal(an.toString(), 'time1+srcA!time4+srcB!time1+srcA', 'eats again'); // FIXME eats an.setAnchor('time5+srcC'); tap.equal(an.toString(), 'time5+srcC!time4+srcB!time1+srcA'); an.removeTip('srcB'); tap.equal(an.toString(), 'time5+srcC!time1+srcA'); tap.end(); });
/** * Created by Administrator on 2016/6/16. */ (function () { 'use strict'; angular .module('sysApp.user.list') .controller('userListController', userListController); userListController.$inject = ['$scope', 'userService', '$log', '$state']; function userListController($scope, UserService, $log, $state) { $log.debug("用户列表加载"); /** * ========== 初始化 ========== */ var vm = $scope.vm = {}; vm.title = "用户列表"; vm.add = function () { $state.go('user.add'); }; vm.edit = function (id) { $state.go('user.edit', { id: id }); }; } })();
// To set up environmental variables, see http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const Twilio = require('twilio').Twilio; const client = new Twilio(accountSid, authToken); client.chat .credentials('CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') .remove() .then(response => { console.log(response); }) .catch(error => { console.log(error); });
const TEXT_NODE = 3; const ELEMENT_NODE = 1; import { DEFAULT_TAG_NAME, VALID_MARKUP_SECTION_TAGNAMES } from 'content-kit-editor/models/markup-section'; import { VALID_MARKUP_TAGNAMES } from 'content-kit-editor/models/markup'; import { getAttributes, normalizeTagName } from 'content-kit-editor/utils/dom-utils'; import { forEach } from 'content-kit-editor/utils/array-utils'; /** * parses an element into a section, ignoring any non-markup * elements contained within * @return {Section} */ export default class SectionParser { constructor(builder) { this.builder = builder; } parse(element) { const tagName = this.sectionTagNameFromElement(element); const section = this.builder.createMarkupSection(tagName); const state = {section, markups:[], text:''}; forEach(element.childNodes, (el) => { this.parseNode(el, state); }); // close a trailing text nodes if it exists if (state.text.length) { let marker = this.builder.createMarker(state.text, state.markups); state.section.markers.append(marker); } if (section.markers.length === 0) { section.markers.append(this.builder.createBlankMarker()); } return section; } parseNode(node, state) { switch (node.nodeType) { case TEXT_NODE: this.parseTextNode(node, state); break; case ELEMENT_NODE: this.parseElementNode(node, state); break; default: throw new Error(`parseNode got unexpected element type ${node.nodeType} ` + node); } } parseElementNode(element, state) { const markup = this.markupFromElement(element); if (markup) { if (state.text.length) { // close previous text marker let marker = this.builder.createMarker(state.text, state.markups); state.section.markers.append(marker); state.text = ''; } state.markups.push(markup); } forEach(element.childNodes, (node) => { this.parseNode(node, state); }); if (markup) { // close the marker started for this node and pop // its markup from the stack let marker = this.builder.createMarker(state.text, state.markups); state.section.markers.append(marker); state.markups.pop(); state.text = ''; } } parseTextNode(textNode, state) { state.text += textNode.textContent; } isSectionElement(element) { return element.nodeType === ELEMENT_NODE && VALID_MARKUP_SECTION_TAGNAMES.indexOf(normalizeTagName(element.tagName)) !== -1; } markupFromElement(element) { const tagName = normalizeTagName(element.tagName); if (VALID_MARKUP_TAGNAMES.indexOf(tagName) === -1) { return null; } return this.builder.createMarkup(tagName, getAttributes(element)); } sectionTagNameFromElement(element) { let tagName = element.tagName; tagName = tagName && normalizeTagName(tagName); if (VALID_MARKUP_SECTION_TAGNAMES.indexOf(tagName) === -1) { tagName = DEFAULT_TAG_NAME; } return tagName; } }
// flow-typed signature: c5fac64666f9589a0c1b2de956dc7919 // flow-typed version: 81d6274128/react-redux_v5.x.x/flow_>=v0.53.x // flow-typed signature: 8db7b853f57c51094bf0ab8b2650fd9c // flow-typed version: ab8db5f14d/react-redux_v5.x.x/flow_>=v0.30.x import type { Dispatch, Store } from "redux"; declare module "react-redux" { /* S = State A = Action OP = OwnProps SP = StateProps DP = DispatchProps */ declare type MapStateToProps<S, OP: Object, SP: Object> = ( state: S, ownProps: OP ) => SP | MapStateToProps<S, OP, SP>; declare type MapDispatchToProps<A, OP: Object, DP: Object> = | ((dispatch: Dispatch<A>, ownProps: OP) => DP) | DP; declare type MergeProps<SP, DP: Object, OP: Object, P: Object> = ( stateProps: SP, dispatchProps: DP, ownProps: OP ) => P; declare type Context = { store: Store<*, *> }; declare class ConnectedComponent<OP, P> extends React$Component<OP> { static WrappedComponent: Class<React$Component<P>>, getWrappedInstance(): React$Component<P>, props: OP, state: void } declare type ConnectedComponentClass<OP, P> = Class< ConnectedComponent<OP, P> >; declare type Connector<OP, P> = ( component: React$ComponentType<P> ) => ConnectedComponentClass<OP, P>; declare class Provider<S, A> extends React$Component<{ store: Store<S, A>, children?: any }> {} declare function createProvider( storeKey?: string, subKey?: string ): Provider<*, *>; declare type ConnectOptions = { pure?: boolean, withRef?: boolean }; declare type Null = null | void; declare function connect<A, OP>( ...rest: Array<void> // <= workaround for https://github.com/facebook/flow/issues/2360 ): Connector<OP, $Supertype<{ dispatch: Dispatch<A> } & OP>>; declare function connect<A, OP>( mapStateToProps: Null, mapDispatchToProps: Null, mergeProps: Null, options: ConnectOptions ): Connector<OP, $Supertype<{ dispatch: Dispatch<A> } & OP>>; declare function connect<S, A, OP, SP>( mapStateToProps: MapStateToProps<S, OP, SP>, mapDispatchToProps: Null, mergeProps: Null, options?: ConnectOptions ): Connector<OP, $Supertype<SP & { dispatch: Dispatch<A> } & OP>>; declare function connect<A, OP, DP>( mapStateToProps: Null, mapDispatchToProps: MapDispatchToProps<A, OP, DP>, mergeProps: Null, options?: ConnectOptions ): Connector<OP, $Supertype<DP & OP>>; declare function connect<S, A, OP, SP, DP>( mapStateToProps: MapStateToProps<S, OP, SP>, mapDispatchToProps: MapDispatchToProps<A, OP, DP>, mergeProps: Null, options?: ConnectOptions ): Connector<OP, $Supertype<SP & DP & OP>>; declare function connect<S, A, OP, SP, DP, P>( mapStateToProps: MapStateToProps<S, OP, SP>, mapDispatchToProps: Null, mergeProps: MergeProps<SP, DP, OP, P>, options?: ConnectOptions ): Connector<OP, P>; declare function connect<S, A, OP, SP, DP, P>( mapStateToProps: MapStateToProps<S, OP, SP>, mapDispatchToProps: MapDispatchToProps<A, OP, DP>, mergeProps: MergeProps<SP, DP, OP, P>, options?: ConnectOptions ): Connector<OP, P>; }
'use strict'; require('mocha'); var assert = require('assert'); var recurse = require('../lib/recurse'); describe('recurse.async', function() { it('should return an array of files', function(cb) { recurse('test/fixtures', function(err, files) { if (err) return cb(err); assert(Array.isArray(files)); assert(files.length); cb(); }); }); it('should create file objects', function(cb) { recurse('test/fixtures', function(err, files) { if (err) return cb(err); assert(files[0]); assert.equal(typeof files[0], 'object'); cb(); }); }); it('should create file objects', function(cb) { recurse('test/fixtures', function(err, files) { if (err) return cb(err); files.forEach(function(file) { if (file.stat.isFile()) { assert(Buffer.isBuffer(file.contents)); } }); cb(); }); }); });
var array_seq_boot = [], array_seq_user = []; var level = 0; $('html').css('height', $(window).width()); var state = 'NewLevel'; var busy_global = busy_boot = false; var index_play_boot = 0; $(function(){ $("#new-game").click(function(){ ShowMessage("O desafio começou!"); setTimeout( NewGame, 1000); }); $("#end-game").click(function(){ state = 'EndGame'; alert('Jogo Abortado'); }); $('#Sair').click(function(){ window.close(); }); $('#grid-button a').click(onClickPlayer); }); function NewGame(){ array_seq_boot = []; array_seq_user = []; level = 0; index_play_boot = 0; $('#fase').html('Level ' + (level + 1)); state = 'NewLevel'; var intervalGlobal = setInterval(function(){ if (!busy_global) { //console.log('state :' + state); switch(state){ case 'NewLevel': busy_global = true; NewLevel(); state = 'PlayBoot'; busy_global = false; break; case 'PlayBoot': busy_global = true; PlayBoot(); break; case 'PlayPlayer': break; case 'GameOver': array_seq_boot = []; array_seq_user = []; array_fase = []; level = 1; index_play_boot = 0; $('#fase').html(''); ShowMessageGameOver("Game Over ;("); setTimeout(function(){ state = 'EndGame'; }, 2000); break; case 'EndGame': clearInterval(intervalGlobal); break; } } }, 100); } function EndGame(){ array_seq_boot = []; array_seq_user = []; array_fase = []; level = 1; index_play_boot = 0; } function onClickPlayer(){ var index_toutch_user = $(this).closest('li').index(); array_seq_user.push( index_toutch_user ); AnimeItem($(this)); //console.log( 'array_seq_boot[array_seq_user.length - 1] : ' + array_seq_boot[array_seq_user.length - 1] + ' | ' + 'index_toutch_user : ' + index_toutch_user); if ( array_seq_user.length <= array_seq_boot.length && array_seq_boot[array_seq_user.length - 1] == index_toutch_user ) { if ( array_seq_user.length == array_seq_boot.length ) //Completou a fase { state = 'NewLevel'; } console.log('ok - index:' + index_toutch_user); } else //Game Over { console.log('ERRO - index:' + index_toutch_user); state = 'GameOver'; } } function NewLevel(){ level++; $('#fase').html('Level ' + level ); array_seq_user = []; //Gera uma coordenada aleátória e adiciona no desafio array_seq_boot.push( parseInt( getRandomArbitary(0,8) ) ); } var PlayBoot = function(){ var jogada_boot = setInterval(function(){ //console.log('array_seq_boot.length : ' + array_seq_boot.length); if ( index_play_boot <= array_seq_boot.length -1 ) { console.log( 'index_play_boot: ' + index_play_boot + ' | position : ' + array_seq_boot[index_play_boot] ); AnimeItem( $('#grid-button > li:nth-child(' + (array_seq_boot[index_play_boot] + 1) + ') > a') ); index_play_boot++; } else{ clearInterval(jogada_boot); index_play_boot = 0; busy_global = false; state = 'PlayPlayer'; } }, 1000); }; function AnimeItem($item){ $item.addClass('show'); setTimeout( function(){ $item.removeClass('show'); //console.log('Class atual :' + $item.attr('class')); },300); } function ShowMessage(message){ $('#message').html('<label>' + message + '</label>'); $('#message').addClass('show-message'); setTimeout(function(){ $('#message').removeClass('show-message'); }, 2000); } function ShowMessageGameOver(message){ $('#message').html('<label>' + message + '</label>'); $('#message').addClass('show-message message-gameover'); setTimeout(function(){ $('#message').removeClass('show-message message-gameover'); }, 2000); }; function getRandomArbitary (min, max) { return Math.random() * (max - min) + min; } /*function compute() { var move = null; var busy = false, task = 'init'; var processor = setInterval(function() { if(!busy) { switch(task) { case 'start-game': alert('O jogo começou! :)'); task = 'doit-boot'; busy = true; break; case 'doit-boot' : //move = PlayBoot(); if(move) task = 'doit-play'; else task = 'done'; break; case 'doit-play': if ( game_over ) { alert('Você perdeu... :('); task = 'final'; busy = false; }else if ( winner ){ alert('Você venceu! :)'); task = 'final'; busy = false; } break; case 'final' : clearInterval(processor); busy = false; break; } } }, 100); */
$(document).ready(function (){ var scanner = new Scanner(); scanner.init('#test0'); scanner.controllerDivStyle=''; scanner.controlBarStyle='background-color:#999;'; //Set control bar at bottom of page //scanner.setControlBar("bottom"); scanner.setControlBar("top"); //Insert scanPanel before #test0 div scanner.setScanPanel("#test0",'before'); //set actions to each buttons in #test0 for (var j = 0, len = 5; j < len; j+=1) { scanner.actions[j]=[]; for (var i = 0, slen = 5; i < slen; i+=1) { scanner.actions[j].push(function(){ var elem=scanner.getElem(); var col = scanner.getSelCol(); var row = scanner.getSelRow(); var val = $(elem +' tr:eq('+row+') td:eq('+col+')').children().first().prop('id'); alert(val); } ); } } scanner.toggleButtonDisable('#stop_test0',true); $('#txtPB').click(function (){ }); $('#stop_test0').click(function (){ scanner.stopTimer(); scanner.toggleButtonDisable('#start_test0',false); scanner.toggleButtonDisable('#select_test0',true); scanner.toggleButtonDisable('#stop_test0',true); }); $('#start_test0').on('click',function(){ scanner.startTimer('row',scanner.scanSpeed); scanner.toggleButtonDisable('#start_test0',true); scanner.toggleButtonDisable('#changeScanSpeed_test0',true); scanner.toggleButtonDisable('#select_test0',false); scanner.toggleButtonDisable('#stop_test0',false); }); scanner.toggleButtonDisable('#start_test0',false); $('#select_test0').on('click',function(){ scanner.selectItem(); scanner.toggleButtonDisable('#start_test0',true); }); $('#scanModeOnOff_test0').on('click',function(){ scanner.toggleScanOnOff(); }); $('#scanModeOnOff_test0').mouseenter(function(){ $('#test0').css('background-color','red'); }).mouseleave(function(){ $('#test0').css('background-color',''); }); $('#changeScanSpeed_test0').on('click',function(){ scanner.setSpeedScan($('#scanSpeed_test0').val()); }); $('#scanSpeed_test0').keyup(function(){ if (($(this).val().length>0 && !isNaN(parseInt($(this).val())))) { scanner.toggleButtonDisable('#changeScanSpeed_test0',false); }else{ scanner.toggleButtonDisable('#changeScanSpeed_test0',true); } }); }); $(document).ready(function (){ //Set click event to each buttons in #test0 $('#test0 :button').on('click',function(){ alert($(this).val()+' is clicked.'); }); }); $(document).ready(function (){ var scanner = new Scanner(); scanner.init('#test'); scanner.controllerDivStyle='background-color: yellow; width: 200px;'; scanner.selectColor='green'; //control bar is already set, so item will only append to control bar scanner.setControlBar(); //Insert scanPanel after #test3 div scanner.setScanPanel("#test3"); scanner.toggleButtonDisable('#stop_test',true); $('#txtPB').click(function (){ }); $('#stop_test').click(function (){ scanner.stopTimer(); scanner.toggleButtonDisable('#start_test',false); scanner.toggleButtonDisable('#select_test',true); scanner.toggleButtonDisable('#stop_test',true); }); $('#start_test').on('click',function(){ scanner.startTimer('row',scanner.scanSpeed); scanner.toggleButtonDisable('#start_test',true); scanner.toggleButtonDisable('#changeScanSpeed_test',true); scanner.toggleButtonDisable('#select_test',false); scanner.toggleButtonDisable('#stop_test',false); }); scanner.toggleButtonDisable('#start_test',false); $('#select_test').on('click',function(){ scanner.selectItem(); scanner.toggleButtonDisable('#start_test',true); }); $('#scanModeOnOff_test').on('click',function(){ scanner.toggleScanOnOff(); }); $('#scanModeOnOff_test').mouseenter(function(){ $('#test').css('background-color','red'); }).mouseleave(function(){ $('#test').css('background-color',''); }); $('#changeScanSpeed_test').on('click',function(){ scanner.setSpeedScan($('#scanSpeed_test').val()); }); $('#scanSpeed_test').keyup(function(){ if (($(this).val().length>0 && !isNaN(parseInt($(this).val())))) { scanner.toggleButtonDisable('#changeScanSpeed_test',false); }else{ scanner.toggleButtonDisable('#changeScanSpeed_test',true); } }); });
/* Utilities */ import marked from 'marked'; import urlObject from 'url'; import moment from 'moment'; import sanitizeHtml from 'sanitize-html'; import getSlug from 'speakingurl'; import { getSetting } from './settings.js'; /** * @summary The global namespace for Telescope utils. * @namespace Telescope.utils */ export const Utils = {}; /** * @summary Convert a camelCase string to dash-separated string * @param {String} str */ Utils.camelToDash = function (str) { return str.replace(/\W+/g, '-').replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase(); }; /** * @summary Convert a camelCase string to a space-separated capitalized string * See http://stackoverflow.com/questions/4149276/javascript-camelcase-to-regular-form * @param {String} str */ Utils.camelToSpaces = function (str) { return str.replace(/([A-Z])/g, ' $1').replace(/^./, function(str){ return str.toUpperCase(); }); }; /** * @summary Convert an underscore-separated string to dash-separated string * @param {String} str */ Utils.underscoreToDash = function (str) { return str.replace('_', '-'); }; /** * @summary Convert a dash separated string to camelCase. * @param {String} str */ Utils.dashToCamel = function (str) { return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');}); }; /** * @summary Convert a string to camelCase and remove spaces. * @param {String} str */ Utils.camelCaseify = function(str) { str = this.dashToCamel(str.replace(' ', '-')); str = str.slice(0,1).toLowerCase() + str.slice(1); return str; }; /** * @summary Trim a sentence to a specified amount of words and append an ellipsis. * @param {String} s - Sentence to trim. * @param {Number} numWords - Number of words to trim sentence to. */ Utils.trimWords = function(s, numWords) { if (!s) return s; var expString = s.split(/\s+/,numWords); if(expString.length >= numWords) return expString.join(" ")+"…"; return s; }; /** * @summary Trim a block of HTML code to get a clean text excerpt * @param {String} html - HTML to trim. */ Utils.trimHTML = function (html, numWords) { var text = Utils.stripHTML(html); return Utils.trimWords(text, numWords); }; /** * @summary Capitalize a string. * @param {String} str */ Utils.capitalize = function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }; Utils.t = function(message) { var d = new Date(); console.log("### "+message+" rendered at "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()); // eslint-disable-line }; Utils.nl2br = function(str) { var breakTag = '<br />'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2'); }; Utils.scrollPageTo = function(selector) { $('body').scrollTop($(selector).offset().top); }; Utils.getDateRange = function(pageNumber) { var now = moment(new Date()); var dayToDisplay=now.subtract(pageNumber-1, 'days'); var range={}; range.start = dayToDisplay.startOf('day').valueOf(); range.end = dayToDisplay.endOf('day').valueOf(); // console.log("after: ", dayToDisplay.startOf('day').format("dddd, MMMM Do YYYY, h:mm:ss a")); // console.log("before: ", dayToDisplay.endOf('day').format("dddd, MMMM Do YYYY, h:mm:ss a")); return range; }; ////////////////////////// // URL Helper Functions // ////////////////////////// /** * @summary Returns the user defined site URL or Meteor.absoluteUrl */ Utils.getSiteUrl = function () { return getSetting('siteUrl', Meteor.absoluteUrl()); }; /** * @summary The global namespace for Telescope utils. * @param {String} url - the URL to redirect */ Utils.getOutgoingUrl = function (url) { return Utils.getSiteUrl() + "out?url=" + encodeURIComponent(url); }; Utils.slugify = function (s) { var slug = getSlug(s, { truncate: 60 }); // can't have posts with an "edit" slug if (slug === "edit") { slug = "edit-1"; } return slug; }; Utils.getUnusedSlug = function (collection, slug) { let suffix = ""; let index = 0; // test if slug is already in use while (!!collection.findOne({slug: slug+suffix})) { index++; suffix = "-"+index; } return slug+suffix; }; Utils.getShortUrl = function(post) { return post.shortUrl || post.url; }; Utils.getDomain = function(url) { try { return urlObject.parse(url).hostname.replace('www.', ''); } catch (error) { return null; } }; Utils.invitesEnabled = function() { return getSetting("requireViewInvite") || getSetting("requirePostInvite"); }; // add http: if missing Utils.addHttp = function (url) { try { if (url.substring(0, 5) !== "http:" && url.substring(0, 6) !== "https:") { url = "http:"+url; } return url; } catch (error) { return null; } }; ///////////////////////////// // String Helper Functions // ///////////////////////////// Utils.cleanUp = function(s) { return this.stripHTML(s); }; Utils.sanitize = function(s) { // console.log('// before sanitization:') // console.log(s) if(Meteor.isServer){ s = sanitizeHtml(s, { allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'img' ] }); // console.log('// after sanitization:') // console.log(s) } return s; }; Utils.stripHTML = function(s) { return s.replace(/<(?:.|\n)*?>/gm, ''); }; Utils.stripMarkdown = function(s) { var htmlBody = marked(s); return Utils.stripHTML(htmlBody); }; // http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key Utils.checkNested = function(obj /*, level1, level2, ... levelN*/) { var args = Array.prototype.slice.call(arguments); obj = args.shift(); for (var i = 0; i < args.length; i++) { if (!obj.hasOwnProperty(args[i])) { return false; } obj = obj[args[i]]; } return true; }; Utils.log = function (s) { if(getSetting('debug', false) || process.env.NODE_ENV === "development") { console.log(s); // eslint-disable-line } }; // see http://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string Utils.getNestedProperty = function (obj, desc) { var arr = desc.split("."); while(arr.length && (obj = obj[arr.shift()])); return obj; }; // see http://stackoverflow.com/a/14058408/649299 _.mixin({ compactObject : function(object) { var clone = _.clone(object); _.each(clone, function(value, key) { if(!value && typeof value !== "boolean") { delete clone[key]; } }); return clone; } }); Utils.getFieldLabel = (fieldName, collection) => { const label = collection.simpleSchema()._schema[fieldName].label; const nameWithSpaces = Utils.camelToSpaces(fieldName); return label || nameWithSpaces; } Utils.getLogoUrl = () => { const logoUrl = getSetting("logoUrl"); if (!!logoUrl) { const prefix = Utils.getSiteUrl().slice(0,-1); // the logo may be hosted on another website return logoUrl.indexOf('://') > -1 ? logoUrl : prefix + logoUrl; } }; // note(apollo): get collection's name from __typename given by react-apollo Utils.getCollectionNameFromTypename = (type) => { if (type.indexOf('Post') > -1) { return 'posts'; } else if (type.indexOf('Cat') > -1) { return 'categories'; } else if (type.indexOf('User') > -1) { return 'users'; } else if (type.indexOf('Comment') > -1) { return 'comments'; } }; Utils.findIndex = (array, predicate) => { let index = -1; let continueLoop = true; array.forEach((item, currentIndex) => { if (continueLoop && predicate(item)) { index = currentIndex continueLoop = false } }); return index; } // adapted from http://stackoverflow.com/a/22072374/649299 Utils.unflatten = function(array, idProperty, parentIdProperty, parent, level=0, tree){ level++; tree = typeof tree !== "undefined" ? tree : []; let children = []; if (typeof parent === "undefined") { // if there is no parent, we're at the root level // so we return all root nodes (i.e. nodes with no parent) children = _.filter(array, node => !node[parentIdProperty]); } else { // if there *is* a parent, we return all its child nodes // (i.e. nodes whose parentId is equal to the parent's id.) children = _.filter(array, node => node[parentIdProperty] === parent[idProperty]); } // if we found children, we keep on iterating if (!!children.length) { if (typeof parent === "undefined") { // if we're at the root, then the tree consist of all root nodes tree = children; } else { // else, we add the children to the parent as the "childrenResults" property parent.childrenResults = children; } // we call the function on each child children.forEach(child => { child.level = level; Utils.unflatten(array, idProperty, parentIdProperty, child, level); }); } return tree; }; // remove the telescope object from a schema and duplicate it at the root Utils.stripTelescopeNamespace = (schema) => { // grab the users schema keys const schemaKeys = Object.keys(schema); // remove any field beginning by telescope: .telescope, .telescope.upvotedPosts.$, ... const filteredSchemaKeys = schemaKeys.filter(key => key.slice(0,9) !== 'telescope'); // replace the previous schema by an object based on this filteredSchemaKeys return filteredSchemaKeys.reduce((sch, key) => ({...sch, [key]: schema[key]}), {}); } /** * Convert an array of field names into a Mongo fields specifier * @param {Array} fieldsArray */ Utils.arrayToFields = (fieldsArray) => { return _.object(fieldsArray, _.map(fieldsArray, function () {return true})); } /** * Get the display name of a React component * @param {React Component} WrappedComponent */ Utils.getComponentDisplayName = (WrappedComponent) => { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; }; /** * Take a collection and a list of documents, and convert all their date fields to date objects * This is necessary because Apollo doesn't support custom scalars, and stores dates as strings * @param {Object} collection * @param {Array} list */ Utils.convertDates = (collection, listOrDocument) => { // if undefined, just return if (!listOrDocument || !listOrDocument.length) return listOrDocument; const list = Array.isArray(listOrDocument) ? listOrDocument : [listOrDocument]; const schema = collection.simpleSchema()._schema; const dateFields = _.filter(_.keys(schema), fieldName => schema[fieldName].type === Date); const convertedList = list.map(result => { dateFields.forEach(fieldName => { if (result[fieldName] && typeof result[fieldName] === 'string') { result[fieldName] = new Date(result[fieldName]); } }); return result; }); return Array.isArray(listOrDocument) ? convertedList : convertedList[0]; } Utils.encodeIntlError = error => typeof error !== "object" ? error : JSON.stringify(error); Utils.decodeIntlError = (error, options = {stripped: false}) => { try { // do we get the error as a string or as an error object? let strippedError = typeof error === 'string' ? error : error.message; // if the error hasn't been cleaned before (ex: it's not an error from a form) if (!options.stripped) { // strip the "GraphQL Error: message [error_code]" given by Apollo if present const graphqlPrefixIsPresent = strippedError.match(/GraphQL error: (.*)/); if (graphqlPrefixIsPresent) { strippedError = graphqlPrefixIsPresent[1]; } // strip the error code if present const errorCodeIsPresent = strippedError.match(/(.*)\[(.*)\]/); if (errorCodeIsPresent) { strippedError = errorCodeIsPresent[1]; } } // the error is an object internationalizable const parsedError = JSON.parse(strippedError); // check if the error has at least an 'id' expected by react-intl if (!parsedError.id) { console.error('[Undecodable error]', error); // eslint-disable-line return {id: 'app.something_bad_happened', value: '[undecodable error]'} } // return the parsed error return parsedError; } catch(__) { // the error is not internationalizable return error; } }; Utils.findWhere = (array, criteria) => array.find(item => Object.keys(criteria).every(key => item[key] === criteria[key])); Utils.defineName = (o, name) => { Object.defineProperty(o, 'name', { value: name }); return o; }; Utils.performCheck = (operation, user, checkedObject, context) => { if (!operation.check(user, checkedObject, context)) throw new Error(Utils.encodeIntlError({id: `app.operation_not_allowed`, value: operation.name})); }
Controller('body', { 'helpers': { tasks: function () { return AppState.get('tasks.list'); }, hideCompleted: function () { return AppState.get('tasks.hideCompleted'); }, incompleteCount: function () { return AppState.get('tasks.incompleteCount'); } }, 'events': { "submit .new-task": function (event) { // Prevent default browser form submit event.preventDefault(); // Get value from form element var text = event.target.text.value; // Insert a task into the collection todoDispatcher.dispatch('tasks.addTask', {data: text}); // Clear form event.target.text.value = ""; }, "change .hide-completed input": function (event) { todoDispatcher.dispatch('tasks.hideCompleted', {data: event.target.checked}); } } })
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /*! * Next JS * Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved. * http://www.xenophy.com */ // {{{ NX.smtp.Response.watch module.exports = function(data) { data = data.toString(); var me = this, emit = false, code = 0, parsed = data.match(/^(?:.*\n)?([^\n]+)\n\s*$/m); me.buffer += data; me.notify(); }; // }}} /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * c-hanging-comment-ender-p: nil * End: */
import React, { Component } from 'react' import colors from '../colors' class H1 extends Component { render() { return <span style={Object.assign({ color: colors.dark, fontSize: '50px', letterSpacing: '2px', textShadow: `6px 6px ${colors.grayLight}`}, this.props.style)}> {this.props.text} </span> } } export default H1
(function(yubnubex, $, undefined) { var commands = new yubnubex.CommandList(); var CommandView = Backbone.View.extend({ tagName: "tr", events: { "click .remove-cmd": "removeCmd" }, template: _.template($('#command-template').html()), initialize: function() { this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; }, removeCmd: function() { this.model.destroy(); } }); var OptionsView = Backbone.View.extend({ el: $("#options-view"), events: { "click #save-new-cmd": "saveNewCmd", "click #clear-all-cmds": "clearAllCmds" }, initialize: function() { this.listenTo(commands, "sort", this.render); commands.fetch(); }, addOne: function(cmd) { var view = new CommandView({model: cmd}); this.$("#commands-table").append(view.render().el); }, render: function() { this.$("#commands-table").empty(); var that = this; commands.each(function (c) { that.addOne(c); }); return this; }, saveNewCmd: function() { commands.create({ trigger: this.$("#new-cmd-trigger").val(), exec: this.$("#new-cmd-exec").val() }, {merge: true}); this.$("#new-cmd-trigger").val(""); this.$("#new-cmd-exec").val(""); this.$("#new-cmd-trigger").focus(); }, clearAllCmds: function(){ while (commands.length > 0) commands.at(0).destroy(); } }); var optionsView = new OptionsView(); }(window.yubnubex = window.yubnubex || {}, jQuery));
var Unit = require('../unit.js'); var Config = require('../../shared/config.js'); var Battleship = module.exports = function(location, owner, world) { this.init(location, owner, 'battleship', world); this.canBeKilledBy = Config.KILL_BATTLESHIP; }; Battleship.prototype = new Unit(); Battleship.prototype.attack = function(defender) { this.wasInBattle = true; if (this.canBeKilledBy.indexOf(defender.type) > -1) { this.kill(); defender.joinBattle(); return true; } return defender.harm(this); }; Battleship.prototype.harm = function(offender) { this.wasInBattle = true; if (this.canBeKilledBy.indexOf(offender.type) > -1) { this.kill(); return true; } };
/** * This is a middleware that validates that the user is a High board member or higher * @param {HTTP} req The request object * @param {HTTP} res The response object * @param {Function} next Callback function that is called once the validation succeed * @ignore */ module.exports = function(req, res, next) { var log = require('./LogMiddleware'); if(req.user.isAdmin() || req.user.isUpperBoard() || req.user.isHighBoard()) { next(); } else { res.status(403).json( { status:'failed', message: 'Access denied' }); req.err = 'HighBoardMiddleware.js, 24\nThe user tries to access a route that is only for High board or higher.'; log.save(req, res); } };
(function(Modernizr, webshims){ "use strict"; var $ = webshims.$; var hasNative = Modernizr.audio && Modernizr.video; var supportsLoop = false; var bugs = webshims.bugs; var swfType = 'mediaelement-jaris'; var loadSwf = function(){ webshims.ready(swfType, function(){ if(!webshims.mediaelement.createSWF){ webshims.mediaelement.loadSwf = true; webshims.reTest([swfType], hasNative); } }); }; var wsCfg = webshims.cfg; var options = wsCfg.mediaelement; var hasFullTrackSupport; var hasSwf; if(!options){ webshims.error("mediaelement wasn't implemented but loaded"); return; } if(hasNative){ var videoElem = document.createElement('video'); Modernizr.videoBuffered = ('buffered' in videoElem); Modernizr.mediaDefaultMuted = ('defaultMuted' in videoElem); supportsLoop = ('loop' in videoElem); webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']); if(!Modernizr.videoBuffered ){ webshims.addPolyfill('mediaelement-native-fix', { d: ['dom-support'] }); webshims.loader.loadList(['mediaelement-native-fix']); } if(!options.preferFlash){ var noSwitch = { 1: 1 }; var switchOptions = function(e){ var media, error, parent; if(!options.preferFlash && ($(e.target).is('audio, video') || ((parent = e.target.parentNode) && $('source', parent).last()[0] == e.target)) && (media = $(e.target).closest('audio, video')) && (error = media.prop('error')) && !noSwitch[error.code] ){ $(function(){ if(hasSwf && !options.preferFlash){ loadSwf(); webshims.ready('WINDOWLOAD '+swfType, function(){ setTimeout(function(){ if(!options.preferFlash && webshims.mediaelement.createSWF && !media.is('.nonnative-api-active')){ options.preferFlash = true; document.removeEventListener('error', switchOptions, true); $('audio, video').each(function(){ webshims.mediaelement.selectSource(this); }); webshims.error("switching mediaelements option to 'preferFlash', due to an error with native player: "+e.target.src+" Mediaerror: "+ media.prop('error')+ 'first error: '+ error); } }, 9); }); } else{ document.removeEventListener('error', switchOptions, true); } }); } }; document.addEventListener('error', switchOptions, true); $('audio, video').each(function(){ var error = $.prop(this, 'error'); if(error && !noSwitch[error]){ switchOptions({target: this}); return false; } }); } } if(Modernizr.track && !bugs.track){ (function(){ if(!bugs.track){ bugs.track = typeof $('<track />')[0].readyState != 'number'; } if(!bugs.track){ try { new TextTrackCue(2, 3, ''); } catch(e){ bugs.track = true; } } })(); } hasFullTrackSupport = Modernizr.track && !bugs.track; webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){ hasSwf = swfmini.hasFlashPlayerVersion('9.0.115'); $('html').addClass(hasSwf ? 'swf' : 'no-swf'); var mediaelement = webshims.mediaelement; mediaelement.parseRtmp = function(data){ var src = data.src.split('://'); var paths = src[1].split('/'); var i, len, found; data.server = src[0]+'://'+paths[0]+'/'; data.streamId = []; for(i = 1, len = paths.length; i < len; i++){ if(!found && paths[i].indexOf(':') !== -1){ paths[i] = paths[i].split(':')[1]; found = true; } if(!found){ data.server += paths[i]+'/'; } else { data.streamId.push(paths[i]); } } if(!data.streamId.length){ webshims.error('Could not parse rtmp url'); } data.streamId = data.streamId.join('/'); }; var getSrcObj = function(elem, nodeName){ elem = $(elem); var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')}; var tmp; if(!src.src){return src;} tmp = elem.attr('data-server'); if(tmp != null){ src.server = tmp; } tmp = elem.attr('type') || elem.attr('data-type'); if(tmp){ src.type = tmp; src.container = $.trim(tmp.split(';')[0]); } else { if(!nodeName){ nodeName = elem[0].nodeName.toLowerCase(); if(nodeName == 'source'){ nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase(); } } if(src.server){ src.type = nodeName+'/rtmp'; src.container = nodeName+'/rtmp'; } else { tmp = mediaelement.getTypeForSrc( src.src, nodeName, src ); if(tmp){ src.type = tmp; src.container = tmp; } } } if(!src.container){ $(elem).attr('data-wsrecheckmimetype', ''); } tmp = elem.attr('media'); if(tmp){ src.media = tmp; } if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){ if(src.server){ src.streamId = src.src; } else { mediaelement.parseRtmp(src); } } return src; }; var hasYt = !hasSwf && ('postMessage' in window) && hasNative; var loadTrackUi = function(){ if(loadTrackUi.loaded){return;} loadTrackUi.loaded = true; if(!options.noAutoTrack){ webshims.ready('WINDOWLOAD', function(){ loadThird(); webshims.loader.loadList(['track-ui']); }); } }; // var loadMediaGroup = function(){ // if(!loadMediaGroup.loaded){ // loadMediaGroup.loaded = true; // webshims.ready(window.MediaController ? 'WINDOWLOAD' : 'DOM', function(){ // webshims.loader.loadList(['mediagroup']); // }); // } // }; var loadYt = (function(){ var loaded; return function(){ if(loaded || !hasYt){return;} loaded = true; webshims.loader.loadScript("https://www.youtube.com/player_api"); $(function(){ webshims._polyfill(["mediaelement-yt"]); }); }; })(); var loadThird = function(){ if(hasSwf){ loadSwf(); } else { loadYt(); } }; webshims.addPolyfill('mediaelement-yt', { test: !hasYt, d: ['dom-support'] }); // webshims.addModule('mediagroup', { // d: ['mediaelement', 'dom-support'] // }); mediaelement.mimeTypes = { audio: { //ogm shouldn´t be used! 'audio/ogg': ['ogg','oga', 'ogm'], 'audio/ogg;codecs="opus"': 'opus', 'audio/mpeg': ['mp2','mp3','mpga','mpega'], 'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'], 'audio/wav': ['wav'], 'audio/3gpp': ['3gp','3gpp'], 'audio/webm': ['webm'], 'audio/fla': ['flv', 'f4a', 'fla'], 'application/x-mpegURL': ['m3u8', 'm3u'] }, video: { //ogm shouldn´t be used! 'video/ogg': ['ogg','ogv', 'ogm'], 'video/mpeg': ['mpg','mpeg','mpe'], 'video/mp4': ['mp4','mpg4', 'm4v'], 'video/quicktime': ['mov','qt'], 'video/x-msvideo': ['avi'], 'video/x-ms-asf': ['asf', 'asx'], 'video/flv': ['flv', 'f4v'], 'video/3gpp': ['3gp','3gpp'], 'video/webm': ['webm'], 'application/x-mpegURL': ['m3u8', 'm3u'], 'video/MP2T': ['ts'] } } ; mediaelement.mimeTypes.source = $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video); mediaelement.getTypeForSrc = function(src, nodeName, data){ if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){ return 'video/youtube'; } if(src.indexOf('rtmp') === 0){ return nodeName+'/rtmp'; } src = src.split('?')[0].split('#')[0].split('.'); src = src[src.length - 1]; var mt; $.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){ if(exts.indexOf(src) !== -1){ mt = mimeType; return false; } }); return mt; }; mediaelement.srces = function(mediaElem, srces){ mediaElem = $(mediaElem); if(!srces){ srces = []; var nodeName = mediaElem[0].nodeName.toLowerCase(); var src = getSrcObj(mediaElem, nodeName); if(!src.src){ $('source', mediaElem).each(function(){ src = getSrcObj(this, nodeName); if(src.src){srces.push(src);} }); } else { srces.push(src); } return srces; } else { mediaElem.removeAttr('src').removeAttr('type').find('source').remove(); if(!$.isArray(srces)){ srces = [srces]; } srces.forEach(function(src){ if(typeof src == 'string'){ src = {src: src}; } mediaElem.append($(document.createElement('source')).attr(src)); }); } }; $.fn.loadMediaSrc = function(srces, poster){ return this.each(function(){ if(poster !== undefined){ $(this).removeAttr('poster'); if(poster){ $.attr(this, 'poster', poster); } } mediaelement.srces(this, srces); $(this).mediaLoad(); }); }; mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'video/youtube', 'video/rtmp', 'audio/rtmp']; mediaelement.canThirdPlaySrces = function(mediaElem, srces){ var ret = ''; if(hasSwf || hasYt){ mediaElem = $(mediaElem); srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){ ret = src; return false; } }); } return ret; }; var nativeCanPlayType = {}; mediaelement.canNativePlaySrces = function(mediaElem, srces){ var ret = ''; if(hasNative){ mediaElem = $(mediaElem); var nodeName = (mediaElem[0].nodeName || '').toLowerCase(); var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType; if(!nativeCanPlay){return ret;} srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.type && nativeCanPlay.call(mediaElem[0], src.type) ){ ret = src; return false; } }); } return ret; }; var emptyType = (/^\s*application\/octet\-stream\s*$/i); var getRemoveEmptyType = function(){ var ret = emptyType.test($.attr(this, 'type') || ''); if(ret){ $(this).removeAttr('type'); } return ret; }; mediaelement.setError = function(elem, message){ if($('source', elem).filter(getRemoveEmptyType).length){ webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.'); try { $(elem).mediaLoad(); } catch(er){} } else { if(!message){ message = "can't play sources"; } $(elem).pause().data('mediaerror', message); webshims.error('mediaelementError: '+ message); setTimeout(function(){ if($(elem).data('mediaerror')){ $(elem).addClass('media-error').trigger('mediaerror'); } }, 1); } }; var handleThird = (function(){ var requested; var readyType = hasSwf ? swfType : 'mediaelement-yt'; return function( mediaElem, ret, data ){ //readd to ready webshims.ready(readyType, function(){ if(mediaelement.createSWF && $(mediaElem).parent()[0]){ mediaelement.createSWF( mediaElem, ret, data ); } else if(!requested) { requested = true; loadThird(); handleThird( mediaElem, ret, data ); } }); if(!requested && hasYt && !mediaelement.createSWF){ loadYt(); } }; })(); var stepSources = function(elem, data, useSwf, _srces, _noLoop){ var ret; if(useSwf || (useSwf !== false && data && data.isActive == 'third')){ ret = mediaelement.canThirdPlaySrces(elem, _srces); if(!ret){ if(_noLoop){ mediaelement.setError(elem, false); } else { stepSources(elem, data, false, _srces, true); } } else { handleThird(elem, ret, data); } } else { ret = mediaelement.canNativePlaySrces(elem, _srces); if(!ret){ if(_noLoop){ mediaelement.setError(elem, false); if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } else { stepSources(elem, data, true, _srces, true); } } else if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } }; var stopParent = /^(?:embed|object|datalist)$/i; var selectSource = function(elem, data){ var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); var _srces = mediaelement.srces(elem); var parent = elem.parentNode; clearTimeout(baseData.loadTimer); $(elem).removeClass('media-error'); $.data(elem, 'mediaerror', false); if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;} data = data || webshims.data(elem, 'mediaelement'); if(mediaelement.sortMedia){ _srces.sort(mediaelement.sortMedia); } stepSources(elem, data, options.preferFlash || undefined, _srces); }; mediaelement.selectSource = selectSource; $(document).on('ended', function(e){ var data = webshims.data(e.target, 'mediaelement'); if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;} setTimeout(function(){ if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;} $(e.target).prop('currentTime', 0).play(); }, 1); }); var handleMedia = false; var initMediaElements = function(){ var testFixMedia = function(){ if(webshims.implement(this, 'mediaelement')){ selectSource(this); if(!Modernizr.mediaDefaultMuted && $.attr(this, 'muted') != null){ $.prop(this, 'muted', true); } //fixes for FF 12 and IE9/10 || does not hurt, if run in other browsers if(hasNative && (!supportsLoop || ('ActiveXObject' in window))){ var bufferTimer; var lastBuffered; var elem = this; var getBufferedString = function(){ var buffered = $.prop(elem, 'buffered'); if(!buffered){return;} var bufferString = ""; for(var i = 0, len = buffered.length; i < len;i++){ bufferString += buffered.end(i); } return bufferString; }; var testBuffer = function(){ var buffered = getBufferedString(); if(buffered != lastBuffered){ lastBuffered = buffered; webshims.info('needed to trigger progress manually'); $(elem).triggerHandler('progress'); } }; $(this) .on({ 'play loadstart progress': function(e){ if(e.type == 'progress'){ lastBuffered = getBufferedString(); } clearTimeout(bufferTimer); bufferTimer = setTimeout(testBuffer, 400); }, 'emptied stalled mediaerror abort suspend': function(e){ if(e.type == 'emptied'){ lastBuffered = false; } clearTimeout(bufferTimer); } }) ; if('ActiveXObject' in window && $.prop(this, 'paused') && !$.prop(this, 'readyState') && $(this).is('audio[preload="none"][controls]:not([autoplay],.nonnative-api-active)')){ $(this).prop('preload', 'metadata').mediaLoad(); } } } }; webshims.ready('dom-support', function(){ handleMedia = true; if(!supportsLoop){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop'); } ['audio', 'video'].forEach(function(nodeName){ var supLoad, supController; supLoad = webshims.defineNodeNameProperty(nodeName, 'load', { prop: { value: function(){ var data = webshims.data(this, 'mediaelement'); selectSource(this, data); if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){ supLoad.prop._supvalue.apply(this, arguments); } $(this).triggerHandler('wsmediareload'); } } }); nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType', { prop: { value: function(type){ var ret = ''; if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){ ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type); if(ret == 'no'){ ret = ''; } } if(!ret && hasSwf){ type = $.trim((type || '').split(';')[0]); if(mediaelement.swfMimeTypes.indexOf(type) != -1){ ret = 'maybe'; } } return ret; } } }); // supController = webshims.defineNodeNameProperty(nodeName, 'controller', { // prop: { // get: function(type){ // if(!loadMediaGroup.loaded){ // loadMediaGroup(); // } // if(mediaelement.controller){ // return mediaelement.controller[nodeName].get.apply(this, arguments); // } // return supController.prop._supget && supController.prop._supget.apply(this, arguments); // }, // set: function(){ // var that = this; // var args = arguments; // if(!loadMediaGroup.loaded){ // loadMediaGroup(); // } // if(mediaelement.controller){ // return mediaelement.controller[nodeName].set.apply(that, args); // } else { // webshims.ready('mediagroup', function(){ // mediaelement.controller[nodeName].set.apply(that, args); // }); // } // return supController.prop._supset && supController.prop._supset.apply(this, arguments); // } // } // }); // webshims.ready('mediagroup', function(){ // mediaelement.controller[nodeName].sup = supController; // }); }); // webshims.onNodeNamesPropertyModify(['audio', 'video'], ['mediaGroup'], { // set: function(){ // var that = this; // var args = arguments; // if(!loadMediaGroup.loaded){ // loadMediaGroup(); // } // if(mediaelement.mediagroup){ // mediaelement.mediagroup.set.apply(that, args); // } else { // webshims.ready('mediagroup', function(){ // mediaelement.mediagroup.set.apply(that, args); // }); // } // }, // initAttr: true // }); webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], { set: function(){ var elem = this; var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ selectSource(elem); elem = null; }, 9); } }); webshims.addReady(function(context, insertedElement){ var media = $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(testFixMedia) ; if(!loadTrackUi.loaded && $('track', media).length){ loadTrackUi(); } // if(!loadMediaGroup.loaded && this.getAttribute('mediagroup')){ // loadMediaGroup(); // } media = null; }); }); if(hasNative && !handleMedia){ webshims.addReady(function(context, insertedElement){ if(!handleMedia){ $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(function(){ if(!mediaelement.canNativePlaySrces(this)){ loadThird(); handleMedia = true; return false; } }) ; } }); } }; if(hasFullTrackSupport){ webshims.defineProperty(TextTrack.prototype, 'shimActiveCues', { get: function(){ return this._shimActiveCues || this.activeCues; } }); } //set native implementation ready, before swf api is retested if(hasNative){ webshims.isReady('mediaelement-core', true); initMediaElements(); webshims.ready('WINDOWLOAD mediaelement', loadThird); } else { webshims.ready(swfType, initMediaElements); } webshims.ready('track', loadTrackUi); }); })(Modernizr, webshims);
/* * HTML5Sortable package * https://github.com/lukasoppermann/html5sortable * * Maintained by Lukas Oppermann <lukas@vea.re> * * Released under the MIT license. */ var sortable = (function () { 'use strict'; /** * Get or set data on element * @param {HTMLElement} element * @param {string} key * @param {any} value * @return {*} */ function addData(element, key, value) { if (value === undefined) { return element && element.h5s && element.h5s.data && element.h5s.data[key]; } else { element.h5s = element.h5s || {}; element.h5s.data = element.h5s.data || {}; element.h5s.data[key] = value; } } /** * Remove data from element * @param {HTMLElement} element */ function removeData(element) { if (element.h5s) { delete element.h5s.data; } } /* eslint-env browser */ /** * Filter only wanted nodes * @param {NodeList|HTMLCollection|Array} nodes * @param {String} selector * @returns {Array} */ var filter = (function (nodes, selector) { if (!(nodes instanceof NodeList || nodes instanceof HTMLCollection || nodes instanceof Array)) { throw new Error('You must provide a nodeList/HTMLCollection/Array of elements to be filtered.'); } if (typeof selector !== 'string') { return Array.from(nodes); } return Array.from(nodes).filter(function (item) { return item.nodeType === 1 && item.matches(selector); }); }); /* eslint-env browser */ /* eslint-disable no-use-before-define */ var stores = new Map(); /* eslint-enable no-use-before-define */ /** * Stores data & configurations per Sortable * @param {Object} config */ var Store = /** @class */ (function () { function Store() { this._config = new Map(); // eslint-disable-line no-undef this._placeholder = undefined; // eslint-disable-line no-undef this._data = new Map(); // eslint-disable-line no-undef } Object.defineProperty(Store.prototype, "config", { /** * get the configuration map of a class instance * @method config * @return {object} */ get: function () { // transform Map to object var config = {}; this._config.forEach(function (value, key) { config[key] = value; }); // return object return config; }, /** * set the configuration of a class instance * @method config * @param {object} config object of configurations */ set: function (config) { if (typeof config !== 'object') { throw new Error('You must provide a valid configuration object to the config setter.'); } // combine config with default var mergedConfig = Object.assign({}, config); // add config to map this._config = new Map(Object.entries(mergedConfig)); }, enumerable: false, configurable: true }); /** * set individual configuration of a class instance * @method setConfig * @param key valid configuration key * @param value any value * @return void */ Store.prototype.setConfig = function (key, value) { if (!this._config.has(key)) { throw new Error("Trying to set invalid configuration item: " + key); } // set config this._config.set(key, value); }; /** * get an individual configuration of a class instance * @method getConfig * @param key valid configuration key * @return any configuration value */ Store.prototype.getConfig = function (key) { if (!this._config.has(key)) { throw new Error("Invalid configuration item requested: " + key); } return this._config.get(key); }; Object.defineProperty(Store.prototype, "placeholder", { /** * get the placeholder for a class instance * @method placeholder * @return {HTMLElement|null} */ get: function () { return this._placeholder; }, /** * set the placeholder for a class instance * @method placeholder * @param {HTMLElement} placeholder * @return {void} */ set: function (placeholder) { if (!(placeholder instanceof HTMLElement) && placeholder !== null) { throw new Error('A placeholder must be an html element or null.'); } this._placeholder = placeholder; }, enumerable: false, configurable: true }); /** * set an data entry * @method setData * @param {string} key * @param {any} value * @return {void} */ Store.prototype.setData = function (key, value) { if (typeof key !== 'string') { throw new Error('The key must be a string.'); } this._data.set(key, value); }; /** * get an data entry * @method getData * @param {string} key an existing key * @return {any} */ Store.prototype.getData = function (key) { if (typeof key !== 'string') { throw new Error('The key must be a string.'); } return this._data.get(key); }; /** * delete an data entry * @method deleteData * @param {string} key an existing key * @return {boolean} */ Store.prototype.deleteData = function (key) { if (typeof key !== 'string') { throw new Error('The key must be a string.'); } return this._data.delete(key); }; return Store; }()); /** * @param {HTMLElement} sortableElement * @returns {Class: Store} */ var store = (function (sortableElement) { // if sortableElement is wrong type if (!(sortableElement instanceof HTMLElement)) { throw new Error('Please provide a sortable to the store function.'); } // create new instance if not avilable if (!stores.has(sortableElement)) { stores.set(sortableElement, new Store()); } // return instance return stores.get(sortableElement); }); /** * @param {Array|HTMLElement} element * @param {Function} callback * @param {string} event */ function addEventListener(element, eventName, callback) { if (element instanceof Array) { for (var i = 0; i < element.length; ++i) { addEventListener(element[i], eventName, callback); } return; } element.addEventListener(eventName, callback); store(element).setData("event" + eventName, callback); } /** * @param {Array<HTMLElement>|HTMLElement} element * @param {string} eventName */ function removeEventListener(element, eventName) { if (element instanceof Array) { for (var i = 0; i < element.length; ++i) { removeEventListener(element[i], eventName); } return; } element.removeEventListener(eventName, store(element).getData("event" + eventName)); store(element).deleteData("event" + eventName); } /** * @param {Array<HTMLElement>|HTMLElement} element * @param {string} attribute * @param {string} value */ function addAttribute(element, attribute, value) { if (element instanceof Array) { for (var i = 0; i < element.length; ++i) { addAttribute(element[i], attribute, value); } return; } element.setAttribute(attribute, value); } /** * @param {Array|HTMLElement} element * @param {string} attribute */ function removeAttribute(element, attribute) { if (element instanceof Array) { for (var i = 0; i < element.length; ++i) { removeAttribute(element[i], attribute); } return; } element.removeAttribute(attribute); } /** * @param {HTMLElement} element * @returns {Object} */ var offset = (function (element) { if (!element.parentElement || element.getClientRects().length === 0) { throw new Error('target element must be part of the dom'); } var rect = element.getClientRects()[0]; return { left: rect.left + window.pageXOffset, right: rect.right + window.pageXOffset, top: rect.top + window.pageYOffset, bottom: rect.bottom + window.pageYOffset }; }); /** * Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed * @param {Function} func to debounce * @param {number} time to wait before calling function with latest arguments, 0 - no debounce * @returns {function} - debounced function */ var debounce = (function (func, wait) { if (wait === void 0) { wait = 0; } var timeout; return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } clearTimeout(timeout); timeout = setTimeout(function () { func.apply(void 0, args); }, wait); }; }); /* eslint-env browser */ /** * Get position of the element relatively to its sibling elements * @param {HTMLElement} element * @returns {number} */ var getIndex = (function (element, elementList) { if (!(element instanceof HTMLElement) || !(elementList instanceof NodeList || elementList instanceof HTMLCollection || elementList instanceof Array)) { throw new Error('You must provide an element and a list of elements.'); } return Array.from(elementList).indexOf(element); }); /* eslint-env browser */ /** * Test whether element is in DOM * @param {HTMLElement} element * @returns {boolean} */ var isInDom = (function (element) { if (!(element instanceof HTMLElement)) { throw new Error('Element is not a node element.'); } return element.parentNode !== null; }); /* eslint-env browser */ /** * Insert node before or after target * @param {HTMLElement} referenceNode - reference element * @param {HTMLElement} newElement - element to be inserted * @param {String} position - insert before or after reference element */ var insertNode = function (referenceNode, newElement, position) { if (!(referenceNode instanceof HTMLElement) || !(referenceNode.parentElement instanceof HTMLElement)) { throw new Error('target and element must be a node'); } referenceNode.parentElement.insertBefore(newElement, (position === 'before' ? referenceNode : referenceNode.nextElementSibling)); }; /** * Insert before target * @param {HTMLElement} target * @param {HTMLElement} element */ var insertBefore = function (target, element) { return insertNode(target, element, 'before'); }; /** * Insert after target * @param {HTMLElement} target * @param {HTMLElement} element */ var insertAfter = function (target, element) { return insertNode(target, element, 'after'); }; /* eslint-env browser */ /** * Filter only wanted nodes * @param {HTMLElement} sortableContainer * @param {Function} customSerializer * @returns {Array} */ var serialize = (function (sortableContainer, customItemSerializer, customContainerSerializer) { if (customItemSerializer === void 0) { customItemSerializer = function (serializedItem, sortableContainer) { return serializedItem; }; } if (customContainerSerializer === void 0) { customContainerSerializer = function (serializedContainer) { return serializedContainer; }; } // check for valid sortableContainer if (!(sortableContainer instanceof HTMLElement) || !sortableContainer.isSortable === true) { throw new Error('You need to provide a sortableContainer to be serialized.'); } // check for valid serializers if (typeof customItemSerializer !== 'function' || typeof customContainerSerializer !== 'function') { throw new Error('You need to provide a valid serializer for items and the container.'); } // get options var options = addData(sortableContainer, 'opts'); var item = options.items; // serialize container var items = filter(sortableContainer.children, item); var serializedItems = items.map(function (item) { return { parent: sortableContainer, node: item, html: item.outerHTML, index: getIndex(item, items) }; }); // serialize container var container = { node: sortableContainer, itemCount: serializedItems.length }; return { container: customContainerSerializer(container), items: serializedItems.map(function (item) { return customItemSerializer(item, sortableContainer); }) }; }); /* eslint-env browser */ /** * create a placeholder element * @param {HTMLElement} sortableElement a single sortable * @param {string|undefined} placeholder a string representing an html element * @param {string} placeholderClasses a string representing the classes that should be added to the placeholder */ var makePlaceholder = (function (sortableElement, placeholder, placeholderClass) { var _a; if (placeholderClass === void 0) { placeholderClass = 'sortable-placeholder'; } if (!(sortableElement instanceof HTMLElement)) { throw new Error('You must provide a valid element as a sortable.'); } // if placeholder is not an element if (!(placeholder instanceof HTMLElement) && placeholder !== undefined) { throw new Error('You must provide a valid element as a placeholder or set ot to undefined.'); } // if no placeholder element is given if (placeholder === undefined) { if (['UL', 'OL'].includes(sortableElement.tagName)) { placeholder = document.createElement('li'); } else if (['TABLE', 'TBODY'].includes(sortableElement.tagName)) { placeholder = document.createElement('tr'); // set colspan to always all rows, otherwise the item can only be dropped in first column placeholder.innerHTML = '<td colspan="100"></td>'; } else { placeholder = document.createElement('div'); } } // add classes to placeholder if (typeof placeholderClass === 'string') { (_a = placeholder.classList).add.apply(_a, placeholderClass.split(' ')); } return placeholder; }); /* eslint-env browser */ /** * Get height of an element including padding * @param {HTMLElement} element an dom element */ var getElementHeight = (function (element) { if (!(element instanceof HTMLElement)) { throw new Error('You must provide a valid dom element'); } // get calculated style of element var style = window.getComputedStyle(element); // get only height if element has box-sizing: border-box specified if (style.getPropertyValue('box-sizing') === 'border-box') { return parseInt(style.getPropertyValue('height'), 10); } // pick applicable properties, convert to int and reduce by adding return ['height', 'padding-top', 'padding-bottom'] .map(function (key) { var int = parseInt(style.getPropertyValue(key), 10); return isNaN(int) ? 0 : int; }) .reduce(function (sum, value) { return sum + value; }); }); /* eslint-env browser */ /** * Get width of an element including padding * @param {HTMLElement} element an dom element */ var getElementWidth = (function (element) { if (!(element instanceof HTMLElement)) { throw new Error('You must provide a valid dom element'); } // get calculated style of element var style = window.getComputedStyle(element); // pick applicable properties, convert to int and reduce by adding return ['width', 'padding-left', 'padding-right'] .map(function (key) { var int = parseInt(style.getPropertyValue(key), 10); return isNaN(int) ? 0 : int; }) .reduce(function (sum, value) { return sum + value; }); }); /* eslint-env browser */ /** * get handle or return item * @param {Array<HTMLElement>} items * @param {string} selector */ var getHandles = (function (items, selector) { if (!(items instanceof Array)) { throw new Error('You must provide a Array of HTMLElements to be filtered.'); } if (typeof selector !== 'string') { return items; } return items // remove items without handle from array .filter(function (item) { return item.querySelector(selector) instanceof HTMLElement || (item.shadowRoot && item.shadowRoot.querySelector(selector) instanceof HTMLElement); }) // replace item with handle in array .map(function (item) { return item.querySelector(selector) || (item.shadowRoot && item.shadowRoot.querySelector(selector)); }); }); /** * @param {Event} event * @returns {HTMLElement} */ var getEventTarget = (function (event) { return (event.composedPath && event.composedPath()[0]) || event.target; }); /* eslint-env browser */ /** * defaultDragImage returns the current item as dragged image * @param {HTMLElement} draggedElement - the item that the user drags * @param {object} elementOffset - an object with the offsets top, left, right & bottom * @param {Event} event - the original drag event object * @return {object} with element, posX and posY properties */ var defaultDragImage = function (draggedElement, elementOffset, event) { return { element: draggedElement, posX: event.pageX - elementOffset.left, posY: event.pageY - elementOffset.top }; }; /** * attaches an element as the drag image to an event * @param {Event} event - the original drag event object * @param {HTMLElement} draggedElement - the item that the user drags * @param {Function} customDragImage - function to create a custom dragImage * @return void */ var setDragImage = (function (event, draggedElement, customDragImage) { // check if event is provided if (!(event instanceof Event)) { throw new Error('setDragImage requires a DragEvent as the first argument.'); } // check if draggedElement is provided if (!(draggedElement instanceof HTMLElement)) { throw new Error('setDragImage requires the dragged element as the second argument.'); } // set default function of none provided if (!customDragImage) { customDragImage = defaultDragImage; } // check if setDragImage method is available if (event.dataTransfer && event.dataTransfer.setDragImage) { // get the elements offset var elementOffset = offset(draggedElement); // get the dragImage var dragImage = customDragImage(draggedElement, elementOffset, event); // check if custom function returns correct values if (!(dragImage.element instanceof HTMLElement) || typeof dragImage.posX !== 'number' || typeof dragImage.posY !== 'number') { throw new Error('The customDragImage function you provided must return and object with the properties element[string], posX[integer], posY[integer].'); } // needs to be set for HTML5 drag & drop to work event.dataTransfer.effectAllowed = 'copyMove'; // Firefox requires it to use the event target's id for the data event.dataTransfer.setData('text/plain', getEventTarget(event).id); // set the drag image on the event event.dataTransfer.setDragImage(dragImage.element, dragImage.posX, dragImage.posY); } }); /** * Check if curList accepts items from destList * @param {sortable} destination the container an item is move to * @param {sortable} origin the container an item comes from */ var listsConnected = (function (destination, origin) { // check if valid sortable if (destination.isSortable === true) { var acceptFrom = store(destination).getConfig('acceptFrom'); // check if acceptFrom is valid if (acceptFrom !== null && acceptFrom !== false && typeof acceptFrom !== 'string') { throw new Error('HTML5Sortable: Wrong argument, "acceptFrom" must be "null", "false", or a valid selector string.'); } if (acceptFrom !== null) { return acceptFrom !== false && acceptFrom.split(',').filter(function (sel) { return sel.length > 0 && origin.matches(sel); }).length > 0; } // drop in same list if (destination === origin) { return true; } // check if lists are connected with connectWith if (store(destination).getConfig('connectWith') !== undefined && store(destination).getConfig('connectWith') !== null) { return store(destination).getConfig('connectWith') === store(origin).getConfig('connectWith'); } } return false; }); /** * default configurations */ var defaultConfiguration = { items: null, // deprecated connectWith: null, // deprecated disableIEFix: null, acceptFrom: null, copy: false, placeholder: null, placeholderClass: 'sortable-placeholder', draggingClass: 'sortable-dragging', hoverClass: false, dropTargetContainerClass: false, debounce: 0, throttleTime: 100, maxItems: 0, itemSerializer: undefined, containerSerializer: undefined, customDragImage: null, orientation: 'vertical' }; /** * make sure a function is only called once within the given amount of time * @param {Function} fn the function to throttle * @param {number} threshold time limit for throttling */ // must use function to keep this context function throttle (fn, threshold) { var _this = this; if (threshold === void 0) { threshold = 250; } // check function if (typeof fn !== 'function') { throw new Error('You must provide a function as the first argument for throttle.'); } // check threshold if (typeof threshold !== 'number') { throw new Error('You must provide a number as the second argument for throttle.'); } var lastEventTimestamp = null; return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var now = Date.now(); if (lastEventTimestamp === null || now - lastEventTimestamp >= threshold) { lastEventTimestamp = now; fn.apply(_this, args); } }; } /* eslint-env browser */ /** * enable or disable hoverClass on mouseenter/leave if container Items * @param {sortable} sortableContainer a valid sortableContainer * @param {boolean} enable enable or disable event */ var enableHoverClass = (function (sortableContainer, enable) { if (typeof store(sortableContainer).getConfig('hoverClass') === 'string') { var hoverClasses_1 = store(sortableContainer).getConfig('hoverClass').split(' '); // add class on hover if (enable === true) { addEventListener(sortableContainer, 'mousemove', throttle(function (event) { // check of no mouse button was pressed when mousemove started == no drag if (event.buttons === 0) { filter(sortableContainer.children, store(sortableContainer).getConfig('items')).forEach(function (item) { var _a, _b; if (item === event.target || item.contains(event.target)) { (_a = item.classList).add.apply(_a, hoverClasses_1); } else { (_b = item.classList).remove.apply(_b, hoverClasses_1); } }); } }, store(sortableContainer).getConfig('throttleTime'))); // remove class on leave addEventListener(sortableContainer, 'mouseleave', function () { filter(sortableContainer.children, store(sortableContainer).getConfig('items')).forEach(function (item) { var _a; (_a = item.classList).remove.apply(_a, hoverClasses_1); }); }); // remove events } else { removeEventListener(sortableContainer, 'mousemove'); removeEventListener(sortableContainer, 'mouseleave'); } } }); /* eslint-env browser */ /* * variables global to the plugin */ var dragging; var draggingHeight; var draggingWidth; /* * Keeps track of the initialy selected list, where 'dragstart' event was triggered * It allows us to move the data in between individual Sortable List instances */ // Origin List - data from before any item was changed var originContainer; var originIndex; var originElementIndex; var originItemsBeforeUpdate; // Previous Sortable Container - we dispatch as sortenter event when a // dragged item enters a sortableContainer for the first time var previousContainer; // Destination List - data from before any item was changed var destinationItemsBeforeUpdate; /** * remove event handlers from items * @param {Array|NodeList} items */ var removeItemEvents = function (items) { removeEventListener(items, 'dragstart'); removeEventListener(items, 'dragend'); removeEventListener(items, 'dragover'); removeEventListener(items, 'dragenter'); removeEventListener(items, 'drop'); removeEventListener(items, 'mouseenter'); removeEventListener(items, 'mouseleave'); }; // Remove container events var removeContainerEvents = function (originContainer, previousContainer) { if (originContainer) { removeEventListener(originContainer, 'dragleave'); } if (previousContainer && (previousContainer !== originContainer)) { removeEventListener(previousContainer, 'dragleave'); } }; /** * getDragging returns the current element to drag or * a copy of the element. * Is Copy Active for sortable * @param {HTMLElement} draggedItem - the item that the user drags * @param {HTMLElement} sortable a single sortable */ var getDragging = function (draggedItem, sortable) { var ditem = draggedItem; if (store(sortable).getConfig('copy') === true) { ditem = draggedItem.cloneNode(true); addAttribute(ditem, 'aria-copied', 'true'); draggedItem.parentElement.appendChild(ditem); ditem.style.display = 'none'; ditem.oldDisplay = draggedItem.style.display; } return ditem; }; /** * Remove data from sortable * @param {HTMLElement} sortable a single sortable */ var removeSortableData = function (sortable) { removeData(sortable); removeAttribute(sortable, 'aria-dropeffect'); }; /** * Remove data from items * @param {Array<HTMLElement>|HTMLElement} items */ var removeItemData = function (items) { removeAttribute(items, 'aria-grabbed'); removeAttribute(items, 'aria-copied'); removeAttribute(items, 'draggable'); removeAttribute(items, 'role'); }; /** * find sortable from element. travels up parent element until found or null. * @param {HTMLElement} element a single sortable * @param {Event} event - the current event. We need to pass it to be able to * find Sortable whith shadowRoot (document fragment has no parent) */ function findSortable(element, event) { if (event.composedPath) { return event.composedPath().find(function (el) { return el.isSortable; }); } while (element.isSortable !== true) { element = element.parentElement; } return element; } /** * Dragging event is on the sortable element. finds the top child that * contains the element. * @param {HTMLElement} sortableElement a single sortable * @param {HTMLElement} element is that being dragged */ function findDragElement(sortableElement, element) { var options = addData(sortableElement, 'opts'); var items = filter(sortableElement.children, options.items); var itemlist = items.filter(function (ele) { return ele.contains(element) || (ele.shadowRoot && ele.shadowRoot.contains(element)); }); return itemlist.length > 0 ? itemlist[0] : element; } /** * Destroy the sortable * @param {HTMLElement} sortableElement a single sortable */ var destroySortable = function (sortableElement) { var opts = addData(sortableElement, 'opts') || {}; var items = filter(sortableElement.children, opts.items); var handles = getHandles(items, opts.handle); // disable adding hover class enableHoverClass(sortableElement, false); // remove event handlers & data from sortable removeEventListener(sortableElement, 'dragover'); removeEventListener(sortableElement, 'dragenter'); removeEventListener(sortableElement, 'dragstart'); removeEventListener(sortableElement, 'dragend'); removeEventListener(sortableElement, 'drop'); // remove event data from sortable removeSortableData(sortableElement); // remove event handlers & data from items removeEventListener(handles, 'mousedown'); removeItemEvents(items); removeItemData(items); removeContainerEvents(originContainer, previousContainer); // clear sortable flag sortableElement.isSortable = false; }; /** * Enable the sortable * @param {HTMLElement} sortableElement a single sortable */ var enableSortable = function (sortableElement) { var opts = addData(sortableElement, 'opts'); var items = filter(sortableElement.children, opts.items); var handles = getHandles(items, opts.handle); addAttribute(sortableElement, 'aria-dropeffect', 'move'); addData(sortableElement, '_disabled', 'false'); addAttribute(handles, 'draggable', 'true'); // enable hover class enableHoverClass(sortableElement, true); // @todo: remove this fix // IE FIX for ghost // can be disabled as it has the side effect that other events // (e.g. click) will be ignored if (opts.disableIEFix === false) { var spanEl = (document || window.document).createElement('span'); if (typeof spanEl.dragDrop === 'function') { addEventListener(handles, 'mousedown', function () { if (items.indexOf(this) !== -1) { this.dragDrop(); } else { var parent = this.parentElement; while (items.indexOf(parent) === -1) { parent = parent.parentElement; } parent.dragDrop(); } }); } } }; /** * Disable the sortable * @param {HTMLElement} sortableElement a single sortable */ var disableSortable = function (sortableElement) { var opts = addData(sortableElement, 'opts'); var items = filter(sortableElement.children, opts.items); var handles = getHandles(items, opts.handle); addAttribute(sortableElement, 'aria-dropeffect', 'none'); addData(sortableElement, '_disabled', 'true'); addAttribute(handles, 'draggable', 'false'); removeEventListener(handles, 'mousedown'); enableHoverClass(sortableElement, false); }; /** * Reload the sortable * @param {HTMLElement} sortableElement a single sortable * @description events need to be removed to not be double bound */ var reloadSortable = function (sortableElement) { var opts = addData(sortableElement, 'opts'); var items = filter(sortableElement.children, opts.items); var handles = getHandles(items, opts.handle); addData(sortableElement, '_disabled', 'false'); // remove event handlers from items removeItemEvents(items); removeContainerEvents(originContainer, previousContainer); removeEventListener(handles, 'mousedown'); // remove event handlers from sortable removeEventListener(sortableElement, 'dragover'); removeEventListener(sortableElement, 'dragenter'); removeEventListener(sortableElement, 'drop'); }; /** * Public sortable object * @param {Array|NodeList} sortableElements * @param {object|string} options|method */ function sortable(sortableElements, options) { // get method string to see if a method is called var method = String(options); options = options || {}; // check if the user provided a selector instead of an element if (typeof sortableElements === 'string') { sortableElements = document.querySelectorAll(sortableElements); } // if the user provided an element, return it in an array to keep the return value consistant if (sortableElements instanceof HTMLElement) { sortableElements = [sortableElements]; } sortableElements = Array.prototype.slice.call(sortableElements); if (/serialize/.test(method)) { return sortableElements.map(function (sortableContainer) { var opts = addData(sortableContainer, 'opts'); return serialize(sortableContainer, opts.itemSerializer, opts.containerSerializer); }); } sortableElements.forEach(function (sortableElement) { if (/enable|disable|destroy/.test(method)) { return sortable[method](sortableElement); } // log deprecation ['connectWith', 'disableIEFix'].forEach(function (configKey) { if (Object.prototype.hasOwnProperty.call(options, configKey) && options[configKey] !== null) { console.warn("HTML5Sortable: You are using the deprecated configuration \"" + configKey + "\". This will be removed in an upcoming version, make sure to migrate to the new options when updating."); } }); // merge options with default options options = Object.assign({}, defaultConfiguration, store(sortableElement).config, options); // init data store for sortable store(sortableElement).config = options; // set options on sortable addData(sortableElement, 'opts', options); // property to define as sortable sortableElement.isSortable = true; // reset sortable reloadSortable(sortableElement); // initialize var listItems = filter(sortableElement.children, options.items); // create element if user defined a placeholder element as a string var customPlaceholder; if (options.placeholder !== null && options.placeholder !== undefined) { var tempContainer = document.createElement(sortableElement.tagName); if (options.placeholder instanceof HTMLElement) { tempContainer.appendChild(options.placeholder); } else { tempContainer.innerHTML = options.placeholder; } customPlaceholder = tempContainer.children[0]; } // add placeholder store(sortableElement).placeholder = makePlaceholder(sortableElement, customPlaceholder, options.placeholderClass); addData(sortableElement, 'items', options.items); if (options.acceptFrom) { addData(sortableElement, 'acceptFrom', options.acceptFrom); } else if (options.connectWith) { addData(sortableElement, 'connectWith', options.connectWith); } enableSortable(sortableElement); addAttribute(listItems, 'role', 'option'); addAttribute(listItems, 'aria-grabbed', 'false'); /* Handle drag events on draggable items Handle is set at the sortableElement level as it will bubble up from the item */ addEventListener(sortableElement, 'dragstart', function (e) { // ignore dragstart events var target = getEventTarget(e); if (target.isSortable === true) { return; } e.stopImmediatePropagation(); if ((options.handle && !target.matches(options.handle)) || target.getAttribute('draggable') === 'false') { return; } var sortableContainer = findSortable(target, e); var dragItem = findDragElement(sortableContainer, target); // grab values originItemsBeforeUpdate = filter(sortableContainer.children, options.items); originIndex = originItemsBeforeUpdate.indexOf(dragItem); originElementIndex = getIndex(dragItem, sortableContainer.children); originContainer = sortableContainer; // add transparent clone or other ghost to cursor setDragImage(e, dragItem, options.customDragImage); // cache selsection & add attr for dragging draggingHeight = getElementHeight(dragItem); draggingWidth = getElementWidth(dragItem); dragItem.classList.add(options.draggingClass); dragging = getDragging(dragItem, sortableContainer); addAttribute(dragging, 'aria-grabbed', 'true'); // dispatch sortstart event on each element in group sortableContainer.dispatchEvent(new CustomEvent('sortstart', { detail: { origin: { elementIndex: originElementIndex, index: originIndex, container: originContainer }, item: dragging, originalTarget: target } })); }); /* We are capturing targetSortable before modifications with 'dragenter' event */ addEventListener(sortableElement, 'dragenter', function (e) { var target = getEventTarget(e); var sortableContainer = findSortable(target, e); if (sortableContainer && sortableContainer !== previousContainer) { destinationItemsBeforeUpdate = filter(sortableContainer.children, addData(sortableContainer, 'items')) .filter(function (item) { return item !== store(sortableElement).placeholder; }); if (options.dropTargetContainerClass) { sortableContainer.classList.add(options.dropTargetContainerClass); } sortableContainer.dispatchEvent(new CustomEvent('sortenter', { detail: { origin: { elementIndex: originElementIndex, index: originIndex, container: originContainer }, destination: { container: sortableContainer, itemsBeforeUpdate: destinationItemsBeforeUpdate }, item: dragging, originalTarget: target } })); addEventListener(sortableContainer, 'dragleave', function (e) { // TODO: rename outTarget to be more self-explanatory // e.fromElement for very old browsers, similar to relatedTarget var outTarget = e.relatedTarget || e.fromElement; if (!e.currentTarget.contains(outTarget)) { if (options.dropTargetContainerClass) { sortableContainer.classList.remove(options.dropTargetContainerClass); } sortableContainer.dispatchEvent(new CustomEvent('sortleave', { detail: { origin: { elementIndex: originElementIndex, index: originIndex, container: sortableContainer }, item: dragging, originalTarget: target } })); } }); } previousContainer = sortableContainer; }); /* * Dragend Event - https://developer.mozilla.org/en-US/docs/Web/Events/dragend * Fires each time dragEvent end, or ESC pressed * We are using it to clean up any draggable elements and placeholders */ addEventListener(sortableElement, 'dragend', function (e) { if (!dragging) { return; } dragging.classList.remove(options.draggingClass); addAttribute(dragging, 'aria-grabbed', 'false'); if (dragging.getAttribute('aria-copied') === 'true' && addData(dragging, 'dropped') !== 'true') { dragging.remove(); } dragging.style.display = dragging.oldDisplay; delete dragging.oldDisplay; var visiblePlaceholder = Array.from(stores.values()).map(function (data) { return data.placeholder; }) .filter(function (placeholder) { return placeholder instanceof HTMLElement; }) .filter(isInDom)[0]; if (visiblePlaceholder) { visiblePlaceholder.remove(); } // dispatch sortstart event on each element in group sortableElement.dispatchEvent(new CustomEvent('sortstop', { detail: { origin: { elementIndex: originElementIndex, index: originIndex, container: originContainer }, item: dragging } })); previousContainer = null; dragging = null; draggingHeight = null; draggingWidth = null; }); /* * Drop Event - https://developer.mozilla.org/en-US/docs/Web/Events/drop * Fires when valid drop target area is hit */ addEventListener(sortableElement, 'drop', function (e) { if (!listsConnected(sortableElement, dragging.parentElement)) { return; } e.preventDefault(); e.stopPropagation(); addData(dragging, 'dropped', 'true'); // get the one placeholder that is currently visible var visiblePlaceholder = Array.from(stores.values()).map(function (data) { return data.placeholder; }) // filter only HTMLElements .filter(function (placeholder) { return placeholder instanceof HTMLElement; }) // only elements in DOM .filter(isInDom)[0]; if (visiblePlaceholder) { // attach element after placeholder insertAfter(visiblePlaceholder, dragging); // remove placeholder from dom visiblePlaceholder.remove(); } else { // set the dropped value to 'false' to delete copied dragging at the time of 'dragend' addData(dragging, 'dropped', 'false'); return; } /* * Fires Custom Event - 'sortstop' */ sortableElement.dispatchEvent(new CustomEvent('sortstop', { detail: { origin: { elementIndex: originElementIndex, index: originIndex, container: originContainer }, item: dragging } })); var placeholder = store(sortableElement).placeholder; var originItems = filter(originContainer.children, options.items) .filter(function (item) { return item !== placeholder; }); var destinationContainer = this.isSortable === true ? this : this.parentElement; var destinationItems = filter(destinationContainer.children, addData(destinationContainer, 'items')) .filter(function (item) { return item !== placeholder; }); var destinationElementIndex = getIndex(dragging, Array.from(dragging.parentElement.children) .filter(function (item) { return item !== placeholder; })); var destinationIndex = getIndex(dragging, destinationItems); if (options.dropTargetContainerClass) { destinationContainer.classList.remove(options.dropTargetContainerClass); } /* * When a list item changed container lists or index within a list * Fires Custom Event - 'sortupdate' */ if (originElementIndex !== destinationElementIndex || originContainer !== destinationContainer) { sortableElement.dispatchEvent(new CustomEvent('sortupdate', { detail: { origin: { elementIndex: originElementIndex, index: originIndex, container: originContainer, itemsBeforeUpdate: originItemsBeforeUpdate, items: originItems }, destination: { index: destinationIndex, elementIndex: destinationElementIndex, container: destinationContainer, itemsBeforeUpdate: destinationItemsBeforeUpdate, items: destinationItems }, item: dragging } })); } }); var debouncedDragOverEnter = debounce(function (sortableElement, element, pageX, pageY) { if (!dragging) { return; } // set placeholder height if forcePlaceholderSize option is set if (options.forcePlaceholderSize) { store(sortableElement).placeholder.style.height = draggingHeight + 'px'; store(sortableElement).placeholder.style.width = draggingWidth + 'px'; } // if element the draggedItem is dragged onto is within the array of all elements in list // (not only items, but also disabled, etc.) if (Array.from(sortableElement.children).indexOf(element) > -1) { var thisHeight = getElementHeight(element); var thisWidth = getElementWidth(element); var placeholderIndex = getIndex(store(sortableElement).placeholder, element.parentElement.children); var thisIndex = getIndex(element, element.parentElement.children); // Check if `element` is bigger than the draggable. If it is, we have to define a dead zone to prevent flickering if (thisHeight > draggingHeight || thisWidth > draggingWidth) { // Dead zone? var deadZoneVertical = thisHeight - draggingHeight; var deadZoneHorizontal = thisWidth - draggingWidth; var offsetTop = offset(element).top; var offsetLeft = offset(element).left; if (placeholderIndex < thisIndex && ((options.orientation === 'vertical' && pageY < offsetTop) || (options.orientation === 'horizontal' && pageX < offsetLeft))) { return; } if (placeholderIndex > thisIndex && ((options.orientation === 'vertical' && pageY > offsetTop + thisHeight - deadZoneVertical) || (options.orientation === 'horizontal' && pageX > offsetLeft + thisWidth - deadZoneHorizontal))) { return; } } if (dragging.oldDisplay === undefined) { dragging.oldDisplay = dragging.style.display; } if (dragging.style.display !== 'none') { dragging.style.display = 'none'; } // To avoid flicker, determine where to position the placeholder // based on where the mouse pointer is relative to the elements // vertical center. var placeAfter = false; try { var elementMiddleVertical = offset(element).top + element.offsetHeight / 2; var elementMiddleHorizontal = offset(element).left + element.offsetWidth / 2; placeAfter = (options.orientation === 'vertical' && (pageY >= elementMiddleVertical)) || (options.orientation === 'horizontal' && (pageX >= elementMiddleHorizontal)); } catch (e) { placeAfter = placeholderIndex < thisIndex; } if (placeAfter) { insertAfter(element, store(sortableElement).placeholder); } else { insertBefore(element, store(sortableElement).placeholder); } // get placeholders from all stores & remove all but current one Array.from(stores.values()) // remove empty values .filter(function (data) { return data.placeholder !== undefined; }) // foreach placeholder in array if outside of current sorableContainer -> remove from DOM .forEach(function (data) { if (data.placeholder !== store(sortableElement).placeholder) { data.placeholder.remove(); } }); } else { // get all placeholders from store var placeholders = Array.from(stores.values()) .filter(function (data) { return data.placeholder !== undefined; }) .map(function (data) { return data.placeholder; }); // check if element is not in placeholders if (placeholders.indexOf(element) === -1 && sortableElement === element && !filter(element.children, options.items).length) { placeholders.forEach(function (element) { return element.remove(); }); element.appendChild(store(sortableElement).placeholder); } } }, options.debounce); // Handle dragover and dragenter events on draggable items var onDragOverEnter = function (e) { var element = e.target; var sortableElement = element.isSortable === true ? element : findSortable(element, e); element = findDragElement(sortableElement, element); if (!dragging || !listsConnected(sortableElement, dragging.parentElement) || addData(sortableElement, '_disabled') === 'true') { return; } var options = addData(sortableElement, 'opts'); if (parseInt(options.maxItems) && filter(sortableElement.children, addData(sortableElement, 'items')).length > parseInt(options.maxItems) && dragging.parentElement !== sortableElement) { return; } e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = store(sortableElement).getConfig('copy') === true ? 'copy' : 'move'; debouncedDragOverEnter(sortableElement, element, e.pageX, e.pageY); }; addEventListener(listItems.concat(sortableElement), 'dragover', onDragOverEnter); addEventListener(listItems.concat(sortableElement), 'dragenter', onDragOverEnter); }); return sortableElements; } sortable.destroy = function (sortableElement) { destroySortable(sortableElement); }; sortable.enable = function (sortableElement) { enableSortable(sortableElement); }; sortable.disable = function (sortableElement) { disableSortable(sortableElement); }; /* START.TESTS_ONLY */ sortable.__testing = { // add internal methods here for testing purposes data: addData, removeItemEvents: removeItemEvents, removeItemData: removeItemData, removeSortableData: removeSortableData, removeContainerEvents: removeContainerEvents }; return sortable; }());
(function () { const form = document.querySelector('form') const url = form.querySelector('input[name="url"]') const short = form.querySelector('input[name="short"]') const share = form.querySelector('button.share') if (navigator.serviceWorker && !navigator.serviceWorker.controller) { navigator.serviceWorker.register('sw.js', { scope: './' }) } if (navigator.share) { share.addEventListener('click', async (e) => { try { await navigator.share({ url: short.value }) } catch (err) { console.error(err) } }) } else { share.parentElement.removeChild(share) } form.addEventListener('submit', async (e) => { e.preventDefault() form.classList.add('loading') url.readOnly = true short.style.visibility = 'hidden' short.value = '' share.style.visibility = 'hidden' try { const response = await window.fetch('/', { method: 'POST', mode: 'same-origin', cache: 'no-cache', headers: new window.Headers({ 'Content-Type': 'application/json' }), body: JSON.stringify({ url: url.value }) }) const json = await response.json() share.style.visibility = 'visible' short.style.visibility = 'visible' short.value = json.short short.select() url.readOnly = false url.value = '' } catch (err) { console.error(err) } finally { form.classList.remove('loading') } }) })()
define("ace/mode/sh_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var reservedKeywords = exports.reservedKeywords = ( '!|{|}|case|do|done|elif|else|'+ 'esac|fi|for|if|in|then|until|while|'+ '&|;|export|local|read|typeset|unset|'+ 'elif|select|set' ); var languageConstructs = exports.languageConstructs = ( '[|]|alias|bg|bind|break|builtin|'+ 'cd|command|compgen|complete|continue|'+ 'dirs|disown|echo|enable|eval|exec|'+ 'exit|fc|fg|getopts|hash|help|history|'+ 'jobs|kill|let|logout|popd|printf|pushd|'+ 'pwd|return|set|shift|shopt|source|'+ 'suspend|test|times|trap|type|ulimit|'+ 'umask|unalias|wait' ); var ShHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "keyword": reservedKeywords, "support.function.builtin": languageConstructs, "invalid.deprecated": "debugger" }, "identifier"); var integer = "(?:(?:[1-9]\\d*)|(?:0))"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + ")"; var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")"; var fileDescriptor = "(?:&" + intPart + ")"; var variableName = "[a-zA-Z_][a-zA-Z0-9_]*"; var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))"; var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))"; var func = "(?:" + variableName + "\\s*\\(\\))"; this.$rules = { "start" : [{ token : "constant", regex : /\\./ }, { token : ["text", "comment"], regex : /(^|\s)(#.*)$/ }, { token : "string", regex : '"', push : [{ token : "constant.language.escape", regex : /\\(?:[$abeEfnrtv\\'"]|x[a-fA-F\d]{1,2}|u[a-fA-F\d]{4}([a-fA-F\d]{4})?|c.|\d{1,3})/ }, { token : "constant", regex : /\$\w+/ }, { token : "string", regex : '"', next: "pop" }, { defaultToken: "string" }] }, { regex : "<<<", token : "keyword.operator" }, { stateName: "heredoc", regex : "(<<)(\\s*)(['\"`]?)([\\w\\-]+)(['\"`]?)", onMatch : function(value, currentState, stack) { var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; var tokens = value.split(this.splitRegex); stack.push(next, tokens[4]); return [ {type:"constant", value: tokens[1]}, {type:"text", value: tokens[2]}, {type:"string", value: tokens[3]}, {type:"support.class", value: tokens[4]}, {type:"string", value: tokens[5]} ]; }, rules: { heredoc: [{ onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }], indentedHeredoc: [{ token: "string", regex: "^\t+" }, { onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }] } }, { regex : "$", token : "empty", next : function(currentState, stack) { if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") return stack[0]; return currentState; } }, { token : "variable.language", regex : builtinVariable }, { token : "variable", regex : variable }, { token : "support.function", regex : func }, { token : "support.function", regex : fileDescriptor }, { token : "string", // ' string start : "'", end : "'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : keywordMapper, regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!=" }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" } ] }; this.normalizeRules(); }; oop.inherits(ShHighlightRules, TextHighlightRules); exports.ShHighlightRules = ShHighlightRules; }); define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; }).call(FoldMode.prototype); }); define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return { text: '{' + selected + '}', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '(' + selected + ')', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return { text: '[' + selected + ']', selection: false }; } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } else { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); if (leftChar == '\\') { return null; } var tokens = session.getTokens(selection.start.row); var col = 0, token; var quotepos = -1; // Track whether we're inside an open quote. for (var x = 0; x < tokens.length; x++) { token = tokens[x]; if (token.type == "string") { quotepos = -1; } else if (quotepos < 0) { quotepos = token.value.indexOf(quote); } if ((token.value.length + col) > selection.start.column) { break; } col += tokens[x].value.length; } if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) { if (!CstyleBehaviour.isSaneInsertion(editor, session)) return; return { text: quote + quote, selection: [1,1] }; } else if (token && token.type === "string") { var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == quote) { return { text: '', selection: [1, 1] }; } } } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); define("ace/mode/sh",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/sh_highlight_rules","ace/range","ace/mode/folding/cstyle","ace/mode/behaviour/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules; var Range = require("../range").Range; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var Mode = function() { this.HighlightRules = ShHighlightRules; this.foldingRules = new CStyleFoldMode(); this.$behaviour = new CstyleBehaviour(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } return indent; }; var outdents = { "pass": 1, "return": 1, "raise": 1, "break": 1, "continue": 1 }; this.checkOutdent = function(state, line, input) { if (input !== "\r\n" && input !== "\r" && input !== "\n") return false; var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens; if (!tokens) return false; do { var last = tokens.pop(); } while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/)))); if (!last) return false; return (last.type == "keyword" && outdents[last.value]); }; this.autoOutdent = function(state, doc, row) { row += 1; var indent = this.$getIndent(doc.getLine(row)); var tab = doc.getTabString(); if (indent.slice(-tab.length) == tab) doc.remove(new Range(row, indent.length-tab.length, row, indent.length)); }; this.$id = "ace/mode/sh"; }).call(Mode.prototype); exports.Mode = Mode; });
'use strict'; module.exports = async (ctx) => { const name = ctx.params.name; ctx.body = `/home/user name = ${name}`; };
myapp.controller('CalendarController', function($scope) { //ons.ready(function() { console.log("CalendarController is ready!"); //}); });
import React from 'react'; import TestUtils from 'react-dom/test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.props.getValue()} readOnly/>; } }); class TestForm extends React.Component { render() { return ( <Formsy> <TestInput name="foo" validations={this.props.rule} value={this.props.inputValue}/> </Formsy> ); } } export default { 'minLength:3': { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass when a string\'s length is bigger': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue="myValue"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail when a string\'s length is smaller': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue="my"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:3" inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); } }, 'minLength:0': { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:0"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass when a string\'s length is bigger': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:0" inputValue="myValue"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:0" inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with an undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:0" inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with a null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:0" inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="minLength:0" inputValue={42}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); } } };
function(head, req) { var template = require('vendor/mustache.couch').compile(this, 'notes', {rows_tag: 'notes', rows_only: req.query.rows_only} ); template.stream({title: 'Notes', update_seq: req.info.update_seq}, function(row) { var doc = row.value; doc.key = JSON.stringify(row.key); return doc; }); }
export {default as counters} from './counters'
#!/usr/bin/env node var fs = require('fs') , ejs = require('ejs') , inquirer = require("inquirer") , args = process.argv.slice(1) , dir = args[1] || process.cwd(); // 判断目录是否存在 fs.exists(dir, cb_dirExists); function cb_dirExists(exists) { if (exists) { // 判断__demolist文件是否已存在 fs.exists(dir + '/__demolist.html', cb_listExists); } else { console.log('指定的目录不存在:' + dir); } } function cb_listExists(exists) { if (exists) { // 询问用户是否覆盖 inquirer.prompt([ { type:'confirm', name: 'replace', message: '__demolist.html文件已存在,是否替换?', default: true}, ], function(answers) { answers.replace && create(); }); } else { create(); } } function create() { // 获取基本信息 inquirer.prompt([ { name: 'name', message: '项目名称:'}, { name: 'author', message: '作者姓名:', default: '前端开发部'}, { name: 'date', message: '起止日期:'}, { name: 'psd', message: '设计稿地址:'}, { name: 'memo', message: '备注:', default: '无备注'} ], function(answers) { require('./sndemolist')(dir, answers); }); }
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['1584',"Tlece.Recruitment.Models.Account Namespace","topic_0000000000000534.html"],['1603',"VerifyPhoneNumberModel Class","topic_0000000000000543.html"],['1604',"Properties","topic_0000000000000543_props--.html"]];
const appNameToLoad = process.argv[process.argv.findIndex( function(value) { return value.indexOf('--content-base') > -1 } ) + 1]; if(appNameToLoad === 'ui-jar') { module.exports = require('./config/webpack.ui-jar.js'); } else { module.exports = require('./config/webpack.dev.js'); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RowCheckbox = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var RowCheckbox = /*#__PURE__*/function (_Component) { _inherits(RowCheckbox, _Component); var _super = _createSuper(RowCheckbox); function RowCheckbox(props) { var _this; _classCallCheck(this, RowCheckbox); _this = _super.call(this, props); _this.state = {}; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowCheckbox, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick && !this.props.disabled) { this.props.onClick({ originalEvent: event, data: this.props.rowData, checked: this.props.selected }); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var className = (0, _classnames.default)('p-checkbox-box p-component', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClassName = (0, _classnames.default)('p-checkbox-icon p-clickable', { 'pi pi-check': this.props.selected }); return /*#__PURE__*/_react.default.createElement("div", { className: "p-checkbox p-component", onClick: this.onClick }, /*#__PURE__*/_react.default.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/_react.default.createElement("input", { type: "checkbox", defaultChecked: this.props.selected, disabled: this.props.disabled, "aria-checked": this.props.selected, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur })), /*#__PURE__*/_react.default.createElement("div", { className: className, role: "checkbox", "aria-checked": this.props.selected }, /*#__PURE__*/_react.default.createElement("span", { className: iconClassName }))); } }]); return RowCheckbox; }(_react.Component); exports.RowCheckbox = RowCheckbox; _defineProperty(RowCheckbox, "defaultProps", { rowData: null, onClick: null, disabled: false }); _defineProperty(RowCheckbox, "propTypes", { rowData: _propTypes.default.object, onClick: _propTypes.default.func, disabled: _propTypes.default.bool });
var config = require('../config'); var handler = require('./responsehandler'); var request = require('superagent'); var root = '/auth'; function getDevToken(callback) { request .get(config.host+root+'/getDevToken') .set('x-dev-token', config.token) .end(handler(callback)); } function newDevToken(callback) { request .get(config.host+root+'/newDevToken') .set('x-dev-token', config.token) .end(handler(callback)); } module.exports = { getDevToken : getDevToken, newDevToken : newDevToken };
(function($) { $.extend($,{ placeholder: { browser_supported: function() { return this._supported !== undefined ? this._supported : ( this._supported = !!('placeholder' in $('<input type="text">')[0]) ); }, shim: function(opts) { var config = { color: '#888', cls: '', lr_padding:4, selector: 'input[placeholder], textarea[placeholder]' }; $.extend(config,opts); !this.browser_supported() && $(config.selector)._placeholder_shim(config); } }}); $.extend($.fn,{ _placeholder_shim: function(config) { function calcPositionCss(target) { var op = $(target).offsetParent().offset(); var ot = $(target).offset(); return { top: ot.top - op.top + ($(target).outerHeight() - $(target).height()) /2, left: ot.left - op.left + config.lr_padding, width: $(target).width() - config.lr_padding }; } return this.each(function() { if( $(this).data('placeholder') ) { var $ol = $(this).data('placeholder'); $ol.css(calcPositionCss($(this))); return true; } var ol = $('<label />') .text($(this).attr('placeholder')) .addClass(config.cls) .css({ position:'absolute', display: 'inline', float:'none', overflow:'hidden', whiteSpace:'nowrap', textAlign: 'left', color: config.color, cursor: 'text', fontSize: $(this).css('font-size') }) .css(calcPositionCss(this)) .attr('for', this.id) .data('target',$(this)) .click(function(){ $(this).data('target').focus() }) .insertBefore(this); $(this) .data('placeholder',ol) .focus(function(){ ol.hide(); }).blur(function() { ol[$(this).val().length ? 'hide' : 'show'](); }).triggerHandler('blur'); $(window) .resize(function() { var $target = ol.data('target') ol.css(calcPositionCss($target)) }); }); } }); })(jQuery); $(document).ready(function() { if ($.placeholder) { $.placeholder.shim(); } });
var assert = require('assert'); var PO = require('..'); describe('Headers', function () { var po; before(function (done) { PO.load(__dirname + '/fixtures/big.po', function (err, result) { assert.equal(err, null); po = result; done(); }); }); it('Parses the po file', function () { assert.notEqual(po, null); }); it('Parses headers correctly', function () { assert.equal(po.headers['Project-Id-Version'], 'Link (6.x-2.9)'); assert.equal(po.headers['MIME-Version'], '1.0'); assert.equal(po.headers['Plural-Forms'], 'nplurals=2; plural=(n > 1);'); }); it('Parses all headers', function () { // There are 11 headers in the .po file, but some default headers // are defined (nr. 12 in this case is Report-Msgid-Bugs-To). assert.equal(Object.keys(po.headers).length, 12); }); }); describe('PO files with no headers', function () { it('Parses an empty string', function () { var po = PO.parse(''); assert.notEqual(po, null); // all headers should be empty for (var key in po.headers) { assert.equal(po.headers[key], ''); } assert.equal(po.items.length, 0); }); it('Parses a minimal example', function () { var po = PO.parse('msgid "minimal PO"\nmsgstr ""'); assert.notEqual(po, null); // all headers should be empty for (var key in po.headers) { assert.equal(po.headers[key], ''); } assert.equal(po.items.length, 1); }); describe('advanced example', function () { var po; before(function (done) { PO.load(__dirname + '/fixtures/no_header.po', function (err, result) { assert.equal(err, null); po = result; done(); }); }); it('Parses the po file', function () { assert.notEqual(po, null); }); it('Finds all items', function () { assert.equal(po.items.length, 2); }); }); describe('advanced example with extra spaces', function () { var po; before(function (done) { PO.load(__dirname + '/fixtures/no_header_extra_spaces.po', function (err, result) { assert.equal(err, null); po = result; done(); }); }); it('Parses the po file', function () { assert.notEqual(po, null); }); it('Finds all items', function () { assert.equal(po.items.length, 2); }); }); });
(function () { TRAFFICSIM_APP.game = TRAFFICSIM_APP.game || {}; TRAFFICSIM_APP.game.road_route_bezier_curve = TRAFFICSIM_APP.game.road_route_bezier_curve || {}; var NS = TRAFFICSIM_APP.game.road_route_bezier_curve; NS.RoadRouteBezierCurve = function (worldController, road, startNode, endNode, controlPoints) { this._controlPoints = controlPoints; TRAFFICSIM_APP.game.road_route.RoadRoute.call(this, worldController, road, startNode, endNode); }; NS.RoadRouteBezierCurve.prototype = Object.create(TRAFFICSIM_APP.game.road_route.RoadRoute.prototype); /** t is a value between 0-1. 0 returns the starting point and 1 returns the ending point. * Anything between 0 and 1 returns a corresponding point in the bezier curve. */ NS.RoadRouteBezierCurve.prototype.getPointAtBezierCurve = function (t, x1, z1, x2, z2, cp1x, cp1z, cp2x, cp2z) { var x = Math.pow(1 - t, 3) * x1 + 3 * Math.pow(1 - t, 2) * t * cp1x + 3 * (1 - t) * Math.pow(t, 2) * cp2x + Math.pow(t, 3) * x2; var z = Math.pow(1 - t, 3) * z1 + 3 * Math.pow(1 - t, 2) * t * cp1z + 3 * (1 - t) * Math.pow(t, 2) * cp2z + Math.pow(t, 3) * z2; return new TRAFFICSIM_APP.utils.vector3.Vector3(x, 0, z); }; /** Given coordinates x and z, returns an approximate T which corresponds the closest point at bezier curve. * The more you give accuracy the more accurate the found point in the curve will be but the calculation will also be slower. * Recommended value is 30. */ NS.RoadRouteBezierCurve.prototype.getTAtBezierCurve = function (x, z, accuracy) { // This might not be the most optimized way to do this, but it works reasonably well for this application. // Divide the curve in to n points. n is the same as the accuracy variable. var curvePoints = []; var step = 1 / accuracy; for (var i = 0; i <= 1; i = i + step) { curvePoints.push({ "t": i, "position": this.getPointAtBezierCurve( i, this.startNode.position.x, this.startNode.position.z, this.endNode.position.x, this.endNode.position.z, this._controlPoints[0].x, this._controlPoints[0].z, this._controlPoints[1].x, this._controlPoints[1].z) } ); } // Find the closest point var closesPointDistance = Number.MAX_VALUE; var closesPoint = null; curvePoints.forEach(function (point) { var distance = TRAFFICSIM_APP.utils.math.distance(x, 0, z, point.position.x, 0, point.position.z); if (distance < closesPointDistance) { closesPointDistance = distance; closesPoint = point; } }); return closesPoint.t; }; /** Returns the next x and y coordinates on the bezier curve. * currentT = Current point at bezier curve * step = How much T is incremented to resolve the next point */ NS.RoadRouteBezierCurve.prototype.getNextPointAtBezierCurve = function (currentT, step) { var nextT = currentT + step; if (nextT <= 0) { return this.startNode.position; } if (nextT >= 1) { return this.endNode.position; } return this.getPointAtBezierCurve( nextT, this.startNode.position.x, this.startNode.position.z, this.endNode.position.x, this.endNode.position.z, this._controlPoints[0].x, this._controlPoints[0].z, this._controlPoints[1].x, this._controlPoints[1].z) }; /** Returns a approximate length of the bezier curve starting from t. If t is not given, it defaults to 0. * The more you give accuracy the more accurate the result will be but the calculation will also be slower. * Recommended value is 30. */ NS.RoadRouteBezierCurve.prototype.getCurveLength = function (accuracy, t) { // This might not be the most optimized way to do this, but it works reasonably well for this application. // Divide the curve in to n points. n is the same as the accuracy variable. var curvePoints = []; var step = 1 / accuracy; for (var i = t || 0; i <= 1; i = i + step) { curvePoints.push({ "position": this.getPointAtBezierCurve( i, this.startNode.position.x, this.startNode.position.z, this.endNode.position.x, this.endNode.position.z, this._controlPoints[0].x, this._controlPoints[0].z, this._controlPoints[1].x, this._controlPoints[1].z) } ); } // Calculate distance between points var sum = 0; for (var j = 0; j < curvePoints.length - 1; j++) { var current = curvePoints[j]; var next = curvePoints[j + 1]; sum += TRAFFICSIM_APP.utils.math.distance(current.position.x, 0, current.position.z, next.position.x, 0, next.position.z) } return sum; }; /** Returns a point which is a bit more near the end point than the given point. */ NS.RoadRouteBezierCurve.prototype.getNextPoint = function (position) { return this.getNextPointAtBezierCurve(this.getTAtBezierCurve(position.x, position.z, 30), 0.05); }; /** Returns a point which is the given distance near the end point starting from the given position. */ NS.RoadRouteBezierCurve.prototype.getNextPointAtDistance = function (position, distance) { return this.getNextPointAtBezierCurve(this.getTAtBezierCurve(position.x, position.z, 30), distance / this.getCurveLength(30)); }; /** Returns a point which is the given distance near the end point starting from the given position. * If the calculated next point goes over the end point, continues using the given nextRoute */ NS.RoadRouteBezierCurve.prototype.getNextPointAtDistanceOrContinue = function (position, distance, nextRoute) { var distanceToEnd = this.getCurveLength(30, this.getTAtBezierCurve(position.x, position.z, 30)); if (distance > distanceToEnd) { if (nextRoute) { return nextRoute.getNextPointAtDistanceOrContinue( nextRoute.startNode.position, distance - distanceToEnd, null); } return this.endNode.position; } return this.getNextPointAtDistance(position, distance); }; })();
/** * Copyright: (c) 2018 Max Klein * License: MIT */ define([ 'sim/Component', 'ComponentRegistry', 'shared/lib/extend' ], function (Component, ComponentRegistry, extend) { function BufferComponent() { Component.call(this); this.in = [false]; this.out = [false]; } extend(BufferComponent, Component); BufferComponent.prototype.exec = function () { this.out[0] = this.in[0]; }; ComponentRegistry.register('buffer', BufferComponent); return BufferComponent; });
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var testing_1 = require('@angular/core/testing'); var testing_2 = require('@angular/compiler/testing'); var core_1 = require('@angular/core'); var todo_model_1 = require('./todo.model'); var todolist_component_1 = require('./todolist.component'); var forms_1 = require('@angular/forms'); var TestComponent = (function () { function TestComponent() { } TestComponent = __decorate([ core_1.Component({ selector: 'as-test', template: '<as-todolist></as-todolist>', directives: [todolist_component_1.TodolistComponent] }), __metadata('design:paramtypes', []) ], TestComponent); return TestComponent; }()); var testFixture; var todoCompiled; var todolistCmp; testing_1.describe('TodolistComponent', function () { testing_1.beforeEachProviders(function () { return [ forms_1.disableDeprecatedForms(), forms_1.provideForms() ]; }); testing_1.it('should have been created successfully', testing_1.async(testing_1.inject([testing_2.TestComponentBuilder], function (tcb) { tcb.createAsync(TestComponent).then(function (fixture) { testFixture = fixture; fixture.detectChanges(); todoCompiled = fixture.nativeElement; todolistCmp = fixture.debugElement .children[0].componentInstance; testing_1.expect(todoCompiled).toBeDefined(); }); }))); testing_1.it('should add todo successfully', function () { todolistCmp.todo = new todo_model_1.Todo('test', true); todolistCmp.addTodo(); testFixture.detectChanges(); var items = todoCompiled.querySelectorAll('.list-group-item'); testing_1.expect(items.length).toEqual(3); var item = items[items.length - 1]; testing_1.expect(item.querySelector('label').textContent).toEqual(' test'); testing_1.expect(item.querySelector('input[type="checkbox"]').checked).toBeTruthy(); }); testing_1.it('should delete todo successfully', function () { todolistCmp.delTodo(0); testFixture.detectChanges(); testing_1.expect(todoCompiled.querySelectorAll('.list-group-item').length) .toEqual(2); }); }); //# sourceMappingURL=todolist.component.spec.js.map
// o--------------------------------------------------------------------------------o // | This file is part of the RGraph package - you can learn more at: | // | | // | https://www.rgraph.net | // | | // | RGraph is licensed under the Open Source MIT license. That means that it's | // | totally free to use and there are no restrictions on what you can do with it! | // o--------------------------------------------------------------------------------o RGraph = window.RGraph || {isrgraph:true,isRGraph:true,rgraph:true}; RGraph.SVG = RGraph.SVG || {}; // Module pattern (function (win, doc, undefined) { RGraph.SVG.Bar = function (conf) { // // A setter that the constructor uses (at the end) // to set all of the properties // // @param string name The name of the property to set // @param string value The value to set the property to // this.set = function (name, value) { if (arguments.length === 1 && typeof name === 'object') { for (i in arguments[0]) { if (typeof i === 'string') { name = ret.name; value = ret.value; this.set(name, value); } } } else { var ret = RGraph.SVG.commonSetter({ object: this, name: name, value: value }); name = ret.name; value = ret.value; this.properties[name] = value; // If setting the colors, update the originalColors // property too if (name === 'colors') { this.originalColors = RGraph.SVG.arrayClone(value); this.colorsParsed = false; } } return this; }; // // A getter. // // @param name string The name of the property to get // this.get = function (name) { return this.properties[name]; }; this.id = conf.id; this.uid = RGraph.SVG.createUID(); this.container = document.getElementById(this.id); this.layers = {}; // MUST be before the SVG tag is created! this.svg = RGraph.SVG.createSVG({object: this,container: this.container}); this.isRGraph = true; this.isrgraph = true; this.rgraph = true; this.data = conf.data; this.type = 'bar'; this.coords = []; this.coords2 = []; this.stackedBackfaces = []; this.originalColors = {}; this.gradientCounter = 1; this.firstDraw = true; // After the first draw this will be false // Convert strings to numbers this.data = RGraph.SVG.stringsToNumbers(this.data); // Add this object to the ObjectRegistry RGraph.SVG.OR.add(this); this.container.style.display = 'inline-block'; this.properties = { marginLeft: 35, marginRight: 35, marginTop: 35, marginBottom: 35, variant: null, variant3dOffsetx: 10, variant3dOffsety: 5, backgroundColor: null, backgroundImage: null, backgroundImageAspect: 'none', backgroundImageStretch: true, backgroundImageOpacity: null, backgroundImageX: null, backgroundImageY: null, backgroundImageW: null, backgroundImageH: null, backgroundGrid: true, backgroundGridColor: '#ddd', backgroundGridLinewidth: 1, backgroundGridHlines: true, backgroundGridHlinesCount: null, backgroundGridVlines: true, backgroundGridVlinesCount: null, backgroundGridBorder: true, backgroundGridDashed: false, backgroundGridDotted: false, backgroundGridDashArray: null, // 20 colors. If you need more you need to set the colors property colors: [ 'red', '#0f0', '#00f', '#ff0', '#0ff', '#0f0','pink','orange','gray','black', 'red', '#0f0', '#00f', '#ff0', '#0ff', '#0f0','pink','orange','gray','black' ], colorsSequential: false, colorsStroke: 'rgba(0,0,0,0)', errorbars: null, marginInner: 3, marginInnerGrouped: 2, marginInnerLeft: 0, marginInnerRight: 0, yaxis: true, yaxisTickmarks: true, yaxisTickmarksLength: 3, yaxisColor: 'black', yaxisScale: true, yaxisLabels: null, yaxisLabelsFont: null, yaxisLabelsSize: null, yaxisLabelsColor: null, yaxisLabelsBold: null, yaxisLabelsItalic: null, yaxisLabelsOffsetx: 0, yaxisLabelsOffsety: 0, yaxisLabelsCount: 5, yaxisScaleUnitsPre: '', yaxisScaleUnitsPost: '', yaxisScaleStrict: false, yaxisScaleDecimals: 0, yaxisScalePoint: '.', yaxisScaleThousand: ',', yaxisScaleRound: false, yaxisScaleMax: null, yaxisScaleMin: 0, yaxisScaleFormatter: null, yaxisTitle: '', yaxisTitleBold: null, yaxisTitleSize: null, yaxisTitleFont: null, yaxisTitleColor: null, yaxisTitleItalic: null, yaxisTitleOffsetx: 0, yaxisTitleOffsety: 0, yaxisTitleX: null, yaxisTitleY: null, yaxisTitleHalign: null, yaxisTitleValign: null, xaxis: true, xaxisTickmarks: true, xaxisTickmarksLength: 5, xaxisLabels: null, xaxisLabelsFont: null, xaxisLabelsSize: null, xaxisLabelsColor: null, xaxisLabelsBold: null, xaxisLabelsItalic: null, xaxisLabelsPosition: 'section', xaxisLabelsPositionSectionTickmarksCount: null, xaxisLabelsOffsetx: 0, xaxisLabelsOffsety: 0, xaxisLabelsFormattedDecimals: 0, xaxisLabelsFormattedPoint: '.', xaxisLabelsFormattedThousand: ',', xaxisLabelsFormattedUnitsPre: '', xaxisLabelsFormattedUnitsPost: '', xaxisColor: 'black', xaxisTitle: '', xaxisTitleBold: null, xaxisTitleSize: null, xaxisTitleFont: null, xaxisTitleColor: null, xaxisTitleItalic: null, xaxisTitleOffsetx: 0, xaxisTitleOffsety: 0, xaxisTitleX: null, xaxisTitleY: null, xaxisTitleHalign: null, xaxisTitleValign: null, labelsAbove: false, labelsAboveFont: null, labelsAboveSize: null, labelsAboveBold: null, labelsAboveItalic: null, labelsAboveColor: null, labelsAboveBackground: null, labelsAboveBackgroundPadding: 0, labelsAboveUnitsPre: null, labelsAboveUnitsPost: null, labelsAbovePoint: null, labelsAboveThousand: null, labelsAboveFormatter: null, labelsAboveDecimals: null, labelsAboveOffsetx: 0, labelsAboveOffsety: 0, labelsAboveHalign: 'center', labelsAboveValign: 'bottom', labelsAboveSpecific: null, textColor: 'black', textFont: 'Arial, Verdana, sans-serif', textSize: 12, textBold: false, textItalic: false, linewidth: 1, grouping: 'grouped', tooltips: null, tooltipsOverride: null, tooltipsEffect: 'fade', tooltipsCssClass: 'RGraph_tooltip', tooltipsCss: null, tooltipsEvent: 'click', tooltipsFormattedThousand: ',', tooltipsFormattedPoint: '.', tooltipsFormattedDecimals: 0, tooltipsFormattedUnitsPre: '', tooltipsFormattedUnitsPost: '', tooltipsFormattedKeyColors: null, tooltipsFormattedKeyColorsShape: 'square', tooltipsFormattedKeyLabels: [], tooltipsFormattedTableHeaders: null, tooltipsFormattedTableData: null, tooltipsPointer: true, tooltipsPositionStatic: true, highlightStroke: 'rgba(0,0,0,0)', highlightFill: 'rgba(255,255,255,0.7)', highlightLinewidth: 1, title: '', titleX: null, titleY: null, titleHalign: 'center', //titleValign: null, titleSize: null, titleColor: null, titleFont: null, titleBold: null, titleItalic: null, titleSubtitle: null, titleSubtitleSize: null, titleSubtitleColor: '#aaa', titleSubtitleFont: null, titleSubtitleBold: null, titleSubtitleItalic: null, shadow: false, shadowOffsetx: 2, shadowOffsety: 2, shadowBlur: 2, shadowOpacity: 0.25, errorbars: null, errorbarsColor: 'black', errorbarsLinewidth: 1, errorbarsCapwidth: 10, key: null, keyColors: null, keyOffsetx: 0, keyOffsety: 0, keyLabelsOffsetx: 0, keyLabelsOffsety: -1, keyLabelsColor: null, keyLabelsSize: null, keyLabelsBold: null, keyLabelsItalic: null, keyLabelsFont: null }; // // Copy the global object properties to this instance // RGraph.SVG.getGlobals(this); // // "Decorate" the object with the generic effects if the effects library has been included // if (RGraph.SVG.FX && typeof RGraph.SVG.FX.decorate === 'function') { RGraph.SVG.FX.decorate(this); } // Add the responsive function to the object this.responsive = RGraph.SVG.responsive; // Add the create function to the object. The create() // function is defined in the SVG core library RGraph.SVG.addCreateFunction(this); // A shortcut var properties = this.properties; // // The draw method draws the Bar chart // this.draw = function () { // Fire the beforedraw event RGraph.SVG.fireCustomEvent(this, 'onbeforedraw'); // Should the first thing that's done inthe.draw() function // except for the onbeforedraw event this.width = Number(this.svg.getAttribute('width')); this.height = Number(this.svg.getAttribute('height')); // Zero these if the 3D effect is not wanted if (properties.variant !== '3d') { properties.variant3dOffsetx = 0; properties.variant3dOffsety = 0; } else { // Set the skew transform on the all group if necessary this.svg.all.setAttribute('transform', 'skewY(5)'); } // Create the defs tag if necessary RGraph.SVG.createDefs(this); // Reset the coords array this.coords = []; this.coords2 = []; this.graphWidth = this.width - properties.marginLeft - properties.marginRight; this.graphHeight = this.height - properties.marginTop - properties.marginBottom; // Make the data sequential first this.data_seq = RGraph.SVG.arrayLinearize(this.data); // This allows the errorbars to be a variety of formats and convert // them all into an array of objects which have the min and max // properties set if (properties.errorbars) { // Go through the error bars and convert numbers to objects for (var i=0; i<this.data_seq.length; ++i) { if (typeof properties.errorbars[i] === 'undefined' || RGraph.SVG.isNull(properties.errorbars[i]) ) { properties.errorbars[i] = {max: null, min: null}; } else if (typeof properties.errorbars[i] === 'number') { properties.errorbars[i] = { min: properties.errorbars[i], max: properties.errorbars[i] }; // Max is undefined } else if (typeof properties.errorbars[i] === 'object' && typeof properties.errorbars[i].max === 'undefined') { properties.errorbars[i].max = null; // Min is not defined } else if (typeof properties.errorbars[i] === 'object' && typeof properties.errorbars[i].min === 'undefined') { properties.errorbars[i].min = null; } } } // // Parse the colors. This allows for simple gradient syntax // // Parse the colors for gradients RGraph.SVG.resetColorsToOriginalValues({object:this}); this.parseColors(); // Go through the data and work out the maximum value // This now also accounts for errorbars var values = []; for (var i=0,max=0; i<this.data.length; ++i) { // Errorbars affect the max value if (properties.errorbars && typeof properties.errorbars[i] === 'number') { var errorbar = properties.errorbars[i]; } else if (properties.errorbars && typeof properties.errorbars[i] === 'object' && typeof properties.errorbars[i].max === 'number') { var errorbar = properties.errorbars[i].max; } else { var errorbar = 0; } if (typeof this.data[i] === 'number') { values.push(this.data[i] + errorbar); } else if (RGraph.SVG.isArray(this.data[i]) && properties.grouping === 'grouped') { values.push(RGraph.SVG.arrayMax(this.data[i]) + errorbar); } else if (RGraph.SVG.isArray(this.data[i]) && properties.grouping === 'stacked') { values.push(RGraph.SVG.arraySum(this.data[i]) + errorbar); } } var max = RGraph.SVG.arrayMax(values); // A custom, user-specified maximum value if (typeof properties.yaxisScaleMax === 'number') { max = properties.yaxisScaleMax; } // Set the ymin to zero if it's set mirror if (properties.yaxisScaleMin === 'mirror' || properties.yaxisScaleMin === 'middle' || properties.yaxisScaleMin === 'center') { this.mirrorScale = true; var mirrorScale = true; properties.yaxisScaleMin = 0; } // // Generate an appropiate scale // this.scale = RGraph.SVG.getScale({ object: this, numlabels: properties.yaxisLabelsCount, unitsPre: properties.yaxisScaleUnitsPre, unitsPost: properties.yaxisScaleUnitsPost, max: max, min: properties.yaxisScaleMin, point: properties.yaxisScalePoint, round: properties.yaxisScaleRound, thousand: properties.yaxisScaleThousand, decimals: properties.yaxisScaleDecimals, strict: typeof properties.yaxisScaleMax === 'number', formatter: properties.yaxisScaleFormatter }); // // Get the scale a second time if the ymin should be mirored // // Set the ymin to zero if it's set mirror if (mirrorScale) { this.scale = RGraph.SVG.getScale({ object: this, numlabels: properties.yaxisLabelsCount, unitsPre: properties.yaxisScaleUnitsPre, unitsPost: properties.yaxisScaleUnitsPost, max: this.scale.max, min: this.scale.max * -1, point: properties.yaxisScalePoint, round: false, thousand: properties.yaxisScaleThousand, decimals: properties.yaxisScaleDecimals, strict: typeof properties.yaxisScaleMax === 'number', formatter: properties.yaxisScaleFormatter }); } // Now the scale has been generated adopt its max value this.max = this.scale.max; this.min = this.scale.min; // Commenting these two lines out allows the data to change and // subsequently a new max can be generated to accommodate the // new data //properties.yaxisScaleMax = this.scale.max; //properties.yaxisScaleMin = this.scale.min; // Draw the background first RGraph.SVG.drawBackground(this); // Draw the threeD axes here so everything else is drawn on top of // it, but after the scale generation if (properties.variant === '3d') { // Draw the 3D Y axis RGraph.SVG.create({ svg: this.svg, parent: this.svg.all, type: 'path', attr: { d: 'M {1} {2} L {3} {4} L {5} {6} L {7} {8}'.format( properties.marginLeft, properties.marginTop, properties.marginLeft + properties.variant3dOffsetx, properties.marginTop - properties.variant3dOffsety, properties.marginLeft + properties.variant3dOffsetx, this.height - properties.marginBottom - properties.variant3dOffsety, properties.marginLeft, this.height - properties.marginBottom, properties.marginLeft, properties.marginTop ), fill: '#ddd', stroke: '#ccc' } }); // Add the group that the negative bars are added to. This makes them // appear below the axes this.threed_xaxis_group = RGraph.SVG.create({ svg: this.svg, type: 'g', parent: this.svg.all, attr: { className: 'rgraph_3d_bar_xaxis_negative' } }); // Draw the 3D X axis RGraph.SVG.create({ svg: this.svg, parent: this.svg.all, type: 'path', attr: { d: 'M {1} {2} L {3} {4} L {5} {6} L {7} {8}'.format( properties.marginLeft, this.getYCoord(0), properties.marginLeft + properties.variant3dOffsetx, this.getYCoord(0) - properties.variant3dOffsety, this.width - properties.marginRight + properties.variant3dOffsetx, this.getYCoord(0) - properties.variant3dOffsety, this.width - properties.marginRight, this.getYCoord(0), properties.marginLeft, this.getYCoord(0) ), fill: '#ddd', stroke: '#ccc' } }); } // Draw the bars this.drawBars(); // // If the xaxisLabels option is a string then turn it // into an array. // if (properties.xaxisLabels && properties.xaxisLabels.length) { if (typeof properties.xaxisLabels === 'string') { properties.xaxisLabels = RGraph.SVG.arrayPad({ array: [], length: this.data.length, value: properties.xaxisLabels }); } // Label substitution // for (var i=0; i<properties.xaxisLabels.length; ++i) { properties.xaxisLabels[i] = RGraph.SVG.labelSubstitution({ object: this, text: properties.xaxisLabels[i], index: i, value: this.data[i], decimals: properties.xaxisLabelsFormattedDecimals || 0, unitsPre: properties.xaxisLabelsFormattedUnitsPre || '', unitsPost: properties.xaxisLabelsFormattedUnitsPost || '', thousand: properties.xaxisLabelsFormattedThousand || ',', point: properties.xaxisLabelsFormattedPoint || '.' }); } } // Draw the axes over the bars RGraph.SVG.drawXAxis(this); RGraph.SVG.drawYAxis(this); // Draw the labelsAbove labels this.drawLabelsAbove(); // Draw the key if (typeof properties.key !== null && RGraph.SVG.drawKey) { RGraph.SVG.drawKey(this); } else if (!RGraph.SVG.isNull(properties.key)) { alert('The drawKey() function does not exist - have you forgotten to include the key library?'); } // Add the event listener that clears the highlight rect if // there is any. Must be MOUSEDOWN (ie before the click event) //var obj = this; //document.body.addEventListener('mousedown', function (e) //{ // //RGraph.SVG.removeHighlight(obj); // //}, false); // // Fire the onfirstdraw event // if (this.firstDraw) { this.firstDraw = false; RGraph.SVG.fireCustomEvent(this, 'onfirstdraw'); } // Fire the draw event RGraph.SVG.fireCustomEvent(this, 'ondraw'); return this; }; // // Draws the bars // this.drawBars = function () { var y = this.getYCoord(0); if (properties.shadow) { RGraph.SVG.setShadow({ object: this, offsetx: properties.shadowOffsetx, offsety: properties.shadowOffsety, blur: properties.shadowBlur, opacity: properties.shadowOpacity, id: 'dropShadow' }); } // Go through the bars for (var i=0,sequentialIndex=0; i<this.data.length; ++i,++sequentialIndex) { // // REGULAR BARS // if (typeof this.data[i] === 'number') { var outerSegment = (this.graphWidth - properties.marginInnerLeft - properties.marginInnerRight) / this.data.length, height = (Math.abs(this.data[i]) - Math.abs(this.scale.min)) / (Math.abs(this.scale.max) - Math.abs(this.scale.min)) * this.graphHeight, width = ( (this.graphWidth - properties.marginInnerLeft - properties.marginInnerRight) / this.data.length) - properties.marginInner - properties.marginInner, x = properties.marginLeft + properties.marginInner + properties.marginInnerLeft + (outerSegment * i); // Work out the height and the Y coord of the Bar if (this.scale.min >= 0 && this.scale.max > 0) { y = this.getYCoord(this.scale.min) - height; } else if (this.scale.min < 0 && this.scale.max > 0) { height = (Math.abs(this.data[i]) / (this.scale.max - this.scale.min)) * this.graphHeight; y = this.getYCoord(0) - height; if (this.data[i] < 0) { y = this.getYCoord(0); } } else if (this.scale.min < 0 && this.scale.max < 0) { height = (Math.abs(this.data[i]) - Math.abs(this.scale.max)) / (Math.abs(this.scale.min) - Math.abs(this.scale.max)) * this.graphHeight; y = properties.marginTop; } var rect = RGraph.SVG.create({ svg: this.svg, type: 'rect', parent: properties.variant === '3d' && this.data[i] < 0 ? this.threed_xaxis_group : this.svg.all, attr: { stroke: properties.colorsStroke, fill: properties.colorsSequential ? (properties.colors[sequentialIndex] ? properties.colors[sequentialIndex] : properties.colors[properties.colors.length - 1]) : properties.colors[0], x: x, y: y, width: width < 0 ? 0 : width, height: height, 'stroke-width': properties.linewidth, 'data-original-x': x, 'data-original-y': y, 'data-original-width': width, 'data-original-height': height, 'data-tooltip': (!RGraph.SVG.isNull(properties.tooltips) && properties.tooltips.length) ? properties.tooltips[i] : '', 'data-index': i, 'data-sequential-index': sequentialIndex, 'data-value': this.data[i], filter: properties.shadow ? 'url(#dropShadow)' : '' } }); // Draw the errorbar if required this.drawErrorbar({ object: this, element: rect, index: i, value: this.data[i], type: 'normal' }); this.coords.push({ object: this, element: rect, x: parseFloat(rect.getAttribute('x')), y: parseFloat(rect.getAttribute('y')), width: parseFloat(rect.getAttribute('width')), height: parseFloat(rect.getAttribute('height')) }); if (!this.coords2[0]) { this.coords2[0] = []; } this.coords2[0].push({ object: this, element: rect, x: parseFloat(rect.getAttribute('x')), y: parseFloat(rect.getAttribute('y')), width: parseFloat(rect.getAttribute('width')), height: parseFloat(rect.getAttribute('height')) }); // // Add the 3D faces if required // if (properties.variant === '3d') { this.drawTop3dFace({rect: rect, value: this.data[i]}); this.drawSide3dFace({rect: rect, value: this.data[i]}); } // Add the tooltip data- attribute if ( !RGraph.SVG.isNull(properties.tooltips) && (!RGraph.SVG.isNull(properties.tooltips[sequentialIndex]) || typeof properties.tooltips === 'string') ) { var obj = this; // // Add tooltip event listeners // (function (idx, seq) { rect.addEventListener(properties.tooltipsEvent.replace(/^on/, ''), function (e) { obj.removeHighlight(); // Show the tooltip RGraph.SVG.tooltip({ object: obj, index: idx, group: null, sequentialIndex: seq, text: typeof properties.tooltips === 'string' ? properties.tooltips : properties.tooltips[seq], event: e }); // Highlight the rect that has been clicked on obj.highlight(e.target); }, false); rect.addEventListener('mousemove', function (e) { e.target.style.cursor = 'pointer' }, false); })(i, sequentialIndex); } // // GROUPED BARS // } else if (RGraph.SVG.isArray(this.data[i]) && properties.grouping === 'grouped') { var outerSegment = ( (this.graphWidth - properties.marginInnerLeft - properties.marginInnerRight) / this.data.length), innerSegment = outerSegment - (2 * properties.marginInner); // Loop through the group for (var j=0; j<this.data[i].length; ++j,++sequentialIndex) { var width = ( (innerSegment - ((this.data[i].length - 1) * properties.marginInnerGrouped)) / this.data[i].length), x = (outerSegment * i) + properties.marginInner + properties.marginLeft + properties.marginInnerLeft + (j * width) + ((j - 1) * properties.marginInnerGrouped); x = properties.marginLeft + properties.marginInnerLeft + (outerSegment * i) + (width * j) + properties.marginInner + (j * properties.marginInnerGrouped); // Calculate the height // eg 0 -> 10 if (this.scale.min === 0 && this.scale.max > this.scale.min) { var height = ((this.data[i][j] - this.scale.min) / (this.scale.max - this.scale.min)) * this.graphHeight, y = this.getYCoord(0) - height; // eg -5 -> -15 } else if (this.scale.max <= 0 && this.scale.min < this.scale.max) { var height = ((this.data[i][j] - this.scale.max) / (this.scale.max - this.scale.min)) * this.graphHeight, y = this.getYCoord(this.scale.max); height = Math.abs(height); // eg 10 -> -10 } else if (this.scale.max > 0 && this.scale.min < 0) { var height = (Math.abs(this.data[i][j]) / (this.scale.max - this.scale.min)) * this.graphHeight, y = this.data[i][j] < 0 ? this.getYCoord(0) : this.getYCoord(this.data[i][j]); // eg 5 -> 10 } else if (this.scale.min > 0 && this.scale.max > this.scale.min) { var height = (Math.abs(this.data[i][j] - this.scale.min) / (this.scale.max - this.scale.min)) * this.graphHeight, y = this.getYCoord(this.scale.min) - height; } // Add the rect tag var rect = RGraph.SVG.create({ svg: this.svg, parent: properties.variant === '3d' && this.data[i][j] < 0 ? this.threed_xaxis_group : this.svg.all, type: 'rect', attr: { stroke: properties.colorsStroke, fill: (properties.colorsSequential && properties.colors[sequentialIndex]) ? properties.colors[sequentialIndex] : properties.colors[j], x: x, y: y, width: width, height: height, 'stroke-width': properties.linewidth, 'data-original-x': x, 'data-original-y': y, 'data-original-width': width, 'data-original-height': height, 'data-index': i, 'data-subindex': j, 'data-sequential-index': sequentialIndex, 'data-tooltip': (!RGraph.SVG.isNull(properties.tooltips) && properties.tooltips.length) ? properties.tooltips[sequentialIndex] : '', 'data-value': this.data[i][j], filter: properties.shadow ? 'url(#dropShadow)' : '' } }); // Draw the errorbar if required this.drawErrorbar({ object: this, element: rect, index: sequentialIndex, value: this.data[i][j], type: 'grouped' }); this.coords.push({ object: this, element: rect, x: parseFloat(rect.getAttribute('x')), y: parseFloat(rect.getAttribute('y')), width: parseFloat(rect.getAttribute('width')), height: parseFloat(rect.getAttribute('height')) }); if (!this.coords2[i]) { this.coords2[i] = []; } this.coords2[i].push({ object: this, element: rect, x: parseFloat(rect.getAttribute('x')), y: parseFloat(rect.getAttribute('y')), width: parseFloat(rect.getAttribute('width')), height: parseFloat(rect.getAttribute('height')) }); // // Add the 3D faces if required // if (properties.variant === '3d') { this.drawTop3dFace({rect: rect, value: this.data[i][j]}); this.drawSide3dFace({rect: rect, value: this.data[i][j]}); } // Add the tooltip data- attribute if ( !RGraph.SVG.isNull(properties.tooltips) && (properties.tooltips[sequentialIndex] || typeof properties.tooltips === 'string') ) { var obj = this; // // Add tooltip event listeners // (function (idx, seq) { obj.removeHighlight(); var indexes = RGraph.SVG.sequentialIndexToGrouped(seq, obj.data); rect.addEventListener(properties.tooltipsEvent.replace(/^on/, ''), function (e) { // Show the tooltip RGraph.SVG.tooltip({ object: obj, group: idx, index: indexes[1], sequentialIndex: seq, text: typeof properties.tooltips === 'string' ? properties.tooltips : properties.tooltips[seq], event: e }); // Highlight the rect that has been clicked on obj.highlight(e.target); }, false); rect.addEventListener('mousemove', function (e) { e.target.style.cursor = 'pointer' }, false); })(i, sequentialIndex); } } --sequentialIndex; // // STACKED CHARTS // } else if (RGraph.SVG.isArray(this.data[i]) && properties.grouping === 'stacked') { var section = ( (this.graphWidth - properties.marginInnerLeft - properties.marginInnerRight) / this.data.length); // Intialise the Y coordinate to the bottom gutter var y = this.getYCoord(0); // Loop through the stack for (var j=0; j<this.data[i].length; ++j,++sequentialIndex) { var height = (this.data[i][j] / (this.max - this.min)) * this.graphHeight, width = section - (2 * properties.marginInner), x = properties.marginLeft + properties.marginInnerLeft + (i * section) + properties.marginInner, y = y - height; // If this is the first iteration of the loop and a shadow // is requested draw a rect here to create it. if (j === 0 && properties.shadow) { var fullHeight = (RGraph.SVG.arraySum(this.data[i]) / (this.max - this.min)) * this.graphHeight; var rect = RGraph.SVG.create({ svg: this.svg, parent: this.svg.all, type: 'rect', attr: { fill: 'white', x: x, y: this.height - properties.marginBottom - fullHeight, width: width, height: fullHeight, 'stroke-width': 0, 'data-index': i, filter: 'url(#dropShadow)' } }); this.stackedBackfaces[i] = rect; } // Create the visible bar var rect = RGraph.SVG.create({ svg: this.svg, parent: this.svg.all, type: 'rect', attr: { stroke: properties.colorsStroke, fill: properties.colorsSequential ? (properties.colors[sequentialIndex] ? properties.colors[sequentialIndex] : properties.colors[properties.colors.length - 1]) : properties.colors[j], x: x, y: y, width: width, height: height, 'stroke-width': properties.linewidth, 'data-original-x': x, 'data-original-y': y, 'data-original-width': width, 'data-original-height': height, 'data-index': i, 'data-subindex': j, 'data-sequential-index': sequentialIndex, 'data-tooltip': (!RGraph.SVG.isNull(properties.tooltips) && properties.tooltips.length) ? properties.tooltips[sequentialIndex] : '', 'data-value': this.data[i][j] } }); // Draw the errorbar if required if (j === (this.data[i].length - 1)) { this.drawErrorbar({ object: this, element: rect, index: i, value: this.data[i][j], type: 'stacked' }); } this.coords.push({ object: this, element: rect, x: parseFloat(rect.getAttribute('x')), y: parseFloat(rect.getAttribute('y')), width: parseFloat(rect.getAttribute('width')), height: parseFloat(rect.getAttribute('height')) }); if (!this.coords2[i]) { this.coords2[i] = []; } this.coords2[i].push({ object: this, element: rect, x: parseFloat(rect.getAttribute('x')), y: parseFloat(rect.getAttribute('y')), width: parseFloat(rect.getAttribute('width')), height: parseFloat(rect.getAttribute('height')) }); // // Add the 3D faces if required // if (properties.variant === '3d') { this.drawTop3dFace({rect: rect, value: this.data[i][j]}); this.drawSide3dFace({rect: rect, value: this.data[i][j]}); } // Add the tooltip data- attribute if ( !RGraph.SVG.isNull(properties.tooltips) && (properties.tooltips[sequentialIndex] || typeof properties.tooltips === 'string') ) { var obj = this; // // Add tooltip event listeners // (function (idx, seq) { rect.addEventListener(properties.tooltipsEvent.replace(/^on/, ''), function (e) { obj.removeHighlight(); var indexes = RGraph.SVG.sequentialIndexToGrouped(seq, obj.data); // Show the tooltip RGraph.SVG.tooltip({ object: obj, index: indexes[1], group: idx, sequentialIndex: seq, text: typeof properties.tooltips === 'string' ? properties.tooltips : properties.tooltips[seq], event: e }); // Highlight the rect that has been clicked on obj.highlight(e.target); }, false); rect.addEventListener('mousemove', function (e) { e.target.style.cursor = 'pointer'; }, false); })(i, sequentialIndex); } } --sequentialIndex; } } }; // // This function can be used to retrieve the relevant Y coordinate for a // particular value. // // @param int value The value to get the Y coordinate for // this.getYCoord = function (value) { if (value > this.scale.max) { return null; } var y, xaxispos = properties.xaxispos; if (value < this.scale.min) { return null; } y = ((value - this.scale.min) / (this.scale.max - this.scale.min)); y *= (this.height - properties.marginTop - properties.marginBottom); y = this.height - properties.marginBottom - y; return y; }; // // This function can be used to highlight a bar on the chart // // @param object rect The rectangle to highlight // this.highlight = function (rect) { var x = parseFloat(rect.getAttribute('x')) - 0.5, y = parseFloat(rect.getAttribute('y')) - 0.5, width = parseFloat(rect.getAttribute('width')) + 1, height = parseFloat(rect.getAttribute('height')) + 1; var highlight = RGraph.SVG.create({ svg: this.svg, parent: this.svg.all, type: 'rect', attr: { stroke: properties.highlightStroke, fill: properties.highlightFill, x: x, y: y, width: width, height: height, 'stroke-width': properties.highlightLinewidth }, style: { pointerEvents: 'none' } }); if (properties.tooltipsEvent === 'mousemove') { //var obj = this; //highlight.addEventListener('mouseout', function (e) //{ // obj.removeHighlight(); // RGraph.SVG.hideTooltip(); // RGraph.SVG.REG.set('highlight', null); //}, false); } // Store the highlight rect in the rebistry so // it can be cleared later RGraph.SVG.REG.set('highlight', highlight); }; // // This allows for easy specification of gradients // this.parseColors = function () { // Save the original colors so that they can be restored when // the canvas is cleared if (!Object.keys(this.originalColors).length) { this.originalColors = { colors: RGraph.SVG.arrayClone(properties.colors), backgroundGridColor: RGraph.SVG.arrayClone(properties.backgroundGridColor), highlightFill: RGraph.SVG.arrayClone(properties.highlightFill), backgroundColor: RGraph.SVG.arrayClone(properties.backgroundColor) } } // colors var colors = properties.colors; if (colors) { for (var i=0; i<colors.length; ++i) { colors[i] = RGraph.SVG.parseColorLinear({ object: this, color: colors[i] }); } } properties.backgroundGridColor = RGraph.SVG.parseColorLinear({object: this, color: properties.backgroundGridColor}); properties.highlightFill = RGraph.SVG.parseColorLinear({object: this, color: properties.highlightFill}); properties.backgroundColor = RGraph.SVG.parseColorLinear({object: this, color: properties.backgroundColor}); }; // // Draws the labelsAbove // this.drawLabelsAbove = function () { // Go through the above labels if (properties.labelsAbove) { var data_seq = RGraph.SVG.arrayLinearize(this.data), seq = 0, stacked_total = 0;; for (var i=0; i<this.coords.length; ++i,seq++) { var num = typeof this.data[i] === 'number' ? this.data[i] : data_seq[seq] ; // If this is a stacked chart then only dothe label // if it's the top segment if (properties.grouping === 'stacked') { var indexes = RGraph.SVG.sequentialIndexToGrouped(i, this.data); var group = indexes[0]; var datapiece = indexes[1]; if (datapiece !== (this.data[group].length - 1) ) { continue; } else { num = RGraph.SVG.arraySum(this.data[group]); } } var str = RGraph.SVG.numberFormat({ object: this, num: num.toFixed(properties.labelsAboveDecimals), prepend: typeof properties.labelsAboveUnitsPre === 'string' ? properties.labelsAboveUnitsPre : null, append: typeof properties.labelsAboveUnitsPost === 'string' ? properties.labelsAboveUnitsPost : null, point: typeof properties.labelsAbovePoint === 'string' ? properties.labelsAbovePoint : null, thousand: typeof properties.labelsAboveThousand === 'string' ? properties.labelsAboveThousand : null, formatter: typeof properties.labelsAboveFormatter === 'function' ? properties.labelsAboveFormatter : null }); // Facilitate labelsAboveSpecific if (properties.labelsAboveSpecific && properties.labelsAboveSpecific.length && (typeof properties.labelsAboveSpecific[seq] === 'string' || typeof properties.labelsAboveSpecific[seq] === 'number') ) { str = properties.labelsAboveSpecific[seq]; } else if ( properties.labelsAboveSpecific && properties.labelsAboveSpecific.length && typeof properties.labelsAboveSpecific[seq] !== 'string' && typeof properties.labelsAboveSpecific[seq] !== 'number') { continue; } var x = parseFloat(this.coords[i].element.getAttribute('x')) + parseFloat(this.coords[i].element.getAttribute('width') / 2) + properties.labelsAboveOffsetx; if (data_seq[i] >= 0) { var y = parseFloat(this.coords[i].element.getAttribute('y')) - 7 + properties.labelsAboveOffsety; var valign = properties.labelsAboveValign; } else { var y = parseFloat(this.coords[i].element.getAttribute('y')) + parseFloat(this.coords[i].element.getAttribute('height')) + 7 - properties.labelsAboveOffsety; var valign = properties.labelsAboveValign === 'top' ? 'bottom' : 'top'; } var textConf = RGraph.SVG.getTextConf({ object: this, prefix: 'labelsAbove' }); RGraph.SVG.text({ object: this, parent: this.svg.all, tag: 'labels.above', text: str, x: x, y: y, halign: properties.labelsAboveHalign, valign: valign, font: textConf.font, size: textConf.size, bold: textConf.bold, italic: textConf.italic, color: textConf.color, background: properties.labelsAboveBackground || null, padding: properties.labelsAboveBackgroundPadding || 0 }); } } }; // // Using a function to add events makes it easier to facilitate method // chaining // // @param string type The type of even to add // @param function func // this.on = function (type, func) { if (type.substr(0,2) !== 'on') { type = 'on' + type; } RGraph.SVG.addCustomEventListener(this, type, func); return this; }; // // Used in chaining. Runs a function there and then - not waiting for // the events to fire (eg the onbeforedraw event) // // @param function func The function to execute // this.exec = function (func) { func(this); return this; }; // // Remove highlight from the chart (tooltips) // this.removeHighlight = function () { var highlight = RGraph.SVG.REG.get('highlight'); if (highlight && highlight.parentNode) { highlight.parentNode.removeChild(highlight); } RGraph.SVG.REG.set('highlight', null); }; // // Draws the top of 3D bars // this.drawTop3dFace = function (opt) { var rect = opt.rect, arr = [parseInt(rect.getAttribute('fill')), 'rgba(255,255,255,0.7)'], x = parseInt(rect.getAttribute('x')), y = parseInt(rect.getAttribute('y')), w = parseInt(rect.getAttribute('width')), h = parseInt(rect.getAttribute('height')), value = parseFloat(rect.getAttribute('data-value')); rect.rgraph_3d_top_face = []; for (var i=0; i<2; ++i) { var color = (i === 0 ? rect.getAttribute('fill') : 'rgba(255,255,255,0.7)'); var face = RGraph.SVG.create({ svg: this.svg, type: 'path', parent: properties.variant === '3d' && opt.value < 0 ? this.threed_xaxis_group : this.svg.all, attr: { stroke: properties.colorsStroke, fill: color, 'stroke-width': properties.linewidth, d: 'M {1} {2} L {3} {4} L {5} {6} L {7} {8}'.format( x, y, x + properties.variant3dOffsetx, y - properties.variant3dOffsety, x + w + properties.variant3dOffsetx, y - properties.variant3dOffsety, x + w, y ) } }); // Store a reference to the rect on the front face of the bar rect.rgraph_3d_top_face[i] = face } }; // // Draws the top of 3D bars // this.drawSide3dFace = function (opt) { var rect = opt.rect, arr = [parseInt(rect.getAttribute('fill')), 'rgba(0,0,0,0.3)'], x = parseInt(rect.getAttribute('x')), y = parseInt(rect.getAttribute('y')), w = parseInt(rect.getAttribute('width')), h = parseInt(rect.getAttribute('height')); rect.rgraph_3d_side_face = []; for (var i=0; i<2; ++i) { var color = (i === 0 ? rect.getAttribute('fill') : 'rgba(0,0,0,0.3)'); var face = RGraph.SVG.create({ svg: this.svg, type: 'path', parent: properties.variant === '3d' && opt.value < 0 ? this.threed_xaxis_group : this.svg.all, attr: { stroke: properties.colorsStroke, fill: color, 'stroke-width': properties.linewidth, d: 'M {1} {2} L {3} {4} L {5} {6} L {7} {8}'.format( x + w, y, x + w + properties.variant3dOffsetx, y - properties.variant3dOffsety, x + w + properties.variant3dOffsetx, y + h - properties.variant3dOffsety, x + w, y + h ) } }); // Store a reference to the rect on the front face of the bar rect.rgraph_3d_side_face[i] = face } }; // This function is used to draw the errorbar. Its in the common // file because it's used by multiple chart libraries this.drawErrorbar = function (opt) { var index = opt.index, datapoint = opt.value, linewidth = RGraph.SVG.getErrorbarsLinewidth({object: this, index: index}), color = RGraph.SVG.getErrorbarsColor({object: this, index: index}), capwidth = RGraph.SVG.getErrorbarsCapWidth({object: this, index: index}), element = opt.element, type = opt.type; // Get the error bar value var max = RGraph.SVG.getErrorbarsMaxValue({ object: this, index: index }); // Get the error bar value var min = RGraph.SVG.getErrorbarsMinValue({ object: this, index: index }); if (!max && !min) { return; } // Accounts for stacked bars if (type === 'stacked') { datapoint = RGraph.SVG.arraySum(this.data[index]); } if (datapoint >= 0) { var x1 = parseFloat(element.getAttribute('x')) + (parseFloat(element.getAttribute('width')) / 2); // Draw the UPPER vertical line var errorbarLine = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: x1, y1: parseFloat(element.getAttribute('y')), x2: x1, y2: this.getYCoord(parseFloat(datapoint + max)), stroke: color, 'stroke-width': linewidth } }); // Draw the cap to the UPPER line var errorbarCap = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: parseFloat(errorbarLine.getAttribute('x1')) - (capwidth / 2), y1: errorbarLine.getAttribute('y2'), x2: parseFloat(errorbarLine.getAttribute('x1')) + (capwidth / 2), y2: errorbarLine.getAttribute('y2'), stroke: color, 'stroke-width': linewidth } }); // Draw the minimum errorbar if necessary if (typeof min === 'number') { var errorbarLine = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: x1, y1: parseFloat(element.getAttribute('y')), x2: x1, y2: this.getYCoord(parseFloat(datapoint - min)), stroke: color, 'stroke-width': linewidth } }); // Draw the cap to the UPPER line var errorbarCap = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: parseFloat(errorbarLine.getAttribute('x1')) - (capwidth / 2), y1: errorbarLine.getAttribute('y2'), x2: parseFloat(errorbarLine.getAttribute('x1')) + (capwidth / 2), y2: errorbarLine.getAttribute('y2'), stroke: color, 'stroke-width': linewidth } }); } } else if (datapoint < 0) { var x1 = parseFloat(element.getAttribute('x')) + (parseFloat(element.getAttribute('width')) / 2), y1 = parseFloat(element.getAttribute('y')) + parseFloat(element.getAttribute('height')), y2 = this.getYCoord(parseFloat(datapoint - Math.abs(max) )) // Draw the vertical line var errorbarLine = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: x1, y1: y1, x2: x1, y2: y2, stroke: color, 'stroke-width': linewidth } }); // Draw the cap to the vertical line var errorbarCap = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: parseFloat(errorbarLine.getAttribute('x1')) - (capwidth / 2), y1: errorbarLine.getAttribute('y2'), x2: parseFloat(errorbarLine.getAttribute('x1')) + (capwidth / 2), y2: errorbarLine.getAttribute('y2'), stroke: color, 'stroke-width': linewidth } }); // Draw the minimum errorbar if necessary if (typeof min === 'number') { var x1 = parseFloat(element.getAttribute('x')) + (parseFloat(element.getAttribute('width')) / 2); var errorbarLine = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: x1, y1: this.getYCoord(parseFloat(datapoint + min)), x2: x1, y2: this.getYCoord(parseFloat(datapoint)), stroke: color, 'stroke-width': linewidth } }); // Draw the cap to the UPPER line var errorbarCap = RGraph.SVG.create({ svg: this.svg, type: 'line', parent: this.svg.all, attr: { x1: parseFloat(errorbarLine.getAttribute('x1')) - (capwidth / 2), y1: errorbarLine.getAttribute('y1'), x2: parseFloat(errorbarLine.getAttribute('x1')) + (capwidth / 2), y2: errorbarLine.getAttribute('y1'), stroke: color, 'stroke-width': linewidth } }); } } }; // // The Bar chart grow effect // this.grow = function () { var opt = arguments[0] || {}, frames = opt.frames || 30, frame = 0, obj = this, data = [], height = null, seq = 0; // // Copy the data // data = RGraph.SVG.arrayClone(this.data); this.draw(); var iterate = function () { for (var i=0,seq=0,len=obj.coords.length; i<len; ++i, ++seq) { var multiplier = (frame / frames) // RGraph.SVG.FX.getEasingMultiplier(frames, frame) // RGraph.SVG.FX.getEasingMultiplier(frames, frame); // TODO Go through the data and update the value according to // the frame number if (typeof data[i] === 'number') { height = Math.abs(obj.getYCoord(data[i]) - obj.getYCoord(0)); obj.data[i] = data[i] * multiplier; height = multiplier * height; // Set the new height on the rect obj.coords[seq].element.setAttribute( 'height', height ); // Set the correct Y coord on the object obj.coords[seq].element.setAttribute( 'y', data[i] < 0 ? obj.getYCoord(0) : obj.getYCoord(0) - height ); // This upadtes the size of the 3D sides to the bar if (properties.variant === '3d') { // Remove the 3D sides to the bar if (obj.coords[i].element.rgraph_3d_side_face[0].parentNode) obj.coords[i].element.rgraph_3d_side_face[0].parentNode.removeChild(obj.coords[i].element.rgraph_3d_side_face[0]); if (obj.coords[i].element.rgraph_3d_side_face[1].parentNode) obj.coords[i].element.rgraph_3d_side_face[1].parentNode.removeChild(obj.coords[i].element.rgraph_3d_side_face[1]); if (obj.coords[i].element.rgraph_3d_top_face[0].parentNode) obj.coords[i].element.rgraph_3d_top_face[0].parentNode.removeChild(obj.coords[i].element.rgraph_3d_top_face[0]); if (obj.coords[i].element.rgraph_3d_top_face[1].parentNode) obj.coords[i].element.rgraph_3d_top_face[1].parentNode.removeChild(obj.coords[i].element.rgraph_3d_top_face[1]); // Add the 3D sides to the bar (again) obj.drawSide3dFace({rect: obj.coords[i].element}); // Draw the top side of the 3D bar if (properties.grouping === 'grouped') { obj.drawTop3dFace({rect: obj.coords[i].element }); } // Now remove and immediately re-add the front face of // the bar - this is so that the front face appears // above the other sides if (obj.coords[i].element.parentNode) { var parent = obj.coords[i].element.parentNode; var node = parent.removeChild(obj.coords[i].element); parent.appendChild(node); } } } else if (typeof data[i] === 'object') { var accumulativeHeight = 0; for (var j=0,len2=data[i].length; j<len2; ++j, ++seq) { height = Math.abs(obj.getYCoord(data[i][j]) - obj.getYCoord(0)); height = multiplier * height; obj.data[i][j] = data[i][j] * multiplier; height = Math.round(height); obj.coords[seq].element.setAttribute( 'height', height ); obj.coords[seq].element.setAttribute( 'y', data[i][j] < 0 ? (obj.getYCoord(0) + accumulativeHeight) : (obj.getYCoord(0) - height - accumulativeHeight) ); // This updates the size of the 3D sides to the bar if (properties.variant === '3d') { // Remove the 3D sides to the bar if (obj.coords[seq].element.rgraph_3d_side_face[0].parentNode) obj.coords[seq].element.rgraph_3d_side_face[0].parentNode.removeChild(obj.coords[seq].element.rgraph_3d_side_face[0]); if (obj.coords[seq].element.rgraph_3d_side_face[1].parentNode) obj.coords[seq].element.rgraph_3d_side_face[1].parentNode.removeChild(obj.coords[seq].element.rgraph_3d_side_face[1]); if (obj.coords[seq].element.rgraph_3d_top_face[0].parentNode) obj.coords[seq].element.rgraph_3d_top_face[0].parentNode.removeChild(obj.coords[seq].element.rgraph_3d_top_face[0]); if (obj.coords[seq].element.rgraph_3d_top_face[1].parentNode) obj.coords[seq].element.rgraph_3d_top_face[1].parentNode.removeChild(obj.coords[seq].element.rgraph_3d_top_face[1]); // Add the 3D sides to the bar (again) obj.drawSide3dFace({rect: obj.coords[seq].element}); // Draw the top side of the 3D bar // TODO Need to only draw the top face when the bar is either // not stacked or is the last segment in the stack obj.drawTop3dFace({rect: obj.coords[seq].element}); // Now remove and immediately re-add the front face of // the bar - this is so that the front face appears // above the other sides if (obj.coords[seq].element.parentNode) { var parent = obj.coords[seq].element.parentNode; var node = parent.removeChild(obj.coords[seq].element); parent.appendChild(node); } } accumulativeHeight += (properties.grouping === 'stacked' ? height : 0); } // // Set the height and Y cooord of the backfaces if necessary // if (obj.stackedBackfaces[i]) { obj.stackedBackfaces[i].setAttribute( 'height', accumulativeHeight ); obj.stackedBackfaces[i].setAttribute( 'y', obj.height - properties.marginBottom - accumulativeHeight ); } // Decrease seq by one so that it's not incremented twice --seq; } } if (frame++ < frames) { //setTimeout(iterate, frame > 1 ? opt.delay : 200); RGraph.SVG.FX.update(iterate); } else if (opt.callback) { (opt.callback)(obj); } }; iterate(); return this; }; // // HBar chart Wave effect. // // @param object OPTIONAL An object map of options. You specify 'frames' // here to give the number of frames in the effect // and also callback to specify a callback function // thats called at the end of the effect // this.wave = function () { // First draw the chart this.draw(); var obj = this, opt = arguments[0] || {}; opt.frames = opt.frames || 60; opt.startFrames = []; opt.counters = []; var framesperbar = opt.frames / 3, frame = -1, callback = opt.callback || function () {}; for (var i=0,len=this.coords.length; i<len; ++i) { opt.startFrames[i] = ((opt.frames / 2) / (obj.coords.length - 1)) * i; opt.counters[i] = 0; // Now zero the height of the bar (and remove the 3D faces) this.coords[i].element.setAttribute('height', 0); if (this.coords[i].element.rgraph_3d_side_face) { var parent = this.coords[i].element.rgraph_3d_side_face[0].parentNode; parent.removeChild(this.coords[i].element.rgraph_3d_side_face[0]); parent.removeChild(this.coords[i].element.rgraph_3d_side_face[1]); parent.removeChild(this.coords[i].element.rgraph_3d_top_face[0]); parent.removeChild(this.coords[i].element.rgraph_3d_top_face[1]); } } function iterator () { ++frame; for (var i=0,len=obj.coords.length; i<len; ++i) { var el = obj.coords[i].element; if (frame > opt.startFrames[i]) { var originalHeight = el.getAttribute('data-original-height'), height, value = parseFloat(el.getAttribute('data-value')); var height = Math.min( ((frame - opt.startFrames[i]) / framesperbar) * originalHeight, originalHeight ); el.setAttribute( 'height', height < 0 ? 0 : height ); el.setAttribute( 'y', value >=0 ? obj.getYCoord(0) - height : obj.getYCoord(0) ); // This updates the size of the 3D sides to the bar if (properties.variant === '3d') { // Remove the 3D sides to the bar var parent = el.rgraph_3d_side_face[0].parentNode; if (parent) parent.removeChild(el.rgraph_3d_side_face[0]); if (parent) parent.removeChild(el.rgraph_3d_side_face[1]); var parent = el.rgraph_3d_top_face[0].parentNode; if (parent) parent.removeChild(el.rgraph_3d_top_face[0]); if (parent) parent.removeChild(el.rgraph_3d_top_face[1]); // Now remove and immediately re-add the front face of // the bar - this is so that the front face appears // above the other sides if (el.parentNode) { var parent = el.parentNode; var node = parent.removeChild(el); parent.appendChild(node); } } if (properties.grouping === 'stacked') { var seq = el.getAttribute('data-sequential-index'); var indexes = RGraph.SVG.sequentialIndexToGrouped(seq, obj.data); if (indexes[1] > 0) { el.setAttribute( 'y', parseInt(obj.coords[i - 1].element.getAttribute('y')) - height ); } } if (properties.variant === '3d') { // Add the 3D sides to the bar (again) obj.drawSide3dFace({ rect: el, value: el.getAttribute('data-value') }); // Draw the top side of the 3D bar if (properties.grouping === 'grouped' || (properties.grouping === 'stacked' && (indexes[1] + 1) === obj.data[indexes[0]].length) ) { obj.drawTop3dFace({ rect: el, value: el.getAttribute('data-value') }); } } } } if (frame >= opt.frames) { callback(obj); } else { RGraph.SVG.FX.update(iterator); } } iterator(); return this; }; // // A worker function that handles Bar chart specific tooltip substitutions // this.tooltipSubstitutions = function (opt) { var indexes = RGraph.SVG.sequentialIndexToGrouped(opt.index, this.data); return { index: indexes[1], dataset: indexes[0], sequentialIndex: opt.index, value: typeof this.data[indexes[0]] === 'number' ? this.data[indexes[0]] : this.data[indexes[0]][indexes[1]], values: typeof this.data[indexes[0]] === 'number' ? [this.data[indexes[0]]] : this.data[indexes[0]] }; }; // // A worker function that returns the correct color/label/value // // @param object specific The indexes that are applicable // @param number index The appropriate index // this.tooltipsFormattedCustom = function (specific, index) { if (typeof this.data[0] === 'object') { var label = (!RGraph.SVG.isNull(properties.tooltipsFormattedKeyLabels) && typeof properties.tooltipsFormattedKeyLabels === 'object' && properties.tooltipsFormattedKeyLabels[index]) ? properties.tooltipsFormattedKeyLabels[index] : ''; } else { var label = ( !RGraph.SVG.isNull(properties.tooltipsFormattedKeyLabels) && typeof properties.tooltipsFormattedKeyLabels === 'object' && properties.tooltipsFormattedKeyLabels[specific.index]) ? properties.tooltipsFormattedKeyLabels[specific.index] : ''; } return { label: label }; }; // // This allows for static tooltip positioning // this.positionTooltipStatic = function (args) { var obj = args.object, e = args.event, tooltip = args.tooltip, index = args.index, svgXY = RGraph.SVG.getSVGXY(obj.svg), coords = this.coords[args.index]; // Position the tooltip in the X direction args.tooltip.style.left = ( svgXY[0] // The X coordinate of the canvas + coords.x // The X coordinate of the bar on the chart - (tooltip.offsetWidth / 2) // Subtract half of the tooltip width + (coords.width / 2) // Add half of the bar width ) + 'px'; // If the chart is a 3D version the tooltip Y position needs this // adjustment var adjustment = 0; if (properties.variant === '3d') { var left = coords.x; var top = coords.y; var angle = 5 / (180 / Math.PI); var adjustment = Math.tan(angle) * left; } args.tooltip.style.top = ( svgXY[1] // The Y coordinate of the canvas + coords.y // The Y coordinate of the bar on the chart - tooltip.offsetHeight // The height of the tooltip - 15 // An arbitrary amount + adjustment // Account for the 3D ) + 'px'; // If the bar is a negative one, add half the height to the Y coord var data_arr = RGraph.SVG.arrayLinearize(this.data); if (data_arr[index] < 0) { args.tooltip.style.top = parseFloat(args.tooltip.style.top) + (coords.height / 2) + 'px'; } // If the top of the tooltip is off the top of the page // then move the tooltip down if(parseFloat(args.tooltip.style.top) < 0) { args.tooltip.style.top = parseFloat(args.tooltip.style.top) + 20 + 'px'; } }; // // Set the options that the user has provided // for (i in conf.options) { if (typeof i === 'string') { this.set(i, conf.options[i]); } } }; return this; // End module pattern })(window, document);
/* Highstock JS v7.2.2 (2020-08-24) Indicator series type for Highstock (c) 2010-2019 Kamil Kulig License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/indicators/regressions",["highcharts","highcharts/modules/stock"],function(c){a(c);a.Highcharts=c;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function c(a,c,l,b){a.hasOwnProperty(c)||(a[c]=b.apply(null,l))}a=a?a._modules:{};c(a,"indicators/regressions.src.js",[a["parts/Globals.js"],a["parts/Utilities.js"]],function(a,c){var l= c.isArray;a=a.seriesType;a("linearRegression","sma",{params:{xAxisUnit:void 0},tooltip:{valueDecimals:4}},{nameBase:"Linear Regression Indicator",getRegressionLineParameters:function(b,a){var d=this.options.params.index,g=function(b,a){return l(b)?b[a]:b},n=b.reduce(function(b,a){return a+b},0),c=a.reduce(function(b,a){return g(a,d)+b},0);n/=b.length;c/=a.length;var e=0,f=0,h;for(h=0;h<b.length;h++){var k=b[h]-n;var p=g(a[h],d)-c;e+=k*p;f+=Math.pow(k,2)}b=f?e/f:0;return{slope:b,intercept:c-b*n}}, getEndPointY:function(b,a){return b.slope*a+b.intercept},transformXData:function(b,a){var d=b[0];return b.map(function(b){return(b-d)/a})},findClosestDistance:function(b){var a,d;for(d=1;d<b.length-1;d++){var c=b[d]-b[d-1];0<c&&(void 0===a||c<a)&&(a=c)}return a},getValues:function(a,c){var b=a.xData;a=a.yData;c=c.period;var g,m={xData:[],yData:[],values:[]},l=this.options.params.xAxisUnit||this.findClosestDistance(b);for(g=c-1;g<=b.length-1;g++){var e=g-c+1;var f=g+1;var h=b[g];var k=b.slice(e,f); e=a.slice(e,f);f=this.transformXData(k,l);k=this.getRegressionLineParameters(f,e);e=this.getEndPointY(k,f[f.length-1]);m.values.push({regressionLineParameters:k,x:h,y:e});m.xData.push(h);m.yData.push(e)}return m}});a("linearRegressionSlope","linearRegression",{},{nameBase:"Linear Regression Slope Indicator",getEndPointY:function(a){return a.slope}});a("linearRegressionIntercept","linearRegression",{},{nameBase:"Linear Regression Intercept Indicator",getEndPointY:function(a){return a.intercept}}); a("linearRegressionAngle","linearRegression",{tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span>{series.name}: <b>{point.y}\u00b0</b><br/>'}},{nameBase:"Linear Regression Angle Indicator",slopeToAngle:function(a){return 180/Math.PI*Math.atan(a)},getEndPointY:function(a){return this.slopeToAngle(a.slope)}});""});c(a,"masters/indicators/regressions.src.js",[],function(){})}); //# sourceMappingURL=regressions.js.map