code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
(function () { 'use strict'; // Uploadfiles controller angular .module('uploadfiles') .controller('UploadfilesController', UploadfilesController); UploadfilesController.$inject = ['$scope', '$state', '$window', 'Authentication', 'uploadfileResolve']; function UploadfilesController ($scope, $state, $window, Authentication, uploadfile) { var vm = this; vm.authentication = Authentication; vm.uploadfile = uploadfile; vm.error = null; vm.form = {}; vm.remove = remove; vm.save = save; // Remove existing Uploadfile function remove() { if ($window.confirm('Are you sure you want to delete?')) { vm.uploadfile.$remove($state.go('uploadfiles.list')); } } // Save Uploadfile function save(isValid) { if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.form.uploadfileForm'); return false; } // TODO: move create/update logic to service if (vm.uploadfile._id) { vm.uploadfile.$update(successCallback, errorCallback); } else { vm.uploadfile.$save(successCallback, errorCallback); } function successCallback(res) { $state.go('uploadfiles.view', { uploadfileId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } } }());
hodge-ken/hodge
modules/uploadfiles/client/controllers/uploadfiles.client.controller.js
JavaScript
mit
1,381
'use strict'; const common = require('../common'); const assert = require('assert'); const URLSearchParams = require('url').URLSearchParams; const { test, assert_false, assert_true } = require('../common/wpt'); /* The following tests are copied from WPT. Modifications to them should be upstreamed first. Refs: https://github.com/w3c/web-platform-tests/blob/8791bed/url/urlsearchparams-has.html License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html */ /* eslint-disable */ test(function() { var params = new URLSearchParams('a=b&c=d'); assert_true(params.has('a')); assert_true(params.has('c')); assert_false(params.has('e')); params = new URLSearchParams('a=b&c=d&a=e'); assert_true(params.has('a')); params = new URLSearchParams('=b&c=d'); assert_true(params.has('')); params = new URLSearchParams('null=a'); assert_true(params.has(null)); }, 'Has basics'); test(function() { var params = new URLSearchParams('a=b&c=d&&'); params.append('first', 1); params.append('first', 2); assert_true(params.has('a'), 'Search params object has name "a"'); assert_true(params.has('c'), 'Search params object has name "c"'); assert_true(params.has('first'), 'Search params object has name "first"'); assert_false(params.has('d'), 'Search params object has no name "d"'); params.delete('first'); assert_false(params.has('first'), 'Search params object has no name "first"'); }, 'has() following delete()'); /* eslint-enable */ // Tests below are not from WPT. { const params = new URLSearchParams(); common.expectsError(() => { params.has.call(undefined); }, { code: 'ERR_INVALID_THIS', type: TypeError, message: 'Value of "this" must be of type URLSearchParams' }); common.expectsError(() => { params.has(); }, { code: 'ERR_MISSING_ARGS', type: TypeError, message: 'The "name" argument must be specified' }); const obj = { toString() { throw new Error('toString'); }, valueOf() { throw new Error('valueOf'); } }; const sym = Symbol(); assert.throws(() => params.has(obj), /^Error: toString$/); assert.throws(() => params.has(sym), /^TypeError: Cannot convert a Symbol value to a string$/); }
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-whatwg-url-searchparams-has.js
JavaScript
mit
2,273
//----------------------------------------------------------------------------- /** * The sprite which covers the entire game screen. * * @class ScreenSprite * @constructor */ function ScreenSprite() { this.initialize.apply(this, arguments); } ScreenSprite.prototype = Object.create(PIXI.Container.prototype); ScreenSprite.prototype.constructor = ScreenSprite; ScreenSprite.prototype.initialize = function () { PIXI.Container.call(this); this._graphics = new PIXI.Graphics(); this.addChild(this._graphics); this.opacity = 0; this._red = -1; this._green = -1; this._blue = -1; this._colorText = ''; this.setBlack(); }; /** * The opacity of the sprite (0 to 255). * * @property opacity * @type Number */ Object.defineProperty(ScreenSprite.prototype, 'opacity', { get: function () { return this.alpha * 255; }, set: function (value) { this.alpha = value.clamp(0, 255) / 255; }, configurable: true }); ScreenSprite.YEPWarned = false; ScreenSprite.warnYep = function () { if (!ScreenSprite.YEPWarned) { console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside."); ScreenSprite.YEPWarned = true; } }; Object.defineProperty(ScreenSprite.prototype, 'anchor', { get: function () { ScreenSprite.warnYep(); this.scale.x = 1; this.scale.y = 1; return {x: 0, y: 0}; }, set: function (value) { this.alpha = value.clamp(0, 255) / 255; }, configurable: true }); Object.defineProperty(ScreenSprite.prototype, 'blendMode', { get: function () { return this._graphics.blendMode; }, set: function (value) { this._graphics.blendMode = value; }, configurable: true }); /** * Sets black to the color of the screen sprite. * * @method setBlack */ ScreenSprite.prototype.setBlack = function () { this.setColor(0, 0, 0); }; /** * Sets white to the color of the screen sprite. * * @method setWhite */ ScreenSprite.prototype.setWhite = function () { this.setColor(255, 255, 255); }; /** * Sets the color of the screen sprite by values. * * @method setColor * @param {Number} r The red value in the range (0, 255) * @param {Number} g The green value in the range (0, 255) * @param {Number} b The blue value in the range (0, 255) */ ScreenSprite.prototype.setColor = function (r, g, b) { if (this._red !== r || this._green !== g || this._blue !== b) { r = Math.round(r || 0).clamp(0, 255); g = Math.round(g || 0).clamp(0, 255); b = Math.round(b || 0).clamp(0, 255); this._red = r; this._green = g; this._blue = b; this._colorText = Utils.rgbToCssColor(r, g, b); var graphics = this._graphics; graphics.clear(); var intColor = (r << 16) | (g << 8) | b; graphics.beginFill(intColor, 1); //whole screen with zoom. BWAHAHAHAHA graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10); } };
rpgtkoolmv/corescript
js/rpg_core/ScreenSprite.js
JavaScript
mit
3,115
var sum_pairs = function (ints, s) { // your code here }; module.exports = sum_pairs;
BrianLusina/JS-Snippets
src/math_numbers/SumOfPairs/sumofpairs.js
JavaScript
mit
91
window.Rendxx = window.Rendxx || {}; window.Rendxx.Game = window.Rendxx.Game || {}; window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {}; window.Rendxx.Game.Ghost.Renderer2D = window.Rendxx.Game.Ghost.Renderer2D || {}; (function (RENDERER) { var Data = RENDERER.Data; var GridSize = Data.grid.size; var _Data = { size: 3, tileSize: 128, tileDispDuration: 50, Name: { 'Blood': 0, 'Electric': 1 } }; var Effort = function (entity) { // data ---------------------------------------------------------- var that = this, tex = {}, _scene = entity.env.scene['effort']; // callback ------------------------------------------------------ // public method ------------------------------------------------- this.update = function (newEffort) { if (newEffort == null || newEffort.length === 0) return; for (var i = 0, l = newEffort.length; i < l;i++){ createEffort(newEffort[i]); } }; this.render = function (delta) { }; // private method ------------------------------------------------- var createEffort = function (effort) { if (effort==null) return; var effortName = effort[0]; var x = effort[1]; var y = effort[2]; if (!tex.hasOwnProperty(effortName)) return; var item = new PIXI.extras.MovieClip(tex[effortName]); item.loop = false; item.anchor.set(0.5, 0.5); item.animationSpeed = 0.5; item.position.set(x * GridSize, y * GridSize); item.scale.set(_Data.size * GridSize / _Data.tileSize, _Data.size * GridSize / _Data.tileSize); item.onComplete = function () { _scene.removeChild(this) }; _scene.addChild(item); item.play(); }; // setup ----------------------------------------------- var _setupTex = function () { tex = {}; var path = entity.root + Data.files.path[Data.categoryName.sprite]; // texture loader ------------------------------------------------------------------------------------------- PIXI.loader .add(path + 'effort.blood.json') .add(path + 'effort.electric.json') .load(function (loader, resources) { // blood var frames = []; var name = path + 'effort.blood.json'; var _f = resources[name].data.frames; var i = 0; while (true) { var val = i < 10 ? '0' + i : i; if (!_f.hasOwnProperty('animation00' + val)) break; frames.push(loader.resources[name].textures['animation00' + val]); i++; } tex[_Data.Name.Blood] = frames; // electric var frames = []; var name = path + 'effort.electric.json'; var _f = resources[name].data.frames; var i = 0; while (true) { var val = i < 10 ? '0' + i : i; if (!_f.hasOwnProperty('animation00' + val)) break; frames.push(loader.resources[name].textures['animation00' + val]); i++; } tex[_Data.Name.Electric] = frames; }); }; var _init = function () { _setupTex(); }; _init(); }; RENDERER.Effort = Effort; RENDERER.Effort.Data = _Data; })(window.Rendxx.Game.Ghost.Renderer2D);
Rendxx/Game-Ghost
Game.Ghost/src/js/renderer2D/Renderer2D.Effort.js
JavaScript
mit
3,745
'use strict'; angular.module('applicant-test').controller('ApplicantTestController', ['$scope', '$stateParams', '$location', 'Authentication', 'Questions', '$http', function($scope, $stateParams, $location, Authentication, Questions, $http ) { $scope.authentication =Authentication; $scope.find = function(){ var url = '/test/'; $http.get(url).success(function(response) { $scope.questions = response; console.log('Questions init'); console.log($scope.questions); }); }; // $scope.findOne = function() { // var url = '/test/' + $stateParams.testId; // console.log('Getting stateParams'); // console.log($stateParams); // $http.get(url).success(function(response) { // $scope.questions = response; // console.log('Questions init'); // console.log($scope.questions); // }); // // $scope.test = Questions.get({ // // testId: $stateParams.testId // // }); // }; }]);
andela/AndelaAPI
public/modules/applicant-test/controllers/list-question.client.js
JavaScript
mit
1,161
/** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ import CoreManager from './CoreManager'; import encode from './encode'; import ParseError from './ParseError'; import ParseGeoPoint from './ParseGeoPoint'; import ParseObject from './ParseObject'; import ParsePromise from './ParsePromise'; import type { RequestOptions, FullOptions } from './RESTController'; export type WhereClause = { [attr: string]: mixed; }; export type QueryJSON = { where: WhereClause; include?: string; keys?: string; limit?: number; skip?: number; order?: string; className?: string; count?: number; }; /** * Converts a string into a regex that matches it. * Surrounding with \Q .. \E does this, we just need to escape any \E's in * the text separately. */ function quote(s: string) { return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E'; } /** * Creates a new parse Parse.Query for the given Parse.Object subclass. * @class Parse.Query * @constructor * @param {} objectClass An instance of a subclass of Parse.Object, or a Parse className string. * * <p>Parse.Query defines a query that is used to fetch Parse.Objects. The * most common use case is finding all objects that match a query through the * <code>find</code> method. For example, this sample code fetches all objects * of class <code>MyClass</code>. It calls a different function depending on * whether the fetch succeeded or not. * * <pre> * var query = new Parse.Query(MyClass); * query.find({ * success: function(results) { * // results is an array of Parse.Object. * }, * * error: function(error) { * // error is an instance of Parse.Error. * } * });</pre></p> * * <p>A Parse.Query can also be used to retrieve a single object whose id is * known, through the get method. For example, this sample code fetches an * object of class <code>MyClass</code> and id <code>myId</code>. It calls a * different function depending on whether the fetch succeeded or not. * * <pre> * var query = new Parse.Query(MyClass); * query.get(myId, { * success: function(object) { * // object is an instance of Parse.Object. * }, * * error: function(object, error) { * // error is an instance of Parse.Error. * } * });</pre></p> * * <p>A Parse.Query can also be used to count the number of objects that match * the query without retrieving all of those objects. For example, this * sample code counts the number of objects of the class <code>MyClass</code> * <pre> * var query = new Parse.Query(MyClass); * query.count({ * success: function(number) { * // There are number instances of MyClass. * }, * * error: function(error) { * // error is an instance of Parse.Error. * } * });</pre></p> */ export default class ParseQuery { className: string; _where: any; _include: Array<string>; _select: Array<string>; _limit: number; _skip: number; _order: Array<string>; _extraOptions: { [key: string]: mixed }; constructor(objectClass: string | ParseObject) { if (typeof objectClass === 'string') { if (objectClass === 'User' && CoreManager.get('PERFORM_USER_REWRITE')) { this.className = '_User'; } else { this.className = objectClass; } } else if (objectClass instanceof ParseObject) { this.className = objectClass.className; } else if (typeof objectClass === 'function') { if (typeof objectClass.className === 'string') { this.className = objectClass.className; } else { var obj = new objectClass(); this.className = obj.className; } } else { throw new TypeError( 'A ParseQuery must be constructed with a ParseObject or class name.' ); } this._where = {}; this._include = []; this._limit = -1; // negative limit is not sent in the server request this._skip = 0; this._extraOptions = {}; } /** * Adds constraint that at least one of the passed in queries matches. * @method _orQuery * @param {Array} queries * @return {Parse.Query} Returns the query, so you can chain this call. */ _orQuery(queries: Array<ParseQuery>): ParseQuery { var queryJSON = queries.map((q) => { return q.toJSON().where; }); this._where.$or = queryJSON; return this; } /** * Helper for condition queries */ _addCondition(key: string, condition: string, value: mixed): ParseQuery { if (!this._where[key] || typeof this._where[key] === 'string') { this._where[key] = {}; } this._where[key][condition] = encode(value, false, true); return this; } /** * Returns a JSON representation of this query. * @method toJSON * @return {Object} The JSON representation of the query. */ toJSON(): QueryJSON { var params: QueryJSON = { where: this._where }; if (this._include.length) { params.include = this._include.join(','); } if (this._select) { params.keys = this._select.join(','); } if (this._limit >= 0) { params.limit = this._limit; } if (this._skip > 0) { params.skip = this._skip; } if (this._order) { params.order = this._order.join(','); } for (var key in this._extraOptions) { params[key] = this._extraOptions[key]; } return params; } /** * Constructs a Parse.Object whose id is already known by fetching data from * the server. Either options.success or options.error is called when the * find completes. * * @method get * @param {String} objectId The id of the object to be fetched. * @param {Object} options A Backbone-style options object. * Valid options are:<ul> * <li>success: A Backbone-style success callback * <li>error: An Backbone-style error callback. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the result when * the query completes. */ get(objectId: string, options?: FullOptions): ParsePromise { this.equalTo('objectId', objectId); var firstOptions = {}; if (options && options.hasOwnProperty('useMasterKey')) { firstOptions.useMasterKey = options.useMasterKey; } if (options && options.hasOwnProperty('sessionToken')) { firstOptions.sessionToken = options.sessionToken; } return this.first(firstOptions).then((response) => { if (response) { return response; } var errorObject = new ParseError( ParseError.OBJECT_NOT_FOUND, 'Object not found.' ); return ParsePromise.error(errorObject); })._thenRunCallbacks(options, null); } /** * Retrieves a list of ParseObjects that satisfy this query. * Either options.success or options.error is called when the find * completes. * * @method find * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the find completes successfully. * <li>error: Function to call when the find fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the results when * the query completes. */ find(options?: FullOptions): ParsePromise { options = options || {}; let findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } let controller = CoreManager.getQueryController(); return controller.find( this.className, this.toJSON(), findOptions ).then((response) => { return response.results.map((data) => { // In cases of relations, the server may send back a className // on the top level of the payload let override = response.className || this.className; if (!data.className) { data.className = override; } return ParseObject.fromJSON(data, true); }); })._thenRunCallbacks(options); } /** * Counts the number of objects that match this query. * Either options.success or options.error is called when the count * completes. * * @method count * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the count completes successfully. * <li>error: Function to call when the find fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the count when * the query completes. */ count(options?: FullOptions): ParsePromise { options = options || {}; var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var controller = CoreManager.getQueryController(); var params = this.toJSON(); params.limit = 0; params.count = 1; return controller.find( this.className, params, findOptions ).then((result) => { return result.count; })._thenRunCallbacks(options); } /** * Retrieves at most one Parse.Object that satisfies this query. * * Either options.success or options.error is called when it completes. * success is passed the object if there is one. otherwise, undefined. * * @method first * @param {Object} options A Backbone-style options object. Valid options * are:<ul> * <li>success: Function to call when the find completes successfully. * <li>error: Function to call when the find fails. * <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to * be used for this request. * <li>sessionToken: A valid session token, used for making a request on * behalf of a specific user. * </ul> * * @return {Parse.Promise} A promise that is resolved with the object when * the query completes. */ first(options?: FullOptions): ParsePromise { options = options || {}; var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var controller = CoreManager.getQueryController(); var params = this.toJSON(); params.limit = 1; return controller.find( this.className, params, findOptions ).then((response) => { var objects = response.results; if (!objects[0]) { return undefined; } if (!objects[0].className) { objects[0].className = this.className; } return ParseObject.fromJSON(objects[0], true); })._thenRunCallbacks(options); } /** * Iterates over each result of a query, calling a callback for each one. If * the callback returns a promise, the iteration will not continue until * that promise has been fulfilled. If the callback returns a rejected * promise, then iteration will stop with that error. The items are * processed in an unspecified order. The query may not have any sort order, * and may not use limit or skip. * @method each * @param {Function} callback Callback that will be called with each result * of the query. * @param {Object} options An optional Backbone-like options object with * success and error callbacks that will be invoked once the iteration * has finished. * @return {Parse.Promise} A promise that will be fulfilled once the * iteration has completed. */ each(callback: (obj: ParseObject) => any, options?: FullOptions): ParsePromise { options = options || {}; if (this._order || this._skip || (this._limit >= 0)) { var error = 'Cannot iterate on a query with sort, skip, or limit.'; return ParsePromise.error(error)._thenRunCallbacks(options); } var promise = new ParsePromise(); var query = new ParseQuery(this.className); // We can override the batch size from the options. // This is undocumented, but useful for testing. query._limit = options.batchSize || 100; query._include = this._include.map((i) => { return i; }); if (this._select) { query._select = this._select.map((s) => { return s; }); } query._where = {}; for (var attr in this._where) { var val = this._where[attr]; if (Array.isArray(val)) { query._where[attr] = val.map((v) => { return v; }); } else if (val && typeof val === 'object') { var conditionMap = {}; query._where[attr] = conditionMap; for (var cond in val) { conditionMap[cond] = val[cond]; } } else { query._where[attr] = val; } } query.ascending('objectId'); var findOptions = {}; if (options.hasOwnProperty('useMasterKey')) { findOptions.useMasterKey = options.useMasterKey; } if (options.hasOwnProperty('sessionToken')) { findOptions.sessionToken = options.sessionToken; } var finished = false; return ParsePromise._continueWhile(() => { return !finished; }, () => { return query.find(findOptions).then((results) => { var callbacksDone = ParsePromise.as(); results.forEach((result) => { callbacksDone = callbacksDone.then(() => { return callback(result); }); }); return callbacksDone.then(() => { if (results.length >= query._limit) { query.greaterThan('objectId', results[results.length - 1].id); } else { finished = true; } }); }); })._thenRunCallbacks(options); } /** Query Conditions **/ /** * Adds a constraint to the query that requires a particular key's value to * be equal to the provided value. * @method equalTo * @param {String} key The key to check. * @param value The value that the Parse.Object must contain. * @return {Parse.Query} Returns the query, so you can chain this call. */ equalTo(key: string, value: mixed): ParseQuery { if (typeof value === 'undefined') { return this.doesNotExist(key); } this._where[key] = encode(value, false, true); return this; } /** * Adds a constraint to the query that requires a particular key's value to * be not equal to the provided value. * @method notEqualTo * @param {String} key The key to check. * @param value The value that must not be equalled. * @return {Parse.Query} Returns the query, so you can chain this call. */ notEqualTo(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$ne', value); } /** * Adds a constraint to the query that requires a particular key's value to * be less than the provided value. * @method lessThan * @param {String} key The key to check. * @param value The value that provides an upper bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ lessThan(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$lt', value); } /** * Adds a constraint to the query that requires a particular key's value to * be greater than the provided value. * @method greaterThan * @param {String} key The key to check. * @param value The value that provides an lower bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ greaterThan(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$gt', value); } /** * Adds a constraint to the query that requires a particular key's value to * be less than or equal to the provided value. * @method lessThanOrEqualTo * @param {String} key The key to check. * @param value The value that provides an upper bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ lessThanOrEqualTo(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$lte', value); } /** * Adds a constraint to the query that requires a particular key's value to * be greater than or equal to the provided value. * @method greaterThanOrEqualTo * @param {String} key The key to check. * @param value The value that provides an lower bound. * @return {Parse.Query} Returns the query, so you can chain this call. */ greaterThanOrEqualTo(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$gte', value); } /** * Adds a constraint to the query that requires a particular key's value to * be contained in the provided list of values. * @method containedIn * @param {String} key The key to check. * @param {Array} values The values that will match. * @return {Parse.Query} Returns the query, so you can chain this call. */ containedIn(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$in', value); } /** * Adds a constraint to the query that requires a particular key's value to * not be contained in the provided list of values. * @method notContainedIn * @param {String} key The key to check. * @param {Array} values The values that will not match. * @return {Parse.Query} Returns the query, so you can chain this call. */ notContainedIn(key: string, value: mixed): ParseQuery { return this._addCondition(key, '$nin', value); } /** * Adds a constraint to the query that requires a particular key's value to * contain each one of the provided list of values. * @method containsAll * @param {String} key The key to check. This key's value must be an array. * @param {Array} values The values that will match. * @return {Parse.Query} Returns the query, so you can chain this call. */ containsAll(key: string, values: Array<mixed>): ParseQuery { return this._addCondition(key, '$all', values); } /** * Adds a constraint for finding objects that contain the given key. * @method exists * @param {String} key The key that should exist. * @return {Parse.Query} Returns the query, so you can chain this call. */ exists(key: string): ParseQuery { return this._addCondition(key, '$exists', true); } /** * Adds a constraint for finding objects that do not contain a given key. * @method doesNotExist * @param {String} key The key that should not exist * @return {Parse.Query} Returns the query, so you can chain this call. */ doesNotExist(key: string): ParseQuery { return this._addCondition(key, '$exists', false); } /** * Adds a regular expression constraint for finding string values that match * the provided regular expression. * This may be slow for large datasets. * @method matches * @param {String} key The key that the string to match is stored in. * @param {RegExp} regex The regular expression pattern to match. * @return {Parse.Query} Returns the query, so you can chain this call. */ matches(key: string, regex: RegExp, modifiers: string): ParseQuery { this._addCondition(key, '$regex', regex); if (!modifiers) { modifiers = ''; } if (regex.ignoreCase) { modifiers += 'i'; } if (regex.multiline) { modifiers += 'm'; } if (modifiers.length) { this._addCondition(key, '$options', modifiers); } return this; } /** * Adds a constraint that requires that a key's value matches a Parse.Query * constraint. * @method matchesQuery * @param {String} key The key that the contains the object to match the * query. * @param {Parse.Query} query The query that should match. * @return {Parse.Query} Returns the query, so you can chain this call. */ matchesQuery(key: string, query: ParseQuery): ParseQuery { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$inQuery', queryJSON); } /** * Adds a constraint that requires that a key's value not matches a * Parse.Query constraint. * @method doesNotMatchQuery * @param {String} key The key that the contains the object to match the * query. * @param {Parse.Query} query The query that should not match. * @return {Parse.Query} Returns the query, so you can chain this call. */ doesNotMatchQuery(key: string, query: ParseQuery): ParseQuery { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$notInQuery', queryJSON); } /** * Adds a constraint that requires that a key's value matches a value in * an object returned by a different Parse.Query. * @method matchesKeyInQuery * @param {String} key The key that contains the value that is being * matched. * @param {String} queryKey The key in the objects returned by the query to * match against. * @param {Parse.Query} query The query to run. * @return {Parse.Query} Returns the query, so you can chain this call. */ matchesKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$select', { key: queryKey, query: queryJSON }); } /** * Adds a constraint that requires that a key's value not match a value in * an object returned by a different Parse.Query. * @method doesNotMatchKeyInQuery * @param {String} key The key that contains the value that is being * excluded. * @param {String} queryKey The key in the objects returned by the query to * match against. * @param {Parse.Query} query The query to run. * @return {Parse.Query} Returns the query, so you can chain this call. */ doesNotMatchKeyInQuery(key: string, queryKey: string, query: ParseQuery): ParseQuery { var queryJSON = query.toJSON(); queryJSON.className = query.className; return this._addCondition(key, '$dontSelect', { key: queryKey, query: queryJSON }); } /** * Adds a constraint for finding string values that contain a provided * string. This may be slow for large datasets. * @method contains * @param {String} key The key that the string to match is stored in. * @param {String} substring The substring that the value must contain. * @return {Parse.Query} Returns the query, so you can chain this call. */ contains(key: string, value: string): ParseQuery { if (typeof value !== 'string') { throw new Error('The value being searched for must be a string.'); } return this._addCondition(key, '$regex', quote(value)); } /** * Adds a constraint for finding string values that start with a provided * string. This query will use the backend index, so it will be fast even * for large datasets. * @method startsWith * @param {String} key The key that the string to match is stored in. * @param {String} prefix The substring that the value must start with. * @return {Parse.Query} Returns the query, so you can chain this call. */ startsWith(key: string, value: string): ParseQuery { if (typeof value !== 'string') { throw new Error('The value being searched for must be a string.'); } return this._addCondition(key, '$regex', '^' + quote(value)); } /** * Adds a constraint for finding string values that end with a provided * string. This will be slow for large datasets. * @method endsWith * @param {String} key The key that the string to match is stored in. * @param {String} suffix The substring that the value must end with. * @return {Parse.Query} Returns the query, so you can chain this call. */ endsWith(key: string, value: string): ParseQuery { if (typeof value !== 'string') { throw new Error('The value being searched for must be a string.'); } return this._addCondition(key, '$regex', quote(value) + '$'); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given. * @method near * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @return {Parse.Query} Returns the query, so you can chain this call. */ near(key: string, point: ParseGeoPoint): ParseQuery { if (!(point instanceof ParseGeoPoint)) { // Try to cast it as a GeoPoint point = new ParseGeoPoint(point); } return this._addCondition(key, '$nearSphere', point); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * @method withinRadians * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @param {Number} maxDistance Maximum distance (in radians) of results to * return. * @return {Parse.Query} Returns the query, so you can chain this call. */ withinRadians(key: string, point: ParseGeoPoint, distance: number): ParseQuery { this.near(key, point); return this._addCondition(key, '$maxDistance', distance); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * Radius of earth used is 3958.8 miles. * @method withinMiles * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @param {Number} maxDistance Maximum distance (in miles) of results to * return. * @return {Parse.Query} Returns the query, so you can chain this call. */ withinMiles(key: string, point: ParseGeoPoint, distance: number): ParseQuery { return this.withinRadians(key, point, distance / 3958.8); } /** * Adds a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * Radius of earth used is 6371.0 kilometers. * @method withinKilometers * @param {String} key The key that the Parse.GeoPoint is stored in. * @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used. * @param {Number} maxDistance Maximum distance (in kilometers) of results * to return. * @return {Parse.Query} Returns the query, so you can chain this call. */ withinKilometers(key: string, point: ParseGeoPoint, distance: number): ParseQuery { return this.withinRadians(key, point, distance / 6371.0); } /** * Adds a constraint to the query that requires a particular key's * coordinates be contained within a given rectangular geographic bounding * box. * @method withinGeoBox * @param {String} key The key to be constrained. * @param {Parse.GeoPoint} southwest * The lower-left inclusive corner of the box. * @param {Parse.GeoPoint} northeast * The upper-right inclusive corner of the box. * @return {Parse.Query} Returns the query, so you can chain this call. */ withinGeoBox(key: string, southwest: ParseGeoPoint, northeast: ParseGeoPoint): ParseQuery { if (!(southwest instanceof ParseGeoPoint)) { southwest = new ParseGeoPoint(southwest); } if (!(northeast instanceof ParseGeoPoint)) { northeast = new ParseGeoPoint(northeast); } this._addCondition(key, '$within', { '$box': [ southwest, northeast ] }); return this; } /** Query Orderings **/ /** * Sorts the results in ascending order by the given key. * * @method ascending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ ascending(...keys: Array<string>): ParseQuery { this._order = []; return this.addAscending.apply(this, keys); } /** * Sorts the results in ascending order by the given key, * but can also add secondary sort descriptors without overwriting _order. * * @method addAscending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ addAscending(...keys: Array<string>): ParseQuery { if (!this._order) { this._order = []; } keys.forEach((key) => { if (Array.isArray(key)) { key = key.join(); } this._order = this._order.concat(key.replace(/\s/g, '').split(',')); }); return this; } /** * Sorts the results in descending order by the given key. * * @method descending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ descending(...keys: Array<string>): ParseQuery { this._order = []; return this.addDescending.apply(this, keys); } /** * Sorts the results in descending order by the given key, * but can also add secondary sort descriptors without overwriting _order. * * @method addDescending * @param {(String|String[]|...String} key The key to order by, which is a * string of comma separated values, or an Array of keys, or multiple keys. * @return {Parse.Query} Returns the query, so you can chain this call. */ addDescending(...keys: Array<string>): ParseQuery { if (!this._order) { this._order = []; } keys.forEach((key) => { if (Array.isArray(key)) { key = key.join(); } this._order = this._order.concat( key.replace(/\s/g, '').split(',').map((k) => { return '-' + k; }) ); }); return this; } /** Query Options **/ /** * Sets the number of results to skip before returning any results. * This is useful for pagination. * Default is to skip zero results. * @method skip * @param {Number} n the number of results to skip. * @return {Parse.Query} Returns the query, so you can chain this call. */ skip(n: number): ParseQuery { if (typeof n !== 'number' || n < 0) { throw new Error('You can only skip by a positive number'); } this._skip = n; return this; } /** * Sets the limit of the number of results to return. The default limit is * 100, with a maximum of 1000 results being returned at a time. * @method limit * @param {Number} n the number of results to limit to. * @return {Parse.Query} Returns the query, so you can chain this call. */ limit(n: number): ParseQuery { if (typeof n !== 'number') { throw new Error('You can only set the limit to a numeric value'); } this._limit = n; return this; } /** * Includes nested Parse.Objects for the provided key. You can use dot * notation to specify which fields in the included object are also fetched. * @method include * @param {String} key The name of the key to include. * @return {Parse.Query} Returns the query, so you can chain this call. */ include(...keys: Array<string>): ParseQuery { keys.forEach((key) => { if (Array.isArray(key)) { this._include = this._include.concat(key); } else { this._include.push(key); } }); return this; } /** * Restricts the fields of the returned Parse.Objects to include only the * provided keys. If this is called multiple times, then all of the keys * specified in each of the calls will be included. * @method select * @param {Array} keys The names of the keys to include. * @return {Parse.Query} Returns the query, so you can chain this call. */ select(...keys: Array<string>): ParseQuery { if (!this._select) { this._select = []; } keys.forEach((key) => { if (Array.isArray(key)) { this._select = this._select.concat(key); } else { this._select.push(key); } }); return this; } /** * Subscribe this query to get liveQuery updates * @method subscribe * @return {LiveQuerySubscription} Returns the liveQuerySubscription, it's an event emitter * which can be used to get liveQuery updates. */ subscribe(): any { let controller = CoreManager.getLiveQueryController(); return controller.subscribe(this); } /** * Constructs a Parse.Query that is the OR of the passed in queries. For * example: * <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre> * * will create a compoundQuery that is an or of the query1, query2, and * query3. * @method or * @param {...Parse.Query} var_args The list of queries to OR. * @static * @return {Parse.Query} The query that is the OR of the passed in queries. */ static or(...queries: Array<ParseQuery>): ParseQuery { var className = null; queries.forEach((q) => { if (!className) { className = q.className; } if (className !== q.className) { throw new Error('All queries must be for the same class.'); } }); var query = new ParseQuery(className); query._orQuery(queries); return query; } } var DefaultController = { find(className: string, params: QueryJSON, options: RequestOptions): ParsePromise { var RESTController = CoreManager.getRESTController(); return RESTController.request( 'GET', 'classes/' + className, params, options ); } }; CoreManager.setQueryController(DefaultController);
nitrag/TiParseJS
Parse-SDK-JS-master/src/ParseQuery.js
JavaScript
mit
34,936
/*! Material Components for the web Copyright (c) 2017 Google Inc. License: Apache-2.0 */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["checkbox"] = factory(); else root["mdc"] = root["mdc"] || {}, root["mdc"]["checkbox"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/assets/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 27); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @template A */ var MDCFoundation = function () { _createClass(MDCFoundation, null, [{ key: "cssClasses", /** @return enum{cssClasses} */ get: function get() { // Classes extending MDCFoundation should implement this method to return an object which exports every // CSS class the foundation class needs as a property. e.g. {ACTIVE: 'mdc-component--active'} return {}; } /** @return enum{strings} */ }, { key: "strings", get: function get() { // Classes extending MDCFoundation should implement this method to return an object which exports all // semantic strings as constants. e.g. {ARIA_ROLE: 'tablist'} return {}; } /** @return enum{numbers} */ }, { key: "numbers", get: function get() { // Classes extending MDCFoundation should implement this method to return an object which exports all // of its semantic numbers as constants. e.g. {ANIMATION_DELAY_MS: 350} return {}; } /** @return {!Object} */ }, { key: "defaultAdapter", get: function get() { // Classes extending MDCFoundation may choose to implement this getter in order to provide a convenient // way of viewing the necessary methods of an adapter. In the future, this could also be used for adapter // validation. return {}; } /** * @param {A=} adapter */ }]); function MDCFoundation() { var adapter = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, MDCFoundation); /** @protected {!A} */ this.adapter_ = adapter; } _createClass(MDCFoundation, [{ key: "init", value: function init() { // Subclasses should override this method to perform initialization routines (registering events, etc.) } }, { key: "destroy", value: function destroy() { // Subclasses should override this method to perform de-initialization routines (de-registering events, etc.) } }]); return MDCFoundation; }(); /* harmony default export */ __webpack_exports__["a"] = (MDCFoundation); /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation__ = __webpack_require__(0); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @template F */ var MDCComponent = function () { _createClass(MDCComponent, null, [{ key: 'attachTo', /** * @param {!Element} root * @return {!MDCComponent} */ value: function attachTo(root) { // Subclasses which extend MDCBase should provide an attachTo() method that takes a root element and // returns an instantiated component with its root set to that element. Also note that in the cases of // subclasses, an explicit foundation class will not have to be passed in; it will simply be initialized // from getDefaultFoundation(). return new MDCComponent(root, new __WEBPACK_IMPORTED_MODULE_0__foundation__["a" /* default */]()); } /** * @param {!Element} root * @param {F=} foundation * @param {...?} args */ }]); function MDCComponent(root) { var foundation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; _classCallCheck(this, MDCComponent); /** @protected {!Element} */ this.root_ = root; for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } this.initialize.apply(this, args); // Note that we initialize foundation here and not within the constructor's default param so that // this.root_ is defined and can be used within the foundation class. /** @protected {!F} */ this.foundation_ = foundation === undefined ? this.getDefaultFoundation() : foundation; this.foundation_.init(); this.initialSyncWithDOM(); } _createClass(MDCComponent, [{ key: 'initialize', value: function initialize() /* ...args */{} // Subclasses can override this to do any additional setup work that would be considered part of a // "constructor". Essentially, it is a hook into the parent constructor before the foundation is // initialized. Any additional arguments besides root and foundation will be passed in here. /** * @return {!F} foundation */ }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { // Subclasses must override this method to return a properly configured foundation class for the // component. throw new Error('Subclasses must override getDefaultFoundation to return a properly configured ' + 'foundation class'); } }, { key: 'initialSyncWithDOM', value: function initialSyncWithDOM() { // Subclasses should override this method if they need to perform work to synchronize with a host DOM // object. An example of this would be a form control wrapper that needs to synchronize its internal state // to some property or attribute of the host DOM. Please note: this is *not* the place to perform DOM // reads/writes that would cause layout / paint, as this is called synchronously from within the constructor. } }, { key: 'destroy', value: function destroy() { // Subclasses may implement this method to release any resources / deregister any listeners they have // attached. An example of this might be deregistering a resize event from the window object. this.foundation_.destroy(); } /** * Wrapper method to add an event listener to the component's root element. This is most useful when * listening for custom events. * @param {string} evtType * @param {!Function} handler */ }, { key: 'listen', value: function listen(evtType, handler) { this.root_.addEventListener(evtType, handler); } /** * Wrapper method to remove an event listener to the component's root element. This is most useful when * unlistening for custom events. * @param {string} evtType * @param {!Function} handler */ }, { key: 'unlisten', value: function unlisten(evtType, handler) { this.root_.removeEventListener(evtType, handler); } /** * Fires a cross-browser-compatible custom event from the component root of the given type, * with the given data. * @param {string} evtType * @param {!Object} evtData * @param {boolean=} shouldBubble */ }, { key: 'emit', value: function emit(evtType, evtData) { var shouldBubble = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var evt = void 0; if (typeof CustomEvent === 'function') { evt = new CustomEvent(evtType, { detail: evtData, bubbles: shouldBubble }); } else { evt = document.createEvent('CustomEvent'); evt.initCustomEvent(evtType, shouldBubble, false, evtData); } this.root_.dispatchEvent(evt); } }]); return MDCComponent; }(); /* harmony default export */ __webpack_exports__["a"] = (MDCComponent); /***/ }), /* 2 */, /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (immutable) */ __webpack_exports__["supportsCssVariables"] = supportsCssVariables; /* harmony export (immutable) */ __webpack_exports__["applyPassive"] = applyPassive; /* harmony export (immutable) */ __webpack_exports__["getMatchesProperty"] = getMatchesProperty; /* harmony export (immutable) */ __webpack_exports__["getNormalizedEventCoords"] = getNormalizedEventCoords; /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @private {boolean|undefined} */ var supportsPassive_ = void 0; /** * @param {!Window} windowObj * @return {boolean|undefined} */ function supportsCssVariables(windowObj) { var supportsFunctionPresent = windowObj.CSS && typeof windowObj.CSS.supports === 'function'; if (!supportsFunctionPresent) { return; } var explicitlySupportsCssVars = windowObj.CSS.supports('--css-vars', 'yes'); // See: https://bugs.webkit.org/show_bug.cgi?id=154669 // See: README section on Safari var weAreFeatureDetectingSafari10plus = windowObj.CSS.supports('(--css-vars: yes)') && windowObj.CSS.supports('color', '#00000000'); return explicitlySupportsCssVars || weAreFeatureDetectingSafari10plus; } // /** * Determine whether the current browser supports passive event listeners, and if so, use them. * @param {!Window=} globalObj * @param {boolean=} forceRefresh * @return {boolean|{passive: boolean}} */ function applyPassive() { var globalObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window; var forceRefresh = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (supportsPassive_ === undefined || forceRefresh) { var isSupported = false; try { globalObj.document.addEventListener('test', null, { get passive() { isSupported = true; } }); } catch (e) {} supportsPassive_ = isSupported; } return supportsPassive_ ? { passive: true } : false; } /** * @param {!Object} HTMLElementPrototype * @return {!Array<string>} */ function getMatchesProperty(HTMLElementPrototype) { return ['webkitMatchesSelector', 'msMatchesSelector', 'matches'].filter(function (p) { return p in HTMLElementPrototype; }).pop(); } /** * @param {!Event} ev * @param {!{x: number, y: number}} pageOffset * @param {!ClientRect} clientRect * @return {!{x: number, y: number}} */ function getNormalizedEventCoords(ev, pageOffset, clientRect) { var x = pageOffset.x, y = pageOffset.y; var documentX = x + clientRect.left; var documentY = y + clientRect.top; var normalizedX = void 0; var normalizedY = void 0; // Determine touch point relative to the ripple container. if (ev.type === 'touchstart') { normalizedX = ev.changedTouches[0].pageX - documentX; normalizedY = ev.changedTouches[0].pageY - documentY; } else { normalizedX = ev.pageX - documentX; normalizedY = ev.pageY - documentY; } return { x: normalizedX, y: normalizedY }; } /***/ }), /* 4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint no-unused-vars: [2, {"args": "none"}] */ /** * Adapter for MDC Ripple. Provides an interface for managing * - classes * - dom * - CSS variables * - position * - dimensions * - scroll position * - event handlers * - unbounded, active and disabled states * * Additionally, provides type information for the adapter to the Closure * compiler. * * Implement this adapter for your framework of choice to delegate updates to * the component in your framework of choice. See architecture documentation * for more details. * https://github.com/material-components/material-components-web/blob/master/docs/architecture.md * * @record */ var MDCRippleAdapter = function () { function MDCRippleAdapter() { _classCallCheck(this, MDCRippleAdapter); } _createClass(MDCRippleAdapter, [{ key: "browserSupportsCssVars", /** @return {boolean} */ value: function browserSupportsCssVars() {} /** @return {boolean} */ }, { key: "isUnbounded", value: function isUnbounded() {} /** @return {boolean} */ }, { key: "isSurfaceActive", value: function isSurfaceActive() {} /** @return {boolean} */ }, { key: "isSurfaceDisabled", value: function isSurfaceDisabled() {} /** @param {string} className */ }, { key: "addClass", value: function addClass(className) {} /** @param {string} className */ }, { key: "removeClass", value: function removeClass(className) {} /** * @param {string} evtType * @param {!Function} handler */ }, { key: "registerInteractionHandler", value: function registerInteractionHandler(evtType, handler) {} /** * @param {string} evtType * @param {!Function} handler */ }, { key: "deregisterInteractionHandler", value: function deregisterInteractionHandler(evtType, handler) {} /** * @param {!Function} handler */ }, { key: "registerResizeHandler", value: function registerResizeHandler(handler) {} /** * @param {!Function} handler */ }, { key: "deregisterResizeHandler", value: function deregisterResizeHandler(handler) {} /** * @param {string} varName * @param {?number|string} value */ }, { key: "updateCssVariable", value: function updateCssVariable(varName, value) {} /** @return {!ClientRect} */ }, { key: "computeBoundingRect", value: function computeBoundingRect() {} /** @return {{x: number, y: number}} */ }, { key: "getWindowPageOffset", value: function getWindowPageOffset() {} }]); return MDCRippleAdapter; }(); /* unused harmony default export */ var _unused_webpack_default_export = (MDCRippleAdapter); /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRipple", function() { return MDCRipple; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_component__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(3); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "MDCRippleFoundation", function() { return __WEBPACK_IMPORTED_MODULE_2__foundation__["a"]; }); /* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "util", function() { return __WEBPACK_IMPORTED_MODULE_3__util__; }); var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @extends MDCComponent<!MDCRippleFoundation> */ var MDCRipple = function (_MDCComponent) { _inherits(MDCRipple, _MDCComponent); /** @param {...?} args */ function MDCRipple() { var _ref; _classCallCheck(this, MDCRipple); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } /** @type {boolean} */ var _this = _possibleConstructorReturn(this, (_ref = MDCRipple.__proto__ || Object.getPrototypeOf(MDCRipple)).call.apply(_ref, [this].concat(args))); _this.disabled = false; /** @private {boolean} */ _this.unbounded_; return _this; } /** * @param {!Element} root * @param {{isUnbounded: (boolean|undefined)}=} options * @return {!MDCRipple} */ _createClass(MDCRipple, [{ key: 'activate', value: function activate() { this.foundation_.activate(); } }, { key: 'deactivate', value: function deactivate() { this.foundation_.deactivate(); } }, { key: 'layout', value: function layout() { this.foundation_.layout(); } /** @return {!MDCRippleFoundation} */ }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { return new __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */](MDCRipple.createAdapter(this)); } }, { key: 'initialSyncWithDOM', value: function initialSyncWithDOM() { this.unbounded = 'mdcRippleIsUnbounded' in this.root_.dataset; } }, { key: 'unbounded', /** @return {boolean} */ get: function get() { return this.unbounded_; } /** @param {boolean} unbounded */ , set: function set(unbounded) { var UNBOUNDED = __WEBPACK_IMPORTED_MODULE_2__foundation__["a" /* default */].cssClasses.UNBOUNDED; this.unbounded_ = Boolean(unbounded); if (this.unbounded_) { this.root_.classList.add(UNBOUNDED); } else { this.root_.classList.remove(UNBOUNDED); } } }], [{ key: 'attachTo', value: function attachTo(root) { var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref2$isUnbounded = _ref2.isUnbounded, isUnbounded = _ref2$isUnbounded === undefined ? undefined : _ref2$isUnbounded; var ripple = new MDCRipple(root); // Only override unbounded behavior if option is explicitly specified if (isUnbounded !== undefined) { ripple.unbounded = /** @type {boolean} */isUnbounded; } return ripple; } /** * @param {!RippleCapableSurface} instance * @return {!MDCRippleAdapter} */ }, { key: 'createAdapter', value: function createAdapter(instance) { var MATCHES = __WEBPACK_IMPORTED_MODULE_3__util__["getMatchesProperty"](HTMLElement.prototype); return { browserSupportsCssVars: function browserSupportsCssVars() { return __WEBPACK_IMPORTED_MODULE_3__util__["supportsCssVariables"](window); }, isUnbounded: function isUnbounded() { return instance.unbounded; }, isSurfaceActive: function isSurfaceActive() { return instance.root_[MATCHES](':active'); }, isSurfaceDisabled: function isSurfaceDisabled() { return instance.disabled; }, addClass: function addClass(className) { return instance.root_.classList.add(className); }, removeClass: function removeClass(className) { return instance.root_.classList.remove(className); }, registerInteractionHandler: function registerInteractionHandler(evtType, handler) { return instance.root_.addEventListener(evtType, handler, __WEBPACK_IMPORTED_MODULE_3__util__["applyPassive"]()); }, deregisterInteractionHandler: function deregisterInteractionHandler(evtType, handler) { return instance.root_.removeEventListener(evtType, handler, __WEBPACK_IMPORTED_MODULE_3__util__["applyPassive"]()); }, registerResizeHandler: function registerResizeHandler(handler) { return window.addEventListener('resize', handler); }, deregisterResizeHandler: function deregisterResizeHandler(handler) { return window.removeEventListener('resize', handler); }, updateCssVariable: function updateCssVariable(varName, value) { return instance.root_.style.setProperty(varName, value); }, computeBoundingRect: function computeBoundingRect() { return instance.root_.getBoundingClientRect(); }, getWindowPageOffset: function getWindowPageOffset() { return { x: window.pageXOffset, y: window.pageYOffset }; } }; } }]); return MDCRipple; }(__WEBPACK_IMPORTED_MODULE_0__material_base_component__["a" /* default */]); /** * See Material Design spec for more details on when to use ripples. * https://material.io/guidelines/motion/choreography.html#choreography-creation * @record */ var RippleCapableSurface = function RippleCapableSurface() { _classCallCheck(this, RippleCapableSurface); }; /** @protected {!Element} */ RippleCapableSurface.prototype.root_; /** * Whether or not the ripple bleeds out of the bounds of the element. * @type {boolean|undefined} */ RippleCapableSurface.prototype.unbounded; /** * Whether or not the ripple is attached to a disabled component. * @type {boolean|undefined} */ RippleCapableSurface.prototype.disabled; /***/ }), /* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_foundation__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constants__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__util__ = __webpack_require__(3); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @typedef {!{ * isActivated: (boolean|undefined), * hasDeactivationUXRun: (boolean|undefined), * wasActivatedByPointer: (boolean|undefined), * wasElementMadeActive: (boolean|undefined), * activationStartTime: (number|undefined), * activationEvent: Event, * isProgrammatic: (boolean|undefined) * }} */ var ActivationStateType = void 0; /** * @typedef {!{ * activate: (string|undefined), * deactivate: (string|undefined), * focus: (string|undefined), * blur: (string|undefined) * }} */ var ListenerInfoType = void 0; /** * @typedef {!{ * activate: function(!Event), * deactivate: function(!Event), * focus: function(), * blur: function() * }} */ var ListenersType = void 0; /** * @typedef {!{ * x: number, * y: number * }} */ var PointType = void 0; /** * @enum {string} */ var DEACTIVATION_ACTIVATION_PAIRS = { mouseup: 'mousedown', pointerup: 'pointerdown', touchend: 'touchstart', keyup: 'keydown', blur: 'focus' }; /** * @extends {MDCFoundation<!MDCRippleAdapter>} */ var MDCRippleFoundation = function (_MDCFoundation) { _inherits(MDCRippleFoundation, _MDCFoundation); _createClass(MDCRippleFoundation, [{ key: 'isSupported_', /** * We compute this property so that we are not querying information about the client * until the point in time where the foundation requests it. This prevents scenarios where * client-side feature-detection may happen too early, such as when components are rendered on the server * and then initialized at mount time on the client. * @return {boolean} */ get: function get() { return this.adapter_.browserSupportsCssVars(); } }], [{ key: 'cssClasses', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */]; } }, { key: 'strings', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */]; } }, { key: 'numbers', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */]; } }, { key: 'defaultAdapter', get: function get() { return { browserSupportsCssVars: function browserSupportsCssVars() /* boolean - cached */{}, isUnbounded: function isUnbounded() /* boolean */{}, isSurfaceActive: function isSurfaceActive() /* boolean */{}, isSurfaceDisabled: function isSurfaceDisabled() /* boolean */{}, addClass: function addClass() /* className: string */{}, removeClass: function removeClass() /* className: string */{}, registerInteractionHandler: function registerInteractionHandler() /* evtType: string, handler: EventListener */{}, deregisterInteractionHandler: function deregisterInteractionHandler() /* evtType: string, handler: EventListener */{}, registerResizeHandler: function registerResizeHandler() /* handler: EventListener */{}, deregisterResizeHandler: function deregisterResizeHandler() /* handler: EventListener */{}, updateCssVariable: function updateCssVariable() /* varName: string, value: string */{}, computeBoundingRect: function computeBoundingRect() /* ClientRect */{}, getWindowPageOffset: function getWindowPageOffset() /* {x: number, y: number} */{} }; } }]); function MDCRippleFoundation(adapter) { _classCallCheck(this, MDCRippleFoundation); /** @private {number} */ var _this = _possibleConstructorReturn(this, (MDCRippleFoundation.__proto__ || Object.getPrototypeOf(MDCRippleFoundation)).call(this, _extends(MDCRippleFoundation.defaultAdapter, adapter))); _this.layoutFrame_ = 0; /** @private {!ClientRect} */ _this.frame_ = /** @type {!ClientRect} */{ width: 0, height: 0 }; /** @private {!ActivationStateType} */ _this.activationState_ = _this.defaultActivationState_(); /** @private {number} */ _this.xfDuration_ = 0; /** @private {number} */ _this.initialSize_ = 0; /** @private {number} */ _this.maxRadius_ = 0; /** @private {!Array<{ListenerInfoType}>} */ _this.listenerInfos_ = [{ activate: 'touchstart', deactivate: 'touchend' }, { activate: 'pointerdown', deactivate: 'pointerup' }, { activate: 'mousedown', deactivate: 'mouseup' }, { activate: 'keydown', deactivate: 'keyup' }, { focus: 'focus', blur: 'blur' }]; /** @private {!ListenersType} */ _this.listeners_ = { activate: function activate(e) { return _this.activate_(e); }, deactivate: function deactivate(e) { return _this.deactivate_(e); }, focus: function focus() { return requestAnimationFrame(function () { return _this.adapter_.addClass(MDCRippleFoundation.cssClasses.BG_FOCUSED); }); }, blur: function blur() { return requestAnimationFrame(function () { return _this.adapter_.removeClass(MDCRippleFoundation.cssClasses.BG_FOCUSED); }); } }; /** @private {!Function} */ _this.resizeHandler_ = function () { return _this.layout(); }; /** @private {!{left: number, top:number}} */ _this.unboundedCoords_ = { left: 0, top: 0 }; /** @private {number} */ _this.fgScale_ = 0; /** @private {number} */ _this.activationTimer_ = 0; /** @private {number} */ _this.fgDeactivationRemovalTimer_ = 0; /** @private {boolean} */ _this.activationAnimationHasEnded_ = false; /** @private {!Function} */ _this.activationTimerCallback_ = function () { _this.activationAnimationHasEnded_ = true; _this.runDeactivationUXLogicIfReady_(); }; return _this; } /** * @return {!ActivationStateType} */ _createClass(MDCRippleFoundation, [{ key: 'defaultActivationState_', value: function defaultActivationState_() { return { isActivated: false, hasDeactivationUXRun: false, wasActivatedByPointer: false, wasElementMadeActive: false, activationStartTime: 0, activationEvent: null, isProgrammatic: false }; } }, { key: 'init', value: function init() { var _this2 = this; if (!this.isSupported_) { return; } this.addEventListeners_(); var _MDCRippleFoundation$ = MDCRippleFoundation.cssClasses, ROOT = _MDCRippleFoundation$.ROOT, UNBOUNDED = _MDCRippleFoundation$.UNBOUNDED; requestAnimationFrame(function () { _this2.adapter_.addClass(ROOT); if (_this2.adapter_.isUnbounded()) { _this2.adapter_.addClass(UNBOUNDED); } _this2.layoutInternal_(); }); } /** @private */ }, { key: 'addEventListeners_', value: function addEventListeners_() { var _this3 = this; this.listenerInfos_.forEach(function (info) { Object.keys(info).forEach(function (k) { _this3.adapter_.registerInteractionHandler(info[k], _this3.listeners_[k]); }); }); this.adapter_.registerResizeHandler(this.resizeHandler_); } /** * @param {Event} e * @private */ }, { key: 'activate_', value: function activate_(e) { var _this4 = this; if (this.adapter_.isSurfaceDisabled()) { return; } var activationState = this.activationState_; if (activationState.isActivated) { return; } activationState.isActivated = true; activationState.isProgrammatic = e === null; activationState.activationEvent = e; activationState.wasActivatedByPointer = activationState.isProgrammatic ? false : e.type === 'mousedown' || e.type === 'touchstart' || e.type === 'pointerdown'; activationState.activationStartTime = Date.now(); requestAnimationFrame(function () { // This needs to be wrapped in an rAF call b/c web browsers // report active states inconsistently when they're called within // event handling code: // - https://bugs.chromium.org/p/chromium/issues/detail?id=635971 // - https://bugzilla.mozilla.org/show_bug.cgi?id=1293741 activationState.wasElementMadeActive = e && e.type === 'keydown' ? _this4.adapter_.isSurfaceActive() : true; if (activationState.wasElementMadeActive) { _this4.animateActivation_(); } else { // Reset activation state immediately if element was not made active. _this4.activationState_ = _this4.defaultActivationState_(); } }); } }, { key: 'activate', value: function activate() { this.activate_(null); } /** @private */ }, { key: 'animateActivation_', value: function animateActivation_() { var _this5 = this; var _MDCRippleFoundation$2 = MDCRippleFoundation.strings, VAR_FG_TRANSLATE_START = _MDCRippleFoundation$2.VAR_FG_TRANSLATE_START, VAR_FG_TRANSLATE_END = _MDCRippleFoundation$2.VAR_FG_TRANSLATE_END; var _MDCRippleFoundation$3 = MDCRippleFoundation.cssClasses, BG_ACTIVE_FILL = _MDCRippleFoundation$3.BG_ACTIVE_FILL, FG_DEACTIVATION = _MDCRippleFoundation$3.FG_DEACTIVATION, FG_ACTIVATION = _MDCRippleFoundation$3.FG_ACTIVATION; var DEACTIVATION_TIMEOUT_MS = MDCRippleFoundation.numbers.DEACTIVATION_TIMEOUT_MS; var translateStart = ''; var translateEnd = ''; if (!this.adapter_.isUnbounded()) { var _getFgTranslationCoor = this.getFgTranslationCoordinates_(), startPoint = _getFgTranslationCoor.startPoint, endPoint = _getFgTranslationCoor.endPoint; translateStart = startPoint.x + 'px, ' + startPoint.y + 'px'; translateEnd = endPoint.x + 'px, ' + endPoint.y + 'px'; } this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_START, translateStart); this.adapter_.updateCssVariable(VAR_FG_TRANSLATE_END, translateEnd); // Cancel any ongoing activation/deactivation animations clearTimeout(this.activationTimer_); clearTimeout(this.fgDeactivationRemovalTimer_); this.rmBoundedActivationClasses_(); this.adapter_.removeClass(FG_DEACTIVATION); // Force layout in order to re-trigger the animation. this.adapter_.computeBoundingRect(); this.adapter_.addClass(BG_ACTIVE_FILL); this.adapter_.addClass(FG_ACTIVATION); this.activationTimer_ = setTimeout(function () { return _this5.activationTimerCallback_(); }, DEACTIVATION_TIMEOUT_MS); } /** * @private * @return {{startPoint: PointType, endPoint: PointType}} */ }, { key: 'getFgTranslationCoordinates_', value: function getFgTranslationCoordinates_() { var activationState = this.activationState_; var activationEvent = activationState.activationEvent, wasActivatedByPointer = activationState.wasActivatedByPointer; var startPoint = void 0; if (wasActivatedByPointer) { startPoint = __WEBPACK_IMPORTED_MODULE_3__util__["getNormalizedEventCoords"]( /** @type {!Event} */activationEvent, this.adapter_.getWindowPageOffset(), this.adapter_.computeBoundingRect()); } else { startPoint = { x: this.frame_.width / 2, y: this.frame_.height / 2 }; } // Center the element around the start point. startPoint = { x: startPoint.x - this.initialSize_ / 2, y: startPoint.y - this.initialSize_ / 2 }; var endPoint = { x: this.frame_.width / 2 - this.initialSize_ / 2, y: this.frame_.height / 2 - this.initialSize_ / 2 }; return { startPoint: startPoint, endPoint: endPoint }; } /** @private */ }, { key: 'runDeactivationUXLogicIfReady_', value: function runDeactivationUXLogicIfReady_() { var _this6 = this; var FG_DEACTIVATION = MDCRippleFoundation.cssClasses.FG_DEACTIVATION; var _activationState_ = this.activationState_, hasDeactivationUXRun = _activationState_.hasDeactivationUXRun, isActivated = _activationState_.isActivated; var activationHasEnded = hasDeactivationUXRun || !isActivated; if (activationHasEnded && this.activationAnimationHasEnded_) { this.rmBoundedActivationClasses_(); this.adapter_.addClass(FG_DEACTIVATION); this.fgDeactivationRemovalTimer_ = setTimeout(function () { _this6.adapter_.removeClass(FG_DEACTIVATION); }, __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */].FG_DEACTIVATION_MS); } } /** @private */ }, { key: 'rmBoundedActivationClasses_', value: function rmBoundedActivationClasses_() { var _MDCRippleFoundation$4 = MDCRippleFoundation.cssClasses, BG_ACTIVE_FILL = _MDCRippleFoundation$4.BG_ACTIVE_FILL, FG_ACTIVATION = _MDCRippleFoundation$4.FG_ACTIVATION; this.adapter_.removeClass(BG_ACTIVE_FILL); this.adapter_.removeClass(FG_ACTIVATION); this.activationAnimationHasEnded_ = false; this.adapter_.computeBoundingRect(); } /** * @param {Event} e * @private */ }, { key: 'deactivate_', value: function deactivate_(e) { var _this7 = this; var activationState = this.activationState_; // This can happen in scenarios such as when you have a keyup event that blurs the element. if (!activationState.isActivated) { return; } // Programmatic deactivation. if (activationState.isProgrammatic) { var evtObject = null; var _state = /** @type {!ActivationStateType} */_extends({}, activationState); requestAnimationFrame(function () { return _this7.animateDeactivation_(evtObject, _state); }); this.activationState_ = this.defaultActivationState_(); return; } var actualActivationType = DEACTIVATION_ACTIVATION_PAIRS[e.type]; var expectedActivationType = activationState.activationEvent.type; // NOTE: Pointer events are tricky - https://patrickhlauke.github.io/touch/tests/results/ // Essentially, what we need to do here is decouple the deactivation UX from the actual // deactivation state itself. This way, touch/pointer events in sequence do not trample one // another. var needsDeactivationUX = actualActivationType === expectedActivationType; var needsActualDeactivation = needsDeactivationUX; if (activationState.wasActivatedByPointer) { needsActualDeactivation = e.type === 'mouseup'; } var state = /** @type {!ActivationStateType} */_extends({}, activationState); requestAnimationFrame(function () { if (needsDeactivationUX) { _this7.activationState_.hasDeactivationUXRun = true; _this7.animateDeactivation_(e, state); } if (needsActualDeactivation) { _this7.activationState_ = _this7.defaultActivationState_(); } }); } }, { key: 'deactivate', value: function deactivate() { this.deactivate_(null); } /** * @param {Event} e * @param {!ActivationStateType} options * @private */ }, { key: 'animateDeactivation_', value: function animateDeactivation_(e, _ref) { var wasActivatedByPointer = _ref.wasActivatedByPointer, wasElementMadeActive = _ref.wasElementMadeActive; var BG_FOCUSED = MDCRippleFoundation.cssClasses.BG_FOCUSED; if (wasActivatedByPointer || wasElementMadeActive) { // Remove class left over by element being focused this.adapter_.removeClass(BG_FOCUSED); this.runDeactivationUXLogicIfReady_(); } } }, { key: 'destroy', value: function destroy() { var _this8 = this; if (!this.isSupported_) { return; } this.removeEventListeners_(); var _MDCRippleFoundation$5 = MDCRippleFoundation.cssClasses, ROOT = _MDCRippleFoundation$5.ROOT, UNBOUNDED = _MDCRippleFoundation$5.UNBOUNDED; requestAnimationFrame(function () { _this8.adapter_.removeClass(ROOT); _this8.adapter_.removeClass(UNBOUNDED); _this8.removeCssVars_(); }); } /** @private */ }, { key: 'removeEventListeners_', value: function removeEventListeners_() { var _this9 = this; this.listenerInfos_.forEach(function (info) { Object.keys(info).forEach(function (k) { _this9.adapter_.deregisterInteractionHandler(info[k], _this9.listeners_[k]); }); }); this.adapter_.deregisterResizeHandler(this.resizeHandler_); } /** @private */ }, { key: 'removeCssVars_', value: function removeCssVars_() { var _this10 = this; var strings = MDCRippleFoundation.strings; Object.keys(strings).forEach(function (k) { if (k.indexOf('VAR_') === 0) { _this10.adapter_.updateCssVariable(strings[k], null); } }); } }, { key: 'layout', value: function layout() { var _this11 = this; if (this.layoutFrame_) { cancelAnimationFrame(this.layoutFrame_); } this.layoutFrame_ = requestAnimationFrame(function () { _this11.layoutInternal_(); _this11.layoutFrame_ = 0; }); } /** @private */ }, { key: 'layoutInternal_', value: function layoutInternal_() { this.frame_ = this.adapter_.computeBoundingRect(); var maxDim = Math.max(this.frame_.height, this.frame_.width); var surfaceDiameter = Math.sqrt(Math.pow(this.frame_.width, 2) + Math.pow(this.frame_.height, 2)); // 60% of the largest dimension of the surface this.initialSize_ = maxDim * MDCRippleFoundation.numbers.INITIAL_ORIGIN_SCALE; // Diameter of the surface + 10px this.maxRadius_ = surfaceDiameter + MDCRippleFoundation.numbers.PADDING; this.fgScale_ = this.maxRadius_ / this.initialSize_; this.xfDuration_ = 1000 * Math.sqrt(this.maxRadius_ / 1024); this.updateLayoutCssVars_(); } /** @private */ }, { key: 'updateLayoutCssVars_', value: function updateLayoutCssVars_() { var _MDCRippleFoundation$6 = MDCRippleFoundation.strings, VAR_SURFACE_WIDTH = _MDCRippleFoundation$6.VAR_SURFACE_WIDTH, VAR_SURFACE_HEIGHT = _MDCRippleFoundation$6.VAR_SURFACE_HEIGHT, VAR_FG_SIZE = _MDCRippleFoundation$6.VAR_FG_SIZE, VAR_LEFT = _MDCRippleFoundation$6.VAR_LEFT, VAR_TOP = _MDCRippleFoundation$6.VAR_TOP, VAR_FG_SCALE = _MDCRippleFoundation$6.VAR_FG_SCALE; this.adapter_.updateCssVariable(VAR_SURFACE_WIDTH, this.frame_.width + 'px'); this.adapter_.updateCssVariable(VAR_SURFACE_HEIGHT, this.frame_.height + 'px'); this.adapter_.updateCssVariable(VAR_FG_SIZE, this.initialSize_ + 'px'); this.adapter_.updateCssVariable(VAR_FG_SCALE, this.fgScale_); if (this.adapter_.isUnbounded()) { this.unboundedCoords_ = { left: Math.round(this.frame_.width / 2 - this.initialSize_ / 2), top: Math.round(this.frame_.height / 2 - this.initialSize_ / 2) }; this.adapter_.updateCssVariable(VAR_LEFT, this.unboundedCoords_.left + 'px'); this.adapter_.updateCssVariable(VAR_TOP, this.unboundedCoords_.top + 'px'); } } }]); return MDCRippleFoundation; }(__WEBPACK_IMPORTED_MODULE_0__material_base_foundation__["a" /* default */]); /* harmony default export */ __webpack_exports__["a"] = (MDCRippleFoundation); /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cssClasses; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return strings; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return numbers; }); /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var cssClasses = { // Ripple is a special case where the "root" component is really a "mixin" of sorts, // given that it's an 'upgrade' to an existing component. That being said it is the root // CSS class that all other CSS classes derive from. ROOT: 'mdc-ripple-upgraded', UNBOUNDED: 'mdc-ripple-upgraded--unbounded', BG_FOCUSED: 'mdc-ripple-upgraded--background-focused', BG_ACTIVE_FILL: 'mdc-ripple-upgraded--background-active-fill', FG_ACTIVATION: 'mdc-ripple-upgraded--foreground-activation', FG_DEACTIVATION: 'mdc-ripple-upgraded--foreground-deactivation' }; var strings = { VAR_SURFACE_WIDTH: '--mdc-ripple-surface-width', VAR_SURFACE_HEIGHT: '--mdc-ripple-surface-height', VAR_FG_SIZE: '--mdc-ripple-fg-size', VAR_LEFT: '--mdc-ripple-left', VAR_TOP: '--mdc-ripple-top', VAR_FG_SCALE: '--mdc-ripple-fg-scale', VAR_FG_TRANSLATE_START: '--mdc-ripple-fg-translate-start', VAR_FG_TRANSLATE_END: '--mdc-ripple-fg-translate-end' }; var numbers = { PADDING: 10, INITIAL_ORIGIN_SCALE: 0.6, DEACTIVATION_TIMEOUT_MS: 300, FG_DEACTIVATION_MS: 83 }; /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "transformStyleProperties", function() { return transformStyleProperties; }); /* harmony export (immutable) */ __webpack_exports__["getCorrectEventName"] = getCorrectEventName; /* harmony export (immutable) */ __webpack_exports__["getCorrectPropertyName"] = getCorrectPropertyName; /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @typedef {{ * noPrefix: string, * webkitPrefix: string * }} */ var VendorPropertyMapType = void 0; /** @const {Object<string, !VendorPropertyMapType>} */ var eventTypeMap = { 'animationstart': { noPrefix: 'animationstart', webkitPrefix: 'webkitAnimationStart', styleProperty: 'animation' }, 'animationend': { noPrefix: 'animationend', webkitPrefix: 'webkitAnimationEnd', styleProperty: 'animation' }, 'animationiteration': { noPrefix: 'animationiteration', webkitPrefix: 'webkitAnimationIteration', styleProperty: 'animation' }, 'transitionend': { noPrefix: 'transitionend', webkitPrefix: 'webkitTransitionEnd', styleProperty: 'transition' } }; /** @const {Object<string, !VendorPropertyMapType>} */ var cssPropertyMap = { 'animation': { noPrefix: 'animation', webkitPrefix: '-webkit-animation' }, 'transform': { noPrefix: 'transform', webkitPrefix: '-webkit-transform' }, 'transition': { noPrefix: 'transition', webkitPrefix: '-webkit-transition' } }; /** * @param {!Object} windowObj * @return {boolean} */ function hasProperShape(windowObj) { return windowObj['document'] !== undefined && typeof windowObj['document']['createElement'] === 'function'; } /** * @param {string} eventType * @return {boolean} */ function eventFoundInMaps(eventType) { return eventType in eventTypeMap || eventType in cssPropertyMap; } /** * @param {string} eventType * @param {!Object<string, !VendorPropertyMapType>} map * @param {!Element} el * @return {string} */ function getJavaScriptEventName(eventType, map, el) { return map[eventType].styleProperty in el.style ? map[eventType].noPrefix : map[eventType].webkitPrefix; } /** * Helper function to determine browser prefix for CSS3 animation events * and property names. * @param {!Object} windowObj * @param {string} eventType * @return {string} */ function getAnimationName(windowObj, eventType) { if (!hasProperShape(windowObj) || !eventFoundInMaps(eventType)) { return eventType; } var map = /** @type {!Object<string, !VendorPropertyMapType>} */eventType in eventTypeMap ? eventTypeMap : cssPropertyMap; var el = windowObj['document']['createElement']('div'); var eventName = ''; if (map === eventTypeMap) { eventName = getJavaScriptEventName(eventType, map, el); } else { eventName = map[eventType].noPrefix in el.style ? map[eventType].noPrefix : map[eventType].webkitPrefix; } return eventName; } // Public functions to access getAnimationName() for JavaScript events or CSS // property names. var transformStyleProperties = ['transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'MSTransform']; /** * @param {!Object} windowObj * @param {string} eventType * @return {string} */ function getCorrectEventName(windowObj, eventType) { return getAnimationName(windowObj, eventType); } /** * @param {!Object} windowObj * @param {string} eventType * @return {string} */ function getCorrectPropertyName(windowObj, eventType) { return getAnimationName(windowObj, eventType); } /***/ }), /* 9 */, /* 10 */, /* 11 */, /* 12 */, /* 13 */, /* 14 */, /* 15 */, /* 16 */, /* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export InputElementState */ var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint no-unused-vars: [2, {"args": "none"}] */ /** * Adapter for MDC Checkbox. Provides an interface for managing * - classes * - dom * - event handlers * * Additionally, provides type information for the adapter to the Closure * compiler. * * Implement this adapter for your framework of choice to delegate updates to * the component in your framework of choice. See architecture documentation * for more details. * https://github.com/material-components/material-components-web/blob/master/docs/architecture.md * * @record */ var MDCCheckboxAdapter = function () { function MDCCheckboxAdapter() { _classCallCheck(this, MDCCheckboxAdapter); } _createClass(MDCCheckboxAdapter, [{ key: "addClass", /** @param {string} className */ value: function addClass(className) {} /** @param {string} className */ }, { key: "removeClass", value: function removeClass(className) {} /** @param {!EventListener} handler */ }, { key: "registerAnimationEndHandler", value: function registerAnimationEndHandler(handler) {} /** @param {!EventListener} handler */ }, { key: "deregisterAnimationEndHandler", value: function deregisterAnimationEndHandler(handler) {} /** @param {!EventListener} handler */ }, { key: "registerChangeHandler", value: function registerChangeHandler(handler) {} /** @param {!EventListener} handler */ }, { key: "deregisterChangeHandler", value: function deregisterChangeHandler(handler) {} /** @return {InputElementState} */ }, { key: "getNativeControl", value: function getNativeControl() {} }, { key: "forceLayout", value: function forceLayout() {} /** @return {boolean} */ }, { key: "isAttachedToDOM", value: function isAttachedToDOM() {} }]); return MDCCheckboxAdapter; }(); /** * @typedef {!{ * checked: boolean, * indeterminate: boolean, * disabled: boolean, * value: ?string * }} */ /* unused harmony default export */ var _unused_webpack_default_export = (MDCCheckboxAdapter); var InputElementState = void 0; /***/ }), /* 18 */, /* 19 */, /* 20 */, /* 21 */, /* 22 */, /* 23 */, /* 24 */, /* 25 */, /* 26 */, /* 27 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(28); /***/ }), /* 28 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MDCCheckbox", function() { return MDCCheckbox; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_animation__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__material_base_component__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__adapter__ = __webpack_require__(17); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation__ = __webpack_require__(29); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__material_ripple__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__material_ripple_util__ = __webpack_require__(3); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "MDCCheckboxFoundation", function() { return __WEBPACK_IMPORTED_MODULE_3__foundation__["a"]; }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-unused-vars */ /* eslint-enable no-unused-vars */ /** * @extends MDCComponent<!MDCCheckboxFoundation> */ var MDCCheckbox = function (_MDCComponent) { _inherits(MDCCheckbox, _MDCComponent); _createClass(MDCCheckbox, [{ key: 'nativeCb_', /** * @return {InputElementState|undefined} * @private */ get: function get() { var NATIVE_CONTROL_SELECTOR = __WEBPACK_IMPORTED_MODULE_3__foundation__["a" /* default */].strings.NATIVE_CONTROL_SELECTOR; var cbEl = /** @type {InputElementState|undefined} */this.root_.querySelector(NATIVE_CONTROL_SELECTOR); return cbEl; } }], [{ key: 'attachTo', value: function attachTo(root) { return new MDCCheckbox(root); } }]); function MDCCheckbox() { var _ref; _classCallCheck(this, MDCCheckbox); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } /** @private {!MDCRipple} */ var _this = _possibleConstructorReturn(this, (_ref = MDCCheckbox.__proto__ || Object.getPrototypeOf(MDCCheckbox)).call.apply(_ref, [this].concat(args))); _this.ripple_ = _this.initRipple_(); return _this; } /** * @return {!MDCRipple} * @private */ _createClass(MDCCheckbox, [{ key: 'initRipple_', value: function initRipple_() { var _this2 = this; var MATCHES = __WEBPACK_IMPORTED_MODULE_5__material_ripple_util__["getMatchesProperty"](HTMLElement.prototype); var adapter = _extends(__WEBPACK_IMPORTED_MODULE_4__material_ripple__["MDCRipple"].createAdapter(this), { isUnbounded: function isUnbounded() { return true; }, isSurfaceActive: function isSurfaceActive() { return _this2.nativeCb_[MATCHES](':active'); }, registerInteractionHandler: function registerInteractionHandler(type, handler) { return _this2.nativeCb_.addEventListener(type, handler); }, deregisterInteractionHandler: function deregisterInteractionHandler(type, handler) { return _this2.nativeCb_.removeEventListener(type, handler); }, computeBoundingRect: function computeBoundingRect() { var _root_$getBoundingCli = _this2.root_.getBoundingClientRect(), left = _root_$getBoundingCli.left, top = _root_$getBoundingCli.top; var DIM = 40; return { top: top, left: left, right: left + DIM, bottom: top + DIM, width: DIM, height: DIM }; } }); var foundation = new __WEBPACK_IMPORTED_MODULE_4__material_ripple__["MDCRippleFoundation"](adapter); return new __WEBPACK_IMPORTED_MODULE_4__material_ripple__["MDCRipple"](this.root_, foundation); } /** @return {!MDCCheckboxFoundation} */ }, { key: 'getDefaultFoundation', value: function getDefaultFoundation() { var _this3 = this; return new __WEBPACK_IMPORTED_MODULE_3__foundation__["a" /* default */]({ addClass: function addClass(className) { return _this3.root_.classList.add(className); }, removeClass: function removeClass(className) { return _this3.root_.classList.remove(className); }, registerAnimationEndHandler: function registerAnimationEndHandler(handler) { return _this3.root_.addEventListener(__WEBPACK_IMPORTED_MODULE_0__material_animation__["getCorrectEventName"](window, 'animationend'), handler); }, deregisterAnimationEndHandler: function deregisterAnimationEndHandler(handler) { return _this3.root_.removeEventListener(__WEBPACK_IMPORTED_MODULE_0__material_animation__["getCorrectEventName"](window, 'animationend'), handler); }, registerChangeHandler: function registerChangeHandler(handler) { return _this3.nativeCb_.addEventListener('change', handler); }, deregisterChangeHandler: function deregisterChangeHandler(handler) { return _this3.nativeCb_.removeEventListener('change', handler); }, getNativeControl: function getNativeControl() { return _this3.nativeCb_; }, forceLayout: function forceLayout() { return _this3.root_.offsetWidth; }, isAttachedToDOM: function isAttachedToDOM() { return Boolean(_this3.root_.parentNode); } }); } /** @return {!MDCRipple} */ }, { key: 'destroy', value: function destroy() { this.ripple_.destroy(); _get(MDCCheckbox.prototype.__proto__ || Object.getPrototypeOf(MDCCheckbox.prototype), 'destroy', this).call(this); } }, { key: 'ripple', get: function get() { return this.ripple_; } /** @return {boolean} */ }, { key: 'checked', get: function get() { return this.foundation_.isChecked(); } /** @param {boolean} checked */ , set: function set(checked) { this.foundation_.setChecked(checked); } /** @return {boolean} */ }, { key: 'indeterminate', get: function get() { return this.foundation_.isIndeterminate(); } /** @param {boolean} indeterminate */ , set: function set(indeterminate) { this.foundation_.setIndeterminate(indeterminate); } /** @return {boolean} */ }, { key: 'disabled', get: function get() { return this.foundation_.isDisabled(); } /** @param {boolean} disabled */ , set: function set(disabled) { this.foundation_.setDisabled(disabled); } /** @return {?string} */ }, { key: 'value', get: function get() { return this.foundation_.getValue(); } /** @param {?string} value */ , set: function set(value) { this.foundation_.setValue(value); } }]); return MDCCheckbox; }(__WEBPACK_IMPORTED_MODULE_1__material_base_component__["a" /* default */]); /***/ }), /* 29 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__material_base_foundation__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__adapter__ = __webpack_require__(17); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constants__ = __webpack_require__(30); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable no-unused-vars */ /* eslint-enable no-unused-vars */ /** @const {!Array<string>} */ var CB_PROTO_PROPS = ['checked', 'indeterminate']; /** * @extends {MDCFoundation<!MDCCheckboxAdapter>} */ var MDCCheckboxFoundation = function (_MDCFoundation) { _inherits(MDCCheckboxFoundation, _MDCFoundation); _createClass(MDCCheckboxFoundation, null, [{ key: 'cssClasses', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */]; } }, { key: 'strings', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */]; } }, { key: 'numbers', get: function get() { return __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */]; } }, { key: 'defaultAdapter', get: function get() { return { addClass: function addClass() /* className: string */{}, removeClass: function removeClass() /* className: string */{}, registerAnimationEndHandler: function registerAnimationEndHandler() /* handler: EventListener */{}, deregisterAnimationEndHandler: function deregisterAnimationEndHandler() /* handler: EventListener */{}, registerChangeHandler: function registerChangeHandler() /* handler: EventListener */{}, deregisterChangeHandler: function deregisterChangeHandler() /* handler: EventListener */{}, getNativeControl: function getNativeControl() /* InputElementState */{}, forceLayout: function forceLayout() {}, isAttachedToDOM: function isAttachedToDOM() /* boolean */{} }; } }]); function MDCCheckboxFoundation(adapter) { _classCallCheck(this, MDCCheckboxFoundation); /** @private {string} */ var _this = _possibleConstructorReturn(this, (MDCCheckboxFoundation.__proto__ || Object.getPrototypeOf(MDCCheckboxFoundation)).call(this, _extends(MDCCheckboxFoundation.defaultAdapter, adapter))); _this.currentCheckState_ = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_INIT; /** @private {string} */ _this.currentAnimationClass_ = ''; /** @private {number} */ _this.animEndLatchTimer_ = 0; _this.animEndHandler_ = /** @private {!EventListener} */function () { clearTimeout(_this.animEndLatchTimer_); _this.animEndLatchTimer_ = setTimeout(function () { _this.adapter_.removeClass(_this.currentAnimationClass_); _this.adapter_.deregisterAnimationEndHandler(_this.animEndHandler_); }, __WEBPACK_IMPORTED_MODULE_2__constants__["b" /* numbers */].ANIM_END_LATCH_MS); }; _this.changeHandler_ = /** @private {!EventListener} */function () { return _this.transitionCheckState_(); }; return _this; } _createClass(MDCCheckboxFoundation, [{ key: 'init', value: function init() { this.adapter_.addClass(__WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */].UPGRADED); this.adapter_.registerChangeHandler(this.changeHandler_); this.installPropertyChangeHooks_(); } }, { key: 'destroy', value: function destroy() { this.adapter_.deregisterChangeHandler(this.changeHandler_); this.uninstallPropertyChangeHooks_(); } /** @return {boolean} */ }, { key: 'isChecked', value: function isChecked() { return this.getNativeControl_().checked; } /** @param {boolean} checked */ }, { key: 'setChecked', value: function setChecked(checked) { this.getNativeControl_().checked = checked; } /** @return {boolean} */ }, { key: 'isIndeterminate', value: function isIndeterminate() { return this.getNativeControl_().indeterminate; } /** @param {boolean} indeterminate */ }, { key: 'setIndeterminate', value: function setIndeterminate(indeterminate) { this.getNativeControl_().indeterminate = indeterminate; } /** @return {boolean} */ }, { key: 'isDisabled', value: function isDisabled() { return this.getNativeControl_().disabled; } /** @param {boolean} disabled */ }, { key: 'setDisabled', value: function setDisabled(disabled) { this.getNativeControl_().disabled = disabled; if (disabled) { this.adapter_.addClass(__WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */].DISABLED); } else { this.adapter_.removeClass(__WEBPACK_IMPORTED_MODULE_2__constants__["a" /* cssClasses */].DISABLED); } } /** @return {?string} */ }, { key: 'getValue', value: function getValue() { return this.getNativeControl_().value; } /** @param {?string} value */ }, { key: 'setValue', value: function setValue(value) { this.getNativeControl_().value = value; } /** @private */ }, { key: 'installPropertyChangeHooks_', value: function installPropertyChangeHooks_() { var _this2 = this; var nativeCb = this.getNativeControl_(); var cbProto = Object.getPrototypeOf(nativeCb); CB_PROTO_PROPS.forEach(function (controlState) { var desc = Object.getOwnPropertyDescriptor(cbProto, controlState); // We have to check for this descriptor, since some browsers (Safari) don't support its return. // See: https://bugs.webkit.org/show_bug.cgi?id=49739 if (validDescriptor(desc)) { var nativeCbDesc = /** @type {!ObjectPropertyDescriptor} */{ get: desc.get, set: function set(state) { desc.set.call(nativeCb, state); _this2.transitionCheckState_(); }, configurable: desc.configurable, enumerable: desc.enumerable }; Object.defineProperty(nativeCb, controlState, nativeCbDesc); } }); } /** @private */ }, { key: 'uninstallPropertyChangeHooks_', value: function uninstallPropertyChangeHooks_() { var nativeCb = this.getNativeControl_(); var cbProto = Object.getPrototypeOf(nativeCb); CB_PROTO_PROPS.forEach(function (controlState) { var desc = /** @type {!ObjectPropertyDescriptor} */Object.getOwnPropertyDescriptor(cbProto, controlState); if (validDescriptor(desc)) { Object.defineProperty(nativeCb, controlState, desc); } }); } /** @private */ }, { key: 'transitionCheckState_', value: function transitionCheckState_() { var nativeCb = this.adapter_.getNativeControl(); if (!nativeCb) { return; } var oldState = this.currentCheckState_; var newState = this.determineCheckState_(nativeCb); if (oldState === newState) { return; } // Check to ensure that there isn't a previously existing animation class, in case for example // the user interacted with the checkbox before the animation was finished. if (this.currentAnimationClass_.length > 0) { clearTimeout(this.animEndLatchTimer_); this.adapter_.forceLayout(); this.adapter_.removeClass(this.currentAnimationClass_); } this.currentAnimationClass_ = this.getTransitionAnimationClass_(oldState, newState); this.currentCheckState_ = newState; // Check for parentNode so that animations are only run when the element is attached // to the DOM. if (this.adapter_.isAttachedToDOM() && this.currentAnimationClass_.length > 0) { this.adapter_.addClass(this.currentAnimationClass_); this.adapter_.registerAnimationEndHandler(this.animEndHandler_); } } /** * @param {!InputElementState} nativeCb * @return {string} * @private */ }, { key: 'determineCheckState_', value: function determineCheckState_(nativeCb) { var TRANSITION_STATE_INDETERMINATE = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_INDETERMINATE, TRANSITION_STATE_CHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_CHECKED, TRANSITION_STATE_UNCHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_UNCHECKED; if (nativeCb.indeterminate) { return TRANSITION_STATE_INDETERMINATE; } return nativeCb.checked ? TRANSITION_STATE_CHECKED : TRANSITION_STATE_UNCHECKED; } /** * @param {string} oldState * @param {string} newState * @return {string} */ }, { key: 'getTransitionAnimationClass_', value: function getTransitionAnimationClass_(oldState, newState) { var TRANSITION_STATE_INIT = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_INIT, TRANSITION_STATE_CHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_CHECKED, TRANSITION_STATE_UNCHECKED = __WEBPACK_IMPORTED_MODULE_2__constants__["c" /* strings */].TRANSITION_STATE_UNCHECKED; var _MDCCheckboxFoundatio = MDCCheckboxFoundation.cssClasses, ANIM_UNCHECKED_CHECKED = _MDCCheckboxFoundatio.ANIM_UNCHECKED_CHECKED, ANIM_UNCHECKED_INDETERMINATE = _MDCCheckboxFoundatio.ANIM_UNCHECKED_INDETERMINATE, ANIM_CHECKED_UNCHECKED = _MDCCheckboxFoundatio.ANIM_CHECKED_UNCHECKED, ANIM_CHECKED_INDETERMINATE = _MDCCheckboxFoundatio.ANIM_CHECKED_INDETERMINATE, ANIM_INDETERMINATE_CHECKED = _MDCCheckboxFoundatio.ANIM_INDETERMINATE_CHECKED, ANIM_INDETERMINATE_UNCHECKED = _MDCCheckboxFoundatio.ANIM_INDETERMINATE_UNCHECKED; switch (oldState) { case TRANSITION_STATE_INIT: if (newState === TRANSITION_STATE_UNCHECKED) { return ''; } // fallthrough case TRANSITION_STATE_UNCHECKED: return newState === TRANSITION_STATE_CHECKED ? ANIM_UNCHECKED_CHECKED : ANIM_UNCHECKED_INDETERMINATE; case TRANSITION_STATE_CHECKED: return newState === TRANSITION_STATE_UNCHECKED ? ANIM_CHECKED_UNCHECKED : ANIM_CHECKED_INDETERMINATE; // TRANSITION_STATE_INDETERMINATE default: return newState === TRANSITION_STATE_CHECKED ? ANIM_INDETERMINATE_CHECKED : ANIM_INDETERMINATE_UNCHECKED; } } /** * @return {!InputElementState} * @private */ }, { key: 'getNativeControl_', value: function getNativeControl_() { return this.adapter_.getNativeControl() || { checked: false, indeterminate: false, disabled: false, value: null }; } }]); return MDCCheckboxFoundation; }(__WEBPACK_IMPORTED_MODULE_0__material_base_foundation__["a" /* default */]); /** * @param {ObjectPropertyDescriptor|undefined} inputPropDesc * @return {boolean} */ /* harmony default export */ __webpack_exports__["a"] = (MDCCheckboxFoundation); function validDescriptor(inputPropDesc) { return !!inputPropDesc && typeof inputPropDesc.set === 'function'; } /***/ }), /* 30 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cssClasses; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return strings; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return numbers; }); /** * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** @const {string} */ var ROOT = 'mdc-checkbox'; /** @enum {string} */ var cssClasses = { UPGRADED: 'mdc-checkbox--upgraded', CHECKED: 'mdc-checkbox--checked', INDETERMINATE: 'mdc-checkbox--indeterminate', DISABLED: 'mdc-checkbox--disabled', ANIM_UNCHECKED_CHECKED: 'mdc-checkbox--anim-unchecked-checked', ANIM_UNCHECKED_INDETERMINATE: 'mdc-checkbox--anim-unchecked-indeterminate', ANIM_CHECKED_UNCHECKED: 'mdc-checkbox--anim-checked-unchecked', ANIM_CHECKED_INDETERMINATE: 'mdc-checkbox--anim-checked-indeterminate', ANIM_INDETERMINATE_CHECKED: 'mdc-checkbox--anim-indeterminate-checked', ANIM_INDETERMINATE_UNCHECKED: 'mdc-checkbox--anim-indeterminate-unchecked' }; /** @enum {string} */ var strings = { NATIVE_CONTROL_SELECTOR: '.' + ROOT + '__native-control', TRANSITION_STATE_INIT: 'init', TRANSITION_STATE_CHECKED: 'checked', TRANSITION_STATE_UNCHECKED: 'unchecked', TRANSITION_STATE_INDETERMINATE: 'indeterminate' }; /** @enum {number} */ var numbers = { ANIM_END_LATCH_MS: 100 }; /***/ }) /******/ ]); });
EngageWinona/next-ones-up
node_modules/@material/checkbox/dist/mdc.checkbox.js
JavaScript
mit
87,698
import SocialShare from './SocialShare' export default SocialShare
synchu/schema
src/components/SocialShare/index.js
JavaScript
mit
68
module.exports = require('react-native').NativeModules.SuperIDRN;
yourtion/ReactNative-SuperID
src/index.js
JavaScript
mit
66
version https://git-lfs.github.com/spec/v1 oid sha256:54bbb07ae1a9f895764c118915dd17af16bf383083de7e4f867c71d1da32c925 size 972
yogeshsaroya/new-cdnjs
ajax/libs/rainbow/1.1.8/js/language/html.min.js
JavaScript
mit
128
!function(e){"use strict";e.redux=e.redux||{},e(document).ready(function(){e.redux.table()}),e.redux.table=function(){var l=e(".wpglobus_flag_table_wrapper").html(),a=e(".wpglobus_flag_table_wrapper").parents("table");a.wrap('<div style="overflow:hidden;" class="wpglobus_flag_table"></div>'),a.remove(),e(".wpglobus_flag_table").html(l)}}(jQuery);
florianduport/slowvan
wp-content/plugins/wpglobus/includes/options/fields/table/field_table.min.js
JavaScript
mit
348
/** Loading progress view @class LoadingView @constructor @return {object} instantiated LoadingView **/ define(['jquery', 'backbone'], function ($, Backbone) { var LoadingView = Backbone.View.extend({ /** Constructor @method initialize **/ initialize: function () { var self = this; BB.comBroker.setService(BB.SERVICES.LOADING_VIEW,self); self.collection.on('add', function(){ BB.comBroker.getService(BB.EVENTS.APP_STACK_VIEW).selectView(BB.Elements.DIGG_CONTAINER); self.collection.off('add'); }); } }); return LoadingView; });
born2net/componentDigg
js/views/LoadingView.js
JavaScript
mit
677
// ***************************************************************** // Ox - A modular framework for developing templated, responsive, grid-based projects. // // ***************************************************************** // Project configuration var project = 'ox' // Directory name for your project. , src = './src/' // The raw files for your project. , build = './build/' // The temporary files of your development build. , dist = './dist/' // The production package that you'll upload to your server. , assets = 'assets/' // The assets folder. , bower = './bower_components/' // Bower packages. , modules = './node_modules/' // npm packages. ; // Project settings module.exports = { browsersync: { files: [build+'/**', '!'+build+'/**.map'] // Watch all files, except map files , notify: false // In-line notifications , open: false // Stops the browser window opening automatically , port: 1337 // Port number for the live version of the site; default: 1377 , server: { baseDir: build } //, proxy: project+'.dev' // Proxy defined to work with Virtual Hosts , watchOptions: { debounceDelay: 2000 // Avoid triggering too many reloads } }, images: { build: { // Copies images from `src` to `build`; does not optimise src: src+'**/*.+(png|jpg|jpeg|gif|svg)' , dest: build } , dist: { // Optimises images in the `dist` folder src: [dist+'**/*.+(png|jpg|jpeg|gif|svg)'] , imagemin: { optimizationLevel: 7 , progressive: true , interlaced: true } , dest: dist } }, scripts: { bundles: { // Bundles are defined by a name and an array of chunks (below) to concatenate. core: ['core'] , vendor: ['vendor'] , jquery: ['jquery'] , modernizr: ['modernizr'] } , chunks: { // Chunks are arrays of paths or globs matching a set of source files core: src+assets+'js/core/*.js' , vendor: src+assets+'js/vendor/*.js' , modernizr: src+assets+'js/modernizr/*.js' , jquery: bower+'jquery/dist/jquery.js' } , dest: build+assets+'js/' , lint: { src: [src+assets+'js/**/*.js', '!'+src+assets+'js/vendor/*.js', '!'+src+assets+'js/modernizr/*.js'] } , minify: { src: build+assets+'js/**/*.js' , uglify: {} // Default options , dest: build+assets+'js/' } }, styles: { build: { src: src+assets+'scss/**/*.scss' , dest: build+assets+'/styles' } , autoprefixer: { browsers: ['> 1%', 'last 2 versions', 'ie 11', 'ios >= 6', 'android >= 4', 'safari >= 8'] , grid: true } , stylelint: {"rules": { "color-no-invalid-hex": true, "number-leading-zero": "always", "number-no-trailing-zeros": true, "length-zero-no-unit": true, "string-quotes": "double", "value-no-vendor-prefix": true, "declaration-colon-space-before": "never", "declaration-bang-space-before": "always", "declaration-bang-space-after": "never", "declaration-block-semicolon-newline-after": "always-multi-line", "selector-list-comma-space-before": "never", "selector-pseudo-element-colon-notation": "double", "max-empty-lines": 5 }} , minify: { safe: true, autoprefixer: false } , libsass: { // Requires the libsass implementation of Sass includePaths: [src+assets+'scss', bower, modules] , precision: 6 } }, theme: { beautify: { "indent_size": 4, "indent_with_tabs": true, "max_preserve_newlines": 1 } , njk: { src: src+'app/pages/**/*.+(html|njk|json)' , path: [src+'app/templates'] , dest: build } , html: { src: src+'**/*.html' , dest: build } , favicon: { src: src+assets+'images/favicon/*.+(ico|jpg|json)' , dest: build+assets+'images' } , font: { src: src+assets+'fonts/**/*.+(eot|svg|ttf|woff|woff2)' , dest: build+assets+'fonts' } }, utils: { clean: [build+'**/.DS_Store'] , wipe: [dist] , dist: { src: [build+'**/*', '!'+build+'**/*.map'] , dest: dist } }, watch: { src: { styles: src+assets+'scss/**/*.scss' , scripts: src+assets+'js/**/*.js' , images: src+'**/*.+(png|jpg|jpeg|gif|svg)' , theme: src+'**/*.+(html|njk|json)' , themeassets: [src+assets+'images/favicon/*.+(ico|jpg|json)', src+assets+'fonts/**/*.+(eot|svg|ttf|woff|woff2)'] } , watcher: 'browsersync' } }
MajorDigital/ox
gulpfile/config.js
JavaScript
mit
4,841
import { app, router, store } from './app' const isDev = process.env.NODE_ENV !== 'production' export default context => { const s = isDev && Date.now() router.push(context.url) const matchedComponents = router.getMatchedComponents() if (!matchedComponents.length) { return Promise.reject({ code: 404 }) } return Promise.all(matchedComponents.map(component => { if (component.preFetch) { return component.preFetch(store) } })).then(() => { isDev && console.log(`data pre-fetch: ${Date.now() - s}ms`) context.initialState = store.state return app }) }
Luncher/Blog
src/server-entry.js
JavaScript
mit
600
/// <reference path="_reference.js" /> "use strict"; var svgNameSpace = "http://www.w3.org/2000/svg"; function createSVG(id, width, height) { var svg = document.createElementNS(svgNameSpace, "svg"); if (id) { svg.setAttribute("id", id); } svg.setAttribute("width", width ); svg.setAttribute("height", height ); return svg; } function createPath(points, stroke, fill, strokeWidth) { var path; path = document.createElementNS(svgNameSpace, 'path'); path.setAttribute('d', points); path.setAttribute('stroke', stroke); path.setAttribute('fill', fill); path.setAttribute('stroke-width', strokeWidth); return path; } function createCircle(x, y, r, fill) { var circle; circle = document.createElementNS(svgNameSpace, 'circle'); circle.setAttribute('cx', x); circle.setAttribute('cy', y); circle.setAttribute('r', r); circle.setAttribute('fill', fill); return circle; } function createImage(x, y, width, height, href) { var image; image = document.createElementNS(svgNameSpace, 'image'); image.setAttribute('x', x); image.setAttribute('y', y); image.setAttribute('width', width); image.setAttribute('height', height); image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', href); return image; } function createText(x, y, fontSize, fontWeight, fontFamily, fill, value) { var text; text = document.createElementNS(svgNameSpace, 'text'); text.setAttribute('x', x); text.setAttribute('y', y); text.setAttribute('font-size', fontSize); text.setAttribute('font-weight', fontWeight); text.setAttribute('font-family', fontFamily); text.setAttribute('fill', fill); text.textContent = value; return text; } function createRect(x, y, width, height, fill, stroke) { var rect; rect = document.createElementNS(svgNameSpace, 'rect'); rect.setAttribute('x', x); rect.setAttribute('y', y); rect.setAttribute('width', width); rect.setAttribute('height', height); rect.setAttribute('fill', fill); rect.setAttribute('stroke', stroke); return rect; }
idoychinov/Telerik_Academy_Homework
JS DOM and UI/04.SVG/scripts/drawUtilities.js
JavaScript
mit
2,139
define(["require", "exports", "./selection", "./collection", "./utils/arrayUtils"], function (require, exports, selection_1, collection_1, arrayUtils_1) { Object.defineProperty(exports, "__esModule", { value: true }); var DataSource = (function () { function DataSource(selection, config) { this.selection = selection || new selection_1.Selection('single'); this.selectionEventID = this.selection.addEventListener(this.selectionEventCallback.bind(this)); this.selection.overrideGetRowKey(this.getRowKey.bind(this)); this.selection.overrideGetRowKeys(this.getRowKeys.bind(this)); this.arrayUtils = new arrayUtils_1.ArrayUtils(); this.key = null; this.mainArray = null; this.config = config; if (this.config) { this.key = config.key || '__avgKey'; this.rowHeight = config.rowHeight || 25; this.groupHeight = config.groupHeight || 25; this.rowHeightCallback = config.rowHeightCallback || function () { return null; }; } else { this.key = '__avgKey'; this.rowHeight = 25; this.groupHeight = 25; this.rowHeightCallback = function () { return null; }; } this.eventIdCount = -1; this.eventCallBacks = []; this.entity = null; this.collection = new collection_1.Collection(this); } DataSource.prototype.getSelection = function () { return this.selection; }; DataSource.prototype.getKey = function () { return this.key; }; DataSource.prototype.length = function () { return this.collection.length; }; DataSource.prototype.triggerEvent = function (event) { var _this = this; this.eventCallBacks.forEach(function (FN, i) { if (FN !== null) { var alive = FN(event); if (!alive) { _this.eventCallBacks[i] = null; } } }); }; DataSource.prototype.addEventListener = function (callback) { this.eventIdCount++; this.eventCallBacks.push(callback); return this.eventIdCount; }; DataSource.prototype.removeEventListener = function (id) { this.eventCallBacks.splice(id, 1); }; DataSource.prototype.setArray = function (array) { this.collection = new collection_1.Collection(this); this.selection.reset(); this.arrayUtils.resetGrouping(); this.arrayUtils.resetSort(this.key); this.entity = null; this.collection.setData(array); this.mainArray = this.collection.getEntities(); this.triggerEvent('collection_changed'); }; DataSource.prototype.push = function (array) { if (Array.isArray(array)) { var grouping = this.arrayUtils.getGrouping(); var collection = this.collection.getEntities(); collection = collection.concat(array); this.collection.setData(collection); this.mainArray = this.collection.getEntities(); this.arrayUtils.runOrderbyOn(this.collection.getEntities()); var untouchedgrouped = this.collection.getEntities(); if (grouping.length > 0) { var groupedArray = this.arrayUtils.group(untouchedgrouped, grouping, true); this.collection.setData(groupedArray, untouchedgrouped); } this.triggerEvent('collection_updated'); } }; DataSource.prototype.refresh = function (data) { if (data) { this.collection = new collection_1.Collection(this); this.collection.setData(data); this.mainArray = this.collection.getEntities(); this.entity = null; } var grouping = this.arrayUtils.getGrouping(); this.arrayUtils.runOrderbyOn(this.collection.getEntities()); if (grouping.length > 0) { var unGroupedArray = this.collection.getEntities(); var groupedArray = this.arrayUtils.group(unGroupedArray, grouping, true); this.collection.setData(groupedArray, unGroupedArray); } this.triggerEvent('collection_updated'); }; DataSource.prototype.select = function (row) { this.entity = this.collection.getRow(row); }; DataSource.prototype.query = function (options) { if (options) { var newArray = this.arrayUtils.query(this.mainArray, options); this.collection.setData(newArray); } else { this.collection.setData(this.mainArray); } this.orderBy(null, true); this.triggerEvent('collection_filtered'); }; DataSource.prototype.orderBy = function (attribute, addToCurrentSort) { var collection = this.collection.getEntities(); var result = this.arrayUtils.orderBy(collection, attribute, addToCurrentSort); this.collection.setData(result.fixed, result.full); this.triggerEvent('collection_sorted'); }; DataSource.prototype.getCurrentOrderBy = function () { return this.arrayUtils.getOrderBy(); }; DataSource.prototype.getCurrentFilter = function () { return this.arrayUtils.getCurrentFilter(); }; DataSource.prototype.getElement = function (row) { if (row === undefined || row === null) { throw new Error('row missing'); } else { return this.collection.getRow(row); } }; DataSource.prototype.updateRowData = function (attribute, data, rows) { var entities = this.collection.getCurrentEntities(); rows.forEach(function (x) { entities[x][attribute] = data; }); }; DataSource.prototype.group = function (grouping, keepExpanded) { var _this = this; this.arrayUtils.resetSort(); grouping.forEach(function (group) { _this.arrayUtils.setOrderBy(group.field, true); }); this.arrayUtils.runOrderbyOn(this.collection.getEntities()); var ungroupedArray = this.collection.getEntities(); var groupedArray = this.arrayUtils.group(ungroupedArray, grouping, keepExpanded); this.collection.setData(groupedArray, ungroupedArray); this.triggerEvent('collection_grouped'); }; DataSource.prototype.groupCollapse = function (id) { var groupedArray = this.arrayUtils.groupCollapse(id); var ungroupedArray = this.collection.getEntities(); this.collection.setData(groupedArray, ungroupedArray); if (id) { this.triggerEvent('collection_collapsed'); } else { this.triggerEvent('collection_collapsed_all'); } }; DataSource.prototype.groupExpand = function (id) { var groupedArray = this.arrayUtils.groupExpand(id); var ungroupedArray = this.collection.getEntities(); this.collection.setData(groupedArray, ungroupedArray); if (id) { this.triggerEvent('collection_expanded'); } else { this.triggerEvent('collection_expanded_all'); } }; DataSource.prototype.getGrouping = function () { return this.arrayUtils.getGrouping(); }; DataSource.prototype.addBlankRow = function () { var newElement = {}; this.mainArray.unshift(newElement); var collectionUngrouped = this.collection.getEntities(); var displayedCollection = this.collection.getCurrentEntities(); var index = collectionUngrouped.indexOf(newElement); if (index === -1) { collectionUngrouped.unshift(newElement); } displayedCollection.unshift(newElement); this.collection.setData(displayedCollection, collectionUngrouped); this.entity = newElement; this.triggerEvent('collection_filtered'); }; DataSource.prototype.unshift = function (data) { if (data) { this.mainArray.unshift(data); var displayedCollection = this.collection.getEntities(); var ungroupedCollection = this.collection.getCurrentEntities(); var index = displayedCollection.indexOf(data); if (index === -1) { displayedCollection.unshift(data); } ungroupedCollection.unshift(data); this.collection.setData(ungroupedCollection, displayedCollection); this.entity = data; this.triggerEvent('collection_filtered'); } }; DataSource.prototype.remove = function (rows) { var _this = this; var keysToDelete = new Set(); var returnArray = []; if (Array.isArray(rows)) { rows.forEach(function (row) { keysToDelete.add(_this.getRowKey(row)); }); } else { if (this.entity && Number.isInteger(rows)) { keysToDelete.add(this.getRowKey(rows)); } } if (keysToDelete.size > 0) { var oldArray = this.collection.getEntities(); for (var i = 0; i < oldArray.length; i++) { if (keysToDelete.has(oldArray[i][this.key]) === true) { returnArray.push(oldArray.splice(i, 1)[0]); i--; } } this.collection.setData(oldArray); this.refresh(); } return returnArray; }; DataSource.prototype.getCollectionStatus = function () { var status = { collectionLength: this.mainArray ? this.mainArray.length : 0, filteredCollectionLength: this.collection.getEntities().length, selectionLength: this.selection.getLength() }; return status; }; DataSource.prototype.setLocaleCompare = function (code, options) { this.arrayUtils.setLocaleCompare(code, options); }; DataSource.prototype.getRowHeightState = function () { return this.collection.getRowHeightState(); }; DataSource.prototype.getRowKey = function (row) { if (this.collection) { return this.collection.getRowKey(row); } else { return null; } }; DataSource.prototype.getRowKeys = function () { if (this.collection) { return this.collection.getRowKeys(); } else { return []; } }; DataSource.prototype.selectionEventCallback = function (e) { this.triggerEvent(e); return true; }; return DataSource; }()); exports.DataSource = DataSource; }); //# sourceMappingURL=dataSource.js.map
vegarringdal/vGrid
dist/amd/dataSource.js
JavaScript
mit
11,755
function TableSort(id) { this.tbl = document.getElementById(id); this.lastSortedTh = null; if (this.tbl && this.tbl.nodeName == "TABLE") { var headings = this.tbl.tHead.rows[0].cells; for (var i=0; headings[i]; i++) { if (headings[i].className.match(/asc|dsc/)) { this.lastSortedTh = headings[i]; } } this.makeSortable(); } } TableSort.prototype.makeSortable = function () { var headings = this.tbl.tHead.rows[0].cells; for (var i=0; headings[i]; i++) { if(!headings[i].className.match(/notSortable/)) { headings[i].cIdx = i; var a = document.createElement("a"); a.href = "#"; a.innerHTML = headings[i].innerHTML; a.onclick = function (that) { return function () { that.sortCol(this); return false; } }(this); headings[i].innerHTML = ""; headings[i].appendChild(a); } } } TableSort.prototype.sortCol = function (el) { /* * Get cell data for column that is to be sorted from HTML table */ var rows = this.tbl.rows; var alpha = [], numeric = []; var aIdx = 0, nIdx = 0; var th = el.parentNode; var cellIndex = th.cIdx; for (var i=1; rows[i]; i++) { var cell = rows[i].cells[cellIndex]; var content = cell.textContent ? cell.textContent : cell.innerText; /* * Split data into two separate arrays, one for numeric content and * one for everything else (alphabetic). Store both the actual data * that will be used for comparison by the sort algorithm (thus the need * to parseFloat() the numeric data) as well as a reference to the * element's parent row. The row reference will be used after the new * order of content is determined in order to actually reorder the HTML * table's rows. */ if(content && String(content).length >= 0) { var num = content.replace(/(\$|\,|\s)/g, ""); if (parseFloat(num) == num) { numeric[nIdx++] = { value: Number(num), row: rows[i] } } else { alpha[aIdx++] = { value: content, row: rows[i] } } } else { alpha[aIdx++] = { value: "", row: rows[i] } } } /* * Sort according to direction (ascending or descending) */ var col = [], top, bottom; if (th.className.match("asc")) { top = bubbleSort(alpha, -1); bottom = bubbleSort(numeric, -1); th.className = th.className.replace(/asc/, "dsc"); } else { top = bubbleSort(numeric, 1); bottom = bubbleSort(alpha, 1); if (th.className.match("dsc")) { th.className = th.className.replace(/dsc/, "asc"); } else { th.className += "asc"; } } /* * Clear asc/dsc class names from the last sorted column's th if it isnt the * same as the one that was just clicked */ if (this.lastSortedTh && th != this.lastSortedTh) { this.lastSortedTh.className = this.lastSortedTh.className.replace(/dsc|asc/g, ""); } this.lastSortedTh = th; /* * Reorder HTML table based on new order of data found in the col array */ col = top.concat(bottom); var tBody = this.tbl.tBodies[0]; for (var i=0; col[i]; i++) { tBody.appendChild(col[i].row); } } function bubbleSort(arr, dir) { // Pre-calculate directional information var start, end; if (dir === 1) { start = 0; end = arr.length; } else if (dir === -1) { start = arr.length-1; end = -1; } // Bubble sort: http://en.wikipedia.org/wiki/Bubble_sort var unsorted = true; while (unsorted) { unsorted = false; for (var i=start; i!=end; i=i+dir) { if (arr[i+dir] && arr[i].value > arr[i+dir].value) { var a = arr[i]; var b = arr[i+dir]; var c = a; arr[i] = b; arr[i+dir] = c; unsorted = true; } } } return arr; }
memiks/readityourself
inc/include.js
JavaScript
mit
4,318
const gulp = require('gulp'); const HubRegistry = require('gulp-hub'); const browserSync = require('browser-sync'); const conf = require('./conf/gulp.conf'); // Load some files into the registry const hub = new HubRegistry([conf.path.tasks('*.js')]); // Tell gulp to use the tasks just loaded gulp.registry(hub); <% if (modules === 'inject') { -%> gulp.task('inject', gulp.series(gulp.parallel('styles', 'scripts'), 'inject')); <% } -%> gulp.task('build', <%- buildTask %>); gulp.task('test', <%- testTask %>); gulp.task('test:auto', <%- testAutoTask %>); gulp.task('serve', <%- serveTask %>); gulp.task('serve:dist', gulp.series('default', 'browsersync:dist')); gulp.task('default', gulp.series('clean', 'build')); gulp.task('watch', watch); function reloadBrowserSync(cb) { browserSync.reload(); cb(); } function watch(done) { <% if (modules === 'inject') { -%> gulp.watch([ conf.path.src('index.html'), 'bower.json' ], gulp.parallel('inject')); <% } -%> <% if (framework !== 'react' && modules !== 'webpack') { -%> <% if (modules !== 'systemjs') { -%> gulp.watch(conf.path.src('app/**/*.html'), gulp.series('partials', reloadBrowserSync)); <% } else { -%> gulp.watch(conf.path.src('**/*.html'), reloadBrowserSync); <% } -%> <% } else if (modules === 'webpack') {-%> gulp.watch(conf.path.tmp('index.html'), reloadBrowserSync); <% } else { -%> gulp.watch(conf.path.src('index.html'), reloadBrowserSync); <% } -%> <% if (modules !== 'webpack') { -%> gulp.watch([ <% if (css !== 'css') { -%> conf.path.src('**/*.<%- css %>'), <% } -%> conf.path.src('**/*.css') ], gulp.series('styles')); <% } -%> <% if (modules === 'inject') { -%> gulp.watch(conf.path.src('**/*.<%- extensions.js %>'), gulp.series('inject')); <% } else if (modules === 'systemjs') { -%> gulp.watch(conf.path.src('**/*.<%- extensions.js %>'), gulp.series('scripts')); <% } -%> done(); }
FountainJS/generator-fountain-gulp
generators/app/templates/gulpfile.js
JavaScript
mit
1,912
// All symbols in the Unified Canadian Aboriginal Syllabics block as per Unicode v5.1.0: [ '\u1400', '\u1401', '\u1402', '\u1403', '\u1404', '\u1405', '\u1406', '\u1407', '\u1408', '\u1409', '\u140A', '\u140B', '\u140C', '\u140D', '\u140E', '\u140F', '\u1410', '\u1411', '\u1412', '\u1413', '\u1414', '\u1415', '\u1416', '\u1417', '\u1418', '\u1419', '\u141A', '\u141B', '\u141C', '\u141D', '\u141E', '\u141F', '\u1420', '\u1421', '\u1422', '\u1423', '\u1424', '\u1425', '\u1426', '\u1427', '\u1428', '\u1429', '\u142A', '\u142B', '\u142C', '\u142D', '\u142E', '\u142F', '\u1430', '\u1431', '\u1432', '\u1433', '\u1434', '\u1435', '\u1436', '\u1437', '\u1438', '\u1439', '\u143A', '\u143B', '\u143C', '\u143D', '\u143E', '\u143F', '\u1440', '\u1441', '\u1442', '\u1443', '\u1444', '\u1445', '\u1446', '\u1447', '\u1448', '\u1449', '\u144A', '\u144B', '\u144C', '\u144D', '\u144E', '\u144F', '\u1450', '\u1451', '\u1452', '\u1453', '\u1454', '\u1455', '\u1456', '\u1457', '\u1458', '\u1459', '\u145A', '\u145B', '\u145C', '\u145D', '\u145E', '\u145F', '\u1460', '\u1461', '\u1462', '\u1463', '\u1464', '\u1465', '\u1466', '\u1467', '\u1468', '\u1469', '\u146A', '\u146B', '\u146C', '\u146D', '\u146E', '\u146F', '\u1470', '\u1471', '\u1472', '\u1473', '\u1474', '\u1475', '\u1476', '\u1477', '\u1478', '\u1479', '\u147A', '\u147B', '\u147C', '\u147D', '\u147E', '\u147F', '\u1480', '\u1481', '\u1482', '\u1483', '\u1484', '\u1485', '\u1486', '\u1487', '\u1488', '\u1489', '\u148A', '\u148B', '\u148C', '\u148D', '\u148E', '\u148F', '\u1490', '\u1491', '\u1492', '\u1493', '\u1494', '\u1495', '\u1496', '\u1497', '\u1498', '\u1499', '\u149A', '\u149B', '\u149C', '\u149D', '\u149E', '\u149F', '\u14A0', '\u14A1', '\u14A2', '\u14A3', '\u14A4', '\u14A5', '\u14A6', '\u14A7', '\u14A8', '\u14A9', '\u14AA', '\u14AB', '\u14AC', '\u14AD', '\u14AE', '\u14AF', '\u14B0', '\u14B1', '\u14B2', '\u14B3', '\u14B4', '\u14B5', '\u14B6', '\u14B7', '\u14B8', '\u14B9', '\u14BA', '\u14BB', '\u14BC', '\u14BD', '\u14BE', '\u14BF', '\u14C0', '\u14C1', '\u14C2', '\u14C3', '\u14C4', '\u14C5', '\u14C6', '\u14C7', '\u14C8', '\u14C9', '\u14CA', '\u14CB', '\u14CC', '\u14CD', '\u14CE', '\u14CF', '\u14D0', '\u14D1', '\u14D2', '\u14D3', '\u14D4', '\u14D5', '\u14D6', '\u14D7', '\u14D8', '\u14D9', '\u14DA', '\u14DB', '\u14DC', '\u14DD', '\u14DE', '\u14DF', '\u14E0', '\u14E1', '\u14E2', '\u14E3', '\u14E4', '\u14E5', '\u14E6', '\u14E7', '\u14E8', '\u14E9', '\u14EA', '\u14EB', '\u14EC', '\u14ED', '\u14EE', '\u14EF', '\u14F0', '\u14F1', '\u14F2', '\u14F3', '\u14F4', '\u14F5', '\u14F6', '\u14F7', '\u14F8', '\u14F9', '\u14FA', '\u14FB', '\u14FC', '\u14FD', '\u14FE', '\u14FF', '\u1500', '\u1501', '\u1502', '\u1503', '\u1504', '\u1505', '\u1506', '\u1507', '\u1508', '\u1509', '\u150A', '\u150B', '\u150C', '\u150D', '\u150E', '\u150F', '\u1510', '\u1511', '\u1512', '\u1513', '\u1514', '\u1515', '\u1516', '\u1517', '\u1518', '\u1519', '\u151A', '\u151B', '\u151C', '\u151D', '\u151E', '\u151F', '\u1520', '\u1521', '\u1522', '\u1523', '\u1524', '\u1525', '\u1526', '\u1527', '\u1528', '\u1529', '\u152A', '\u152B', '\u152C', '\u152D', '\u152E', '\u152F', '\u1530', '\u1531', '\u1532', '\u1533', '\u1534', '\u1535', '\u1536', '\u1537', '\u1538', '\u1539', '\u153A', '\u153B', '\u153C', '\u153D', '\u153E', '\u153F', '\u1540', '\u1541', '\u1542', '\u1543', '\u1544', '\u1545', '\u1546', '\u1547', '\u1548', '\u1549', '\u154A', '\u154B', '\u154C', '\u154D', '\u154E', '\u154F', '\u1550', '\u1551', '\u1552', '\u1553', '\u1554', '\u1555', '\u1556', '\u1557', '\u1558', '\u1559', '\u155A', '\u155B', '\u155C', '\u155D', '\u155E', '\u155F', '\u1560', '\u1561', '\u1562', '\u1563', '\u1564', '\u1565', '\u1566', '\u1567', '\u1568', '\u1569', '\u156A', '\u156B', '\u156C', '\u156D', '\u156E', '\u156F', '\u1570', '\u1571', '\u1572', '\u1573', '\u1574', '\u1575', '\u1576', '\u1577', '\u1578', '\u1579', '\u157A', '\u157B', '\u157C', '\u157D', '\u157E', '\u157F', '\u1580', '\u1581', '\u1582', '\u1583', '\u1584', '\u1585', '\u1586', '\u1587', '\u1588', '\u1589', '\u158A', '\u158B', '\u158C', '\u158D', '\u158E', '\u158F', '\u1590', '\u1591', '\u1592', '\u1593', '\u1594', '\u1595', '\u1596', '\u1597', '\u1598', '\u1599', '\u159A', '\u159B', '\u159C', '\u159D', '\u159E', '\u159F', '\u15A0', '\u15A1', '\u15A2', '\u15A3', '\u15A4', '\u15A5', '\u15A6', '\u15A7', '\u15A8', '\u15A9', '\u15AA', '\u15AB', '\u15AC', '\u15AD', '\u15AE', '\u15AF', '\u15B0', '\u15B1', '\u15B2', '\u15B3', '\u15B4', '\u15B5', '\u15B6', '\u15B7', '\u15B8', '\u15B9', '\u15BA', '\u15BB', '\u15BC', '\u15BD', '\u15BE', '\u15BF', '\u15C0', '\u15C1', '\u15C2', '\u15C3', '\u15C4', '\u15C5', '\u15C6', '\u15C7', '\u15C8', '\u15C9', '\u15CA', '\u15CB', '\u15CC', '\u15CD', '\u15CE', '\u15CF', '\u15D0', '\u15D1', '\u15D2', '\u15D3', '\u15D4', '\u15D5', '\u15D6', '\u15D7', '\u15D8', '\u15D9', '\u15DA', '\u15DB', '\u15DC', '\u15DD', '\u15DE', '\u15DF', '\u15E0', '\u15E1', '\u15E2', '\u15E3', '\u15E4', '\u15E5', '\u15E6', '\u15E7', '\u15E8', '\u15E9', '\u15EA', '\u15EB', '\u15EC', '\u15ED', '\u15EE', '\u15EF', '\u15F0', '\u15F1', '\u15F2', '\u15F3', '\u15F4', '\u15F5', '\u15F6', '\u15F7', '\u15F8', '\u15F9', '\u15FA', '\u15FB', '\u15FC', '\u15FD', '\u15FE', '\u15FF', '\u1600', '\u1601', '\u1602', '\u1603', '\u1604', '\u1605', '\u1606', '\u1607', '\u1608', '\u1609', '\u160A', '\u160B', '\u160C', '\u160D', '\u160E', '\u160F', '\u1610', '\u1611', '\u1612', '\u1613', '\u1614', '\u1615', '\u1616', '\u1617', '\u1618', '\u1619', '\u161A', '\u161B', '\u161C', '\u161D', '\u161E', '\u161F', '\u1620', '\u1621', '\u1622', '\u1623', '\u1624', '\u1625', '\u1626', '\u1627', '\u1628', '\u1629', '\u162A', '\u162B', '\u162C', '\u162D', '\u162E', '\u162F', '\u1630', '\u1631', '\u1632', '\u1633', '\u1634', '\u1635', '\u1636', '\u1637', '\u1638', '\u1639', '\u163A', '\u163B', '\u163C', '\u163D', '\u163E', '\u163F', '\u1640', '\u1641', '\u1642', '\u1643', '\u1644', '\u1645', '\u1646', '\u1647', '\u1648', '\u1649', '\u164A', '\u164B', '\u164C', '\u164D', '\u164E', '\u164F', '\u1650', '\u1651', '\u1652', '\u1653', '\u1654', '\u1655', '\u1656', '\u1657', '\u1658', '\u1659', '\u165A', '\u165B', '\u165C', '\u165D', '\u165E', '\u165F', '\u1660', '\u1661', '\u1662', '\u1663', '\u1664', '\u1665', '\u1666', '\u1667', '\u1668', '\u1669', '\u166A', '\u166B', '\u166C', '\u166D', '\u166E', '\u166F', '\u1670', '\u1671', '\u1672', '\u1673', '\u1674', '\u1675', '\u1676', '\u1677', '\u1678', '\u1679', '\u167A', '\u167B', '\u167C', '\u167D', '\u167E', '\u167F' ];
mathiasbynens/unicode-data
5.1.0/blocks/Unified-Canadian-Aboriginal-Syllabics-symbols.js
JavaScript
mit
7,132
// All code points with the `Sentence_Terminal` property as per Unicode v9.0.0: [ 0x21, 0x2E, 0x3F, 0x589, 0x61F, 0x6D4, 0x700, 0x701, 0x702, 0x7F9, 0x964, 0x965, 0x104A, 0x104B, 0x1362, 0x1367, 0x1368, 0x166E, 0x1735, 0x1736, 0x1803, 0x1809, 0x1944, 0x1945, 0x1AA8, 0x1AA9, 0x1AAA, 0x1AAB, 0x1B5A, 0x1B5B, 0x1B5E, 0x1B5F, 0x1C3B, 0x1C3C, 0x1C7E, 0x1C7F, 0x203C, 0x203D, 0x2047, 0x2048, 0x2049, 0x2E2E, 0x2E3C, 0x3002, 0xA4FF, 0xA60E, 0xA60F, 0xA6F3, 0xA6F7, 0xA876, 0xA877, 0xA8CE, 0xA8CF, 0xA92F, 0xA9C8, 0xA9C9, 0xAA5D, 0xAA5E, 0xAA5F, 0xAAF0, 0xAAF1, 0xABEB, 0xFE52, 0xFE56, 0xFE57, 0xFF01, 0xFF0E, 0xFF1F, 0xFF61, 0x10A56, 0x10A57, 0x11047, 0x11048, 0x110BE, 0x110BF, 0x110C0, 0x110C1, 0x11141, 0x11142, 0x11143, 0x111C5, 0x111C6, 0x111CD, 0x111DE, 0x111DF, 0x11238, 0x11239, 0x1123B, 0x1123C, 0x112A9, 0x1144B, 0x1144C, 0x115C2, 0x115C3, 0x115C9, 0x115CA, 0x115CB, 0x115CC, 0x115CD, 0x115CE, 0x115CF, 0x115D0, 0x115D1, 0x115D2, 0x115D3, 0x115D4, 0x115D5, 0x115D6, 0x115D7, 0x11641, 0x11642, 0x1173C, 0x1173D, 0x1173E, 0x11C41, 0x11C42, 0x16A6E, 0x16A6F, 0x16AF5, 0x16B37, 0x16B38, 0x16B44, 0x1BC9F, 0x1DA88 ];
mathiasbynens/unicode-data
9.0.0/properties/Sentence_Terminal-code-points.js
JavaScript
mit
1,239
import { expect } from 'chai'; import Draft, { EditorState, SelectionState } from 'draft-js'; import handleBlockType from '../handleBlockType'; describe('handleBlockType', () => { describe('no markup', () => { const rawContentState = { entityMap: {}, blocks: [ { key: 'item1', text: '[ ]', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }; const contentState = Draft.convertFromRaw(rawContentState); const selection = new SelectionState({ anchorKey: 'item1', anchorOffset: 3, focusKey: 'item1', focusOffset: 3, isBackward: false, hasFocus: true, }); const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selection); it('does not convert block type', () => { const newEditorState = handleBlockType(editorState, ' '); expect(newEditorState).to.equal(editorState); expect(Draft.convertToRaw(newEditorState.getCurrentContent())).to.deep.equal(rawContentState); }); }); const testCases = { 'converts from unstyled to header-one': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '# Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'header-one', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 6, focusKey: 'item1', focusOffset: 6, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to header-two': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '## Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'header-two', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 7, focusKey: 'item1', focusOffset: 7, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to header-three': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '### Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'header-three', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 8, focusKey: 'item1', focusOffset: 8, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to header-four': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '#### Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'header-four', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 9, focusKey: 'item1', focusOffset: 9, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to header-five': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '##### Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'header-five', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 10, focusKey: 'item1', focusOffset: 10, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to header-six': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '###### Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'header-six', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 11, focusKey: 'item1', focusOffset: 11, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to unordered-list-item with hyphen': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '- Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'unordered-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 6, focusKey: 'item1', focusOffset: 6, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to unordered-list-item with astarisk': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '* Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'unordered-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 6, focusKey: 'item1', focusOffset: 6, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to ordered-list-item': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '2. Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'ordered-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 7, focusKey: 'item1', focusOffset: 7, isBackward: false, hasFocus: true, }), }, 'converts from unordered-list-item to unchecked checkable-list-item': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '[] Test', type: 'unordered-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test', type: 'checkable-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: { checked: false, }, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 1, focusKey: 'item1', focusOffset: 1, isBackward: false, hasFocus: true, }), }, 'converts from unordered-list-item to checked checkable-list-item': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '[x]Test', type: 'unordered-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test', type: 'checkable-list-item', depth: 0, inlineStyleRanges: [], entityRanges: [], data: { checked: true, }, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 3, focusKey: 'item1', focusOffset: 3, isBackward: false, hasFocus: true, }), }, 'converts from unstyled to blockquote': { before: { entityMap: {}, blocks: [ { key: 'item1', text: '> Test', type: 'unstyled', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, after: { entityMap: {}, blocks: [ { key: 'item1', text: 'Test ', type: 'blockquote', depth: 0, inlineStyleRanges: [], entityRanges: [], data: {}, }, ], }, selection: new SelectionState({ anchorKey: 'item1', anchorOffset: 6, focusKey: 'item1', focusOffset: 6, isBackward: false, hasFocus: true, }), }, }; Object.keys(testCases).forEach(k => { describe(k, () => { const testCase = testCases[k]; const { before, after, selection, character = ' ' } = testCase; const contentState = Draft.convertFromRaw(before); const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selection); it('converts block type', () => { const newEditorState = handleBlockType(editorState, character); expect(newEditorState).not.to.equal(editorState); expect(Draft.convertToRaw(newEditorState.getCurrentContent())).to.deep.equal(after); }); }); }); });
ngs/draft-js-markdown-shortcuts-plugin
src/modifiers/__test__/handleBlockType-test.js
JavaScript
mit
12,232
var searchData= [ ['text',['text',['../class_politechnikon_1_1game__elements_1_1_text.html#aa18ff5a85e90a5d19b62976a65863932',1,'Politechnikon::game_elements::Text']]], ['textbuffor',['TextBuffor',['../class_politechnikon_1_1game__elements_1_1_field.html#a35f9c0081c0928be00204ca03ca56f1e',1,'Politechnikon::game_elements::Field']]], ['texture',['Texture',['../class_politechnikon_1_1engine_1_1_initialized_object_texture.html#a01631ef3363a7c274d3b89d5032a4407',1,'Politechnikon::engine::InitializedObjectTexture']]], ['texturepath',['TexturePath',['../class_politechnikon_1_1engine_1_1_initialized_object_texture.html#af22f9450a1f0be442485364e2ad9a77f',1,'Politechnikon::engine::InitializedObjectTexture']]], ['thisgame',['ThisGame',['../struct_politechnikon_1_1game__logic_1_1_score.html#a50c9999f319885c723ff6026c25f44b4',1,'Politechnikon::game_logic::Score']]] ];
netruitus/Politechnikon
Docs/Dokumentacja/search/properties_e.js
JavaScript
mit
878
//================================================================ // RS_HUD_OptimizedMobile.js // --------------------------------------------------------------- // The MIT License // Copyright (c) 2015 biud436 // --------------------------------------------------------------- // Free for commercial and non commercial use. //================================================================ /*: * RS_HUD_OptimizedMobile.js * @plugindesc (v1.0.1) This plugin draws the HUD, which displays the hp and mp and exp and level of each party members. * * @author biud436 * * @param --- Image Name * * @param Texture Atlas * @parent --- Image Name * @desc import texture atlas. * @default config * @require 1 * @dir img/rs_hud/ * @type file * * @param EXP Gauge * @parent --- Image Name * @desc Specifies to import file in the path named 'exr' * @default exr * * @param Empty Gauge * @parent --- Image Name * @desc Specifies to import file in the path named 'gauge' * @default gauge * * @param HP Gauge * @parent --- Image Name * @desc Specifies to import file in the path named 'hp' * @default hp * * @param MP Gauge * @parent --- Image Name * @desc Specifies to import file in the path named 'mp' * @default mp * * @param HUD Background * @parent --- Image Name * @desc Specifies to import file in the path named 'hud_window_empty' * @default hud_window_empty * * @param Masking * @parent --- Image Name * @desc Specifies to import file in the path named 'masking' * @default masking * * @param --- Image Custom Position * * @param Face Position * @parent --- Image Custom Position * @desc Specifies the properties of the face sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 0, 0, true * * @param HP Position * @parent --- Image Custom Position * @desc Specifies the properties of the hp sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 160, 41, true * * @param MP Position * @parent --- Image Custom Position * @desc Specifies the properties of the mp sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 160, 67, true * * @param EXP Position * @parent --- Image Custom Position * @desc Specifies the properties of the exp sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 83, 89, true * * @param HP Text Position * @parent --- Image Custom Position * @desc Specifies the properties of the hp text sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 160, 51, true * * @param MP Text Position * @parent --- Image Custom Position * @desc Specifies the properties of the mp text sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 160, 77, true * * @param Level Text Position * @parent --- Image Custom Position * @desc Specifies the properties of the level text sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 60, 78, true * * @param EXP Text Position * @parent --- Image Custom Position * @desc Specifies the properties of the exp text sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 120.5, 91, true * * @param Name Text Position * @parent --- Image Custom Position * @desc Specifies the properties of the name text sprite by x, y, visible * (Draw it at changing position relative to a background sprite) * @default 54, 51, false * * @param --- Noraml * * @param Width * @parent --- Noraml * @desc Do not change this when you are using the default sprite batch. * (default : 317) * @default 317 * * @param Height * @parent --- Noraml * @desc Do not change this when you are using the default sprite batch. * (default : 101) * @default 101 * * @param Margin * @parent --- Noraml * @type number * @min 0 * @desc Sets the margin to the HUD borders. * @default 0 * * @param Gaussian Blur * @parent --- Noraml * @type boolean * @desc Sets the Gaussian Blur. * @default true * * @param Show * @parent --- Noraml * @type boolean * @desc Sets the visible status. (default : true) * @default true * * @param Opacity * @parent --- Noraml * @type number * @min 0 * @max 255 * @desc Sets the opacity. * @default 255 * * @param Arrangement * @parent --- Noraml * @type string[] * @desc Create an array to set the anchor of each HUD. * @default ["LeftTop", "LeftBottom", "RightTop", "RightBottom"] * * @param Anchor * @parent --- Noraml * @desc If anchor is not found, HUD would set to this anchor. * @default LeftTop * * @param preloadImportantFaces * @parent --- Noraml * @type string[] * @desc Allow you to pre-load the base face chips. * (If you do not set this parameter, It can cause errors in the game.) * @default ["Actor1", "Actor2", "Actor3"] * * @param Battle Only * @parent --- Noraml * @type boolean * @desc If you want to use the HUD only in battles. * (default : false) * @default false * * @param Show Comma * @parent --- Noraml * @type boolean * @desc Sets the value that indicates whether this parameter displays * the values with commas every three digits. * @default false * * @param Max Exp Text * @parent --- Noraml * @desc * @default ------/------ * * @param Max Members * @parent --- Noraml * @type number * @min 1 * @desc Specifies the maximum number of party members that displays within the game screen. * @default 4 * * @param --- Font * * @param Chinese Font * @parent --- Font * @desc Specifies the desired fonts * @default SimHei, Heiti TC, sans-serif * * @param Korean Font * @parent --- Font * @desc Specifies the desired fonts * @default NanumGothic, Dotum, AppleGothic, sans-serif * * @param Standard Font * @parent --- Font * @desc Specifies to import a css for the font file from ./fonts folder. * @default GameFont * * @param Level Text Size * @parent --- Font * @desc Specify the text size for levels. * @default 24 * * @param HP Text Size * @parent --- Font * @desc Specify the text size for HP. * @default 12 * * @param MP Text Size * @parent --- Font * @desc Specify the text size for MP. * @default 12 * * @param EXP Text Size * @parent --- Font * @desc Specify the text size for EXP. * @default 12 * * @param Name Text Size * @parent --- Font * @desc Specify the text size for names. * @default 12 * * @param --- Text Color * * @param HP Color * @parent --- Text Color * @desc Specify the text color for HP. * @default #ffffff * * @param MP Color * @parent --- Text Color * @desc Specify the text color for MP. * @default #ffffff * * @param EXP Color * @parent --- Text Color * @desc Specify the text color for EXP. * @default #ffffff * * @param Level Color * @parent --- Text Color * @desc Specify the text color for levels. * @default #ffffff * * @param Name Color * @parent --- Text Color * @desc Specify the text color for names. * @default #ffffff * * @param --- Text Outline Color * * @param HP Outline Color * @parent --- Text Outline Color * @desc Specify the text outline color for HP. * @default rgba(0, 0, 0, 0.5) * * @param MP Outline Color * @parent --- Text Outline Color * @desc Specify the text outline color for MP. * @default rgba(0, 0, 0, 0.5) * * @param EXP Outline Color * @parent --- Text Outline Color * @desc Specify the text outline color for EXP. * @default rgba(0, 0, 0, 0.5) * * @param Level Outline Color * @parent --- Text Outline Color * @desc Specify the text outline color for levels. * @default rgba(0, 0, 0, 0.5) * * @param Name Outline Color * @parent --- Text Outline Color * @desc Specify the text outline color for names. * @default rgba(0, 0, 0, 0.5) * * @param --- Text Outline Width * * @param HP Outline Width * @parent --- Text Outline Width * @desc Specify the maximum width of a text border line for HP. * @default 4 * * @param MP Outline Width * @parent --- Text Outline Width * @desc Specify the maximum width of a text border line for MP. * @default 4 * * @param EXP Outline Width * @parent --- Text Outline Width * @desc Specify the maximum width of a text border line for EXP. * @default 4 * * @param Level Outline Width * @parent --- Text Outline Width * @desc Specify the maximum width of a text border line for levels. * @default 4 * * @param Name Outline Width * @parent --- Text Outline Width * @desc Specify the maximum width of a text border line for names. * @default 4 * * @param --- Custom Font * * @param Using Custom Font * @parent --- Custom Font * @type boolean * @desc Specify whether the custom font shows (default : false) * YES - true / NO - false * @default false * * @param Custom Font Name * @parent --- Custom Font * @desc Specify the name of the custom font * @default NanumBrush * * @param Custom Font Src * @parent --- Custom Font * @desc Specify the path of the font file from a game project folder * @default fonts/NanumBrush.ttf * * @param --- Custom HUD Anchor * * @param Custom Pos 1 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to a custom position of the help section) * @default 0, (H * 0) + PD * * @param Custom Pos 2 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default 0, (H * 1) + PD * * @param Custom Pos 3 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default 0, (H * 2) + PD * * @param Custom Pos 4 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default 0, (H * 3) + PD * * @param Custom Pos 5 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default 0, (H * 4) + PD * * @param Custom Pos 6 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default W + PD, (H * 0) + PD * * @param Custom Pos 7 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default W + PD, (H * 1) + PD * * @param Custom Pos 8 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default W + PD, (H * 2) + PD * * @param Custom Pos 9 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default W + PD, (H * 3) + PD * * @param Custom Pos 10 * @parent --- Custom HUD Anchor * @desc Predefined Variables : W, H, PD, BW, BH * (Please refer to the help section) * @default W + PD, (H * 4) + PD * * @help * ============================================================================= * Installations * ============================================================================= * * Download the resources and place them in your img/rs_hud folder. * All the resources can download in the following link. * img/rs_hud/config.json : https://github.com/biud436/MV/raw/master/HUD/config.json * img/rs_hud/config.png : https://github.com/biud436/MV/raw/master/HUD/config.png * * Github Link : https://github.com/biud436/MV/blob/master/HUD/RS_HUD_OptimizedMobile.js * * ============================================================================= * Custom Positions * ============================================================================= * * To display in correct place, you need to know which predefined variables are currently available. * You can be available predefined variables as belows when specifying the parameter * named 'Custom Pos'. So you can quickly set up positions for a hud itself. * * Predefined Variables : * W - 'W' is the same as a parameter named 'Width' in Plugin Manager. * H - 'H' is the same as a parameter named 'Height' in Plugin Manager * PD - 'PD' is the same as a parameter named 'Margin' in Plugin Manager * BW - 'BW' is the same as a maximum width of the game canvas. * BH - 'BH' is the same as a maximum height of the game canvas. * * Each sprites draw at changing position relative to the background sprite. * Therefore, this custom position is pretty important values. * * ============================================================================= * Notetags * ============================================================================= * * Insert the following the notetag into the map property window as below. * <DISABLE_HUD> : A notetag can use in the map that does not wish create each huds. * * ============================================================================= * Script Calls * ============================================================================= * * ----------------------------------------------------------------------------- * Set Opacity * ----------------------------------------------------------------------------- * Sets the opacity of the HUD to x. * * $gameHud.opacity = x; * * That is a number between 0 and 255. * * For example : * $gameHud.opacity = 128; * * ----------------------------------------------------------------------------- * Set visibility * ----------------------------------------------------------------------------- * This variable will change the visible option of the HUD. * * $gameHud.show = true/false; * * For example : * $gameHud.show = false; * * ----------------------------------------------------------------------------- * Refresh Texts * ----------------------------------------------------------------------------- * In general, text and gauge sprites refresh when requesting a refresh so this one is not * updated on every frame. Therefore if you need to immediately refresh * all texts for themselves, you will use as belows. * * $gameTemp.notifyHudTextRefresh(); * * ----------------------------------------------------------------------------- * Clear and create all huds * ----------------------------------------------------------------------------- * if you need to immediately recreate for all Huds, you will use as belows. * * $gameTemp.notifyHudRefresh(); * ============================================================================= * Plugin Commands * ============================================================================= * * RS_HUD Opacity x : This command sets up the opacity for all hud elements. * 'x' is a number value between 0 and 255. * * RS_HUD Visible true/false : This command sets up whether it displays all containers for HUD. * 'RS_HUD Visible true' sets its visibility to true. * 'RS_HUD Visible false' sets its visibility to false. * * RS_HUD import file_name : This command imports the parameter as the json file from your data folder. * RS_HUD export file_name : This command exports the parameter as the json file to your data folder. * * ============================================================================= * Change Log * ============================================================================= * 2018.03.16 (v1.0.0) - First Release (forked in RS_HUD_4m) * 2018.05.09 (v1.0.1) - Supported a face image that is made using SumRndmDde's CharacterCreatorEX plugin. */ var Imported = Imported || {}; Imported.RS_HUD_OptimizedMobile = '1.0.1'; var $gameHud = null; var RS = RS || {}; RS.HUD = RS.HUD || {}; RS.HUD.param = RS.HUD.param || {}; (function() { if(Utils.RPGMAKER_VERSION < '1.5.0') { console.warn('Note that RS_HUD_4m plugin can use only in RMMV v1.5.0 or above.'); return; } var parameters = PluginManager.parameters('RS_HUD_OptimizedMobile'); // Image Settings RS.HUD.param.imgEXP = String(parameters['EXP Gauge'] || 'exr'); RS.HUD.param.imgEmptyGauge = String(parameters['Empty Gauge'] || 'gauge'); RS.HUD.param.imgHP = String(parameters['HP Gauge'] || 'hp'); RS.HUD.param.imgMP = String(parameters['MP Gauge'] || 'mp'); RS.HUD.param.imgEmptyHUD = String(parameters['HUD Background'] || 'hud_window_empty'); RS.HUD.param.imgMasking = String(parameters['Masking'] || 'masking'); // Image Position RS.HUD.loadImagePosition = function (szRE) { var target = szRE.match(/(.*),(.*),(.*)/i); var x = parseFloat(RegExp.$1); var y = parseFloat(RegExp.$2); var visible = Boolean(String(RegExp.$3).contains('true')); return {'x': x, 'y': y, 'visible': visible}; }; RS.HUD.loadRealNumber = function (paramName, val) { var value = Number(parameters[paramName]); switch (typeof(value)) { case 'object': case 'undefined': value = val; break; } return value; }; RS.HUD.param.ptFace = RS.HUD.loadImagePosition(parameters['Face Position'] || '0, 0, true'); RS.HUD.param.ptHP = RS.HUD.loadImagePosition(parameters['HP Position'] || '160, 43, true'); RS.HUD.param.ptMP = RS.HUD.loadImagePosition(parameters['MP Position'] || '160, 69, true'); RS.HUD.param.ptEXP = RS.HUD.loadImagePosition(parameters['EXP Position'] || '83, 91, true'); RS.HUD.param.ptHPText = RS.HUD.loadImagePosition(parameters['HP Text Position'] || '160, 53, true'); RS.HUD.param.ptMPText = RS.HUD.loadImagePosition(parameters['MP Text Position'] || '160, 79, true'); RS.HUD.param.ptLevelText = RS.HUD.loadImagePosition(parameters['Level Text Position'] || '60, 80, true'); RS.HUD.param.ptEXPText = RS.HUD.loadImagePosition(parameters['EXP Text Position'] || '120.5, 93, true'); RS.HUD.param.ptNameText = RS.HUD.loadImagePosition(parameters['Name Text Position'] || '54, 53, true'); // Normal Settings RS.HUD.param.nWidth = RS.HUD.loadRealNumber('Width', 317); RS.HUD.param.nHeight = RS.HUD.loadRealNumber('Height', 101); RS.HUD.param.nPD = RS.HUD.loadRealNumber('Margin', 0); RS.HUD.param.blurProcessing = Boolean(parameters['Gaussian Blur'] === "true"); RS.HUD.param.bShow = Boolean(parameters['Show'] ==="true"); RS.HUD.param.nOpacity = RS.HUD.loadRealNumber('Opacity', 255); RS.HUD.param.szAnchor = String(parameters['Anchor'] || "LeftTop"); RS.HUD.param.arrangement = eval(parameters['Arrangement']); RS.HUD.param.preloadImportantFaces = eval(parameters['preloadImportantFaces'] || 'Actor1'); RS.HUD.param.battleOnly = Boolean(parameters['Battle Only'] === "true"); RS.HUD.param.showComma = Boolean(parameters['Show Comma'] === 'true'); RS.HUD.param.maxExpText = String(parameters['Max Exp Text'] || "------/------"); RS.HUD.param.nMaxMembers = parseInt(parameters["Max Members"] || 4); RS.HUD.getDefaultHUDAnchor = function () { var anchor = { "LeftTop": {x: RS.HUD.param.nPD, y: RS.HUD.param.nPD}, "LeftBottom": {x: RS.HUD.param.nPD, y: Graphics.boxHeight - RS.HUD.param.nHeight - RS.HUD.param.nPD}, "RightTop": {x: Graphics.boxWidth - RS.HUD.param.nWidth - RS.HUD.param.nPD, y: RS.HUD.param.nPD}, "RightBottom": {x: Graphics.boxWidth - RS.HUD.param.nWidth - RS.HUD.param.nPD, y: Graphics.boxHeight - RS.HUD.param.nHeight - RS.HUD.param.nPD} }; return anchor; }; // Font Settings RS.HUD.param.chineseFont = String(parameters['Chinese Font'] || 'SimHei, Heiti TC, sans-serif'); RS.HUD.param.koreanFont = String(parameters['Korean Font'] || 'NanumGothic, Dotum, AppleGothic, sans-serif'); RS.HUD.param.standardFont = String(parameters['Standard Font'] || 'GameFont'); // Text Size RS.HUD.param.levelTextSize = RS.HUD.loadRealNumber('Level Text Size', 12); RS.HUD.param.hpTextSize = RS.HUD.loadRealNumber('HP Text Size', 12); RS.HUD.param.mpTextSize = RS.HUD.loadRealNumber('MP Text Size', 12); RS.HUD.param.expTextSize = RS.HUD.loadRealNumber('EXP Text Size', 12); RS.HUD.param.nameTextSize = RS.HUD.loadRealNumber('Name Text Size', 12); // Text Color RS.HUD.param.szHpColor = String(parameters['HP Color'] || '#ffffff'); RS.HUD.param.szMpColor = String(parameters['MP Color'] || '#ffffff'); RS.HUD.param.szExpColor = String(parameters['EXP Color'] || '#ffffff'); RS.HUD.param.szLevelColor = String(parameters['Level Color'] || '#ffffff'); RS.HUD.param.szNameColor = String(parameters['Name Color'] || '#ffffff'); // Text Outline Color RS.HUD.param.szHpOutlineColor = String(parameters['HP Outline Color'] || 'rgba(0, 0, 0, 0.5)'); RS.HUD.param.szMpOutlineColor = String(parameters['MP Outline Color'] || 'rgba(0, 0, 0, 0.5)'); RS.HUD.param.szExpOutlineColor = String(parameters['EXP Outline Color'] || 'rgba(0, 0, 0, 0.5)'); RS.HUD.param.szLevelOutlineColor = String(parameters['Level Outline Color'] || 'rgba(0, 0, 0, 0.5)'); RS.HUD.param.szNameOutlineColor = String(parameters['Name Outline Color'] || 'rgba(0, 0, 0, 0.5)'); // Text Outline Width RS.HUD.param.szHpOutlineWidth = RS.HUD.loadRealNumber('HP Outline Width', 4); RS.HUD.param.szMpOutlineWidth = RS.HUD.loadRealNumber('MP Outline Width', 4); RS.HUD.param.szExpOutlineWidth = RS.HUD.loadRealNumber('EXP Outline Width', 4); RS.HUD.param.szLevelOutlineWidth = RS.HUD.loadRealNumber('Level Outline Width', 4); RS.HUD.param.szNameOutlineWidth = RS.HUD.loadRealNumber('Name Outline Width', 4); // Custom Font RS.HUD.param.bUseCustomFont = Boolean(parameters['Using Custom Font'] === 'true'); RS.HUD.param.szCustomFontName = String(parameters['Custom Font Name'] || 'GameFont' ); RS.HUD.param.szCustomFontSrc = String(parameters['Custom Font Src'] || 'fonts/mplus-1m-regular.ttf'); // Custom HUD Anchor RS.HUD.param.ptCustormAnchor = []; RS.HUD.param.isCurrentBattleShowUp = false; RS.HUD.param.isPreviousShowUp = false; RS.HUD.param.init = false; PIXI.loader .add("config", "img/rs_hud/config.json") .load(onAssetsLoaded); function onAssetsLoaded() { RS.HUD.param.init = true; }; RS.HUD.loadCustomPosition = function (szRE) { var W = RS.HUD.param.nWidth; var H = RS.HUD.param.nHeight; var PD = RS.HUD.param.nPD; var BW = Graphics.boxWidth || 816; var BH = Graphics.boxHeight || 624; var x = eval('[' + szRE + ']'); if(x instanceof Array) return new Point(x[0], x[1]); return new Point(0, 0); }; // Opacity and Tone Glitter Settings var nOpacityEps = 5; var nOpacityMin = 64; var nFaceDiameter = 96; var nHPGlitter = 0.4; var nMPGlitter = 0.4; var nEXPGlitter = 0.7; var defaultTemplate = 'hud_default_template.json'; //---------------------------------------------------------------------------- // Data Imports & Exports // // RS.HUD.localFilePath = function (fileName) { if(!Utils.isNwjs()) return ''; var path, base; path = require('path'); base = path.dirname(process.mainModule.filename); return path.join(base, 'data/') + (fileName || defaultTemplate); }; RS.HUD.exportData = function (fileName) { var fs, data, filePath; if(!Utils.isNwjs()) return false; if(!RS.HUD.param) return false; fs = require('fs'); data = JSON.stringify(RS.HUD.param); filePath = RS.HUD.localFilePath(fileName); fs.writeFile(filePath, data, 'utf8', function (err) { if (err) throw err; }); }; RS.HUD.loadData = function (data) { var params = Object.keys(RS.HUD.param); data = JSON.parse(data); params.forEach(function (name) { RS.HUD.param[name] = data[name]; }, this); setTimeout(function () { $gameTemp.notifyHudRefresh(); }, 0); }; RS.HUD.importData = function (fileName) { if(!Utils.isNwjs()) return false; var fs = require('fs'); var filePath = RS.HUD.localFilePath(fileName); var data = fs.readFileSync(filePath, { encoding: 'utf8' }); RS.HUD.loadData(data); }; RS.HUD.importDataWithAjax = function (fileName) { var xhr = new XMLHttpRequest(); var self = RS.HUD; var url = './data/' + (fileName || defaultTemplate); xhr.open('GET', url); xhr.onload = function() { if(xhr.status < 400) { RS.HUD.loadData(xhr.responseText.slice(0)); } } xhr.send(); }; RS.HUD.loadPicture = function (filename) { var bitmap = ImageManager.reservePicture(filename); return bitmap; }; RS.HUD.loadFace = function (filename) { var bitmap = ImageManager.reserveFace(filename); return bitmap; }; //---------------------------------------------------------------------------- // Bitmap // // Bitmap.prototype.drawClippingImage = function(bitmap, maskImage , _x, _y, _sx, _sy) { var context = this._context; context.save(); context.drawImage(maskImage._canvas, _x, _y, nFaceDiameter, nFaceDiameter); context.globalCompositeOperation = 'source-atop'; context.drawImage(bitmap._canvas, _sx, _sy, 144, 144, 0, 0, nFaceDiameter, nFaceDiameter); context.restore(); this._setDirty(); }; Bitmap.prototype.drawClippingImageNonBlur = function(bitmap, _x, _y, _sx, _sy) { var context = this._context; context.save(); context.beginPath(); context.arc(_x + 45, _y + 45 , 45, 0, Math.PI * 2, false); context.clip(); context.drawImage(bitmap._canvas, _sx, _sy, 144, 144, 0, 0, nFaceDiameter, nFaceDiameter); context.restore(); this._setDirty(); }; //---------------------------------------------------------------------------- // Game_Temp // // Game_Temp.prototype.notifyHudTextRefresh = function() { if($gameHud) $gameHud.updateText(); }; Game_Temp.prototype.notifyHudRefresh = function() { if($gameHud) $gameHud.refresh(); }; //---------------------------------------------------------------------------- // Game_System ($gameSystem) // // var _alias_Game_System_initialize = Game_System.prototype.initialize; Game_System.prototype.initialize = function() { _alias_Game_System_initialize.call(this); this._rs_hud = this._rs_hud || {}; this._rs_hud.show = this._rs_hud.show || RS.HUD.param.bShow; this._rs_hud.opacity = this._rs_hud.opacity || RS.HUD.param.nOpacity; }; //---------------------------------------------------------------------------- // Game_Battler // // var alias_Game_Battler_refresh = Game_Battler.prototype.refresh; Game_Battler.prototype.refresh = function() { alias_Game_Battler_refresh.call(this); $gameTemp.notifyHudTextRefresh(); }; //---------------------------------------------------------------------------- // Game_Actor // // Game_Actor.prototype.relativeExp = function () { if(this.isMaxLevel()) { return this.expForLevel(this.maxLevel()); } else { return this.currentExp() - this.currentLevelExp(); } }; Game_Actor.prototype.relativeMaxExp = function () { if(!this.isMaxLevel()) { return this.nextLevelExp() - this.currentLevelExp(); } else { return this.expForLevel(this.maxLevel()); } }; //---------------------------------------------------------------------------- // Game_Party // // var alias_Game_Party_swapOrder = Game_Party.prototype.swapOrder; Game_Party.prototype.swapOrder = function(index1, index2) { alias_Game_Party_swapOrder.call(this, index1, index2); $gameTemp.notifyHudRefresh(); }; //---------------------------------------------------------------------------- // TextData // // function TextData() { this.initialize.apply(this, arguments); } TextData.prototype = Object.create(Sprite.prototype); TextData.prototype.constructor = TextData; TextData.prototype.initialize = function(bitmap, func, params) { Sprite.prototype.initialize.call(this, bitmap); this.setCallbackFunction(func); this.updateTextLog(); this._params = params; this.requestUpdate(); }; TextData.prototype.setCallbackFunction = function (cbFunc) { this._callbackFunction = cbFunc; }; TextData.prototype.updateTextLog = function () { this._log = this._callbackFunction.call(); }; TextData.prototype.startCallbackFunction = function () { this._callbackFunction.call(this); }; TextData.prototype.getTextProperties = function (n) { return this._params[n]; }; TextData.prototype.drawDisplayText = function () { this.defaultFontSettings(); this.bitmap.drawText(this._callbackFunction(this), 0, 0, 120, this._params[0] + 8, 'center'); }; TextData.prototype.isRefresh = function () { var currentText = this._callbackFunction(); return currentText.localeCompare(this._log) !== 0; }; TextData.prototype.clearTextData = function () { this.bitmap.clear(); }; TextData.prototype.requestUpdate = function () { this.clearTextData(); this.drawDisplayText(); this.updateTextLog(); }; TextData.prototype.standardFontFace = function() { if(RS.HUD.param.bUseCustomFont) { return RS.HUD.param.szCustomFontName; } else { if (navigator.language.match(/^zh/)) { return RS.HUD.param.chineseFont; } else if (navigator.language.match(/^ko/)) { return RS.HUD.param.koreanFont; } else { return RS.HUD.param.standardFont; } } }; TextData.prototype.defaultFontSettings = function() { var param = this._params; this.bitmap.fontFace = this.standardFontFace(); this.bitmap.fontSize = param[0]; this.bitmap.textColor = param[1]; this.bitmap.outlineColor = param[2]; this.bitmap.outlineWidth = param[3]; }; //---------------------------------------------------------------------------- // HUD // // function HUD() { this.initialize.apply(this, arguments); }; //---------------------------------------------------------------------------- // RS_HudLayer // // function RS_HudLayer() { this.initialize.apply(this, arguments); }; RS_HudLayer.prototype = Object.create(Sprite.prototype); RS_HudLayer.prototype.constructor = RS_HudLayer; RS_HudLayer.prototype.initialize = function(bitmap) { Sprite.prototype.initialize.call(this, bitmap); this.alpha = 0; this.createItemLayer(); }; RS_HudLayer.prototype.createItemLayer = function () { this._items = new Sprite(); this._items.setFrame(0, 0, Graphics.boxWidth, Graphics.boxHeight); this.addChild(this._items); }; RS_HudLayer.prototype.drawAllHud = function() { var allHud = this._items; var items = RS.HUD.param.arrangement; // This removes any drawing objects that have already been created. if(allHud.children.length > 0) { allHud.removeChildren(0, allHud.children.length); } items.forEach(function(item, index){ // This code runs only when there is a party member at a specific index. if(!!$gameParty.members()[index]) { if(item !== null) allHud.addChild(new HUD({szAnchor: item, nIndex: index})); } }, this); // It sorts objects by party number. this.sort(); this.show = $gameSystem._rs_hud.show; this.opacity = $gameSystem._rs_hud.opacity; }; RS_HudLayer.prototype.update = function () { var members = $gameParty.members(); this.children.forEach(function(child, idx) { if (child.update && members[idx]) { child.update(); } }); }; RS_HudLayer.prototype.sort = function() { var allHud = this._items; var array = allHud.children; allHud.children = array.sort(function(a, b) { return a._memberIndex - b._memberIndex; }); } RS_HudLayer.prototype.refresh = function() { var allHud = this._items; allHud.children.forEach(function(i) { allHud.removeChild(i); }, this); this.drawAllHud(); this.show = $gameSystem._rs_hud.show; }; RS_HudLayer.prototype.updateText = function() { var allHud = this._items; allHud.children.forEach(function(i) { i.updateText(); }, this); }; RS_HudLayer.prototype.updateFrame = function () { var allHud = this._items; allHud.children.forEach(function(i) { i.paramUpdate(); }, this); }; RS_HudLayer.prototype.remove = function(index) { var self = this; setTimeout(function() { while($gameParty.size() !== self._items.children.length) { self.drawAllHud(); } }, 0); }; Object.defineProperty(RS_HudLayer.prototype, 'show', { get: function() { return this.visible; }, set: function(value) { this.visible = value; $gameSystem._rs_hud.show = value; }, }); Object.defineProperty(RS_HudLayer.prototype, 'opacity', { get: function() { return Math.floor(this.alpha * 255); }, set: function(value) { this.alpha = value * 0.00392156862745098; $gameSystem._rs_hud.opacity = value.clamp(0, 255); }, }); //---------------------------------------------------------------------------- // RS_EmptyHudLayer // // function RS_EmptyHudLayer() { this.initialize.apply(this, arguments); } RS_EmptyHudLayer.prototype = Object.create(Sprite.prototype); RS_EmptyHudLayer.prototype.constructor = RS_EmptyHudLayer; RS_EmptyHudLayer.prototype.initialize = function(bitmap) { Sprite.prototype.initialize.call(this, bitmap); this.alpha = 0; }; RS_EmptyHudLayer.prototype.constructor = RS_EmptyHudLayer; Object.defineProperty(RS_EmptyHudLayer.prototype, 'show', { get: function() { return $gameSystem._rs_hud.show; }, set: function(value) { $gameSystem._rs_hud.show = value; } }); Object.defineProperty(RS_EmptyHudLayer.prototype, 'opacity', { get: function() { return $gameSystem._rs_hud.opacity; }, set: function(value) { $gameSystem._rs_hud.opacity = value.clamp(0, 255); } }); //---------------------------------------------------------------------------- // HUD // // HUD.prototype = Object.create(Stage.prototype); HUD.prototype.constructor = HUD; HUD.prototype.initialize = function(config) { Stage.prototype.initialize.call(this); this.createHud(); this.setAnchor(config.szAnchor || "LeftBottom"); this.setMemberIndex(parseInt(config.nIndex) || 0); this.createFace(); this.createHp(); this.createMp(); this.createExp(); this.createText(); this.setPosition(); this.paramUpdate(); }; HUD.prototype.getAnchor = function(magnet) { var anchor = RS.HUD.getDefaultHUDAnchor(); // Add Custom Anchor for(var i = 0; i < RS.HUD.param.nMaxMembers; i++) { var idx = parseInt(i + 1); anchor['Custom Pos ' + idx] = RS.HUD.param.ptCustormAnchor[i]; } return anchor[magnet]; }; HUD.prototype.setAnchor = function(anchor) { var pos = this.getAnchor(anchor); if(typeof(pos) === 'object') { this._hud.x = pos.x; this._hud.y = pos.y; } else { this.setAnchor(RS.HUD.param.szAnchor); } }; HUD.prototype.setMemberIndex = function(index) { this._memberIndex = index; }; HUD.prototype.fromImage = function(textureName) { var texture = PIXI.utils.TextureCache[textureName + ".png"]; var sprite = new PIXI.Sprite(texture); return sprite; }; HUD.prototype.createHud = function() { this._hud = this.fromImage(RS.HUD.param.imgEmptyHUD); this.addChild(this._hud); }; HUD.prototype.createFace = function() { var player = this.getPlayer(); if(Imported["SumRndmDde Character Creator EX"]) { if(player.hasSetImage()) { this._faceBitmap = player.getCreatorBitmapFace(); } else { this._faceBitmap = RS.HUD.loadFace(player.faceName()); } } else { this._faceBitmap = RS.HUD.loadFace(player.faceName()); } this._maskBitmap = RS.HUD.loadPicture(RS.HUD.param.imgMasking); this._maskBitmap.addLoadListener(function() { this._faceBitmap.addLoadListener(this.circleClippingMask.bind(this, player.faceIndex())); }.bind(this)); }; HUD.prototype.circleClippingMask = function(faceIndex) { this._face = new Sprite(); var fw = Window_Base._faceWidth; var fh = Window_Base._faceHeight; var sx = (faceIndex % 4) * fw; var sy = Math.floor(faceIndex / 4) * fh; this._face.bitmap = new Bitmap(nFaceDiameter, nFaceDiameter); if (RS.HUD.param.blurProcessing) { this._face.bitmap.drawClippingImage(this._faceBitmap, this._maskBitmap, 0, 0, sx, sy); } else { this._face.bitmap.drawClippingImageNonBlur(this._faceBitmap, 0, 0, sx, sy); } this.addChild(this._face); this.setCoord(this._face, RS.HUD.param.ptFace); }; HUD.prototype.createMask = function (parent) { var mask = new PIXI.Graphics(); mask.beginFill(0x0000ff, 1.0); mask.drawRect(0,0, parent.width, parent.height); mask.endFill(); parent.mask = mask; return mask; }; HUD.prototype.createHp = function() { this._hp = this.fromImage(RS.HUD.param.imgHP); this._hpMask = this.createMask(this._hp); this.addChild(this._hpMask, this._hp); }; HUD.prototype.createMp = function() { this._mp = this.fromImage(RS.HUD.param.imgMP); this._mpMask = this.createMask(this._mp); this.addChild(this._mpMask, this._mp); }; HUD.prototype.createExp = function() { this._exp = this.fromImage(RS.HUD.param.imgEXP); this._expMask = this.createMask(this._exp); this.addChild(this._expMask, this._exp); }; HUD.prototype.getTextParams = function(src) { var param = RS.HUD.param; var textProperties = { 'HP': [param.hpTextSize, param.szHpColor, param.szHpOutlineColor, param.szHpOutlineWidth], 'MP': [param.mpTextSize, param.szMpColor, param.szMpOutlineColor, param.szMpOutlineWidth], 'EXP': [param.expTextSize, param.szExpColor, param.szExpOutlineColor, param.szExpOutlineWidth], 'LEVEL': [param.levelTextSize, param.szLevelColor, param.szLevelOutlineColor, param.szLevelOutlineWidth], 'NAME': [param.nameTextSize, param.szNameColor, param.szNameOutlineColor, param.szNameOutlineWidth] }; return textProperties[src]; }; HUD.prototype.createText = function() { this._hpText = this.addText(this.getHp.bind(this), this.getTextParams('HP')); this._mpText = this.addText(this.getMp.bind(this), this.getTextParams('MP')); this._expText = this.addText(this.getExp.bind(this), this.getTextParams('EXP')); this._levelText = this.addText(this.getLevel.bind(this), this.getTextParams('LEVEL')); this._nameText = this.addText(this.getName.bind(this), this.getTextParams('NAME')); }; HUD.prototype.setPosition = function() { var param = RS.HUD.param; if(this._face) this.setCoord(this._face, param.ptFace); this.setCoord(this._hpMask, param.ptHP); this.setCoord(this._hp, param.ptHP); this.setCoord(this._mpMask, param.ptMP); this.setCoord(this._mp, param.ptMP); this.setCoord(this._expMask, param.ptEXP); this.setCoord(this._exp, param.ptEXP); this.setCoord(this._hpText, param.ptHPText); this.setCoord(this._mpText, param.ptMPText); this.setCoord(this._levelText, param.ptLevelText); this.setCoord(this._expText, param.ptEXPText); this.setCoord(this._nameText, param.ptNameText); }; HUD.prototype.addText = function(strFunc, params) { var bitmap = new Bitmap(120, params[0] + 8); var text = new TextData(bitmap, strFunc, params); var length = this.children.length; this.addChildAt(text, length); text.drawDisplayText(); return text; }; HUD.prototype.getPlayer = function() { return $gameParty.members()[this._memberIndex]; }; HUD.prototype.getHp = function() { var player = this.getPlayer(); if(!player) return "0 / 0"; if(RS.HUD.param.showComma) { return "%1 / %2".appendComma(player.hp, player.mhp); } else { return "%1 / %2".format(player.hp, player.mhp); } }; HUD.prototype.getMp = function() { var player = this.getPlayer(); if(!player) return "0 / 0"; if(RS.HUD.param.showComma) { return "%1 / %2".appendComma(player.mp, player.mmp); } else { return "%1 / %2".format(player.mp, player.mmp); } }; HUD.prototype.getExp = function() { var player = this.getPlayer(); if(!player) return "0 / 0"; if(player.isMaxLevel()) return RS.HUD.param.maxExpText; if(RS.HUD.param.showComma) { return "%1 / %2".appendComma(player.relativeExp(), player.relativeMaxExp()); } else { return "%1 / %2".format(player.relativeExp(), player.relativeMaxExp()); } }; HUD.prototype.getLevel = function() { var player = this.getPlayer(); if(!player) return "0"; if(RS.HUD.param.showComma) { return "%1".appendComma(player.level); } else { return "%1".format(player.level); } }; HUD.prototype.getName = function() { var player = this.getPlayer(); if(!player) return ""; var name = player && player.name(); if(name) { return name; } else { return ' '; } }; HUD.prototype.getHpRate = function() { var player = this.getPlayer(); if(!player) return 0; return this._hp.width * (player.hp / player.mhp); }; HUD.prototype.getMpRate = function() { var player = this.getPlayer(); if(!player) return 0; return this._mp.width * (player.mp / player.mmp); }; HUD.prototype.getExpRate = function() { var player = this.getPlayer(); if(!player) return 0; return this._exp.width * (player.relativeExp() / player.relativeMaxExp()); }; HUD.prototype.getRealExpRate = function () { var player = this.getPlayer(); if(!player) return 0; if(this.inBattle() && $dataSystem.optDisplayTp) { return ( player.tp / player.maxTp() ); } else { return ( player.relativeExp() / player.relativeMaxExp() ); } }; HUD.prototype.setCoord = function(s,obj) { var oy = (s._callbackFunction instanceof Function) ? (s.bitmap.height / 2) : 0; s.x = this._hud.x + obj.x; s.y = this._hud.y + obj.y - oy; s.visible = obj.visible; }; HUD.prototype.update = function() { this.paramUpdate(); }; HUD.prototype.updateText = function() { this._hpText.requestUpdate(); this._mpText.requestUpdate(); this._expText.requestUpdate(); this._levelText.requestUpdate(); this._nameText.requestUpdate(); }; HUD.prototype.updateGuage = function (mask, w, h) { if(!mask) return; mask.clear(); mask.beginFill(0x0000ff, 1.0); mask.drawRect(0,0, w, h); mask.endFill(); }; HUD.prototype.paramUpdate = function() { this.updateGuage(this._hpMask, this.getHpRate(), this._hp.height); this.updateGuage(this._mpMask, this.getMpRate(), this._mp.height); this.updateGuage(this._expMask, this.getExpRate(), this._exp.height); }; HUD.prototype.inBattle = function() { return (SceneManager._scene instanceof Scene_Battle || $gameParty.inBattle() || DataManager.isBattleTest()); }; Object.defineProperty(HUD.prototype, 'show', { get: function() { return $gameSystem._rs_hud.show; }, set: function(value) { this.children.forEach( function(i) { i.visible = value; }, this); $gameSystem._rs_hud.show = value; if(value === true) { this.setPosition(); } }, }); Object.defineProperty(HUD.prototype, 'opacity', { get: function() { return $gameSystem._rs_hud.opacity; }, set: function(value) { this.children.forEach( function(i) { i.opacity = value.clamp(0, 255); }, this); $gameSystem._rs_hud.opacity = value.clamp(0, 255); }, }); //---------------------------------------------------------------------------- // Scene_Map // // var alias_Scene_Map_createDisplayObjects = Scene_Map.prototype.createDisplayObjects; Scene_Map.prototype.createDisplayObjects = function() { alias_Scene_Map_createDisplayObjects.call(this); if(RS.HUD.param.battleOnly || ($dataMap && $dataMap.meta.DISABLE_HUD) ) { $gameHud = new RS_EmptyHudLayer(); } else { this._hudLayer = new RS_HudLayer(); this._hudLayer.setFrame(0, 0, Graphics.boxWidth, Graphics.boxHeight); $gameHud = this._hudLayer; this._hudLayer.drawAllHud(); this.addChild(this._hudLayer); this.swapChildren(this._windowLayer, this._hudLayer); } }; var alias_Scene_Map_start = Scene_Map.prototype.start; Scene_Map.prototype.start = function () { alias_Scene_Map_start.call(this); $gameTemp.notifyHudTextRefresh(); }; var alias_Scene_Map_terminate = Scene_Map.prototype.terminate; Scene_Map.prototype.terminate = function() { this.removeChild(this._hudLayer); $gameHud = null; alias_Scene_Map_terminate.call(this); }; //---------------------------------------------------------------------------- // Game_Party // // var alias_Game_Party_addActor = Game_Party.prototype.addActor; Game_Party.prototype.addActor = function(actorId) { alias_Game_Party_addActor.call(this, actorId); $gameTemp.notifyHudRefresh(); }; var alias_Game_Party_removeActor = Game_Party.prototype.removeActor; Game_Party.prototype.removeActor = function(actorId) { alias_Game_Party_removeActor.call(this, actorId); $gameTemp.notifyHudRefresh(); }; //---------------------------------------------------------------------------- // Scene_Boot // // var alias_Scene_Boot_loadSystemWindowImage = Scene_Boot.prototype.loadSystemWindowImage; Scene_Boot.prototype.loadSystemWindowImage = function() { alias_Scene_Boot_loadSystemWindowImage.call(this); // Load Face RS.HUD.param.preloadImportantFaces.forEach(function(i) { if(Utils.RPGMAKER_VERSION >= '1.5.0') { ImageManager.reserveFace(i) } else { ImageManager.loadFace(i); } }, this); if(Utils.RPGMAKER_VERSION >= '1.5.0') { ImageManager.reservePicture(RS.HUD.param.imgHP); ImageManager.reservePicture(RS.HUD.param.imgMP); ImageManager.reservePicture(RS.HUD.param.imgEXP); } }; var alias_Scene_Boot_start = Scene_Boot.prototype.start; Scene_Boot.prototype.start = function() { alias_Scene_Boot_start.call(this); // Load Custom Anchor for(var i = 0; i < RS.HUD.param.nMaxMembers; i++) { RS.HUD.param.ptCustormAnchor.push( RS.HUD.loadCustomPosition(parameters[String('Custom Pos ' + (i + 1))] || '0, 0') ); } // Load Custom Font if(RS.HUD.param.bUseCustomFont) { Graphics.loadFont(RS.HUD.param.szCustomFontName, RS.HUD.param.szCustomFontSrc); } }; //---------------------------------------------------------------------------- // Scene_Map // // var alias_Scene_Map_snapForBattleBackground = Scene_Map.prototype.snapForBattleBackground; Scene_Map.prototype.snapForBattleBackground = function() { var temp = $gameHud.show; if($gameHud && $gameHud.show) $gameHud.show = false; alias_Scene_Map_snapForBattleBackground.call(this); if($gameHud && !$gameHud.show) { RS.HUD.param.isPreviousShowUp = temp; $gameHud.show = temp; } }; var alias_Scene_Map_updateFade = Scene_Map.prototype.updateFade; Scene_Map.prototype.updateFade = function() { alias_Scene_Map_updateFade.call(this); if(this._fadeDuration == 0 && RS.HUD.param.isCurrentBattleShowUp) { if($gameHud) $gameHud.show = RS.HUD.param.isPreviousShowUp; RS.HUD.param.isCurrentBattleShowUp = false; } }; var alias_Scene_Battle_updateFade = Scene_Battle.prototype.updateFade; Scene_Battle.prototype.updateFade = function() { alias_Scene_Battle_updateFade.call(this); if(this._fadeDuration == 0 && !RS.HUD.param.isCurrentBattleShowUp) { if($gameHud) $gameHud.show = true; RS.HUD.param.isCurrentBattleShowUp = true; } }; //---------------------------------------------------------------------------- // Game_Interpreter // // var alias_Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { alias_Game_Interpreter_pluginCommand.call(this, command, args); if(command === "RS_HUD") { switch (args[0].toLowerCase()) { case 'opacity': $gameHud.opacity = Number(args[1]); break; case 'visible': $gameHud.show = Boolean(args[1] === "true"); break; case 'import': RS.HUD.importDataWithAjax(args[1] + '.json'); break; case 'export': RS.HUD.exportData(args[1] + '.json'); break; } } }; //---------------------------------------------------------------------------- // String Utils // // /** * String.prototype.toArray */ String.prototype.toArray = function(){ return this.split(""); } /** * String.prototype.reverse */ String.prototype.reverse = function(){ return this.toArray().reverse().join(""); } /** * String.prototype.toComma */ String.prototype.toComma = function(){ return this.reverse().match(/.{1,3}/g).join(",").reverse(); } /** * Replaces %1, %2 and so on in the string to the arguments. * * @method String.prototype.format * @param {Any} ...args The objects to format * @return {String} A formatted string */ String.prototype.appendComma = function() { var args = arguments; return this.replace(/%([0-9]+)/g, function(s, n) { return (args[Number(n) - 1] + '').toComma(); }); }; //============================================================================ // Scene_Boot //============================================================================ var alias_Scene_Boot_isReady = Scene_Boot.prototype.isReady; Scene_Boot.prototype.isReady = function() { if(alias_Scene_Boot_isReady.call(this)) { return RS.HUD.param.init; } else { return false; } }; //---------------------------------------------------------------------------- // Output Objects // // window.HUD = HUD; window.RS_HudLayer = RS_HudLayer; })();
biud436/MV
HUD/RS_HUD_OptimizedMobile.js
JavaScript
mit
50,310
var fs = require('fs'); var path = require('path'); var gulp = require('gulp'); var sass = require('gulp-sass'); // Load all gulp plugins automatically // and attach them to the `plugins` object var plugins = require('gulp-load-plugins')(); // Temporary solution until gulp 4 // https://github.com/gulpjs/gulp/issues/355 var runSequence = require('run-sequence'); var pkg = require('./package.json'); var dirs = pkg['h5bp-configs'].directories; // --------------------------------------------------------------------- // | Helper tasks | // --------------------------------------------------------------------- gulp.task('archive:create_archive_dir', function () { fs.mkdirSync(path.resolve(dirs.archive), '0755'); }); gulp.task('archive:zip', function (done) { var archiveName = path.resolve(dirs.archive, pkg.name + '_v' + pkg.version + '.zip'); var archiver = require('archiver')('zip'); var files = require('glob').sync('**/*.*', { 'cwd': dirs.dist, 'dot': true // include hidden files }); var output = fs.createWriteStream(archiveName); archiver.on('error', function (error) { done(); throw error; }); output.on('close', done); files.forEach(function (file) { var filePath = path.resolve(dirs.dist, file); // `archiver.bulk` does not maintain the file // permissions, so we need to add files individually archiver.append(fs.createReadStream(filePath), { 'name': file, 'mode': fs.statSync(filePath) }); }); archiver.pipe(output); archiver.finalize(); }); gulp.task('clean', function (done) { require('del')([ dirs.archive, dirs.dist ], done); }); gulp.task('copy', [ 'copy:.htaccess', 'copy:index.html', 'copy:jquery', 'copy:license', 'copy:main.css', 'copy:misc', 'copy:normalize' ]); gulp.task('copy:.htaccess', function () { return gulp.src('node_modules/apache-server-configs/dist/.htaccess') .pipe(plugins.replace(/# ErrorDocument/g, 'ErrorDocument')) .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:index.html', function () { return gulp.src(dirs.src + '/index.html') .pipe(plugins.replace(/{{JQUERY_VERSION}}/g, pkg.devDependencies.jquery)) .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:jquery', function () { return gulp.src(['node_modules/jquery/dist/jquery.min.js']) .pipe(plugins.rename('jquery-' + pkg.devDependencies.jquery + '.min.js')) .pipe(gulp.dest(dirs.dist + '/js/vendor')); }); gulp.task('copy:license', function () { return gulp.src('LICENSE.txt') .pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:main.css', function () { var banner = '/*! HTML5 Boilerplate v' + pkg.version + ' | ' + pkg.license.type + ' License' + ' | ' + pkg.homepage + ' */\n\n'; return gulp.src(dirs.src + '/css/main.css') .pipe(plugins.header(banner)) .pipe(plugins.autoprefixer({ browsers: ['last 2 versions', 'ie >= 8', '> 1%'], cascade: false })) .pipe(gulp.dest(dirs.dist + '/css')); }); gulp.task('copy:misc', function () { return gulp.src([ // Copy all files dirs.src + '/**/*', // Exclude the following files // (other tasks will handle the copying of these files) '!' + dirs.src + '/css/main.css', '!' + dirs.src + '/css/*.css.map', '!' + dirs.src + '/index.html', '!' + dirs.src + '/styles/**/*', '!' + dirs.src + '/js/util/**/*', '!' + dirs.src + '/js/.DS_Store', '!' + dirs.src + '/js/util', '!' + dirs.src + '/styles' ], { // Include hidden files by default dot: true }).pipe(gulp.dest(dirs.dist)); }); gulp.task('copy:normalize', function () { return gulp.src('node_modules/normalize.css/normalize.css') .pipe(gulp.dest(dirs.dist + '/css')); }); gulp.task('lint:js', function () { return gulp.src([ 'gulpfile.js', dirs.src + '/js/*.js', dirs.test + '/*.js' ])//.pipe(plugins.jscs()) //.pipe(plugins.jshint()) .pipe(plugins.jshint.reporter('jshint-stylish')) .pipe(plugins.jshint.reporter('fail')); }); gulp.task('sass', function () { return gulp.src('./styles/scss/*.scss') .pipe(sass()) .pipe(gulp.dest('./css')); }); /*gulp.task('scripts', function(){ gulp.src('./js/!*.js') .pipe(concat('all.js')) .pipe(gulp.dest('./dist')) .pipe(rename('all.min.js')) .pipe(uglify()) .pipe(gulp.dest('./dist')); });*/ // --------------------------------------------------------------------- // | Main tasks | // --------------------------------------------------------------------- gulp.task('archive', function (done) { runSequence( 'build', 'archive:create_archive_dir', 'archive:zip', done); }); gulp.task('build', function (done) { runSequence( ['clean', 'lint:js'], 'copy', done); }); gulp.task('default', ['archive']); gulp.task('default', function () { gulp.run('archive'); gulp.watch(['./styles/scss/!*.scss'], function () { gulp.run('sass'); }); });
weiyonglei/bigsmallgame
gulpfile.js
JavaScript
mit
5,406
(function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.C = factory(); } }(this, function () { function runAndWaitOn(func) { return function (value) { var handlerRes = func(value); if (handlerRes && typeof handlerRes.then === 'function') { return handlerRes.then(function() { return value; }); } return value; }; } function C (handler, optionalPromise, onFulfilled, onRejected){ var promise = optionalPromise ? optionalPromise.then(wrap(onFulfilled), wrap(onRejected)) : new Promise(handler); var _u = this; function wrap(func){ return typeof func === 'function' ? function() { var res = func.apply(undefined, arguments); if (res === _u) { throw new TypeError('promise resolution value can`t be promise itself') } return res; } : undefined; } function _catch(){ var handler; var constructor; switch (arguments.length) { case 2: constructor = arguments[0]; handler = arguments[1]; break; case 1: handler = arguments[0]; break; default: throw new TypeError('Usage: .catch(constructor, handler) or .catch(handler)'); } return new C(null, promise, null, function (val) { var shouldBeCaught = typeof constructor === 'undefined' || val instanceof constructor; if (shouldBeCaught) { return handler.apply(this, arguments); } throw val; }); } function _finally(func) { return new C(null, promise, runAndWaitOn(func), runAndWaitOn(func)); } function _spread(func) { return new C(null, promise, function (arr) { if (!Array.isArray(arr)) { return func.call(null, arr); } return func.apply(null, arr); }); } function _then(onFulfilled, onRejected) { return new C(null, promise, onFulfilled, onRejected); } function tap(func) { return new C(null, promise, runAndWaitOn(func)); } Object.defineProperties(this, { catch: { value: _catch }, finally: { value: _finally }, spread: { value: _spread }, tap: { value: tap }, then: { value: _then } }); } C.resolve = function resolve(value) { return new C(function (resolve) { resolve(value); }); } C.reject = function reject(value) { return new C(function (resolve, reject) { reject(value); }); } C.all = function all(arr) { return C.resolve(Promise.all(arr)); } return C; }));
codazzo/cranberry
index.js
JavaScript
mit
3,421
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var Task = require('ember-cli/lib/models/task'); var Promise = require('ember-cli/lib/ext/promise'); var RSVP = require('rsvp'); var fs = require('fs-extra'); var path = require('path'); var exec = Promise.denodeify(require('child_process').exec); var remove = Promise.denodeify(fs.remove); var ensureFile = Promise.denodeify(fs.ensureFile); var root = process.cwd(); var tmp = require('tmp-sync'); var tmproot = path.join(root, 'tmp'); var MoveCommandBase = require('../../../lib/commands/move'); describe('move command', function() { var ui; var tasks; var analytics; var project; var fakeSpawn; var CommandUnderTest; var buildTaskCalled; var buildTaskReceivedProject; var tmpdir; before(function() { CommandUnderTest = Command.extend(MoveCommandBase); }); beforeEach(function() { buildTaskCalled = false; ui = new MockUI(); analytics = new MockAnalytics(); tasks = { Build: Task.extend({ run: function() { buildTaskCalled = true; buildTaskReceivedProject = !!this.project; return RSVP.resolve(); } }) }; project = { isEmberCLIProject: function() { return true; } }; }); function setupGit() { return exec('git --version') .then(function(){ return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' }) .then(function(result) { console.log('result',result) return; // return exec('git init'); }) .catch(function(e){ return exec('git init'); }); }); } function generateFile(path) { return ensureFile(path); } function addFileToGit(path) { return ensureFile(path) .then(function() { return exec('git add .'); }); } function addFilesToGit(files) { var filesToAdd = files.map(addFileToGit); return RSVP.all(filesToAdd); } function setupForMove() { return setupTmpDir() // .then(setupGit) .then(addFilesToGit.bind(null,['foo.js','bar.js'])); } function setupTmpDir() { return Promise.resolve() .then(function(){ tmpdir = tmp.in(tmproot); process.chdir(tmpdir); return tmpdir; }); } function cleanupTmpDir() { return Promise.resolve() .then(function(){ process.chdir(root); return remove(tmproot); }); } /* afterEach(function() { process.chdir(root); return remove(tmproot); }); */ /* //TODO: fix so this isn't moving the fixtures it('smoke test', function() { return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); } }).validateAndRun(['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); }); */ it('exits for unversioned file', function() { return setupTmpDir() .then(function(){ fs.writeFileSync('foo.js','foo'); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['nope.js']); } }).validateAndRun(['nope.js']).then(function() { expect(ui.output).to.include('nope.js'); expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); it('can move a file', function() { return setupForMove(). then(function(result) { console.log('result',result); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['foo.js', 'foo-bar.js']); } }).validateAndRun(['foo.js', 'foo-bar.js']).then(function() { expect(ui.output).to.include('foo.js'); // expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); });
trabus/ember-cli-mv
tests/unit/commands/move-nodetest.js
JavaScript
mit
4,872
/*! * Jade - Parser * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var Lexer = require('./lexer') , nodes = require('./nodes'); /** * Initialize `Parser` with the given input `str` and `filename`. * * @param {String} str * @param {String} filename * @param {Object} options * @api public */ var Parser = exports = module.exports = function Parser(str, filename, options){ this.input = str; this.lexer = new Lexer(str, options); this.filename = filename; }; /** * Tags that may not contain tags. */ var textOnly = exports.textOnly = ['code', 'script', 'textarea', 'style', 'title']; /** * Parser prototype. */ Parser.prototype = { /** * Return the next token object. * * @return {Object} * @api private */ advance: function(){ return this.lexer.advance(); }, /** * Skip `n` tokens. * * @param {Number} n * @api private */ skip: function(n){ while (n--) this.advance(); }, /** * Single token lookahead. * * @return {Object} * @api private */ peek: function() { return this.lookahead(1); }, /** * Return lexer lineno. * * @return {Number} * @api private */ line: function() { return this.lexer.lineno; }, /** * `n` token lookahead. * * @param {Number} n * @return {Object} * @api private */ lookahead: function(n){ return this.lexer.lookahead(n); }, /** * Parse input returning a string of js for evaluation. * * @return {String} * @api public */ parse: function(){ var block = new nodes.Block; block.line = this.line(); while ('eos' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else { block.push(this.parseExpr()); } } return block; }, /** * Expect the given type, or throw an exception. * * @param {String} type * @api private */ expect: function(type){ if (this.peek().type === type) { return this.advance(); } else { throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); } }, /** * Accept the given `type`. * * @param {String} type * @api private */ accept: function(type){ if (this.peek().type === type) { return this.advance(); } }, /** * tag * | doctype * | mixin * | include * | filter * | comment * | text * | each * | code * | id * | class */ parseExpr: function(){ switch (this.peek().type) { case 'tag': return this.parseTag(); case 'mixin': return this.parseMixin(); case 'include': return this.parseInclude(); case 'doctype': return this.parseDoctype(); case 'filter': return this.parseFilter(); case 'comment': return this.parseComment(); case 'text': return this.parseText(); case 'each': return this.parseEach(); case 'code': return this.parseCode(); case 'id': case 'class': var tok = this.advance(); this.lexer.defer(this.lexer.tok('tag', 'div')); this.lexer.defer(tok); return this.parseExpr(); default: throw new Error('unexpected token "' + this.peek().type + '"'); } }, /** * Text */ parseText: function(){ var tok = this.expect('text') , node = new nodes.Text(tok.val); node.line = this.line(); return node; }, /** * code */ parseCode: function(){ var tok = this.expect('code') , node = new nodes.Code(tok.val, tok.buffer, tok.escape) , block , i = 1; node.line = this.line(); while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; block = 'indent' == this.lookahead(i).type; if (block) { this.skip(i-1); node.block = this.parseBlock(); } return node; }, /** * comment */ parseComment: function(){ var tok = this.expect('comment') , node; if ('indent' == this.peek().type) { node = new nodes.BlockComment(tok.val, this.parseBlock(), tok.buffer); } else { node = new nodes.Comment(tok.val, tok.buffer); } node.line = this.line(); return node; }, /** * doctype */ parseDoctype: function(){ var tok = this.expect('doctype') , node = new nodes.Doctype(tok.val); node.line = this.line(); return node; }, /** * filter attrs? text-block */ parseFilter: function(){ var block , tok = this.expect('filter') , attrs = this.accept('attrs'); this.lexer.pipeless = true; block = this.parseTextBlock(); this.lexer.pipeless = false; var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); node.line = this.line(); return node; }, /** * tag ':' attrs? block */ parseASTFilter: function(){ var block , tok = this.expect('tag') , attrs = this.accept('attrs'); this.expect(':'); block = this.parseBlock(); var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); node.line = this.line(); return node; }, /** * each block */ parseEach: function(){ var tok = this.expect('each') , node = new nodes.Each(tok.code, tok.val, tok.key, this.parseBlock()); node.line = this.line(); return node; }, /** * include */ parseInclude: function(){ var path = require('path') , fs = require('fs') , dirname = path.dirname , basename = path.basename , join = path.join; if (!this.filename) throw new Error('the "filename" option is required to use includes'); var path = name = this.expect('include').val.trim() , dir = dirname(this.filename); // non-jade if (~basename(path).indexOf('.')) { var path = join(dir, path) , str = fs.readFileSync(path, 'utf8'); return new nodes.Literal(str); } var path = join(dir, path + '.jade') , str = fs.readFileSync(path, 'utf8') , parser = new Parser(str, path) , ast = parser.parse(); return ast; }, /** * mixin block */ parseMixin: function(){ var tok = this.expect('mixin') , name = tok.val , args = tok.args; var block = 'indent' == this.peek().type ? this.parseBlock() : null; return new nodes.Mixin(name, args, block); }, /** * indent (text | newline)* outdent */ parseTextBlock: function(){ var text = new nodes.Text; text.line = this.line(); var spaces = this.expect('indent').val; if (null == this._spaces) this._spaces = spaces; var indent = Array(spaces - this._spaces + 1).join(' '); while ('outdent' != this.peek().type) { switch (this.peek().type) { case 'newline': text.push('\\n'); this.advance(); break; case 'indent': text.push('\\n'); this.parseTextBlock().nodes.forEach(function(node){ text.push(node); }); text.push('\\n'); break; default: text.push(indent + this.advance().val); } } if (spaces == this._spaces) this._spaces = null; this.expect('outdent'); return text; }, /** * indent expr* outdent */ parseBlock: function(){ var block = new nodes.Block; block.line = this.line(); this.expect('indent'); while ('outdent' != this.peek().type) { if ('newline' == this.peek().type) { this.advance(); } else { block.push(this.parseExpr()); } } this.expect('outdent'); return block; }, /** * tag (attrs | class | id)* (text | code | ':')? newline* block? */ parseTag: function(){ // ast-filter look-ahead var i = 2; if ('attrs' == this.lookahead(i).type) ++i; if (':' == this.lookahead(i).type) { if ('indent' == this.lookahead(++i).type) { return this.parseASTFilter(); } } var name = this.advance().val , tag = new nodes.Tag(name); tag.line = this.line(); // (attrs | class | id)* out: while (true) { switch (this.peek().type) { case 'id': case 'class': var tok = this.advance(); tag.setAttribute(tok.type, "'" + tok.val + "'"); continue; case 'attrs': var obj = this.advance().attrs , names = Object.keys(obj); for (var i = 0, len = names.length; i < len; ++i) { var name = names[i] , val = obj[name]; tag.setAttribute(name, val); } continue; default: break out; } } // check immediate '.' if ('.' == this.peek().val) { tag.textOnly = true; this.advance(); } // (text | code | ':')? switch (this.peek().type) { case 'text': tag.text = this.parseText(); break; case 'code': tag.code = this.parseCode(); break; case ':': this.advance(); tag.block = new nodes.Block; tag.block.push(this.parseTag()); break; } // newline* while ('newline' == this.peek().type) this.advance(); tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); // script special-case if ('script' == tag.name) { var type = tag.getAttribute('type'); if (type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { tag.textOnly = false; } } // block? if ('indent' == this.peek().type) { if (tag.textOnly) { this.lexer.pipeless = true; tag.block = this.parseTextBlock(); this.lexer.pipeless = false; } else { var block = this.parseBlock(); if (tag.block) { for (var i = 0, len = block.nodes.length; i < len; ++i) { tag.block.push(block.nodes[i]); } } else { tag.block = block; } } } return tag; } };
cpatni/github-watch-riak-search
node_modules/jade/lib/parser.js
JavaScript
mit
10,190
'use strict'; var IoTServer = require("../iot"); var inquirer = require("inquirer"); var chalk = require('chalk'); inquirer.prompt([{ type: "input", name: "iotBaseURL", message: "Enter the URL to the IoT Server", default: "http://iotserver:7101" }], function(answers) { var iot = new IoTServer(answers.iotBaseURL); iot.setPrincipal('iot', 'welcome1'); console.log(chalk.bold("Initial IoT Version: ") + chalk.cyan(iot.getVersion())); var d = null; iot.checkVersion() .then(function (version) { console.log(chalk.bold("IoT Version: ") + chalk.cyan(version), "[getVersion =", iot.getVersion(), "]"); return iot.createDevice("sharedSecret"); }) .then(function (device) { d = device; console.log(chalk.bold("Device created: ") + chalk.cyan(device.getID())); return device.activate(); }) .then(function (device) { console.log(chalk.bold("Device Activated: ") + chalk.cyan(device.getState())); var data = [{temp: 182}, {temp: 213}, {temp: 16}, {temp: 11}]; return device.sendDataMessages("jsclient:temperature", data); }) .then(function (response) { console.log(chalk.bold("Messages sent. Response: "), response.body); return d.delete(); }) .then(function (gateway) { console.log(chalk.bold("Device deleted.")); }) .catch(function (error) { console.log(chalk.bold.red("*** Error ***")); console.log(error.body || error); if (d) d.delete(); }); });
gravesjohnr/Sigfox-Thinxtra-Oracle-IoT-Bridge
jsclient/tests/testVersion.js
JavaScript
mit
1,645
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define({ "configText": "Ustaw tekst konfiguracyjny:", "generalSettings": { "tabTitle": "Ustawienia ogólne", "measurementUnitLabel": "Jednostka miary", "currencyLabel": "Symbol miary", "roundCostLabel": "Zaokrąglaj koszt", "projectOutputSettings": "Ustawienia wynikowe projektu", "typeOfProjectAreaLabel": "Typ obszaru projektu", "bufferDistanceLabel": "Odległość buforowania", "csvReportExportLabel": "Zezwól użytkownikowi na eksportowanie raportu projektu", "editReportSettingsBtnTooltip": "Edytuj ustawienia raportu", "roundCostValues": { "twoDecimalPoint": "Dwa miejsca po przecinku", "nearestWholeNumber": "Najbliższa liczba całkowita", "nearestTen": "Najbliższa dziesiątka", "nearestHundred": "Najbliższa setka", "nearestThousand": "Najbliższe tysiące", "nearestTenThousands": "Najbliższe dziesiątki tysięcy" }, "reportSettings": { "reportSettingsPopupTitle": "Ustawienia raportu", "reportNameLabel": "Nazwa raportu (opcjonalnie):", "checkboxLabel": "Pokaż", "layerTitle": "Tytuł", "columnLabel": "Etykieta", "duplicateMsg": "Duplikuj etykietę" }, "projectAreaType": { "outline": "Obrys", "buffer": "Bufor" }, "errorMessages": { "currency": "Nieprawidłowa jednostka waluty", "bufferDistance": "Nieprawidłowa odległość buforowania", "outOfRangebufferDistance": "Wartość powinna być większa niż 0 i mniejsza niż lub równa 100" } }, "projectSettings": { "tabTitle": "Ustawienia projektu", "costingGeometrySectionTitle": "Zdefiniuj obszar geograficzny na potrzeby kalkulacji kosztów (opcjonalnie)", "costingGeometrySectionNote": "Uwaga: skonfigurowanie tej warstwy umożliwi użytkownikowi konfigurowanie równań kosztów szablonów obiektów na podstawie obszarów geograficznych.", "projectTableSectionTitle": "Możliwość zapisania/wczytania ustawień projektu (opcjonalnie)", "projectTableSectionNote": "Uwaga: skonfigurowanie wszystkich tabel i warstw umożliwi użytkownikowi zapisanie/wczytanie projektu w celu ponownego wykorzystania.", "costingGeometryLayerLabel": "Warstwa geometrii kalkulacji kosztów", "fieldLabelGeography": "Pole do oznaczenia etykietą obszaru geograficznego", "projectAssetsTableLabel": "Tabela zasobów projektu", "projectMultiplierTableLabel": "Tabela kosztów dodatkowych mnożnika projektu", "projectLayerLabel": "Warstwa projektu", "configureFieldsLabel": "Skonfiguruj pola", "fieldDescriptionHeaderTitle": "Opis pola", "layerFieldsHeaderTitle": "Pole warstwy", "selectLabel": "Zaznacz", "errorMessages": { "duplicateLayerSelection": "Warstwa ${layerName} jest już wybrana", "invalidConfiguration": "Należy wybrać wartość ${fieldsString}" }, "costingGeometryHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć możliwość wykonywania zapytania</li><li>\tWarstwa musi zawierać pole GlobalID</li></p>", "fieldToLabelGeographyHelp": "<p>Pola znakowe i liczbowe wybranej warstwy geometrii kalkulacji kosztów zostaną wyświetlone w menu rozwijanym Pole do oznaczenia etykietą obszaru geograficznego.</p>", "projectAssetsTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać sześć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tAssetGUID (pole typu GUID)</li><li>\tCostEquation (pole typu String)</li><li>\tScenario (pole typu String)</li><li>\tTemplateName (pole typu String)</li><li> GeographyGUID (pole typu GUID)</li><li>\tProjectGUID (pole typu GUID)</li></ul> </p>", "projectMultiplierTableHelp": "<p>Zostaną wyświetlone tabele z następującymi warunkami: <br/> <li>Tabela musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Tabela musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>\tDescription (pole typu String)</li><li>\tType (pole typu String)</li><li>\tValue (pole typu Float/Double)</li><li>\tCostindex (pole typu Integer)</li><li> \tProjectGUID (pole typu GUID))</li></ul> </p>", "projectLayerHelp": "<p>Zostaną wyświetlone warstwy poligonowe z następującymi warunkami: <br/> <li>Warstwa musi mieć możliwości edycji, czyli tworzenia, usuwania i aktualizacji</li> <li>Warstwa musi zawierać pięć pól o dokładnie takich nazwach i typach danych:</li><ul><li>ProjectName (pole typu String)</li><li>Description (pole typu String)</li><li>Totalassetcost (pole typu Float/Double)</li><li>Grossprojectcost (pole typu Float/Double)</li><li>GlobalID (pole typu GlobalID)</li></ul> </p>", "pointLayerCentroidLabel": "Centroid warstwy punktowej", "selectRelatedPointLayerDefaultOption": "Zaznacz", "pointLayerHintText": "<p>Zostaną wyświetlone warstwy punktowe z następującymi warunkami: <br/> <li>\tWarstwa musi mieć pole 'Projectid' (typ GUID)</li><li>\tWarstwa musi mieć możliwość edycji, a więc atrybut 'Tworzenie', 'Usuwanie' i 'Aktualizacja'</li></p>" }, "layerSettings": { "tabTitle": "Ustawienia warstwy", "layerNameHeaderTitle": "Nazwa warstwy", "layerNameHeaderTooltip": "Lista warstw na mapie", "EditableLayerHeaderTitle": "Edytowalne", "EditableLayerHeaderTooltip": "Dołącz warstwę i jej szablony w widżecie kalkulacji kosztów", "SelectableLayerHeaderTitle": "Podlegające selekcji", "SelectableLayerHeaderTooltip": "Geometria z obiektu może zostać użyta do wygenerowania nowego elementu kosztu", "fieldPickerHeaderTitle": "ID projektu (opcjonalnie)", "fieldPickerHeaderTooltip": "Pole opcjonalne (typu znakowego), w którym będzie przechowywany identyfikator projektu", "selectLabel": "Zaznacz", "noAssetLayersAvailable": "Nie znaleziono warstwy zasobów na wybranej mapie internetowej", "disableEditableCheckboxTooltip": "Ta warstwa nie ma możliwości edycji", "missingCapabilitiesMsg": "Dla tej warstwy brak następujących funkcji:", "missingGlobalIdMsg": "Ta warstwa nie ma pola GlobalId", "create": "Tworzenie", "update": "Aktualizuj", "deleteColumnLabel": "Usuń", "attributeSettingHeaderTitle": "Ustawienia atrybutów", "addFieldLabelTitle": "Dodaj atrybuty", "layerAttributesHeaderTitle": "Atrybuty warstwy", "projectLayerAttributesHeaderTitle": "Atrybuty warstwy projektu", "attributeSettingsPopupTitle": "Ustawienia atrybutów warstwy" }, "costingInfo": { "tabTitle": "Informacje o kalkulacji kosztów", "proposedMainsLabel": "Proponowane elementy główne", "addCostingTemplateLabel": "Dodaj szablon kalkulacji kosztów", "manageScenariosTitle": "Zarządzaj scenariuszami", "featureTemplateTitle": "Szablon obiektu", "costEquationTitle": "Równanie kosztów", "geographyTitle": "Obszar geograficzny", "scenarioTitle": "Scenariusz", "actionTitle": "Działania", "scenarioNameLabel": "Nazwa scenariusza", "addBtnLabel": "Dodaj", "srNoLabel": "Nie.", "deleteLabel": "Usuwanie", "duplicateScenarioName": "Duplikuj nazwę scenariusza", "hintText": "<div>Wskazówka: użyj następujących słów kluczowych</div><ul><li><b>{TOTALCOUNT}</b>: używa łącznej liczby zasobów tego samego typu w obszarze geograficznym</li><li><b>{MEASURE}</b>: używa długości dla zasobu liniowego i pola powierzchni dla zasobu poligonowego</li><li><b>{TOTALMEASURE}</b>: używa łącznej długości dla zasobu liniowego i łącznego pola powierzchni dla zasobu poligonowego tego samego typu w obszarze geograficznym</li></ul> Możesz użyć funkcji, takich jak:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Należy zmodyfikować równanie kosztów zgodnie z wymaganiami projektu.", "noneValue": "Brak", "requiredCostEquation": "Niepoprawne równanie kosztów dla warstwy ${layerName} : ${templateName}", "duplicateTemplateMessage": "Istnieje podwójny wpis szablonu dla warstwy ${layerName} : ${templateName}", "defaultEquationRequired": "Wymagane jest domyślne równanie dla warstwy ${layerName} : ${templateName}", "validCostEquationMessage": "Wprowadź prawidłowe równanie kosztów", "costEquationHelpText": "Edytuj równanie kosztów zgodnie z wymaganiami projektu", "scenarioHelpText": "Wybierz scenariusz zgodnie z wymaganiami projektu", "copyRowTitle": "Kopiuj wiersz", "noTemplateAvailable": "Dodaj co najmniej jeden szablon dla warstwy ${layerName}", "manageScenarioLabel": "Zarządzaj scenariuszem", "noLayerMessage": "Wprowadź co najmniej jedną warstwę w ${tabName}", "noEditableLayersAvailable": "Warstwy, które należy oznaczyć jako możliwe do edycji na karcie ustawień warstwy", "updateProjectCostCheckboxLabel": "Aktualizuj równania projektu", "updateProjectCostEquationHint": "Wskazówka: Umożliwia użytkownikowi aktualizowanie równań kosztów zasobów, które zostały już dodane do istniejących projektów, za pomocą nowych równań zdefiniowanych niżej na podstawie szablonu obiektu, geografii i scenariusza. Jeśli brak określonej kombinacji, zostanie przyjęty koszt domyślny, tzn. geografia i scenariusz ma wartość 'None' (brak). W przypadku usunięcia szablonu obiektu ustawiony zostanie koszt równy 0." }, "statisticsSettings": { "tabTitle": "Dodatkowe ustawienia", "addStatisticsLabel": "Dodaj statystykę", "fieldNameTitle": "Pole", "statisticsTitle": "Etykieta", "addNewStatisticsText": "Dodaj nową statystykę", "deleteStatisticsText": "Usuń statystykę", "moveStatisticsUpText": "Przesuń statystykę w górę", "moveStatisticsDownText": "Przesuń statystykę w dół", "selectDeselectAllTitle": "Zaznacz wszystkie" }, "projectCostSettings": { "addProjectCostLabel": "Dodaj koszt dodatkowy projektu", "additionalCostValueColumnHeader": "Wartość", "invalidProjectCostMessage": "Nieprawidłowa wartość kosztu projektu", "additionalCostLabelColumnHeader": "Etykieta", "additionalCostTypeColumnHeader": "Typ" }, "statisticsType": { "countLabel": "Liczba", "averageLabel": "Średnia", "maxLabel": "Maksimum", "minLabel": "Minimum", "summationLabel": "Zsumowanie", "areaLabel": "Pole powierzchni", "lengthLabel": "Długość" } });
tmcgee/cmv-wab-widgets
wab/2.14/widgets/CostAnalysis/setting/nls/pl/strings.js
JavaScript
mit
11,272
/* eslint-disable class-methods-use-this */ import Relay from 'react-relay'; class DeletePermissionMutation extends Relay.Mutation { getMutation() { return Relay.QL` mutation { deletePermission(input: $input) } `; } getVariables() { return { projectId: this.props.project.id, userId: this.props.userId, }; } getFatQuery() { return Relay.QL` fragment on DeletePermissionPayload { deletedPermissionId viewer { id project(name: "${this.props.project.name}") { users(first: 10) { edges { node { id fullname } } } } allUsers { id fullname } } } `; } getConfigs() { return [{ type: 'NODE_DELETE', parentName: 'viewer', parentID: this.props.viewer.id, connectionName: 'users', deletedIDFieldName: 'deletedPermissionId', }]; } } export default DeletePermissionMutation;
NikaBuligini/whistleblower-server
app/react/mutations/DeletePermissionMutation.js
JavaScript
mit
1,108
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Exame = mongoose.model('Exame'), _ = require('lodash'); /** * Create a Exame */ exports.create = function(req, res) { var exame = new Exame(req.body); exame.user = req.user; exame.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(exame); } }); }; exports.addPergunta= function(exameId,perguntaId){ Exame.findById(exameId).exec(function(err,exame){ if(err){ console.log('erro finding exam first'); return; } else{ if(!exame){ // console.log('exam not found'+exameId); return; } var exame1=exame.toObject(); exame1._perguntas.push(perguntaId); exame = _.extend(exame , exame1); exame.save(function(err) { if (err) { //console.log('erro ao salvar'); return; } else { //console.log('sucesso'); } }); } }); }; exports.listar = function(req, res) { Exame.find().select('id ano').exec(function (err,exames) { // body... if(err){ return res.status(400).send({message:errorHandler.getErrorMessage(err)}); } else{ res.jsonp(exames); } }); }; /** * Show the current Exame */ exports.read = function(req, res) { Exame.findById(req.params.exameId).populate({path:'_perguntas',model:'Pergunta'}).populate('disciplina').exec(function(err,exame){ if(err){ return res.status(400).send({message:errorHandler.getErrorMessage(err)}); } else{ if(!exame){ return res.status(404).send({message:'Exame nao encontrado'}); } Exame.populate(exame._perguntas,{ path:'_ajuda', model:'Ajuda'}, function(err,docs){ if(err){ return res.status(400).send({message:errorHandler.getErrorMessage(err)}); } exame._ajuda=docs; }); Exame.populate(exame._perguntas,{ path:'_alternativas', model:'Alternativa'}, function(err,docs){ if(err){ return res.status(400).send({message:errorHandler.getErrorMessage(err)}); } // console.log(docs.toObject()); // exame._perguntas=docs; res.jsonp(exame); //exame=docs; }); //res.jsonp(exame); } }); }; /** * Exame middleware */ // exports.exameByID = function(req, res, next, id) { // Exame.findById(id).populate('_perguntas').exec(function(err, exame) { // //Exame.findById(id).deepPopulate('_perguntas.alternativas').exec(function(err, exame) { // if (err) return next(err); // if (! exame) return next(new Error('Failed to load Exame ' + id)); // req.exame = exame ; // next(); // }); // }; /** * Update a Exame */ exports.update = function(req, res) { var exame = req.exame ; exame = _.extend(exame , req.body); exame.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(exame); } }); }; /** * Delete an Exame */ exports.delete = function(req, res) { var exame = req.exame ; exame.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(exame); } }); }; /** * List of Exames */ exports.list = function(req, res) { Exame.find().select('id ano disciplina').populate('disciplina','name').sort({ano:-1}).exec(function(err, exames) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(exames); } }); }; /** * Exame authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.exame.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
osvaldoM/Teste
app/controllers/exames.server.controller.js
JavaScript
mit
3,775
goog.module('test_files.use_closure_externs.use_closure_externs');var module = module || {id: 'test_files/use_closure_externs/use_closure_externs.js'};/** * @fileoverview A source file that uses types that are used in .d.ts files, but * that are not available or use different names in Closure's externs. * @suppress {checkTypes} checked by tsc */ console.log('work around TS dropping consecutive comments'); let /** @type {!NodeListOf<!HTMLParagraphElement>} */ x = document.getElementsByTagName('p'); console.log(x); const /** @type {(null|!RegExpExecArray)} */ res = ((/asd/.exec('asd asd'))); console.log(res);
lucidsoftware/tsickle
test_files/use_closure_externs/use_closure_externs.js
JavaScript
mit
619
/** * Created with JetBrains WebStorm. * User: yujilong * Date: 14-2-11 * Time: 上午11:08 * To change this template use File | Settings | File Templates. */ define(['jquery', 'util', 'post/PostContent'], function ($, util, PostContent) { var Post = function (_id, categoryId, boardId, title, createTime, taobaoUrl, lastUpdateTime , fontCoverPic , status, price) { this._id = _id; this.categoryId = categoryId; this.boardId = boardId; this.title = title; this.createTime = createTime; this.taobaoUrl = taobaoUrl; this.lastUpdateTime = lastUpdateTime; this.postContents = []; this.fontCoverPic = fontCoverPic; this.status = status; this.price = price; }; Post.prototype = { createContent: function (_id) { var content = new PostContent(_id); this.postContents.push(content); return content; }, createContentKey: function (fn) { util.sendAjax('/burning/cms/createPostContentKey', { }, 'json', fn, 'post'); }, save : function(){ var title = $('#createBox').find('input[name="postTitle"]').val(); var url = encodeURI($('#createBox').find('input[name="taobaoUrl"]').val()); this.title = title; this.taobaoUrl = url; }, pullContents : function(_id){ var tThis = this; for(var i = 0, len = this.postContents.length; i < len ; i++){ var content = this.postContents[i]; if(content._id.trim() === _id.trim()){ (function(index){ var tmp = tThis.postContents.splice(index,1); })(i); break; } } }, updateContent : function(_id,info,type,sort){ var content = this.findContent(_id); content.info = info; content.type = type; }, findContent : function (_id){ for(var i = 0, len = this.postContents.length; i < len ; i++){ if(this.postContents[i]._id === _id){ return this.postContents[i]; } } }, submit:function(){ this.initVals(); var tThis = this; var obj = this.validatePost(); if(obj.flag){ (function(){ util.sendAjax('/burning/cms/createPost',{ post : { categoryId : tThis.categoryId, boardId : tThis.boardId, title : tThis.title, taobaoUrl : tThis.taobaoUrl, postContents : tThis.postContents, status : tThis.status, price : tThis.price } }, 'json', function(data){ if(data.rs == 1){ location.reload(true); } else { alert('error'); } }, 'post'); })(); }else{ return obj; } }, initVals : function(){ this.title = $('#createBox').find('input[name="postTitle"]').val(); this.taobaoUrl = encodeURI($('#createBox').find('input[name="taobaoUrl"]').val()); this.status = $('#createBox').find('select[name="status"]').val(); this.price = $('#createBox').find('input[name="price"]').val(); for(var i = 0 , len = this.postContents.length; i<len; i++){ if(this.postContents[i].type == 1){ this.initTextContent(this.postContents[i]); } } }, initTextContent : function(content){ var text = $('#' + content._id).find('textarea').val(); content.info.text = text; }, initDefaultText : function(content){ content.type = 1; content.info = { text:'' }; }, validatePost : function(){ var error_msg = ''; var tThis = this; if(!/^[0-9]+(.[0-9]+)?$/.test(tThis.price)){ error_msg = '请输入正确的数字,如12.30或12!'; return { flag : false, error : error_msg }; } if(this.postContents.length === 0){ error_msg = '请添加图片或文章内容'; return { flag : false, error : error_msg }; } if(!/^http:\/\//.test(tThis.taobaoUrl)){ return { flag: false, error : '请输入正确的URL,如:http://www.baidu.com' } } if(!this.title){ error_msg = '请填写标题'; return { flag : false, error : error_msg }; } for(var i = 0, len = this.postContents.length; i < len ; i ++) { var content = this.postContents[i]; if(content.type == 1 && !content.info.text){ return { flag : false, error : '有部分段落未填写数据' }; }else if(content.type != 1 && !content.info){ return { flag : false, error : '有部分图片尚未上传' } } } return { flag : true }; }, delByPostId : function(fn){ var tThis = this; util.sendAjax('/burning/cms/delPostById', { _id : tThis._id }, 'json', fn, 'delete'); }, getPostById : function(fn){ var tThis = this; util.sendAjax('/burning/cms/getPostById',{ _id : tThis._id },'json',fn,'get'); }, updatePostById : function(fn){ var tThis = this; util.sendAjax('/burning/cms/updatePostById',{ _id: tThis._id, taobaoUrl : tThis.taobaoUrl, price : tThis.price, title : tThis.title },'json',fn,'put'); }, updatePostStatus : function(fn){ var tThis = this; util.sendAjax('/burning/cms/updatePostStatus',{ _id:tThis._id, status : tThis.status },'json',fn,'put'); }, multUpdatePostStatus : function(ids,status,fn){ console.log(ids); var tThis = this; util.sendAjax('/burning/cms/multUpdatePostStatus',{ ids:ids, status : status },'json',fn,'put'); }, multdelPostStatus : function(ids,fn){ console.log(ids); var tThis = this; util.sendAjax('/burning/cms/multDelPost',{ ids:ids },'json',fn,'delete'); } }; return Post; });
skyujilong/burning
public/javascripts/post/Post.js
JavaScript
mit
7,492
'use strict' module.exports = (gulp) => { require('./build/node')(gulp) require('./build/browser')(gulp) require('./clean')(gulp) gulp.task('build', ['build:browser']) }
dryajov/aegir
tasks/build.js
JavaScript
mit
180
import React from 'react' import PropTypes from 'prop-types' import A from 'components/A' const Arasaac = ({ link }) => link ? ( <A href={'http://www.arasaac.org'} target='_blank' alt='Arasaac'> ARASAAC (http://www.arasaac.org) </A> ) : ( <A href={'http://www.arasaac.org'} target='_blank' alt='Arasaac'> ARASAAC </A> ) Arasaac.propTypes = { link: PropTypes.bool } export default Arasaac
juanda99/arasaac-frontend
app/components/License/Arasaac.js
JavaScript
mit
427
/** * Simple wrapper for lang.hitch to make it into an easy function */ define(['dojo/_base/lang'], function (lang) { var l = { _mixin: function(dest, source, copyFunc){ // summary: // Copies/adds all properties of source to dest; returns dest. // dest: Object // The object to which to copy/add all properties contained in source. // source: Object // The object from which to draw all properties to copy into dest. // copyFunc: Function? // The process used to copy/add a property in source; defaults to the Javascript assignment operator. // returns: // dest, as modified // description: // All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions // found in Object.prototype, are copied/added to dest. Copying/adding each particular property is // delegated to copyFunc (if any); copyFunc defaults to the Javascript assignment operator if not provided. // Notice that by default, _mixin executes a so-called "shallow copy" and aggregate types are copied/added by reference. var name, s, i, empty = {}; for(name in source){ // the (!(name in empty) || empty[name] !== s) condition avoids copying properties in "source" // inherited from Object.prototype. For example, if dest has a custom toString() method, // don't overwrite it with the toString() method that source inherited from Object.prototype s = source[name]; if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){ dest[name] = copyFunc ? copyFunc(s) : s; } } // if(has("bug-for-in-skips-shadowed")){ // if(source){ // for(i = 0; i < _extraLen; ++i){ // name = _extraNames[i]; // s = source[name]; // if(!(name in dest) || (dest[name] !== s && (!(name in empty) || empty[name] !== s))){ // dest[name] = copyFunc ? copyFunc(s) : s; // } // } // } // } return dest; // Object }, mixin: function(dest, sources){ // summary: // Copies/adds all properties of one or more sources to dest; returns dest. // dest: Object // The object to which to copy/add all properties contained in source. If dest is falsy, then // a new object is manufactured before copying/adding properties begins. // sources: Object... // One of more objects from which to draw all properties to copy into dest. sources are processed // left-to-right and if more than one of these objects contain the same property name, the right-most // value "wins". // returns: Object // dest, as modified // description: // All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions // found in Object.prototype, are copied/added from sources to dest. sources are processed left to right. // The Javascript assignment operator is used to copy/add each property; therefore, by default, mixin // executes a so-called "shallow copy" and aggregate types are copied/added by reference. // example: // make a shallow copy of an object // | var copy = lang.mixin({}, source); // example: // many class constructors often take an object which specifies // values to be configured on the object. In this case, it is // often simplest to call `lang.mixin` on the `this` object: // | declare("acme.Base", null, { // | constructor: function(properties){ // | // property configuration: // | lang.mixin(this, properties); // | // | console.log(this.quip); // | // ... // | }, // | quip: "I wasn't born yesterday, you know - I've seen movies.", // | // ... // | }); // | // | // create an instance of the class and configure it // | var b = new acme.Base({quip: "That's what it does!" }); // example: // copy in properties from multiple objects // | var flattened = lang.mixin( // | { // | name: "Frylock", // | braces: true // | }, // | { // | name: "Carl Brutanananadilewski" // | } // | ); // | // | // will print "Carl Brutanananadilewski" // | console.log(flattened.name); // | // will print "true" // | console.log(flattened.braces); if(!dest){ dest = {}; } for(var i = 1, l = arguments.length; i < l; i++){ this._mixin(dest, arguments[i]); } return dest; // Object } } return lang.hitch(l, function () { var arr = {}, args = Array.prototype.slice.call(arguments, 0); args.unshift(arr); this.mixin.apply(this, args); return arr; }); });
liquidg3/altair
core/lib/altair/facades/mixin.js
JavaScript
mit
5,576
$(function () { 'use strict'; QUnit.module('popover plugin') QUnit.test('should be defined on jquery object', function (assert) { assert.expect(1) assert.ok($(document.body).popover, 'popover method is defined') }) QUnit.module('popover', { beforeEach: function () { // Run all tests in noConflict mode -- it's the only way to ensure that the plugin works in noConflict mode $.fn.bootstrapPopover = $.fn.popover.noConflict() }, afterEach: function () { $.fn.popover = $.fn.bootstrapPopover delete $.fn.bootstrapPopover } }) QUnit.test('should provide no conflict', function (assert) { assert.expect(1) assert.strictEqual($.fn.popover, undefined, 'popover was set back to undefined (org value)') }) QUnit.test('should return jquery collection containing the element', function (assert) { assert.expect(2) var $el = $('<div/>') var $popover = $el.bootstrapPopover() assert.ok($popover instanceof $, 'returns jquery collection') assert.strictEqual($popover[0], $el[0], 'collection contains element') }) QUnit.test('should render popover element', function (assert) { assert.expect(2) var $popover = $('<a href="#" title="mdo" data-content="https://twitter.com/mdo">@mdo</a>') .appendTo('#qunit-fixture') .bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover removed') }) QUnit.test('should store popover instance in popover data object', function (assert) { assert.expect(1) var $popover = $('<a href="#" title="mdo" data-content="https://twitter.com/mdo">@mdo</a>').bootstrapPopover() assert.ok($popover.data('bs.popover'), 'popover instance exists') }) QUnit.test('should store popover trigger in popover instance data object', function (assert) { assert.expect(1) var $popover = $('<a href="#" title="ResentedHook">@ResentedHook</a>') .appendTo('#qunit-fixture') .bootstrapPopover() $popover.bootstrapPopover('show') assert.ok($('.popover').data('bs.popover'), 'popover trigger stored in instance data') }) QUnit.test('should get title and content from options', function (assert) { assert.expect(4) var $popover = $('<a href="#">@fat</a>') .appendTo('#qunit-fixture') .bootstrapPopover({ title: function () { return '@fat' }, content: function () { return 'loves writing tests (╯°□°)╯︵ ┻━┻' } }) $popover.bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.strictEqual($('.popover .popover-title').text(), '@fat', 'title correctly inserted') assert.strictEqual($('.popover .popover-content').text(), 'loves writing tests (╯°□°)╯︵ ┻━┻', 'content correctly inserted') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover was removed') }) QUnit.test('should not duplicate HTML object', function (assert) { assert.expect(6) var $div = $('<div/>').html('loves writing tests (╯°□°)╯︵ ┻━┻') var $popover = $('<a href="#">@fat</a>') .appendTo('#qunit-fixture') .bootstrapPopover({ content: function () { return $div } }) $popover.bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.equal($('.popover .popover-content').html(), $div, 'content correctly inserted') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover was removed') $popover.bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.equal($('.popover .popover-content').html(), $div, 'content correctly inserted') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover was removed') }) QUnit.test('should get title and content from attributes', function (assert) { assert.expect(4) var $popover = $('<a href="#" title="@mdo" data-content="loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻" >@mdo</a>') .appendTo('#qunit-fixture') .bootstrapPopover() .bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.strictEqual($('.popover .popover-title').text(), '@mdo', 'title correctly inserted') assert.strictEqual($('.popover .popover-content').text(), 'loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻', 'content correctly inserted') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover was removed') }) QUnit.test('should get title and content from attributes ignoring options passed via js', function (assert) { assert.expect(4) var $popover = $('<a href="#" title="@mdo" data-content="loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻" >@mdo</a>') .appendTo('#qunit-fixture') .bootstrapPopover({ title: 'ignored title option', content: 'ignored content option' }) .bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.strictEqual($('.popover .popover-title').text(), '@mdo', 'title correctly inserted') assert.strictEqual($('.popover .popover-content').text(), 'loves data attributes (づ。◕‿‿◕。)づ ︵ ┻━┻', 'content correctly inserted') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover was removed') }) QUnit.test('should respect custom template', function (assert) { assert.expect(3) var $popover = $('<a href="#">@fat</a>') .appendTo('#qunit-fixture') .bootstrapPopover({ title: 'Test', content: 'Test', template: '<div class="popover foobar"><div class="arrow"></div><div class="inner"><h3 class="title"/><div class="content"><p/></div></div></div>' }) $popover.bootstrapPopover('show') assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.ok($('.popover').hasClass('foobar'), 'custom class is present') $popover.bootstrapPopover('hide') assert.strictEqual($('.popover').length, 0, 'popover was removed') }) QUnit.test('should destroy popover', function (assert) { assert.expect(7) var $popover = $('<div/>') .bootstrapPopover({ trigger: 'hover' }) .on('click.foo', $.noop) assert.ok($popover.data('bs.popover'), 'popover has data') assert.ok($._data($popover[0], 'events').mouseover && $._data($popover[0], 'events').mouseout, 'popover has hover event') assert.strictEqual($._data($popover[0], 'events').click[0].namespace, 'foo', 'popover has extra click.foo event') $popover.bootstrapPopover('show') $popover.bootstrapPopover('destroy') assert.ok(!$popover.hasClass('in'), 'popover is hidden') assert.ok(!$popover.data('popover'), 'popover does not have data') assert.strictEqual($._data($popover[0], 'events').click[0].namespace, 'foo', 'popover still has click.foo') assert.ok(!$._data($popover[0], 'events').mouseover && !$._data($popover[0], 'events').mouseout, 'popover does not have any events') }) QUnit.test('should render popover element using delegated selector', function (assert) { assert.expect(2) var $div = $('<div><a href="#" title="mdo" data-content="https://twitter.com/mdo">@mdo</a></div>') .appendTo('#qunit-fixture') .bootstrapPopover({ selector: 'a', trigger: 'click' }) $div.find('a').trigger('click') assert.notEqual($('.popover').length, 0, 'popover was inserted') $div.find('a').trigger('click') assert.strictEqual($('.popover').length, 0, 'popover was removed') }) QUnit.test('should detach popover content rather than removing it so that event handlers are left intact', function (assert) { assert.expect(1) var $content = $('<div class="content-with-handler"><a class="btn btn-warning">Button with event handler</a></div>').appendTo('#qunit-fixture') var handlerCalled = false $('.content-with-handler .btn').on('click', function () { handlerCalled = true }) var $div = $('<div><a href="#">Show popover</a></div>') .appendTo('#qunit-fixture') .bootstrapPopover({ html: true, trigger: 'manual', container: 'body', content: function () { return $content } }) var done = assert.async() $div .one('shown.bs.popover', function () { $div .one('hidden.bs.popover', function () { $div .one('shown.bs.popover', function () { $('.content-with-handler .btn').trigger('click') $div.bootstrapPopover('destroy') assert.ok(handlerCalled, 'content\'s event handler still present') done() }) .bootstrapPopover('show') }) .bootstrapPopover('hide') }) .bootstrapPopover('show') }) QUnit.test('should throw an error when initializing popover on the document object without specifying a delegation selector', function (assert) { assert.expect(1) assert.throws(function () { $(document).bootstrapPopover({title: 'What am I on?', content: 'My selector is missing'}) }, new Error('`selector` option must be specified when initializing popover on the window.document object!')) }) QUnit.test('should do nothing when an attempt is made to hide an uninitialized popover', function (assert) { assert.expect(1) var $popover = $('<span data-toggle="popover" data-title="some title" data-content="some content">some text</span>') .appendTo('#qunit-fixture') .on('hidden.bs.popover shown.bs.popover', function () { assert.ok(false, 'should not fire any popover events') }) .bootstrapPopover('hide') assert.strictEqual($popover.data('bs.popover'), undefined, 'should not initialize the popover') }) QUnit.test('should throw an error when template contains multiple top-level elements', function (assert) { assert.expect(1) assert.throws(function () { $('<span data-toggle="popover" data-title="some title" data-content="some content">some text</span>') .appendTo('#qunit-fixture') .bootstrapPopover({template: '<div>Foo</div><div>Bar</div>'}) .bootstrapPopover('show') }, new Error('popover `template` option must consist of exactly 1 top-level element!')) }) QUnit.test('should fire inserted event', function (assert) { assert.expect(2) var done = assert.async() $('<a href="#">@Johann-S</a>') .appendTo('#qunit-fixture') .on('inserted.bs.popover', function () { assert.notEqual($('.popover').length, 0, 'popover was inserted') assert.ok(true, 'inserted event fired') done() }) .bootstrapPopover({ title: 'Test', content: 'Test' }) .bootstrapPopover('show') }) })
zolfer/bootstrap
js/tests/unit/popover.js
JavaScript
mit
12,861
import internalQuerySelector from '../src/query-selector'; import { querySelector } from '../src'; describe('exports', () => { it('exports `querySelector`', () => { expect(querySelector).toEqual(internalQuerySelector); }); });
demiazz/lighty-plugin-legacy
spec/index.spec.js
JavaScript
mit
237
'use strict'; module.exports = class Account { constructor(name, password, email) { var load = typeof name === 'object'; this._username = load ? name._username : name; this._password = load ? name._password : password; this._email = load ? name._email : email; this._userType = load ? name._userType : 1; // 1 is a basic user, 2 is an admin this._userGames = load ? name._userGames : []; this._numWin = load ? name._numWin : 0; this._numLoss = load ? name._numLoss : 0; this._overallRatio = load ? name._overallRatio : 0; this._userSkillLevel = load ? name._userSkillLevel : 0; } get username() { return this._username; } set username(username) { this._username = username; } get password() { return this._password; } set password(password) { this._password = password; } get email() { return this._email; } set email(email) { this._email = email; } get userType() { return this._userType; } set userType(type) { this._userType = type; } get userGames() { return this._userGames; } get userWins() { return this._numWin; } get userLoss() { return this._numLoss; } updateFromPlayer(player) { if (player.result === 1) { this._numWin++; } else { this._numLoss++; } this._overallRatio = (this._numWin / this._numLoss).toFixed(2); this._userSkillLevel = player.skill; // We would also add the game ID to the games array, but we aren't saving games atm } get overallRatio() { return this._overallRatio; } get userSkillLevel() { return this._userSkillLevel; } /** * Updates user best game by looking for the game the user * scored the highest skill in. */ calculateBestGame() { var Skill=0; this._userSkillLevel=0; for(var i= 0; i< this._userGames.length; i++) { this._userSkillLevel += this._userGames[i].gameSkill; if(this._userGames[i].gameResult == 0) i++; else if(Skill < this._userGames[i].gameSkill){ Skill= this._userGames[i].gameSkill; this._userBestGame= i; } } } };
SENG-299-Group-6-Summer16/Go-WebApp
model/Account.js
JavaScript
mit
2,225
"use strict"; var _ = require('lodash'); _.mixin({ pickObjectParams: function (data, params) { params = Array.prototype.slice.call(arguments, 1); return _.map(data, function (item) { return _.pick.apply(_, [item].concat(params)); }); }, omitObjectParams: function (datam, params) { params = Array.prototype.slice.call(arguments, 1); return _.map(data, function (item) { return _.omit.apply(_, [item].concat(params)); }); }, stripHtml: function (str) { return str.replace(/<(?:.|\n)*?>/gm, ''); }, timeAgoDate: function (time) { var date = new Date(time), diff = (((new Date()).getTime() - date.getTime()) / 1000), day_diff = Math.floor(diff / 86400); if (isNaN(day_diff) || day_diff < 0) return; return day_diff == 0 && ( diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago" || day_diff < 365 && Math.ceil(day_diff / 30) + " mounts ago" || day_diff > 365 && Math.floor(day_diff / 365) + " years ago"; }, getImageFromContent: function (str) { var image = str.match(/<img.+?src=["'](.+?)["'].+?>/) return image ? image[1] : ""; }, addhttp: function (url) { if (!/^(f|ht)tps?:\/\//i.test(url)) { url = "http://" + url; } return url; }, truncate: function(str, length, truncateStr){ if (str == null) return ''; str = String(str); truncateStr = truncateStr || '...'; length = ~~length; return str.length > length ? str.slice(0, length) + truncateStr : str; }, getFunctionArgs:function(func){ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, text = func.toString(), args = text.match(FN_ARGS)[1].replace(/ /g,'').split(','); _.remove(args,function(arg){ return (arg == "" || arg == undefined || arg == null) }); return args; }, deepExtend: function (obj) { //https://gist.github.com/kurtmilam/1868955 var parentRE = /#{\s*?_\s*?}/, slice = Array.prototype.slice, hasOwnProperty = Object.prototype.hasOwnProperty; _.each(slice.call(arguments, 1), function(source) { for (var prop in source) { if (hasOwnProperty.call(source, prop)) { if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop]) || _.isDate(source[prop])) { obj[prop] = source[prop]; } else if (_.isString(source[prop]) && parentRE.test(source[prop])) { if (_.isString(obj[prop])) { obj[prop] = source[prop].replace(parentRE, obj[prop]); } } else if (_.isArray(obj[prop]) || _.isArray(source[prop])){ if (!_.isArray(obj[prop]) || !_.isArray(source[prop])){ throw 'Error: Trying to combine an array with a non-array (' + prop + ')'; } else { obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function (item) { return _.isNull(item);}); } } else if (_.isObject(obj[prop]) || _.isObject(source[prop])){ if (!_.isObject(obj[prop]) || !_.isObject(source[prop])){ throw 'Error: Trying to combine an object with a non-object (' + prop + ')'; } else { obj[prop] = _.deepExtend(obj[prop], source[prop]); } } else { obj[prop] = source[prop]; } } } }); return obj; } }); if (!String.prototype.format) { String.prototype.format = function () { var args = arguments; return this.replace(/{(\d+)}/g, function (match, number) { return typeof args[number] != 'undefined' ? args[number] : match ; }); }; }
umair-gujjar/appolo
lib/util/util.js
JavaScript
mit
4,651
/** * @namespace * @description All general ABC methods and functionality should be placed within this namespace. * @version 0.0.5 Jul 2014 * @author ABC Innovation * */ var ABC = function() { var includeLocations = []; var onLoadFunctions = [getSubMenus, clearSearchField]; var lastNav = null; var navTimer = null; loadIncludes(includeLocations); loadEvents(onLoadFunctions); /** * Iterate through an array of functions and call them onLoad * * @param {array} functionArray All functions to be called on load */ function loadEvents(functionArray) { for (var i=0;i < functionArray.length;i++) { addLoadEvent(functionArray[i]); } } /** * Run a specified function on load * * @param {function} func Function to be called */ function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); }; } } /** * Iterate through an array of file locations and write out an HTML script * tag for each one. * * @param {array} includeArray Array of file locations */ function loadIncludes(includeArray) { for (var i=0;i < includeArray.length;i++) { document.write('<scr' + 'ipt type="text/javascript" src="' + includeArray[i] + '"></scr' + 'ipt>'); } } /** * GLOBAL NAVIGATION SPECIFIC FUNCTIONS */ /** * Perform a HTTP request to retrieve the submenu html for the global nav * and attach it to the appropriate element. * * @return void */ function getSubMenus() { // need to check active stylesheet! // don't get sub menus if handheld or iphone css var xmlhttp; var baseURL = 'http://' + location.host; var subMenus = baseURL + '/res/abc/submenus.htm'; // find width of nav var navX = document.getElementById("abcNavWrapper"); var navWidth; // quit if navX is null or undefined if (navX == null) { return; } if (navX.currentStyle) { navWidth = parseInt(navX.currentStyle["width"]); //alert('currentStyle: width=' + navWidth); } else if (window.getComputedStyle) { navWidth = parseInt(document.defaultView.getComputedStyle(navX,null).getPropertyValue("width")); //alert('getComputedStyle: width=' + navWidth); } // could use instead: //var navWidth = document.getElementById("abcNavWrapper").offsetWidth; // download submenus for full-size screens if (navWidth >= 940) { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE5, IE6 } else { //alert("Your browser does not support XMLHTTP!"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && (xmlhttp.status == 200 || xmlhttp.status == 304)) { document.getElementById('abcNavMenu').innerHTML = xmlhttp.responseText; // after loading submenus addNavEvents(); addLinkTracking(); } }; xmlhttp.open("GET",subMenus,true); xmlhttp.send(null); } } /** * Adds onmouseover and onmouseout events to top-level navs * * @return void */ function addNavEvents() { var topNavs = document.getElementById('abcNavMenu').childNodes; for (var nodeN in topNavs) { if (topNavs[nodeN].nodeType == 1) { topNavs[nodeN].onmouseover = function() { showSubMenu(this); }; topNavs[nodeN].onmouseout = function() { hideSubMenu(this); }; } } } /** * show submenus of a top-level nav * * @return void */ function showSubMenu(obj) { // show submenu if it exists if (obj && obj.firstChild && obj.firstChild.nextSibling) { if (obj.firstChild.nextSibling.nodeType == 1) { obj.firstChild.nextSibling.style.display = 'block'; // IE } else { obj.firstChild.nextSibling.nextSibling.style.display = 'block'; // DOM } } // clear timeout clearTimeout(navTimer); // hide last Nav immediately (if not same as current nav) if (ABC.lastNav != obj) { hideNav(); } } /** * hide submenus of a top-level nav - after a 500 millisecond delay * * @return void */ function hideSubMenu(obj) { ABC.lastNav = obj; navTimer = setTimeout('ABC.hideNav()',500); } /** * Hide submenus of a top-level nav - called by hideSubMenu after a delay * * @return void */ function hideNav() { var obj = ABC.lastNav; // hide last submenu if it exists if (obj && obj.firstChild && obj.firstChild.nextSibling) { if (obj.firstChild.nextSibling.nodeType == 1) { obj.firstChild.nextSibling.style.display = 'none'; // IE } else { obj.firstChild.nextSibling.nextSibling.style.display = 'none'; // DOM } } } /** * Adds Webtrends link tracking to abcNav * * @return void */ function addLinkTracking() { //if (document.getElementsByTagName('body')[0].className.indexOf('abcHomepage') != -1) { var navLinks = document.getElementById("abcNav").getElementsByTagName('A'); var link; for (var i=0, j=navLinks.length; i<j; i++) { link = navLinks[i]; link.onmouseup = function(){ var parent = this.parentNode; var parentId = parent.id; // climb up tree until you find a parent with an id while (parentId === '') { parent = parent.parentNode; parentId = parent.id; } // find the current site profile var profile = 'other'; if (typeof abcContentProfile != 'undefined') { profile = abcContentProfile; } else if (ABC.Stats && ABC.Stats.getProfile()) { profile = ABC.Stats.getProfile(); } // add the webtrends query string if ((this.search.indexOf('WT.z_navMenu') == -1)) { this.search += (this.search == '') ? '?' : '&'; this.search += 'WT.z_navMenu=' + parentId; this.search += '&WT.z_srcSite=' + profile; this.search += '&WT.z_linkName=' + (this.textContent || this.innerText || this.title || '').replace(/(?: & )|\s/gi, '_'); } }; } //} } /** * Toggle the search field in the top navigation to contain the holding * text of 'Keyword' unless in focus or filled with a value. * * @return void */ function clearSearchField() { var searchBox = document.getElementById('abcNavQuery'); var defaultText = 'Keywords'; if (searchBox != null) { searchBox.onfocus = function() { if (this.value == defaultText) { this.value = ''; } }; searchBox.onblur = function() { if (!this.value) { this.value = defaultText; } }; searchBox.parentNode.onsubmit = function() { if ((searchBox.value == defaultText) || (searchBox.value == '')) { document.location.href = "http://search.abc.net.au/search/search.cgi?collection=abcall_meta"; return false; } }; } } return { hideNav : function() { hideNav(); }, addLoadEvents : function(functionArray) { loadEvents(functionArray); } }; }();
gloriakang/vax-sentiment
articles/article_saved_html/Whooping cough increase related to current vaccine › News in Science (ABC Science)_files/abc.js
JavaScript
mit
7,152
// Get the modal var modal = document.getElementById('myModal'); // Get the image and insert it inside the modal - use its "alt" text as a caption var img = document.getElementById('myImg'); var modalImg = document.getElementById("img01"); var captionText = document.getElementById("caption"); img.onclick = function(){ modal.style.display = "block"; modalImg.src = this.src; modalImg.alt = this.alt; captionText.innerHTML = this.alt; } // Get the <span> element that closes the modal var span = document.getElementsByClassName("close")[0]; // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = "none"; }
BRichardson2993/WebSquatch
modal.js
JavaScript
mit
679
import { Selector } from 'testcafe' const host = process.env.HOST || 'localhost' const port = process.env.PORT || '3000' const MAIN_PAGE = `http://${host}:${port}` // eslint-disable-next-line no-unused-expressions, no-undef fixture`Hello, world!`.beforeEach(async (t) => { await t.setNativeDialogHandler(() => true) await t.navigateTo(MAIN_PAGE) }) test('home page', async (t) => { await t .expect( await Selector('section').withText( 'Hello World, this is my first styled component!' ).exists ) .eql(true) })
reimagined/resolve
templates/js/styled-components/test/e2e/index.test.js
JavaScript
mit
548
var React = require('react'); module.exports = React.createClass({ render: function () { return ( <html lang="sv"> <head> <meta charSet="utf-8" /> <title>{this.props.title}</title> </head> <body style={{ width: 300 + 'px', margin: '0 auto'}}> <h1>{this.props.title}</h1> <p>Det finns ingen sida med addressen <b>{this.props.url}</b>. Kontrollera addressen igen eller gå till <a href="/">skissaochgissa.se</a>.</p> </body> </html> ); } });
klambycom/Skissa-och-gissa
src/components/404.js
JavaScript
mit
561
var http = require('http') , https = require('https') , url = require('url') , vm = require('vm') , cluster = require('cluster') , util = require('util') , haikuConsole = require('./haikuConsole.js') , sandbox = require('./sandbox.js') var shutdown , shutdownInProgress = false , requestCount = 0 , argv process.on('message', function (msg) { process.send({ response: msg.challange }); }) .on('uncaughtException', function (err) { log('Entering shutdown mode after an uncaught exception: ' + (err.message || err) + (err.stack ? '\n' + err.stack : '')); initiateShutdown(); }); function log(thing) { console.log(process.pid + ': ' + thing); } function shutdownNext() { if (shutdown) { clearTimeout(shutdown); shutdown = undefined; } process.nextTick(function() { log('Recycling self. Active connections: TCP: ' + httpServer.connections + ', TLS: ' + httpsServer.connections); process.exit(); }); } // raised by HTTP or HTTPS server when one of the client connections closes function onConnectionClose() { if (shutdownInProgress && 0 === (httpServer.connections + httpsServer.connections)) shutdownNext() } function initiateShutdown() { if (!shutdownInProgress) { // stop accepting new requests httpServer.close(); httpsServer.close(); shutdownInProgress = true; if (0 === (httpServer.connections + httpsServer.connections)) { // there are no active connections - shut down now shutdownNext(); } else { // Shut down when all active connections close (see onConnectionClose above) // or when the graceful shutdown timeout expires, whichever comes first. // Graceful shutdown timeout is twice the handler processing timeout. shutdown = setTimeout(shutdownNext, argv.t * 2); } } } function onRequestFinished(context) { if (!context.finished) { context.finished = true; context.req.socket.end(); // force buffers to be be flushed } } function haikuError(context, status, error) { log(new Date() + ' Status: ' + status + ', Request URL: ' + context.req.url + ', Error: ' + error); try { context.req.resume(); context.res.writeHead(status); if (error && 'HEAD' !== context.req.method) context.res.end((typeof error === 'string' ? error : JSON.stringify(error)) + '\n'); else context.res.end(); } catch (e) { // empty } onRequestFinished(context); } function limitExecutionTime(context) { // setup timeout for request processing context.timeout = setTimeout(function () { delete context.timeout; haikuError(context, 500, 'Handler ' + context.handlerName + ' did not complete within the time limit of ' + argv.t + 'ms'); onRequestFinished(context); }, argv.t); // handler processing timeout // intercept end of response to cancel the timeout timer and // speed up shutdown if one is in progress context.res.end = sandbox.wrapFunction(context.res, 'end', function () { var result = arguments[--arguments.length].apply(this, arguments); if (context.timeout) { clearTimeout(context.timeout); delete context.timeout; onRequestFinished(context); } return result; }); } function executeHandler(context) { log(new Date() + ' executing ' + context.handlerName); // limit execution time of the handler to the preconfigured value limitExecutionTime(context); // expose rigged console through sandbox var sandboxAddons = { console: haikuConsole.createConsole(context, argv.l, argv.d) } // evaluate handler code in strict mode to prevent stack walking from untrusted code context.handler = "'use strict';" + context.handler; context.req.resume(); try { vm.runInNewContext(context.handler, sandbox.createSandbox(context, sandboxAddons), context.handlerName); } catch (e) { haikuError(context, 500, 'Handler ' + context.handlerName + ' generated an exception at runtime: ' + (e.message || e) + (e.stack ? '\n' + e.stack : '')); } } function resolveHandler(context) { if (!context.handlerName) return haikuError(context, 400, 'The x-haiku-handler HTTP request header or query paramater must specify the URL of the scriptlet to run.'); try { context.handlerUrl = url.parse(context.handlerName); } catch (e) { return haikuError(context, 400, 'The x-haiku-handler parameter must be a valid URL that resolves to a JavaScript scriptlet.'); } var engine; if (context.handlerUrl.protocol === 'http:') { engine = http; context.handlerUrl.port = context.handlerUrl.port || 80; } else if (context.handlerUrl.protocol === 'https:') { engine = https; context.handlerUrl.port = context.handlerUrl.port || 443; } else return haikuError(context, 400, 'The x-haiku-handler parameter specifies unsupported protocol. Only http and https are supported.'); var handlerRequest; var processResponse = function(res) { context.handler = ''; var length = 0; res.on('data', function(chunk) { length += chunk.length; if (length > argv.i) { handlerRequest.abort(); return haikuError(context, 400, 'The size of the handler exceeded the quota of ' + argv.i + ' bytes.'); } context.handler += chunk; }) .on('end', function() { if (res.statusCode === 200) executeHandler(context); else if (res.statusCode === 302 && context.redirect < 3) { context.handlerName = res.headers['location']; context.redirect++; resolveHandler(context); } else return haikuError(context, 400, 'HTTP error when obtaining handler code from ' + context.handlerName + ': ' + res.statusCode); }); } var processError = function(error) { haikuError(context, 400, 'Unable to obtain HTTP handler code from ' + context.handlerName + ': ' + error); } if (argv.proxyHost) { // HTTPS or HTTP request through HTTP proxy http.request({ // establishing a tunnel host: argv.proxyHost, port: argv.proxyPort, method: 'CONNECT', path: context.handlerUrl.hostname + ':' + context.handlerUrl.port }).on('connect', function(pres, socket, head) { if (pres.statusCode !== 200) return haikuError(context, 400, 'Unable to connect to the host ' + context.host); else handlerRequest = engine.get({ host: context.handlerUrl.hostname, port: context.handlerUrl.port, path: context.handlerUrl.path, socket: socket, // using a tunnel agent: false // cannot use a default agent }, processResponse).on('error', processError); }).on('error', processError).end(); } else // no proxy handlerRequest = engine.get({ host: context.handlerUrl.hostname, port: context.handlerUrl.port, path: context.handlerUrl.path }, processResponse).on('error', processError); } function getHaikuParam(context, name, defaultValue) { return context.req.headers[name] || context.reqUrl.query[name] || defaultValue; } function processRequest(req, res) { if (req.url === '/favicon.ico') return haikuError({ req: req, res: res}, 404); if (!shutdownInProgress && argv.r > 0 && ++requestCount >= argv.r) { log('Entering shutdown mode after reaching request quota. Current active connections: TCP: ' + httpServer.connections + ', TLS: ' + httpsServer.connections); initiateShutdown(); } req.pause(); var context = { req: req, res: res, redirect: 0, reqUrl: url.parse(req.url, true) } context.handlerName = getHaikuParam(context, 'x-haiku-handler'); context.console = getHaikuParam(context, 'x-haiku-console', 'none'); resolveHandler(context); } exports.main = function(args) { argv = args; // enter module sanbox - from now on all module reustes in this process will // be subject to sandboxing sandbox.enterModuleSandbox(); httpServer = http.createServer(processRequest) .on('connection', function(socket) { socket.on('close', onConnectionClose) }) .listen(argv.p); httpsServer = https.createServer({ cert: argv.cert, key: argv.key }, processRequest) .on('connection', function(socket) { socket.on('close', onConnectionClose) }) .listen(argv.s); }
ecoiso/ecoiso
node_modules/haiku-http/src/worker.js
JavaScript
mit
8,353
import * as API from '../utils/Api' export const SET_CATEGORIES = "SET_CATEGORIES" export function setCategories(categories) { return { type: SET_CATEGORIES, categories } } export const fetchGetCategories = () => dispatch => ( API.getCategories().then(data => { dispatch(setCategories(data.categories)) }) );
faridsaud/udacity-readable-project
src/actions/Category.js
JavaScript
mit
352
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _toast = require('./toast.container'); Object.defineProperty(exports, 'default', { enumerable: true, get: function get() { return _interopRequireDefault(_toast).default; } }); var _redux = require('./redux'); Object.keys(_redux).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _redux[key]; } }); }); Object.defineProperty(exports, 'reducer', { enumerable: true, get: function get() { return _interopRequireDefault(_redux).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
Trampss/kriya
lib/toast/index.js
JavaScript
mit
782
define({ "configText": "아래의 필터 그룹 정의", "labels": { "groupName": "필터 설정 이름:", "groupNameTip": "사용자가 선택할 필터의 이름입니다.", "groupDesc": "설명:", "groupDescTip": "필터 설정의 설명입니다.", "groupOperator": "프리셋 연산자:", "groupOperatorTip": "필터의 연산자를 미리 정의하는 옵션입니다. 프리셋 연산자가 선택되지 않으면 필터가 동일한 연산자를 사용하게 됩니다.", "groupDefault": "프리셋 값:", "groupDefaultTip": "기존 레이어에서 값을 선택하는 옵션입니다.", "sameLayerAppend": "레이어가 두 번 이상 나열된 경우:", "sameLayerConjunc": "다음을 사용하여 추가:", "caseSearch": "대소문자 구분 검색 수행: ", "headerTextHelp": "필터 선택 위에 표시할 텍스트 제공" }, "buttons": { "addNewGroup": "새 그룹 추가", "addNewGroupTip": "새 필터 설정을 추가합니다.", "addLayer": "레이어 추가", "addLayerTip": "레이어를 필터 설정에 추가합니다." }, "inputs": { "groupName": "그룹에 이름 지정", "groupDesc": "그룹 설명", "groupDefault": "사전 정의된 값 입력", "sameLayerAny": "임의 일치 식", "sameLayerAll": "모두 일치 식", "simpleMode": "간단한 뷰에서 시작", "simpleModeTip": "구성된 위젯 인터페이스를 단순화하는 옵션입니다. 옵션을 선택한 경우 연산자 드롭다운 목록과 기준 추가 버튼이 인터페이스에서 제거됩니다.", "webmapAppendModeAny": "기존 맵 필터에 임의 식 추가", "webmapAppendModeAll": "기존 맵 필터에 모든 식 추가", "webmapAppendModeTip": "기존 웹 맵 필터에 필터 집합을 추가하는 옵션입니다.", "persistOnClose": "위젯이 닫힌 후 유지", "selectGroup": "필터링할 그룹 선택", "hideDropDown": "하나의 그룹만 구성된 경우 헤더 및 필터 선택 항목을 숨깁니다", "optionsMode": "위젯 옵션 숨기기", "optionsModeTip": "추가 위젯 설정을 표시하는 옵션입니다. 옵션을 선택한 경우 정의된 필터를 저장 및 불러오고 위젯이 닫힌 후에 필터를 유지하는 기능이 인터페이스에서 제거됩니다.", "optionOR": "OR", "optionAND": "AND", "optionEQUAL": "EQUALS", "optionNOTEQUAL": "NOT EQUAL", "optionGREATERTHAN": "GREATER THAN", "optionGREATERTHANEQUAL": "GREATER THAN OR EQUAL", "optionLESSTHAN": "LESS THAN", "optionLESSTHANEQUAL": "LESS THAN OR EQUAL", "optionSTART": "BEGINS WITH", "optionEND": "ENDS WITH", "optionLIKE": "CONTAINS", "optionNOTLIKE": "DOES NOT CONTAIN", "optionONORBEFORE": "다음 시간 또는 그 이전", "optionONORAFTER": "다음 시간 또는 그 이후", "optionNONE": "NONE" }, "tables": { "layer": "레이어", "layerTip": "맵에 정의된 레이어 이름입니다.", "field": "필드", "fieldTip": "레이어가 필터링될 필드입니다.", "value": "값 사용", "valueTip": "레이어에서 드롭다운 목록 값을 사용하는 옵션입니다. 레이어를 이 매개변수에 사용하지 않는 경우 기본 텍스트 상자가 사용자에게 표시됩니다.", "zoom": "확대", "zoomTip": "필터가 적용된 후에 피처의 범위를 확대하는 옵션입니다. 하나의 레이어만 확대하는 데 선택할 수 있습니다.", "action": "삭제", "actionTip": "필터 설정에서 레이어를 제거합니다." }, "popup": { "label": "값 선택" }, "errors": { "noGroups": "최소 하나 이상의 그룹이 필요합니다.", "noGroupName": "하나 이상의 그룹 이름이 없습니다.", "noDuplicates": "하나 이상의 그룹 이름이 중복되었습니다.", "noRows": "테이블에 최소 하나의 행이 필요합니다.", "noLayers": "맵에 레이어가 없습니다." }, "picker": { "description": "이 그룹에 대한 프리셋 값을 찾으려면 이 양식을 사용합니다.", "layer": "레이어 선택", "layerTip": "웹 맵에 정의된 레이어 이름입니다.", "field": "필드 선택", "fieldTip": "프리셋 값이 설정될 필드입니다.", "value": "값 선택", "valueTip": "위젯의 기본값이 될 값입니다." } });
tmcgee/cmv-wab-widgets
wab/2.15/widgets/GroupFilter/setting/nls/ko/strings.js
JavaScript
mit
4,446
define('dummy/tests/app.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - .'); QUnit.test('app.js should pass jshint', function (assert) { assert.ok(true, 'app.js should pass jshint.'); }); }); define('dummy/tests/helpers/destroy-app', ['exports', 'ember'], function (exports, _ember) { exports['default'] = destroyApp; function destroyApp(application) { _ember['default'].run(application, 'destroy'); } }); define('dummy/tests/helpers/destroy-app.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - helpers'); QUnit.test('helpers/destroy-app.js should pass jshint', function (assert) { assert.ok(true, 'helpers/destroy-app.js should pass jshint.'); }); }); define('dummy/tests/helpers/module-for-acceptance', ['exports', 'qunit', 'dummy/tests/helpers/start-app', 'dummy/tests/helpers/destroy-app'], function (exports, _qunit, _dummyTestsHelpersStartApp, _dummyTestsHelpersDestroyApp) { exports['default'] = function (name) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; (0, _qunit.module)(name, { beforeEach: function beforeEach() { this.application = (0, _dummyTestsHelpersStartApp['default'])(); if (options.beforeEach) { options.beforeEach.apply(this, arguments); } }, afterEach: function afterEach() { (0, _dummyTestsHelpersDestroyApp['default'])(this.application); if (options.afterEach) { options.afterEach.apply(this, arguments); } } }); }; }); define('dummy/tests/helpers/module-for-acceptance.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - helpers'); QUnit.test('helpers/module-for-acceptance.js should pass jshint', function (assert) { assert.ok(true, 'helpers/module-for-acceptance.js should pass jshint.'); }); }); define('dummy/tests/helpers/resolver', ['exports', 'ember/resolver', 'dummy/config/environment'], function (exports, _emberResolver, _dummyConfigEnvironment) { var resolver = _emberResolver['default'].create(); resolver.namespace = { modulePrefix: _dummyConfigEnvironment['default'].modulePrefix, podModulePrefix: _dummyConfigEnvironment['default'].podModulePrefix }; exports['default'] = resolver; }); define('dummy/tests/helpers/resolver.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - helpers'); QUnit.test('helpers/resolver.js should pass jshint', function (assert) { assert.ok(true, 'helpers/resolver.js should pass jshint.'); }); }); define('dummy/tests/helpers/start-app', ['exports', 'ember', 'dummy/app', 'dummy/config/environment'], function (exports, _ember, _dummyApp, _dummyConfigEnvironment) { exports['default'] = startApp; function startApp(attrs) { var application = undefined; var attributes = _ember['default'].merge({}, _dummyConfigEnvironment['default'].APP); attributes = _ember['default'].merge(attributes, attrs); // use defaults, but you can override; _ember['default'].run(function () { application = _dummyApp['default'].create(attributes); application.setupForTesting(); application.injectTestHelpers(); }); return application; } }); define('dummy/tests/helpers/start-app.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - helpers'); QUnit.test('helpers/start-app.js should pass jshint', function (assert) { assert.ok(true, 'helpers/start-app.js should pass jshint.'); }); }); define('dummy/tests/router.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - .'); QUnit.test('router.js should pass jshint', function (assert) { assert.ok(true, 'router.js should pass jshint.'); }); }); define('dummy/tests/test-helper', ['exports', 'dummy/tests/helpers/resolver', 'ember-qunit'], function (exports, _dummyTestsHelpersResolver, _emberQunit) { (0, _emberQunit.setResolver)(_dummyTestsHelpersResolver['default']); }); define('dummy/tests/test-helper.jshint', ['exports'], function (exports) { 'use strict'; QUnit.module('JSHint - .'); QUnit.test('test-helper.js should pass jshint', function (assert) { assert.ok(true, 'test-helper.js should pass jshint.'); }); }); /* jshint ignore:start */ require('dummy/tests/test-helper'); EmberENV.TESTS_FILE_LOADED = true; /* jshint ignore:end */ //# sourceMappingURL=tests.map
michaljach/ember-cli-xpagination
dist/assets/tests.js
JavaScript
mit
4,478
'use strict'; var app = angular.module('testReport.project.settings', [ 'ngRoute', ]); app.config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/project/:projectId/settings', { templateUrl: '/static/app/partials/project/settings/settings.html', controller: 'ProjectSettingsCtrl' }); }]); app.controller('ProjectSettingsCtrl', ['$rootScope', '$scope', '$routeParams', '$q', '$filter', '$location', 'Auth', 'Project', function ($rootScope, $scope, $routeParams, $q, $filter, $location, Auth, Project) { $rootScope.isMainDashboard = false; $scope.formErrors = null; var admin_settings = ['chart_type', 'results_view', 'weight', 'current_build']; if(!$rootScope.getActiveProject()) { $rootScope.selectProject($routeParams.projectId); } $scope.activeProjectId = $rootScope.getActiveProject(); function reloadSettings() { $rootScope.getProjectSettings($routeParams.projectId, '').then(function(result) { _.each(result, function(item) { item.$save = true; }); $scope.settings = _.sortBy(_.filter(result, function(item) { return !_.contains(admin_settings, item.key); }), 'key'); }); } reloadSettings(); $scope.addSettingsItem = function() { $scope.settings.push({ key: '', value: '' , $edit: true, $save: false }); }; $scope.cancelSettingsItem = function(item, index) { $scope.formErrors = null; if (!item.$save) { $scope.settings.splice(index, 1); } item.$edit = false; }; $scope.updateSettings = function (item) { $scope.formErrors = null; if (!item.$save && checkKeyExistent(item.key)) { $scope.formErrors = 'Key "' + item.key + '" already exists.'; return; } if (item.key === '') { return; } item.$edit = false; Project.save_settings({ projectId: $scope.activeProjectId }, item, function(result) { if (result.message === 'ok') { item.$save = true; } }, function(result) { $scope.formErrors = result.data.detail; }); }; $scope.deleteSettings = function (item) { var modal = $('#ConfirmationModal'); $scope.modalTitle = 'Attention'; $scope.modalBody = 'Are you sure you want to delete key "' + item.key + '" with value "' + item.value + '"?'; $scope.modalCallBack = function () { Project.delete_settings({ projectId: $scope.activeProjectId }, item, function(result) { if (result.message === 'ok') { reloadSettings(); } }, function(result) { $scope.formErrors = result.data.detail; }); }; modal.modal('show'); }; function checkKeyExistent(key) { var saved_settings_keys = []; _.each($scope.settings, function(item) { if (item.$save) { saved_settings_keys.push(item.key); } }); return _.contains(saved_settings_keys, key); } } ]);
2gis/badger
public/app/partials/project/settings/settings.js
JavaScript
mit
3,490
define( [ 'angular', 'ngRoute', 'config/config', 'tmdb/services/TMDBAPIService'], function( angular, $routeParams, config, TMDBAPIService ) { "use strict"; var MovieTileController = function($scope, TMDBAPIService, $routeParams ) { $scope.view = { images: config.apiImg }; $scope.clickOne = function(){ console.log("en el click one"); }; $scope.clickTwo = function(){ console.log("en el click two"); }; }; MovieTileController.$inject = [ '$scope', 'TMDBAPIService', '$routeParams' ]; return MovieTileController; } );
nelson-portilla/angular_start
src/main/tmdb/partials/movieTile/movieTileController.js
JavaScript
mit
734
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const vgraph_1 = require("./vgraph"); const vrootgraph_list_1 = require("../../components/graph/vrootgraph.list"); const cabeiri_lang_1 = require("cabeiri-lang"); class RootGraphesState { constructor() { this.selectedRootGraph = cabeiri_lang_1.CID.CID_NONE; } } exports.RootGraphesState = RootGraphesState; class VRootGraphes extends React.Component { constructor(props) { super(props); this.onRootGraphSelected = (selectedRootGraph) => { var graphState = new RootGraphesState(); graphState.selectedRootGraph = selectedRootGraph; this.setState(graphState); }; this.state = new RootGraphesState(); } componentDidMount() { } render() { return React.createElement("div", { className: "container-fluid" }, React.createElement("div", { className: "row" }, React.createElement("div", { className: "col-xs-4 col-md-3" }, React.createElement(vrootgraph_list_1.VRootGraphList, { onItemSelected: this.onRootGraphSelected, searchLabel: "Graphes" })), React.createElement("div", { className: "col-xs-10 col-md-9" }, React.createElement(vgraph_1.VGraph, { rootGraphCID: this.state.selectedRootGraph })))); } ; } exports.VRootGraphes = VRootGraphes; ; React.createFactory(VRootGraphes); //# sourceMappingURL=vrootgraphes.js.map
CabeiriIO/cabeiri-editor
app/js/components/graph/vrootgraphes.js
JavaScript
mit
1,526
const fs = require('fs'); const p = require('path'); // walk $PATH to find bin const which = (bin) => { const path = process.env.PATH.split(p.delimiter); let file = ''; path.find((v) => { const testPath = v + p.sep + bin; if (fs.existsSync(testPath)) { file = testPath; return true; } return false; }); return file; }; const config = { removeInfected: false, // don't change quarantineInfected: `${__dirname}/infected`, // required for testing // scanLog: `${__dirname}/clamscan-log`, // not required clamscan: { path: which('clamscan'), // required for testing }, clamdscan: { socket: '/var/run/clamd.scan/clamd.sock', // - can be set to null host: '127.0.0.1', // required for testing (change for your system) - can be set to null port: 3310, // required for testing (change for your system) - can be set to null path: which('clamdscan'), // required for testing timeout: 1000, localFallback: false, // configFile: '/etc/clamd.d/scan.conf' // set if required }, // preference: 'clamdscan', // not used if socket/host+port is provided debugMode: false, }; // Force specific socket when on GitHub Actions if (process.env.CI) config.clamdscan.socket = '/var/run/clamav/clamd.ctl'; module.exports = config;
kylefarris/clamscan
tests/test_config.js
JavaScript
mit
1,387
module.exports = client => { //eslint-disable-line no-unused-vars console.log(`Reconnecting... [at ${new Date()}]`); };
SuvanL/delet
events/reconnecting.js
JavaScript
mit
124
import React from 'react'; import { FlexRow, FlexCell } from '../common'; import CharacterName from './CharacterName'; import InfoBlock from './InfoBlock'; const PersonalInfo = ({ character }) => ( <FlexRow> <FlexCell columns={3}> <CharacterName character={character} /> </FlexCell> <FlexCell columns={9}> <InfoBlock character={character} /> </FlexCell> </FlexRow> ); export default PersonalInfo;
revuniversal/5e-sheets
src/character/sheet/basic/BasicInfo.js
JavaScript
mit
431
import React from 'react'; const Footer = () => <p>Footer</p>; export default Footer;
petertrotman/critrolemoments
src/layout/Footer.js
JavaScript
mit
88
/* License: MIT. * Copyright (C) 2013, 2014, Uri Shaked. */ 'use strict'; module.exports = function (grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ karma: { unit: { configFile: 'karma.conf.js', singleRun: true } }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'angular-moment.js', 'tests.js' ] }, uglify: { dist: { files: { 'angular-moment.min.js': 'angular-moment.js' } } } }); grunt.registerTask('test', [ 'jshint', 'karma' ]); grunt.registerTask('build', [ 'jshint', 'uglify' ]); grunt.registerTask('default', ['build']); };
jenklee/few
node_modules/angular-moment/Gruntfile.js
JavaScript
mit
773
'use strict' const { lt, inRange } = require('lodash') module.exports = boardSize => { if (lt(boardSize, 70)) return '<70l' if (inRange(boardSize, 70, 80)) return '70l to 80l' if (inRange(boardSize, 80, 90)) return '80l to 90l' if (inRange(boardSize, 90, 100)) return '90l to 100l' if (inRange(boardSize, 100, 110)) return '100l to 110l' if (inRange(boardSize, 110, 120)) return '110l to 120l' if (inRange(boardSize, 120, 130)) return '120l to 130l' return '>130l' }
windtoday/windtoday-core
core/range/board-size.js
JavaScript
mit
485
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Choices', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, QuestionId: { type: Sequelize.UUID }, text: { type: Sequelize.TEXT }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Choices'); } };
thirdtruck/sumo-survey
migrations/20170311204915-create-choice.js
JavaScript
mit
651
#!/usr/bin/env node var express = require('express'), package = require('./package.json'), program = require('commander'), _ = require('underscore'), Assets = require('./lib/assets.js'); program .version(package.version) .option('-s, --store <store>', 'Location of storage') .option('-u, --url <url>', 'Base url', '/store') .parse(process.argv); if (!program.store) program.help(); var assets = new Assets(program.store), app = express(); app.get(program.url + '/:id', /** * GET asset meta information * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * * @returns {json} Meta information about asset */ function(req, res) { assets .get(req.params.id) .done(function(asset) { res.json(asset); }, function() { res.json(404, {error: 'Asset not found'}); }); } ); app.get(program.url + '/data/:id', /** * GET asset data * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * * @returns {file|redirect} File associated with asset or redirect to server * that has the file */ function(req, res) { assets .getData(req.params.id) .done(function(file) { res.download(file.path, file.name); }, function() { res.json(404, {error: 'Asset not found'}); }); } ); app.post(program.url, [express.json(), express.multipart()], /** * POST asset meta information and data * * @param {Object} req * @prop {Object} files Uploaded files * * @returns {json} Meta information about asset */ function(req, res) { assets .fromUploads(req.files) .done(function() { res.send(''); }, function(err) { res.send(500, {error: 'Upload failed', raw_error: err}); }); } ); app.put(program.url + '/:id', [express.json(), express.multipart()], /** * PUT asset meta information * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * @prop {Object} files Uploaded files * * @returns {json} Meta information about asset */ function(req, res) { assets.put(req.params.id, file); } ); app.delete(program.url + '/:id', /** * DELETE asset * * @param {Object} req * @prop {Object} params * @prop {string} params.id The asset ID * * @returns {json} Meta information about asset */ function(req, res) { assets.delete(req.params.id); } ); assets .init(true) .then(function() { app.listen(3001); console.log('Listening on port 3001'); });
dustinmoorenet/asset-server
index.js
JavaScript
mit
2,697
export default { data () { return { selected: null, options: [ { id: 1, label: 'Richard Hendricks' }, { id: 2, label: 'Bertram Gilfoyle' }, { id: 3, label: 'Dinesh Chugtai' }, { id: 4, label: 'Jared Dunn', disabled: true }, { id: 5, label: 'Erlich Bachman', disabled: true } ] }; } };
inkline/inkline
src/components/ISelect/examples/disabled-option.js
JavaScript
mit
425
'use strict'; describe('Service: mainService', function () { // load the service's module beforeEach(module('catsGoApp')); // instantiate service var mainService; beforeEach(inject(function (_mainService_) { mainService = _mainService_; })); it('randomArray testing', function () { var a=mainService.randomArray(4,5,1); expect(a).not.toBe(null) expect(!!mainService).toBe(true); }); });
Ale9Hack/Angular-app-CatsGo
test/spec/services/mainService.js
JavaScript
mit
429
export default { props: { things: [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 5, name: 'e' } ] }, html: ` <div>a</div> <div>b</div> <div>c</div> <div>d</div> <div>e</div> `, test({ assert, component, raf }) { let divs = document.querySelectorAll('div'); divs.forEach(div => { div.getBoundingClientRect = function() { const index = [...this.parentNode.children].indexOf(this); const top = index * 30; return { left: 0, right: 100, top, bottom: top + 20 }; }; }); component.things = [ { id: 5, name: 'e' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 1, name: 'a' } ]; divs = document.querySelectorAll('div'); assert.equal(divs[0].dy, 120); assert.equal(divs[4].dy, -120); raf.tick(50); assert.equal(divs[0].dy, 60); assert.equal(divs[4].dy, -60); raf.tick(100); assert.equal(divs[0].dy, 0); assert.equal(divs[4].dy, 0); } };
sveltejs/svelte
test/runtime/samples/animation-js-easing/_config.js
JavaScript
mit
1,031
import React, {Component} from 'react'; import { Router, IndexRoute, Route, browserHistory } from 'react-router'; import UserCard from './UserCard'; import firebase from './firebase'; import NewContact from './NewContact'; class UserCards extends Component { constructor() { super(); this.state = { contacts: [] }; this.contactsArray = []; } get baseContactReference() { return firebase.database().ref(`baseContact/${firebase.auth().currentUser.uid}/`); } componentDidMount() { this.baseContactReference.on('child_added', (snapshot) => { const newContactCard = snapshot.val(); var contactArr = { fullName: newContactCard.fullName, company:newContactCard.company, id: newContactCard.id, email: newContactCard.email, followUp: newContactCard.followUp }; this.contactsArray.push(contactArr); this.setState({ contacts: this.contactsArray }); }); } componentWillUnmount() { this.baseContactReference.off(); } loadCards() { return this.state.contacts.map(contact => { return( <div className="contactInfoCard hello" key={contact.id}> <UserCard contact={contact} email={contact.email}/> </div> ) }) } render(){ return( <div className="user-cards"> {this.loadCards()} </div> ) } } export default UserCards
bcgodfrey91/tier-2
src/UserCards.js
JavaScript
mit
1,410
var urls = [ "https://vk.com/igor.suvorov", "https://twitter.com/suvorovigor", "https://telegram.me/skillbranch", "@skillbranch", "https://vk.com/skillbranch?w=wall-117903599_1076",]; function getName(url) { const reg = /(@|\/)?[\w\9.]+/ig; const reg1 = /[\w\9.]+/ig; const matches = url.match(reg); console.log(matches); // return "@"+matches[matches.length-1]; return "@"+matches[matches.length-1].match(reg1); } export default function canonize(url) { return getName(url); }
nazip/SkillBranch
src/canonize.js
JavaScript
mit
495
version https://git-lfs.github.com/spec/v1 oid sha256:8a773d7f07d6a2ce3c6379427f1a5aa12f7545b4da9579eae9b6a31ec13a11b7 size 43336
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.0/get/get-debug.js
JavaScript
mit
130
import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import fetchMock from 'fetch-mock'; import { fetchLogin, testing, } from './login'; const mockStore = configureMockStore([thunk]); beforeEach(() => { fetchMock.restore(); }); test('fetch login with success', done => { fetchMock.post(`${testing.base_url}/auth/login/`, { status: 200, body: {success: true}, }); const store = mockStore(); const expectedActions = [ testing.fetchLoginSuccess(), ]; const email = "mario.rossi@email.com"; const password = "pippo"; return store.dispatch(fetchLogin(email, password)) .then(() => { expect(store.getActions()).toEqual(expectedActions); done(); }); }); test('fetch login failure', done => { fetchMock.post(`${testing.base_url}/auth/login/`, { status: 401, body: {}, }); const store = mockStore(); const expectedActions = [ testing.fetchLoginFailure(), ]; const email = "mario.rossi@email.com"; const password = "pippo"; return store.dispatch(fetchLogin(email, password)) .then(() => { expect(store.getActions()).toEqual(expectedActions); done(); }); });
nbschool/ecommerce_web
src/modules/login.test.js
JavaScript
mit
1,190
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('keyboard-navigable-list', 'Integration | Component | keyboard navigable list', { integration: true }); test('if passed in an array it renders the items in a list.', function(assert) { //this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.set('theArray', [1, 2, 3]); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{keyboard-navigable-list contentArray=theArray}}`); assert.equal(this.$('ul[data-parent-ul] > li').length, 3, 'it renders the proper number of items'); assert.equal(this.$('ul[data-parent-ul] > li').first().text().trim(), 1, 'the first item is 1'); assert.equal(this.$('ul[data-parent-ul] > li').last().text().trim(), 3, 'the last item is 3'); }); test('if passed in an array contains an object key it displays that property on the object.', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name"}}`); assert.equal(this.$('ul[data-parent-ul] > li').first().text().trim(), 'hello', 'the first item is hello'); assert.equal(this.$('ul[data-parent-ul] > li').last().text().trim(), 'third item', 'the last item is third item'); }); test('after the component loads no li item has the class of active', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name"}}`); assert.equal(this.$('li.active').length, 0, 'by default no one is active'); }); test('if linkDirection is set, hasLink is true and a link is present', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name" linkDirection='people.show'}}`); assert.equal(this.$('ul[data-parent-ul] > li:eq(0) > a').length, 1, 'if there is a linkDirection there is a link'); }); test('if used as a block level component it gives you access to the individual items in the array', function(assert) { this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]); this.render(hbs`{{#keyboard-navigable-list contentArray=theArray as |person|}} {{person.name}} {{/keyboard-navigable-list}}`); assert.equal(this.$('ul[data-parent-ul] > li:eq(0)').text().trim(), 'hello', 'we have access to the items from the yield'); });
baroquon/ember-keyboard-navigable-list
tests/integration/components/keyboard-navigable-list-test.js
JavaScript
mit
2,648
define(['knockout', 'Q', 'model', 'css!mediaelement-css', 'css!dataTables-bootstrap-css', 'css!datatables-scroller-css', 'text!./mim-video-playlist.html', 'datatables', 'knockout.punches', 'mediaelement', 'datatables-bootstrap', 'datatables-scroller'], function (ko, Q, model, css, dataTablesBootstrapCss,datatablesScrollerCss, templateMarkup) { function MimVideoPlaylist(params) { var self = this; self.urlBaseVideo = 'videoDirectory/'; self.urlApi = 'Api/'; self.videoSuffix = '.mp4'; self.videoSuffix = '.jpg'; self.isVideoDataLoaded = ko.observable(false); self.url = { getVideoList: self.urlApi + 'video' }; self.list = ko.observableArray([]); self.list0 = ko.observableArray([]); self.fileName = ko.observable(); self.posterFileName = ko.observable(); self.isVideoVisible = ko.observable(false); self.mustPlay = ko.observable(false); self.playOnRender = ko.observable(false); self.playerAssign = function () { delete self.player; self.player = $('#videoContent').mediaelementplayer({ alwaysShowControls: false, features: ['playpause', 'volume'], success: function (mediaElement, domObject) { if (self.mustPlay()) mediaElement.play(); }, error: function (data) { } }); }; self.playlistClick = function (data) { self.isVideoVisible(false); self.fileName(data.video); ko.utils.arrayForEach(self.list(), function (item) { item.isPlaying(false) }); data.isPlaying(true); self.posterFileName(data.poster); self.mustPlay(true); self.isVideoVisible(true); return true; } self.player = null; self.mapping = { create: function (options) { var vmCreate = ko.mapping.fromJS(options.data, { 'ignore': ['Video','Title'] }); vmCreate.isPlaying = ko.observable(false); vmCreate.isNotPlaying = ko.pureComputed(function () { return !vmCreate.isPlaying(); }); vmCreate.poster = self.urlBaseVideo+ options.data.Video + self.posterSuffix vmCreate.video = self.urlBaseVideo + options.data.Video + self.videoSuffix; vmCreate.title = options.data.Title; return vmCreate; } }; self.initModel = function () { Q(model.post(self.url.getVideoList)) .then(function (data) { ko.mapping.fromJS(data.d, self.mapping, self.list); self.fileName(self.list()[0].video); self.posterFileName(self.list()[0].poster); self.isVideoDataLoaded(true); }); } self.initView = function () { $('#mim-playlist-innner').DataTable( { responsive: true, "deferRender": true, "jQueryUI": false, "sDom": 't', dom: "S", "sScrollY": "360px", scrollCollapse: true, "deferRender": true, "autoWidth": true, "autoHigh": false, searching: false, ordering: false, "info": false, }); $('#mim-playlist-innner').removeClass('display').addClass('table table-striped table-bordered'); $('.dataTables_scrollBody').css('height', 360); $('.dataTables_scrollBody').css('width', '100%'); }; ko.punches.enableAll(); self.initModel(); self.initView(); self.isVideoVisible(true); } MimVideoPlaylist.prototype.dispose = function() { }; return { viewModel: MimVideoPlaylist, template: templateMarkup }; });
maciek3t/mim-video-playlist
mim-video-playlist/mim-video-playlist.js
JavaScript
mit
4,513
import { encode } from 'vlq'; function Chunk ( start, end, content ) { this.start = start; this.end = end; this.original = content; this.intro = ''; this.outro = ''; this.content = content; this.storeName = false; this.edited = false; // we make these non-enumerable, for sanity while debugging Object.defineProperties( this, { previous: { writable: true, value: null }, next: { writable: true, value: null } }); } Chunk.prototype = { appendLeft: function appendLeft ( content ) { this.outro += content; }, appendRight: function appendRight ( content ) { this.intro = this.intro + content; }, clone: function clone () { var chunk = new Chunk( this.start, this.end, this.original ); chunk.intro = this.intro; chunk.outro = this.outro; chunk.content = this.content; chunk.storeName = this.storeName; chunk.edited = this.edited; return chunk; }, contains: function contains ( index ) { return this.start < index && index < this.end; }, eachNext: function eachNext ( fn ) { var chunk = this; while ( chunk ) { fn( chunk ); chunk = chunk.next; } }, eachPrevious: function eachPrevious ( fn ) { var chunk = this; while ( chunk ) { fn( chunk ); chunk = chunk.previous; } }, edit: function edit ( content, storeName, contentOnly ) { this.content = content; if ( !contentOnly ) { this.intro = ''; this.outro = ''; } this.storeName = storeName; this.edited = true; return this; }, prependLeft: function prependLeft ( content ) { this.outro = content + this.outro; }, prependRight: function prependRight ( content ) { this.intro = content + this.intro; }, split: function split ( index ) { var sliceIndex = index - this.start; var originalBefore = this.original.slice( 0, sliceIndex ); var originalAfter = this.original.slice( sliceIndex ); this.original = originalBefore; var newChunk = new Chunk( index, this.end, originalAfter ); newChunk.outro = this.outro; this.outro = ''; this.end = index; if ( this.edited ) { // TODO is this block necessary?... newChunk.edit( '', false ); this.content = ''; } else { this.content = originalBefore; } newChunk.next = this.next; if ( newChunk.next ) { newChunk.next.previous = newChunk; } newChunk.previous = this; this.next = newChunk; return newChunk; }, toString: function toString () { return this.intro + this.content + this.outro; }, trimEnd: function trimEnd ( rx ) { this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) { return true; } var trimmed = this.content.replace( rx, '' ); if ( trimmed.length ) { if ( trimmed !== this.content ) { this.split( this.start + trimmed.length ).edit( '', false ); } return true; } else { this.edit( '', false ); this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) { return true; } } }, trimStart: function trimStart ( rx ) { this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) { return true; } var trimmed = this.content.replace( rx, '' ); if ( trimmed.length ) { if ( trimmed !== this.content ) { this.split( this.end - trimmed.length ); this.edit( '', false ); } return true; } else { this.edit( '', false ); this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) { return true; } } } }; var _btoa; if ( typeof window !== 'undefined' && typeof window.btoa === 'function' ) { _btoa = window.btoa; } else if ( typeof Buffer === 'function' ) { _btoa = function (str) { return new Buffer( str ).toString( 'base64' ); }; } else { _btoa = function () { throw new Error( 'Unsupported environment: `window.btoa` or `Buffer` should be supported.' ); }; } var btoa = _btoa; function SourceMap ( properties ) { this.version = 3; this.file = properties.file; this.sources = properties.sources; this.sourcesContent = properties.sourcesContent; this.names = properties.names; this.mappings = properties.mappings; } SourceMap.prototype = { toString: function toString () { return JSON.stringify( this ); }, toUrl: function toUrl () { return 'data:application/json;charset=utf-8;base64,' + btoa( this.toString() ); } }; function guessIndent ( code ) { var lines = code.split( '\n' ); var tabbed = lines.filter( function (line) { return /^\t+/.test( line ); } ); var spaced = lines.filter( function (line) { return /^ {2,}/.test( line ); } ); if ( tabbed.length === 0 && spaced.length === 0 ) { return null; } // More lines tabbed than spaced? Assume tabs, and // default to tabs in the case of a tie (or nothing // to go on) if ( tabbed.length >= spaced.length ) { return '\t'; } // Otherwise, we need to guess the multiple var min = spaced.reduce( function ( previous, current ) { var numSpaces = /^ +/.exec( current )[0].length; return Math.min( numSpaces, previous ); }, Infinity ); return new Array( min + 1 ).join( ' ' ); } function getRelativePath ( from, to ) { var fromParts = from.split( /[\/\\]/ ); var toParts = to.split( /[\/\\]/ ); fromParts.pop(); // get dirname while ( fromParts[0] === toParts[0] ) { fromParts.shift(); toParts.shift(); } if ( fromParts.length ) { var i = fromParts.length; while ( i-- ) { fromParts[i] = '..'; } } return fromParts.concat( toParts ).join( '/' ); } var toString$1 = Object.prototype.toString; function isObject ( thing ) { return toString$1.call( thing ) === '[object Object]'; } function getLocator ( source ) { var originalLines = source.split( '\n' ); var start = 0; var lineRanges = originalLines.map( function ( line, i ) { var end = start + line.length + 1; var range = { start: start, end: end, line: i }; start = end; return range; }); var i = 0; function rangeContains ( range, index ) { return range.start <= index && index < range.end; } function getLocation ( range, index ) { return { line: range.line, column: index - range.start }; } return function locate ( index ) { var range = lineRanges[i]; var d = index >= range.end ? 1 : -1; while ( range ) { if ( rangeContains( range, index ) ) { return getLocation( range, index ); } i += d; range = lineRanges[i]; } }; } function Mappings ( hires ) { var this$1 = this; var offsets = { generatedCodeColumn: 0, sourceIndex: 0, sourceCodeLine: 0, sourceCodeColumn: 0, sourceCodeName: 0 }; var generatedCodeLine = 0; var generatedCodeColumn = 0; this.raw = []; var rawSegments = this.raw[ generatedCodeLine ] = []; var pending = null; this.addEdit = function ( sourceIndex, content, original, loc, nameIndex ) { if ( content.length ) { rawSegments.push([ generatedCodeColumn, sourceIndex, loc.line, loc.column, nameIndex ]); } else if ( pending ) { rawSegments.push( pending ); } this$1.advance( content ); pending = null; }; this.addUneditedChunk = function ( sourceIndex, chunk, original, loc, sourcemapLocations ) { var originalCharIndex = chunk.start; var first = true; while ( originalCharIndex < chunk.end ) { if ( hires || first || sourcemapLocations[ originalCharIndex ] ) { rawSegments.push([ generatedCodeColumn, sourceIndex, loc.line, loc.column, -1 ]); } if ( original[ originalCharIndex ] === '\n' ) { loc.line += 1; loc.column = 0; generatedCodeLine += 1; this$1.raw[ generatedCodeLine ] = rawSegments = []; generatedCodeColumn = 0; } else { loc.column += 1; generatedCodeColumn += 1; } originalCharIndex += 1; first = false; } pending = [ generatedCodeColumn, sourceIndex, loc.line, loc.column, -1 ]; }; this.advance = function (str) { if ( !str ) { return; } var lines = str.split( '\n' ); var lastLine = lines.pop(); if ( lines.length ) { generatedCodeLine += lines.length; this$1.raw[ generatedCodeLine ] = rawSegments = []; generatedCodeColumn = lastLine.length; } else { generatedCodeColumn += lastLine.length; } }; this.encode = function () { return this$1.raw.map( function (segments) { var generatedCodeColumn = 0; return segments.map( function (segment) { var arr = [ segment[0] - generatedCodeColumn, segment[1] - offsets.sourceIndex, segment[2] - offsets.sourceCodeLine, segment[3] - offsets.sourceCodeColumn ]; generatedCodeColumn = segment[0]; offsets.sourceIndex = segment[1]; offsets.sourceCodeLine = segment[2]; offsets.sourceCodeColumn = segment[3]; if ( ~segment[4] ) { arr.push( segment[4] - offsets.sourceCodeName ); offsets.sourceCodeName = segment[4]; } return encode( arr ); }).join( ',' ); }).join( ';' ); }; } var Stats = function Stats () { Object.defineProperties( this, { startTimes: { value: {} } }); }; Stats.prototype.time = function time ( label ) { this.startTimes[ label ] = process.hrtime(); }; Stats.prototype.timeEnd = function timeEnd ( label ) { var elapsed = process.hrtime( this.startTimes[ label ] ); if ( !this[ label ] ) { this[ label ] = 0; } this[ label ] += elapsed[0] * 1e3 + elapsed[1] * 1e-6; }; var warned = { insertLeft: false, insertRight: false, storeName: false }; function MagicString$1 ( string, options ) { if ( options === void 0 ) options = {}; var chunk = new Chunk( 0, string.length, string ); Object.defineProperties( this, { original: { writable: true, value: string }, outro: { writable: true, value: '' }, intro: { writable: true, value: '' }, firstChunk: { writable: true, value: chunk }, lastChunk: { writable: true, value: chunk }, lastSearchedChunk: { writable: true, value: chunk }, byStart: { writable: true, value: {} }, byEnd: { writable: true, value: {} }, filename: { writable: true, value: options.filename }, indentExclusionRanges: { writable: true, value: options.indentExclusionRanges }, sourcemapLocations: { writable: true, value: {} }, storedNames: { writable: true, value: {} }, indentStr: { writable: true, value: guessIndent( string ) } }); this.byStart[ 0 ] = chunk; this.byEnd[ string.length ] = chunk; } MagicString$1.prototype = { addSourcemapLocation: function addSourcemapLocation ( char ) { this.sourcemapLocations[ char ] = true; }, append: function append ( content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); } this.outro += content; return this; }, appendLeft: function appendLeft ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byEnd[ index ]; if ( chunk ) { chunk.appendLeft( content ); } else { this.intro += content; } return this; }, appendRight: function appendRight ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byStart[ index ]; if ( chunk ) { chunk.appendRight( content ); } else { this.outro += content; } return this; }, clone: function clone () { var cloned = new MagicString$1( this.original, { filename: this.filename }); var originalChunk = this.firstChunk; var clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone(); while ( originalChunk ) { cloned.byStart[ clonedChunk.start ] = clonedChunk; cloned.byEnd[ clonedChunk.end ] = clonedChunk; var nextOriginalChunk = originalChunk.next; var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone(); if ( nextClonedChunk ) { clonedChunk.next = nextClonedChunk; nextClonedChunk.previous = clonedChunk; clonedChunk = nextClonedChunk; } originalChunk = nextOriginalChunk; } cloned.lastChunk = clonedChunk; if ( this.indentExclusionRanges ) { cloned.indentExclusionRanges = this.indentExclusionRanges.slice(); } Object.keys( this.sourcemapLocations ).forEach( function (loc) { cloned.sourcemapLocations[ loc ] = true; }); return cloned; }, generateMap: function generateMap ( options ) { var this$1 = this; options = options || {}; var sourceIndex = 0; var names = Object.keys( this.storedNames ); var mappings = new Mappings( options.hires ); var locate = getLocator( this.original ); if ( this.intro ) { mappings.advance( this.intro ); } this.firstChunk.eachNext( function (chunk) { var loc = locate( chunk.start ); if ( chunk.intro.length ) { mappings.advance( chunk.intro ); } if ( chunk.edited ) { mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 ); } else { mappings.addUneditedChunk( sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations ); } if ( chunk.outro.length ) { mappings.advance( chunk.outro ); } }); var map = new SourceMap({ file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ), sources: [ options.source ? getRelativePath( options.file || '', options.source ) : null ], sourcesContent: options.includeContent ? [ this.original ] : [ null ], names: names, mappings: mappings.encode() }); return map; }, getIndentString: function getIndentString () { return this.indentStr === null ? '\t' : this.indentStr; }, indent: function indent ( indentStr, options ) { var this$1 = this; var pattern = /^[^\r\n]/gm; if ( isObject( indentStr ) ) { options = indentStr; indentStr = undefined; } indentStr = indentStr !== undefined ? indentStr : ( this.indentStr || '\t' ); if ( indentStr === '' ) { return this; } // noop options = options || {}; // Process exclusion ranges var isExcluded = {}; if ( options.exclude ) { var exclusions = typeof options.exclude[0] === 'number' ? [ options.exclude ] : options.exclude; exclusions.forEach( function (exclusion) { for ( var i = exclusion[0]; i < exclusion[1]; i += 1 ) { isExcluded[i] = true; } }); } var shouldIndentNextCharacter = options.indentStart !== false; var replacer = function (match) { if ( shouldIndentNextCharacter ) { return ("" + indentStr + match); } shouldIndentNextCharacter = true; return match; }; this.intro = this.intro.replace( pattern, replacer ); var charIndex = 0; var chunk = this.firstChunk; while ( chunk ) { var end = chunk.end; if ( chunk.edited ) { if ( !isExcluded[ charIndex ] ) { chunk.content = chunk.content.replace( pattern, replacer ); if ( chunk.content.length ) { shouldIndentNextCharacter = chunk.content[ chunk.content.length - 1 ] === '\n'; } } } else { charIndex = chunk.start; while ( charIndex < end ) { if ( !isExcluded[ charIndex ] ) { var char = this$1.original[ charIndex ]; if ( char === '\n' ) { shouldIndentNextCharacter = true; } else if ( char !== '\r' && shouldIndentNextCharacter ) { shouldIndentNextCharacter = false; if ( charIndex === chunk.start ) { chunk.prependRight( indentStr ); } else { var rhs = chunk.split( charIndex ); rhs.prependRight( indentStr ); this$1.byStart[ charIndex ] = rhs; this$1.byEnd[ charIndex ] = chunk; chunk = rhs; } } } charIndex += 1; } } charIndex = chunk.end; chunk = chunk.next; } this.outro = this.outro.replace( pattern, replacer ); return this; }, insert: function insert () { throw new Error( 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)' ); }, insertLeft: function insertLeft ( index, content ) { if ( !warned.insertLeft ) { console.warn( 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead' ); // eslint-disable-line no-console warned.insertLeft = true; } return this.appendLeft( index, content ); }, insertRight: function insertRight ( index, content ) { if ( !warned.insertRight ) { console.warn( 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead' ); // eslint-disable-line no-console warned.insertRight = true; } return this.prependRight( index, content ); }, move: function move ( start, end, index ) { if ( index >= start && index <= end ) { throw new Error( 'Cannot move a selection inside itself' ); } this._split( start ); this._split( end ); this._split( index ); var first = this.byStart[ start ]; var last = this.byEnd[ end ]; var oldLeft = first.previous; var oldRight = last.next; var newRight = this.byStart[ index ]; if ( !newRight && last === this.lastChunk ) { return this; } var newLeft = newRight ? newRight.previous : this.lastChunk; if ( oldLeft ) { oldLeft.next = oldRight; } if ( oldRight ) { oldRight.previous = oldLeft; } if ( newLeft ) { newLeft.next = first; } if ( newRight ) { newRight.previous = last; } if ( !first.previous ) { this.firstChunk = last.next; } if ( !last.next ) { this.lastChunk = first.previous; this.lastChunk.next = null; } first.previous = newLeft; last.next = newRight; if ( !newLeft ) { this.firstChunk = first; } if ( !newRight ) { this.lastChunk = last; } return this; }, overwrite: function overwrite ( start, end, content, options ) { var this$1 = this; if ( typeof content !== 'string' ) { throw new TypeError( 'replacement content must be a string' ); } while ( start < 0 ) { start += this$1.original.length; } while ( end < 0 ) { end += this$1.original.length; } if ( end > this.original.length ) { throw new Error( 'end is out of bounds' ); } if ( start === end ) { throw new Error( 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead' ); } this._split( start ); this._split( end ); if ( options === true ) { if ( !warned.storeName ) { console.warn( 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string' ); // eslint-disable-line no-console warned.storeName = true; } options = { storeName: true }; } var storeName = options !== undefined ? options.storeName : false; var contentOnly = options !== undefined ? options.contentOnly : false; if ( storeName ) { var original = this.original.slice( start, end ); this.storedNames[ original ] = true; } var first = this.byStart[ start ]; var last = this.byEnd[ end ]; if ( first ) { if ( end > first.end && first.next !== this.byStart[ first.end ] ) { throw new Error( 'Cannot overwrite across a split point' ); } first.edit( content, storeName, contentOnly ); if ( last ) { first.next = last.next; } else { first.next = null; this.lastChunk = first; } first.original = this.original.slice( start, end ); first.end = end; } else { // must be inserting at the end var newChunk = new Chunk( start, end, '' ).edit( content, storeName ); // TODO last chunk in the array may not be the last chunk, if it's moved... last.next = newChunk; newChunk.previous = last; } return this; }, prepend: function prepend ( content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'outro content must be a string' ); } this.intro = content + this.intro; return this; }, prependLeft: function prependLeft ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byEnd[ index ]; if ( chunk ) { chunk.prependLeft( content ); } else { this.intro = content + this.intro; } return this; }, prependRight: function prependRight ( index, content ) { if ( typeof content !== 'string' ) { throw new TypeError( 'inserted content must be a string' ); } this._split( index ); var chunk = this.byStart[ index ]; if ( chunk ) { chunk.prependRight( content ); } else { this.outro = content + this.outro; } return this; }, remove: function remove ( start, end ) { var this$1 = this; while ( start < 0 ) { start += this$1.original.length; } while ( end < 0 ) { end += this$1.original.length; } if ( start === end ) { return this; } if ( start < 0 || end > this.original.length ) { throw new Error( 'Character is out of bounds' ); } if ( start > end ) { throw new Error( 'end must be greater than start' ); } this._split( start ); this._split( end ); var chunk = this.byStart[ start ]; while ( chunk ) { chunk.intro = ''; chunk.outro = ''; chunk.edit( '' ); chunk = end > chunk.end ? this$1.byStart[ chunk.end ] : null; } return this; }, slice: function slice ( start, end ) { var this$1 = this; if ( start === void 0 ) start = 0; if ( end === void 0 ) end = this.original.length; while ( start < 0 ) { start += this$1.original.length; } while ( end < 0 ) { end += this$1.original.length; } var result = ''; // find start chunk var chunk = this.firstChunk; while ( chunk && ( chunk.start > start || chunk.end <= start ) ) { // found end chunk before start if ( chunk.start < end && chunk.end >= end ) { return result; } chunk = chunk.next; } if ( chunk && chunk.edited && chunk.start !== start ) { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); } var startChunk = chunk; while ( chunk ) { if ( chunk.intro && ( startChunk !== chunk || chunk.start === start ) ) { result += chunk.intro; } var containsEnd = chunk.start < end && chunk.end >= end; if ( containsEnd && chunk.edited && chunk.end !== end ) { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); } var sliceStart = startChunk === chunk ? start - chunk.start : 0; var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length; result += chunk.content.slice( sliceStart, sliceEnd ); if ( chunk.outro && ( !containsEnd || chunk.end === end ) ) { result += chunk.outro; } if ( containsEnd ) { break; } chunk = chunk.next; } return result; }, // TODO deprecate this? not really very useful snip: function snip ( start, end ) { var clone = this.clone(); clone.remove( 0, start ); clone.remove( end, clone.original.length ); return clone; }, _split: function _split ( index ) { var this$1 = this; if ( this.byStart[ index ] || this.byEnd[ index ] ) { return; } var chunk = this.lastSearchedChunk; var searchForward = index > chunk.end; while ( true ) { if ( chunk.contains( index ) ) { return this$1._splitChunk( chunk, index ); } chunk = searchForward ? this$1.byStart[ chunk.end ] : this$1.byEnd[ chunk.start ]; } }, _splitChunk: function _splitChunk ( chunk, index ) { if ( chunk.edited && chunk.content.length ) { // zero-length edited chunks are a special case (overlapping replacements) var loc = getLocator( this.original )( index ); throw new Error( ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")") ); } var newChunk = chunk.split( index ); this.byEnd[ index ] = chunk; this.byStart[ index ] = newChunk; this.byEnd[ newChunk.end ] = newChunk; if ( chunk === this.lastChunk ) { this.lastChunk = newChunk; } this.lastSearchedChunk = chunk; return true; }, toString: function toString () { var str = this.intro; var chunk = this.firstChunk; while ( chunk ) { str += chunk.toString(); chunk = chunk.next; } return str + this.outro; }, trimLines: function trimLines () { return this.trim('[\\r\\n]'); }, trim: function trim ( charType ) { return this.trimStart( charType ).trimEnd( charType ); }, trimEnd: function trimEnd ( charType ) { var this$1 = this; var rx = new RegExp( ( charType || '\\s' ) + '+$' ); this.outro = this.outro.replace( rx, '' ); if ( this.outro.length ) { return this; } var chunk = this.lastChunk; do { var end = chunk.end; var aborted = chunk.trimEnd( rx ); // if chunk was trimmed, we have a new lastChunk if ( chunk.end !== end ) { this$1.lastChunk = chunk.next; this$1.byEnd[ chunk.end ] = chunk; this$1.byStart[ chunk.next.start ] = chunk.next; } if ( aborted ) { return this$1; } chunk = chunk.previous; } while ( chunk ); return this; }, trimStart: function trimStart ( charType ) { var this$1 = this; var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' ); this.intro = this.intro.replace( rx, '' ); if ( this.intro.length ) { return this; } var chunk = this.firstChunk; do { var end = chunk.end; var aborted = chunk.trimStart( rx ); if ( chunk.end !== end ) { // special case... if ( chunk === this$1.lastChunk ) { this$1.lastChunk = chunk.next; } this$1.byEnd[ chunk.end ] = chunk; this$1.byStart[ chunk.next.start ] = chunk.next; } if ( aborted ) { return this$1; } chunk = chunk.next; } while ( chunk ); return this; } }; var hasOwnProp = Object.prototype.hasOwnProperty; function Bundle ( options ) { if ( options === void 0 ) options = {}; this.intro = options.intro || ''; this.separator = options.separator !== undefined ? options.separator : '\n'; this.sources = []; this.uniqueSources = []; this.uniqueSourceIndexByFilename = {}; } Bundle.prototype = { addSource: function addSource ( source ) { if ( source instanceof MagicString$1 ) { return this.addSource({ content: source, filename: source.filename, separator: this.separator }); } if ( !isObject( source ) || !source.content ) { throw new Error( 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`' ); } [ 'filename', 'indentExclusionRanges', 'separator' ].forEach( function (option) { if ( !hasOwnProp.call( source, option ) ) { source[ option ] = source.content[ option ]; } }); if ( source.separator === undefined ) { // TODO there's a bunch of this sort of thing, needs cleaning up source.separator = this.separator; } if ( source.filename ) { if ( !hasOwnProp.call( this.uniqueSourceIndexByFilename, source.filename ) ) { this.uniqueSourceIndexByFilename[ source.filename ] = this.uniqueSources.length; this.uniqueSources.push({ filename: source.filename, content: source.content.original }); } else { var uniqueSource = this.uniqueSources[ this.uniqueSourceIndexByFilename[ source.filename ] ]; if ( source.content.original !== uniqueSource.content ) { throw new Error( ("Illegal source: same filename (" + (source.filename) + "), different contents") ); } } } this.sources.push( source ); return this; }, append: function append ( str, options ) { this.addSource({ content: new MagicString$1( str ), separator: ( options && options.separator ) || '' }); return this; }, clone: function clone () { var bundle = new Bundle({ intro: this.intro, separator: this.separator }); this.sources.forEach( function (source) { bundle.addSource({ filename: source.filename, content: source.content.clone(), separator: source.separator }); }); return bundle; }, generateMap: function generateMap ( options ) { var this$1 = this; if ( options === void 0 ) options = {}; var names = []; this.sources.forEach( function (source) { Object.keys( source.content.storedNames ).forEach( function (name) { if ( !~names.indexOf( name ) ) { names.push( name ); } }); }); var mappings = new Mappings( options.hires ); if ( this.intro ) { mappings.advance( this.intro ); } this.sources.forEach( function ( source, i ) { if ( i > 0 ) { mappings.advance( this$1.separator ); } var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[ source.filename ] : -1; var magicString = source.content; var locate = getLocator( magicString.original ); if ( magicString.intro ) { mappings.advance( magicString.intro ); } magicString.firstChunk.eachNext( function (chunk) { var loc = locate( chunk.start ); if ( chunk.intro.length ) { mappings.advance( chunk.intro ); } if ( source.filename ) { if ( chunk.edited ) { mappings.addEdit( sourceIndex, chunk.content, chunk.original, loc, chunk.storeName ? names.indexOf( chunk.original ) : -1 ); } else { mappings.addUneditedChunk( sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations ); } } else { mappings.advance( chunk.content ); } if ( chunk.outro.length ) { mappings.advance( chunk.outro ); } }); if ( magicString.outro ) { mappings.advance( magicString.outro ); } }); return new SourceMap({ file: ( options.file ? options.file.split( /[\/\\]/ ).pop() : null ), sources: this.uniqueSources.map( function (source) { return options.file ? getRelativePath( options.file, source.filename ) : source.filename; }), sourcesContent: this.uniqueSources.map( function (source) { return options.includeContent ? source.content : null; }), names: names, mappings: mappings.encode() }); }, getIndentString: function getIndentString () { var indentStringCounts = {}; this.sources.forEach( function (source) { var indentStr = source.content.indentStr; if ( indentStr === null ) { return; } if ( !indentStringCounts[ indentStr ] ) { indentStringCounts[ indentStr ] = 0; } indentStringCounts[ indentStr ] += 1; }); return ( Object.keys( indentStringCounts ).sort( function ( a, b ) { return indentStringCounts[a] - indentStringCounts[b]; })[0] ) || '\t'; }, indent: function indent ( indentStr ) { var this$1 = this; if ( !arguments.length ) { indentStr = this.getIndentString(); } if ( indentStr === '' ) { return this; } // noop var trailingNewline = !this.intro || this.intro.slice( -1 ) === '\n'; this.sources.forEach( function ( source, i ) { var separator = source.separator !== undefined ? source.separator : this$1.separator; var indentStart = trailingNewline || ( i > 0 && /\r?\n$/.test( separator ) ); source.content.indent( indentStr, { exclude: source.indentExclusionRanges, indentStart: indentStart//: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator ) }); // TODO this is a very slow way to determine this trailingNewline = source.content.toString().slice( 0, -1 ) === '\n'; }); if ( this.intro ) { this.intro = indentStr + this.intro.replace( /^[^\n]/gm, function ( match, index ) { return index > 0 ? indentStr + match : match; }); } return this; }, prepend: function prepend ( str ) { this.intro = str + this.intro; return this; }, toString: function toString () { var this$1 = this; var body = this.sources.map( function ( source, i ) { var separator = source.separator !== undefined ? source.separator : this$1.separator; var str = ( i > 0 ? separator : '' ) + source.content.toString(); return str; }).join( '' ); return this.intro + body; }, trimLines: function trimLines () { return this.trim('[\\r\\n]'); }, trim: function trim ( charType ) { return this.trimStart( charType ).trimEnd( charType ); }, trimStart: function trimStart ( charType ) { var this$1 = this; var rx = new RegExp( '^' + ( charType || '\\s' ) + '+' ); this.intro = this.intro.replace( rx, '' ); if ( !this.intro ) { var source; var i = 0; do { source = this$1.sources[i]; if ( !source ) { break; } source.content.trimStart( charType ); i += 1; } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source? } return this; }, trimEnd: function trimEnd ( charType ) { var this$1 = this; var rx = new RegExp( ( charType || '\\s' ) + '+$' ); var source; var i = this.sources.length - 1; do { source = this$1.sources[i]; if ( !source ) { this$1.intro = this$1.intro.replace( rx, '' ); break; } source.content.trimEnd( charType ); i -= 1; } while ( source.content.toString() === '' ); // TODO faster way to determine non-empty source? return this; } }; export { Bundle };export default MagicString$1; //# sourceMappingURL=magic-string.es.js.map
ocadni/citychrone
.build/bundle/programs/server/npm/node_modules/meteor/server-render/node_modules/magic-string/dist/magic-string.es.js
JavaScript
mit
32,718
export * from './PostProcessor.js'; export * from './EffectComposer.js'; export * from './pass/index.js'; export * from './shader/index.js';
thejmazz/whitestorm.js
src/framework/components/rendering/post-processing/index.js
JavaScript
mit
141
'use strict'; module.exports = function intervalTime(startIntervalTime){ return function(done){ var endTime = Date.now(); var runTime = endTime - startIntervalTime; done(null,{'intervalTime': runTime}); }; };
markmontymark/mined
lib/fn/intervalTime.js
JavaScript
mit
227
/** * description * Author: Oded Sagir * @param Object require for adding dependencies * @return Object Class Object */ define(function(require) { var database = { posts: require("text!api/posts.json") }; return database; });
hamecoded/Backbone-Require-Boilerplate
public/api/database.js
JavaScript
mit
267
/* http://prismjs.com/download.html?themes=prism&languages=git&plugins=line-numbers */ self = (typeof window !== 'undefined') ? window // if in browser : ( (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) ? self // if in worker : {} // if in node js ); /** * Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * @author Lea Verou http://lea.verou.me */ var Prism = (function(){ // Private helper vars var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i; var _ = self.Prism = { util: { encode: function (tokens) { if (tokens instanceof Token) { return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); } else if (_.util.type(tokens) === 'Array') { return tokens.map(_.util.encode); } else { return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' '); } }, type: function (o) { return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1]; }, // Deep clone a language definition (e.g. to extend it) clone: function (o) { var type = _.util.type(o); switch (type) { case 'Object': var clone = {}; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = _.util.clone(o[key]); } } return clone; case 'Array': return o.map(function(v) { return _.util.clone(v); }); } return o; } }, languages: { extend: function (id, redef) { var lang = _.util.clone(_.languages[id]); for (var key in redef) { lang[key] = redef[key]; } return lang; }, /** * Insert a token before another token in a language literal * As this needs to recreate the object (we cannot actually insert before keys in object literals), * we cannot just provide an object, we need anobject and a key. * @param inside The key (or language id) of the parent * @param before The key to insert before. If not provided, the function appends instead. * @param insert Object with the key/value pairs to insert * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted. */ insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; if (arguments.length == 2) { insert = arguments[1]; for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { grammar[newToken] = insert[newToken]; } } return grammar; } var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } // Update references in other language definitions _.languages.DFS(_.languages, function(key, value) { if (value === root[inside] && key != inside) { this[key] = ret; } }); return root[inside] = ret; }, // Traverse a language definition with Depth First Search DFS: function(o, callback, type) { for (var i in o) { if (o.hasOwnProperty(i)) { callback.call(o, i, o[i], type || i); if (_.util.type(o[i]) === 'Object') { _.languages.DFS(o[i], callback); } else if (_.util.type(o[i]) === 'Array') { _.languages.DFS(o[i], callback, i); } } } } }, highlightAll: function(async, callback) { var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'); for (var i=0, element; element = elements[i++];) { _.highlightElement(element, async === true, callback); } }, highlightElement: function(element, async, callback) { // Find language var language, grammar, parent = element; while (parent && !lang.test(parent.className)) { parent = parent.parentNode; } if (parent) { language = (parent.className.match(lang) || [,''])[1]; grammar = _.languages[language]; } if (!grammar) { return; } // Set language on the element, if not present element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; // Set language on the parent, for styling parent = element.parentNode; if (/pre/i.test(parent.nodeName)) { parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; } var code = element.textContent; if(!code) { return; } code = code.replace(/^(?:\r?\n|\r)/,''); var env = { element: element, language: language, grammar: grammar, code: code }; _.hooks.run('before-highlight', env); if (async && self.Worker) { var worker = new Worker(_.filename); worker.onmessage = function(evt) { env.highlightedCode = Token.stringify(JSON.parse(evt.data), language); _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(env.element); _.hooks.run('after-highlight', env); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code })); } else { env.highlightedCode = _.highlight(env.code, env.grammar, env.language); _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(element); _.hooks.run('after-highlight', env); } }, highlight: function (text, grammar, language) { var tokens = _.tokenize(text, grammar); return Token.stringify(_.util.encode(tokens), language); }, tokenize: function(text, grammar, language) { var Token = _.Token; var strarr = [text]; var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } tokenloop: for (var token in grammar) { if(!grammar.hasOwnProperty(token) || !grammar[token]) { continue; } var patterns = grammar[token]; patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns]; for (var j = 0; j < patterns.length; ++j) { var pattern = patterns[j], inside = pattern.inside, lookbehind = !!pattern.lookbehind, lookbehindLength = 0, alias = pattern.alias; pattern = pattern.pattern || pattern; for (var i=0; i<strarr.length; i++) { // Don’t cache length as it changes during the loop var str = strarr[i]; if (strarr.length > text.length) { // Something went terribly wrong, ABORT, ABORT! break tokenloop; } if (str instanceof Token) { continue; } pattern.lastIndex = 0; var match = pattern.exec(str); if (match) { if(lookbehind) { lookbehindLength = match[1].length; } var from = match.index - 1 + lookbehindLength, match = match[0].slice(lookbehindLength), len = match.length, to = from + len, before = str.slice(0, from + 1), after = str.slice(to + 1); var args = [i, 1]; if (before) { args.push(before); } var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias); args.push(wrapped); if (after) { args.push(after); } Array.prototype.splice.apply(strarr, args); } } } } return strarr; }, hooks: { all: {}, add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); }, run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i=0, callback; callback = callbacks[i++];) { callback(env); } } } }; var Token = _.Token = function(type, content, alias) { this.type = type; this.content = content; this.alias = alias; }; Token.stringify = function(o, language, parent) { if (typeof o == 'string') { return o; } if (_.util.type(o) === 'Array') { return o.map(function(element) { return Token.stringify(element, language, o); }).join(''); } var env = { type: o.type, content: Token.stringify(o.content, language, parent), tag: 'span', classes: ['token', o.type], attributes: {}, language: language, parent: parent }; if (env.type == 'comment') { env.attributes['spellcheck'] = 'true'; } if (o.alias) { var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); var attributes = ''; for (var name in env.attributes) { attributes += name + '="' + (env.attributes[name] || '') + '"'; } return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>'; }; if (!self.document) { if (!self.addEventListener) { // in Node.js return self.Prism; } // In worker self.addEventListener('message', function(evt) { var message = JSON.parse(evt.data), lang = message.language, code = message.code; self.postMessage(JSON.stringify(_.util.encode(_.tokenize(code, _.languages[lang])))); self.close(); }, false); return self.Prism; } // Get current script and highlight var script = document.getElementsByTagName('script'); script = script[script.length - 1]; if (script) { _.filename = script.src; if (document.addEventListener && !script.hasAttribute('data-manual')) { document.addEventListener('DOMContentLoaded', _.highlightAll); } } return self.Prism; })(); if (typeof module !== 'undefined' && module.exports) { module.exports = Prism; } ; Prism.languages.git = { /* * A simple one line comment like in a git status command * For instance: * $ git status * # On branch infinite-scroll * # Your branch and 'origin/sharedBranches/frontendTeam/infinite-scroll' have diverged, * # and have 1 and 2 different commits each, respectively. * nothing to commit (working directory clean) */ 'comment': /^#.*$/m, /* * a string (double and simple quote) */ 'string': /("|')(\\?.)*?\1/m, /* * a git command. It starts with a random prompt finishing by a $, then "git" then some other parameters * For instance: * $ git add file.txt */ 'command': { pattern: /^.*\$ git .*$/m, inside: { /* * A git command can contain a parameter starting by a single or a double dash followed by a string * For instance: * $ git diff --cached * $ git log -p */ 'parameter': /\s(--|-)\w+/m } }, /* * Coordinates displayed in a git diff command * For instance: * $ git diff * diff --git file.txt file.txt * index 6214953..1d54a52 100644 * --- file.txt * +++ file.txt * @@ -1 +1,2 @@ * -Here's my tetx file * +Here's my text file * +And this is the second line */ 'coord': /^@@.*@@$/m, /* * Regexp to match the changed lines in a git diff output. Check the example above. */ 'deleted': /^-(?!-).+$/m, 'inserted': /^\+(?!\+).+$/m, /* * Match a "commit [SHA1]" line in a git log output. * For instance: * $ git log * commit a11a14ef7e26f2ca62d4b35eac455ce636d0dc09 * Author: lgiraudel * Date: Mon Feb 17 11:18:34 2014 +0100 * * Add of a new line */ 'commit_sha1': /^commit \w{40}$/m }; ; Prism.hooks.add('after-highlight', function (env) { // works only for <code> wrapped inside <pre data-line-numbers> (not inline) var pre = env.element.parentNode; if (!pre || !/pre/i.test(pre.nodeName) || pre.className.indexOf('line-numbers') === -1) { return; } var linesNum = (1 + env.code.split('\n').length); var lineNumbersWrapper; var lines = new Array(linesNum); lines = lines.join('<span></span>'); lineNumbersWrapper = document.createElement('span'); lineNumbersWrapper.className = 'line-numbers-rows'; lineNumbersWrapper.innerHTML = lines; if (pre.hasAttribute('data-start')) { pre.style.counterReset = 'linenumber ' + (parseInt(pre.getAttribute('data-start'), 10) - 1); } env.element.appendChild(lineNumbersWrapper); });;
TimothyGu/fateserver-node
public/js/prism.js
JavaScript
mit
12,087
const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const { validateSignInForm, isLoggedIn } = require('../middlewares/validation'); const { signOutUser } = require('../../models/helper-functions'); const user = require('../../models/users'); const reviews = require('../../models/reviews'); const urlEncodedParser = bodyParser.urlencoded({ extended: false }); router.get('/sign-up', (req, res) => { res.render('sign-up', { error: false }); }); router.route('/sign-in') .get((req, res) => { res.render('sign-in', { error: false }); }) .post(urlEncodedParser, validateSignInForm, (req, res, next) => { const credentials = req.body; user.loginByEmail(credentials, req) .then((user) => { res.redirect(`users/${user.id}`); }) .catch((error) => { console.log('An error occured while logging in user::', error); next(new Error('incorrect email and/or password')); }) }); router.get('/sign-out', (req, res) => { signOutUser(req); res.redirect('/?isloggedIn=false'); }) module.exports = router;
zubairnahmed/phase-4-challenge
src/server/routes/authentication.js
JavaScript
mit
1,128
define(function(require,exports,module){"use strict";var PreferencesManager=brackets.getModule("preferences/PreferencesManager");PreferencesManager.set("openSVGasXML",true)});
shellyginelle/Code-With-Venus
Old/dist/extensions/extra/SVGasXML/main.js
JavaScript
mit
175
define(function () { return { registerExtenders: registerExtenders }; function registerExtenders() { registerDateBinding(); registerMoneyExtension(); } function registerDateBinding () { ko.bindingHandlers.dateString = { //Credit to Ryan Rahlf http://stackoverflow.com/questions/17001303/date-formatting-issues-with-knockout-and-syncing-to-breeze-js-entityaspect-modif init: function (element, valueAccessor) { //attach an event handler to our dom element to handle user input element.onchange = function () { var value = valueAccessor();//get our observable //set our observable to the parsed date from the input value(moment(element.value).toDate()); }; }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var value = valueAccessor(); var valueUnwrapped = ko.utils.unwrapObservable(value); if (valueUnwrapped) { element.value = moment(valueUnwrapped).format('L'); } } }; } function registerMoneyExtension() { //Credit to Josh Bush http://freshbrewedcode.com/joshbush/2011/12/27/knockout-js-observable-extensions/ var format = function (value) { toks = value.toFixed(2).replace('-', '').split('.'); var display = '$' + $.map(toks[0].split('').reverse(), function (elm, i) { return [(i % 3 === 0 && i > 0 ? ',' : ''), elm]; }).reverse().join('') + '.' + toks[1]; return value < 0 ? '(' + display + ')' : display; }; ko.subscribable.fn.money = function () { var target = this; var writeTarget = function (value) { target(parseFloat(value.replace(/[^0-9.-]/g, ''))); }; var result = ko.computed({ read: function () { return target(); }, write: writeTarget }); result.formatted = ko.computed({ read: function () { return format(target()); }, write: writeTarget }); return result; }; } });
michaelcodes/HotTowel-Durandal2-Northwind-Sample
HotTowelNorthwind/App/utils/knockoutExtenders.js
JavaScript
mit
2,399
'use strict'; /* * AngularJS Toaster * Version: 0.4.4 * * Copyright 2013 Jiri Kavulak. * All Rights Reserved. * Use, reproduction, distribution, and modification of this code is subject to the terms and * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php * * Author: Jiri Kavulak * Related to project of John Papa and Hans Fjällemark */ angular.module('toaster', ['ngAnimate']) .service('toaster', ['$rootScope', function ($rootScope) { this.pop = function (type, title, body, timeout, bodyOutputType) { this.toast = { type: type, title: title, body: body, timeout: timeout, bodyOutputType: bodyOutputType }; $rootScope.$broadcast('toaster-newToast'); }; this.clear = function () { $rootScope.$broadcast('toaster-clearToasts'); }; }]) .constant('toasterConfig', { 'limit': 0, // limits max number of toasts 'tap-to-dismiss': true, 'newest-on-top': true, //'fade-in': 1000, // done in css //'on-fade-in': undefined, // not implemented //'fade-out': 1000, // done in css // 'on-fade-out': undefined, // not implemented //'extended-time-out': 1000, // not implemented 'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky 'icon-classes': { error: 'toast-error', info: 'toast-info', success: 'toast-success', warning: 'toast-warning' }, 'body-output-type': '', // Options: '', 'trustedHtml', 'template' 'body-template': 'toasterBodyTmpl.html', 'icon-class': 'toast-info', 'position-class': 'toast-bottom-left', 'title-class': 'toast-title', 'message-class': 'toast-message' }) .directive('toasterContainer', ['$compile', '$timeout', '$sce', 'toasterConfig', 'toaster', function ($compile, $timeout, $sce, toasterConfig, toaster) { return { replace: true, restrict: 'EA', link: function (scope, elm, attrs) { var id = 0; var mergedConfig = toasterConfig; if (attrs.toasterOptions) { angular.extend(mergedConfig, scope.$eval(attrs.toasterOptions)); } scope.config = { position: mergedConfig['position-class'], title: mergedConfig['title-class'], message: mergedConfig['message-class'], tap: mergedConfig['tap-to-dismiss'] }; scope.configureTimer = function configureTimer(toast) { var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out']; if (timeout > 0) setTimeout(toast, timeout); }; function addToast(toast) { toast.type = mergedConfig['icon-classes'][toast.type]; if (!toast.type) toast.type = mergedConfig['icon-class']; id++; angular.extend(toast, { id: id }); // Set the toast.bodyOutputType to the default if it isn't set toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type']; switch (toast.bodyOutputType) { case 'trustedHtml': toast.html = $sce.trustAsHtml(toast.body); break; case 'template': toast.bodyTemplate = toast.body || mergedConfig['body-template']; break; } scope.configureTimer(toast); if (mergedConfig['newest-on-top'] === true) { scope.toasters.unshift(toast); if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) { scope.toasters.pop(); } } else { scope.toasters.push(toast); if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) { scope.toasters.shift(); } } } function setTimeout(toast, time) { toast.timeout = $timeout(function () { scope.removeToast(toast.id); }, time); } scope.toasters = []; scope.$on('toaster-newToast', function () { addToast(toaster.toast); }); scope.$on('toaster-clearToasts', function () { scope.toasters.splice(0, scope.toasters.length); }); }, controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) { $scope.stopTimer = function (toast) { if (toast.timeout) { $timeout.cancel(toast.timeout); toast.timeout = null; } }; $scope.restartTimer = function (toast) { if (!toast.timeout) $scope.configureTimer(toast); }; $scope.removeToast = function (id) { var i = 0; for (i; i < $scope.toasters.length; i++) { if ($scope.toasters[i].id === id) break; } $scope.toasters.splice(i, 1); }; $scope.remove = function (id) { if ($scope.config.tap === true) { $scope.removeToast(id); } }; }], template: '<div id="toast-container" ng-class="config.position">' + '<div ng-repeat="toaster in toasters" class="toast" ng-class="toaster.type" ng-click="remove(toaster.id)" ng-mouseover="stopTimer(toaster)" ng-mouseout="restartTimer(toaster)">' + '<div ng-class="config.title">{{toaster.title}}</div>' + '<div ng-class="config.message" ng-switch on="toaster.bodyOutputType">' + '<div ng-switch-when="trustedHtml" ng-bind-html="toaster.html"></div>' + '<div ng-switch-when="template"><div ng-include="toaster.bodyTemplate"></div></div>' + '<div ng-switch-default >{{toaster.body}}</div>' + '</div>' + '</div>' + '</div>' }; }]);
xyzstarr/Rewards
BMW_Colleague_Rewards/www/lib/toaster/toaster.js
JavaScript
mit
6,452
/*! * Redback * Copyright(c) 2011 Chris O'Hara <cohara87@gmail.com> * MIT Licensed */ /** * Module dependencies. */ var Structure = require('../Structure'); /** * See https://gist.github.com/chriso/54dd46b03155fcf555adccea822193da * * Count the number of times a subject performs an action over an interval * in the immediate past - this can be used to rate limit the subject if * the count goes over a certain threshold. For example, you could track * how many times an IP (the subject) has viewed a page (the action) over * a certain time frame and limit them accordingly. * * Usage: * `redback.createRateLimit(action [, options]);` * * Options: * `bucket_interval` - default is 5 seconds * `bucket_span` - default is 10 minutes * `subject_expiry` - default is 20 minutes * * Reference: * https://gist.github.com/chriso/54dd46b03155fcf555adccea822193da * http://redis.io/topics/data-types#hash * * Redis Structure: * `(namespace:)action:<subject1> = hash(bucket => count)` * `(namespace:)action:<subject2> = hash(bucket => count)` * `(namespace:)action:<subjectN> = hash(bucket => count)` */ var RateLimit = exports.RateLimit = Structure.new(); /** * Setup the RateLimit structure. * * @param {Object} options (optional) * @api private */ RateLimit.prototype.init = function (options) { options = options || {}; this.bucket_span = options.bucket_span || 600; this.bucket_interval = options.bucket_interval || 5; this.subject_expiry = options.subject_expiry || 1200; this.bucket_count = Math.round(this.bucket_span / this.bucket_interval); } /** * Get the bucket associated with the current time. * * @param {int} time (optional) - default is the current time (ms since epoch) * @return {int} bucket * @api private */ RateLimit.prototype.getBucket = function (time) { time = (time || new Date().getTime()) / 1000; return Math.floor((time % this.bucket_span) / this.bucket_interval); } /** * Increment the count for the specified subject. * * @param {string} subject * @param {Function} callback (optional) * @return this * @api public */ RateLimit.prototype.add = function (subject, callback) { if (Array.isArray(subject)) { return this.addAll(subject, callback); } var bucket = this.getBucket(), multi = this.client.multi(); subject = this.key + ':' + subject; //Increment the current bucket multi.hincrby(subject, bucket, 1) //Clear the buckets ahead multi.hdel(subject, (bucket + 1) % this.bucket_count) .hdel(subject, (bucket + 2) % this.bucket_count) //Renew the key TTL multi.expire(subject, this.subject_expiry); multi.exec(function (err) { if (!callback) return; if (err) return callback(err); callback(null); }); return this; } /** * Count the number of times the subject has performed an action * in the last `interval` seconds. * * @param {string} subject * @param {int} interval * @param {Function} callback * @return this * @api public */ RateLimit.prototype.count = function (subject, interval, callback) { var bucket = this.getBucket(), multi = this.client.multi(), count = Math.floor(interval / this.bucket_interval); subject = this.key + ':' + subject; //Get the counts from the previous `count` buckets multi.hget(subject, bucket); while (count--) { multi.hget(subject, (--bucket + this.bucket_count) % this.bucket_count); } //Add up the counts from each bucket multi.exec(function (err, counts) { if (err) return callback(err, null); for (var count = 0, i = 0, l = counts.length; i < l; i++) { if (counts[i]) { count += parseInt(counts[i], 10); } } callback(null, count); }); return this; } /** * An alias for `ratelimit.add(subject).count(subject, interval);` * * @param {string} subject * @param {int} interval * @param {Function} callback * @return this * @api public */ RateLimit.prototype.addCount = function (subject, interval, callback) { var bucket = this.getBucket(), multi = this.client.multi(), count = Math.floor(interval / this.bucket_interval); subject = this.key + ':' + subject; //Increment the current bucket multi.hincrby(subject, bucket, 1) //Clear the buckets ahead multi.hdel(subject, (bucket + 1) % this.bucket_count) .hdel(subject, (bucket + 2) % this.bucket_count) //Renew the key TTL multi.expire(subject, this.subject_expiry); //Get the counts from the previous `count` buckets multi.hget(subject, bucket); while (count--) { multi.hget(subject, (--bucket + this.bucket_count) % this.bucket_count); } //Add up the counts from each bucket multi.exec(function (err, counts) { if (err) return callback(err, null); for (var count = 0, i = 4, l = counts.length; i < l; i++) { if (counts[i]) { count += parseInt(counts[i], 10); } } callback(null, count); }); return this; }
chriso/redback
lib/advanced_structures/RateLimit.js
JavaScript
mit
5,167
var _ = require('lodash') var assert = require('assert') var common = require('./common') module.exports = function() { var adapter = { wrap: column => `"${column}"` } adapter.createTimestamps = function(data, options) { options = options || {} var table = this.wrap(data.identity.name) var schema = options.schema || 'public' return this.db .query( 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE ' + "TABLE_NAME='" + data.identity.name + "' AND COLUMN_NAME='updated_at' AND " + "TABLE_CATALOG=current_database() AND TABLE_SCHEMA='" + schema + "'", null, options ) .then(recordset => { if (recordset.length === 0) { return this.db.execute( `ALTER TABLE ${table} ADD ${this.wrap( 'updated_at' )} TIMESTAMP(3) WITHOUT TIME ZONE`, null, options ) } }) } adapter.buildInsertCommand = function(data) { data.insertCommand = `INSERT INTO ${this.wrap( data.identity.name )} (<fields>${data.timestamps ? `,"updated_at"` : ''}) VALUES (<values>${ data.timestamps ? `,(now() at time zone 'utc')` : '' }) RETURNING *` } adapter.buildUpdateCommand = function(data) { data.updateCommand = `UPDATE ${this.wrap( data.identity.name )} SET <fields-values>${ data.timestamps ? `,"updated_at"=(now() at time zone 'utc')` : '' } WHERE <primary-keys> RETURNING *` } adapter.buildDeleteCommand = function(data) { data.deleteCommand = 'DELETE FROM ' + this.wrap(data.identity.name) + ' WHERE <find-keys> RETURNING *' } adapter.create = common.create adapter.update = common.update adapter.destroy = common.destroy adapter.extractRecordset = function(jsonset, coerce) { assert(_.isArray(jsonset), 'jsonset is not an array') _.forEach(jsonset, function(record) { coerce.map(function(coercion) { const value = record[coercion.property] if (value === void 0) { record[coercion.property] = null } else if (value !== null) { record[coercion.property] = coercion.fn(record[coercion.property]) } }) }) return jsonset } adapter.buildQuery = function buildQuery(data, options, isAssociation) { var fields = [] _.forEach( data.properties, function(property, name) { var fieldName = property.field || name var alias = name fields.push( this.wrap(fieldName) + (alias !== fieldName ? ' AS ' + this.wrap(alias) : '') ) if ( options.fetchExternalDescription && property.display && property.schema && property.schema.$ref && property.schema.key ) { let display = property.display const point = display.indexOf('.') if (point > -1) { display = display.substr(point + 1) } fields.push( `(select "${display}" FROM "${property.schema.$ref}" where "${ property.schema.key }"="${data.key}"."${fieldName}") as "${_.camelCase( `${data.identity.name} ${name} ${display}` )}"` ) } }.bind(this) ) if (data.timestamps) { fields.push(this.wrap('updated_at')) } _.forEach( data.associations, function(association) { if (!association.data.foreignKey) { return false } const query = this.buildQuery(association.data, options, true) var foreignKey = association.data.properties[association.data.foreignKey].field || association.data.foreignKey fields.push( '(select array_to_json(array_agg(row_to_json(t))) from (' + query + ' WHERE ' + this.wrap(foreignKey) + '=' + this.wrap(data.key) + '.' + this.wrap(data.primaryKeyFields[0]) + ' ORDER BY ' + ( association.data.primaryOrderFields || association.data.primaryKeyFields ) .map(this.wrap.bind(this)) .join() + ') t) AS ' + this.wrap(association.data.key) ) }.bind(this) ) let fetchCommand = 'SELECT ' + fields.join(',') + ' FROM ' + this.wrap(data.identity.name) + ' AS ' + this.wrap(data.key) if (options.schema && !isAssociation) { fetchCommand = fetchCommand.replace( /" FROM "/g, `" FROM ${options.schema}."` ) } return fetchCommand } adapter.getCoercionFunction = function(type, timezone) { switch (type) { case 'datetime': return function(value) { if (timezone === 'ignore') { var d = new Date(value + 'Z') return new Date(d.getTime() + d.getTimezoneOffset() * 60000) } else { return new Date(value) } } default: return function(value) { return value } } } return adapter }
andrglo/json-schema-entity
src/adapters/postgres.js
JavaScript
mit
5,239
module.exports = function( grunt ) { // Project configuration. grunt.initConfig( { pkg : grunt.file.readJSON( "bower.json" ), jshint : { options : { jshintrc : true }, src : { src : [ "src/*.js" ] } }, uglify : { js : { src : "src/<%= pkg.name %>.js", dest : "dist/<%= pkg.name %>.min.js" } }, watch : { files : [ "src/*.js" ], tasks : [ "jshint" ] } } ); grunt.loadNpmTasks( "grunt-contrib-jshint" ); grunt.loadNpmTasks( "grunt-contrib-uglify" ); grunt.loadNpmTasks( "grunt-contrib-watch" ); grunt.registerTask( "default", [ "jshint", "uglify" ] ); };
oliversalzburg/ng-i18n-node
Gruntfile.js
JavaScript
mit
659
export function initialize(application) { application.inject('route', 'session', 'service:session'); application.inject('route', 'sessionAccount', 'service:session-account'); application.inject('controller', 'session', 'service:session'); application.inject('controller', 'sessionAccount', 'service:session-account'); application.inject('component', 'session', 'service:session'); application.inject('component', 'sessionAccount', 'service:session-account'); } export default { name: 'session', after: 'ember-simple-auth', initialize };
campus-discounts/embersy
embersy-frontend/app/initializers/session.js
JavaScript
mit
556
import Canvas from '../tool/Canvas.js'; import Animation from './Animation/Animation.js'; import Frame from './Animation/Frame.js'; import Player from '../engine/Player.js'; class Avatar { static radius = 360; static shakeTime = 300; constructor(player, direction) { this.player = player; this.idle = Avatar.createLozange('#FFFD1B', '#BCBB14', 1, direction, 0.5, 0.75, 0.25); this.idleShadow = Avatar.createLozange('#000000', '#000000', 0.1, direction, 0.5, 0.75, 0.25); this.thrust = Avatar.createLozange('#F5DF0E', '#AB9B0A', 1, direction, 0.25, 1, 0.25); this.thrustShadow = Avatar.createLozange('#000000', '#000000', 0.1, direction, 0.25, 1, 0.25); this.shake = 0; this.shakeTimout = null; this.startShake = this.startShake.bind(this); this.endShake = this.endShake.bind(this); this.player.setWallEventListener(this.startShake); } static createFrames(color, colorDark, direction) { const size = Avatar.radius * 2; const canvas = new Canvas(size, size); const context = canvas.context(); let frames = [ ]; } static createLozange(color, colorDark, alpha, direction, height, body, head) { const canvasWidth = 2; const canvasHeight = 2; const size = Avatar.radius * 2; const canvas = new Canvas(size * canvasWidth, size * canvasHeight); const context = canvas.context; const center = { x: canvasWidth / 2, y: canvasHeight / 2 }; const top = { x: center.x, y: center.y - (height / 2) }; const right = { x: center.x + head, y: center.y } const bottom = { x: center.x, y: top.y + height }; const left = { x: center.x - body, y: center.y }; if (direction) { canvas.reverse(); } context.scale(size, size); canvas.setAlpha(alpha); canvas.setFill(color); context.beginPath(); context.moveTo(left.x, left.y); context.lineTo(top.x, top.y); context.lineTo(right.x, right.y); context.fill(); canvas.setFill(colorDark); context.beginPath(); context.moveTo(left.x, left.y); context.lineTo(bottom.x, bottom.y); context.lineTo(right.x, right.y); context.fill(); if (direction) { canvas.reverse(); } return canvas; } startShake() { this.shake = Date.now(); this.shakeTimout = setTimeout(this.endShake, Avatar.shakeTime); } endShake() { this.shake = false; clearTimeout(this.shakeTimout); } getShake() { if (!this.shake) { return 0; } const time = (Date.now() - this.shake) / Avatar.shakeTime * 4 * Math.PI; return Math.cos(time) * Avatar.radius / 25; } draw() { return this.player.thrusting ? this.thrust.element : this.idle.element; } drawShadow() { return this.player.thrusting ? this.thrustShadow.element : this.idleShadow.element; } getSize() { const ratio = 1 + (this.player.getSpeedRatio() - 1) * 0.5; return Avatar.radius / devicePixelRatio * ratio; } getDropShadow() { return Avatar.radius * 0.1; } } export default Avatar;
thrustgame/thrust
src/view/Avatar.js
JavaScript
mit
3,325
const PlotCard = require('../../plotcard.js'); class TheSpidersWeb extends PlotCard { setupCardAbilities(ability) { this.reaction({ limit: ability.limit.perPhase(1), when: { onClaimApplied: event => event.player === this.controller && event.challenge.challengeType === 'intrigue' }, handler: () => { this.game.addMessage('{0} uses {1} to be able to initiate an additional {2} challenge with claim raised by 1', this.controller, this, 'intrigue'); this.untilEndOfPhase(ability => ({ targetController: 'current', effect: ability.effects.mayInitiateAdditionalChallenge('intrigue') })); this.untilEndOfPhase(ability =>({ condition: () => this.game.isDuringChallenge({ challengeType: 'intrigue' }), match: card => card === this.controller.activePlot, effect: ability.effects.modifyClaim(1) })); } }); } } TheSpidersWeb.code = '09049'; module.exports = TheSpidersWeb;
DukeTax/throneteki
server/game/cards/09-HoT/TheSpidersWeb.js
JavaScript
mit
1,145
// All code points in the Buginese block as per Unicode v5.1.0: [ 0x1A00, 0x1A01, 0x1A02, 0x1A03, 0x1A04, 0x1A05, 0x1A06, 0x1A07, 0x1A08, 0x1A09, 0x1A0A, 0x1A0B, 0x1A0C, 0x1A0D, 0x1A0E, 0x1A0F, 0x1A10, 0x1A11, 0x1A12, 0x1A13, 0x1A14, 0x1A15, 0x1A16, 0x1A17, 0x1A18, 0x1A19, 0x1A1A, 0x1A1B, 0x1A1C, 0x1A1D, 0x1A1E, 0x1A1F ];
mathiasbynens/unicode-data
5.1.0/blocks/Buginese-code-points.js
JavaScript
mit
355
'use strict'; 'use strict'; angular.module('appModule', [ 'ngRoute', 'appControllers' ]) .config(function($routeProvider) { $routeProvider.when('/home', { controller : 'SettingCtrl', templateUrl : '/views/public/setting.html' }).when('/postcodes', { controller : 'PostCodeCtrl', templateUrl : '/views/postcode/list.html' }).when('/postcode/:id', { controller : 'PostCodeEditCtrl', templateUrl : '/views/postcode/detail.html' }).otherwise({ redirectTo : '/home' }); });
vollov/angularjs-crud
client/app/js/app.js
JavaScript
mit
504
'use strict'; const assert = require('assert'); const context = require('../helpers/context'); describe('ctx.search=', () => { it('should replace the search', () => { const ctx = context({ url: '/store/shoes' }); ctx.search = '?page=2&color=blue'; assert.equal(ctx.url, '/store/shoes?page=2&color=blue'); assert.equal(ctx.search, '?page=2&color=blue'); }); it('should update ctx.querystring and ctx.query', () => { const ctx = context({ url: '/store/shoes' }); ctx.search = '?page=2&color=blue'; assert.equal(ctx.url, '/store/shoes?page=2&color=blue'); assert.equal(ctx.querystring, 'page=2&color=blue'); assert.equal(ctx.query.page, '2'); assert.equal(ctx.query.color, 'blue'); }); it('should change .url but not .originalUrl', () => { const ctx = context({ url: '/store/shoes' }); ctx.search = '?page=2&color=blue'; assert.equal(ctx.url, '/store/shoes?page=2&color=blue'); assert.equal(ctx.originalUrl, '/store/shoes'); assert.equal(ctx.request.originalUrl, '/store/shoes'); }); describe('when missing', () => { it('should return ""', () => { const ctx = context({ url: '/store/shoes' }); assert.equal(ctx.search, ''); }); }); });
fl0w/koa
test/request/search.js
JavaScript
mit
1,235
/* Thing > Intangible > Enumeration > WarrantyScope - A range of of services that will be provided to a customer free of charge in case of a defect or malfunction of a product. Commonly used values: http://purl.org/goodrelations/v1#Labor-BringIn http://purl.org/goodrelations/v1#PartsAndLabor-BringIn http://purl.org/goodrelations/v1#PartsAndLabor-PickUp. Generated automatically by the reactGenerator. */ var WarrantyScope= React.createClass({ getDefaultProps: function(){ return { } }, render: function(){ var props = this.props.props; var potentialAction; if( props.potentialAction ){ if( props.potentialAction instanceof Array ){ potentialAction = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] potentialAction = potentialAction.concat( props.potentialAction.map( function(result, index){ return ( <Action {...result} key={index} /> ) }) ); potentialAction.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { potentialAction = ( <Action props={ props.potentialAction } /> ); } } var description; if( props.description ){ if( props.description instanceof Array ){ description = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] description = description.concat( props.description.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. description is a Text.'></div> ) }) ); description.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { description = ( <div data-advice='Put your HTML here. description is a Text.'></div> ); } } var sameAs; if( props.sameAs ){ if( props.sameAs instanceof Array ){ sameAs = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] sameAs = sameAs.concat( props.sameAs.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. sameAs is a URL.'></div> ) }) ); sameAs.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { sameAs = ( <div data-advice='Put your HTML here. sameAs is a URL.'></div> ); } } var image; if( props.image ){ if( props.image instanceof Array ){ image = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] image = image.concat( props.image.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ) }) ); image.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { image = ( <div data-advice='Put your HTML here. image is a URL or ImageObject.'></div> ); } } var url; if( props.url ){ if( props.url instanceof Array ){ url = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] url = url.concat( props.url.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. url is a URL.'></div> ) }) ); url.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { url = ( <div data-advice='Put your HTML here. url is a URL.'></div> ); } } var supersededBy; if( props.supersededBy ){ if( props.supersededBy instanceof Array ){ supersededBy = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] supersededBy = supersededBy.concat( props.supersededBy.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. supersededBy is a Class or Property or Enumeration.'></div> ) }) ); supersededBy.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { supersededBy = ( <div data-advice='Put your HTML here. supersededBy is a Class or Property or Enumeration.'></div> ); } } var mainEntityOfPage; if( props.mainEntityOfPage ){ if( props.mainEntityOfPage instanceof Array ){ mainEntityOfPage = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] mainEntityOfPage = mainEntityOfPage.concat( props.mainEntityOfPage.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ) }) ); mainEntityOfPage.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { mainEntityOfPage = ( <div data-advice='Put your HTML here. mainEntityOfPage is a CreativeWork or URL.'></div> ); } } var additionalType; if( props.additionalType ){ if( props.additionalType instanceof Array ){ additionalType = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] additionalType = additionalType.concat( props.additionalType.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. additionalType is a URL.'></div> ) }) ); additionalType.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { additionalType = ( <div data-advice='Put your HTML here. additionalType is a URL.'></div> ); } } var alternateName; if( props.alternateName ){ if( props.alternateName instanceof Array ){ alternateName = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] alternateName = alternateName.concat( props.alternateName.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. alternateName is a Text.'></div> ) }) ); alternateName.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { alternateName = ( <div data-advice='Put your HTML here. alternateName is a Text.'></div> ); } } var name; if( props.name ){ if( props.name instanceof Array ){ name = [ (<div key='header' data-advice='HTML for the *head* of the section'></div>) ] name = name.concat( props.name.map( function(result, index){ return ( <div key={index} data-advice='Put your HTML here. name is a Text.'></div> ) }) ); name.push( ( <div key='footer' data-advice='HTML for the *footer* of the section'></div> ) ); } else { name = ( <div data-advice='Put your HTML here. name is a Text.'></div> ); } } return (<div title='WarrantyScope' className='WarrantyScope entity'> { potentialAction } { description } { sameAs } { image } { url } { supersededBy } { mainEntityOfPage } { additionalType } { alternateName } { name } </div>); } });
adrienthiery/cormorant
src/jsx/warrantyscope.js
JavaScript
mit
7,484
/* pointbreak.js - PointBreak provides a friendly interface to matchMedia with named media queries and easy to create callbacks. Authors & copyright (c) 2013: WebLinc, David Knight. */ (function(win) { 'use strict'; var EVENT_TYPE_MATCH = 'match', EVENT_TYPE_UNMATCH = 'unmatch'; // Create a point object which contains the functionality to trigger events and name alias for the media query function createPoint() { return { name : null, media : '', mql : null, listeners : { once : { match : null, unmatch : null }, match : [], unmatch : [] }, trigger : function(type) { var listenerType = this.listeners[type]; for (var i = 0, len = listenerType.length; i < len; i++) { var listener = listenerType[i]; if (typeof(listener.callback) === 'function') { listener.callback.call(win, this, listener.data); } } }, handleListener: null, // Fires 'callback' that matches the 'type' immediately now : function(type, callback, data) { var matches = this.mql && this.mql.matches; if ((type === EVENT_TYPE_MATCH && matches) || (type === EVENT_TYPE_UNMATCH && !matches)) { callback.call(win, this, data || {}); } return this; }, // Fired the first time the conditions are matched or unmatched once : function(type, callback, data) { var matches = this.mql && this.mql.matches; if ((type === EVENT_TYPE_MATCH && matches) || (type === EVENT_TYPE_UNMATCH && !matches)) { this.once[type] = null; callback.call(win, this, data || {}); } else { this.once[type] = { callback : callback, data : data }; } return this; }, // Fired each time the conditions are matched or unmatched which could be multiple times during a session on : function(type, callback, data) { this.listeners[type].push({ callback : callback, data : data || {} }); return this; }, // Removes a specific callback or all callbacks if 'callback' is undefined for 'match' or 'unmatch' off : function(type, callback) { if (callback) { var listenerType = this.listeners[type]; for (var i = 0; i < listenerType.length; i++) { if (listenerType[i].callback === callback) { listenerType.splice(i, 1); i--; } } } else { this.listeners[type] = []; this.once[type] = null; } return this; } }; } // Interface for points that provides easy get/set methods and storage in the 'points' object win.PointBreak = { // Contains alias for media queries points: {}, // PointBreak.set('xsmall', '(min-width: 320px) and (max-width: 480px)') set: function (name, value) { var point = this.points[name]; // Reset 'listeners' and removeListener from 'mql' (MediaQueryList) // else create point object and add 'name' property if (point) { point.mql.removeListener(point.handleListener); point .off(EVENT_TYPE_MATCH) .off(EVENT_TYPE_UNMATCH); } else { point = this.points[name] = createPoint(); point.name = name; } // Set up listener function for 'mql' point.handleListener = function(mql) { var type = (mql.matches && EVENT_TYPE_MATCH) || EVENT_TYPE_UNMATCH, once = point.once[type]; // 'point' comes from the 'set' scope if (typeof(once) === 'function') { point.once[type] = null; once.call(win, point); } point.trigger(type); }; // Set up matchMedia and listener, requires matchMedia support or equivalent polyfill to evaluate media query // See https://github.com/weblinc/media-match or https://github.com/paulirish/matchMedia.js for matchMedia polyfill point.media = value || 'all'; point.mql = (win.matchMedia && win.matchMedia(point.media)) || { matches : false, media : point.media, addListener : function() {}, removeListener : function() {} }; point.mql.addListener(point.handleListener); return point; }, // PointBreak.get('xsmall') get: function(name) { return this.points[name] || null; }, // PointBreak.matches('xsmall') matches: function(name) { return (this.points[name] && this.points[name].mql.matches) || false; }, // PointBreak.lastMatch('xsmall small medium') lastMatch: function(nameList) { var list = nameList.indexOf(' ') ? nameList.split(' ') : [nameList], name = '', result = ''; for (var i = 0, len = list.length; i < len; i++) { name = list[i]; if (this.points[name] && this.points[name].mql.matches) { result = name; } } return result; } }; })(window);
weblinc/pointbreak.js
pointbreak.js
JavaScript
mit
6,390
var cc = require('closure-compiler'); var vinylTransform = require('vinyl-transform'); var mapStream = require('map-stream'); module.exports = function () { return vinylTransform(function () { return mapStream(function (data, next) { cc.compile(data, {}, function afterCompile (err, stdout) { if (err) { return next(err) } else { return next(null, stdout); } }); }); }); }
parambirs/aui-demos
node_modules/@atlassian/aui/build/lib/minify.js
JavaScript
mit
510
import { StaticResource } from 'iab-vast-model' export default ($staticResource) => { const res = new StaticResource() res.creativeType = $staticResource.creativeType res.uri = $staticResource._value return res }
zentrick/iab-vast-parser
src/factory/static-resource.js
JavaScript
mit
222
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view'; class wsapp extends Component { render() { return <ScrollableTabView style={{marginTop: 20, }} initialPage={2} scrollWithoutAnimation={false} renderTabBar={() => <ScrollableTabBar />} ref={(tabView) => { this.tabView = tabView; }}> <Text tabLabel='Tab #1'>My</Text> <Text tabLabel='Tab #2'>favorite</Text> <Text tabLabel='Tab #3'>project</Text> <TouchableOpacity tabLabel='Back' onPress={() => this.tabView.goToPage(0)}> <Text>Lets go back!</Text> </TouchableOpacity> </ScrollableTabView> } } export default wsapp
huanganqi/wsapp
src/v0/demo/react-native-scrollable-tab-view/index.js
JavaScript
mit
855
'use strict'; var expect = require('chai').expect; var Config = require('../lib/dalek/config.js'); describe('dalek-internal-config', function () { it('should exist', function () { expect(Config).to.be.ok; }); it('can be initialized', function () { var config = new Config({}, {tests: []}, {}); expect(config).to.be.ok; }); it('can get a value', function () { var config = new Config({foo: 'bar'}, {tests: []}, {}); expect(config.get('foo')).to.equal('bar'); }); it('can read & parse a yaml file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readyml(__dirname + '/mock/Dalekfile.yml'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can read & parse a json file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readjson(__dirname + '/mock/Dalekfile.json'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can read & parse a json5 file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readjson5(__dirname + '/mock/Dalekfile.json5'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can read & parse a js file', function () { var config = new Config({}, {tests: []}, {}); var fileContents = config.readjs(__dirname + '/mock/Dalekfile.js'); expect(fileContents).to.include.keys('browsers'); expect(fileContents.browsers).to.be.an('array'); expect(fileContents.browsers[0]).to.be.an('object'); expect(fileContents.browsers[0]).to.include.keys('chrome'); expect(fileContents.browsers[0].chrome).to.include.keys('port'); expect(fileContents.browsers[0].chrome.port).to.equal(6000); }); it('can check the avilability of a config file', function () { var config = new Config({}, {tests: []}, {}); var path = __dirname + '/mock/Dalekfile.coffee'; expect(config.checkAvailabilityOfConfigFile(path)).to.equal(path); }); it('can verify a reporter', function () { var config = new Config({}, {tests: []}, {}); var reporter = { isReporter: function () { return true; } }; var reporters = ['foobar']; expect(config.verifyReporters(reporters, reporter)[0]).to.equal(reporters[0]); }); it('can verify a driver', function () { var config = new Config({}, {tests: []}, {}); var driver = { isDriver: function () { return true; } }; var drivers = ['foobar']; expect(config.verifyDrivers(drivers, driver)[0]).to.equal(drivers[0]); }); it('can return the previous filename if the _checkFile iterator foudn a file', function () { var config = new Config({}, {tests: []}, {}); expect(config._checkFile('foobarbaz', '', '', '')).to.equal('foobarbaz'); }); it('can check the existance of default config files', function () { var config = new Config({}, {tests: []}, {}); config.defaultFilename = __dirname + '/mock/Dalekfile'; expect(config._checkFile('js', 'coffee', 0, ['js', 'coffee'])).to.equal(__dirname + '/mock/Dalekfile.js'); }); it('can check the existance of default config files (1st in row doesnt exist, snd. does)', function () { var config = new Config({}, {tests: []}, {}); config.defaultFilename = __dirname + '/mock/Dalekfile'; expect(config._checkFile('txt', 'coffee', 0, ['txt', 'coffee'])).to.equal(__dirname + '/mock/Dalekfile.coffee'); }); });
niallo/tardisjs
test/lib_dalek_config_TEST.js
JavaScript
mit
4,394
SirTrevor.Locales = { en: { general: { 'delete': 'Delete?', 'drop': 'Drag __block__ here', 'paste': 'Or paste URL here', 'upload': '...or choose a file', 'close': 'close', 'position': 'Position', 'wait': 'Please wait...', 'link': 'Enter a link' }, errors: { 'title': "You have the following errors:", 'validation_fail': "__type__ block is invalid", 'block_empty': "__name__ must not be empty", 'type_missing': "You must have a block of type __type__", 'required_type_empty': "A required block type __type__ is empty", 'load_fail': "There was a problem loading the contents of the document" }, blocks: { text: { 'title': "Text" }, columns: { 'title': "Columns" }, list: { 'title': "List" }, quote: { 'title': "Quote", 'credit_field': "Credit" }, image: { 'title': "Image", 'upload_error': "There was a problem with your upload" }, video: { 'title': "Video" }, tweet: { 'title': "Tweet", 'fetch_error': "There was a problem fetching your tweet" }, embedly: { 'title': "Embedly", 'fetch_error': "There was a problem fetching your embed", 'key_missing': "An Embedly API key must be present" }, heading: { 'title': "Heading" } } } }; if (window.i18n === undefined || window.i18n.init === undefined) { // Minimal i18n stub that only reads the English strings SirTrevor.log("Using i18n stub"); window.i18n = { t: function(key, options) { var parts = key.split(':'), str, obj, part, i; obj = SirTrevor.Locales[SirTrevor.LANGUAGE]; for(i = 0; i < parts.length; i++) { part = parts[i]; if(!_.isUndefined(obj[part])) { obj = obj[part]; } } str = obj; if (!_.isString(str)) { return ""; } if (str.indexOf('__') >= 0) { _.each(options, function(value, opt) { str = str.replace('__' + opt + '__', value); }); } return str; } }; } else { SirTrevor.log("Using i18next"); // Only use i18next when the library has been loaded by the user, keeps // dependencies slim i18n.init({ resStore: SirTrevor.Locales, fallbackLng: SirTrevor.LANGUAGE, ns: { namespaces: ['general', 'blocks'], defaultNs: 'general' } }); }
ansata-biz/sir-trevor-js
src/locales.js
JavaScript
mit
2,572
// telegram.link // Copyright 2014 Enrico Stara 'enrico.stara@gmail.com' // Released under the MIT License // http://telegram.link // Dependencies: var api = require('../api'); var utility = require('../utility'); // *** // This module wraps API methods required to manage the session updates // See [Api Methods](https://core.telegram.org/methods#working-with-updates) // Access only via Client object (like client.updates) and `updates` instance property function Updates(client) { this.client = client; } // *** // **Event: **`'method name'` // Each of the following methods emits an event with the same name when done, an `error` event otherwise. // *** // updates.**getState([callback])** // Return a Promise to get the current state of updates. // [Click here for more details](https://core.telegram.org/method/updates.getState) // The code: Updates.prototype.getState = function (callback) { return utility.callService(api.service.updates.getState, this.client, this.client._channel, callback, arguments); }; // *** // updates.**getDifference(pts, date, qts, [callback])** // Return a Promise to get the difference between the current state of updates and transmitted. // [Click here for more details](https://core.telegram.org/method/updates.getDifference) // The code: Updates.prototype.getDifference = function (pts, date, qts, callback) { return utility.callService(api.service.updates.getDifference, this.client, this.client._channel, callback, arguments); }; // Export the class module.exports = exports = Updates;
enricostara/telegram.link
lib/api/updates.js
JavaScript
mit
1,579
(function() { function setUpTopLevelInteraction() { var TopLevelInteraction = new ITPHelper({ redirectUrl: document.body.dataset.redirectUrl, }); TopLevelInteraction.execute(); } document.addEventListener("DOMContentLoaded", setUpTopLevelInteraction); })();
Shopify/shopify_app
app/assets/javascripts/shopify_app/top_level_interaction.js
JavaScript
mit
284
/// <reference path="./typings/globals.d.ts"/> /// <reference path="./typings/lib.d.ts"/> var angular = require('angular'); var magics_scene_1 = require('./directives/magics-scene'); var magics_spy_1 = require('./directives/magics-spy'); var magics_stage_1 = require('./directives/magics-stage'); var constants_1 = require('./services/constants'); var magics_1 = require('./services/magics'); exports.__esModule = true; exports["default"] = angular.module('ngMagics', [ magics_scene_1["default"], magics_spy_1["default"], magics_stage_1["default"], constants_1["default"], magics_1["default"] ]) .name;
ex-machine/ng-magics
dist/es5/index.js
JavaScript
mit
627
/** * Array.from ponyfill. * * @param {Object} iterable * * @returns {Array} */ export default function arrayFrom(iterable) { const arr = []; for (let i = 0; i < iterable.length; i += 1) { arr.push(iterable[i]); } return arr; }
jakezatecky/react-dual-listbox
src/js/util/arrayFrom.js
JavaScript
mit
260
import { expect } from 'chai' import _drop from '../../src/array/_drop2' describe('_drop', function(){ it('is a function', function(){ expect(_drop).to.be.a('function') }) it('returns an array', function(){ const droppedArray = _drop([5,7,2]) expect(droppedArray).to.be.a('array') }) it('returns [2] when given [5,7,2], 2', function(){ const droppedArray = _drop([5,7,2], 2) expect(droppedArray).to.be.deep.equal([2]) }) it('returns [7, 2] when given [5,7,2]', function(){ const droppedArray = _drop([5,7,2]) expect(droppedArray).to.be.deep.equal([7, 2]) }) it('returns [] when given [5,7,2], 17', function(){ const droppedArray = _drop([5,7,2], 17) expect(droppedArray).to.be.deep.equal([]) }) })
pkallas/Reimplement-Lodash
test/array/_drop_test2.js
JavaScript
mit
761