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
/** * @license AngularJS v1.0.6 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) { 'use strict'; /** * @ngdoc overview * @name ngResource * @description */ /** * @ngdoc object * @name ngResource.$resource * @requires $http * * @description * A factory which creates a resource object that lets you interact with * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. * * The returned resource object has action methods which provide high-level behaviors without * the need to interact with the low level {@link ng.$http $http} service. * * # Installation * To use $resource make sure you have included the `angular-resource.js` that comes in Angular * package. You can also find this file on Google CDN, bower as well as at * {@link http://code.angularjs.org/ code.angularjs.org}. * * Finally load the module in your application: * * angular.module('app', ['ngResource']); * * and you are ready to get started! * * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. If you are using a URL with a port number (e.g. * `http://example.com:8080/api`), you'll need to escape the colon character before the port * number, like this: `$resource('http://example.com\\:8080/api')`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in * `actions` methods. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in * URL `/path/greet?salutation=Hello`. * * If the parameter value is prefixed with `@` then the value of that parameter is extracted from * the data object (useful for non-GET operations). * * @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the * default set of resource actions. The declaration should be created in the following format: * * {action1: {method:?, params:?, isArray:?}, * action2: {method:?, params:?, isArray:?}, * ...} * * Where: * * - `action` – {string} – The name of action. This name becomes the name of the method on your * resource object. * - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`, * and `JSONP` * - `params` – {object=} – Optional set of pre-bound parameters for this action. * - isArray – {boolean=} – If true then the returned object for this action is an array, see * `returns` section. * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * * { 'get': {method:'GET'}, * 'save': {method:'POST'}, * 'query': {method:'GET', isArray:true}, * 'remove': {method:'DELETE'}, * 'delete': {method:'DELETE'} }; * * Calling these methods invoke an {@link ng.$http} with the specified http method, * destination and parameters. When the data is returned from the server then the object is an * instance of the resource class. The actions `save`, `remove` and `delete` are available on it * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, * read, update, delete) on server-side data like this: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It is important to realize that invoking a $resource object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty * object results in no rendering, once the data arrives from the server then the object is * populated with the data and the view automatically re-renders itself showing the new data. This * means that in most case one never has to write a callback function for the action methods. * * The action methods on the class object or instance object can be invoked with the following * parameters: * * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` * - non-GET instance actions: `instance.$action([parameters], [success], [error])` * * * @example * * # Credit card resource * * <pre> // Define CreditCard class var CreditCard = $resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, { charge: {method:'POST', params:{charge:true}} }); // We can retrieve a collection from the server var cards = CreditCard.query(function() { // GET: /user/123/card // server returns: [ {id:456, number:'1234', name:'Smith'} ]; var card = cards[0]; // each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); card.name = "J. Smith"; // non GET methods are mapped onto the instances card.$save(); // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} // server returns: {id:456, number:'1234', name: 'J. Smith'}; // our custom method is mapped as well. card.$charge({amount:9.99}); // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} }); // we can create an instance as well var newCard = new CreditCard({number:'0123'}); newCard.name = "Mike Smith"; newCard.$save(); // POST: /user/123/card {number:'0123', name:'Mike Smith'} // server returns: {id:789, number:'01234', name: 'Mike Smith'}; expect(newCard.id).toEqual(789); * </pre> * * The object returned from this function execution is a resource "class" which has "static" method * for each action in the definition. * * Calling these methods invoke `$http` on the `url` template with the given `method` and `params`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. <pre> var User = $resource('/user/:userId', {userId:'@id'}); var user = User.get({userId:123}, function() { user.abc = true; user.$save(); }); </pre> * * It's worth noting that the success callback for `get`, `query` and other method gets passed * in the response that came from the server as well as $http header getter function, so one * could rewrite the above example and get access to http headers as: * <pre> var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(u, getResponseHeaders){ u.abc = true; u.$save(function(u, putResponseHeaders) { //u => saved user object //putResponseHeaders => $http header getter }); }); </pre> * # Buzz client Let's look at what a buzz client created with the `$resource` service looks like: <doc:example> <doc:source jsfiddle="false"> <script> function BuzzController($resource) { this.userId = 'googlebuzz'; this.Activity = $resource( 'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments', {alt:'json', callback:'JSON_CALLBACK'}, {get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}} ); } BuzzController.prototype = { fetch: function() { this.activities = this.Activity.get({userId:this.userId}); }, expandReplies: function(activity) { activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id}); } }; BuzzController.$inject = ['$resource']; </script> <div ng-controller="BuzzController"> <input ng-model="userId"/> <button ng-click="fetch()">fetch</button> <hr/> <div ng-repeat="item in activities.data.items"> <h1 style="font-size: 15px;"> <img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a> <a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a> </h1> {{item.object.content | html}} <div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;"> <img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/> <a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}} </div> </div> </div> </doc:source> <doc:scenario> </doc:scenario> </doc:example> */ angular.module('ngResource', ['ng']). factory('$resource', ['$http', '$parse', function($http, $parse) { var DEFAULT_ACTIONS = { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }; var noop = angular.noop, forEach = angular.forEach, extend = angular.extend, copy = angular.copy, isFunction = angular.isFunction, getter = function(obj, path) { return $parse(path)(obj); }; /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } function Route(template, defaults) { this.template = template = template + '#'; this.defaults = defaults || {}; var urlParams = this.urlParams = {}; forEach(template.split(/\W/), function(param){ if (param && (new RegExp("(^|[^\\\\]):" + param + "\\W").test(template))) { urlParams[param] = true; } }); this.template = template.replace(/\\:/g, ':'); } Route.prototype = { url: function(params) { var self = this, url = this.template, val, encodedVal; params = params || {}; forEach(this.urlParams, function(_, urlParam){ val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; if (angular.isDefined(val) && val !== null) { encodedVal = encodeUriSegment(val); url = url.replace(new RegExp(":" + urlParam + "(\\W)", "g"), encodedVal + "$1"); } else { url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W)", "g"), function(match, leadingSlashes, tail) { if (tail.charAt(0) == '/') { return tail; } else { return leadingSlashes + tail; } }); } }); url = url.replace(/\/?#$/, ''); var query = []; forEach(params, function(value, key){ if (!self.urlParams[key]) { query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); } }); query.sort(); url = url.replace(/\/*$/, ''); return url + (query.length ? '?' + query.join('&') : ''); } }; function ResourceFactory(url, paramDefaults, actions) { var route = new Route(url); actions = extend({}, DEFAULT_ACTIONS, actions); function extractParams(data, actionParams){ var ids = {}; actionParams = extend({}, paramDefaults, actionParams); forEach(actionParams, function(value, key){ ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value; }); return ids; } function Resource(value){ copy(value || {}, this); } forEach(actions, function(action, name) { action.method = angular.uppercase(action.method); var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH'; Resource[name] = function(a1, a2, a3, a4) { var params = {}; var data; var success = noop; var error = null; switch(arguments.length) { case 4: error = a4; success = a3; //fallthrough case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { success = a1; error = a2; break; } success = a2; error = a3; //fallthrough } else { params = a1; data = a2; success = a3; break; } case 1: if (isFunction(a1)) success = a1; else if (hasBody) data = a1; else params = a1; break; case 0: break; default: throw "Expected between 0-4 arguments [params, data, success, error], got " + arguments.length + " arguments."; } var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data)); $http({ method: action.method, url: route.url(extend({}, extractParams(data, action.params || {}), params)), data: data }).then(function(response) { var data = response.data; if (data) { if (action.isArray) { value.length = 0; forEach(data, function(item) { value.push(new Resource(item)); }); } else { copy(data, value); } } (success||noop)(value, response.headers); }, error); return value; }; Resource.prototype['$' + name] = function(a1, a2, a3) { var params = extractParams(this), success = noop, error; switch(arguments.length) { case 3: params = a1; success = a2; error = a3; break; case 2: case 1: if (isFunction(a1)) { success = a1; error = a2; } else { params = a1; success = a2 || noop; } case 0: break; default: throw "Expected between 1-3 arguments [params, success, error], got " + arguments.length + " arguments."; } var data = hasBody ? this : undefined; Resource[name].call(this, params, data, success, error); }; }); Resource.bind = function(additionalParamDefaults){ return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); }; return Resource; } return ResourceFactory; }]); })(window, window.angular);
bacardi55/b-55-log
web/jocs/components/angular-resource/angular-resource.js
JavaScript
mit
17,163
import { Duration, isDuration } from './constructor'; import toInt from '../utils/to-int'; import hasOwnProp from '../utils/has-own-prop'; import { DATE, HOUR, MINUTE, SECOND, MILLISECOND } from '../units/constants'; import { cloneWithOffset } from '../units/offset'; import { createLocal } from '../create/local'; // ASP.NET json date format regex var aspNetRegex = /^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?\d*)?$/; // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere // and further modified to allow for strings containing both week and day var isoRegex = /^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/; export function createDuration (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, diffRes; if (isDuration(input)) { duration = { ms : input._milliseconds, d : input._days, M : input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : 0, d : toInt(match[DATE]) * sign, h : toInt(match[HOUR]) * sign, m : toInt(match[MINUTE]) * sign, s : toInt(match[SECOND]) * sign, ms : toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y : parseIso(match[2], sign), M : parseIso(match[3], sign), w : parseIso(match[4], sign), d : parseIso(match[5], sign), h : parseIso(match[6], sign), m : parseIso(match[7], sign), s : parseIso(match[8], sign) }; } else if (duration == null) {// checks for null or undefined duration = {}; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(createLocal(duration.from), createLocal(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; } createDuration.fn = Duration.prototype; function parseIso (inp, sign) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; if (!(base.isValid() && other.isValid())) { return {milliseconds: 0, months: 0}; } other = cloneWithOffset(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; }
krasnyuk/e-liquid-MS
wwwroot/assets/js/moment/src/lib/duration/create.js
JavaScript
mit
3,948
/* jshint -W100 */ /* jslint maxlen: 86 */ define(function () { // Farsi (Persian) return { errorLoading: function () { return 'امکان بارگذاری نتایج وجود ندارد.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'لطفاً ' + overChars + ' کاراکتر را حذف نمایید'; return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'لطفاً تعداد ' + remainingChars + ' کاراکتر یا بیشتر وارد نمایید'; return message; }, loadingMore: function () { return 'در حال بارگذاری نتایج بیشتر...'; }, maximumSelected: function (args) { var message = 'شما تنها می‌توانید ' + args.maximum + ' آیتم را انتخاب نمایید'; return message; }, noResults: function () { return 'هیچ نتیجه‌ای یافت نشد'; }, searching: function () { return 'در حال جستجو...'; } }; });
krasnyuk/e-liquid-MS
wwwroot/assets/js/select2/src/js/select2/i18n/fa.js
JavaScript
mit
1,152
//! moment.js locale configuration //! locale : belarusian (be) //! author : Dmitry Demidov : https://github.com/demidov91 //! author: Praleska: http://praleska.pro/ //! Author : Menelion Elensúle : https://github.com/Oire import moment from '../moment'; function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', 'dd': 'дзень_дні_дзён', 'MM': 'месяц_месяцы_месяцаў', 'yy': 'год_гады_гадоў' }; if (key === 'm') { return withoutSuffix ? 'хвіліна' : 'хвіліну'; } else if (key === 'h') { return withoutSuffix ? 'гадзіна' : 'гадзіну'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_'), 'accusative': 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), 'accusative': 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } export default moment.defineLocale('be', { months : monthsCaseReplace, monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), weekdays : weekdaysCaseReplace, weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY г.', LLL : 'D MMMM YYYY г., HH:mm', LLLL : 'dddd, D MMMM YYYY г., HH:mm' }, calendar : { sameDay: '[Сёння ў] LT', nextDay: '[Заўтра ў] LT', lastDay: '[Учора ў] LT', nextWeek: function () { return '[У] dddd [ў] LT'; }, lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return '[У мінулую] dddd [ў] LT'; case 1: case 2: case 4: return '[У мінулы] dddd [ў] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'праз %s', past : '%s таму', s : 'некалькі секунд', m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : relativeTimeWithPlural, hh : relativeTimeWithPlural, d : 'дзень', dd : relativeTimeWithPlural, M : 'месяц', MM : relativeTimeWithPlural, y : 'год', yy : relativeTimeWithPlural }, meridiemParse: /ночы|раніцы|дня|вечара/, isPM : function (input) { return /^(дня|вечара)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ночы'; } else if (hour < 12) { return 'раніцы'; } else if (hour < 17) { return 'дня'; } else { return 'вечара'; } }, ordinalParse: /\d{1,2}-(і|ы|га)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы'; case 'D': return number + '-га'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } });
LilShy/test
新建文件夹/material_admin_v-1.5-2/Template/jquery/vendors/bower_components/moment/src/locale/be.js
JavaScript
apache-2.0
5,171
#!/usr/bin/env node require("./bin/npm-cli.js")
nikste/visualizationDemo
zeppelin-web/node/npm/cli.js
JavaScript
apache-2.0
48
var vows = require("vows"), _ = require("../../"), load = require("../load"), assert = require("../assert"); var suite = vows.describe("d3.max"); suite.addBatch({ "max": { topic: load("arrays/max").expression("d3.max"), "returns the greatest numeric value for numbers": function(max) { assert.equal(max([1]), 1); assert.equal(max([5, 1, 2, 3, 4]), 5); assert.equal(max([20, 3]), 20); assert.equal(max([3, 20]), 20); }, "returns the greatest lexicographic value for strings": function(max) { assert.equal(max(["c", "a", "b"]), "c"); assert.equal(max(["20", "3"]), "3"); assert.equal(max(["3", "20"]), "3"); }, "ignores null, undefined and NaN": function(max) { var o = {valueOf: function() { return NaN; }}; assert.equal(max([NaN, 1, 2, 3, 4, 5]), 5); assert.equal(max([o, 1, 2, 3, 4, 5]), 5); assert.equal(max([1, 2, 3, 4, 5, NaN]), 5); assert.equal(max([1, 2, 3, 4, 5, o]), 5); assert.equal(max([10, null, 3, undefined, 5, NaN]), 10); assert.equal(max([-1, null, -3, undefined, -5, NaN]), -1); }, "compares heterogenous types as numbers": function(max) { assert.strictEqual(max([20, "3"]), 20); assert.strictEqual(max(["20", 3]), "20"); assert.strictEqual(max([3, "20"]), "20"); assert.strictEqual(max(["3", 20]), 20); }, "returns undefined for empty array": function(max) { assert.isUndefined(max([])); assert.isUndefined(max([null])); assert.isUndefined(max([undefined])); assert.isUndefined(max([NaN])); assert.isUndefined(max([NaN, NaN])); }, "applies the optional accessor function": function(max) { assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.min(d); }), 2); assert.equal(max([1, 2, 3, 4, 5], function(d, i) { return i; }), 4); } } }); suite.export(module);
MoonApps/barelyalive
www/js/vendor/d3-master/test/arrays/max-test.js
JavaScript
gpl-2.0
1,919
var name; switch (name) { case "Kamol": doSomething(); default: doSomethingElse(); } switch (name) { default: doSomethingElse(); break; case "Kamol": doSomething(); }
bryantaylor/Epic
wp-content/themes/epic/node_modules/grunt-contrib-jshint/node_modules/jshint/tests/stable/unit/fixtures/switchDefaultFirst.js
JavaScript
gpl-2.0
173
(function() { "use strict"; var WORD = /[\w$]+/, RANGE = 500; CodeMirror.registerHelper("hint", "anyword", function(editor, options) { var word = options && options.word || WORD; var range = options && options.range || RANGE; var cur = editor.getCursor(), curLine = editor.getLine(cur.line); var start = cur.ch, end = start; while (end < curLine.length && word.test(curLine.charAt(end))) ++end; while (start && word.test(curLine.charAt(start - 1))) --start; var curWord = start != end && curLine.slice(start, end); var list = [], seen = {}; var re = new RegExp(word.source, "g"); for (var dir = -1; dir <= 1; dir += 2) { var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir; for (; line != end; line += dir) { var text = editor.getLine(line), m; while (m = re.exec(text)) { if (line == cur.line && m[0] === curWord) continue; if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) { seen[m[0]] = true; list.push(m[0]); } } } } return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)}; }); })();
zoyoe/ectool
zoyoeec/static/CodeMirror/addon/hint/anyword-hint.js
JavaScript
gpl-2.0
1,296
import { addFormatToken } from '../format/format'; import { addUnitAlias } from './aliases'; import { addUnitPriority } from './priorities'; import { addRegexToken, match1to2, matchWord, regexEscape } from '../parse/regex'; import { addWeekParseToken } from '../parse/token'; import toInt from '../utils/to-int'; import isArray from '../utils/is-array'; import indexOf from '../utils/index-of'; import hasOwnProp from '../utils/has-own-prop'; import { createUTC } from '../create/utc'; import getParsingFlags from '../create/parsing-flags'; // FORMATTING addFormatToken('d', 0, 'do', 'day'); addFormatToken('dd', 0, 0, function (format) { return this.localeData().weekdaysMin(this, format); }); addFormatToken('ddd', 0, 0, function (format) { return this.localeData().weekdaysShort(this, format); }); addFormatToken('dddd', 0, 0, function (format) { return this.localeData().weekdays(this, format); }); addFormatToken('e', 0, 0, 'weekday'); addFormatToken('E', 0, 0, 'isoWeekday'); // ALIASES addUnitAlias('day', 'd'); addUnitAlias('weekday', 'e'); addUnitAlias('isoWeekday', 'E'); // PRIORITY addUnitPriority('day', 11); addUnitPriority('weekday', 11); addUnitPriority('isoWeekday', 11); // PARSING addRegexToken('d', match1to2); addRegexToken('e', match1to2); addRegexToken('E', match1to2); addRegexToken('dd', function (isStrict, locale) { return locale.weekdaysMinRegex(isStrict); }); addRegexToken('ddd', function (isStrict, locale) { return locale.weekdaysShortRegex(isStrict); }); addRegexToken('dddd', function (isStrict, locale) { return locale.weekdaysRegex(isStrict); }); addWeekParseToken(['dd', 'ddd', 'dddd'], function (input, week, config, token) { var weekday = config._locale.weekdaysParse(input, token, config._strict); // if we didn't get a weekday name, mark the date as invalid if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) { week[token] = toInt(input); }); // HELPERS function parseWeekday(input, locale) { if (typeof input !== 'string') { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale.weekdaysParse(input); if (typeof input === 'number') { return input; } return null; } function parseIsoWeekday(input, locale) { if (typeof input === 'string') { return locale.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } // LOCALES export var defaultLocaleWeekdays = 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'); export function localeWeekdays (m, format) { return isArray(this._weekdays) ? this._weekdays[m.day()] : this._weekdays[this._weekdays.isFormat.test(format) ? 'format' : 'standalone'][m.day()]; } export var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'); export function localeWeekdaysShort (m) { return this._weekdaysShort[m.day()]; } export var defaultLocaleWeekdaysMin = 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'); export function localeWeekdaysMin (m) { return this._weekdaysMin[m.day()]; } function handleStrictParse(weekdayName, format, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2000, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase(); } } if (strict) { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format === 'dddd') { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format === 'ddd') { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } export function localeWeekdaysParse (weekdayName, format, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse.call(this, weekdayName, format, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp('^' + this.weekdays(mom, '').replace('.', '\.?') + '$', 'i'); this._shortWeekdaysParse[i] = new RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\.?') + '$', 'i'); this._minWeekdaysParse[i] = new RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\.?') + '$', 'i'); } if (!this._weekdaysParse[i]) { regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'dddd' && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'ddd' && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format === 'dd' && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } // MOMENTS export function getSetDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } } export function getSetLocaleDayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); } export function getSetISODayOfWeek (input) { if (!this.isValid()) { return input != null ? this : NaN; } // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } var defaultWeekdaysRegex = matchWord; export function weekdaysRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, '_weekdaysRegex')) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } var defaultWeekdaysShortRegex = matchWord; export function weekdaysShortRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, '_weekdaysShortRegex')) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } var defaultWeekdaysMinRegex = matchWord; export function weekdaysMinRegex (isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, '_weekdaysRegex')) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, '_weekdaysMinRegex')) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse () { function cmpLenRev(a, b) { return b.length - a.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { // make the regex if we don't have it already mom = createUTC([2000, 1]).day(i); minp = this.weekdaysMin(mom, ''); shortp = this.weekdaysShort(mom, ''); longp = this.weekdays(mom, ''); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } // Sorting makes sure if one weekday (or abbr) is a prefix of another it // will match the longer piece. minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 7; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); mixedPieces[i] = regexEscape(mixedPieces[i]); } this._weekdaysRegex = new RegExp('^(' + mixedPieces.join('|') + ')', 'i'); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp('^(' + longPieces.join('|') + ')', 'i'); this._weekdaysShortStrictRegex = new RegExp('^(' + shortPieces.join('|') + ')', 'i'); this._weekdaysMinStrictRegex = new RegExp('^(' + minPieces.join('|') + ')', 'i'); }
Nucleo-235/roupa-livre-ionic
www/lib/moment/src/lib/units/day-of-week.js
JavaScript
gpl-3.0
11,793
//! moment.js locale configuration //! locale : Chinese (Hong Kong) [zh-hk] //! author : Ben : https://github.com/ben-lin //! author : Chris Lam : https://github.com/hehachris //! author : Konstantin : https://github.com/skfd ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, (function (moment) { 'use strict'; var zhHk = moment.defineLocale('zh-hk', { months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY年MMMD日', LL : 'YYYY年MMMD日', LLL : 'YYYY年MMMD日 HH:mm', LLLL : 'YYYY年MMMD日dddd HH:mm', l : 'YYYY年MMMD日', ll : 'YYYY年MMMD日', lll : 'YYYY年MMMD日 HH:mm', llll : 'YYYY年MMMD日dddd HH:mm' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '中午') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, ordinal : function (number, period) { switch (period) { case 'd' : case 'D' : case 'DDD' : return number + '日'; case 'M' : return number + '月'; case 'w' : case 'W' : return number + '週'; default : return number; } }, relativeTime : { future : '%s內', past : '%s前', s : '幾秒', m : '1 分鐘', mm : '%d 分鐘', h : '1 小時', hh : '%d 小時', d : '1 天', dd : '%d 天', M : '1 個月', MM : '%d 個月', y : '1 年', yy : '%d 年' } }); return zhHk; })));
stevemoore113/ch_web_-
資源/CCEI/handsontable/dist/moment/locale/zh-hk.js
JavaScript
mit
3,363
var assert = require('assert'); var cookie = require('..'); suite('parse'); test('basic', function() { assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar')); assert.deepEqual({ foo: '123' }, cookie.parse('foo=123')); }); test('ignore spaces', function() { assert.deepEqual({ FOO: 'bar', baz: 'raz' }, cookie.parse('FOO = bar; baz = raz')); }); test('escaping', function() { assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' }, cookie.parse('foo="bar=123456789&name=Magic+Mouse"')); assert.deepEqual({ email: ' ",;/' }, cookie.parse('email=%20%22%2c%3b%2f')); }); test('ignore escaping error and return original value', function() { assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar')); });
BrowenChen/classroomDashboard
zzishwebsite/node_modules/express/node_modules/connect/node_modules/cookie/test/parse.js
JavaScript
mit
800
(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'module', './util'], factory); } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') { factory(exports, module, require('./util')); } else { var mod = { exports: {} }; factory(mod.exports, mod, global.Util); global.modal = mod.exports; } })(this, function (exports, module, _util) { '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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _Util = _interopRequireDefault(_util); /** * -------------------------------------------------------------------------- * Bootstrap (v4.0.0): modal.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ var Modal = (function ($) { /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ var NAME = 'modal'; var VERSION = '4.0.0'; var DATA_KEY = 'bs.modal'; var EVENT_KEY = '.' + DATA_KEY; var DATA_API_KEY = '.data-api'; var JQUERY_NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 300; var BACKDROP_TRANSITION_DURATION = 150; var Default = { backdrop: true, keyboard: true, focus: true, show: true }; var DefaultType = { backdrop: '(boolean|string)', keyboard: 'boolean', focus: 'boolean', show: 'boolean' }; var Event = { HIDE: 'hide' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY, FOCUSIN: 'focusin' + EVENT_KEY, RESIZE: 'resize' + EVENT_KEY, CLICK_DISMISS: 'click.dismiss' + EVENT_KEY, KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY, MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY, MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY, CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY }; var ClassName = { SCROLLBAR_MEASURER: 'modal-scrollbar-measure', BACKDROP: 'modal-backdrop', OPEN: 'modal-open', FADE: 'fade', IN: 'in' }; var Selector = { DIALOG: '.modal-dialog', DATA_TOGGLE: '[data-toggle="modal"]', DATA_DISMISS: '[data-dismiss="modal"]', FIXED_CONTENT: '.navbar-fixed-top, .navbar-fixed-bottom, .is-fixed' }; /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ var Modal = (function () { function Modal(element, config) { _classCallCheck(this, Modal); this._config = this._getConfig(config); this._element = element; this._dialog = $(element).find(Selector.DIALOG)[0]; this._backdrop = null; this._isShown = false; this._isBodyOverflowing = false; this._ignoreBackdropClick = false; this._originalBodyPadding = 0; this._scrollbarWidth = 0; } /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ // getters _createClass(Modal, [{ key: 'toggle', // public value: function toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } }, { key: 'show', value: function show(relatedTarget) { var _this = this; var showEvent = $.Event(Event.SHOW, { relatedTarget: relatedTarget }); $(this._element).trigger(showEvent); if (this._isShown || showEvent.isDefaultPrevented()) { return; } this._isShown = true; this._checkScrollbar(); this._setScrollbar(); $(document.body).addClass(ClassName.OPEN); this._setEscapeEvent(); this._setResizeEvent(); $(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, $.proxy(this.hide, this)); $(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () { $(_this._element).one(Event.MOUSEUP_DISMISS, function (event) { if ($(event.target).is(_this._element)) { that._ignoreBackdropClick = true; } }); }); this._showBackdrop($.proxy(this._showElement, this, relatedTarget)); } }, { key: 'hide', value: function hide(event) { if (event) { event.preventDefault(); } var hideEvent = $.Event(Event.HIDE); $(this._element).trigger(hideEvent); if (!this._isShown || hideEvent.isDefaultPrevented()) { return; } this._isShown = false; this._setEscapeEvent(); this._setResizeEvent(); $(document).off(Event.FOCUSIN); $(this._element).removeClass(ClassName.IN); $(this._element).off(Event.CLICK_DISMISS); $(this._dialog).off(Event.MOUSEDOWN_DISMISS); if (_Util['default'].supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) { $(this._element).one(_Util['default'].TRANSITION_END, $.proxy(this._hideModal, this)).emulateTransitionEnd(TRANSITION_DURATION); } else { this._hideModal(); } } }, { key: 'dispose', value: function dispose() { $.removeData(this._element, DATA_KEY); $(window).off(EVENT_KEY); $(document).off(EVENT_KEY); $(this._element).off(EVENT_KEY); $(this._backdrop).off(EVENT_KEY); this._config = null; this._element = null; this._dialog = null; this._backdrop = null; this._isShown = null; this._isBodyOverflowing = null; this._ignoreBackdropClick = null; this._originalBodyPadding = null; this._scrollbarWidth = null; } // private }, { key: '_getConfig', value: function _getConfig(config) { config = $.extend({}, Default, config); _Util['default'].typeCheckConfig(NAME, config, DefaultType); return config; } }, { key: '_showElement', value: function _showElement(relatedTarget) { var _this2 = this; var transition = _Util['default'].supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE); if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { // don't move modals dom position document.body.appendChild(this._element); } this._element.style.display = 'block'; this._element.scrollTop = 0; if (transition) { _Util['default'].reflow(this._element); } $(this._element).addClass(ClassName.IN); if (this._config.focus) { this._enforceFocus(); } var shownEvent = $.Event(Event.SHOWN, { relatedTarget: relatedTarget }); var transitionComplete = function transitionComplete() { if (_this2._config.focus) { _this2._element.focus(); } $(_this2._element).trigger(shownEvent); }; if (transition) { $(this._dialog).one(_Util['default'].TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION); } else { transitionComplete(); } } }, { key: '_enforceFocus', value: function _enforceFocus() { var _this3 = this; $(document).off(Event.FOCUSIN) // guard against infinite focus loop .on(Event.FOCUSIN, function (event) { if (_this3._element !== event.target && !$(_this3._element).has(event.target).length) { _this3._element.focus(); } }); } }, { key: '_setEscapeEvent', value: function _setEscapeEvent() { var _this4 = this; if (this._isShown && this._config.keyboard) { $(this._element).on(Event.KEYDOWN_DISMISS, function (event) { if (event.which === 27) { _this4.hide(); } }); } else if (!this._isShown) { $(this._element).off(Event.KEYDOWN_DISMISS); } } }, { key: '_setResizeEvent', value: function _setResizeEvent() { if (this._isShown) { $(window).on(Event.RESIZE, $.proxy(this._handleUpdate, this)); } else { $(window).off(Event.RESIZE); } } }, { key: '_hideModal', value: function _hideModal() { var _this5 = this; this._element.style.display = 'none'; this._showBackdrop(function () { $(document.body).removeClass(ClassName.OPEN); _this5._resetAdjustments(); _this5._resetScrollbar(); $(_this5._element).trigger(Event.HIDDEN); }); } }, { key: '_removeBackdrop', value: function _removeBackdrop() { if (this._backdrop) { $(this._backdrop).remove(); this._backdrop = null; } } }, { key: '_showBackdrop', value: function _showBackdrop(callback) { var _this6 = this; var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : ''; if (this._isShown && this._config.backdrop) { var doAnimate = _Util['default'].supportsTransitionEnd() && animate; this._backdrop = document.createElement('div'); this._backdrop.className = ClassName.BACKDROP; if (animate) { $(this._backdrop).addClass(animate); } $(this._backdrop).appendTo(document.body); $(this._element).on(Event.CLICK_DISMISS, function (event) { if (_this6._ignoreBackdropClick) { _this6._ignoreBackdropClick = false; return; } if (event.target !== event.currentTarget) { return; } if (_this6._config.backdrop === 'static') { _this6._element.focus(); } else { _this6.hide(); } }); if (doAnimate) { _Util['default'].reflow(this._backdrop); } $(this._backdrop).addClass(ClassName.IN); if (!callback) { return; } if (!doAnimate) { callback(); return; } $(this._backdrop).one(_Util['default'].TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION); } else if (!this._isShown && this._backdrop) { $(this._backdrop).removeClass(ClassName.IN); var callbackRemove = function callbackRemove() { _this6._removeBackdrop(); if (callback) { callback(); } }; if (_Util['default'].supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) { $(this._backdrop).one(_Util['default'].TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION); } else { callbackRemove(); } } else if (callback) { callback(); } } // ---------------------------------------------------------------------- // the following methods are used to handle overflowing modals // todo (fat): these should probably be refactored out of modal.js // ---------------------------------------------------------------------- }, { key: '_handleUpdate', value: function _handleUpdate() { this._adjustDialog(); } }, { key: '_adjustDialog', value: function _adjustDialog() { var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; if (!this._isBodyOverflowing && isModalOverflowing) { this._element.style.paddingLeft = this._scrollbarWidth + 'px'; } if (this._isBodyOverflowing && !isModalOverflowing) { this._element.style.paddingRight = this._scrollbarWidth + 'px~'; } } }, { key: '_resetAdjustments', value: function _resetAdjustments() { this._element.style.paddingLeft = ''; this._element.style.paddingRight = ''; } }, { key: '_checkScrollbar', value: function _checkScrollbar() { var fullWindowWidth = window.innerWidth; if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8 var documentElementRect = document.documentElement.getBoundingClientRect(); fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left); } this._isBodyOverflowing = document.body.clientWidth < fullWindowWidth; this._scrollbarWidth = this._getScrollbarWidth(); } }, { key: '_setScrollbar', value: function _setScrollbar() { var bodyPadding = parseInt($(Selector.FIXED_CONTENT).css('padding-right') || 0, 10); this._originalBodyPadding = document.body.style.paddingRight || ''; if (this._isBodyOverflowing) { document.body.style.paddingRight = bodyPadding + (this._scrollbarWidth + 'px'); } } }, { key: '_resetScrollbar', value: function _resetScrollbar() { document.body.style.paddingRight = this._originalBodyPadding; } }, { key: '_getScrollbarWidth', value: function _getScrollbarWidth() { // thx d.walsh var scrollDiv = document.createElement('div'); scrollDiv.className = ClassName.SCROLLBAR_MEASURER; document.body.appendChild(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); return scrollbarWidth; } // static }], [{ key: '_jQueryInterface', value: function _jQueryInterface(config, relatedTarget) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = $.extend({}, Modal.Default, $(this).data(), typeof config === 'object' && config); if (!data) { data = new Modal(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { data[config](relatedTarget); } else if (_config.show) { data.show(relatedTarget); } }); } }, { key: 'VERSION', get: function get() { return VERSION; } }, { key: 'Default', get: function get() { return Default; } }]); return Modal; })(); $(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) { var _this7 = this; var target = undefined; var selector = _Util['default'].getSelectorFromElement(this); if (selector) { target = $(selector)[0]; } var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data()); if (this.tagName === 'A') { event.preventDefault(); } var $target = $(target).one(Event.SHOW, function (showEvent) { if (showEvent.isDefaultPrevented()) { // only register focus restorer if modal will actually get shown return; } $target.one(Event.HIDDEN, function () { if ($(_this7).is(':visible')) { _this7.focus(); } }); }); Modal._jQueryInterface.call($(target), config, this); }); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Modal._jQueryInterface; $.fn[NAME].Constructor = Modal; $.fn[NAME].noConflict = function () { $.fn[NAME] = JQUERY_NO_CONFLICT; return Modal._jQueryInterface; }; return Modal; })(jQuery); module.exports = Modal; });
davygxyz/neundorfer
wp-content/themes/neundorfer/sass/bootstrap/docs/dist/js/umd/modal.js
JavaScript
gpl-2.0
17,699
"use strict"; exports.__esModule = true; var _typeof2 = require("babel-runtime/helpers/typeof"); var _typeof3 = _interopRequireDefault(_typeof2); var _keys = require("babel-runtime/core-js/object/keys"); var _keys2 = _interopRequireDefault(_keys); var _getIterator2 = require("babel-runtime/core-js/get-iterator"); var _getIterator3 = _interopRequireDefault(_getIterator2); exports.explode = explode; exports.verify = verify; exports.merge = merge; var _virtualTypes = require("./path/lib/virtual-types"); var virtualTypes = _interopRequireWildcard(_virtualTypes); var _babelMessages = require("babel-messages"); var messages = _interopRequireWildcard(_babelMessages); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); var _clone = require("lodash/clone"); var _clone2 = _interopRequireDefault(_clone); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function explode(visitor) { if (visitor._exploded) return visitor; visitor._exploded = true; for (var nodeType in visitor) { if (shouldIgnoreKey(nodeType)) continue; var parts = nodeType.split("|"); if (parts.length === 1) continue; var fns = visitor[nodeType]; delete visitor[nodeType]; for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var part = _ref; visitor[part] = fns; } } verify(visitor); delete visitor.__esModule; ensureEntranceObjects(visitor); ensureCallbackArrays(visitor); for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var _nodeType3 = _ref2; if (shouldIgnoreKey(_nodeType3)) continue; var wrapper = virtualTypes[_nodeType3]; if (!wrapper) continue; var _fns2 = visitor[_nodeType3]; for (var type in _fns2) { _fns2[type] = wrapCheck(wrapper, _fns2[type]); } delete visitor[_nodeType3]; if (wrapper.types) { for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { var _ref4; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref4 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref4 = _i4.value; } var _type = _ref4; if (visitor[_type]) { mergePair(visitor[_type], _fns2); } else { visitor[_type] = _fns2; } } } else { mergePair(visitor, _fns2); } } for (var _nodeType in visitor) { if (shouldIgnoreKey(_nodeType)) continue; var _fns = visitor[_nodeType]; var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; if (deprecratedKey) { console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); aliases = [deprecratedKey]; } if (!aliases) continue; delete visitor[_nodeType]; for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { var _ref3; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref3 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref3 = _i3.value; } var alias = _ref3; var existing = visitor[alias]; if (existing) { mergePair(existing, _fns); } else { visitor[alias] = (0, _clone2.default)(_fns); } } } for (var _nodeType2 in visitor) { if (shouldIgnoreKey(_nodeType2)) continue; ensureCallbackArrays(visitor[_nodeType2]); } return visitor; } function verify(visitor) { if (visitor._verified) return; if (typeof visitor === "function") { throw new Error(messages.get("traverseVerifyRootFunction")); } for (var nodeType in visitor) { if (nodeType === "enter" || nodeType === "exit") { validateVisitorMethods(nodeType, visitor[nodeType]); } if (shouldIgnoreKey(nodeType)) continue; if (t.TYPES.indexOf(nodeType) < 0) { throw new Error(messages.get("traverseVerifyNodeType", nodeType)); } var visitors = visitor[nodeType]; if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { for (var visitorKey in visitors) { if (visitorKey === "enter" || visitorKey === "exit") { validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); } else { throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); } } } } visitor._verified = true; } function validateVisitorMethods(path, val) { var fns = [].concat(val); for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { var _ref5; if (_isArray5) { if (_i5 >= _iterator5.length) break; _ref5 = _iterator5[_i5++]; } else { _i5 = _iterator5.next(); if (_i5.done) break; _ref5 = _i5.value; } var fn = _ref5; if (typeof fn !== "function") { throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); } } } function merge(visitors) { var states = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; var wrapper = arguments[2]; var rootVisitor = {}; for (var i = 0; i < visitors.length; i++) { var visitor = visitors[i]; var state = states[i]; explode(visitor); for (var type in visitor) { var visitorType = visitor[type]; if (state || wrapper) { visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); } var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; mergePair(nodeVisitor, visitorType); } } return rootVisitor; } function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { var newVisitor = {}; var _loop = function _loop(key) { var fns = oldVisitor[key]; if (!Array.isArray(fns)) return "continue"; fns = fns.map(function (fn) { var newFn = fn; if (state) { newFn = function newFn(path) { return fn.call(state, path, state); }; } if (wrapper) { newFn = wrapper(state.key, key, newFn); } return newFn; }); newVisitor[key] = fns; }; for (var key in oldVisitor) { var _ret = _loop(key); if (_ret === "continue") continue; } return newVisitor; } function ensureEntranceObjects(obj) { for (var key in obj) { if (shouldIgnoreKey(key)) continue; var fns = obj[key]; if (typeof fns === "function") { obj[key] = { enter: fns }; } } } function ensureCallbackArrays(obj) { if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; } function wrapCheck(wrapper, fn) { var newFn = function newFn(path) { if (wrapper.checkPath(path)) { return fn.apply(this, arguments); } }; newFn.toString = function () { return fn.toString(); }; return newFn; } function shouldIgnoreKey(key) { if (key[0] === "_") return true; if (key === "enter" || key === "exit" || key === "shouldSkip") return true; if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; return false; } function mergePair(dest, src) { for (var key in src) { dest[key] = [].concat(dest[key] || [], src[key]); } }
jintoppy/react-training
step8-unittest/node_modules/babel-plugin-transform-decorators/node_modules/babel-traverse/lib/visitors.js
JavaScript
mit
8,665
var gulp = require('gulp'); var paths = require('../paths'); var del = require('del'); var vinylPaths = require('vinyl-paths'); // deletes all files in the output path gulp.task('clean', function() { return gulp.src([paths.output]) .pipe(vinylPaths(del)); });
victorzki/doclify
workspace/build/tasks/clean.js
JavaScript
mit
267
var test = require('tap').test var server = require('./lib/server.js') var common = require('./lib/common.js') var client = common.freshClient() function nop () {} var URI = 'http://localhost:1337/rewrite' var TOKEN = 'b00b00feed' var PARAMS = { auth: { token: TOKEN } } test('logout call contract', function (t) { t.throws(function () { client.logout(undefined, PARAMS, nop) }, 'requires a URI') t.throws(function () { client.logout([], PARAMS, nop) }, 'requires URI to be a string') t.throws(function () { client.logout(URI, undefined, nop) }, 'requires params object') t.throws(function () { client.logout(URI, '', nop) }, 'params must be object') t.throws(function () { client.logout(URI, PARAMS, undefined) }, 'requires callback') t.throws(function () { client.logout(URI, PARAMS, 'callback') }, 'callback must be function') t.throws( function () { var params = { auth: {} } client.logout(URI, params, nop) }, { name: 'AssertionError', message: 'can only log out for token auth' }, 'auth must include token' ) t.end() }) test('log out from a token-based registry', function (t) { server.expect('DELETE', '/-/user/token/' + TOKEN, function (req, res) { t.equal(req.method, 'DELETE') t.equal(req.headers.authorization, 'Bearer ' + TOKEN, 'request is authed') res.json({message: 'ok'}) }) client.logout(URI, PARAMS, function (er) { t.ifError(er, 'no errors') t.end() }) }) test('cleanup', function (t) { server.close() t.end() })
markredballoon/clivemizen
wp-content/themes/redballoon/bootstrap/npm/node_modules/npm-registry-client/test/logout.js
JavaScript
gpl-2.0
1,584
/* Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ //>>built define("dojo/store/JsonRest",["../_base/xhr","../_base/lang","../json","../_base/declare","./util/QueryResults"],function(_1,_2,_3,_4,_5){ var _6=null; return _4("dojo.store.JsonRest",_6,{constructor:function(_7){ this.headers={}; _4.safeMixin(this,_7); },headers:{},target:"",idProperty:"id",ascendingPrefix:"+",descendingPrefix:"-",_getTarget:function(id){ var _8=this.target; if(typeof id!="undefined"){ if(_8.charAt(_8.length-1)=="/"){ _8+=id; }else{ _8+="/"+id; } } return _8; },get:function(id,_9){ _9=_9||{}; var _a=_2.mixin({Accept:this.accepts},this.headers,_9.headers||_9); return _1("GET",{url:this._getTarget(id),handleAs:"json",headers:_a}); },accepts:"application/javascript, application/json",getIdentity:function(_b){ return _b[this.idProperty]; },put:function(_c,_d){ _d=_d||{}; var id=("id" in _d)?_d.id:this.getIdentity(_c); var _e=typeof id!="undefined"; return _1(_e&&!_d.incremental?"PUT":"POST",{url:this._getTarget(id),postData:_3.stringify(_c),handleAs:"json",headers:_2.mixin({"Content-Type":"application/json",Accept:this.accepts,"If-Match":_d.overwrite===true?"*":null,"If-None-Match":_d.overwrite===false?"*":null},this.headers,_d.headers)}); },add:function(_f,_10){ _10=_10||{}; _10.overwrite=false; return this.put(_f,_10); },remove:function(id,_11){ _11=_11||{}; return _1("DELETE",{url:this._getTarget(id),headers:_2.mixin({},this.headers,_11.headers)}); },query:function(_12,_13){ _13=_13||{}; var _14=_2.mixin({Accept:this.accepts},this.headers,_13.headers); var _15=this.target.indexOf("?")>-1; if(_12&&typeof _12=="object"){ _12=_1.objectToQuery(_12); _12=_12?(_15?"&":"?")+_12:""; } if(_13.start>=0||_13.count>=0){ _14["X-Range"]="items="+(_13.start||"0")+"-"+(("count" in _13&&_13.count!=Infinity)?(_13.count+(_13.start||0)-1):""); if(this.rangeParam){ _12+=(_12||_15?"&":"?")+this.rangeParam+"="+_14["X-Range"]; _15=true; }else{ _14.Range=_14["X-Range"]; } } if(_13&&_13.sort){ var _16=this.sortParam; _12+=(_12||_15?"&":"?")+(_16?_16+"=":"sort("); for(var i=0;i<_13.sort.length;i++){ var _17=_13.sort[i]; _12+=(i>0?",":"")+(_17.descending?this.descendingPrefix:this.ascendingPrefix)+encodeURIComponent(_17.attribute); } if(!_16){ _12+=")"; } } var _18=_1("GET",{url:this.target+(_12||""),handleAs:"json",headers:_14}); _18.total=_18.then(function(){ var _19=_18.ioArgs.xhr.getResponseHeader("Content-Range"); if(!_19){ _19=_18.ioArgs.xhr.getResponseHeader("X-Content-Range"); } return _19&&(_19=_19.match(/\/(.*)/))&&+_19[1]; }); return _5(_18); }}); });
mbouami/pme
web/js/dojo/store/JsonRest.js
JavaScript
mit
2,702
var cx = require('classnames'); var blacklist = require('blacklist'); var React = require('react'); module.exports = React.createClass({ displayName: 'Field', getDefaultProps() { return { d: null, t: null, m: null, label: '' } }, renderError() { if(!this.props.error) return null; return <span className="error">{this.props.error}</span>; }, renderLabel() { var cn = cx('label', this.props.d ? `g-${this.props.d}` : null); if(!this.props.label) { return ( <label className={cn}>&nbsp;</label> ); } return ( <label className={cn}> {this.props.label} </label> ); }, render() { var props = blacklist(this.props, 'label', 'error', 'children', 'd', 't', 'm'); props.className = cx('u-field', { 'g-row': this.props.d, 'u-field-row': this.props.d, 'u-field-err': this.props.error }); return ( <div {... props}> {this.renderLabel()} {this.props.d ? ( <div className={`g-${24 - this.props.d}`}> {this.props.children} </div> ) : this.props.children} {this.renderError()} </div> ); } });
wangzuo/feng-ui
react/field.js
JavaScript
isc
1,218
/* @flow */ import { PropTypes } from 'react' export default PropTypes.oneOfType([ // [Number, Number] PropTypes.arrayOf(PropTypes.number), // {lat: Number, lng: Number} PropTypes.shape({ lat: PropTypes.number, lng: PropTypes.number, }), // {lat: Number, lon: Number} PropTypes.shape({ lat: PropTypes.number, lon: PropTypes.number, }), ])
wxtiles/wxtiles-map
node_modules/react-leaflet/src/types/latlng.js
JavaScript
isc
373
import { modulo } from './Math.js' export function random(x) { return modulo(Math.sin(x) * 43758.5453123, 1) }
damienmortini/dlib
packages/core/math/PRNG.js
JavaScript
isc
114
const test = require('tape') const sinon = require('sinon') const helpers = require('../test/helpers') const MockCrock = require('../test/MockCrock') const bindFunc = helpers.bindFunc const curry = require('./curry') const _compose = curry(require('./compose')) const isFunction = require('./isFunction') const isObject = require('./isObject') const isSameType = require('./isSameType') const isString = require('./isString') const unit = require('./_unit') const fl = require('./flNames') const Maybe = require('./Maybe') const Pred = require('./Pred') const constant = x => () => x const identity = x => x const applyTo = x => fn => fn(x) const List = require('./List') test('List', t => { const f = x => List(x).toArray() t.ok(isFunction(List), 'is a function') t.ok(isObject(List([])), 'returns an object') t.equals(List([]).constructor, List, 'provides TypeRep on constructor') t.ok(isFunction(List.of), 'provides an of function') t.ok(isFunction(List.fromArray), 'provides a fromArray function') t.ok(isFunction(List.type), 'provides a type function') t.ok(isString(List['@@type']), 'provides a @@type string') const err = /List: List must wrap something/ t.throws(List, err, 'throws with no parameters') t.same(f(undefined), [ undefined ], 'wraps value in array when called with undefined') t.same(f(null), [ null ], 'wraps value in array when called with null') t.same(f(0), [ 0 ], 'wraps value in array when called with falsey number') t.same(f(1), [ 1 ], 'wraps value in array when called with truthy number') t.same(f(''), [ '' ], 'wraps value in array when called with falsey string') t.same(f('string'), [ 'string' ], 'wraps value in array when called with truthy string') t.same(f(false), [ false ], 'wraps value in array when called with false') t.same(f(true), [ true ], 'wraps value in array when called with true') t.same(f({}), [ {} ], 'wraps value in array when called with an Object') t.same(f([ 1, 2, 3 ]), [ 1, 2, 3 ], 'Does not wrap an array, just uses it as the list') t.end() }) test('List fantasy-land api', t => { const m = List('value') t.ok(isFunction(List[fl.empty]), 'provides empty function on constructor') t.ok(isFunction(List[fl.of]), 'provides of function on constructor') t.ok(isFunction(m[fl.of]), 'provides of method on instance') t.ok(isFunction(m[fl.empty]), 'provides empty method on instance') t.ok(isFunction(m[fl.equals]), 'provides equals method on instance') t.ok(isFunction(m[fl.concat]), 'provides concat method on instance') t.ok(isFunction(m[fl.map]), 'provides map method on instance') t.ok(isFunction(m[fl.chain]), 'provides chain method on instance') t.ok(isFunction(m[fl.reduce]), 'provides reduce method on instance') t.ok(isFunction(m[fl.filter]), 'provides filter method on instance') t.end() }) test('List @@implements', t => { const f = List['@@implements'] t.equal(f('ap'), true, 'implements ap func') t.equal(f('chain'), true, 'implements chain func') t.equal(f('concat'), true, 'implements concat func') t.equal(f('empty'), true, 'implements empty func') t.equal(f('equals'), true, 'implements equals func') t.equal(f('map'), true, 'implements map func') t.equal(f('of'), true, 'implements of func') t.equal(f('reduce'), true, 'implements reduce func') t.equal(f('traverse'), true, 'implements traverse func') t.end() }) test('List fromArray', t => { const fromArray = bindFunc(List.fromArray) const err = /List.fromArray: Array required/ t.throws(fromArray(undefined), err, 'throws with undefined') t.throws(fromArray(null), err, 'throws with null') t.throws(fromArray(0), err, 'throws with falsey number') t.throws(fromArray(1), err, 'throws with truthy number') t.throws(fromArray(''), err, 'throws with falsey string') t.throws(fromArray('string'), err, 'throws with truthy string') t.throws(fromArray(false), err, 'throws with false') t.throws(fromArray(true), err, 'throws with true') t.throws(fromArray({}), err, 'throws with an object') const data = [ [ 2, 1 ], 'a' ] t.ok(isSameType(List, List.fromArray([ 0 ])), 'returns a List') t.same(List.fromArray(data).valueOf(), data, 'wraps the value passed into List in an array') t.end() }) test('List inspect', t => { const m = List([ 1, true, 'string' ]) t.ok(isFunction(m.inspect), 'provides an inpsect function') t.equal(m.inspect, m.toString, 'toString is the same function as inspect') t.equal(m.inspect(), 'List [ 1, true, "string" ]', 'returns inspect string') t.end() }) test('List type', t => { const m = List([]) t.ok(isFunction(m.type), 'is a function') t.equal(m.type, List.type, 'static and instance versions are the same') t.equal(m.type(), 'List', 'returns List') t.end() }) test('List @@type', t => { const m = List([]) t.equal(m['@@type'], List['@@type'], 'static and instance versions are the same') t.equal(m['@@type'], 'crocks/List@4', 'returns crocks/List@4') t.end() }) test('List head', t => { const empty = List.empty() const one = List.of(1) const two = List([ 2, 3 ]) t.ok(isFunction(two.head), 'Provides a head Function') t.ok(isSameType(Maybe, empty.head()), 'empty List returns a Maybe') t.ok(isSameType(Maybe, one.head()), 'one element List returns a Maybe') t.ok(isSameType(Maybe, two.head()), 'two element List returns a Maybe') t.equal(empty.head().option('Nothing'), 'Nothing', 'empty List returns a Nothing') t.equal(one.head().option('Nothing'), 1, 'one element List returns a `Just 1`') t.equal(two.head().option('Nothing'), 2, 'two element List returns a `Just 2`') t.end() }) test('List tail', t => { const empty = List.empty() const one = List.of(1) const two = List([ 2, 3 ]) const three = List([ 4, 5, 6 ]) t.ok(isFunction(two.tail), 'Provides a tail Function') t.equal(empty.tail().type(), Maybe.type(), 'empty List returns a Maybe') t.equal(one.tail().type(), Maybe.type(), 'one element List returns a Maybe') t.equal(two.tail().type(), Maybe.type(), 'two element List returns a Maybe') t.equal(three.tail().type(), Maybe.type(), 'three element List returns a Maybe') t.equal(empty.tail().option('Nothing'), 'Nothing', 'empty List returns a Nothing') t.equal(one.tail().option('Nothing'), 'Nothing', 'one element List returns a `Just 1`') t.equal(two.tail().option('Nothing').type(), 'List', 'two element List returns a `Just List`') t.same(two.tail().option('Nothing').valueOf(), [ 3 ], 'two element Maybe List contains `[ 3 ]`') t.equal(three.tail().option('Nothing').type(), 'List', 'three element List returns a `Just List`') t.same(three.tail().option('Nothing').valueOf(), [ 5, 6 ], 'three element Maybe List contains `[ 5, 6 ]`') t.end() }) test('List cons', t => { const list = List.of('guy') const consed = list.cons('hello') t.ok(isFunction(list.cons), 'provides a cons function') t.notSame(list.valueOf(), consed.valueOf(), 'keeps old list intact') t.same(consed.valueOf(), [ 'hello', 'guy' ], 'returns a list with the element pushed to front') t.end() }) test('List valueOf', t => { const x = List([ 'some-thing', 34 ]).valueOf() t.same(x, [ 'some-thing', 34 ], 'provides the wrapped array') t.end() }) test('List toArray', t => { const data = [ 'some-thing', [ 'else', 43 ], 34 ] const a = List(data).toArray() t.same(a, data, 'provides the wrapped array') t.end() }) test('List equals functionality', t => { const a = List([ 'a', 'b' ]) const b = List([ 'a', 'b' ]) const c = List([ '1', 'b' ]) const value = 'yep' const nonList = { type: 'List...Not' } t.equal(a.equals(c), false, 'returns false when 2 Lists are not equal') t.equal(a.equals(b), true, 'returns true when 2 Lists are equal') t.equal(a.equals(value), false, 'returns false when passed a simple value') t.equal(a.equals(nonList), false, 'returns false when passed a non-List') t.end() }) test('List equals properties (Setoid)', t => { const a = List([ 0, 'like' ]) const b = List([ 0, 'like' ]) const c = List([ 1, 'rainbow' ]) const d = List([ 'like', 0 ]) t.ok(isFunction(List([]).equals), 'provides an equals function') t.equal(a.equals(a), true, 'reflexivity') t.equal(a.equals(b), b.equals(a), 'symmetry (equal)') t.equal(a.equals(c), c.equals(a), 'symmetry (!equal)') t.equal(a.equals(b) && b.equals(d), a.equals(d), 'transitivity') t.end() }) test('List concat properties (Semigroup)', t => { const a = List([ 1, '' ]) const b = List([ 0, null ]) const c = List([ true, 'string' ]) const left = a.concat(b).concat(c) const right = a.concat(b.concat(c)) t.ok(isFunction(a.concat), 'provides a concat function') t.same(left.valueOf(), right.valueOf(), 'associativity') t.equal(a.concat(b).type(), a.type(), 'returns a List') t.end() }) test('List concat errors', t => { const a = List([ 1, 2 ]) const notList = { type: constant('List...Not') } const cat = bindFunc(a.concat) const err = /List.concat: List required/ t.throws(cat(undefined), err, 'throws with undefined') t.throws(cat(null), err, 'throws with null') t.throws(cat(0), err, 'throws with falsey number') t.throws(cat(1), err, 'throws with truthy number') t.throws(cat(''), err, 'throws with falsey string') t.throws(cat('string'), err, 'throws with truthy string') t.throws(cat(false), err, 'throws with false') t.throws(cat(true), err, 'throws with true') t.throws(cat([]), err, 'throws with an array') t.throws(cat({}), err, 'throws with an object') t.throws(cat(notList), err, 'throws when passed non-List') t.end() }) test('List concat fantasy-land errors', t => { const a = List([ 1, 2 ]) const notList = { type: constant('List...Not') } const cat = bindFunc(a[fl.concat]) const err = /List.fantasy-land\/concat: List required/ t.throws(cat(undefined), err, 'throws with undefined') t.throws(cat(null), err, 'throws with null') t.throws(cat(0), err, 'throws with falsey number') t.throws(cat(1), err, 'throws with truthy number') t.throws(cat(''), err, 'throws with falsey string') t.throws(cat('string'), err, 'throws with truthy string') t.throws(cat(false), err, 'throws with false') t.throws(cat(true), err, 'throws with true') t.throws(cat([]), err, 'throws with an array') t.throws(cat({}), err, 'throws with an object') t.throws(cat(notList), err, 'throws when passed non-List') t.end() }) test('List concat functionality', t => { const a = List([ 1, 2 ]) const b = List([ 3, 4 ]) t.same(a.concat(b).valueOf(), [ 1, 2, 3, 4 ], 'concats second to first') t.same(b.concat(a).valueOf(), [ 3, 4, 1, 2 ], 'concats first to second') t.end() }) test('List empty properties (Monoid)', t => { const m = List([ 1, 2 ]) t.ok(isFunction(m.concat), 'provides a concat function') t.ok(isFunction(m.empty), 'provides an empty function') const right = m.concat(m.empty()) const left = m.empty().concat(m) t.same(right.valueOf(), m.valueOf(), 'right identity') t.same(left.valueOf(), m.valueOf(), 'left identity') t.end() }) test('List empty functionality', t => { const x = List([ 0, 1, true ]).empty() t.equal(x.type(), 'List', 'provides a List') t.same(x.valueOf(), [], 'provides an empty array') t.end() }) test('List reduce errors', t => { const reduce = bindFunc(List([ 1, 2 ]).reduce) const err = /List.reduce: Function required for first argument/ t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument') t.throws(reduce(null, 0), err, 'throws with null in the first argument') t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument') t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument') t.throws(reduce('', 0), err, 'throws with falsey string in the first argument') t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument') t.throws(reduce(false, 0), err, 'throws with false in the first argument') t.throws(reduce(true, 0), err, 'throws with true in the first argument') t.throws(reduce({}, 0), err, 'throws with an object in the first argument') t.throws(reduce([], 0), err, 'throws with an array in the first argument') t.end() }) test('List reduce fantasy-land errors', t => { const reduce = bindFunc(List([ 1, 2 ])[fl.reduce]) const err = /List.fantasy-land\/reduce: Function required for first argument/ t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument') t.throws(reduce(null, 0), err, 'throws with null in the first argument') t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument') t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument') t.throws(reduce('', 0), err, 'throws with falsey string in the first argument') t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument') t.throws(reduce(false, 0), err, 'throws with false in the first argument') t.throws(reduce(true, 0), err, 'throws with true in the first argument') t.throws(reduce({}, 0), err, 'throws with an object in the first argument') t.throws(reduce([], 0), err, 'throws with an array in the first argument') t.end() }) test('List reduce functionality', t => { const f = (y, x) => y + x const m = List([ 1, 2, 3 ]) t.equal(m.reduce(f, 0), 6, 'reduces as expected with a neutral initial value') t.equal(m.reduce(f, 10), 16, 'reduces as expected with a non-neutral initial value') t.end() }) test('List reduceRight errors', t => { const reduce = bindFunc(List([ 1, 2 ]).reduceRight) const err = /List.reduceRight: Function required for first argument/ t.throws(reduce(undefined, 0), err, 'throws with undefined in the first argument') t.throws(reduce(null, 0), err, 'throws with null in the first argument') t.throws(reduce(0, 0), err, 'throws with falsey number in the first argument') t.throws(reduce(1, 0), err, 'throws with truthy number in the first argument') t.throws(reduce('', 0), err, 'throws with falsey string in the first argument') t.throws(reduce('string', 0), err, 'throws with truthy string in the first argument') t.throws(reduce(false, 0), err, 'throws with false in the first argument') t.throws(reduce(true, 0), err, 'throws with true in the first argument') t.throws(reduce({}, 0), err, 'throws with an object in the first argument') t.throws(reduce([], 0), err, 'throws with an array in the first argument') t.end() }) test('List reduceRight functionality', t => { const f = (y, x) => y.concat(x) const m = List([ '1', '2', '3' ]) t.equal(m.reduceRight(f, '4'), '4321', 'reduces as expected') t.end() }) test('List fold errors', t => { const f = bindFunc(x => List(x).fold()) const noSemi = /^TypeError: List.fold: List must contain Semigroups of the same type/ t.throws(f(undefined), noSemi, 'throws when contains single undefined') t.throws(f(null), noSemi, 'throws when contains single null') t.throws(f(0), noSemi, 'throws when contains single falsey number') t.throws(f(1), noSemi, 'throws when contains single truthy number') t.throws(f(false), noSemi, 'throws when contains single false') t.throws(f(true), noSemi, 'throws when contains single true') t.throws(f({}), noSemi, 'throws when contains a single object') t.throws(f(unit), noSemi, 'throws when contains a single function') const empty = /^TypeError: List.fold: List must contain at least one Semigroup/ t.throws(f([]), empty, 'throws when empty') const diff = /^TypeError: List.fold: List must contain Semigroups of the same type/ t.throws(f([ [], '' ]), diff, 'throws when empty') t.end() }) test('List fold functionality', t => { const f = x => List(x).fold() t.same(f([ [ 1 ], [ 2 ] ]), [ 1, 2 ], 'combines and extracts semigroups') t.equals(f('lucky'), 'lucky', 'extracts a single semigroup') t.end() }) test('List foldMap errors', t => { const noFunc = bindFunc(fn => List([ 1 ]).foldMap(fn)) const funcErr = /^TypeError: List.foldMap: Semigroup returning function required/ t.throws(noFunc(undefined), funcErr, 'throws with undefined') t.throws(noFunc(null), funcErr, 'throws with null') t.throws(noFunc(0), funcErr, 'throws with falsey number') t.throws(noFunc(1), funcErr, 'throws with truthy number') t.throws(noFunc(false), funcErr, 'throws with false') t.throws(noFunc(true), funcErr, 'throws with true') t.throws(noFunc(''), funcErr, 'throws with falsey string') t.throws(noFunc('string'), funcErr, 'throws with truthy string') t.throws(noFunc({}), funcErr, 'throws with an object') t.throws(noFunc([]), funcErr, 'throws with an array') const fn = bindFunc(x => List(x).foldMap(identity)) const emptyErr = /^TypeError: List.foldMap: List must not be empty/ t.throws(fn([]), emptyErr, 'throws when passed an empty List') const notSameSemi = /^TypeError: List.foldMap: Provided function must return Semigroups of the same type/ t.throws(fn([ 0 ]), notSameSemi, 'throws when function does not return a Semigroup') t.throws(fn([ '', 0 ]), notSameSemi, 'throws when not all returned values are Semigroups') t.throws(fn([ '', [] ]), notSameSemi, 'throws when different semigroups are returned') t.end() }) test('List foldMap functionality', t => { const fold = xs => List(xs).foldMap(x => x.toString()) t.same(fold([ 1, 2 ]), '12', 'combines and extracts semigroups') t.same(fold([ 3 ]), '3', 'extracts a single semigroup') t.end() }) test('List filter fantasy-land errors', t => { const filter = bindFunc(List([ 0 ])[fl.filter]) const err = /List.fantasy-land\/filter: Pred or predicate function required/ t.throws(filter(undefined), err, 'throws with undefined') t.throws(filter(null), err, 'throws with null') t.throws(filter(0), err, 'throws with falsey number') t.throws(filter(1), err, 'throws with truthy number') t.throws(filter(''), err, 'throws with falsey string') t.throws(filter('string'), err, 'throws with truthy string') t.throws(filter(false), err, 'throws with false') t.throws(filter(true), err, 'throws with true') t.throws(filter([]), err, 'throws with an array') t.throws(filter({}), err, 'throws with an object') t.end() }) test('List filter errors', t => { const filter = bindFunc(List([ 0 ]).filter) const err = /List.filter: Pred or predicate function required/ t.throws(filter(undefined), err, 'throws with undefined') t.throws(filter(null), err, 'throws with null') t.throws(filter(0), err, 'throws with falsey number') t.throws(filter(1), err, 'throws with truthy number') t.throws(filter(''), err, 'throws with falsey string') t.throws(filter('string'), err, 'throws with truthy string') t.throws(filter(false), err, 'throws with false') t.throws(filter(true), err, 'throws with true') t.throws(filter([]), err, 'throws with an array') t.throws(filter({}), err, 'throws with an object') t.end() }) test('List filter functionality', t => { const m = List([ 4, 5, 10, 34, 'string' ]) const bigNum = x => typeof x === 'number' && x > 10 const justStrings = x => typeof x === 'string' const bigNumPred = Pred(bigNum) const justStringsPred = Pred(justStrings) t.same(m.filter(bigNum).valueOf(), [ 34 ], 'filters for bigNums with function') t.same(m.filter(justStrings).valueOf(), [ 'string' ], 'filters for strings with function') t.same(m.filter(bigNumPred).valueOf(), [ 34 ], 'filters for bigNums with Pred') t.same(m.filter(justStringsPred).valueOf(), [ 'string' ], 'filters for strings with Pred') t.end() }) test('List filter properties (Filterable)', t => { const m = List([ 2, 6, 10, 25, 9, 28 ]) const n = List([ 'string', 'party' ]) const isEven = x => x % 2 === 0 const isBig = x => x >= 10 const left = m.filter(x => isBig(x) && isEven(x)).valueOf() const right = m.filter(isBig).filter(isEven).valueOf() t.same(left, right , 'distributivity') t.same(m.filter(() => true).valueOf(), m.valueOf(), 'identity') t.same(m.filter(() => false).valueOf(), n.filter(() => false).valueOf(), 'annihilation') t.end() }) test('List reject errors', t => { const reject = bindFunc(List([ 0 ]).reject) const err = /List.reject: Pred or predicate function required/ t.throws(reject(undefined), err, 'throws with undefined') t.throws(reject(null), err, 'throws with null') t.throws(reject(0), err, 'throws with falsey number') t.throws(reject(1), err, 'throws with truthy number') t.throws(reject(''), err, 'throws with falsey string') t.throws(reject('string'), err, 'throws with truthy string') t.throws(reject(false), err, 'throws with false') t.throws(reject(true), err, 'throws with true') t.throws(reject([]), err, 'throws with an array') t.throws(reject({}), err, 'throws with an object') t.end() }) test('List reject functionality', t => { const m = List([ 4, 5, 10, 34, 'string' ]) const bigNum = x => typeof x === 'number' && x > 10 const justStrings = x => typeof x === 'string' const bigNumPred = Pred(bigNum) const justStringsPred = Pred(justStrings) t.same(m.reject(bigNum).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with function') t.same(m.reject(justStrings).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with function') t.same(m.reject(bigNumPred).valueOf(), [ 4, 5, 10, 'string' ], 'rejects bigNums with Pred') t.same(m.reject(justStringsPred).valueOf(), [ 4, 5, 10, 34 ], 'rejects strings with Pred') t.end() }) test('List map errors', t => { const map = bindFunc(List([]).map) const err = /List.map: Function required/ t.throws(map(undefined), err, 'throws with undefined') t.throws(map(null), err, 'throws with null') t.throws(map(0), err, 'throws with falsey number') t.throws(map(1), err, 'throws with truthy number') t.throws(map(''), err, 'throws with falsey string') t.throws(map('string'), err, 'throws with truthy string') t.throws(map(false), err, 'throws with false') t.throws(map(true), err, 'throws with true') t.throws(map([]), err, 'throws with an array') t.throws(map({}), err, 'throws with an object') t.doesNotThrow(map(unit), 'allows a function') t.end() }) test('List map fantasy-land errors', t => { const map = bindFunc(List([])[fl.map]) const err = /List.fantasy-land\/map: Function required/ t.throws(map(undefined), err, 'throws with undefined') t.throws(map(null), err, 'throws with null') t.throws(map(0), err, 'throws with falsey number') t.throws(map(1), err, 'throws with truthy number') t.throws(map(''), err, 'throws with falsey string') t.throws(map('string'), err, 'throws with truthy string') t.throws(map(false), err, 'throws with false') t.throws(map(true), err, 'throws with true') t.throws(map([]), err, 'throws with an array') t.throws(map({}), err, 'throws with an object') t.doesNotThrow(map(unit), 'allows a function') t.end() }) test('List map functionality', t => { const spy = sinon.spy(identity) const xs = [ 42 ] const m = List(xs).map(spy) t.equal(m.type(), 'List', 'returns a List') t.equal(spy.called, true, 'calls mapping function') t.same(m.valueOf(), xs, 'returns the result of the map inside of new List') t.end() }) test('List map properties (Functor)', t => { const m = List([ 49 ]) const f = x => x + 54 const g = x => x * 4 t.ok(isFunction(m.map), 'provides a map function') t.same(m.map(identity).valueOf(), m.valueOf(), 'identity') t.same(m.map(_compose(f, g)).valueOf(), m.map(g).map(f).valueOf(), 'composition') t.end() }) test('List ap errors', t => { const left = bindFunc(x => List([ x ]).ap(List([ 0 ]))) const noFunc = /List.ap: Wrapped values must all be functions/ t.throws(left([ undefined ]), noFunc, 'throws when wrapped value is undefined') t.throws(left([ null ]), noFunc, 'throws when wrapped value is null') t.throws(left([ 0 ]), noFunc, 'throws when wrapped value is a falsey number') t.throws(left([ 1 ]), noFunc, 'throws when wrapped value is a truthy number') t.throws(left([ '' ]), noFunc, 'throws when wrapped value is a falsey string') t.throws(left([ 'string' ]), noFunc, 'throws when wrapped value is a truthy string') t.throws(left([ false ]), noFunc, 'throws when wrapped value is false') t.throws(left([ true ]), noFunc, 'throws when wrapped value is true') t.throws(left([ [] ]), noFunc, 'throws when wrapped value is an array') t.throws(left([ {} ]), noFunc, 'throws when wrapped value is an object') t.throws(left([ unit, 'string' ]), noFunc, 'throws when wrapped values are not all functions') const ap = bindFunc(x => List([ unit ]).ap(x)) const noList = /List.ap: List required/ t.throws(ap(undefined), noList, 'throws with undefined') t.throws(ap(null), noList, 'throws with null') t.throws(ap(0), noList, 'throws with falsey number') t.throws(ap(1), noList, 'throws with truthy number') t.throws(ap(''), noList, 'throws with falsey string') t.throws(ap('string'), noList, 'throws with truthy string') t.throws(ap(false), noList, 'throws with false') t.throws(ap(true), noList, 'throws with true') t.throws(ap([]), noList, 'throws with an array') t.throws(ap({}), noList, 'throws with an object') t.end() }) test('List ap properties (Apply)', t => { const m = List([ identity ]) const a = m.map(_compose).ap(m).ap(m) const b = m.ap(m.ap(m)) t.ok(isFunction(List([]).ap), 'provides an ap function') t.ok(isFunction(List([]).map), 'implements the Functor spec') t.same(a.ap(List([ 3 ])).valueOf(), b.ap(List([ 3 ])).valueOf(), 'composition') t.end() }) test('List of', t => { t.equal(List.of, List([]).of, 'List.of is the same as the instance version') t.equal(List.of(0).type(), 'List', 'returns a List') t.same(List.of(0).valueOf(), [ 0 ], 'wraps the value passed into List in an array') t.end() }) test('List of properties (Applicative)', t => { const m = List([ identity ]) t.ok(isFunction(List([]).of), 'provides an of function') t.ok(isFunction(List([]).ap), 'implements the Apply spec') t.same(m.ap(List([ 3 ])).valueOf(), [ 3 ], 'identity') t.same(m.ap(List.of(3)).valueOf(), List.of(identity(3)).valueOf(), 'homomorphism') const a = x => m.ap(List.of(x)) const b = x => List.of(applyTo(x)).ap(m) t.same(a(3).valueOf(), b(3).valueOf(), 'interchange') t.end() }) test('List chain errors', t => { const chain = bindFunc(List([ 0 ]).chain) const bad = bindFunc(x => List.of(x).chain(identity)) const noFunc = /List.chain: Function required/ t.throws(chain(undefined), noFunc, 'throws with undefined') t.throws(chain(null), noFunc, 'throws with null') t.throws(chain(0), noFunc, 'throw with falsey number') t.throws(chain(1), noFunc, 'throws with truthy number') t.throws(chain(''), noFunc, 'throws with falsey string') t.throws(chain('string'), noFunc, 'throws with truthy string') t.throws(chain(false), noFunc, 'throws with false') t.throws(chain(true), noFunc, 'throws with true') t.throws(chain([]), noFunc, 'throws with an array') t.throws(chain({}), noFunc, 'throws with an object') const noList = /List.chain: Function must return a List/ t.throws(bad(undefined), noList, 'throws when function returns undefined') t.throws(bad(null), noList, 'throws when function returns null') t.throws(bad(0), noList, 'throws when function returns falsey number') t.throws(bad(1), noList, 'throws when function returns truthy number') t.throws(bad(''), noList, 'throws when function returns falsey string') t.throws(bad('string'), noList, 'throws when function returns truthy string') t.throws(bad(false), noList, 'throws when function returns false') t.throws(bad(true), noList, 'throws when function returns true') t.throws(bad([]), noList, 'throws when function returns an array') t.throws(bad({}), noList, 'throws when function returns an object') t.throws(bad(unit), noList, 'throws when function returns a function') t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT') t.end() }) test('List chain fantasy-land errors', t => { const chain = bindFunc(List([ 0 ])[fl.chain]) const bad = bindFunc(x => List.of(x)[fl.chain](identity)) const noFunc = /List.fantasy-land\/chain: Function required/ t.throws(chain(undefined), noFunc, 'throws with undefined') t.throws(chain(null), noFunc, 'throws with null') t.throws(chain(0), noFunc, 'throw with falsey number') t.throws(chain(1), noFunc, 'throws with truthy number') t.throws(chain(''), noFunc, 'throws with falsey string') t.throws(chain('string'), noFunc, 'throws with truthy string') t.throws(chain(false), noFunc, 'throws with false') t.throws(chain(true), noFunc, 'throws with true') t.throws(chain([]), noFunc, 'throws with an array') t.throws(chain({}), noFunc, 'throws with an object') const noList = /List.fantasy-land\/chain: Function must return a List/ t.throws(bad(undefined), noList, 'throws when function returns undefined') t.throws(bad(null), noList, 'throws when function returns null') t.throws(bad(0), noList, 'throws when function returns falsey number') t.throws(bad(1), noList, 'throws when function returns truthy number') t.throws(bad(''), noList, 'throws when function returns falsey string') t.throws(bad('string'), noList, 'throws when function returns truthy string') t.throws(bad(false), noList, 'throws when function returns false') t.throws(bad(true), noList, 'throws when function returns true') t.throws(bad([]), noList, 'throws when function returns an array') t.throws(bad({}), noList, 'throws when function returns an object') t.throws(bad(unit), noList, 'throws when function returns a function') t.throws(bad(MockCrock), noList, 'throws when function a non-List ADT') t.end() }) test('List chain properties (Chain)', t => { t.ok(isFunction(List([]).chain), 'provides a chain function') t.ok(isFunction(List([]).ap), 'implements the Apply spec') const f = x => List.of(x + 2) const g = x => List.of(x + 10) const a = x => List.of(x).chain(f).chain(g) const b = x => List.of(x).chain(y => f(y).chain(g)) t.same(a(10).valueOf(), b(10).valueOf(), 'assosiativity') t.end() }) test('List chain properties (Monad)', t => { t.ok(isFunction(List([]).chain), 'implements the Chain spec') t.ok(isFunction(List([]).of), 'implements the Applicative spec') const f = x => List([ x ]) t.same(List.of(3).chain(f).valueOf(), f(3).valueOf(), 'left identity') t.same(f(3).chain(List.of).valueOf(), f(3).valueOf(), 'right identity') t.end() }) test('List sequence errors', t => { const seq = bindFunc(List.of(MockCrock(2)).sequence) const seqBad = bindFunc(List.of(0).sequence) const err = /List.sequence: Applicative TypeRep or Apply returning function required/ t.throws(seq(undefined), err, 'throws with undefined') t.throws(seq(null), err, 'throws with null') t.throws(seq(0), err, 'throws falsey with number') t.throws(seq(1), err, 'throws truthy with number') t.throws(seq(''), err, 'throws falsey with string') t.throws(seq('string'), err, 'throws with truthy string') t.throws(seq(false), err, 'throws with false') t.throws(seq(true), err, 'throws with true') t.throws(seq([]), err, 'throws with an array') t.throws(seq({}), err, 'throws with an object') const noAppl = /List.sequence: Must wrap Applys of the same type/ t.throws(seqBad(unit), noAppl, 'wrapping non-Apply throws') t.end() }) test('List sequence with Apply function', t => { const x = 'string' const fn = x => MockCrock(x) const m = List.of(MockCrock(x)).sequence(fn) t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock') t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List') t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value') const ar = x => [ x ] const arM = List.of([ x ]).sequence(ar) t.ok(isSameType(Array, arM), 'Provides an outer type of Array') t.ok(isSameType(List, arM[0]), 'Provides an inner type of List') t.same(arM[0].valueOf(), [ x ], 'inner List contains original inner value') t.end() }) test('List sequence with Applicative TypeRep', t => { const x = 'string' const m = List.of(MockCrock(x)).sequence(MockCrock) t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock') t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List') t.same(m.valueOf().valueOf(), [ x ], 'inner List contains original inner value') const ar = List.of([ x ]).sequence(Array) t.ok(isSameType(Array, ar), 'Provides an outer type of Array') t.ok(isSameType(List, ar[0]), 'Provides an inner type of List') t.same(ar[0].valueOf(), [ x ], 'inner List contains original inner value') t.end() }) test('List traverse errors', t => { const trav = bindFunc(List.of(2).traverse) const first = /List.traverse: Applicative TypeRep or Apply returning function required for first argument/ t.throws(trav(undefined, MockCrock), first, 'throws with undefined in first argument') t.throws(trav(null, MockCrock), first, 'throws with null in first argument') t.throws(trav(0, MockCrock), first, 'throws falsey with number in first argument') t.throws(trav(1, MockCrock), first, 'throws truthy with number in first argument') t.throws(trav('', MockCrock), first, 'throws falsey with string in first argument') t.throws(trav('string', MockCrock), first, 'throws with truthy string in first argument') t.throws(trav(false, MockCrock), first, 'throws with false in first argument') t.throws(trav(true, MockCrock), first, 'throws with true in first argument') t.throws(trav([], MockCrock), first, 'throws with an array in first argument') t.throws(trav({}, MockCrock), first, 'throws with an object in first argument') const second = /List.traverse: Apply returning functions required for second argument/ t.throws(trav(MockCrock, undefined), second, 'throws with undefined in second argument') t.throws(trav(MockCrock, null), second, 'throws with null in second argument') t.throws(trav(MockCrock, 0), second, 'throws falsey with number in second argument') t.throws(trav(MockCrock, 1), second, 'throws truthy with number in second argument') t.throws(trav(MockCrock, ''), second, 'throws falsey with string in second argument') t.throws(trav(MockCrock, 'string'), second, 'throws with truthy string in second argument') t.throws(trav(MockCrock, false), second, 'throws with false in second argument') t.throws(trav(MockCrock, true), second, 'throws with true in second argument') t.throws(trav(MockCrock, []), second, 'throws with an array in second argument') t.throws(trav(MockCrock, {}), second, 'throws with an object in second argument') const noAppl = /List.traverse: Both functions must return an Apply of the same type/ t.throws(trav(unit, MockCrock), noAppl, 'throws with non-Appicative returning function in first argument') t.throws(trav(MockCrock, unit), noAppl, 'throws with non-Appicative returning function in second argument') t.end() }) test('List traverse with Apply function', t => { const x = 'string' const res = 'result' const f = x => MockCrock(x) const fn = m => constant(m(res)) const m = List.of(x).traverse(f, fn(MockCrock)) t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock') t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List') t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value') const ar = x => [ x ] const arM = List.of(x).traverse(ar, fn(ar)) t.ok(isSameType(Array, arM), 'Provides an outer type of Array') t.ok(isSameType(List, arM[0]), 'Provides an inner type of List') t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value') t.end() }) test('List traverse with Applicative TypeRep', t => { const x = 'string' const res = 'result' const fn = m => constant(m(res)) const m = List.of(x).traverse(MockCrock, fn(MockCrock)) t.ok(isSameType(MockCrock, m), 'Provides an outer type of MockCrock') t.ok(isSameType(List, m.valueOf()), 'Provides an inner type of List') t.same(m.valueOf().valueOf(), [ res ], 'inner List contains transformed value') const ar = x => [ x ] const arM = List.of(x).traverse(Array, fn(ar)) t.ok(isSameType(Array, arM), 'Provides an outer type of Array') t.ok(isSameType(List, arM[0]), 'Provides an inner type of List') t.same(arM[0].valueOf(), [ res ], 'inner List contains transformed value') t.end() })
evilsoft/crocks
src/core/List.spec.js
JavaScript
isc
36,528
'use strict'; var main = { expand:true, cwd: './build/styles/', src:['*.css'], dest: './build/styles/' }; module.exports = { main:main };
ariosejs/bui
grunt/config/cssmin.js
JavaScript
isc
161
/** * QUnit v1.3.0pre - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2011 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. * Pulled Live from Git Sat Jan 14 01:10:01 UTC 2012 * Last Commit: 0712230bb203c262211649b32bd712ec7df5f857 */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e) { return false; } })() }; var testId = 0, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.className = "running"; li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( config.previousModule ) { runLoggingCallbacks('moduleDone', QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( 'moduleStart', QUnit, { name: this.module } ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } runLoggingCallbacks( 'testStart', QUnit, { name: this.testName, module: this.module }); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if ( !config.pollution ) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message ); } }, run: function() { config.current = this; if ( this.async ) { QUnit.stop(); } if ( config.notrycatch ) { this.callback.call(this.testEnvironment); return; } try { this.callback.call(this.testEnvironment); } catch(e) { fail("Test " + this.testName + " died, exception and test follows", e, this.callback); QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; try { this.testEnvironment.teardown.call(this.testEnvironment); checkPollution(); } catch(e) { QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message ); } }, finish: function() { config.current = this; if ( this.expected != null && this.expected != this.assertions.length ) { QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( var i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if (bad) { sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); } else { sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); } } if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; var a = document.createElement("a"); a.innerHTML = "Rerun"; a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); addEvent(b, "click", function() { var next = b.nextSibling.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( a ); li.appendChild( ol ); } else { for ( var i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); } runLoggingCallbacks( 'testDone', QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length } ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); if (bad) { run(); } else { synchronize(run, true); }; } }; var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>', testEnvironmentArg; if ( arguments.length === 2 ) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if ( expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeInnerText(msg); runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function(count) { config.semaphore -= count || 1; if (config.semaphore > 0) { // don't start until equal number of stop-calls return; } if (config.semaphore < 0) { // ignore if start is called more often then stop config.semaphore = 0; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if (config.semaphore > 0) { return; } if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(true); }, 13); } else { config.blocking = false; process(true); } }, stop: function(count) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout(config.timeout); config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout); } } }; //We want access to the constructor's prototype (function() { function F(){}; F.prototype = QUnit; QUnit = new F(); //Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; })(); // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, urlConfig: ['noglobals', 'notrycatch'], //logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}, current; if ( params[ 0 ] ) { for ( var i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; config.filter = urlParams.filter; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 0 }); var tests = id( "qunit-tests" ), banner = id( "qunit-banner" ), result = id( "qunit-testresult" ); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = 'Running...<br/>&nbsp;'; } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if ( window.jQuery ) { jQuery( "#qunit-fixture" ).html( config.fixture ); } else { var main = id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeInnerText(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeInnerText(QUnit.jsDump.parse(expected)); actual = escapeInnerText(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>'; } } output += "</table>"; runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var querystring = "?", key; for ( key in params ) { if ( !hasOwn.call( params, key ) ) { continue; } querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } return window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent }); //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later //Doing this allows us to tell if the following methods have been overwritten on the actual //QUnit object, which is a deprecated way of using the callbacks. extend(QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback('begin'), // done: { failed, passed, total, runtime } done: registerLoggingCallback('done'), // log: { result, actual, expected, message } log: registerLoggingCallback('log'), // testStart: { name } testStart: registerLoggingCallback('testStart'), // testDone: { name, failed, passed, total } testDone: registerLoggingCallback('testDone'), // moduleStart: { name } moduleStart: registerLoggingCallback('moduleStart'), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback('moduleDone') }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( 'begin', QUnit, {} ); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var urlConfigHtml = '', len = config.urlConfig.length; for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) { config[val] = QUnit.urlParams[val]; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; } var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml; addEvent( banner, "change", function( event ) { var params = {}; params[ event.target.name ] = event.target.checked ? true : undefined; window.location = QUnit.url( params ); }); } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var ol = document.getElementById("qunit-tests"); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace(/ hidepass /, " "); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem("qunit-filter-passed-tests", "true"); } else { sessionStorage.removeItem("qunit-filter-passed-tests"); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { filter.checked = true; var ol = document.getElementById("qunit-tests"); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }; addEvent(window, "load", QUnit.load); // addEvent(window, "error") gives us a useless event object window.onerror = function( message, file, line ) { if ( QUnit.config.current ) { ok( false, message + ", " + file + ":" + line ); } else { test( "global failure", function() { ok( false, message + ", " + file + ":" + line ); }); } }; function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { runLoggingCallbacks( 'moduleDone', QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), runtime = +new Date - config.started, passed = config.stats.all - config.stats.bad, html = [ 'Tests completed in ', runtime, ' milliseconds.<br/>', '<span class="passed">', passed, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad, '</span> failed.' ].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && typeof document !== "undefined" && document.title ) { // show ✖ for good, ✔ for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ (config.stats.bad ? "\u2716" : "\u2714"), document.title.replace(/^[\u2714\u2716] /i, "") ].join(" "); } runLoggingCallbacks( 'done', QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime } ); } function validTest( name ) { var filter = config.filter, run = false; if ( !filter ) { return true; } var not = filter.charAt( 0 ) === "!"; if ( not ) { filter = filter.slice( 1 ); } if ( name.indexOf( filter ) !== -1 ) { return !not; } if ( not ) { run = true; } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch ( e ) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } else if (e.sourceURL) { // Safari, PhantomJS // TODO sourceURL points at the 'throw new Error' line above, useless //return e.sourceURL + ":" + e.line; } } } function escapeInnerText(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&<>]/g, function(s) { switch(s) { case "&": return "&amp;"; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(last); } } function process( last ) { var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { window.setTimeout( function(){ process( last ); }, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( !hasOwn.call( window, key ) ) { continue; } config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { ok( false, "Introduced global variable(s): " + newGlobals.join(", ") ); } var deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.error(exception.stack); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { if ( b[prop] === undefined ) { delete a[prop]; // Avoid "Member not found" error in IE8 caused by setting window.constructor } else if ( prop !== "constructor" || a !== window ) { a[prop] = b[prop]; } } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } function registerLoggingCallback(key){ return function(callback){ config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks(key, scope, args) { //debugger; var callbacks; if ( QUnit.hasOwnProperty(key) ) { QUnit[key].call(scope, args); } else { callbacks = config[key]; for( var i = 0; i < callbacks.length; i++ ) { callbacks[i].call( scope, args ); } } } // Test for equality any JavaScript type. // Author: Philippe Rathé <[email protected]> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var getProto = Object.getPrototypeOf || function (obj) { return obj.__proto__; }; var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string" : useStrictEquality, "boolean" : useStrictEquality, "number" : useStrictEquality, "null" : useStrictEquality, "undefined" : useStrictEquality, "nan" : function(b) { return isNaN(b); }, "date" : function(b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp" : function(b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function" : function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array" : function(b, a) { var i, j, loop; var len; // b could be an object literal here if (!(QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } // track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { loop = true;// dont rewalk array } } if (!loop && !innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object" : function(b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of // strings // comparing constructors is more strict than using // instanceof if (a.constructor !== b.constructor) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if (!((getProto(a) === null && getProto(b) === Object.prototype) || (getProto(b) === null && getProto(a) === Object.prototype))) { return false; } } // stack constructor before traversing properties callers.push(a.constructor); // track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty // and go deep loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) loop = true; // don't go down the same path // twice } aProperties.push(i); // collect a's properties if (!loop && !innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties .sort()); } }; }(); innerEquiv = function() { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function(a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1)); }; return innerEquiv; }(); /** * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * http://flesler.blogspot.com Licensed under BSD * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr, stack ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] , undefined , stack); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance stack = stack || [ ]; var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; var inStack = inArray(obj, stack); if (inStack != -1) { return 'recursion('+(inStack - stack.length)+')'; } //else if (type == 'function') { stack.push(obj); var res = parser.call( this, obj, stack ); stack.pop(); return res; } // else return (type == 'string') ? parser : this.parsers.error; }, typeOf:function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', 'undefined':'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map, stack ) { var ret = [ ]; QUnit.jsDump.up(); for ( var key in map ) { var val = map[key]; ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack)); } QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; }; //from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n) { var ns = {}; var os = {}; for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: [], o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: [], n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if ( !hasOwn.call( ns, i ) ) { continue; } if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n) { o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
crgwbr/flakeyjs
tests/qunit.js
JavaScript
isc
41,188
import AddLearningToStoryDescription from '../../../../src/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description' import WWLTWRepository from '../../../../src/content_scripts/repositories/wwltw_repository'; import StoryTitleProvider from '../../../../src/content_scripts/utilities/story_title_provider'; import ProjectIdProvider from '../../../../src/content_scripts/utilities/project_id_provider'; describe('AddLearningToStoryDescription', function () { let wwltwRepositorySpy; let foundStory; let execute; const projectId = 'some project id'; const storyTitle = 'some story title'; beforeEach(function () { wwltwRepositorySpy = new WWLTWRepository(); foundStory = {id: '1234'}; spyOn(chrome.runtime, 'sendMessage'); spyOn(wwltwRepositorySpy, 'findByTitle').and.returnValue(Promise.resolve([foundStory])); spyOn(wwltwRepositorySpy, 'update').and.returnValue(Promise.resolve()); spyOn(StoryTitleProvider, 'currentStoryTitle').and.returnValue(storyTitle); spyOn(ProjectIdProvider, 'getProjectId').and.returnValue(projectId); const useCase = new AddLearningToStoryDescription(wwltwRepositorySpy); execute = useCase.execute; }); describe('execute', function () { describe('when called outside of AddLearningToStoryDescription instance', function () { it('finds the story', function () { execute('some tag, some other tag', 'some body'); expect(wwltwRepositorySpy.findByTitle).toHaveBeenCalledWith( projectId, storyTitle ); }); it('sends analytics data', function () { execute(); expect(chrome.runtime.sendMessage).toHaveBeenCalledWith({ eventType: 'submit' }); }); it('updates the found story', function (done) { const body = 'some body'; const tags = 'some tag, some other tag'; execute(tags, body).then(function () { expect(wwltwRepositorySpy.update).toHaveBeenCalledWith( projectId, foundStory, tags, body ); done(); }); }); }); }); });
oliverswitzer/wwltw-for-pivotal-tracker
test/content_scripts/pivotal_tracker/use_cases/add_learning_to_story_description_spec.js
JavaScript
isc
2,332
"use strict"; var Template = function (options) { this._pageTitle = ''; this._titleSeparator = options.title_separator; this._siteTitle = options.site_title; this._req = null; this._res = null; }; Template.prototype.bindMiddleware = function(req, res) { this._req = req; this._res = res; }; Template.prototype.setPageTitle = function(pageTitle) { this._pageTitle = pageTitle; }; Template.prototype.setSiteTitle = function(siteTitle) { this._siteTitle = siteTitle; }; Template.prototype.setTitleSeparator = function(separator) { this._titleSeparator = separator; }; Template.prototype.getTitle = function() { if (this._pageTitle !== '') { return this._pageTitle + ' ' + this._titleSeparator + ' ' + this._siteTitle; } else { return this._siteTitle; } }; Template.prototype.getPageTitle = function() { return this._pageTitle; }; Template.prototype.getSiteTitle = function() { return this._siteTitle; }; Template.prototype.render = function(path, params) { this._res.render('partials/' + path, params); }; module.exports = Template;
mythos-framework/mythos-lib-template
Template.js
JavaScript
isc
1,091
/* eslint-env mocha */ const mockBot = require('../mockBot') const assert = require('assert') const mockery = require('mockery') const sinon = require('sinon') const json = JSON.stringify({ state: 'normal', nowTitle: 'Midnight News', nowInfo: '20/03/2019', nextStart: '2019-03-20T00:30:00Z', nextTitle: 'Book of the Week' }) describe('radio module', function () { let sandbox before(function () { // mockery mocks the entire require() mockery.enable() mockery.registerMock('request-promise', { get: () => Promise.resolve(json) }) // sinon stubs individual functions sandbox = sinon.sandbox.create() mockBot.loadModule('radio') }) it('should parse the API correctly', async function () { sandbox.useFakeTimers({ now: 1553040900000 }) // 2019-03-20T00:15:00Z const promise = await mockBot.runCommand('!r4') assert.strictEqual(promise, 'Now: \u000300Midnight News\u000f \u000315(20/03/2019)\u000f followed by Book of the Week in 15 minutes (12:30 am)') }) after(function (done) { mockery.disable() mockery.deregisterAll() done() }) })
zuzakistan/civilservant
test/modules/radio.js
JavaScript
isc
1,122
describe("Membrane Panel Operations with flat files:", function() { "use strict"; var window; beforeEach(async function() { await getDocumentLoadPromise("base/gui/index.html"); window = testFrame.contentWindow; window.LoadPanel.testMode = {fakeFiles: true}; let p1 = MessageEventPromise(window, "MembranePanel initialized"); let p2 = MessageEventPromise( window, "MembranePanel cached configuration reset" ); window.OuterGridManager.membranePanelRadio.click(); await Promise.all([p1, p2]); }); function getErrorMessage() { let output = window.OuterGridManager.currentErrorOutput; if (!output.firstChild) return null; return output.firstChild.nodeValue; } it("starts with no graph names and two rows", function() { // two delete buttons and one add button { let buttons = window.HandlerNames.grid.getElementsByTagName("button"); expect(buttons.length).toBe(3); for (let i = 0; i < buttons.length; i++) { expect(buttons[i].disabled).toBe(i < buttons.length - 1); } } const [graphNames, graphSymbolLists] = window.HandlerNames.serializableNames(); expect(Array.isArray(graphNames)).toBe(true); expect(Array.isArray(graphSymbolLists)).toBe(true); expect(graphNames.length).toBe(0); expect(graphSymbolLists.length).toBe(0); expect(getErrorMessage()).toBe(null); }); it("supports the pass-through function for the membrane", function() { const editor = window.MembranePanel.passThroughEditor; { expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false); } { window.MembranePanel.passThroughCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); } { window.MembranePanel.primordialsCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); const prelim = "(function() {\n const items = Membrane.Primordials.slice(0);\n\n"; const value = window.MembranePanel.getPassThrough(true); expect(value.startsWith(prelim)).toBe(true); } { window.MembranePanel.primordialsCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(false); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(true); } { window.MembranePanel.passThroughCheckbox.click(); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(false); expect(window.MembranePanel.primordialsCheckbox.disabled).toBe(true); expect(window.CodeMirrorManager.getEditorEnabled(editor)).toBe(false); } }); describe( "The graph handler names API requires at least two distinct names (either symbols or strings)", function() { function validateControls() { window.HandlerNames.update(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); const rv = []; const length = inputs.length; for (let i = 0; i < length; i++) { rv.push(inputs[i].checkValidity()); expect(inputs[i].nextElementSibling.disabled).toBe(length == 2); } return rv; } it("initial state is disallowed for two inputs", function() { const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(false); expect(states[1]).toBe(false); }); it("allows a name to be an unique string", function() { const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(true); expect(states[1]).toBe(true); }); it("clicking on the addRow button really does add a new row", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(false); }); it("disallows non-unique strings", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(false); }); it("allows removing a row", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "baz"; inputs[0].nextElementSibling.click(); expect(inputs.length).toBe(2); expect(inputs[0].value).toBe("bar"); expect(inputs[1].value).toBe("baz"); const states = validateControls(); expect(states.length).toBe(2); expect(states[0]).toBe(true); expect(states[1]).toBe(true); }); it("allows a symbol to share a name with a string", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(true); }); it("allows two symbols to share a name", function() { window.HandlerNames.addRow(); const inputs = window.MembranePanel.form.getElementsByClassName("objectgraph-name"); inputs[0].value = "foo"; inputs[1].value = "bar"; inputs[2].value = "foo"; inputs[0].previousElementSibling.firstElementChild.checked = true; // symbol inputs[2].previousElementSibling.firstElementChild.checked = true; // symbol const states = validateControls(); expect(states.length).toBe(3); expect(states[0]).toBe(true); expect(states[1]).toBe(true); expect(states[2]).toBe(true); }); } ); }); it("Membrane Panel supports pass-through function", async function() { await getDocumentLoadPromise("base/gui/index.html"); const window = testFrame.contentWindow; window.LoadPanel.testMode = { fakeFiles: true, configSource: `{ "configurationSetup": { "useZip": false, "commonFiles": [], "formatVersion": 1, "lastUpdated": "Mon, 19 Feb 2018 20:56:56 GMT" }, "membrane": { "passThroughSource": " // hello world", "passThroughEnabled": true, "primordialsPass": true }, "graphs": [ { "name": "wet", "isSymbol": false, "passThroughSource": "", "passThroughEnabled": false, "primordialsPass": false, "distortions": [] }, { "name": "dry", "isSymbol": false, "passThroughSource": "", "passThroughEnabled": false, "primordialsPass": false, "distortions": [] } ] }` }; let p1 = MessageEventPromise(window, "MembranePanel initialized"); let p2 = MessageEventPromise( window, "MembranePanel cached configuration reset", "MembranePanel exception thrown in reset" ); window.OuterGridManager.membranePanelRadio.click(); await Promise.all([p1, p2]); expect(window.MembranePanel.passThroughCheckbox.checked).toBe(true); expect(window.MembranePanel.primordialsCheckbox.checked).toBe(true); expect(window.MembranePanel.getPassThrough()).toContain("// hello world"); });
ajvincent/es7-membrane
docs/gui/tests/membranePanel.js
JavaScript
isc
9,110
tressa.title('HyperHTML'); tressa.assert(typeof hyperHTML === 'function', 'hyperHTML is a function'); try { tressa.log(''); } catch(e) { tressa.log = console.log.bind(console); } tressa.async(function (done) { tressa.log('## injecting text and attributes'); var i = 0; var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); function update(i) { return render` <p data-counter="${i}"> Time: ${ // IE Edge mobile did something funny here // as template string returned xxx.xxxx // but as innerHTML returned xxx.xx (Math.random() * new Date).toFixed(2) } </p> `; } function compare(html) { return /^\s*<p data-counter="\d">\s*Time: \d+\.\d+<[^>]+?>\s*<\/p>\s*$/i.test(html); } var html = update(i++).innerHTML; var p = div.querySelector('p'); var attr = p.attributes[0]; tressa.assert(compare(html), 'correct HTML'); tressa.assert(html === div.innerHTML, 'correctly returned'); setTimeout(function () { tressa.log('## updating same nodes'); var html = update(i++).innerHTML; tressa.assert(compare(html), 'correct HTML update'); tressa.assert(html === div.innerHTML, 'update applied'); tressa.assert(p === div.querySelector('p'), 'no node was changed'); tressa.assert(attr === p.attributes[0], 'no attribute was changed'); done(); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## perf: same virtual text twice'); var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); var html = (update('hello').innerHTML, update('hello').innerHTML); function update(text) { return render`<p>${text} world</p>`; } tressa.assert( update('hello').innerHTML === update('hello').innerHTML, 'same text' ); done(div); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## injecting HTML'); var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); var html = update('hello').innerHTML; function update(text) { return render`<p>${['<strong>' + text + '</strong>']}</p>`; } function compare(html) { return /^<p><strong>\w+<\/strong><!--.+?--><\/p>$/i.test(html); } tressa.assert(compare(html), 'HTML injected'); tressa.assert(html === div.innerHTML, 'HTML returned'); done(div); }); }) .then(function (div) { return tressa.async(function (done) { tressa.log('## function attributes'); var render = hyperHTML.bind(div); var times = 0; update(function (e) { console.log(e.type); if (++times > 1) { return tressa.assert(false, 'events are broken'); } if (e) { e.preventDefault(); e.stopPropagation(); } tressa.assert(true, 'onclick invoked'); tressa.assert(!a.hasAttribute('onclick'), 'no attribute'); update(null); e = document.createEvent('Event'); e.initEvent('click', false, false); a.dispatchEvent(e); done(div); }); function update(click) { // also test case-insensitive builtin events return render`<a href="#" onClick="${click}">click</a>`; } var a = div.querySelector('a'); var e = document.createEvent('Event'); e.initEvent('click', false, false); a.dispatchEvent(e); }); }) .then(function (div) { return tressa.async(function (done) { tressa.log('## changing template'); var render = hyperHTML.bind(div); var html = update('hello').innerHTML; function update(text) { return render`<p>${{any: ['<em>' + text + '</em>']}}</p>`; } function compare(html) { return /^<p><em>\w+<\/em><!--.+?--><\/p>$/i.test(html); } tressa.assert(compare(html), 'new HTML injected'); tressa.assert(html === div.innerHTML, 'new HTML returned'); done(div); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## custom events'); var render = hyperHTML.bind(document.createElement('p')); var e = document.createEvent('Event'); e.initEvent('Custom-EVENT', true, true); (render`<span onCustom-EVENT="${function (e) { tressa.assert(e.type === 'Custom-EVENT', 'event triggered'); done(); }}">how cool</span>` ).firstElementChild.dispatchEvent(e); }); }) .then(function () { tressa.log('## multi wire removal'); var render = hyperHTML.wire(); var update = function () { return render` <p>1</p> <p>2</p> `; }; update().remove(); update = function () { return render` <p>1</p> <p>2</p> <p>3</p> `; }; update().remove(); tressa.assert(true, 'OK'); }) .then(function () { tressa.log('## the attribute id'); var div = document.createElement('div'); hyperHTML.bind(div)`<p id=${'id'} class='class'>OK</p>`; tressa.assert(div.firstChild.id === 'id', 'the id is preserved'); tressa.assert(div.firstChild.className === 'class', 'the class is preserved'); }) .then(function () { return tressa.async(function (done) { tressa.log('## hyperHTML.wire()'); var render = hyperHTML.wire(); var update = function () { return render` <p>1</p> `; }; var node = update(); tressa.assert(node.nodeName.toLowerCase() === 'p', 'correct node'); var same = update(); tressa.assert(node === same, 'same node returned'); render = hyperHTML.wire(null); update = function () { return render` 0 <p>1</p> `; }; node = update().childNodes; tressa.assert(Array.isArray(node), 'list of nodes'); same = update().childNodes; tressa.assert( node.length === same.length && node[0] && node.every(function (n, i) { return same[i] === n; }), 'same list returned' ); var div = document.createElement('div'); render = hyperHTML.bind(div); render`${node}`; same = div.childNodes; tressa.assert( node[0] && node.every(function (n, i) { return same[i] === n; }), 'same list applied' ); function returnSame() { return render`a`; } render = hyperHTML.wire(); tressa.assert( returnSame() === returnSame(), 'template sensible wire' ); done(); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## hyperHTML.wire(object)'); var point = {x: 1, y: 2}; function update() { return hyperHTML.wire(point)` <span style="${` position: absolute; left: ${point.x}px; top: ${point.y}px; `}">O</span>`; } try { update(); } catch(e) { console.error(e) } tressa.assert(update() === update(), 'same output'); tressa.assert(hyperHTML.wire(point) === hyperHTML.wire(point), 'same wire'); done(); }); }) .then(function () { if (typeof MutationObserver === 'undefined') return; return tressa.async(function (done) { tressa.log('## preserve first child where first child is the same as incoming'); var div = document.body.appendChild(document.createElement('div')); var render = hyperHTML.bind(div); var observer = new MutationObserver(function (mutations) { for (var i = 0, len = mutations.length; i < len; i++) { trackMutations(mutations[i].addedNodes, 'added'); trackMutations(mutations[i].removedNodes, 'removed'); } }); observer.observe(div, { childList: true, subtree: true, }); var counters = []; function trackMutations (nodes, countKey) { for (var i = 0, len = nodes.length, counter, key; i < len; i++) { if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute('data-test')) { key = nodes[i].getAttribute('data-test'); counter = counters[key] || (counters[key] = { added: 0, removed: 0 }); counter[countKey]++; } if (nodes[i].childNodes.length > 0) { trackMutations(nodes[i].childNodes, countKey); } } } var listItems = []; function update(items) { render` <section> <ul>${ items.map(function (item, i) { return hyperHTML.wire((listItems[i] || (listItems[i] = {})))` <li data-test="${i}">${() => item.text}</li> `; }) }</ul> </section>`; } update([]); setTimeout(function () { update([{ text: 'test1' }]); }, 10); setTimeout(function () { update([{ text: 'test1' }, { text: 'test2' }]); }, 20); setTimeout(function () { update([{ text: 'test1' }]); }, 30); setTimeout(function () { if (counters.length) { tressa.assert(counters[0].added === 1, 'first item added only once'); tressa.assert(counters[0].removed === 0, 'first item never removed'); } done(); }, 100); }); }) .then(function () { tressa.log('## rendering one node'); var div = document.createElement('div'); var br = document.createElement('br'); var hr = document.createElement('hr'); hyperHTML.bind(div)`<div>${br}</div>`; tressa.assert(div.firstChild.firstChild === br, 'one child is added'); hyperHTML.bind(div)`<div>${hr}</div>`; tressa.assert(div.firstChild.firstChild === hr, 'one child is changed'); hyperHTML.bind(div)`<div>${[hr, br]}</div>`; tressa.assert( div.firstChild.childNodes[0] === hr && div.firstChild.childNodes[1] === br, 'more children are added' ); hyperHTML.bind(div)`<div>${[br, hr]}</div>`; tressa.assert( div.firstChild.childNodes[0] === br && div.firstChild.childNodes[1] === hr, 'children can be swapped' ); hyperHTML.bind(div)`<div>${br}</div>`; tressa.assert(div.firstChild.firstChild === br, 'one child is kept'); hyperHTML.bind(div)`<div>${[]}</div>`; tressa.assert(/<div><!--.+?--><\/div>/.test(div.innerHTML), 'dropped all children'); }) .then(function () { tressa.log('## wire by id'); let ref = {}; let wires = { a: function () { return hyperHTML.wire(ref, ':a')`<a></a>`; }, p: function () { return hyperHTML.wire(ref, ':p')`<p></p>`; } }; tressa.assert(wires.a().nodeName.toLowerCase() === 'a', '<a> is correct'); tressa.assert(wires.p().nodeName.toLowerCase() === 'p', '<p> is correct'); tressa.assert(wires.a() === wires.a(), 'same wire for <a>'); tressa.assert(wires.p() === wires.p(), 'same wire for <p>'); }) .then(function () { return tressa.async(function (done) { tressa.log('## Promises instead of nodes'); let wrap = document.createElement('div'); let render = hyperHTML.bind(wrap); render`<p>${ new Promise(function (r) { setTimeout(r, 50, 'any'); }) }</p>${ new Promise(function (r) { setTimeout(r, 10, 'virtual'); }) }<hr><div>${[ new Promise(function (r) { setTimeout(r, 20, 1); }), new Promise(function (r) { setTimeout(r, 10, 2); }), ]}</div>${[ new Promise(function (r) { setTimeout(r, 20, 3); }), new Promise(function (r) { setTimeout(r, 10, 4); }), ]}`; let result = wrap.innerHTML; setTimeout(function () { tressa.assert(result !== wrap.innerHTML, 'promises fullfilled'); tressa.assert( /^<p>any<!--.+?--><\/p>virtual<!--.+?--><hr(?: ?\/)?><div>12<!--.+?--><\/div>34<!--.+?-->$/.test(wrap.innerHTML), 'both any and virtual content correct' ); done(); }, 100); }); }) .then(function () { hyperHTML.engine = hyperHTML.engine; tressa.log('## for code coverage sake'); let wrap = document.createElement('div'); let text = [document.createTextNode('a'), document.createTextNode('b'), document.createTextNode('c')]; let testingMajinBuu = hyperHTML.bind(wrap); testingMajinBuu`${[text]}`; tressa.assert(wrap.textContent === 'abc'); text[0] = document.createTextNode('c'); text[2] = document.createTextNode('a'); testingMajinBuu`${[text]}`; tressa.assert(wrap.textContent === 'cba'); let result = hyperHTML.wire()`<!--not hyperHTML-->`; tressa.assert(result.nodeType === 8, 'it is a comment'); tressa.assert(result.textContent === 'not hyperHTML', 'correct content'); hyperHTML.bind(wrap)`<br/>${'node before'}`; tressa.assert(/^<br(?: ?\/)?>node before<!--.+?-->$/i.test(wrap.innerHTML), 'node before'); hyperHTML.bind(wrap)`${'node after'}<br/>`; tressa.assert(/^node after<!--.+?--><br(?: ?\/)?>$/i.test(wrap.innerHTML), 'node after'); hyperHTML.bind(wrap)`<style> ${'hyper-html{}'} </style>`; tressa.assert('<style>hyper-html{}</style>' === wrap.innerHTML.toLowerCase(), 'node style'); var empty = function (value) { return hyperHTML.bind(wrap)`${value}`; }; empty(document.createTextNode('a')); empty(document.createDocumentFragment()); empty(document.createDocumentFragment()); let fragment = document.createDocumentFragment(); fragment.appendChild(document.createTextNode('b')); empty(fragment); empty(123); tressa.assert(wrap.textContent === '123', 'text as number'); empty(true); tressa.assert(wrap.textContent === 'true', 'text as boolean'); empty([1]); tressa.assert(wrap.textContent === '1', 'text as one entry array'); empty(['1', '2']); tressa.assert(wrap.textContent === '12', 'text as multi entry array of strings'); let arr = [document.createTextNode('a'), document.createTextNode('b')]; empty([arr]); tressa.assert(wrap.textContent === 'ab', 'text as multi entry array of nodes'); empty([arr]); tressa.assert(wrap.textContent === 'ab', 'same array of nodes'); empty(wrap.childNodes); tressa.assert(wrap.textContent === 'ab', 'childNodes as list'); hyperHTML.bind(wrap)`a=${{length:1, '0':'b'}}`; tressa.assert(wrap.textContent === 'a=b', 'childNodes as virtual list'); empty = function () { return hyperHTML.bind(wrap)`[${'text'}]`; }; empty(); empty(); let onclick = (e) => {}; let handler = {handleEvent: onclick}; empty = function () { return hyperHTML.bind(wrap)`<p onclick="${onclick}" onmouseover="${handler}" align="${'left'}"></p>`; }; empty(); handler = {handleEvent: onclick}; empty(); empty(); empty = function (value) { return hyperHTML.bind(wrap)`<br/>${value}<br/>`; }; empty(arr[0]); empty(arr); empty(arr); empty([]); empty(['1', '2']); empty(document.createDocumentFragment()); tressa.assert(true, 'passed various virtual content scenarios'); let svgContainer = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); if (!('ownerSVGElement' in svgContainer)) svgContainer.ownerSVGElement = null; hyperHTML.bind(svgContainer)`<rect x="1" y="2" />`; result = hyperHTML.wire(null, 'svg')`<svg></svg>`; tressa.assert(result.nodeName.toLowerCase() === 'svg', 'svg content is allowed too'); result = hyperHTML.wire()``; tressa.assert(!result.innerHTML, 'empty content'); let tr = hyperHTML.wire()`<tr><td>ok</td></tr>`; tressa.assert(true, 'even TR as template'); hyperHTML.bind(wrap)`${' 1 '}`; tressa.assert(wrap.textContent === ' 1 ', 'text in between'); hyperHTML.bind(wrap)` <br/>${1}<br/> `; tressa.assert(/^\s*<br(?: ?\/)?>1<!--.+?--><br(?: ?\/)?>\s*$/.test(wrap.innerHTML), 'virtual content in between'); let last = hyperHTML.wire(); empty = function (style) { return last`<textarea style=${style}>${() => 'same text'}</textarea>`; }; empty('border:0'); empty({border: 0}); empty({vh: 100}); empty({vh: 10, vw: 1}); empty(null); empty(''); const sameStyle = {ord: 0}; empty(sameStyle); empty(sameStyle); empty = function () { return last`<p data=${last}></p>`; }; empty(); empty(); let p = last`<p data=${last}>${0}</p>`; const UID = p.childNodes[1].data; last`<textarea new>${`<!--${UID}-->`}</textarea>`; hyperHTML.wire()`<p><!--ok--></p>`; }) .then(function () { tressa.log('## <script> shenanigans'); return tressa.async(function (done) { var div = document.createElement('div'); document.body.appendChild(div); hyperHTML.bind(div)`<script src="../index.js?_=asd" onreadystatechange="${event => { if (/loaded|complete/.test(event.readyState)) setTimeout(() => { tressa.assert(true, 'executed'); done(); }); }}" onload="${() => { tressa.assert(true, 'executed'); done(); }}" onerror="${() => { tressa.assert(true, 'executed'); done(); }}" ></script>`; // in nodejs case if (!('onload' in document.defaultView)) { var evt = document.createEvent('Event'); evt.initEvent('load', false, false); div.firstChild.dispatchEvent(evt); } }); }) .then(function () { tressa.log('## SVG and style'); var render = hyperHTML.wire(null, 'svg'); Object.prototype.ownerSVGElement = null; function rect(style) { return render`<rect style=${style} />`; } var node = rect({}); delete Object.prototype.ownerSVGElement; rect({width: 100}); console.log(node.getAttribute('style')); tressa.assert(/width:\s*100px;/.test(node.getAttribute('style')), 'correct style object'); rect('height:10px;'); tressa.assert(/height:\s*10px;/.test(node.getAttribute('style')), 'correct style string'); rect(null); tressa.assert(/^(?:|null)$/.test(node.getAttribute('style')), 'correct style reset'); }) .then(function () { var a = document.createTextNode('a'); var b = document.createTextNode('b'); var c = document.createTextNode('c'); var d = document.createTextNode('d'); var e = document.createTextNode('e'); var f = document.createTextNode('f'); var g = document.createTextNode('g'); var h = document.createTextNode('h'); var i = document.createTextNode('i'); var div = document.createElement('div'); var render = hyperHTML.bind(div); render`${[]}`; tressa.assert(div.textContent === '', 'div is empty'); render`${[c, d, e, f]}`; // all tests know that a comment node is inside the div tressa.assert(div.textContent === 'cdef' && div.childNodes.length === 5, 'div has 4 nodes'); render`${[c, d, e, f]}`; tressa.assert(div.textContent === 'cdef', 'div has same 4 nodes'); render`${[a, b, c, d, e, f]}`; tressa.assert(div.textContent === 'abcdef' && div.childNodes.length === 7, 'div has same 4 nodes + 2 prepends'); render`${[a, b, c, d, e, f, g, h, i]}`; tressa.assert(div.textContent === 'abcdefghi' && div.childNodes.length === 10, 'div has 6 nodes + 3 appends'); render`${[b, c, d, e, f, g, h, i]}`; tressa.assert(div.textContent === 'bcdefghi' && div.childNodes.length === 9, 'div has dropped first node'); render`${[b, c, d, e, f, g, h]}`; tressa.assert(div.textContent === 'bcdefgh' && div.childNodes.length === 8, 'div has dropped last node'); render`${[b, c, d, f, e, g, h]}`; tressa.assert(div.textContent === 'bcdfegh', 'div has changed 2 nodes'); render`${[b, d, c, f, g, e, h]}`; tressa.assert(div.textContent === 'bdcfgeh', 'div has changed 4 nodes'); render`${[b, d, c, g, e, h]}`; tressa.assert(div.textContent === 'bdcgeh' && div.childNodes.length === 7, 'div has removed central node'); }) .then(function () { tressa.log('## no WebKit backfire'); var div = document.createElement('div'); function update(value, attr) { return hyperHTML.bind(div)` <input value="${value}" shaka="${attr}">`; } var input = update('', '').firstElementChild; input.value = '456'; input.setAttribute('shaka', 'laka'); update('123', 'laka'); tressa.assert(input.value === '123', 'correct input'); tressa.assert(input.value === '123', 'correct attribute'); update('', ''); input.value = '123'; input.attributes.shaka.value = 'laka'; update('123', 'laka'); tressa.assert(input.value === '123', 'input.value was not reassigned'); }) .then(function () { tressa.log('## wired arrays are rendered properly'); var div = document.createElement('div'); var employees = [ {first: 'Bob', last: 'Li'}, {first: 'Ayesha', last: 'Johnson'} ]; var getEmployee = employee => hyperHTML.wire(employee)` <div>First name: ${employee.first}</div> <p></p>`; hyperHTML.bind(div)`${employees.map(getEmployee)}`; tressa.assert(div.childElementCount === 4, 'correct elements as setAny'); hyperHTML.bind(div)` <p></p>${employees.map(getEmployee)}`; tressa.assert(div.childElementCount === 5, 'correct elements as setVirtual'); hyperHTML.bind(div)` <p></p>${[]}`; tressa.assert(div.childElementCount === 1, 'only one element left'); }) .then(function () {return tressa.async(function (done) { function textarea(value) { return hyperHTML.bind(div)`<textarea>${value}</textarea>`; } tressa.log('## textarea text'); var div = document.createElement('div'); textarea(1); var ta = div.firstElementChild; tressa.assert(ta.textContent === '1', 'primitives are fine'); textarea(null); tressa.assert(ta.textContent === '', 'null/undefined is fine'); var p = Promise.resolve('OK'); textarea(p); p.then(function () { console.log(div.innerHTML); tressa.assert(ta.textContent === 'OK', 'promises are fine'); textarea({text: 'text'}); tressa.assert(ta.textContent === 'text', 'text is fine'); textarea({html: 'html'}); tressa.assert(ta.textContent === 'html', 'html is fine'); textarea({any: 'any'}); tressa.assert(ta.textContent === 'any', 'any is fine'); textarea(['ar', 'ray']); tressa.assert(ta.textContent === 'array', 'array is fine'); textarea({placeholder: 'placeholder'}); tressa.assert(ta.textContent === 'placeholder', 'placeholder is fine'); textarea({unknown: 'unknown'}); tressa.assert(ta.textContent === '', 'intents are fine'); done(); }); })}) .then(function () { tressa.log('## attributes with weird chars'); var div = document.createElement('div'); hyperHTML.bind(div)`<p _foo=${'bar'}></p>`; tressa.assert(div.firstChild.getAttribute('_foo') === 'bar', 'OK'); }) .then(function () { tressa.log('## attributes without quotes'); var div = document.createElement('div'); hyperHTML.bind(div)`<p test=${'a"b'}></p>`; tressa.assert(div.firstChild.getAttribute('test') === 'a"b', 'OK'); }) .then(function () { tressa.log('## any content extras'); var div = document.createElement('div'); var html = hyperHTML.bind(div); setContent(undefined); tressa.assert(/<p><!--.+?--><\/p>/.test(div.innerHTML), 'expected layout'); setContent({text: '<img/>'}); tressa.assert(/<p>&lt;img(?: ?\/)?&gt;<!--.+?--><\/p>/.test(div.innerHTML), 'expected text'); function setContent(which) { return html`<p>${which}</p>`; } }) .then(function () { tressa.log('## any different content extras'); var div = document.createElement('div'); hyperHTML.bind(div)`<p>${undefined}</p>`; tressa.assert(/<p><!--.+?--><\/p>/.test(div.innerHTML), 'expected layout'); hyperHTML.bind(div)`<p>${{text: '<img/>'}}</p>`; tressa.assert(/<p>&lt;img(?: ?\/)?&gt;<!--.+?--><\/p>/.test(div.innerHTML), 'expected text'); }) .then(function () { tressa.log('## virtual content extras'); var div = document.createElement('div'); hyperHTML.bind(div)`a ${null}`; tressa.assert(/a <[^>]+?>/.test(div.innerHTML), 'expected layout'); hyperHTML.bind(div)`a ${{text: '<img/>'}}`; tressa.assert(/a &lt;img(?: ?\/)?&gt;<[^>]+?>/.test(div.innerHTML), 'expected text'); hyperHTML.bind(div)`a ${{any: 123}}`; tressa.assert(/a 123<[^>]+?>/.test(div.innerHTML), 'expected any'); hyperHTML.bind(div)`a ${{html: '<b>ok</b>'}}`; tressa.assert(/a <b>ok<\/b><[^>]+?>/.test(div.innerHTML), 'expected html'); hyperHTML.bind(div)`a ${{}}`; tressa.assert(/a <[^>]+?>/.test(div.innerHTML), 'expected nothing'); }) .then(function () { tressa.log('## defined transformer'); hyperHTML.define('eUC', encodeURIComponent); var div = document.createElement('div'); hyperHTML.bind(div)`a=${{eUC: 'b c'}}`; tressa.assert(/a=b%20c<[^>]+?>/.test(div.innerHTML), 'expected virtual layout'); hyperHTML.bind(div)`<p>${{eUC: 'b c'}}</p>`; tressa.assert(/<p>b%20c<!--.+?--><\/p>/.test(div.innerHTML), 'expected layout'); // TODO: for coverage sake // defined transformer ... so what? hyperHTML.define('eUC', encodeURIComponent); // non existent one ... so what? hyperHTML.bind(div)`a=${{nOPE: 'b c'}}`; }) .then(function () { tressa.log('## attributes with null values'); var div = document.createElement('div'); var anyAttr = function (value) { hyperHTML.bind(div)`<p any-attr=${value}>any content</p>`; }; anyAttr('1'); tressa.assert( div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') === '1', 'regular attribute' ); anyAttr(null); tressa.assert( !div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') == null, 'can be removed' ); anyAttr(undefined); tressa.assert( !div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') == null, 'multiple times' ); anyAttr('2'); tressa.assert( div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') === '2', 'but can be also reassigned' ); anyAttr('3'); tressa.assert( div.firstChild.hasAttribute('any-attr') && div.firstChild.getAttribute('any-attr') === '3', 'many other times' ); var inputName = function (value) { hyperHTML.bind(div)`<input name=${value}>`; }; inputName('test'); tressa.assert( div.firstChild.hasAttribute('name') && div.firstChild.name === 'test', 'special attributes are set too' ); inputName(null); tressa.assert( !div.firstChild.hasAttribute('name') && !div.firstChild.name, 'but can also be removed' ); inputName(undefined); tressa.assert( !div.firstChild.hasAttribute('name') && !div.firstChild.name, 'with either null or undefined' ); inputName('back'); tressa.assert( div.firstChild.hasAttribute('name') && div.firstChild.name === 'back', 'and can be put back' ); }) .then(function () {return tressa.async(function (done) { tressa.log('## placeholder'); var div = document.createElement('div'); var vdiv = document.createElement('div'); hyperHTML.bind(div)`<p>${{eUC: 'b c', placeholder: 'z'}}</p>`; hyperHTML.bind(vdiv)`a=${{eUC: 'b c', placeholder: 'z'}}`; tressa.assert(/<p>z<!--.+?--><\/p>/.test(div.innerHTML), 'expected inner placeholder layout'); tressa.assert(/a=z<[^>]+?>/.test(vdiv.innerHTML), 'expected virtual placeholder layout'); setTimeout(function () { tressa.assert(/<p>b%20c<!--.+?--><\/p>/.test(div.innerHTML), 'expected inner resolved layout'); tressa.assert(/a=b%20c<[^>]+?>/.test(vdiv.innerHTML), 'expected virtual resolved layout'); hyperHTML.bind(div)`<p>${{text: 1, placeholder: '9'}}</p>`; setTimeout(function () { tressa.assert(/<p>1<!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with text'); hyperHTML.bind(div)`<p>${{any: [1, 2], placeholder: '9'}}</p>`; setTimeout(function () { tressa.assert(/<p>12<!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with any'); hyperHTML.bind(div)`<p>${{html: '<b>3</b>', placeholder: '9'}}</p>`; setTimeout(function () { tressa.assert(/<p><b>3<\/b><!--.+?--><\/p>/.test(div.innerHTML), 'placeholder with html'); done(); }, 10); }, 10); }, 10); }, 10); });}) .then(function () { tressa.log('## hyper(...)'); var hyper = hyperHTML.hyper; tressa.assert(typeof hyper() === 'function', 'empty hyper() is a wire tag'); tressa.assert((hyper`abc`).textContent === 'abc', 'hyper`abc`'); tressa.assert((hyper`<p>a${2}c</p>`).textContent === 'a2c', 'hyper`<p>a${2}c</p>`'); tressa.assert((hyper(document.createElement('div'))`abc`).textContent === 'abc', 'hyper(div)`abc`'); tressa.assert((hyper(document.createElement('div'))`a${'b'}c`).textContent === 'abc', 'hyper(div)`a${"b"}c`'); // WFT jsdom ?! delete Object.prototype.nodeType; tressa.assert((hyper({})`abc`).textContent === 'abc', 'hyper({})`abc`'); tressa.assert((hyper({})`<p>a${'b'}c</p>`).textContent === 'abc', 'hyper({})`<p>a${\'b\'}c</p>`'); tressa.assert((hyper({}, ':id')`abc`).textContent === 'abc', 'hyper({}, \':id\')`abc`'); tressa.assert((hyper({}, ':id')`<p>a${'b'}c</p>`).textContent === 'abc', 'hyper({}, \':id\')`<p>a${\'b\'}c</p>`'); tressa.assert((hyper('svg')`<rect />`), 'hyper("svg")`<rect />`'); }) .then(function () { tressa.log('## data=${anyContent}'); var obj = {rand: Math.random()}; var div = hyperHTML.wire()`<div data=${obj}>abc</div>`; tressa.assert(div.data === obj, 'data available without serialization'); tressa.assert(div.outerHTML === '<div>abc</div>', 'attribute not there'); }) .then(function () { tressa.log('## hyper.Component'); class Button extends hyperHTML.Component { render() { return this.html` <button>hello</button>`; } } class Rect extends hyperHTML.Component { constructor(state) { super(); this.setState(state, false); } render() { return this.svg` <rect x=${this.state.x} y=${this.state.y} />`; } } class Paragraph extends hyperHTML.Component { constructor(state) { super(); this.setState(state); } onclick() { this.clicked = true; } render() { return this.html` <p attr=${this.state.attr} onclick=${this}>hello</p>`; } } var div = document.createElement('div'); var render = hyperHTML.bind(div); render`${[ new Button, new Rect({x: 123, y: 456}) ]}`; tressa.assert(div.querySelector('button'), 'the <button> exists'); tressa.assert(div.querySelector('rect'), 'the <rect /> exists'); tressa.assert(div.querySelector('rect').getAttribute('x') == '123', 'attributes are OK'); var p = new Paragraph(() => ({attr: 'test'})); render`${p}`; tressa.assert(div.querySelector('p').getAttribute('attr') === 'test', 'the <p attr=test> is defined'); p.render().click(); tressa.assert(p.clicked, 'the event worked'); render`${[ hyperHTML.Component.for.call(Rect, {x: 789, y: 123}) ]}`; tressa.assert(div.querySelector('rect').getAttribute('x') == '789', 'the for(state) worked'); }) .then(function () { return tressa.async(function (done) { tressa.log('## Component method via data-call'); class Paragraph extends hyperHTML.Component { globally(e) { tressa.assert(e.type === 'click', 'data-call invoked globall'); done(); } test(e) { tressa.assert(e.type === 'click', 'data-call invoked locally'); } render() { return this.html` <p data-call="test" onclick=${this}>hello</p>`; } } class GlobalEvent extends hyperHTML.Component { onclick(e) { tressa.assert(e.type === 'click', 'click invoked globally'); document.removeEventListener('click', this); done(); } render() { document.addEventListener('click', this); return document; } } var p = new Paragraph(); p.render().click(); var e = document.createEvent('Event'); e.initEvent('click', true, true); (new GlobalEvent).render().dispatchEvent(e); }); }) .then(function () { return tressa.async(function (done) { tressa.log('## Custom Element attributes'); var global = document.defaultView; var registry = global.customElements; var customElements = { _: Object.create(null), define: function (name, Class) { this._[name.toLowerCase()] = Class; }, get: function (name) { return this._[name.toLowerCase()]; } }; Object.defineProperty(global, 'customElements', { configurable: true, value: customElements }); function DumbElement() {} DumbElement.prototype.dumb = null; DumbElement.prototype.asd = null; customElements.define('dumb-element', DumbElement); function update(wire) { return wire`<div> <dumb-element dumb=${true} asd=${'qwe'}></dumb-element><dumber-element dumb=${true}></dumber-element> </div>`; } var div = update(hyperHTML.wire()); if (!(div.firstElementChild instanceof DumbElement)) { tressa.assert(div.firstElementChild.dumb !== true, 'not upgraded elements does not have special attributes'); tressa.assert(div.lastElementChild.dumb !== true, 'unknown elements never have special attributes'); // simulate an upgrade div.firstElementChild.constructor.prototype.dumb = null; } div = update(hyperHTML.wire()); delete div.firstElementChild.constructor.prototype.dumb; tressa.assert(div.firstElementChild.dumb === true, 'upgraded elements have special attributes'); Object.defineProperty(global, 'customElements', { configurable: true, value: registry }); done(); }); }) .then(function () { tressa.log('## hyper.Component state'); class DefaultState extends hyperHTML.Component { get defaultState() { return {a: 'a'}; } render() {} } class State extends hyperHTML.Component {} var ds = new DefaultState; var o = ds.state; tressa.assert(!ds.propertyIsEnumerable('state'), 'states are not enumerable'); tressa.assert(!ds.propertyIsEnumerable('_state$'), 'neither their secret'); tressa.assert(o.a === 'a', 'default state retrieved'); var s = new State; s.state = o; tressa.assert(s.state === o, 'state can be set too'); ds.setState({b: 'b'}); tressa.assert(o.a === 'a' && o.b === 'b', 'state was updated'); s.state = {z: 123}; tressa.assert(s.state.z === 123 && !s.state.a, 'state can be re-set too'); }) .then(function () { tressa.log('## splice and sort'); var todo = [ {id: 0, text: 'write documentation'}, {id: 1, text: 'publish online'}, {id: 2, text: 'create Code Pen'} ]; var div = document.createElement('div'); update(); todo.sort(function(a, b) { return a.text < b.text ? -1 : 1; }); update(); tressa.assert(/^\s+create Code Pen\s*publish online\s*write documentation\s+$/.test(div.textContent), 'correct order'); function update() { hyperHTML.bind(div)`<ul> ${todo.map(function (item) { return hyperHTML.wire(item) `<li data-id=${item.id}>${item.text}</li>`; })} </ul>`; } }) .then(function () { return tressa.async(function (done) { tressa.log('## Component connected/disconnected'); var calls = 0; class Paragraph extends hyperHTML.Component { onconnected(e) { calls++; tressa.assert(e.type === 'connected', 'component connected'); e.currentTarget.parentNode.removeChild(e.currentTarget); } ondisconnected(e) { calls++; tressa.assert(e.type === 'disconnected', 'component disconnected'); } render() { return this.html` <p onconnected=${this} ondisconnected=${this}>hello</p>`; } } var p = new Paragraph().render(); document.body.appendChild(p); if (p.parentNode) { setTimeout(function () { var e = document.createEvent('Event'); e.initEvent('DOMNodeInserted', false, false); Object.defineProperty(e, 'target', {value: document.body}); document.dispatchEvent(e); setTimeout(function () { e = document.createEvent('Event'); e.initEvent('DOMNodeInserted', false, false); Object.defineProperty(e, 'target', {value: document.createTextNode('')}); document.dispatchEvent(e); setTimeout(function () { e = document.createEvent('Event'); e.initEvent('DOMNodeRemoved', false, false); Object.defineProperty(e, 'target', {value: p}); document.dispatchEvent(e); setTimeout(function () { tressa.assert(calls === 2, 'correct amount of calls'); done(); }, 100); }, 100); }, 100); }, 100); } }); }) .then(function () { tressa.log('## style=${fun}'); var render = hyperHTML.wire(); function p(style) { return render`<p style=${style}></p>`; } var node = p({fontSize:24}); tressa.assert(node.style.fontSize, node.style.fontSize); p({}); tressa.assert(!node.style.fontSize, 'object cleaned'); p('font-size: 18px'); tressa.assert(node.style.fontSize, node.style.fontSize); p({'--custom-color': 'red'}); if (node.style.cssText !== '') tressa.assert(node.style.getPropertyValue('--custom-color') === 'red', 'custom style'); else console.log('skipping CSS properties for IE'); }) .then(function () { tressa.log('## <self-closing />'); var div = hyperHTML.wire()`<div><self-closing test=${1} /><input /><self-closing test="2" /></div>`; tressa.assert(div.childNodes.length === 3, 'nodes did self close'); tressa.assert(div.childNodes[0].getAttribute('test') == "1", 'first node ok'); tressa.assert(/input/i.test(div.childNodes[1].nodeName), 'second node ok'); tressa.assert(div.childNodes[2].getAttribute('test') == "2", 'third node ok'); div = hyperHTML.wire()`<div> <self-closing test=1 /><input /><self-closing test="2" /> </div>`; tressa.assert(div.children.length === 3, 'nodes did self close'); tressa.assert(div.children[0].getAttribute('test') == "1", 'first node ok'); tressa.assert(/input/i.test(div.children[1].nodeName), 'second node ok'); tressa.assert(div.children[2].getAttribute('test') == "2", 'third node ok'); div = hyperHTML.wire()` <div style="width: 200px;"> <svg viewBox="0 0 30 30" fill="currentColor"> <path d="M 0,27 L 27,0 L 30,3 L 3,30 Z" /> <path d="M 0,3 L 3,0 L 30,27 L 27,30 Z" /> </svg> </div> `; tressa.assert(div.children.length === 1, 'one svg'); tressa.assert(div.querySelectorAll('path').length === 2, 'two paths'); }) .then(function () { tressa.log('## <with><self-closing /></with>'); function check(form) { return form.children.length === 3 && /label/i.test(form.children[0].nodeName) && /input/i.test(form.children[1].nodeName) && /button/i.test(form.children[2].nodeName) } tressa.assert( check(hyperHTML.wire()` <form onsubmit=${check}> <label/> <input type="email" placeholder="email"> <button>Button</button> </form>`), 'no quotes is OK' ); tressa.assert( check(hyperHTML.wire()` <form onsubmit=${check}> <label /> <input type="email" placeholder="email"/> <button>Button</button> </form>`), 'self closing is OK' ); tressa.assert( check(hyperHTML.wire()` <form onsubmit="${check}"> <label/> <input type="email" placeholder="email"> <button>Button</button> </form>`), 'quotes are OK' ); tressa.assert( check(hyperHTML.wire()` <form onsubmit="${check}"> <label/> <input type="email" placeholder="email" /> <button>Button</button> </form>`), 'quotes and self-closing too OK' ); }) .then(function () { return tressa.async(function (done) { tressa.log('## Nested Component connected/disconnected'); class GrandChild extends hyperHTML.Component { onconnected(e) { tressa.assert(e.type === 'connected', 'grand child component connected'); } ondisconnected(e) { tressa.assert(e.type === 'disconnected', 'grand child component disconnected'); } render() { return this.html` <p class="grandchild" onconnected=${this} ondisconnected=${this}>I'm grand child</p>`; } } class Child extends hyperHTML.Component { onconnected(e) { tressa.assert(e.type === 'connected', 'child component connected'); } ondisconnected(e) { tressa.assert(e.type === 'disconnected', 'child component disconnected'); } render() { return this.html` <div class="child" onconnected=${this} ondisconnected=${this}>I'm child ${new GrandChild()} </div> `; } } let connectedTimes = 0, disconnectedTimes = 0; class Parent extends hyperHTML.Component { onconnected(e) { connectedTimes ++; tressa.assert(e.type === 'connected', 'parent component connected'); tressa.assert(connectedTimes === 1, 'connected callback should only be triggered once'); } ondisconnected(e) { disconnectedTimes ++; tressa.assert(e.type === 'disconnected', 'parent component disconnected'); tressa.assert(disconnectedTimes === 1, 'disconnected callback should only be triggered once'); done(); } render() { return this.html` <div class="parent" onconnected=${this} ondisconnected=${this}>I'm parent ${new Child()} </div> `; } } var p = new Parent().render(); document.body.appendChild(p); setTimeout(function () { if (p.parentNode) { var e = document.createEvent('Event'); e.initEvent('DOMNodeInserted', false, false); Object.defineProperty(e, 'target', {value: document.body}); document.dispatchEvent(e); setTimeout(function () { e = document.createEvent('Event'); e.initEvent('DOMNodeRemoved', false, false); Object.defineProperty(e, 'target', {value: p}); document.dispatchEvent(e); if (p.parentNode) p.parentNode.removeChild(p); }, 100); } }, 100); }); }) .then(function () { tressa.log('## Declarative Components'); class MenuSimple extends hyperHTML.Component { render(props) { return this.setState(props, false).html` <div>A simple menu</div> <ul> ${props.items.map( (item, i) => MenuItem.for(this, i).render(item) )} </ul> `; } } class MenuWeakMap extends hyperHTML.Component { render(props) { return this.setState(props, false).html` <div>A simple menu</div> <ul> ${props.items.map( item => MenuItem.for(this, item).render(item) )} </ul> `; } } class MenuItem extends hyperHTML.Component { render(props) { return this.setState(props, false).html` <li>${props.name}</li> `; } } var a = document.createElement('div'); var b = document.createElement('div'); var method = hyperHTML.Component.for; if (!MenuSimple.for) { MenuSimple.for = method; MenuWeakMap.for = method; MenuItem.for = method; } hyperHTML.bind(a)`${MenuSimple.for(a).render({ items: [{name: 'item 1'}, {name: 'item 2'}, {name: 'item 3'}] })}`; tressa.assert(MenuSimple.for(a) === MenuSimple.for(a), 'same simple menu'); hyperHTML.bind(b)`${MenuWeakMap.for(b).render({ items: [{name: 'item 1'}, {name: 'item 2'}, {name: 'item 3'}] })}`; tressa.assert(MenuWeakMap.for(a) === MenuWeakMap.for(a), 'same weakmap menu'); tressa.assert(MenuSimple.for(a) !== MenuWeakMap.for(a), 'different from simple'); tressa.assert(MenuSimple.for(a) === MenuSimple.for(a), 'same as simple'); tressa.assert(a.outerHTML === b.outerHTML, 'same layout'); }) .then(function () { tressa.log('## Component.dispatch'); class Pomponent extends hyperHTML.Component { trigger() { this.dispatch('event', 123); } render() { return this.html`<p>a</p><p>b</p>`; } } class Solonent extends hyperHTML.Component { render() { return this.html`<p>c</p>`; } } var a = document.createElement('div'); var p = new Pomponent; p.trigger(); var s = new Solonent; var dispatched = false; hyperHTML.bind(a)`${[p, s]}`; a.addEventListener('event', event => { tressa.assert(event.detail === 123, 'expected details'); tressa.assert(event.component === p, 'expected component'); dispatched = true; }); p.trigger(); s.dispatch('test'); if (!dispatched) throw new Error('broken dispatch'); }) .then(function () { tressa.log('## slotted callback'); var div = document.createElement('div'); var result = []; function A() { result.push(arguments); return {html: '<b>a</b>'}; } function B() { result.push(arguments); return {html: '<b>b</b>'}; } function update() { hyperHTML.bind(div)`${A} - ${B}`; } update(); tressa.assert(result[0][0].parentNode === div, 'expected parent node for A'); tressa.assert(result[1][0].parentNode === div, 'expected parent node for B'); }) .then(function () { tressa.log('## define(hyper-attribute, callback)'); var a = document.createElement('div'); var random = Math.random().toPrecision(6); // IE < 11 var result = []; hyperHTML.define('hyper-attribute', function (target, value) { result.push(target, value); return random; }); hyperHTML.bind(a)`<p hyper-attribute=${random}/>`; if (!result.length) throw new Error('attributes intents failed'); else { tressa.assert(result[0] === a.firstElementChild, 'expected target'); tressa.assert(result[1] === random, 'expected value'); tressa.assert( a.firstElementChild.getAttribute('hyper-attribute') == random, 'expected attribute' ); } result.splice(0); hyperHTML.define('other-attribute', function (target, value) { result.push(target, value); return ''; }); hyperHTML.define('disappeared-attribute', function (target, value) { }); hyperHTML.define('whatever-attribute', function (target, value) { return value; }); hyperHTML.define('null-attribute', function (target, value) { return null; }); hyperHTML.bind(a)`<p other-attribute=${random} disappeared-attribute=${random} whatever-attribute=${random} null-attribute=${random} />`; if (!result.length) throw new Error('attributes intents failed'); else { tressa.assert(result[0] === a.firstElementChild, 'expected other target'); tressa.assert(result[1] === random, 'expected other value'); tressa.assert( a.firstElementChild.getAttribute('other-attribute') === '', 'expected other attribute' ); tressa.assert( !a.firstElementChild.hasAttribute('disappeared-attribute'), 'disappeared-attribute removed' ); tressa.assert( a.firstElementChild.getAttribute('whatever-attribute') == random, 'whatever-attribute set' ); tressa.assert( !a.firstElementChild.hasAttribute('null-attribute'), 'null-attribute removed' ); } }) // WARNING THESE TEST MUST BE AT THE VERY END // WARNING THESE TEST MUST BE AT THE VERY END // WARNING THESE TEST MUST BE AT THE VERY END .then(function () { // WARNING THESE TEST MUST BE AT THE VERY END tressa.log('## IE9 double viewBox 🌈 🌈'); var output = document.createElement('div'); try { hyperHTML.bind(output)`<svg viewBox=${'0 0 50 50'}></svg>`; tressa.assert(output.firstChild.getAttribute('viewBox') == '0 0 50 50', 'correct camelCase attribute'); } catch(o_O) { tressa.assert(true, 'code coverage caveat'); } }) .then(function () { tressa.log('## A-Frame compatibility'); var output = hyperHTML.wire()`<a-scene></a-scene>`; tressa.assert(output.nodeName.toLowerCase() === 'a-scene', 'correct element'); }) // */ .then(function () { if (!tressa.exitCode) { document.body.style.backgroundColor = '#0FA'; } tressa.end(); });
WebReflection/hyperHTML
test/test.js
JavaScript
isc
47,230
var DND_START_EVENT = 'dnd-start', DND_END_EVENT = 'dnd-end', DND_DRAG_EVENT = 'dnd-drag'; angular .module( 'app' ) .config( [ 'iScrollServiceProvider', function(iScrollServiceProvider){ iScrollServiceProvider.configureDefaults({ iScroll: { momentum: false, mouseWheel: true, disableMouse: false, useTransform: true, scrollbars: true, interactiveScrollbars: true, resizeScrollbars: false, probeType: 2, preventDefault: false // preventDefaultException: { // tagName: /^.*$/ // } }, directive: { asyncRefreshDelay: 0, refreshInterval: false } }); } ] ) .controller( 'main', function( $scope, draggingIndicator, iScrollService ){ 'use strict'; this.iScrollState = iScrollService.state; var DND_SCROLL_IGNORED_HEIGHT = 20, // ignoring 20px touch-scroll, // TODO: this might be stored somewhere in browser env DND_ACTIVATION_TIMEOUT = 500, // milliseconds needed to touch-activate d-n-d MOUSE_OVER_EVENT = 'mousemove'; var self = this, items = [], touchTimerId; $scope.dragging = draggingIndicator; for( var i = 0; i< 25; i++ ){ items.push( i ); } $scope.items = items; this.disable = function ( ){ $scope.iScrollInstance.disable(); }; this.log = function ( msg ){ console.log( 'got msg', msg ); }; } );
kosich/ng-hammer-iscroll-drag
main.js
JavaScript
isc
1,547
'use strict' let _ = require('lodash') let HttpClient = require('./http-client') /** * Server configuration and environment information * @extends {HttpClient} */ class Config extends HttpClient { /** * @constructs Config * @param {Object} options General configuration options * @param {Object} options.http configurations for HttpClient */ constructor (options) { super(options.http) } /** * Return the whole server information * @return {Promise} A promise that resolves to the server information */ server () { return this._httpRequest('GET') .then((response) => response.metadata) } /** * Retrieve the server configuration * @return {Promise} A promise that resolves to the server configuration */ get () { return this.server() .then((server) => server.config) } /** * Unset parameters from server configuration * @param {...String} arguments A list parameters that you want to unset * @return {Promise} A promise that resolves when the config has been unset */ unset () { return this.get() .then((config) => _.omit(config, _.flatten(Array.from(arguments)))) .then((config) => this.update(config)) } /** * Set one or more configurations in the server * @param {Object} data A plain object containing the configuration you want * to insert or update in the server * @return {Pomise} A promise that resolves when the config has been set */ set (data) { return this.get() .then((config) => _.merge(config, data)) .then((config) => this.update(config)) } /** * Replaces the whole server configuration for the one provided * @param {Object} data The new server configuration * @return {Promise} A promise that resolves when the configuration has been * replaces */ update (data) { return this._httpRequest('PUT', { config: data }) } } module.exports = Config
alanhoff/node-lxd
lib/config.js
JavaScript
isc
1,927
import $ from 'jquery'; import { router } from 'src/router'; import './header.scss'; export default class Header { static selectors = { button: '.header__enter', search: '.header__search' }; constructor($root) { this.elements = { $root, $window: $(window) }; this.attachEvents(); } attachEvents() { this.elements.$root.on('click', Header.selectors.button, this.handleClick) } handleClick = () => { const search = $(Header.selectors.search).val(); if (search) { router.navigate(`/search?query=${search}`); } } }
ksukhova/Auction
src/components/header/header.js
JavaScript
isc
658
"use strict"; describe("This package", function(){ it("rubs the lotion on its skin, or else", function(){ 2..should.equal(2); // In this universe, it'd damn well better }); it("gets the hose again", function(){ this.should.be.extensible.and.ok; // Eventually }); it("should not fail", function(){ NaN.should.not.equal(NaN); // NaH global.foo = "Foo"; }); it("might be written later"); // Nah it("should fail", function(){ const A = { alpha: "A", beta: "B", gamma: "E", delta: "D", }; const B = { Alpha: "A", beta: "B", gamma: "E", delta: "d", }; A.should.equal(B); }); describe("Suite nesting", function(){ it("does something useful eventually", function(done){ setTimeout(() => done(), 40); }); it("cleans anonymous async functions", async function(){ if(true){ true.should.be.true; } }); it("cleans anonymous generators", function * (){ if(true){ true.should.be.true; } }); it("cleans named async functions", async function foo() { if(true){ true.should.be.true; } }); it("cleans named generators", function * foo (){ if(true){ true.should.be.true; } }); it("cleans async arrow functions", async () => { if(true){ true.should.be.true; } }); }); }); describe("Second suite at top-level", function(){ it("shows another block", function(){ Chai.expect(Date).to.be.an.instanceOf(Function); }); it("breaks something", function(){ something(); }); it("loads locally-required files", () => { expect(global.someGlobalThing).to.equal("fooXYZ"); }); unlessOnWindows.it("enjoys real symbolic links", () => { "Any Unix-like system".should.be.ok; }); }); describe("Aborted tests", () => { before(() => {throw new Error("Nah, not really")}); it("won't reach this", () => true.should.not.be.false); it.skip("won't reach this either", () => true.should.be.true); });
Alhadis/Atom-Mocha
spec/basic-spec.js
JavaScript
isc
1,958
'use strict'; var yeoman = require('yeoman-generator'), chalk = require('chalk'), yosay = require('yosay'), bakery = require('../../lib/bakery'), feedback = require('../../lib/feedback'), debug = require('debug')('bakery:generators:cm-bash:index'), glob = require('glob'), path = require('path'), _ = require('lodash'); // placeholder for CM implementaiton delivering a BASH-based project. var BakeryCM = yeoman.Base.extend({ constructor: function () { yeoman.Base.apply(this, arguments); this._options.help.desc = 'Show this help'; this.argument('projectname', { type: String, required: this.config.get('projectname') == undefined }); }, // generators are invalid without at least one method to run during lifecycle default: function () { /* TAKE NOTE: these next two lines are fallout of having to include ALL sub-generators in .composeWith(...) at the top level. Essentially ALL SUBGENERATORS RUN ALL THE TIME. So we have to escape from generators we don't want running within EVERY lifecycle method. (ugh) */ let cmInfo = this.config.get('cm'); if (cmInfo.generatorName != 'cm-bash') { return; } } }); module.exports = BakeryCM;
datapipe/generator-bakery
generators/cm-bash/index.js
JavaScript
isc
1,256
/*\ |*| |*| :: cookies.js :: |*| |*| A complete cookies reader/writer framework with full unicode support. |*| |*| Revision #1 - September 4, 2014 |*| |*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| |*| Syntaxes: |*| |*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]]) |*| * docCookies.getItem(name) |*| * docCookies.removeItem(name[, path[, domain]]) |*| * docCookies.hasItem(name) |*| * docCookies.keys() |*| \*/ export default { getItem: function (sKey) { if (!sKey) { return null; } return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function (sKey, sPath, sDomain) { if (!this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { if (!sKey) { return false; } return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, keys: function () { var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/); for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); } return aKeys; } };
thinhhung610/my-blog
js/vendor/cookie.js
JavaScript
isc
2,508
'use strict'; // Proxy URL (optional) const proxyUrl = 'drupal.dev'; // API keys const TINYPNG_KEY = ''; // fonts const fontList = []; // vendors const jsVendorList = []; const cssVendorList = []; // paths to relevant directories const dirs = { src: './src', dest: './dist' }; // paths to file sources const sources = { js: `${dirs.src}/**/*.js`, scss: `${dirs.src}/**/*.scss`, coreScss: `${dirs.src}/scss/main.scss`, img: `./img/**/*.{png,jpg}`, font: fontList, jsVendor: jsVendorList, cssVendor: cssVendorList }; // paths to file destinations const dests = { js: `${dirs.dest}/js`, css: `${dirs.dest}/css`, img: `${dirs.dest}/img`, sigFile: `./img/.tinypng-sigs`, font: `${dirs.dest}/fonts`, vendor: `${dirs.dest}/vendors` }; // plugins import gulp from 'gulp'; import browserSync from 'browser-sync'; import gulpLoadPlugins from 'gulp-load-plugins'; // auto-load plugins const $ = gulpLoadPlugins(); /**************************************** Gulp Tasks *****************************************/ // launch browser sync as a standalone local server gulp.task('browser-sync-local', browserSyncLocal()); // browser-sync task for starting the server by proxying a local url gulp.task('browser-sync-proxy', browserSyncProxy()); // copy vendor CSS gulp.task('css-vendors', cssVendors()); // copy fonts gulp.task('fonts', fonts()); // Lint Javascript Task gulp.task('js-lint', javascriptLint()); // Concatenate and Minify Vendor JS gulp.task('js-vendors', javascriptVendors()); // lint sass task gulp.task('sass-lint', sassLint()); // Concatenate & Minify JS gulp.task('scripts', ['js-lint'], scripts()); // compile, prefix, and minify the sass gulp.task('styles', styles()); // compress and combine svg icons gulp.task('svg', svg()); // Unit testing gulp.task('test', test()); // compress png and jpg images via tinypng API gulp.task('tinypng', tinypng()); // Watch Files For Changes gulp.task('watch', watch()); // default task builds src, opens up a standalone server, and watches for changes gulp.task('default', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // local task builds src, opens up a standalone server, and watches for changes gulp.task('local', [ 'fonts', 'styles', 'scripts', 'browser-sync-local', 'watch' ]); // proxy task builds src, opens up a proxy server, and watches for changes gulp.task('proxy', [ 'fonts', 'styles', 'scripts', 'browser-sync-proxy', 'watch' ]); // builds everything gulp.task('build', [ 'fonts', 'styles', 'scripts', 'css-vendors', 'js-vendors' ]); // builds the vendor files gulp.task('vendors', [ 'css-vendors', 'js-vendors' ]); // compresses imagery gulp.task('images', [ 'svg', 'tinypng' ]); /**************************************** Task Logic *****************************************/ function browserSyncLocal () { return () => { browserSync.init({ server: '../../../../' }); }; } function browserSyncProxy () { return () => { browserSync.init({ proxy: proxyUrl }); }; } function cssVendors () { return () => { return gulp.src(sources.cssVendor) .pipe(gulp.dest(dests.vendor)); }; } function fonts () { return () => { gulp.src(sources.font) .pipe(gulp.dest(dests.font)); }; } function javascriptLint () { return () => { return gulp.src(sources.js) .pipe($.jshint({esversion: 6})) .pipe($.jshint.reporter('jshint-stylish')); }; } function javascriptVendors () { return () => { return gulp.src(sources.jsVendor) .pipe($.plumber()) .pipe($.concat('vendors.min.js')) .pipe($.uglify()) .pipe(gulp.dest(dests.vendor)); }; } function sassLint () { return () => { return gulp.src(sources.scss) .pipe($.sassLint()) .pipe($.sassLint.format()) .pipe($.sassLint.failOnError()); }; } function scripts () { return () => { return gulp.src(sources.js) .pipe($.plumber()) .pipe($.sourcemaps.init()) .pipe($.concat('main.js')) .pipe($.babel()) .pipe(gulp.dest(dests.js)) .pipe($.rename({suffix: '.min'})) .pipe($.uglify()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.js)) .pipe(browserSync.stream()); }; } function styles () { return () => { return gulp.src(sources.coreScss) .pipe($.sourcemaps.init()) .pipe($.sass().on('error', $.sass.logError)) .pipe($.autoprefixer(["> 1%", "last 2 versions"], { cascade: true })) .pipe(gulp.dest(dests.css)) .pipe($.rename({suffix: '.min'})) .pipe($.cleanCss()) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest(dests.css)) .pipe(browserSync.stream()); }; } function svg () { return () => { return gulp.src('./img/icons/*.svg') .pipe($.svgmin()) .pipe($.svgstore()) .pipe(gulp.dest('./img/icons')); }; } function test (done) { return () => { let server = new karma.Server('./karma.conf.js', done); server.start(); }; } function tinypng () { return () => { return gulp.src(sources.img) .pipe($.tinypngCompress({ key: TINYPNG_KEY, sigFile: dests.sigFile })) .pipe(gulp.dest(dests.img)); }; } function watch () { return () => { gulp.watch(sources.js, ['scripts']); gulp.watch(sources.scss, ['styles']); gulp.watch('**/*.php', browserSync.reload); }; }
TricomB2B/tricom-drupal-7-base
gulpfile.babel.js
JavaScript
mit
5,441
'use strict'; const debug = require('debug')('WechatController'); const EventEmitter = require('events').EventEmitter; const Cache = require('../../service/Cache'); const Wechat = require('../../service/Wechat'); const config = require('../../config'); const _ = require('lodash'); const async = require('async'); /* 微信公众平台连接认证 */ exports.wechatValidation = function (req, res, next) { let signature = req.query.signature; let timestamp = req.query.timestamp; let nonce = req.query.nonce; let echostr = req.query.echostr; let flag = Wechat.validateSignature(signature, timestamp, nonce); if (flag) return res.send(echostr); else return res.send({success: false}); }; /* 更新access token */ exports.updateAccessToken = function (req, res, next) { Wechat.updateAccessToken(); res.send('updateAccessToken'); }; /* 接收来自微信的消息推送 */ exports.processWechatEvent = function (req, res, next) { let content = req.body.xml; console.log('Event received. Event: %s', JSON.stringify(content)); res.send('success'); if(!content) return; try { let fromOpenId = content.FromUserName[0], toOpenId = content.ToUserName[0], createTime = content.CreateTime[0], event = content.Event ? content.Event[0] : "", eventKey = content.EventKey ? content.EventKey[0] : "", msgType = content.MsgType[0], msgId = content.MsgID ? content.MsgID[0] : "", status = content.Status ? content.Status[0] : "", ticket = content.Ticket ? content.Ticket[0] : null; if(msgType === 'event') { const WechatEvent = req.app.db.models.WechatEvent; let wechatEvent = new WechatEvent({ event: content }); wechatEvent.save((err) => { if(err) console.error(err, err.stack); handleEvent(req, res, fromOpenId, event, eventKey, msgId, status, ticket); }); } } catch(e) { console.error(e, e.stack); } }; function handleEvent(req, res, openId, name, key, msgId, status, ticket) { const Subscriber = req.app.db.models.Subscriber; const InvitationCard = req.app.db.models.InvitationCard; name = String(name).toLowerCase(); if(name === 'scan') { if(ticket) { InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => { if(err) return console.error(err); if(cardDoc && cardDoc.invitationTask.status === 'OPEN') { if(cardDoc.openId === openId) { return Wechat.sendText(openId, "你不能扫描自己的任务卡"); } else { Subscriber.findOne({ openId, subscribe: true }).exec((err, subscriberDoc) => { if(err) return console.error(err); if(subscriberDoc) return Wechat.sendText(openId, "你已经关注,不能被邀请"); }); } } }); } } if(name === 'click') { if(key.indexOf('invitationTask') === 0) { let taskId = key.split('-')[1]; require('../../service/InvitationCard').sendCard(openId, taskId); } if(key.indexOf('message') === 0) { let replyQueueId = key.split('-')[1]; let ReplyQueue = req.app.db.models.ReplyQueue; let ReplyQueueLog = req.app.db.models.ReplyQueueLog; function sendMessages(messageGroup) { async.eachSeries(messageGroup, function(message, callback) { if(message.type === 'text') { return Wechat.sendText(openId, message.content).then((data) => { setTimeout(callback, 1000); }).catch(callback); } if(message.type === 'image') { return Wechat.sendImage(openId, message.mediaId).then((data) => { setTimeout(callback, 5000); }).catch(callback); } }, function(err) { err && console.log(err); }); } ReplyQueueLog.findOne({ openId, replyQueue: replyQueueId}).exec((err, log) => { if(log) { let nextIndex = log.clickCount; if(nextIndex > log.messageGroupsSnapshot.length-1) { nextIndex = log.messageGroupsSnapshot.length-1; } else { ReplyQueueLog.findByIdAndUpdate(log._id, { clickCount: nextIndex + 1 }, { new: true }).exec(); } sendMessages(log.messageGroupsSnapshot[nextIndex]) } else { ReplyQueue.findById(replyQueueId).exec((err, replyQueue) => { new ReplyQueueLog({ openId: openId, replyQueue: replyQueueId, messageGroupsSnapshot: replyQueue.messageGroups, clickCount: 1 }).save(); sendMessages(replyQueue.messageGroups[0]); }); } }); } } if(name === 'subscribe') { const workflow = new EventEmitter(); let introducer = null; let card = null; // 检查扫码标记 workflow.on('checkTicket', () => { debug('Event: checkTicket'); if(ticket) return workflow.emit('findNewUser'); // 在数据库中寻找该"新"用户 return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情 }); // 在数据库中寻找该用户 workflow.on('findNewUser', () => { debug('Event: findNewUser'); Subscriber.findOne({ openId }).exec((err, doc) => { if(err) return workflow.emit('error', err); // 错误 if(!doc) return workflow.emit('getTaskAndCard'); // 查找邀请卡和任务配置 InvitationCard.findOne({ openId, qrTicket: ticket }).exec((err, selfScanedCardDoc) => { if(err) return workflow.emit('error', err); // 错误 if(selfScanedCardDoc) return Wechat.sendText(openId, "你不能扫描自己的任务卡"); if(doc.subscribe) return Wechat.sendText(openId, "你已经关注,不能被邀请"); Wechat.sendText(openId, "你已经被邀请过,不能被再次邀请"); }); return workflow.emit('getSubscriberInfo'); // 获得"新"用户详情 }); }); workflow.on('getTaskAndCard', () => { debug('Event: getTaskAndCard'); InvitationCard.findOne({ qrTicket: ticket }).populate('invitationTask').exec((err, cardDoc) => { if(err) return workflow.emit('error', err); // 错误 if(!cardDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请卡,获得"新"用户详情 if(!cardDoc.invitationTask) return workflow.emit('getSubscriberInfo'); // 邀请卡任务不存在,获得"新"用户详情 if(cardDoc.invitationTask.status !== 'OPEN') return workflow.emit('getSubscriberInfo'); // 邀请卡任务已关闭,获得"新"用户详情 card = cardDoc.toJSON(); Subscriber.findOne({ openId: cardDoc.openId }).exec((err, introducerDoc) => { if(err) return workflow.emit('error', err); // 错误 if(!introducerDoc) return workflow.emit('getSubscriberInfo'); // 没有此邀请人,获得"新"用户详情 introducer = introducerDoc.toJSON(); return workflow.emit('invitedCountPlus'); // 增加邀请量 }); }); }); workflow.on('invitedCountPlus', () => { debug('Event: invitedCountPlus'); InvitationCard.findOneAndUpdate({ qrTicket: ticket }, { $inc: { invitedCount: 1 }}, function(err, doc) { if(err) return workflow.emit('error', err); // 错误 console.log(`[WechatController] Add Invitation: ${ticket}`); workflow.emit('getSubscriberInfo'); }); }); workflow.on('getSubscriberInfo', () => { debug('Event: getSubscriberInfo'); Wechat.getSubscriberInfo(openId).then((info) => { let newData = { openId: info.openid, groupId: info.groupid, unionId: info.unionid, subscribe: info.subscribe ? true : false, subscribeTime: new Date(info.subscribe_time * 1000), nickname: info.nickname, remark: info.remark, gender: info.sex, headImgUrl: info.headimgurl, city: info.city, province: info.province, country: info.country, language: info.language }; if(introducer) { newData.introducer = introducer._id; if(card.invitationTask.invitedFeedback) { let invitedCount = card.invitedCount + 1; let remainCount = card.invitationTask.threshold - invitedCount; let invitedFeedback = card.invitationTask.invitedFeedback; if(remainCount > 0) { invitedFeedback = invitedFeedback.replace(/###/g, info.nickname) invitedFeedback = invitedFeedback.replace(/#invited#/g, invitedCount + ''); invitedFeedback = invitedFeedback.replace(/#remain#/g, remainCount + '') Wechat.sendText(introducer.openId, invitedFeedback); } } } Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){ if(err) return workflow.emit('error', err); // 错误 console.log(`[WechatController] New Subscriber: ${openId}`); }); }).catch((err) => { if(err) return workflow.emit('error', err); // 错误 }) }); // 错误 workflow.on('error', (err, wechatMessage) => { debug('Event: error'); if(err) { console.error(err, err.stack); } else { console.error('Undefined Error Event'); } }); workflow.emit('checkTicket'); } if(name === 'unsubscribe') { let Subscriber = req.app.db.models.Subscriber; let newData = { subscribe: false }; Subscriber.findOneAndUpdate({ openId }, newData, { upsert: true }, function(err, doc){ if (err) return console.error(err); console.log(`[WechatController] Unsubscribe: ${openId}`); }); } if(name === 'templatesendjobfinish') { let TemplateSendLog = req.app.db.models.TemplateSendLog; status = _.upperFirst(status); TemplateSendLog.findOneAndUpdate({ msgId: msgId }, { status : status }, function(err, doc){ if (err) return console.log(err); console.log(`[WechatController] TEMPLATESENDJOBFINISH: ${msgId}`); }); } }
xwang1024/bomblab
lib/controller/wechat/index.js
JavaScript
mit
10,120
// get the languange parameter in the URL (i for case insensitive; //exec for test for a match in a string and return thr first match) function getURLParameter(key) { var result = new RegExp(key + '=([^&]*)', 'i').exec(window.location.search); return result && result[1] || ''; } // function toggleLang(lang) { var lang = lang || 'de'; document.location = document.location.pathname + '?lang=' + lang; } // set UR var lang = getURLParameter('lang') || 'de'; $('#lang').ready(function() { $('#lang li').each(function() { var li = $(this)[0]; if (li.id == lang) $(this).addClass('selected'); }); });
geoadmin/web-storymaps
htdocs/common/js/toggleLang.js
JavaScript
mit
624
'use strict'; var _get = require('babel-runtime/helpers/get')['default']; var _inherits = require('babel-runtime/helpers/inherits')['default']; var _createClass = require('babel-runtime/helpers/create-class')['default']; var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default']; var _extends = require('babel-runtime/helpers/extends')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; Object.defineProperty(exports, '__esModule', { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _EnhancedSwitch = require('./EnhancedSwitch'); var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch); var Radio = (function (_React$Component) { _inherits(Radio, _React$Component); function Radio() { _classCallCheck(this, Radio); _get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments); } _createClass(Radio, [{ key: 'getValue', value: function getValue() { return this.refs.enhancedSwitch.getValue(); } }, { key: 'setChecked', value: function setChecked(newCheckedValue) { this.refs.enhancedSwitch.setSwitched(newCheckedValue); } }, { key: 'isChecked', value: function isChecked() { return this.refs.enhancedSwitch.isSwitched(); } }, { key: 'render', value: function render() { var enhancedSwitchProps = { ref: 'enhancedSwitch', inputType: 'radio' }; // labelClassName return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps)); } }]); return Radio; })(_react2['default'].Component); exports['default'] = Radio; module.exports = exports['default'];
andres81/auth-service
frontend/node_modules/react-icheck/lib/Radio.js
JavaScript
mit
1,815
!(function(root) { function Grapnel(opts) { "use strict"; var self = this; // Scope reference this.events = {}; // Event Listeners this.state = null; // Router state object this.options = opts || {}; // Options this.options.env = this.options.env || (!!(Object.keys(root).length === 0 && process && process.browser !== true) ? 'server' : 'client'); this.options.mode = this.options.mode || (!!(this.options.env !== 'server' && this.options.pushState && root.history && root.history.pushState) ? 'pushState' : 'hashchange'); this.version = '0.6.4'; // Version if ('function' === typeof root.addEventListener) { root.addEventListener('hashchange', function() { self.trigger('hashchange'); }); root.addEventListener('popstate', function(e) { // Make sure popstate doesn't run on init -- this is a common issue with Safari and old versions of Chrome if (self.state && self.state.previousState === null) return false; self.trigger('navigate'); }); } return this; }; /** * Create a RegExp Route from a string * This is the heart of the router and I've made it as small as possible! * * @param {String} Path of route * @param {Array} Array of keys to fill * @param {Bool} Case sensitive comparison * @param {Bool} Strict mode */ Grapnel.regexRoute = function(path, keys, sensitive, strict) { if (path instanceof RegExp) return path; if (path instanceof Array) path = '(' + path.join('|') + ')'; // Build route RegExp path = path.concat(strict ? '' : '/?') .replace(/\/\(/g, '(?:/') .replace(/\+/g, '__plus__') .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) { keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || ''); }) .replace(/([\/.])/g, '\\$1') .replace(/__plus__/g, '(.+)') .replace(/\*/g, '(.*)'); return new RegExp('^' + path + '$', sensitive ? '' : 'i'); }; /** * ForEach workaround utility * * @param {Array} to iterate * @param {Function} callback */ Grapnel._forEach = function(a, callback) { if (typeof Array.prototype.forEach === 'function') return Array.prototype.forEach.call(a, callback); // Replicate forEach() return function(c, next) { for (var i = 0, n = this.length; i < n; ++i) { c.call(next, this[i], i, this); } }.call(a, callback); }; /** * Add an route and handler * * @param {String|RegExp} route name * @return {self} Router */ Grapnel.prototype.get = Grapnel.prototype.add = function(route) { var self = this, middleware = Array.prototype.slice.call(arguments, 1, -1), handler = Array.prototype.slice.call(arguments, -1)[0], request = new Request(route); var invoke = function RouteHandler() { // Build request parameters var req = request.parse(self.path()); // Check if matches are found if (req.match) { // Match found var extra = { route: route, params: req.params, req: req, regex: req.match }; // Create call stack -- add middleware first, then handler var stack = new CallStack(self, extra).enqueue(middleware.concat(handler)); // Trigger main event self.trigger('match', stack, req); // Continue? if (!stack.runCallback) return self; // Previous state becomes current state stack.previousState = self.state; // Save new state self.state = stack; // Prevent this handler from being called if parent handler in stack has instructed not to propagate any more events if (stack.parent() && stack.parent().propagateEvent === false) { stack.propagateEvent = false; return self; } // Call handler stack.callback(); } // Returns self return self; }; // Event name var eventName = (self.options.mode !== 'pushState' && self.options.env !== 'server') ? 'hashchange' : 'navigate'; // Invoke when route is defined, and once again when app navigates return invoke().on(eventName, invoke); }; /** * Fire an event listener * * @param {String} event name * @param {Mixed} [attributes] Parameters that will be applied to event handler * @return {self} Router */ Grapnel.prototype.trigger = function(event) { var self = this, params = Array.prototype.slice.call(arguments, 1); // Call matching events if (this.events[event]) { Grapnel._forEach(this.events[event], function(fn) { fn.apply(self, params); }); } return this; }; /** * Add an event listener * * @param {String} event name (multiple events can be called when separated by a space " ") * @param {Function} callback * @return {self} Router */ Grapnel.prototype.on = Grapnel.prototype.bind = function(event, handler) { var self = this, events = event.split(' '); Grapnel._forEach(events, function(event) { if (self.events[event]) { self.events[event].push(handler); } else { self.events[event] = [handler]; } }); return this; }; /** * Allow event to be called only once * * @param {String} event name(s) * @param {Function} callback * @return {self} Router */ Grapnel.prototype.once = function(event, handler) { var ran = false; return this.on(event, function() { if (ran) return false; ran = true; handler.apply(this, arguments); handler = null; return true; }); }; /** * @param {String} Route context (without trailing slash) * @param {[Function]} Middleware (optional) * @return {Function} Adds route to context */ Grapnel.prototype.context = function(context) { var self = this, middleware = Array.prototype.slice.call(arguments, 1); return function() { var value = arguments[0], submiddleware = (arguments.length > 2) ? Array.prototype.slice.call(arguments, 1, -1) : [], handler = Array.prototype.slice.call(arguments, -1)[0], prefix = (context.slice(-1) !== '/' && value !== '/' && value !== '') ? context + '/' : context, path = (value.substr(0, 1) !== '/') ? value : value.substr(1), pattern = prefix + path; return self.add.apply(self, [pattern].concat(middleware).concat(submiddleware).concat([handler])); } }; /** * Navigate through history API * * @param {String} Pathname * @return {self} Router */ Grapnel.prototype.navigate = function(path) { return this.path(path).trigger('navigate'); }; Grapnel.prototype.path = function(pathname) { var self = this, frag; if ('string' === typeof pathname) { // Set path if (self.options.mode === 'pushState') { frag = (self.options.root) ? (self.options.root + pathname) : pathname; root.history.pushState({}, null, frag); } else if (root.location) { root.location.hash = (self.options.hashBang ? '!' : '') + pathname; } else { root._pathname = pathname || ''; } return this; } else if ('undefined' === typeof pathname) { // Get path if (self.options.mode === 'pushState') { frag = root.location.pathname.replace(self.options.root, ''); } else if (self.options.mode !== 'pushState' && root.location) { frag = (root.location.hash) ? root.location.hash.split((self.options.hashBang ? '#!' : '#'))[1] : ''; } else { frag = root._pathname || ''; } return frag; } else if (pathname === false) { // Clear path if (self.options.mode === 'pushState') { root.history.pushState({}, null, self.options.root || '/'); } else if (root.location) { root.location.hash = (self.options.hashBang) ? '!' : ''; } return self; } }; /** * Create routes based on an object * * @param {Object} [Options, Routes] * @param {Object Routes} * @return {self} Router */ Grapnel.listen = function() { var opts, routes; if (arguments[0] && arguments[1]) { opts = arguments[0]; routes = arguments[1]; } else { routes = arguments[0]; } // Return a new Grapnel instance return (function() { // TODO: Accept multi-level routes for (var key in routes) { this.add.call(this, key, routes[key]); } return this; }).call(new Grapnel(opts || {})); }; /** * Create a call stack that can be enqueued by handlers and middleware * * @param {Object} Router * @param {Object} Extend * @return {self} CallStack */ function CallStack(router, extendObj) { this.stack = CallStack.global.slice(0); this.router = router; this.runCallback = true; this.callbackRan = false; this.propagateEvent = true; this.value = router.path(); for (var key in extendObj) { this[key] = extendObj[key]; } return this; }; /** * Build request parameters and allow them to be checked against a string (usually the current path) * * @param {String} Route * @return {self} Request */ function Request(route) { this.route = route; this.keys = []; this.regex = Grapnel.regexRoute(route, this.keys); }; // This allows global middleware CallStack.global = []; /** * Prevent a callback from being called * * @return {self} CallStack */ CallStack.prototype.preventDefault = function() { this.runCallback = false; }; /** * Prevent any future callbacks from being called * * @return {self} CallStack */ CallStack.prototype.stopPropagation = function() { this.propagateEvent = false; }; /** * Get parent state * * @return {Object} Previous state */ CallStack.prototype.parent = function() { var hasParentEvents = !!(this.previousState && this.previousState.value && this.previousState.value == this.value); return (hasParentEvents) ? this.previousState : false; }; /** * Run a callback (calls to next) * * @return {self} CallStack */ CallStack.prototype.callback = function() { this.callbackRan = true; this.timeStamp = Date.now(); this.next(); }; /** * Add handler or middleware to the stack * * @param {Function|Array} Handler or a array of handlers * @param {Int} Index to start inserting * @return {self} CallStack */ CallStack.prototype.enqueue = function(handler, atIndex) { var handlers = (!Array.isArray(handler)) ? [handler] : ((atIndex < handler.length) ? handler.reverse() : handler); while (handlers.length) { this.stack.splice(atIndex || this.stack.length + 1, 0, handlers.shift()); } return this; }; /** * Call to next item in stack -- this adds the `req`, `event`, and `next()` arguments to all middleware * * @return {self} CallStack */ CallStack.prototype.next = function() { var self = this; return this.stack.shift().call(this.router, this.req, this, function next() { self.next.call(self); }); }; /** * Match a path string -- returns a request object if there is a match -- returns false otherwise * * @return {Object} req */ Request.prototype.parse = function(path) { var match = path.match(this.regex), self = this; var req = { params: {}, keys: this.keys, matches: (match || []).slice(1), match: match }; // Build parameters Grapnel._forEach(req.matches, function(value, i) { var key = (self.keys[i] && self.keys[i].name) ? self.keys[i].name : i; // Parameter key will be its key or the iteration index. This is useful if a wildcard (*) is matched req.params[key] = (value) ? decodeURIComponent(value) : undefined; }); return req; }; // Append utility constructors to Grapnel Grapnel.CallStack = CallStack; Grapnel.Request = Request; if ('function' === typeof root.define && !root.define.amd.grapnel) { root.define(function(require, exports, module) { root.define.amd.grapnel = true; return Grapnel; }); } else if ('object' === typeof module && 'object' === typeof module.exports) { module.exports = exports = Grapnel; } else { root.Grapnel = Grapnel; } }).call({}, ('object' === typeof window) ? window : this); /* var router = new Grapnel({ pushState : true, hashBang : true }); router.get('/products/:category/:id?', function(req){ var id = req.params.id, category = req.params.category console.log(category, id); }); router.get('/tiempo', function(req){ console.log("tiempo!"); $("#matikbirdpath").load("views/rooms.html", function(res){ console.log(res); console.log("hola"); }); }); router.get('/', function(req){ console.log(req.user); console.log("hola!"); $("#matikbirdpath").load("views/rooms.html", function(res){ console.log(res); console.log("hola"); }); }); router.navigate('/'); */ NProgress.start(); var routes = { '/' : function(req, e){ $("#matikbirdpath").load("views/main.html", function(res){ console.log(res); NProgress.done(); }); }, '/dashboard' : function(req, e){ $("#matikbirdpath").load("views/dashboard.html", function(res){ console.log(res); NProgress.done(); }); }, '/calendario' : function(req, e){ $("#matikbirdpath").load("views/calendario.html", function(res){ console.log(res); console.log("hola"); }); }, '/now' : function(req, e){ $("#matikbirdpath").load("views/clase_ahora.html", function(res){ console.log(res); console.log("hola"); }); }, '/category/:id' : function(req, e){ // Handle route }, '/*' : function(req, e){ if(!e.parent()){ $("#matikbirdpath").load("views/main.html", function(res){ console.log(res); NProgress.done(); }); } } } var router = Grapnel.listen({ pushState : true, hashBang: true }, routes);
matikbird/matikbird.github.io
portfolio/copylee/assets/mtk-route.js
JavaScript
mit
16,205
class Foo { [prop1]: string; }
motiz88/astring-flow
test/data/roundtrip/flow-parser-tests/test-046.js
JavaScript
mit
30
(function () { "use strict"; angular.module('projectManagerSPA').controller('userLoginController', ['authenticationService', '$scope', '$state',function (authenticationService, $scope, $state) { $scope.logIn = function () { authenticationService.logIn($scope.username, $scope.password, function () { $state.go('organizationList'); }); }; $scope.logOut = function () { $state.go('userLogout'); }; }]); })();
ivanthescientist/ProjectManager
src/main/resources/public/js/controller/user.login.controller.js
JavaScript
mit
503
var map; var infoWindow; // A variável markersData guarda a informação necessária a cada marcador // Para utilizar este código basta alterar a informação contida nesta variável var markersData = [ { lat: -3.741262, lng: -38.539389, nome: "Campus do Pici - Universidade Federal do Ceará", endereco:"Av. Mister Hull, s/n", telefone: "(85) 3366-9500" // não colocar virgula no último item de cada maracdor }, { lat: -3.780833, lng: -38.469656, nome: "Colosso Lake Lounge", endereco:"Rua Hermenegildo Sá Cavalcante, s/n", telefone: "(85) 98160-0088" // não colocar virgula no último item de cada maracdor } // não colocar vírgula no último marcador ]; function initialize() { var mapOptions = { center: new google.maps.LatLng(40.601203,-8.668173), zoom: 9, mapTypeId: 'roadmap', }; map = new google.maps.Map(document.getElementById('map-slackline'), mapOptions); // cria a nova Info Window com referência à variável infowindow // o conteúdo da Info Window será atribuído mais tarde infoWindow = new google.maps.InfoWindow(); // evento que fecha a infoWindow com click no mapa google.maps.event.addListener(map, 'click', function() { infoWindow.close(); }); // Chamada para a função que vai percorrer a informação // contida na variável markersData e criar os marcadores a mostrar no mapa displayMarkers(); } google.maps.event.addDomListener(window, 'load', initialize); // Esta função vai percorrer a informação contida na variável markersData // e cria os marcadores através da função createMarker function displayMarkers(){ // esta variável vai definir a área de mapa a abranger e o nível do zoom // de acordo com as posições dos marcadores var bounds = new google.maps.LatLngBounds(); // Loop que vai estruturar a informação contida em markersData // para que a função createMarker possa criar os marcadores for (var i = 0; i < markersData.length; i++){ var latlng = new google.maps.LatLng(markersData[i].lat, markersData[i].lng); var nome = markersData[i].nome; var endereco = markersData[i].endereco; var telefone = markersData[i].telefone; createMarker(latlng, nome, endereco, telefone); // Os valores de latitude e longitude do marcador são adicionados à // variável bounds bounds.extend(latlng); } // Depois de criados todos os marcadores // a API através da sua função fitBounds vai redefinir o nível do zoom // e consequentemente a área do mapa abrangida. map.fitBounds(bounds); } // Função que cria os marcadores e define o conteúdo de cada Info Window. function createMarker(latlng, nome, endereco, telefone){ var marker = new google.maps.Marker({ map: map, position: latlng, title: nome }); // Evento que dá instrução à API para estar alerta ao click no marcador. // Define o conteúdo e abre a Info Window. google.maps.event.addListener(marker, 'click', function() { // Variável que define a estrutura do HTML a inserir na Info Window. var iwContent = '<div id="iw_container">' + '<div class="iw_title">' + nome + '</div>' + '<div class="iw_content">' + endereco + '<br />' + telefone + '<br />'; // O conteúdo da variável iwContent é inserido na Info Window. infoWindow.setContent(iwContent); // A Info Window é aberta. infoWindow.open(map, marker); }); }
KatharineAmaral29/ArenaSports
js/mapslackline.js
JavaScript
mit
3,584
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _default; function _default() { return function ({ addUtilities, variants }) { addUtilities({ '.bg-clip-border': { 'background-clip': 'border-box' }, '.bg-clip-padding': { 'background-clip': 'padding-box' }, '.bg-clip-content': { 'background-clip': 'content-box' }, '.bg-clip-text': { 'background-clip': 'text' } }, variants('backgroundClip')); }; }
matryer/bitbar
xbarapp.com/node_modules/tailwindcss/lib/plugins/backgroundClip.js
JavaScript
mit
550
var gulp = require('gulp'); var karma = require('karma').server; var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var rename = require('gulp-rename'); var path = require('path'); var plumber = require('gulp-plumber'); var runSequence = require('run-sequence'); var jshint = require('gulp-jshint'); /** * File patterns **/ // Root directory var rootDirectory = path.resolve('./'); // Source directory for build process var sourceDirectory = path.join(rootDirectory, './src'); var sourceFiles = [ // Make sure module files are handled first path.join(sourceDirectory, '/**/*.module.js'), // Then add all JavaScript files path.join(sourceDirectory, '/**/*.js') ]; var lintFiles = [ 'gulpfile.js', // Karma configuration 'karma-*.conf.js' ].concat(sourceFiles); gulp.task('build', function() { gulp.src(sourceFiles) .pipe(plumber()) .pipe(concat('df-validator.js')) .pipe(gulp.dest('./dist/')) .pipe(uglify()) .pipe(rename('df-validator.min.js')) .pipe(gulp.dest('./dist')); }); /** * Process */ gulp.task('process-all', function (done) { runSequence(/*'jshint',*/ 'test-src', 'build', done); }); /** * Watch task */ gulp.task('watch', function () { // Watch JavaScript files gulp.watch(sourceFiles, ['process-all']); }); /** * Validate source JavaScript */ gulp.task('jshint', function () { return gulp.src(lintFiles) .pipe(plumber()) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')); }); /** * Run test once and exit */ gulp.task('test-src', function (done) { karma.start({ configFile: __dirname + '/karma-src.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-concatenated', function (done) { karma.start({ configFile: __dirname + '/karma-dist-concatenated.conf.js', singleRun: true }, done); }); /** * Run test once and exit */ gulp.task('test-dist-minified', function (done) { karma.start({ configFile: __dirname + '/karma-dist-minified.conf.js', singleRun: true }, done); }); gulp.task('default', function () { runSequence('process-all', 'watch'); });
nikita-yaroshevich/df-validator
gulpfile.js
JavaScript
mit
2,192
/** * Created by quanpower on 14-8-20. */ var config = require('./../config'); var redis = require('./redis'); var _ = require('lodash'); function cacheDevice(device){ if(device){ var cloned = _.clone(device); redis.set('DEVICE_' + device.uuid, JSON.stringify(cloned),function(){ //console.log('cached', uuid); }); } } function noop(){} if(config.redis){ module.exports = cacheDevice; } else{ module.exports = noop; }
SmartLinkCloud/IOT-platform
lib/cacheDevice.js
JavaScript
mit
479
/** * morningstar-base-charts * * Copyright © 2016 . All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import defaultClasses from "../config/classes.js"; import ChartBase from "./chartBase.js"; import { ChartUtils } from "../utils/utils.js"; /** * Horizontal Bar Chart Implementation * * @extends {ChartBase} */ class HorizontalBarChart extends ChartBase{ /** * Creates an instance of HorizontalBarChart. * * @param {any} options */ constructor(options) { super(options); } /** * @override */ render(options) { var axes = this.axes, yScale = axes.axis("y").scale(), xScale = axes.axis("x").scale(), data = this.data[0].values, chartArea = this.layer, barHeight = yScale.rangeBand(), barPadding = 6, hasNegative = ChartUtils.hasNegative(data), animation = (options && !options.animation) ? false : true;; var getClass = d => { if(hasNegative){ return d >= 0 ? "h-bar-positive" : "h-bar-negative"; } return "h-bar"; }; var draw = selection => { selection.attr("class", getClass) .attr("x", (d) => xScale(Math.min(0, d))) .attr("y", 6) .attr("transform", (d, i) => "translate(0," + i * barHeight + ")") .attr("width", d => animation ? 0 : Math.abs(xScale(d) - xScale(0)) ) .attr("height", barHeight - barPadding); return selection; }; var bar = chartArea.selectAll("rect").data(data); bar.call(draw) .enter().append("rect").call(draw); bar.exit().remove(); if (animation) { bar.transition().duration(300) .attr("width", d => Math.abs(xScale(d) - xScale(0))); } } /** * * * @param {any} index */ onMouseover(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 0.5); } /** * * * @param {any} index */ onMouseout(index) { this.canvas.svg.selectAll(`.${defaultClasses.CHART_GROUP}.${defaultClasses.FOCUS}-${index}`) .transition() .style("opacity", 1); } /** * * * @param {any} data */ _formatData(data) { var xDomain = this.axes.axis("x").scale().domain(); this._categories = data.map(value => value.name); this.data = xDomain.map(function (series, i) { var item = { series }; item.values = data.map(value => { return { series: series, category: value.name, value: value.values[i], index: value.index }; }); return item; }); } } export default HorizontalBarChart;
jmconde/charts
src/js/charts/horizontal.js
JavaScript
mit
3,156
/** * Copyright (c) 2014-2015, CKSource - Frederico Knabben. All rights reserved. * Licensed under the terms of the MIT License (see LICENSE.md). */ ( function( QUnit, bender ) { var total = 0, failed = 0, passed = 0, ignored = 0, errors = 0, result = { success: true, errors: [] }; // prevent QUnit from starting QUnit.config.autostart = false; bender.removeListener( window, 'load', QUnit.load ); function start() { QUnit.testStart( function() { total++; } ); QUnit.testDone( function( details ) { details.success = result.success; details.error = result.errors.length ? result.errors.join( '\n' ) : undefined; details.duration = details.runtime; details.fullName = details.module + ' ' + details.name; bender.result( details ); if ( details.success ) { if ( details.ignored ) { ignored++; } else { passed++; } } else { failed++; errors++; } result.success = true; result.errors = []; } ); QUnit.done( function( details ) { details.duration = details.runtime; bender.next( { coverage: window.__coverage__, duration: details.runtime, passed: passed, failed: failed, errors: errors, ignored: ignored, total: total } ); } ); QUnit.log( function( details ) { // add detailed error message to test result if ( !details.result ) { result.success = false; result.errors.push( [ details.message, 'Expected: ' + details.expected, 'Actual: ' + details.actual, details.source ].join( '\n' ) ); } } ); // manually start the runner QUnit.load(); QUnit.start(); } function stopRunner() { QUnit.stop(); } function isSingle( name ) { return name === decodeURIComponent( window.location.hash.substr( 1 ) ); } var oldTest = QUnit.test; QUnit.test = function( name ) { var module = this.config.currentModule, fullName = module ? module + ' ' + name : name; if ( window.location.hash && window.location.hash !== '#child' && !isSingle( fullName ) ) { return; } oldTest.apply( this, arguments ); }; window.assert = bender.assert = QUnit.assert; bender.runner = QUnit; bender.start = start; bender.stopRunner = stopRunner; } )( window.QUnit || {}, bender );
benderjs/benderjs-qunit
lib/adapter.js
JavaScript
mit
2,277
/** * This is a "mini-app" that encapsulates router definitions. See more * at: http://expressjs.com/guide/routing.html (search for "express.Router") * */ var router = require('express').Router({ mergeParams: true }); module.exports = router; // Don't just use, but also export in case another module needs to use these as well. router.callbacks = require('./controllers/hello'); router.models = require('./models'); //-- For increased module encapsulation, you could also serve templates with module-local //-- paths, but using shared layouts and partials may become tricky / impossible //var hbs = require('hbs'); //app.set('views', __dirname + '/views'); //app.set('view engine', 'handlebars'); //app.engine('handlebars', hbs.__express); // Module's Routes. Please note this is actually under /hello, because module is attached under /hello router.get('/', router.callbacks.sayHello);
KalenAnson/nodebootstrap
lib/hello/hello.js
JavaScript
mit
903
import WebhookNotification, { LinkClick, LinkClickCount, MessageTrackingData, WebhookDelta, WebhookObjectAttributes, WebhookObjectData, } from '../src/models/webhook-notification'; import { WebhookTriggers } from '../src/models/webhook'; describe('Webhook Notification', () => { test('Should deserialize from JSON properly', done => { const webhookNotificationJSON = { deltas: [ { date: 1602623196, object: 'message', type: 'message.created', object_data: { namespace_id: 'aaz875kwuvxik6ku7pwkqp3ah', account_id: 'aaz875kwuvxik6ku7pwkqp3ah', object: 'message', attributes: { action: 'save_draft', job_status_id: 'abc1234', thread_id: '2u152dt4tnq9j61j8seg26ni6', received_date: 1602623166, }, id: '93mgpjynqqu5fohl2dvv6ray7', metadata: { sender_app_id: 64280, link_data: [ { url: 'https://nylas.com/', count: 1, }, ], timestamp: 1602623966, recents: [ { ip: '24.243.155.85', link_index: 0, id: 0, user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36', timestamp: 1602623980, }, ], message_id: '4utnziee7bu2ohak56wfxe39p', payload: 'Tracking enabled', }, }, }, ], }; const webhookNotification = new WebhookNotification().fromJSON( webhookNotificationJSON ); expect(webhookNotification.deltas.length).toBe(1); const webhookDelta = webhookNotification.deltas[0]; expect(webhookDelta instanceof WebhookDelta).toBe(true); expect(webhookDelta.date).toEqual(new Date(1602623196 * 1000)); expect(webhookDelta.object).toEqual('message'); expect(webhookDelta.type).toEqual(WebhookTriggers.MessageCreated); const webhookDeltaObjectData = webhookDelta.objectData; expect(webhookDeltaObjectData instanceof WebhookObjectData).toBe(true); expect(webhookDeltaObjectData.id).toEqual('93mgpjynqqu5fohl2dvv6ray7'); expect(webhookDeltaObjectData.accountId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.namespaceId).toEqual( 'aaz875kwuvxik6ku7pwkqp3ah' ); expect(webhookDeltaObjectData.object).toEqual('message'); const webhookDeltaObjectAttributes = webhookDeltaObjectData.objectAttributes; expect( webhookDeltaObjectAttributes instanceof WebhookObjectAttributes ).toBe(true); expect(webhookDeltaObjectAttributes.action).toEqual('save_draft'); expect(webhookDeltaObjectAttributes.jobStatusId).toEqual('abc1234'); expect(webhookDeltaObjectAttributes.threadId).toEqual( '2u152dt4tnq9j61j8seg26ni6' ); expect(webhookDeltaObjectAttributes.receivedDate).toEqual( new Date(1602623166 * 1000) ); const webhookMessageTrackingData = webhookDeltaObjectData.metadata; expect(webhookMessageTrackingData instanceof MessageTrackingData).toBe( true ); expect(webhookMessageTrackingData.messageId).toEqual( '4utnziee7bu2ohak56wfxe39p' ); expect(webhookMessageTrackingData.payload).toEqual('Tracking enabled'); expect(webhookMessageTrackingData.timestamp).toEqual( new Date(1602623966 * 1000) ); expect(webhookMessageTrackingData.senderAppId).toBe(64280); expect(webhookMessageTrackingData.linkData.length).toBe(1); expect(webhookMessageTrackingData.recents.length).toBe(1); const linkData = webhookMessageTrackingData.linkData[0]; expect(linkData instanceof LinkClickCount).toBe(true); expect(linkData.url).toEqual('https://nylas.com/'); expect(linkData.count).toBe(1); const recents = webhookMessageTrackingData.recents[0]; expect(recents instanceof LinkClick).toBe(true); expect(recents.id).toBe(0); expect(recents.ip).toEqual('24.243.155.85'); expect(recents.userAgent).toEqual( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36' ); expect(recents.timestamp).toEqual(new Date(1602623980 * 1000)); expect(recents.linkIndex).toBe(0); done(); }); });
nylas/nylas-nodejs
__tests__/webhook-notification-spec.js
JavaScript
mit
4,538
import deepFreeze from 'deep-freeze'; import { arrayToMap, mapKeysToArray } from './mapUtils'; describe('arrayToMap', () => { it('should create map from 2D array', () => { const a = [ ['key1', 'value1'], ['key2', 'value2'] ]; deepFreeze(a); const result = arrayToMap(a); expect(result.size).toBe(2); expect(result.get('key1')).toBe('value1'); expect(result.get('key2')).toBe('value2'); }); it('should create empty map from empty array', () => { const result = arrayToMap([]); expect(result.size).toBe(0); }); }); describe('mapKeysToArray', () => { it('should create array from map keys in order', () => { const map = new Map(); map.set('a', 'value1'); map.set('c', 'value2'); map.set('1', 'value3'); map.set('b', 'value4'); map.set('2', 'value5'); const result = mapKeysToArray(map); expect(result).toEqual(['a', 'c', '1', 'b', '2']); }); it('should create empty array from new map', () => { const map = new Map(); const result = mapKeysToArray(map); expect(result).toEqual([]); }); });
TrueWill/embracer
src/utils/mapUtils.test.js
JavaScript
mit
1,107
require('./node') require('./console')
Jam3/hihat
lib/prelude/node-console.js
JavaScript
mit
39
/* * Author: Brendan Le Foll <[email protected]> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var m = require("mraa") console.log("mraa version: " + m.getVersion()); var x = new m.Gpio(8) x.dir(m.DIR_OUT) x.write(1)
rwaldron/mraa
examples/javascript/example.js
JavaScript
mit
1,305
/*! fingoCarousel.js © heoyunjee, 2016 */ function(global, $){ 'use strict'; /** * width: carousel width * height: carousel height * margin: tabpanel margin * count: how many tabpanels will move when you click button * col: how many columns in carousel mask * row: how many rows in carousel mask * infinite: infinite carousel or not(true or false) * index: index of active tabpanel */ // Default Options var defaults = { 'width': 1240, 'height': 390, 'margin': 0, 'count': 1, 'col': 1, 'row': 1, 'infinite': false, 'index': 0 }; // Constructor Function var Carousel = function(widget, options) { // Public this.$widget = $(widget); this.settings = $.extend({}, defaults, options); this.carousel_infinite = false; this.carousel_row = 0; this.carousel_width = 0; this.carousel_height = 0; this.carousel_count = 0; this.carousel_col = 0; this.carousel_content_margin = 0; this.active_index = 0; this.carousel_one_tab = 0; this.carousel_content_width = 0; this.carousel_content_height= 0; this.$carousel = null; this.$carousel_headline = null; this.$carousel_tablist = null; this.$carousel_tabs = null; this.$carousel_button_group = null; this.$carousel_mask = null; this.$carousel_tabpanels = null; this.$carousel_tabpanel_imgs = null; this.$carousel_tabpanel_content_videos = null; this.start_tabpanel_index = 0; // 초기 설정 this.init(); // 이벤트 연결 this.events(); }; // Prototype Object Carousel.prototype = { 'init': function() { var $this = this; var $widget = this.$widget; // 캐러셀 내부 구성 요소 참조 this.$carousel = $widget; this.$carousel_headline = this.$carousel.children(':header:first'); this.$carousel_tablist = this.$carousel.children('ul').wrap('<div/>').parent(); this.$carousel_tabs = this.$carousel_tablist.find('a'); this.$carousel_tabpanels = this.$carousel.children().find('figure'); this.$carousel_content = this.$carousel_tabpanels.children().parent(); this.$carousel_tabpanel_imgs = this.$carousel.children().last().find('img').not('.icon'); this.$carousel_tabpanel_content_videos = this.$carousel.children().last().find('iframe'); this.setResponsive(); this.carousel_width = this.settings.width; this.carousel_height = this.settings.height; this.carousel_infinite = this.settings.infinite; this.carousel_row = this.settings.row; this.carousel_count = this.settings.count; this.carousel_col = this.settings.col; this.carousel_content_margin = this.settings.margin; this.start_tabpanel_index = this.settings.index; // 동적으로 캐러셀 구조 생성/추가 this.createPrevNextButtons(); this.createCarouselMask(); // 역할별 스타일링 되는 클래스 설정 this.settingClass(); this.settingSliding(); }, 'createPrevNextButtons': function() { var button_group = ['<div>', '<button type="button"></button>', '<button type="button"></button>', '</div>'].join(''); this.$carousel_button_group = $(button_group).insertAfter( this.$carousel_tablist ); }, 'createCarouselMask': function() { this.$carousel_tabpanels.parent().closest('div').wrap('<div/>'); this.$carousel_mask = this.$carousel.children().last(); }, 'settingClass': function() { this.$carousel.addClass('ui-carousel'); this.$carousel_headline.addClass('ui-carousel-headline'); this.$carousel_tablist.addClass('ui-carousel-tablist'); this.$carousel_tabs.addClass('ui-carousel-tab'); this.$carousel_button_group.addClass('ui-carousel-button-group'); this.$carousel_button_group.children().first().addClass('ui-carousel-prev-button'); this.$carousel_button_group.children().last().addClass('ui-carousel-next-button'); this.$carousel_tabpanels.addClass('ui-carousel-tabpanel'); this.$carousel_tabpanels.parent().closest('div').addClass('ui-carousel-tabpanel-wrapper'); this.$carousel_mask.addClass('ui-carousel-mask'); this.$carousel_tabpanel_imgs.addClass('ui-carousel-image'); this.$carousel_tabpanel_content_videos.addClass('ui-carousel-video'); if(this.carousel_row === 2) { var j = 1; var j2 = 1; for(var i = 0, l = this.$carousel_tabpanels.length; i < l; i++) { if(i%2===1){ this.$carousel_tabpanels.eq(i).addClass('top-2'); this.$carousel_tabpanels.eq(i).addClass('left-' + j); j++; } else { this.$carousel_tabpanels.eq(i).addClass('top-1'); this.$carousel_tabpanels.eq(i).addClass('left-' + j2); j2++; } } } }, 'settingSliding': function() { var $carousel = this.$carousel; var $tabpanel = this.$carousel_tabpanels; var $tabpanel_wrapper = $tabpanel.parent(); var $carousel_mask = this.$carousel_mask; var carousel_tabpannel_width = ($carousel_mask.width() - (this.carousel_col - 1) * this.carousel_content_margin) / this.carousel_col; this.carousel_content_width = this.$carousel_tabpanel_imgs.eq(0).width(); // carousel 높이 설정 $carousel.height(this.carousel_height); // Set carousel tabpanel(div or img) size and margin if(this.settings.col === 1) { $tabpanel.width($carousel.width()); } else { $tabpanel .width(this.carousel_content_width) .css('margin-right', this.carousel_content_margin); } // Set carousel tabpanel wrapper width $tabpanel_wrapper.width(($tabpanel.width() + this.carousel_content_margin) * ($tabpanel.length + 1)); // Set carousel one tab mask width this.carousel_one_tab = ($tabpanel.width() + this.carousel_content_margin) * this.carousel_count; if(this.start_tabpanel_index !== 0) { for(var i = 0, l = this.start_tabpanel_index + 1; i < l; i++) { this.$carousel_tabpanels.last().parent().prepend(this.$carousel_tabpanels.eq($tabpanel.length - (i + 1))); } } // Carousel 상태 초기화 if(this.carousel_infinite === true) { // tabpanel active 상태 초기화 this.$carousel_tabpanels.eq(this.active_index).radioClass('active'); // tabpanel wrapper 위치 초기화 $tabpanel_wrapper.css('left', -this.carousel_one_tab); } else if(this.carousel_col !== 1){ // Infinite Carousel이 아닐때 // prevBtn 비활성화 this.prevBtnDisable(); } // 인디케이터 active 상태 초기화 this.$carousel_tabs.eq(this.active_index).parent().radioClass('active'); }, 'prevBtnActive': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'false') .css({'opacity': 1, 'display': 'block'}); }, 'prevBtnDisable': function() { this.$carousel.find('.ui-carousel-prev-button') .attr('aria-disabled', 'true') .css({'opacity': 0, 'display': 'none'}); }, 'events': function() { var widget = this; var $carousel = widget.$carousel; var $tabs = widget.$carousel_tabs; var $buttons = widget.$carousel_button_group.children(); // buttons event $buttons.on('click', function() { if ( this.className === 'ui-carousel-prev-button' ) { widget.prevPanel(); } else { widget.nextPanel(); } }); // tabs event $.each($tabs, function(index) { var $tab = $tabs.eq(index); $tab.on('click', $.proxy(widget.viewTabpanel, widget, index, null)); }); }, 'setActiveIndex': function(index) { // 활성화된 인덱스를 사용자가 클릭한 인덱스로 변경 this.active_index = index; // tab 최대 개수 var carousel_tabs_max = (this.$carousel_tabpanels.length / (this.carousel_count * this.carousel_row)) - 1; // 한 마스크 안에 패널이 다 채워지지 않을 경우 if((this.$carousel_tabpanels.length % (this.carousel_count * this.carousel_row)) !== 0) { carousel_tabs_max = carousel_tabs_max + 1; } // 처음 또는 마지막 인덱스에 해당할 경우 마지막 또는 처음으로 변경하는 조건 처리 if ( this.active_index < 0 ) { this.active_index = carousel_tabs_max; } if ( this.active_index > carousel_tabs_max ) { this.active_index = 0; } return this.active_index; }, 'nextPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index + 1); this.viewTabpanel(active_index, 'next'); } }, 'prevPanel': function() { if(!this.$carousel_tabpanels.parent().is(':animated')) { var active_index = this.setActiveIndex(this.active_index - 1); this.viewTabpanel(active_index, 'prev'); } }, 'viewTabpanel': function(index, btn, e) { // 사용자가 클릭을 하는 행위가 발생하면 이벤트 객체를 받기 때문에 // 조건 확인을 통해 브라우저의 기본 동작 차단 if (e) { e.preventDefault(); } this.active_index = index; var $carousel_wrapper = this.$carousel_tabpanels.eq(index).parent(); var one_width = this.carousel_one_tab; // Infinite Carousel if(this.carousel_infinite === true) { // index에 해당되는 탭패널 활성화 this.$carousel_tabpanels.eq(index).radioClass('active'); // next 버튼 눌렀을때 if(btn === 'next') { $carousel_wrapper.stop().animate({ 'left': -one_width * 2 }, 500, 'easeOutExpo', function() { $carousel_wrapper.append($carousel_wrapper.children().first()); $carousel_wrapper.css('left', -one_width); this.animating = false; }); // prev 버튼 눌렀을때 } else if(btn === 'prev') { $carousel_wrapper.stop().animate({ 'left': 0 }, 500, 'easeOutExpo', function() { $carousel_wrapper.prepend($carousel_wrapper.children().last()); $carousel_wrapper.css('left', -one_width); }); } } else if(this.carousel_infinite === false) { if(this.carousel_col !== 1) { if(index === 0) { this.prevBtnDisable(); } else { this.prevBtnActive(); } } $carousel_wrapper.stop().animate({ 'left': index * -this.carousel_one_tab }, 600, 'easeOutExpo'); } // 인디케이터 라디오클래스 활성화 this.$carousel_tabs.eq(index).parent().radioClass('active'); }, 'setResponsive': function() { if(global.innerWidth <= 750) { this.settings.width = this.settings.width.mobile || this.settings.width; this.settings.height = this.settings.height.mobile || this.settings.height; this.settings.margin = this.settings.margin.mobile || this.settings.margin; this.settings.count = this.settings.count.mobile || this.settings.count; this.settings.col = this.settings.col.mobile || this.settings.col; this.settings.row = this.settings.row.mobile || this.settings.row; if(this.settings.infinite.mobile !== undefined) { this.settings.infinite = this.settings.infinite.mobile; } this.settings.index = 0; } else if(global.innerWidth <= 1024) { this.settings.width = this.settings.width.tablet || this.settings.width; this.settings.height = this.settings.height.tablet || this.settings.height; this.settings.margin = this.settings.margin.tablet || this.settings.margin; this.settings.count = this.settings.count.tablet || this.settings.count; this.settings.col = this.settings.col.tablet || this.settings.col; this.settings.row = this.settings.row.tablet || this.settings.row; if(this.settings.infinite.tablet !== undefined) { this.settings.infinite = this.settings.infinite.tablet; } this.settings.index = this.settings.index.tablet || this.settings.index; } else { this.settings.width = this.settings.width.desktop || this.settings.width; this.settings.height = this.settings.height.desktop || this.settings.height; this.settings.margin = this.settings.margin.desktop || this.settings.margin; this.settings.count = this.settings.count.desktop || this.settings.count; this.settings.col = this.settings.col.desktop || this.settings.col; this.settings.row = this.settings.row.desktop || this.settings.row; if(this.settings.infinite.desktop !== undefined) { this.settings.infinite = this.settings.infinite.desktop; } this.settings.index = this.settings.index.desktop || this.settings.index; } } }; // jQuery Plugin $.fn.fingoCarousel = function(options){ var $collection = this; // jQuery {} return $.each($collection, function(idx){ var $this = $collection.eq(idx); var _instance = new Carousel( this, options ); // 컴포넌트 화 $this.data('fingoCarousel', _instance); }); }; })(this, this.jQuery);
ooyunjee/fingoCarousel
fingo.carousel.js
JavaScript
mit
13,831
class upnp_soaprequest { constructor() { } // System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType) CreateObjRef() { } // bool Equals(System.Object obj) Equals() { } // int GetHashCode() GetHashCode() { } // System.Object GetLifetimeService() GetLifetimeService() { } // type GetType() GetType() { } // System.Object InitializeLifetimeService() InitializeLifetimeService() { } // string ToString() ToString() { } } module.exports = upnp_soaprequest;
mrpapercut/wscript
testfiles/COMobjects/JSclasses/UPnP.SOAPRequest.js
JavaScript
mit
569
module.exports = { schedule_inputError: "Not all required inputs are present in the request", reminder_newscheduleSuccess: "A new mail has been successfully saved and scheduled", schedule_ShdlError: "The scheduleAt should be a timestamp (like : 1411820580000) and should be in the future", gbl_oops: "Oops something went wrong", gbl_success: "success" };
karankohli13/sendgrid-scheduler
messages/messages.js
JavaScript
mit
375
/** * create edit language file link */ export default (lang) => { return `https://github.com/electerm/electerm-locales/edit/master/locales/${lang}.js` }
electerm/electerm
src/client/common/create-lang-edit-link.js
JavaScript
mit
159
/** * @author Ultimo <[email protected]> * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version 0.1 (25-06-2017) * * Hier schreiben wir die JavaScript Funktionen. * */ src="jquery-3.2.1.min"; $(document).ready(function(){ $("td:contains('-')").filter(":contains('€')").addClass('neg'); $(".betrag").filter(":contains('-')").addClass('neg'); }); function goBack() { window.history.back(); }
vonUltimo/kasse
js/lib.js
JavaScript
mit
446
var compare = require('typewiselite') var search = require('binary-search') function compareKeys (a, b) { return compare(a.key, b.key) } module.exports = function (_compare) { var ary = [], kv _compare = _compare || compare function cmp (a, b) { return _compare(a.key, b.key) } return kv = { getIndex: function (key) { return search(ary, {key: key}, cmp, 0, ary.length - 1) }, get: function (key) { var i = this.getIndex(key) return i >= 0 ? ary[i].value : undefined }, has: function (key) { return this.getIndex(key) >= 0 }, //update a key set: function (key, value) { return kv.add({key: key, value: value}) }, add: function (o) { var i = search(ary, o, cmp) //overwrite a key, or insert a key if(i < 0) ary.splice(~i, 0, o) else ary[i] = o return i }, toJSON: function () { return ary.slice() }, store: ary } } module.exports.search = search module.exports.compareKeys = compareKeys
dominictarr/binary-map
index.js
JavaScript
mit
1,040
define( [ 'jquery', 'angular', 'json!nuke/data/dummy_model.json', 'json!nuke/data/dummy_layout.json', 'text!nuke/demo.html' ], function( $, ng, dummyModel, dummyLayout, htmlDemoTemplate ) { 'use strict'; var module = ng.module( 'NukeDemoApp', [ 'nbe' ] ) .run( [ '$templateCache', function( $templateCache ) { $templateCache.put( 'lib/demo.html', htmlDemoTemplate ); } ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// function NukeDemoController( $scope, $timeout ) { $scope.model = dummyModel; $scope.layout = dummyLayout; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// module.controller( 'NukeDemoController', [ '$scope', '$timeout', NukeDemoController ] ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// return module; } );
x1B/nbe
examples/nuke/lib/NukeDemoController.js
JavaScript
mit
998
/** * @author Richard Davey <[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * This is where the magic happens. The Game object is the heart of your game, * providing quick access to common functions and handling the boot process. * * "Hell, there are no rules here - we're trying to accomplish something." * Thomas A. Edison * * @class Phaser.Game * @constructor * @param {object} [gameConfig={}] - The game configuration object */ Phaser.Game = function (gameConfig) { /** * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances). * @readonly */ this.id = Phaser.GAMES.push(this) - 1; /** * @property {object} config - The Phaser.Game configuration object. */ this.config = null; /** * @property {object} physicsConfig - The Phaser.Physics.World configuration object. */ this.physicsConfig = null; /** * @property {string|HTMLElement} parent - The Games DOM parent. * @default */ this.parent = ''; /** * The current Game Width in pixels. * * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead. * * @property {integer} width * @readonly * @default */ this.width = 800; /** * The current Game Height in pixels. * * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead. * * @property {integer} height * @readonly * @default */ this.height = 600; /** * The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object. * * @property {integer} resolution * @readonly * @default */ this.resolution = 1; /** * @property {integer} _width - Private internal var. * @private */ this._width = 800; /** * @property {integer} _height - Private internal var. * @private */ this._height = 600; /** * @property {boolean} transparent - Use a transparent canvas background or not. * @default */ this.transparent = false; /** * @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally. * @default */ this.antialias = false; /** * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering. * @default */ this.preserveDrawingBuffer = false; /** * Clear the Canvas each frame before rendering the display list. * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display. * @property {boolean} clearBeforeRender * @default */ this.clearBeforeRender = true; /** * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer. * @protected */ this.renderer = null; /** * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, or Phaser.HEADLESS. * @readonly */ this.renderType = Phaser.AUTO; /** * @property {Phaser.StateManager} state - The StateManager. */ this.state = null; /** * @property {boolean} isBooted - Whether the game engine is booted, aka available. * @readonly */ this.isBooted = false; /** * @property {boolean} isRunning - Is game running or paused? * @readonly */ this.isRunning = false; /** * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout * @protected */ this.raf = null; /** * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory. */ this.add = null; /** * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator. */ this.make = null; /** * @property {Phaser.Cache} cache - Reference to the assets cache. */ this.cache = null; /** * @property {Phaser.Input} input - Reference to the input manager */ this.input = null; /** * @property {Phaser.Loader} load - Reference to the assets loader. */ this.load = null; /** * @property {Phaser.Math} math - Reference to the math helper. */ this.math = null; /** * @property {Phaser.Net} net - Reference to the network class. */ this.net = null; /** * @property {Phaser.ScaleManager} scale - The game scale manager. */ this.scale = null; /** * @property {Phaser.SoundManager} sound - Reference to the sound manager. */ this.sound = null; /** * @property {Phaser.Stage} stage - Reference to the stage. */ this.stage = null; /** * @property {Phaser.Time} time - Reference to the core game clock. */ this.time = null; /** * @property {Phaser.TweenManager} tweens - Reference to the tween manager. */ this.tweens = null; /** * @property {Phaser.World} world - Reference to the world. */ this.world = null; /** * @property {Phaser.Physics} physics - Reference to the physics manager. */ this.physics = null; /** * @property {Phaser.PluginManager} plugins - Reference to the plugin manager. */ this.plugins = null; /** * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. */ this.rnd = null; /** * @property {Phaser.Device} device - Contains device information and capabilities. */ this.device = Phaser.Device; /** * @property {Phaser.Camera} camera - A handy reference to world.camera. */ this.camera = null; /** * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to. */ this.canvas = null; /** * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL) */ this.context = null; /** * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities. */ this.debug = null; /** * @property {Phaser.Particles} particles - The Particle Manager. */ this.particles = null; /** * @property {Phaser.Create} create - The Asset Generator. */ this.create = null; /** * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped. * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully. * @property {boolean} lockRender * @default */ this.lockRender = false; /** * @property {boolean} stepping - Enable core loop stepping with Game.enableStep(). * @default * @readonly */ this.stepping = false; /** * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects. * @default * @readonly */ this.pendingStep = false; /** * @property {number} stepCount - When stepping is enabled this contains the current step cycle. * @default * @readonly */ this.stepCount = 0; /** * @property {Phaser.Signal} onPause - This event is fired when the game pauses. */ this.onPause = null; /** * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state. */ this.onResume = null; /** * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide). */ this.onBlur = null; /** * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show). */ this.onFocus = null; /** * @property {boolean} _paused - Is game paused? * @private */ this._paused = false; /** * @property {boolean} _codePaused - Was the game paused via code or a visibility change? * @private */ this._codePaused = false; /** * The ID of the current/last logic update applied this render frame, starting from 0. * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.` * @property {integer} currentUpdateID * @protected */ this.currentUpdateID = 0; /** * Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed). * @property {integer} updatesThisFrame * @protected */ this.updatesThisFrame = 1; /** * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due. * @private */ this._deltaTime = 0; /** * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame. * @private */ this._lastCount = 0; /** * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented. * @private */ this._spiraling = 0; /** * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap) * @private */ this._kickstart = true; /** * If the game is struggling to maintain the desired FPS, this signal will be dispatched. * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value. * @property {Phaser.Signal} fpsProblemNotifier * @public */ this.fpsProblemNotifier = new Phaser.Signal(); /** * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly. */ this.forceSingleUpdate = true; /** * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched. * @private */ this._nextFpsNotification = 0; // Parse the configuration object if (typeof gameConfig !== 'object') { throw new Error('Missing game configuration object: ' + gameConfig); } this.parseConfig(gameConfig); this.device.whenReady(this.boot, this); return this; }; Phaser.Game.prototype = { /** * Parses a Game configuration object. * * @method Phaser.Game#parseConfig * @protected */ parseConfig: function (config) { this.config = config; if (config['enableDebug'] === undefined) { this.config.enableDebug = true; } if (config['width']) { this._width = config['width']; } if (config['height']) { this._height = config['height']; } if (config['renderer']) { this.renderType = config['renderer']; } if (config['parent']) { this.parent = config['parent']; } if (config['transparent'] !== undefined) { this.transparent = config['transparent']; } if (config['antialias'] !== undefined) { this.antialias = config['antialias']; } if (config['resolution']) { this.resolution = config['resolution']; } if (config['preserveDrawingBuffer'] !== undefined) { this.preserveDrawingBuffer = config['preserveDrawingBuffer']; } if (config['clearBeforeRender'] !== undefined) { this.clearBeforeRender = config['clearBeforeRender']; } if (config['physicsConfig']) { this.physicsConfig = config['physicsConfig']; } var seed = [(Date.now() * Math.random()).toString()]; if (config['seed']) { seed = config['seed']; } this.rnd = new Phaser.RandomDataGenerator(seed); var state = null; if (config['state']) { state = config['state']; } this.state = new Phaser.StateManager(this, state); }, /** * Initialize engine sub modules and start the game. * * @method Phaser.Game#boot * @protected */ boot: function () { if (this.isBooted) { return; } this.onPause = new Phaser.Signal(); this.onResume = new Phaser.Signal(); this.onBlur = new Phaser.Signal(); this.onFocus = new Phaser.Signal(); this.isBooted = true; PIXI.game = this; this.math = Phaser.Math; this.scale = new Phaser.ScaleManager(this, this._width, this._height); this.stage = new Phaser.Stage(this); this.setUpRenderer(); this.world = new Phaser.World(this); this.add = new Phaser.GameObjectFactory(this); this.make = new Phaser.GameObjectCreator(this); this.cache = new Phaser.Cache(this); this.load = new Phaser.Loader(this); this.time = new Phaser.Time(this); this.tweens = new Phaser.TweenManager(this); this.input = new Phaser.Input(this); this.sound = new Phaser.SoundManager(this); this.physics = new Phaser.Physics(this, this.physicsConfig); this.particles = new Phaser.Particles(this); this.create = new Phaser.Create(this); this.plugins = new Phaser.PluginManager(this); this.net = new Phaser.Net(this); this.time.boot(); this.stage.boot(); this.world.boot(); this.scale.boot(); this.input.boot(); this.sound.boot(); this.state.boot(); if (this.config['enableDebug']) { this.debug = new Phaser.Utils.Debug(this); this.debug.boot(); } else { this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} }; } this.showDebugHeader(); this.isRunning = true; if (this.config && this.config['forceSetTimeOut']) { this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']); } else { this.raf = new Phaser.RequestAnimationFrame(this, false); } this._kickstart = true; if (window['focus']) { if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus)) { window.focus(); } } this.raf.start(); }, /** * Displays a Phaser version debug header in the console. * * @method Phaser.Game#showDebugHeader * @protected */ showDebugHeader: function () { if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner) { return; } var v = Phaser.VERSION; var r = 'Canvas'; var a = 'HTML Audio'; var c = 1; if (this.renderType === Phaser.WEBGL) { r = 'WebGL'; c++; } else if (this.renderType === Phaser.HEADLESS) { r = 'Headless'; } if (this.device.webAudio) { a = 'WebAudio'; c++; } if (this.device.chrome) { var args = [ '%c %c %c Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665', 'background: #fb8cb3', 'background: #d44a52', 'color: #ffffff; background: #871905;', 'background: #d44a52', 'background: #fb8cb3', 'background: #ffffff' ]; for (var i = 0; i < 3; i++) { if (i < c) { args.push('color: #ff2424; background: #fff'); } else { args.push('color: #959595; background: #fff'); } } console.log.apply(console, args); } else if (window['console']) { console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io'); } }, /** * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. * * @method Phaser.Game#setUpRenderer * @protected */ setUpRenderer: function () { if (this.config['canvas']) { this.canvas = this.config['canvas']; } else { this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true); } if (this.config['canvasStyle']) { this.canvas.style = this.config['canvasStyle']; } else { this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; } if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && !this.device.webGL)) { if (this.device.canvas) { // They requested Canvas and their browser supports it this.renderType = Phaser.CANVAS; this.renderer = new PIXI.CanvasRenderer(this); this.context = this.renderer.context; } else { throw new Error('Phaser.Game - Cannot create Canvas or WebGL context, aborting.'); } } else { // They requested WebGL and their browser supports it this.renderType = Phaser.WEBGL; this.renderer = new PIXI.WebGLRenderer(this); this.context = null; this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false); this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false); } if (this.device.cocoonJS) { this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false; } if (this.renderType !== Phaser.HEADLESS) { this.stage.smoothed = this.antialias; Phaser.Canvas.addToDOM(this.canvas, this.parent, false); Phaser.Canvas.setTouchAction(this.canvas); } }, /** * Handles WebGL context loss. * * @method Phaser.Game#contextLost * @private * @param {Event} event - The webglcontextlost event. */ contextLost: function (event) { event.preventDefault(); this.renderer.contextLost = true; }, /** * Handles WebGL context restoration. * * @method Phaser.Game#contextRestored * @private */ contextRestored: function () { this.renderer.initContext(); this.cache.clearGLTextures(); this.renderer.contextLost = false; }, /** * The core game loop. * * @method Phaser.Game#update * @protected * @param {number} time - The current time as provided by RequestAnimationFrame. */ update: function (time) { this.time.update(time); if (this._kickstart) { this.updateLogic(this.time.desiredFpsMult); // call the game render update exactly once every frame this.updateRender(this.time.slowMotion * this.time.desiredFps); this._kickstart = false; return; } // if the logic time is spiraling upwards, skip a frame entirely if (this._spiraling > 1 && !this.forceSingleUpdate) { // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate if (this.time.time > this._nextFpsNotification) { // only permit one fps notification per 10 seconds this._nextFpsNotification = this.time.time + 10000; // dispatch the notification signal this.fpsProblemNotifier.dispatch(); } // reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped this._deltaTime = 0; this._spiraling = 0; // call the game render update exactly once every frame this.updateRender(this.time.slowMotion * this.time.desiredFps); } else { // step size taking into account the slow motion speed var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps; // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0); // call the game update logic multiple times if necessary to "catch up" with dropped frames // unless forceSingleUpdate is true var count = 0; this.updatesThisFrame = Math.floor(this._deltaTime / slowStep); if (this.forceSingleUpdate) { this.updatesThisFrame = Math.min(1, this.updatesThisFrame); } while (this._deltaTime >= slowStep) { this._deltaTime -= slowStep; this.currentUpdateID = count; this.updateLogic(this.time.desiredFpsMult); count++; if (this.forceSingleUpdate && count === 1) { break; } else { this.time.refresh(); } } // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly) if (count > this._lastCount) { this._spiraling++; } else if (count < this._lastCount) { // looks like it caught up successfully, reset the spiral alert counter this._spiraling = 0; } this._lastCount = count; // call the game render update exactly once every frame unless we're playing catch-up from a spiral condition this.updateRender(this._deltaTime / slowStep); } }, /** * Updates all logic subsystems in Phaser. Called automatically by Game.update. * * @method Phaser.Game#updateLogic * @protected * @param {number} timeStep - The current timeStep value as determined by Game.update. */ updateLogic: function (timeStep) { if (!this._paused && !this.pendingStep) { if (this.stepping) { this.pendingStep = true; } this.scale.preUpdate(); this.debug.preUpdate(); this.camera.preUpdate(); this.physics.preUpdate(); this.state.preUpdate(timeStep); this.plugins.preUpdate(timeStep); this.stage.preUpdate(); this.state.update(); this.stage.update(); this.tweens.update(); this.sound.update(); this.input.update(); this.physics.update(); this.particles.update(); this.plugins.update(); this.stage.postUpdate(); this.plugins.postUpdate(); } else { // Scaling and device orientation changes are still reflected when paused. this.scale.pauseUpdate(); this.state.pauseUpdate(); this.debug.preUpdate(); } this.stage.updateTransform(); }, /** * Runs the Render cycle. * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required. * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down. * It then calls plugin.render on any loaded plugins, in the order in which they were enabled. * After this State.render is called. Any rendering that happens here will take place on-top of the display list. * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled. * This method is called automatically by Game.update, you don't need to call it directly. * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean. * Phaser will only render when this boolean is `false`. * * @method Phaser.Game#updateRender * @protected * @param {number} elapsedTime - The time elapsed since the last update. */ updateRender: function (elapsedTime) { if (this.lockRender) { return; } this.state.preRender(elapsedTime); if (this.renderType !== Phaser.HEADLESS) { this.renderer.render(this.stage); this.plugins.render(elapsedTime); this.state.render(elapsedTime); } this.plugins.postRender(elapsedTime); }, /** * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?) * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors! * * @method Phaser.Game#enableStep */ enableStep: function () { this.stepping = true; this.pendingStep = false; this.stepCount = 0; }, /** * Disables core game loop stepping. * * @method Phaser.Game#disableStep */ disableStep: function () { this.stepping = false; this.pendingStep = false; }, /** * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame. * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress. * * @method Phaser.Game#step */ step: function () { this.pendingStep = false; this.stepCount++; }, /** * Nukes the entire game from orbit. * * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins. * * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM * and resets the PIXI default renderer. * * @method Phaser.Game#destroy */ destroy: function () { this.raf.stop(); this.state.destroy(); this.sound.destroy(); this.scale.destroy(); this.stage.destroy(); this.input.destroy(); this.physics.destroy(); this.plugins.destroy(); this.state = null; this.sound = null; this.scale = null; this.stage = null; this.input = null; this.physics = null; this.plugins = null; this.cache = null; this.load = null; this.time = null; this.world = null; this.isBooted = false; this.renderer.destroy(false); Phaser.Canvas.removeFromDOM(this.canvas); PIXI.defaultRenderer = null; Phaser.GAMES[this.id] = null; }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#gamePaused * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ gamePaused: function (event) { // If the game is already paused it was done via game code, so don't re-pause it if (!this._paused) { this._paused = true; this.time.gamePaused(); if (this.sound.muteOnPause) { this.sound.setMute(); } this.onPause.dispatch(event); // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 if (this.device.cordova && this.device.iOS) { this.lockRender = true; } } }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#gameResumed * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ gameResumed: function (event) { // Game is paused, but wasn't paused via code, so resume it if (this._paused && !this._codePaused) { this._paused = false; this.time.gameResumed(); this.input.reset(); if (this.sound.muteOnPause) { this.sound.unsetMute(); } this.onResume.dispatch(event); // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800 if (this.device.cordova && this.device.iOS) { this.lockRender = false; } } }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#focusLoss * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ focusLoss: function (event) { this.onBlur.dispatch(event); if (!this.stage.disableVisibilityChange) { this.gamePaused(event); } }, /** * Called by the Stage visibility handler. * * @method Phaser.Game#focusGain * @param {object} event - The DOM event that caused the game to pause, if any. * @protected */ focusGain: function (event) { this.onFocus.dispatch(event); if (!this.stage.disableVisibilityChange) { this.gameResumed(event); } } }; Phaser.Game.prototype.constructor = Phaser.Game; /** * The paused state of the Game. A paused game doesn't update any of its subsystems. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. * @name Phaser.Game#paused * @property {boolean} paused - Gets and sets the paused state of the Game. */ Object.defineProperty(Phaser.Game.prototype, "paused", { get: function () { return this._paused; }, set: function (value) { if (value === true) { if (this._paused === false) { this._paused = true; this.sound.setMute(); this.time.gamePaused(); this.onPause.dispatch(this); } this._codePaused = true; } else { if (this._paused) { this._paused = false; this.input.reset(); this.sound.unsetMute(); this.time.gameResumed(); this.onResume.dispatch(this); } this._codePaused = false; } } }); /** * * "Deleted code is debugged code." - Jeff Sickel * * ヽ(〃^▽^〃)ノ * */
vpmedia/phaser2-lite
src/core/Game.js
JavaScript
mit
31,942
/* app/ui/map/svg */ define( [ 'jquery', 'raphael', 'app/ui/map/data', 'app/ui/map/util', 'util/detector', 'pubsub' ], function ($, Raphael, MapData, MapUtil, Detector) { 'use strict'; var SVG; return { nzte: {}, markers: [], exports: {}, countryText: {}, sets: {}, continentSets: {}, text: {}, raphael: null, _$container: null, _isExportsMap: false, init: function () { SVG = this; this._$container = $('.js-map-container'); this._isExportsMap = $('#js-map-nzte').length ? false : true; //If already setup just show the map again if (this._$container.is('.is-loaded')) { this._$container.show(); return; } if (this._isExportsMap) { this._initInteractiveMap(); return; } this._initRegularMap(); }, _initInteractiveMap: function () { this._setUpMap(); this._drawMap(); this._createContinentSets(); this._initInteractiveMapEvents(); this._setLoaded(); this._hideLoader(); }, _initRegularMap: function () { this._setUpMap(); this._drawMap(); this._createSets(); this._initRegularMapEvents(); this._setLoaded(); this._hideLoader(); }, _setLoaded: function () { this._$container.addClass('is-loaded'); }, _hideLoader: function () { $.publish('/loader/hide'); }, _setUpMap: function () { var id = this._isExportsMap ? 'js-map-exports' : 'js-map-nzte'; this._$container.show(); this.raphael = Raphael(id, '100%', '100%'); this.raphael.setViewBox(0, 0, 841, 407, true); this.raphael.canvas.setAttribute('preserveAspectRatio', 'xMinYMin meet'); }, _drawMap: function () { this._addMainMap(); this._addContinentMarkers(); this._addContinentMarkerText(); if (this._isExportsMap) { this._addCountryMarkers(); } }, _addMainMap: function () { var mainAttr = { stroke: 'none', fill: '#dededd', 'fill-rule': 'evenodd', 'stroke-linejoin': 'round' }; this.nzte.main = this.raphael.path(MapData.main).attr(mainAttr); }, _addContinentMarkers: function () { var markerAttr = { stroke: 'none', fill: '#f79432', 'stroke-linejoin': 'round', cursor: 'pointer' }; var markerPaths = MapData.markers[0]; for (var continent in markerPaths) { if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') { this.markers[continent] = this.raphael.path(markerPaths[continent]).attr(markerAttr); } } }, _addContinentMarkerText: function () { var textAttr = { stroke: 'none', fill: '#ffffff', 'fill-rule': 'evenodd', 'stroke-linejoin': 'round', cursor: 'pointer' }; var textPaths = MapData.text[0]; for (var continent in textPaths) { if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') { this.text[continent] = this.raphael.path(textPaths[continent]).attr(textAttr); } } }, _addCountryMarkers: function () { var marker; for (var region in this.markers) { marker = this.markers[region]; this._createHoverBox(region, marker); } }, _createHoverBox: function (region, marker) { var set; var markerAttr = { stroke: 'none', fill: '#116697', opacity: 0, 'stroke-linejoin': 'round' }; var markerPaths = MapData.exportsText[0]; var country = markerPaths[region]; if (!country) { return; } var countryText = markerPaths[region][0]; var numberOfCountries = Object.keys(countryText).length; var markerBox = marker.getBBox(); var topX = markerBox.x; var bottomY = markerBox.y2; var width = region !== 'india-middle-east-and-africa' ? 150 : 200; //Add the rectangle this.exports[region] = this.raphael.rect(topX + 28, bottomY - 1, width, (21 * numberOfCountries) + 5).toBack().attr(markerAttr); //Create a set to combine countries, hover box and region icon/text set = this.raphael.set(); set.push( this.exports[region] ); //Add the country Text this._addCountryText(markerBox, countryText, topX + 28, bottomY - 1, 21, region, set); }, _addCountryText: function (markerBox, countryText, x, y, height, region, set) { var updatedX = x + 10; var updatedY = y + 10; var textAttr = { font: '13px Arial', textAlign: 'left', fill: "#ffffff", cursor: 'pointer', 'text-decoration': 'underline', 'text-anchor': 'start', opacity: 0 }; for (var country in countryText) { var text = countryText[country].toUpperCase(); this.countryText[country] = this.raphael.text(updatedX, updatedY, text).toBack().attr(textAttr); updatedY += height; set.push( this.countryText[country] ); } this.continentSets[region] = set.hide(); }, _createSets: function () { for (var region in this.markers) { var set = this.raphael.set(); set.push( this.markers[region], this.text[region] ); this.sets[region] = set; } }, _createContinentSets: function () { for (var region in this.markers) { var set = this.raphael.set(); set.push( this.markers[region], this.text[region], this.continentSets[region] ); this.sets[region] = set; } }, _initInteractiveMapEvents: function () { this._initCountryTextEvents(); this._initCountryHoverEvents(); }, _initRegularMapEvents: function () { var bounceEasing = 'cubic-bezier(0.680, -0.550, 0.265, 1.550)'; var mouseOverMarkerBounce = { transform: 's1.1' }; var mouseOverMarkerBounceWithTranslate = { transform: 's1.1t5,0' }; var mouseOutMarkerBounce = { transform: 's1' }; var mouseOverMarker = { fill: '#116697' }; var mouseOutMarker = { fill: '#f79432' }; for (var region in this.sets) { var set = this.sets[region]; var marker = this.markers[region]; var text = this.text[region]; (function (savedSet, savedRegion, savedMarker, savedText) { savedSet.attr({ cursor: 'pointer' }); savedSet.hover(function () { //A slight translation is needed for 'india-middle-east-and-africa' so when hovered it isn't clipped by container var transformAttr = savedRegion !== 'india-middle-east-and-africa' ? mouseOverMarkerBounce : mouseOverMarkerBounceWithTranslate; savedMarker.animate(transformAttr, 250, bounceEasing); savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); savedText.animate(transformAttr, 250, bounceEasing); }, function () { savedMarker.animate(mouseOutMarkerBounce, 250, bounceEasing); savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); savedText.animate(mouseOutMarkerBounce, 250, bounceEasing); }); savedSet.click(function () { MapUtil.goToUrl(savedRegion, false); }); })(set, region, marker, text); } }, _initCountryHoverEvents: function () { var noHover = Detector.noSvgHover(); var mouseOverMarker = { fill: '#116697' }; var mouseOutMarker = { fill: '#f79432' }; for (var region in this.sets) { var set = this.sets[region]; var continentSet = this.continentSets[region]; var marker = this.markers[region]; var text = this.text[region]; var hoverBox = this.exports[region]; (function (savedSet, savedContinentSet, savedRegion, savedMarker, savedText, savedBox) { savedSet.attr({ cursor: 'pointer' }); if (noHover) { savedMarker.data('open', false); savedSet.click(function () { if (savedMarker.data('open') === false) { SVG._closeAllContinents(); savedMarker.data('open', true); savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo'); } else { savedMarker.data('open', false); savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack(); } }); savedSet.hover(function () { savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); }, function () { savedMarker.data('open') === false && savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); }); } else { savedSet.hover(function () { savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo'); savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo'); }, function () { savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine'); savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack(); }); } })(set, continentSet, region, marker, text, hoverBox); } }, _closeAllContinents: function () { for (var region in this.sets) { var continentSet = this.continentSets[region]; var marker = this.markers[region]; var mouseOutMarker = { fill: '#f79432' }; marker.data('open', false); marker.animate(mouseOutMarker, 250, 'easeInOutSine'); continentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack(); } }, _initCountryTextEvents: function () { for (var country in this.countryText) { var text = this.countryText[country]; (function (savedText, savedCountry) { savedText.click(function () { MapUtil.goToUrl(savedCountry, true); }); savedText.hover(function () { savedText.animate({ 'fill-opacity': 0.6 }, 250, 'easeInOutSine'); }, function () { savedText.animate({ 'fill-opacity': 1 }, 250, 'easeInOutSine'); }); })(text, country); } } }; } );
patocallaghan/questionnaire-js
original/assets/scripts/src/app/ui/map/svg.js
JavaScript
mit
9,939
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ meta: { version: '2.0.0', banner: '/*! Ebla - v<%= meta.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '* Copyright (c) <%= grunt.template.today("yyyy") %> ' + 'Monospaced */' }, concat: { dist: { src: ['<banner:meta.banner>', 'javascripts/libs/jquery.cookie.js', 'javascripts/ebla/ebla.js', 'javascripts/ebla/debug.js', 'javascripts/ebla/flash-message.js', 'javascripts/ebla/compatibility.js', 'javascripts/ebla/elements.js', 'javascripts/ebla/controls.js', 'javascripts/ebla/data.js', 'javascripts/ebla/images.js', 'javascripts/ebla/layout.js', 'javascripts/ebla/loader.js', 'javascripts/ebla/navigation.js', 'javascripts/ebla/navigation.event.js', 'javascripts/ebla/navigation.keyboard.js', 'javascripts/ebla/placesaver.js', 'javascripts/ebla/progress.js', 'javascripts/ebla/resize.js', 'javascripts/ebla/toc.js', 'javascripts/ebla/init.js', 'javascripts/ebla/book.js'], dest: 'javascripts/ebla.js' } }, uglify: { dist: { src: ['<banner:meta.banner>', 'javascripts/ebla.js'], dest: 'javascripts/ebla.min.js' } }, sass: { dist: { options: { style: 'compressed' }, files: { 'stylesheets/ebla.css': 'stylesheets/ebla.scss', 'stylesheets/book.css': 'stylesheets/book.scss' } } }, watch: { files: ['javascripts/ebla/*.js', 'stylesheets/*.scss'], tasks: ['sass', 'concat', 'uglify'] }, jshint: { files: ['Gruntfile.js', 'javascripts/ebla.js'], options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, browser: true, jquery: true, devel: true, globals: { Modernizr: true, debug: true, bookData: true, bookJson: true } }, } }); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); // Default task. grunt.registerTask('default', ['sass', 'concat', 'jshint', 'uglify']); };
monospaced/paperback
ebla/Gruntfile.js
JavaScript
mit
2,746
import {Chart} from 'react-google-charts'; import React, {Component, PropTypes} from 'react'; import DataFormatter from '../../utils/DataFormatter'; class EnvyBarChart extends Component { constructor(props) { super(props); this.state={ options:{ hAxis: {title: 'Event Type'}, vAxis: {title: 'Envy Events'}, legend: 'none', }, }; } generateGraph(events) { var formatter = new DataFormatter(); var result = formatter.generateEnvyGraph(events); return result; } render() { var data = this.generateGraph(this.props.events); return ( <Chart chartType="ColumnChart" data={data} options={this.state.options} graph_id="EnvyBarChart" width='40vw' height='50vh' /> ); } }; EnvyBarChart.propTypes = { events: PropTypes.array.isRequired } export default EnvyBarChart;
papernotes/actemotion
src/components/charts/EnvyBarChart.js
JavaScript
mit
828
"use strict"; let mongoose = require('mongoose'), Schema = mongoose.Schema, EmailValidator = require('./emailValidator'); class User { constructor(explicitConnection) { this.explicitConnection = explicitConnection; this.schema = new Schema({ email: { type: 'string', trim: true, required: true }, organization: { type: 'string', trim: true, required: true }, password: {type: 'string', required: true}, isVisibleAccount: {type: 'boolean'}, userApiKey: {type: 'string'}, userApiSecret: {type: 'string'}, linkedApps: {}, avatarProto: {type: 'string'}, gmailAccount: {type: 'string'}, facebookAccount: {type: 'string'}, twitterAccount: {type: 'string'}, fullname: {type: 'string'}, loginHistories: [], changeProfileHistories: [], changeAuthorizationHistories: [], sparqlQuestions: [], blockingHistories: [], authorizations: {}, tripleUsage: {type: 'number', default: 0}, tripleUsageHistory: [], isBlocked: { type: 'boolean', required: true }, blockedCause: { type: 'string', } }).index({ email: 1, organization: 1 }, { unique: true }); } getModel() { if (this.explicitConnection === undefined) { return mongoose.model('User', this.schema); } else { return this.explicitConnection.model('User', this.schema); } } } module.exports = User;
koneksys/KLD
api/model/user.js
JavaScript
mit
1,603
module.export = { };
Force-Wj/chat-demo
src/base/util.js
JavaScript
mit
22
(function (ns) { // dependencies var assert = require('assert'); var esgraph = require('esgraph'); var worklist = require('analyses'); var common = require("../../base/common.js"); var Context = require("../../base/context.js"); var Base = require("../../base/index.js"); var codegen = require('escodegen'); var annotateRight = require("./infer_expression.js"); var InferenceScope = require("./registry/").InferenceScope; var System = require("./registry/system.js"); var Annotations = require("./../../type-system/annotation.js"); var walk = require('estraverse'); var Tools = require("../settools.js"); var Shade = require("../../interfaces.js"); var walkes = require('walkes'); var validator = require('../validator'); var TypeInfo = require("../../type-system/typeinfo.js").TypeInfo; // shortcuts var Syntax = common.Syntax; var Set = worklist.Set; var FunctionAnnotation = Annotations.FunctionAnnotation; var ANNO = Annotations.ANNO; function findConstantsFor(ast, names, constantVariables) { var result = new Set(), annotation, name, formerValue; constantVariables = constantVariables ? constantVariables.values() : []; walkes(ast, { AssignmentExpression: function(recurse) { if (this.left.type != Syntax.Identifier) { Shade.throwError(ast, "Can't find constant for computed left expression"); } name = this.left.name; if(names.has(name)) { annotation = ANNO(this.right); if(annotation.hasConstantValue()) { switch(this.operator) { case "=": result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)}); break; case "-=": case "+=": case "*=": case "/=": formerValue = constantVariables.filter(function(v){ return v.name == name; }); if(formerValue.length) { var c = formerValue[0].constant, v; switch(this.operator) { case "+=": v = c + TypeInfo.copyStaticValue(annotation); break; case "-=": v = c - TypeInfo.copyStaticValue(annotation); break; case "*=": v = c * TypeInfo.copyStaticValue(annotation); break; case "/=": v = c / TypeInfo.copyStaticValue(annotation); break; } result.add({ name: name, constant: v}); } break; default: assert(!this.operator); } } } recurse(this.right); }, VariableDeclarator: function(recurse) { name = this.id.name; if (this.init && names.has(name)) { annotation = ANNO(this.init); if(annotation.hasConstantValue()) { result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)}); } } recurse(this.init); }, UpdateExpression: function(recurse) { if(this.argument.type == Syntax.Identifier) { name = this.argument.name; annotation = ANNO(this); if(annotation.hasConstantValue()) { var value = TypeInfo.copyStaticValue(annotation); if (!this.prefix) { value = this.operator == "--" ? --value : ++value; } result.add({ name: name, constant: value}); } } } }); return result; } /** * * @param ast * @param {AnalysisContext} context * @param {*} opt * @constructor */ var TypeInference = function (ast, context, opt) { opt = opt || {}; this.context = context; this.propagateConstants = opt.propagateConstants || false; }; Base.extend(TypeInference.prototype, { /** * @param {*} ast * @param {*} opt * @returns {*} */ inferBody: function (ast, opt) { var cfg = esgraph(ast, { omitExceptions: true }), context = this.context, propagateConstants = this.propagateConstants; //console.log("infer body", cfg) var result = worklist(cfg, /** * @param {Set} input * @this {FlowNode} * @returns {*} */ function (input) { if (!this.astNode || this.type) // Start and end node do not influence the result return input; //console.log("Analyze", codegen.generate(this.astNode), this.astNode.type); // Local if(propagateConstants) { this.kill = this.kill || Tools.findVariableAssignments(this.astNode, true); } annotateRight(context, this.astNode, propagateConstants ? input : null ); this.decl = this.decl || context.declare(this.astNode); //context.computeConstants(this.astNode, input); if(!propagateConstants) { return input; } var filteredInput = null, generate = null; if (this.kill.size) { // Only if there's an assignment, we need to generate generate = findConstantsFor(this.astNode, this.kill, propagateConstants ? input : null); var that = this; filteredInput = new Set(input.filter(function (elem) { return !that.kill.some(function(tokill) { return elem.name == tokill }); })); } var result = Set.union(filteredInput || input, generate); // console.log("input:", input); // console.log("kill:", this.kill); // console.log("generate:", generate); // console.log("filteredInput:", filteredInput); // console.log("result:", result); return result; } , { direction: 'forward', merge: worklist.merge(function(a,b) { if (!a && !b) return null; //console.log("Merge", a && a.values(), b && b.values()) var result = Set.intersect(a, b); //console.log("Result", result && result.values()) return result; }) }); //Tools.printMap(result, cfg); return ast; } }); /** * * @param ast * @param {AnalysisContext} context * @param opt * @returns {*} */ var inferProgram = function (ast, context, opt) { opt = opt || {}; //var globalScope = createGlobalScope(ast); //registerSystemInformation(globalScope, opt); var typeInference = new TypeInference(ast, context, opt); var result = typeInference.inferBody(ast, opt); return result; }; ns.infer = inferProgram; }(exports));
xml3d/shade.js
src/analyze/typeinference/typeinference.js
JavaScript
mit
8,226
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import { toggleSelect } from '../actions/users'; import { createLink } from '../../utils'; class User extends Component { render() { const profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'bigger') : ''; const small_profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'mini') : ''; var description = this.props.user.description; if(description) { description = description.replace(/@[A-Za-z_0-9]+/g, id => createLink(`https://twitter.com/${id.substring(1)}`, id)); this.props.user.entities.description.urls.forEach(url => description = description.replace(new RegExp(url.url, 'g'), createLink(url.expanded_url, url.expanded_url))); } return this.props.settings.showMode === 'card' ? ( <li className={'responsive-card ' + (this.props.user.select ? 'responsive-card--selected' : '')}> <input type="checkbox" checked={this.props.user.select} className="user__select" onChange={this.props.toggleSelect} /> <div alt="" className="card-img-top" style={{ backgroundImage: this.props.user.profile_banner_url ? `url(${this.props.user.profile_banner_url + '/600x200'})` : 'none', backgroundColor: !this.props.user.profile_banner_url ? `#${this.props.user.profile_link_color}` : 'transparent' }} onClick={this.props.toggleSelect}></div> <div className="card-block"> <div className="media"> <div className="media-left"> <img src={profile_image_url_https} width="73" height="73" className="media-left__icon" /> </div> <div className="media-body"> <div className="card-title"> <div className="card-title__name"> {this.props.user.name} </div> <div className="card-title__screen-name"> <small> <a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new" title={this.props.user.id_str}>@{this.props.user.screen_name}</a> {this.props.user.protected ? ( <span> &nbsp;<i className="fa fa-lock"></i> </span> ) : null} </small> </div> </div> </div> </div> </div> <ul className="list-group list-group-flush"> { this.props.user.entities && this.props.user.entities.url ? ( <li className="list-group-item"> <a href={this.props.user.entities.url.urls[0].url} target="_new"> <i className="fa fa-link fa-fw"></i> {this.props.user.entities.url.urls[0].expanded_url ? this.props.user.entities.url.urls[0].expanded_url : this.props.user.entities.url.urls[0].url}</a> </li> ) : null } { this.props.user.location ? ( <li className="list-group-item"> <i className="fa fa-map-marker fa-fw"></i> {this.props.user.location} </li> ) : null } </ul> {this.props.user.entities && !this.props.user.entities.url && !this.props.user.location ? <hr /> : null} <div className="card-block"> <p className="card-text" dangerouslySetInnerHTML={{__html: description}}> </p> </div> </li> ) : ( <tr onClick={e => { if(['A', 'INPUT'].includes(e.target.tagName)) { e.stopPropagation(); } else { this.props.toggleSelect(); } }}> <td className="user-list-table__checkbox user-list-table__checkbox--row"> <input type="checkbox" checked={this.props.user.select} onChange={this.props.toggleSelect} /> </td> <td className="user-list-table__name user-list-table__name--row"><img src={small_profile_image_url_https} width="24" height="24" /> {this.props.user.name}</td> <td> <a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new">{this.props.user.screen_name}</a> {this.props.user.protected ? ( <span> &nbsp;<i className="fa fa-lock"></i> </span> ) : null} </td> <td>{this.props.user.friends_count}</td> <td>{this.props.user.followers_count}</td> <td>{this.props.user.status ? moment(new Date(this.props.user.status.created_at)).format('YYYY/MM/DD HH:mm:ss') : null}</td> </tr> ); } } User.propTypes = { userId: PropTypes.string.isRequired, user: PropTypes.object.isRequired, settings: PropTypes.object.isRequired }; User.defaultProps = { userId: '0', user: {}, settings: {} }; function mapStateToProps(state, ownProps) { return { user: state.users.users.allUserInfo[ownProps.userId], settings: state.settings }; } function mapDispatchToProps(dispatch, ownProps) { return { toggleSelect() { dispatch(toggleSelect(ownProps.userId)); } }; } export default connect(mapStateToProps, mapDispatchToProps)(User);
sunya9/follow-manager
src/containers/User.js
JavaScript
mit
5,320
/*** * Textile parser for JavaScript * * Copyright (c) 2012 Borgar Þorsteinsson (MIT License). * */ /*jshint laxcomma:true laxbreak:true eqnull:true loopfunc:true sub:true */ ;(function(){ "use strict"; /*** * Regular Expression helper methods * * This provides the `re` object, which contains several helper * methods for working with big regular expressions (soup). * */ var re = { _cache: {} , pattern: { 'punct': "[!-/:-@\\[\\\\\\]-`{-~]" , 'space': '\\s' } , escape: function ( src ) { return src.replace( /[\-\[\]\{\}\(\)\*\+\?\.\,\\\^\$\|\#\s]/g, "\\$&" ); } , collapse: function ( src ) { return src.replace( /(?:#.*?(?:\n|$))/g, '' ) .replace( /\s+/g, '' ) ; } , expand_patterns: function ( src ) { // TODO: provide escape for patterns: \[:pattern:] ? return src.replace( /\[\:\s*(\w+)\s*\:\]/g, function ( m, k ) { return ( k in re.pattern ) ? re.expand_patterns( re.pattern[ k ] ) : k ; }) ; } , isRegExp: function ( r ) { return Object.prototype.toString.call( r ) === "[object RegExp]"; } , compile: function ( src, flags ) { if ( re.isRegExp( src ) ) { if ( arguments.length === 1 ) { // no flags arg provided, use the RegExp one flags = ( src.global ? 'g' : '' ) + ( src.ignoreCase ? 'i' : '' ) + ( src.multiline ? 'm' : '' ); } src = src.source; } // don't do the same thing twice var ckey = src + ( flags || '' ); if ( ckey in re._cache ) { return re._cache[ ckey ]; } // allow classes var rx = re.expand_patterns( src ); // allow verbose expressions if ( flags && /x/.test( flags ) ) { rx = re.collapse( rx ); } // allow dotall expressions if ( flags && /s/.test( flags ) ) { rx = rx.replace( /([^\\])\./g, '$1[^\\0]' ); } // TODO: test if MSIE and add replace \s with [\s\u00a0] if it is? // clean flags and output new regexp flags = ( flags || '' ).replace( /[^gim]/g, '' ); return ( re._cache[ ckey ] = new RegExp( rx, flags ) ); } }; /*** * JSONML helper methods - http://www.jsonml.org/ * * This provides the `JSONML` object, which contains helper * methods for rendering JSONML to HTML. * * Note that the tag ! is taken to mean comment, this is however * not specified in the JSONML spec. * */ var JSONML = { escape: function ( text, esc_quotes ) { return text.replace( /&(?!(#\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});)/g, "&amp;" ) .replace( /</g, "&lt;" ) .replace( />/g, "&gt;" ) .replace( /"/g, esc_quotes ? "&quot;" : '"' ) .replace( /'/g, esc_quotes ? "&#39;" : "'" ) ; } , toHTML: function ( jsonml ) { jsonml = jsonml.concat(); // basic case if ( typeof jsonml === "string" ) { return JSONML.escape( jsonml ); } var tag = jsonml.shift() , attributes = {} , content = [] , tag_attrs = "" , a ; if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !_isArray( jsonml[ 0 ] ) ) { attributes = jsonml.shift(); } while ( jsonml.length ) { content.push( JSONML.toHTML( jsonml.shift() ) ); } for ( a in attributes ) { tag_attrs += ( attributes[ a ] == null ) ? " " + a : " " + a + '="' + JSONML.escape( String( attributes[ a ] ), true ) + '"' ; } // be careful about adding whitespace here for inline elements if ( tag == "!" ) { return "<!--" + content.join( "" ) + "-->"; } else if ( tag === "img" || tag === "br" || tag === "hr" || tag === "input" ) { return "<" + tag + tag_attrs + " />"; } else { return "<" + tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">"; } } }; // merge object b properties into obect a function merge ( a, b ) { for ( var k in b ) { a[ k ] = b[ k ]; } return a; } var _isArray = Array.isArray || function ( a ) { return Object.prototype.toString.call(a) === '[object Array]'; }; /* expressions */ re.pattern[ 'blocks' ] = '(?:b[qc]|div|notextile|pre|h[1-6]|fn\\d+|p|###)'; re.pattern[ 'pba_class' ] = '\\([^\\)]+\\)'; re.pattern[ 'pba_style' ] = '\\{[^\\}]+\\}'; re.pattern[ 'pba_lang' ] = '\\[[^\\[\\]]+\\]'; re.pattern[ 'pba_align' ] = '(?:<>|<|>|=)'; re.pattern[ 'pba_pad' ] = '[\\(\\)]+'; re.pattern[ 'pba_attr' ] = '(?:[:pba_class:]|[:pba_style:]|[:pba_lang:]|[:pba_align:]|[:pba_pad:])*'; re.pattern[ 'url_punct' ] = '[.,«»″‹›!?]'; re.pattern[ 'html_id' ] = '[a-zA-Z][a-zA-Z\\d:]*'; re.pattern[ 'html_attr' ] = '(?:"[^"]+"|\'[^\']+\'|[^>\\s]+)'; re.pattern[ 'tx_urlch' ] = '[\\w"$\\-_.+!*\'(),";\\/?:@=&%#{}|\\\\^~\\[\\]`]'; re.pattern[ 'tx_cite' ] = ':((?:[^\\s()]|\\([^\\s()]+\\)|[()])+?)(?=[!-\\.:-@\\[\\\\\\]-`{-~]+(?:$|\\s)|$|\\s)'; re.pattern[ 'listhd' ] = '[\\t ]*[\\#\\*]*(\\*|\\#(?:_|\\d+)?)[:pba_attr:](?: \\S|\\.\\s*(?=\\S|\\n))'; re.pattern[ 'ucaps' ] = "A-Z"+ // Latin extended À-Þ "\u00c0-\u00d6\u00d8-\u00de"+ // Latin caps with embelishments and ligatures... "\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f"+ "\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178\u0179\u017b\u017d"+ "\u0181\u0182\u0184\u0186\u0187\u0189-\u018b\u018e-\u0191\u0193\u0194\u0196-\u0198\u019c\u019d\u019f\u01a0\u01a2\u01a4\u01a6\u01a7\u01a9\u01ac\u01ae\u01af\u01b1-\u01b3\u01b5\u01b7\u01b8\u01bc"+ "\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe"+ "\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a\u023b\u023d\u023e"+ "\u0241\u0243-\u0246\u0248\u024a\u024c\u024e"+ "\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40"+ "\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e"+ "\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe"+ "\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe"+ "\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e\u2c7f"+ "\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e"+ "\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d\ua77e"+ "\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa"; var re_block = re.compile( /^([:blocks:])/ ) , re_block_se = re.compile( /^[:blocks:]$/ ) , re_block_normal = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n(?:\s*\n|$)+)/, 's' ) , re_block_extended = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n+(?=[:blocks:][:pba_attr:]\.))/, 's' ) , re_ruler = /^(\-\-\-+|\*\*\*+|___+)(\r?\n\s+|$)/ , re_list = re.compile( /^((?:[:listhd:][^\0]*?(?:\r?\n|$))+)(\s*\n|$)/,'s' ) , re_list_item = re.compile( /^([\#\*]+)([^\0]+?)(\n(?=[:listhd:])|$)/, 's' ) , re_deflist = /^((?:- (?:[^\n]\n?)+?)+:=(?: *\n[^\0]+?=:(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- )))))+/ , re_deflist_item = /^((?:- (?:[^\n]\n?)+?)+):=( *\n[^\0]+?=:\s*(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- ))))/ , re_table = re.compile( /^((?:table[:pba_attr:]\.\n)?(?:(?:[:pba_attr:]\.[^\n\S]*)?\|.*?\|[^\n\S]*(?:\n|$))+)([^\n\S]*\n)?/, 's' ) , re_table_head = /^table(_?)([^\n]+)\.\s?\n/ , re_table_row = re.compile( /^([:pba_attr:]\.[^\n\S]*)?\|(.*?)\|[^\n\S]*(\n|$)/, 's' ) , re_fenced_phrase = /^\[(__?|\*\*?|\?\?|[\-\+\^~@%])([^\n]+)\1\]/ , re_phrase = /^([\[\{]?)(__?|\*\*?|\?\?|[\-\+\^~@%])/ , re_text = re.compile( /^.+?(?=[\\<!\[_\*`]|\n|$)/, 's' ) , re_image = re.compile( /^!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?/ ) , re_image_fenced = re.compile( /^\[!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?\]/ ) // NB: there is an exception in here to prevent matching "TM)" , re_caps = re.compile( /^((?!TM\)|tm\))[[:ucaps:]](?:[[:ucaps:]\d]{1,}(?=\()|[[:ucaps:]\d]{2,}))(?:\((.*?)\))?(?=\W|$)/ ) , re_link = re.compile( /^"(?!\s)((?:[^\n"]|"(?![\s:])[^\n"]+"(?!:))+)"[:tx_cite:]/ ) , re_link_fenced = /^\["([^\n]+?)":((?:\[[a-z0-9]*\]|[^\]])+)\]/ , re_link_ref = re.compile( /^\[([^\]]+)\]((?:https?:\/\/|\/)\S+)(?:\s*\n|$)/ ) , re_link_title = /\s*\(((?:\([^\(\)]*\)|[^\(\)])+)\)$/ , re_footnote_def = /^fn\d+$/ , re_footnote = /^\[(\d+)(\!?)\]/ // HTML , re_html_tag_block = re.compile( /^\s*<([:html_id:](?::[a-zA-Z\d]+)*)((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ ) , re_html_tag = re.compile( /^<([:html_id:])((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ ) , re_html_comment = re.compile( /^<!--(.+?)-->/, 's' ) , re_html_end_tag = re.compile( /^<\/([:html_id:])([^>]*)>/ ) , re_html_attr = re.compile( /^\s*([^=\s]+)(?:\s*=\s*("[^"]+"|'[^']+'|[^>\s]+))?/ ) , re_entity = /&(#\d\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});/ // glyphs , re_dimsign = /([\d\.,]+['"]? ?)x( ?)(?=[\d\.,]['"]?)/g , re_emdash = /(^|[\s\w])--([\s\w]|$)/g , re_trademark = /(\b ?|\s|^)(?:\((?:TM|tm)\)|\[(?:TM|tm)\])/g , re_registered = /(\b ?|\s|^)(?:\(R\)|\[R\])/gi , re_copyright = /(\b ?|\s|^)(?:\(C\)|\[C\])/gi , re_apostrophe = /(\w)\'(\w)/g , re_double_prime = re.compile( /(\d*[\.,]?\d+)"(?=\s|$|[:punct:])/g ) , re_single_prime = re.compile( /(\d*[\.,]?\d+)'(?=\s|$|[:punct:])/g ) , re_closing_dquote = re.compile( /([^\s\[\(])"(?=$|\s|[:punct:])/g ) , re_closing_squote = re.compile( /([^\s\[\(])'(?=$|\s|[:punct:])/g ) // pba , re_pba_classid = /^\(([^\(\)\n]+)\)/ , re_pba_padding_l = /^(\(+)/ , re_pba_padding_r = /^(\)+)/ , re_pba_align_blk = /^(<>|<|>|=)/ , re_pba_align_img = /^(<|>|=)/ , re_pba_valign = /^(~|\^|\-)/ , re_pba_colspan = /^\\(\d+)/ , re_pba_rowspan = /^\/(\d+)/ , re_pba_styles = /^\{([^\}]*)\}/ , re_pba_css = /^\s*([^:\s]+)\s*:\s*(.+)\s*$/ , re_pba_lang = /^\[([^\[\]\n]+)\]/ ; var phrase_convert = { '*': 'strong' , '**': 'b' , '??': 'cite' , '_': 'em' , '__': 'i' , '-': 'del' , '%': 'span' , '+': 'ins' , '~': 'sub' , '^': 'sup' , '@': 'code' }; // area, base, basefont, bgsound, br, col, command, embed, frame, hr, // img, input, keygen, link, meta, param, source, track or wbr var html_singletons = { 'br': 1 , 'hr': 1 , 'img': 1 , 'link': 1 , 'meta': 1 , 'wbr': 1 , 'area': 1 , 'param': 1 , 'input': 1 , 'option': 1 , 'base': 1 }; var pba_align_lookup = { '<': 'left' , '=': 'center' , '>': 'right' , '<>': 'justify' }; var pba_valign_lookup = { '~':'bottom' , '^':'top' , '-':'middle' }; // HTML tags allowed in the document (root) level that trigger HTML parsing var allowed_blocktags = { 'p': 0 , 'hr': 0 , 'ul': 1 , 'ol': 0 , 'li': 0 , 'div': 1 , 'pre': 0 , 'object': 1 , 'script': 0 , 'noscript': 0 , 'blockquote': 1 , 'notextile': 1 }; function ribbon ( feed ) { var _slot = null , org = feed + '' , pos = 0 ; return { save: function () { _slot = pos; } , load: function () { pos = _slot; feed = org.slice( pos ); } , advance: function ( n ) { pos += ( typeof n === 'string' ) ? n.length : n; return ( feed = org.slice( pos ) ); } , lookbehind: function ( nchars ) { nchars = nchars == null ? 1 : nchars; return org.slice( pos - nchars, pos ); } , startsWith: function ( s ) { return feed.substring(0, s.length) === s; } , valueOf: function(){ return feed; } , toString: function(){ return feed; } }; } function builder ( arr ) { var _arr = _isArray( arr ) ? arr : []; return { add: function ( node ) { if ( typeof node === 'string' && typeof _arr[_arr.length - 1 ] === 'string' ) { // join if possible _arr[ _arr.length - 1 ] += node; } else if ( _isArray( node ) ) { var f = node.filter(function(s){ return s !== undefined; }); _arr.push( f ); } else if ( node ) { _arr.push( node ); } return this; } , merge: function ( s ) { for (var i=0,l=s.length; i<l; i++) { this.add( s[i] ); } return this; } , linebreak: function () { if ( _arr.length ) { this.add( '\n' ); } } , get: function () { return _arr; } }; } function copy_pba ( s, blacklist ) { if ( !s ) { return undefined; } var k, d = {}; for ( k in s ) { if ( k in s && ( !blacklist || !(k in blacklist) ) ) { d[ k ] = s[ k ]; } } return d; } function parse_html_attr ( attr ) { // parse ATTR and add to element var _attr = {} , m , val ; while ( (m = re_html_attr.exec( attr )) ) { _attr[ m[1] ] = ( typeof m[2] === 'string' ) ? m[2].replace( /^(["'])(.*)\1$/, '$2' ) : null ; attr = attr.slice( m[0].length ); } return _attr; } // This "indesciminately" parses HTML text into a list of JSON-ML element // No steps are taken however to prevent things like <table><p><td> - user can still create nonsensical but "well-formed" markup function parse_html ( src, whitelist_tags ) { var org = src + '' , list = [] , root = list , _stack = [] , m , oktag = whitelist_tags ? function ( tag ) { return tag in whitelist_tags; } : function () { return true; } , tag ; src = (typeof src === 'string') ? ribbon( src ) : src; // loop do { if ( (m = re_html_comment.exec( src )) && oktag('!') ) { src.advance( m[0] ); list.push( [ '!', m[1] ] ); } // end tag else if ( (m = re_html_end_tag.exec( src )) && oktag(m[1]) ) { tag = m[1]; var junk = m[2]; if ( _stack.length ) { for (var i=_stack.length-1; i>=0; i--) { var head = _stack[i]; if ( head[0] === tag ) { _stack.splice( i ); list = _stack[ _stack.length - 1 ] || root; break; } } } src.advance( m[0] ); } // open/void tag else if ( (m = re_html_tag.exec( src )) && oktag(m[1]) ) { src.advance( m[0] ); tag = m[1]; var single = m[3] || m[1] in html_singletons , tail = m[4] , element = [ tag ] ; // attributes if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); } // tag if ( single ) { // single tag // let us add the element and continue our quest... list.push( element ); if ( tail ) { list.push( tail ); } } else { // open tag if ( tail ) { element.push( tail ); } // TODO: some things auto close other things: <td>, <li>, <p>, <table> // if ( tag === 'p' && _stack.length ) { // var seek = /^(p)$/; // for (var i=_stack.length-1; i>=0; i--) { // var head = _stack[i]; // if ( seek.test( head[0] ) /* === tag */ ) { // //src.advance( m[0] ); // _stack.splice( i ); // list = _stack[i] || root; // } // } // } // TODO: some elements can move parser into "text" mode // style, xmp, iframe, noembed, noframe, textarea, title, script, noscript, plaintext //if ( /^(script)$/.test( tag ) ) { } _stack.push( element ); list.push( element ); list = element; } } else { // no match, move by all "uninteresting" chars m = /([^<]+|[^\0])/.exec( src ); if ( m ) { list.push( m[0] ); } src.advance( m ? m[0].length || 1 : 1 ); } } while ( src.valueOf() ); return root; } /* attribute parser */ function parse_attr ( input, element, end_token ) { /* The attr bit causes massive problems for span elements when parentheses are used. Parentheses are a total mess and, unsurprisingly, cause trip-ups: RC: `_{display:block}(span) span (span)_` -> `<em style="display:block;" class="span">(span) span (span)</em>` PHP: `_{display:block}(span) span (span)_` -> `<em style="display:block;">(span) span (span)</em>` PHP and RC seem to mostly solve this by not parsing a final attr parens on spans if the following character is a non-space. I've duplicated that: Class/ID is not matched on spans if it is followed by `end_token` or <space>. Lang is not matched here if it is followed by the end token. Theoretically I could limit the lang attribute to /^\[[a-z]{2+}(\-[a-zA-Z0-9]+)*\]/ because Textile is layered on top of HTML which only accepts valid BCP 47 language tags, but who knows what atrocities are being preformed out there in the real world. So this attempts to emulate the other libraries. */ input += ''; if ( !input || element === 'notextile' ) { return undefined; } var m , st = {} , o = { 'style': st } , remaining = input , is_block = element === 'table' || element === 'td' || re_block_se.test( element ) // "in" test would be better but what about fn#.? , is_img = element === 'img' , is_list = element === 'li' , is_phrase = !is_block && !is_img && element !== 'a' , re_pba_align = ( is_img ) ? re_pba_align_img : re_pba_align_blk ; do { if ( (m = re_pba_styles.exec( remaining )) ) { m[1].split(';').forEach(function(p){ var d = p.match( re_pba_css ); if ( d ) { st[ d[1] ] = d[2]; } }); remaining = remaining.slice( m[0].length ); continue; } if ( (m = re_pba_lang.exec( remaining )) ) { var rm = remaining.slice( m[0].length ); if ( ( !rm && is_phrase ) || ( end_token && end_token === rm.slice(0,end_token.length) ) ) { m = null; } else { o['lang'] = m[1]; remaining = remaining.slice( m[0].length ); } continue; } if ( (m = re_pba_classid.exec( remaining )) ) { var rm = remaining.slice( m[0].length ); if ( ( !rm && is_phrase ) || ( end_token && (rm[0] === ' ' || end_token === rm.slice(0,end_token.length)) ) ) { m = null; } else { var bits = m[1].split( '#' ); if ( bits[0] ) { o['class'] = bits[0]; } if ( bits[1] ) { o['id'] = bits[1]; } remaining = rm; } continue; } if ( is_block || is_list ) { if ( (m = re_pba_padding_l.exec( remaining )) ) { st[ "padding-left" ] = ( m[1].length ) + "em"; remaining = remaining.slice( m[0].length ); continue; } if ( (m = re_pba_padding_r.exec( remaining )) ) { st[ "padding-right" ] = ( m[1].length ) + "em"; remaining = remaining.slice( m[0].length ); continue; } } // only for blocks: if ( is_img || is_block || is_list ) { if ( (m = re_pba_align.exec( remaining )) ) { var align = pba_align_lookup[ m[1] ]; if ( is_img ) { o[ 'align' ] = align; } else { st[ 'text-align' ] = align; } remaining = remaining.slice( m[0].length ); continue; } } // only for table cells if ( element === 'td' || element === 'tr' ) { if ( (m = re_pba_valign.exec( remaining )) ) { st[ "vertical-align" ] = pba_valign_lookup[ m[1] ]; remaining = remaining.slice( m[0].length ); continue; } } if ( element === 'td' ) { if ( (m = re_pba_colspan.exec( remaining )) ) { o[ "colspan" ] = m[1]; remaining = remaining.slice( m[0].length ); continue; } if ( (m = re_pba_rowspan.exec( remaining )) ) { o[ "rowspan" ] = m[1]; remaining = remaining.slice( m[0].length ); continue; } } } while ( m ); // collapse styles var s = []; for ( var v in st ) { s.push( v + ':' + st[v] ); } if ( s.length ) { o.style = s.join(';'); } else { delete o.style; } return remaining == input ? undefined : [ input.length - remaining.length, o ] ; } /* glyph parser */ function parse_glyphs ( src ) { if ( typeof src !== 'string' ) { return src; } // NB: order is important here ... return src // arrow .replace( /([^\-]|^)->/, '$1&#8594;' ) // arrow // dimensions .replace( re_dimsign, '$1&#215;$2' ) // dimension sign // ellipsis .replace( /([^.]?)\.{3}/g, '$1&#8230;' ) // ellipsis // dashes .replace( re_emdash, '$1&#8212;$2' ) // em dash .replace( / - /g, ' &#8211; ' ) // en dash // legal marks .replace( re_trademark, '$1&#8482;' ) // trademark .replace( re_registered, '$1&#174;' ) // registered .replace( re_copyright, '$1&#169;' ) // copyright // double quotes .replace( re_double_prime, '$1&#8243;' ) // double prime .replace( re_closing_dquote, '$1&#8221;' ) // double closing quote .replace( /"/g, '&#8220;' ) // double opening quote // single quotes .replace( re_single_prime, '$1&#8242;' ) // single prime .replace( re_apostrophe, '$1&#8217;$2' ) // I'm an apostrophe .replace( re_closing_squote, '$1&#8217;' ) // single closing quote .replace( /'/g, '&#8216;' ) // fractions and degrees .replace( /[\(\[]1\/4[\]\)]/, '&#188;' ) .replace( /[\(\[]1\/2[\]\)]/, '&#189;' ) .replace( /[\(\[]3\/4[\]\)]/, '&#190;' ) .replace( /[\(\[]o[\]\)]/, '&#176;' ) .replace( /[\(\[]\+\/\-[\]\)]/, '&#177;' ) ; } /* list parser */ function list_pad ( n ) { var s = '\n'; while ( n-- ) { s += '\t'; } return s; } function parse_list ( src, options ) { src = ribbon( src.replace( /(^|\r?\n)[\t ]+/, '$1' ) ); var stack = [] , curr_idx = {} , last_idx = options._lst || {} , list_pba , item_index = 0 , m , n , s ; while ( (m = re_list_item.exec( src )) ) { var item = [ 'li' ] , start_index = 0 , dest_level = m[1].length , type = m[1].substr(-1) === '#' ? 'ol' : 'ul' , new_li = null , lst , par , pba , r ; // list starts and continuations if ( n = /^(_|\d+)/.exec( m[2] ) ) { item_index = isFinite( n[1] ) ? parseInt( n[1], 10 ) : last_idx[ dest_level ] || curr_idx[ dest_level ] || 1; m[2] = m[2].slice( n[1].length ); } if ( pba = parse_attr( m[2], 'li' ) ) { m[2] = m[2].slice( pba[0] ); pba = pba[1]; } // list control if ( /^\.\s*$/.test( m[2] ) ) { list_pba = pba || {}; src.advance( m[0] ); continue; } // create nesting until we have correct level while ( stack.length < dest_level ) { // list always has an attribute object, this simplifies first-pba resolution lst = [ type, {}, list_pad( stack.length + 1 ), (new_li = [ 'li' ]) ]; par = stack[ stack.length - 1 ]; if ( par ) { par.li.push( list_pad( stack.length ) ); par.li.push( lst ); } stack.push({ ul: lst , li: new_li , att: 0 // count pba's found per list }); curr_idx[ stack.length ] = 1; } // remove nesting until we have correct level while ( stack.length > dest_level ) { r = stack.pop(); r.ul.push( list_pad( stack.length ) ); // lists have a predictable structure - move pba from listitem to list if ( r.att === 1 && !r.ul[3][1].substr ) { merge( r.ul[1], r.ul[3].splice( 1, 1 )[ 0 ] ); } } // parent list par = stack[ stack.length - 1 ]; // have list_pba or start_index? if ( item_index ) { par.ul[1].start = curr_idx[ dest_level ] = item_index; item_index = 0; // falsy prevents this from fireing until it is set again } if ( list_pba ) { par.att = 9; // "more than 1" prevent pba transfers on list close merge( par.ul[1], list_pba ); list_pba = null; } if ( !new_li ) { par.ul.push( list_pad( stack.length ), item ); par.li = item; } if ( pba ) { par.li.push( pba ); par.att++; } Array.prototype.push.apply( par.li, parse_inline( m[2].trim(), options ) ); src.advance( m[0] ); curr_idx[ dest_level ] = (curr_idx[ dest_level ] || 0) + 1; } // remember indexes for continuations next time options._lst = curr_idx; while ( stack.length ) { s = stack.pop(); s.ul.push( list_pad( stack.length ) ); // lists have a predictable structure - move pba from listitem to list if ( s.att === 1 && !s.ul[3][1].substr ) { merge( s.ul[1], s.ul[3].splice( 1, 1 )[ 0 ] ); } } return s.ul; } /* definitions list parser */ function parse_deflist ( src, options ) { src = ribbon( src.trim() ); var deflist = [ 'dl', '\n' ] , terms , def , m ; while ( (m = re_deflist_item.exec( src )) ) { // add terms terms = m[1].split( /(?:^|\n)\- / ).slice(1); while ( terms.length ) { deflist.push( '\t' , [ 'dt' ].concat( parse_inline( terms.shift().trim(), options ) ) , '\n' ); } // add definitions def = m[2].trim(); deflist.push( '\t' , [ 'dd' ].concat( /=:$/.test( def ) ? parse_blocks( def.slice(0,-2).trim(), options ) : parse_inline( def, options ) ) , '\n' ); src.advance( m[0] ); } return deflist; } /* table parser */ function parse_table ( src, options ) { src = ribbon( src.trim() ); var table = [ 'table' ] , row , inner , pba , more , m ; if ( (m = re_table_head.exec( src )) ) { // parse and apply table attr src.advance( m[0] ); pba = parse_attr( m[2], 'table' ); if ( pba ) { table.push( pba[1] ); } } while ( (m = re_table_row.exec( src )) ) { row = [ 'tr' ]; if ( m[1] && (pba = parse_attr( m[1], 'tr' )) ) { // FIXME: requires "\.\s?" -- else what ? row.push( pba[1] ); } table.push( '\n\t', row ); inner = ribbon( m[2] ); do { inner.save(); // cell loop var th = inner.startsWith( '_' ) , cell = [ th ? 'th' : 'td' ] ; if ( th ) { inner.advance( 1 ); } pba = parse_attr( inner, 'td' ); if ( pba ) { inner.advance( pba[0] ); cell.push( pba[1] ); // FIXME: don't do this if next text fails } if ( pba || th ) { var d = /^\.\s*/.exec( inner ); if ( d ) { inner.advance( d[0] ); } else { cell = [ 'td' ]; inner.load(); } } var mx = /^(==.*?==|[^\|])*/.exec( inner ); cell = cell.concat( parse_inline( mx[0], options ) ); row.push( '\n\t\t', cell ); more = inner.valueOf().charAt( mx[0].length ) === '|'; inner.advance( mx[0].length + 1 ); } while ( more ); row.push( '\n\t' ); src.advance( m[0] ); } table.push( '\n' ); return table; } /* inline parser */ function parse_inline ( src, options ) { src = ribbon( src ); var list = builder() , m , pba ; // loop do { src.save(); // linebreak -- having this first keeps it from messing to much with other phrases if ( src.startsWith( '\r\n' ) ) { src.advance( 1 ); // skip cartridge returns } if ( src.startsWith( '\n' ) ) { src.advance( 1 ); if ( options.breaks ) { list.add( [ 'br' ] ); } list.add( '\n' ); continue; } // inline notextile if ( (m = /^==(.*?)==/.exec( src )) ) { src.advance( m[0] ); list.add( m[1] ); continue; } // lookbehind => /([\s>.,"'?!;:])$/ var behind = src.lookbehind( 1 ); var boundary = !behind || /^[\s>.,"'?!;:()]$/.test( behind ); // FIXME: need to test right boundary for phrases as well if ( (m = re_phrase.exec( src )) && ( boundary || m[1] ) ) { src.advance( m[0] ); var tok = m[2] , fence = m[1] , phrase_type = phrase_convert[ tok ] , code = phrase_type === 'code' ; if ( (pba = !code && parse_attr( src, phrase_type, tok )) ) { src.advance( pba[0] ); pba = pba[1]; } // FIXME: if we can't match the fence on the end, we should output fence-prefix as normal text // seek end var m_mid; var m_end; if ( fence === '[' ) { m_mid = '^(.*?)'; m_end = '(?:])'; } else if ( fence === '{' ) { m_mid = '^(.*?)'; m_end = '(?:})'; } else { var t1 = re.escape( tok.charAt(0) ); m_mid = ( code ) ? '^(\\S+|\\S+.*?\\S)' : '^([^\\s' + t1 + ']+|[^\\s' + t1 + '].*?\\S('+t1+'*))' ; m_end = '(?=$|[\\s.,"\'!?;:()«»„“”‚‘’])'; } var rx = re.compile( m_mid + '(' + re.escape( tok ) + ')' + m_end ); if ( (m = rx.exec( src )) && m[1] ) { src.advance( m[0] ); if ( code ) { list.add( [ phrase_type, m[1] ] ); } else { list.add( [ phrase_type, pba ].concat( parse_inline( m[1], options ) ) ); } continue; } // else src.load(); } // image if ( (m = re_image.exec( src )) || (m = re_image_fenced.exec( src )) ) { src.advance( m[0] ); pba = m[1] && parse_attr( m[1], 'img' ); var attr = pba ? pba[1] : { 'src':'' } , img = [ 'img', attr ] ; attr.src = m[2]; attr.alt = m[3] ? ( attr.title = m[3] ) : ''; if ( m[4] ) { // +cite causes image to be wraped with a link (or link_ref)? // TODO: support link_ref for image cite img = [ 'a', { 'href': m[4] }, img ]; } list.add( img ); continue; } // html comment if ( (m = re_html_comment.exec( src )) ) { src.advance( m[0] ); list.add( [ '!', m[1] ] ); continue; } // html tag // TODO: this seems to have a lot of overlap with block tags... DRY? if ( (m = re_html_tag.exec( src )) ) { src.advance( m[0] ); var tag = m[1] , single = m[3] || m[1] in html_singletons , element = [ tag ] , tail = m[4] ; if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); } if ( single ) { // single tag list.add( element ).add( tail ); continue; } else { // need terminator // gulp up the rest of this block... var re_end_tag = re.compile( "^(.*?)(</" + tag + "\\s*>)", 's' ); if ( (m = re_end_tag.exec( src )) ) { src.advance( m[0] ); if ( tag === 'code' ) { element.push( tail, m[1] ); } else if ( tag === 'notextile' ) { list.merge( parse_inline( m[1], options ) ); continue; } else { element = element.concat( parse_inline( m[1], options ) ); } list.add( element ); continue; } // end tag is missing, treat tag as normal text... } src.load(); } // footnote if ( (m = re_footnote.exec( src )) && /\S/.test( behind ) ) { src.advance( m[0] ); list.add( [ 'sup', { 'class': 'footnote', 'id': 'fnr' + m[1] }, ( m[2] === '!' ? m[1] // "!" suppresses the link : [ 'a', { href: '#fn' + m[1] }, m[1] ] ) ] ); continue; } // caps / abbr if ( (m = re_caps.exec( src )) ) { src.advance( m[0] ); var caps = [ 'span', { 'class': 'caps' }, m[1] ]; if ( m[2] ) { caps = [ 'acronym', { 'title': m[2] }, caps ]; // FIXME: use <abbr>, not acronym! } list.add( caps ); continue; } // links if ( (boundary && (m = re_link.exec( src ))) || (m = re_link_fenced.exec( src )) ) { src.advance( m[0].length ); var title = m[1].match( re_link_title ) , inner = ( title ) ? m[1].slice( 0, m[1].length - title[0].length ) : m[1] ; if ( (pba = parse_attr( inner, 'a' )) ) { inner = inner.slice( pba[0] ); pba = pba[1]; } else { pba = {}; } if ( title && !inner ) { inner = title[0]; title = ""; } pba.href = m[2]; if ( title ) { pba.title = title[1]; } list.add( [ 'a', pba ].concat( parse_inline( inner.replace( /^(\.?\s*)/, '' ), options ) ) ); continue; } // no match, move by all "uninteresting" chars m = /([a-zA-Z0-9,.':]+|[ \f\r\t\v\xA0\u2028\u2029]+|[^\0])/.exec( src ); if ( m ) { list.add( m[0] ); } src.advance( m ? m[0].length || 1 : 1 ); } while ( src.valueOf() ); return list.get().map( parse_glyphs ); } /* block parser */ function parse_blocks ( src, options ) { var list = builder() , paragraph = function ( s, tag, pba, linebreak ) { tag = tag || 'p'; var out = []; s.split( /(?:\r?\n){2,}/ ).forEach(function( bit, i ) { if ( tag === 'p' && /^\s/.test( bit ) ) { // no-paragraphs // WTF?: Why does Textile not allow linebreaks in spaced lines bit = bit.replace( /\r?\n[\t ]/g, ' ' ).trim(); out = out.concat( parse_inline( bit, options ) ); } else { if ( linebreak && i ) { out.push( linebreak ); } out.push( pba ? [ tag, pba ].concat( parse_inline( bit, options ) ) : [ tag ].concat( parse_inline( bit, options ) ) ); } }); return out; } , link_refs = {} , m ; src = ribbon( src.replace( /^( *\r?\n)+/, '' ) ); // loop while ( src.valueOf() ) { src.save(); // link_ref -- this goes first because it shouldn't trigger a linebreak if ( (m = re_link_ref.exec( src )) ) { src.advance( m[0] ); link_refs[ m[1] ] = m[2]; continue; } // add linebreak list.linebreak(); // named block if ( (m = re_block.exec( src )) ) { src.advance( m[0] ); var block_type = m[0] , pba = parse_attr( src, block_type ) ; if ( pba ) { src.advance( pba[0] ); pba = pba[1]; } if ( (m = /^\.(\.?)(?:\s|(?=:))/.exec( src )) ) { // FIXME: this whole copy_pba seems rather strange? // slurp rest of block var extended = !!m[1]; m = ( extended ? re_block_extended : re_block_normal ).exec( src.advance( m[0] ) ); src.advance( m[0] ); // bq | bc | notextile | pre | h# | fn# | p | ### if ( block_type === 'bq' ) { var cite, inner = m[1]; if ( (m = /^:(\S+)\s+/.exec( inner )) ) { if ( !pba ) { pba = {}; } pba.cite = m[1]; inner = inner.slice( m[0].length ); } // RedCloth adds all attr to both: this is bad because it produces duplicate IDs list.add( [ 'blockquote', pba, '\n' ].concat( paragraph( inner, 'p', copy_pba(pba, { 'cite':1, 'id':1 }), '\n' ) ).concat(['\n']) ); } else if ( block_type === 'bc' ) { var sub_pba = ( pba ) ? copy_pba(pba, { 'id':1 }) : null; list.add( [ 'pre', pba, ( sub_pba ? [ 'code', sub_pba, m[1] ] : [ 'code', m[1] ] ) ] ); } else if ( block_type === 'notextile' ) { list.merge( parse_html( m[1] ) ); } else if ( block_type === '###' ) { // ignore the insides } else if ( block_type === 'pre' ) { // I disagree with RedCloth, but agree with PHP here: // "pre(foo#bar).. line1\n\nline2" prevents multiline preformat blocks // ...which seems like the whole point of having an extended pre block? list.add( [ 'pre', pba, m[1] ] ); } else if ( re_footnote_def.test( block_type ) ) { // footnote // Need to be careful: RedCloth fails "fn1(foo#m). footnote" -- it confuses the ID var fnid = block_type.replace( /\D+/g, '' ); if ( !pba ) { pba = {}; } pba['class'] = ( pba['class'] ? pba['class'] + ' ' : '' ) + 'footnote'; pba['id'] = 'fn' + fnid; list.add( [ "p", pba, [ 'a', { 'href': '#fnr' + fnid }, [ 'sup', fnid ] ], ' ' ].concat( parse_inline( m[1], options ) ) ); } else { // heading | paragraph list.merge( paragraph( m[1], block_type, pba, '\n' ) ); } continue; } else { src.load(); } } // HTML comment if ( (m = re_html_comment.exec( src )) ) { src.advance( m[0] + (/(?:\s*\n+)+/.exec( src ) || [])[0] ); list.add( [ '!', m[1] ] ); continue; } // block HTML if ( (m = re_html_tag_block.exec( src )) ) { var tag = m[1] , single = m[3] || tag in html_singletons , tail = m[4] ; // Unsurprisingly, all Textile implementations I have tested have trouble parsing simple HTML: // // "<div>a\n<div>b\n</div>c\n</div>d" // // I simply match them here as there is no way anyone is using nested HTML today, or if they // are, then this will at least output less broken HTML as redundant tags will get quoted. // Is block tag? ... if ( tag in allowed_blocktags ) { src.advance( m[0] ); var element = [ tag ]; if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); } if ( single ) { // single tag // let us add the element and continue our quest... list.add( element ); continue; } else { // block // gulp up the rest of this block... var re_end_tag = re.compile( "^(.*?)(\\s*)(</" + tag + "\\s*>)(\\s*)", 's' ); if ( (m = re_end_tag.exec( src )) ) { src.advance( m[0] ); if ( tag === 'pre' ) { element.push( tail ); element = element.concat( parse_html( m[1].replace( /(\r?\n)+$/, '' ), { 'code': 1 } ) ); if ( m[2] ) { element.push( m[2] ); } list.add( element ); } else if ( tag === 'notextile' ) { element = parse_html( m[1].trim() ); list.merge( element ); } else if ( tag === 'script' || tag === 'noscript' ) { //element = parse_html( m[1].trim() ); element.push( tail + m[1] ); list.add( element ); } else { // These strange (and unnecessary) linebreak tests are here to get the // tests working perfectly. In reality, this doesn't matter one bit. if ( /\n/.test( tail ) ) { element.push( '\n' ); } if ( /\n/.test( m[1] ) ) { element = element.concat( parse_blocks( m[1], options ) ); } else { element = element.concat( parse_inline( m[1].replace( /^ +/, '' ), options ) ); } if ( /\n/.test( m[2] ) ) { element.push( '\n' ); } list.add( element ); } continue; } /*else { // end tag is missing, treat tag as normal text... }*/ } } src.load(); } // ruler if ( (m = re_ruler.exec( src )) ) { src.advance( m[0] ); list.add( [ 'hr' ] ); continue; } // list if ( (m = re_list.exec( src )) ) { src.advance( m[0] ); list.add( parse_list( m[0], options ) ); continue; } // definition list if ( (m = re_deflist.exec( src )) ) { src.advance( m[0] ); list.add( parse_deflist( m[0], options ) ); continue; } // table if ( (m = re_table.exec( src )) ) { src.advance( m[0] ); list.add( parse_table( m[1], options ) ); continue; } // paragraph m = re_block_normal.exec( src ); list.merge( paragraph( m[1], 'p', undefined, "\n" ) ); src.advance( m[0] ); } return list.get().map( fix_links, link_refs ); } // recurse the tree and swap out any "href" attributes function fix_links ( jsonml ) { if ( _isArray( jsonml ) ) { if ( jsonml[0] === 'a' ) { // found a link var attr = jsonml[1]; if ( typeof attr === "object" && 'href' in attr && attr.href in this ) { attr.href = this[ attr.href ]; } } for (var i=1,l=jsonml.length; i<l; i++) { if ( _isArray( jsonml[i] ) ) { fix_links.call( this, jsonml[i] ); } } } return jsonml; } /* exposed */ function textile ( txt, opt ) { // get a throw-away copy of options opt = merge( merge( {}, textile.defaults ), opt || {} ); // run the converter return parse_blocks( txt, opt ).map( JSONML.toHTML ).join( '' ); } // options textile.defaults = { 'breaks': true // single-line linebreaks are converted to <br> by default }; textile.setOptions = textile.setoptions = function ( opt ) { merge( textile.defaults, opt ); return this; }; textile.parse = textile.convert = textile; textile.html_parser = parse_html; textile.jsonml = function ( txt, opt ) { // get a throw-away copy of options opt = merge( merge( {}, textile.defaults ), opt || {} ); // parse and return tree return [ 'html' ].concat( parse_blocks( txt, opt ) ); }; textile.serialize = JSONML.toHTML; if ( typeof module !== 'undefined' && module.exports ) { module.exports = textile; } else { this.textile = textile; } }).call(function() { return this || (typeof window !== 'undefined' ? window : global); }());
muffinmad/atom-textile-preview
lib/textile.js
JavaScript
mit
45,902
/*! Copyright 2011, Ben Lin (http://dreamerslab.com/) * Licensed under the MIT License (LICENSE.txt). * * Version: 1.0.0 * * Requires: jQuery 1.2.3+ */ $.preload = function(){ var tmp = [], i = arguments.length; // reverse loop run faster for( ; i-- ; ) tmp.push( $( '<img />' ).attr( 'src', arguments[ i ] )); };
dreamerslab/ci.view
example_site/assets/js/lib/jquery.preload.js
JavaScript
mit
320
/*jshint indent: 4, browser:true*/ /*global L*/ /* * L.TimeDimension.Player */ //'use strict'; L.TimeDimension.Player = (L.Layer || L.Class).extend({ includes: (L.Evented || L.Mixin.Events), initialize: function(options, timeDimension) { L.setOptions(this, options); this._timeDimension = timeDimension; this._paused = false; this._buffer = this.options.buffer || 5; this._minBufferReady = this.options.minBufferReady || 1; this._waitingForBuffer = false; this._loop = this.options.loop || false; this._steps = 1; this._timeDimension.on('timeload', (function(data) { this.release(); // free clock this._waitingForBuffer = false; // reset buffer }).bind(this)); this.setTransitionTime(this.options.transitionTime || 1000); this._timeDimension.on('limitschanged availabletimeschanged timeload', (function(data) { this._timeDimension.prepareNextTimes(this._steps, this._minBufferReady, this._loop); }).bind(this)); }, _tick: function() { var maxIndex = this._getMaxIndex(); var maxForward = (this._timeDimension.getCurrentTimeIndex() >= maxIndex) && (this._steps > 0); var maxBackward = (this._timeDimension.getCurrentTimeIndex() == 0) && (this._steps < 0); if (maxForward || maxBackward) { // we reached the last step if (!this._loop) { this.pause(); this.stop(); this.fire('animationfinished'); return; } } if (this._paused) { return; } var numberNextTimesReady = 0, buffer = this._bufferSize; if (this._minBufferReady > 0) { numberNextTimesReady = this._timeDimension.getNumberNextTimesReady(this._steps, buffer, this._loop); // If the player was waiting, check if all times are loaded if (this._waitingForBuffer) { if (numberNextTimesReady < buffer) { console.log('Waiting until buffer is loaded. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } else { // all times loaded console.log('Buffer is fully loaded!'); this.fire('running'); this._waitingForBuffer = false; } } else { // check if player has to stop to wait and force to full all the buffer if (numberNextTimesReady < this._minBufferReady) { console.log('Force wait for load buffer. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this._waitingForBuffer = true; this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } } } this.pause(); this._timeDimension.nextTime(this._steps, this._loop); if (buffer > 0) { this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); } }, _getMaxIndex: function(){ return Math.min(this._timeDimension.getAvailableTimes().length - 1, this._timeDimension.getUpperLimitIndex() || Infinity); }, start: function(numSteps) { if (this._intervalID) return; this._steps = numSteps || 1; this._waitingForBuffer = false; var startedOver = false; if (this.options.startOver){ if (this._timeDimension.getCurrentTimeIndex() === this._getMaxIndex()){ this._timeDimension.setCurrentTimeIndex(this._timeDimension.getLowerLimitIndex() || 0); startedOver = true; } } this.release(); this._intervalID = window.setInterval( L.bind(this._tick, this), this._transitionTime); if (!startedOver) this._tick(); this.fire('play'); this.fire('running'); }, stop: function() { if (!this._intervalID) return; clearInterval(this._intervalID); this._intervalID = null; this._waitingForBuffer = false; this.fire('stop'); }, pause: function() { this._paused = true; }, release: function () { this._paused = false; }, getTransitionTime: function() { return this._transitionTime; }, isPlaying: function() { return this._intervalID ? true : false; }, isWaiting: function() { return this._waitingForBuffer; }, isLooped: function() { return this._loop; }, setLooped: function(looped) { this._loop = looped; this.fire('loopchange', { loop: looped }); }, setTransitionTime: function(transitionTime) { this._transitionTime = transitionTime; if (typeof this._buffer === 'function') { this._bufferSize = this._buffer.call(this, this._transitionTime, this._minBufferReady, this._loop); console.log('Buffer size changed to ' + this._bufferSize); } else { this._bufferSize = this._buffer; } if (this._intervalID) { this.stop(); this.start(this._steps); } this.fire('speedchange', { transitionTime: transitionTime, buffer: this._bufferSize }); }, getSteps: function() { return this._steps; } });
geofbaum/geofbaum.github.io
src/leaflet.timedimension.player.js
JavaScript
mit
5,914
'use strict'; angular.module('mean.settings').config(['$stateProvider', function($stateProvider) { var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/'); } }); return deferred.promise; }; $stateProvider.state('settings', { url: '/settings', templateUrl: 'settings/views/index.html', resolve: { loggedin: checkLoggedin } }); } ]);
indie-hackathon/dchat
packages/custom/settings/public/routes/settings.js
JavaScript
mit
787
import PropTypes from 'prop-types' import React from 'react' import block from 'bem-cn-lite' import { Field, reduxForm } from 'redux-form' import { compose } from 'underscore' import { connect } from 'react-redux' import { renderTextInput } from '../text_input' import { renderCheckboxInput } from '../checkbox_input' import { signUp, updateAuthFormStateAndClearError } from '../../client/actions' import { GDPRMessage } from 'desktop/components/react/gdpr/GDPRCheckbox' function validate(values) { const { accepted_terms_of_service, email, name, password } = values const errors = {} if (!name) errors.name = 'Required' if (!email) errors.email = 'Required' if (!password) errors.password = 'Required' if (!accepted_terms_of_service) errors.accepted_terms_of_service = 'Please agree to our terms to continue' return errors } function SignUp(props) { const { error, handleSubmit, isLoading, signUpAction, updateAuthFormStateAndClearErrorAction, } = props const b = block('consignments-submission-sign-up') return ( <div className={b()}> <div className={b('title')}>Create an Account</div> <div className={b('subtitle')}> Already have an account?{' '} <span className={b('clickable')} onClick={() => updateAuthFormStateAndClearErrorAction('logIn')} > Log in </span>. </div> <form className={b('form')} onSubmit={handleSubmit(signUpAction)}> <div className={b('row')}> <div className={b('row-item')}> <Field name="name" component={renderTextInput} item={'name'} label={'Full Name'} autofocus /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="email" component={renderTextInput} item={'email'} label={'Email'} type={'email'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="password" component={renderTextInput} item={'password'} label={'Password'} type={'password'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="accepted_terms_of_service" component={renderCheckboxInput} item={'accepted_terms_of_service'} label={<GDPRMessage />} value={false} /> </div> </div> <button className={b .builder()('sign-up-button') .mix('avant-garde-button-black')()} type="submit" > {isLoading ? <div className="loading-spinner-white" /> : 'Submit'} </button> {error && <div className={b('error')}>{error}</div>} </form> </div> ) } const mapStateToProps = state => { return { error: state.submissionFlow.error, isLoading: state.submissionFlow.isLoading, } } const mapDispatchToProps = { signUpAction: signUp, updateAuthFormStateAndClearErrorAction: updateAuthFormStateAndClearError, } SignUp.propTypes = { error: PropTypes.string, handleSubmit: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, signUpAction: PropTypes.func.isRequired, updateAuthFormStateAndClearErrorAction: PropTypes.func.isRequired, } export default compose( reduxForm({ form: 'signUp', // a unique identifier for this form validate, }), connect(mapStateToProps, mapDispatchToProps) )(SignUp)
kanaabe/force
src/desktop/apps/consign/components/sign_up/index.js
JavaScript
mit
3,781
TF.listen();
rivers/tabfusion
src/listener.js
JavaScript
mit
13
$(document).ready(function() { $(document).on('submit', '.status-button', function(e) { e.preventDefault(); var joinButton = e.target $.ajax(joinButton.action, { method: 'PATCH', data: $(this).serialize() }) .done(function(data) { gameDiv = $(joinButton).parent(); gameDiv.replaceWith(data); }) .fail(function() { alert("Failure!"); }); }); });
nyc-dragonflies-2015/whos_got_next
app/assets/javascripts/players.js
JavaScript
mit
412
function OrganizationController() { // injetando dependência 'ngInject'; // ViewModel const vm = this; console.log('OrganizationController'); } export default { name: 'OrganizationController', fn: OrganizationController };
dnaloco/digitala
app/erp/js/controllers/human-resource/organiz.js
JavaScript
mit
242
import React, { Component } from 'react'; import Header from './Header'; import MainSection from './MainSection'; export default class App extends Component { render() { return ( <div> <Header/> <MainSection/> </div> ); } }
loggur/react-redux-provide
examples/todomvc/components/App.js
JavaScript
mit
265
version https://git-lfs.github.com/spec/v1 oid sha256:641860132ccb9772e708b19feb3d59bb6291f6c40eebbfcfa0982a4e8eeda219 size 69639
yogeshsaroya/new-cdnjs
ajax/libs/holder/2.5.0/holder.js
JavaScript
mit
130
(function(global) { var vwl = {}; var receivePoster; var receiveEntry; var receiveLoadedList; // vwl.init - advertise VWL info and register for VWL messages // // Parameters: // left - (optional) url of this world's initial left entry image // right - (optional) url of this world's initial right entry image // receivePosterFunc - (optional) function to handle poster images from other // worlds // receiveEntryFunc - (optional) function to handle entry images from other // worlds // recevieLoadedListFunc - (optional) function to handle list of loaded worlds vwl.init = function(left, right, receivePosterFunc, receiveEntryFunc, receiveLoadedListFunc) { receivePoster = receivePosterFunc; receiveEntry = receiveEntryFunc; receiveLoadedList = receiveLoadedListFunc; receiveEntry && window.addEventListener('message', function(message) { if (message.source != window || message.origin != window.location.origin) return; if (message.data.tabInfo) { var left = null; var right = null; if (message.data.tabInfo.info && message.data.tabInfo.info.entry_image) { left = message.data.tabInfo.info.entry_image.left_src; right = message.data.tabInfo.info.entry_image.right_src; } receiveEntry(message.data.tabInfo.url, message.data.tabInfo.loaded, left, right); } if (message.data.loadedList !== undefined) { receiveLoadedList(message.data.loadedList); } }, false); window.postMessage({info:{entry_image:{ left_src:left, right_src:right}}}, '*'); } // vwl.getInfo - get info (entry image and poster image) on a specific world // // Parameters: // url - url of worlds to get info on // getPoster - (optional) if true get the poster image vwl.getInfo = function(url, getPoster) { if (receivePoster && getPoster) { var request = new XMLHttpRequest(); var dir = url.substr(0, url.lastIndexOf('/') + 1); request.open('GET', dir + 'vwl_info.json'); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var poster = JSON.parse(request.responseText).poster_image; receivePoster(url, poster.left_src ? dir + poster.left_src : null, poster.right_src ? dir + poster.right_src : null, poster._2d_src ? dir + poster._2d_src : null); } else { receivePoster(url); } } request.send(null); } receiveEntry && window.postMessage({getInfo:url}, '*'); } // vwl.getLoadedList - get the list of loaded worlds vwl.getLoadedList = function() { window.postMessage({getLoadedList:true}, '*'); } // vwl.open - load world // // Parameters: // url - url of world to open vwl.open = function(url) { window.postMessage({open:url}, '*'); } // vwl.navigate - navigate to a world // // Parameters: // left - (optional) new left entry image for current world // right - (optional) new right entry image for current world // url - url of world to navigate to vwl.navigate = function(left, right, url) { var message = {navigate:url}; if (left && right) { message.info = {entry_image:{left_src:left, right_src:right}}; } window.postMessage(message, '*'); } global.vwl = vwl; }) (window);
BigRobCoder/VirtualWorldLink
lib/vwl.js
JavaScript
mit
3,364
// These two object contain information about the state of Ebl var GlobalState = Base.extend({ constructor: function() { this.isAdmin = false; this.authToken = null; this.docTitle = null; this.container = null; // default config this.config = { template: 'default', language: 'en', postsPerPage: 5, pageTitleFormat: "{ebl_title} | {doc_title}", // callbacks onBlogLoaded: null, onPostOpened: null, onPageChanged: null }; } }); var LocalState = Base.extend({ constructor: function() { this.page = 0; this.post = null; this.editors = null; } }); var PostStatus = { NEW: 0, DRAFT: 1, PUBLISHED: 2, parse: function (s) { if (s.toLowerCase() == "new") return 0; if (s.toLowerCase() == "draft") return 1; if (s.toLowerCase() == "published") return 2; return null; } }; var gState = new GlobalState(); // state shared among the entire session var lState = new LocalState(); // state of the current view
alessandrofrancesconi/ebl
ebl/core/js_src/state/state.js
JavaScript
mit
1,178
import React from 'react' import { Container, Group, TabBar, Icon, Badge, amStyles, } from 'amazeui-touch' import {Link} from 'react-router' class App extends React.Component{ propsType ={ children:React.PropTypes.node } render(){ let { location, params, children, ...props } = this.props; let transition = children.props.transition || 'sfr' return ( <Container direction="column"> <Container transition={transition} > {children} </Container> <TabBar > <TabBar.Item component={Link} eventKey = 'home' active = {location.pathname === '/'} icon = 'home' title = '首页' to='/' /> <TabBar.Item component={Link} active={location.pathname === '/class'} eventKey="class" icon="list" title="课程" to='/class' /> <TabBar.Item active={location.pathname === '/search'} eventKey="search" icon="search" title="发现" /> <TabBar.Item component={Link} active={location.pathname === '/me'} eventKey="person" icon="person" title="我" to='/me' /> </TabBar> </Container> ) } } export default App
yiweimatou/yiweimatou-mobile
src/components/pages/app.js
JavaScript
mit
1,961
/* * unstrap v1.1.3 * https://unstrap.org * 2015-2020 * MIT license */ const version = '1.1.3', collection = {}; function extendUnstrap (v) { var list; if (!collection[v].selectors) { collection[v].selectors = ['.' + collection[v].name]; } collection[v].selectors.forEach(function (sel) { list = document.querySelectorAll(sel); for (var i = 0; i < list.length; i++) { collection[v].extend && collection[v].extend(list.item(i)); } }) } function init () { var observer = new MutationObserver(function (mut) { mut.forEach(function (m) { var n = m.addedNodes, f; for (var i=0; i<n.length; i++) { var c = n.item(i).classList; if (c) { for (var j = 0; j < c.length; j++) { if (f = collection[c.item(j)]) { f.extend && f.extend(n.item(i)); } } } } }); }); Object.keys(collection).forEach(function (v) { extendUnstrap(v); }) observer.observe(document.body, {childList: true, subtree: true}); } function register (...components) { components.forEach((component) => { if (component.name) { collection[component.name] = component; } }) } function unregister (...components) { components.forEach((component) => { delete collection[component.name]; }) } function list () { return Object.keys(collection).sort(); } window.onload = init; export default { version, register, unregister, list }
unstrap/unstrap
unstrap.js
JavaScript
mit
1,620
'use strict'; const toBytes = s => [...s].map(c => c.charCodeAt(0)); const xpiZipFilename = toBytes('META-INF/mozilla.rsa'); const oxmlContentTypes = toBytes('[Content_Types].xml'); const oxmlRels = toBytes('_rels/.rels'); const fileType = input => { const buf = input instanceof Uint8Array ? input : new Uint8Array(input); if (!(buf && buf.length > 1)) { return null; } const check = (header, options) => { options = Object.assign({ offset: 0 }, options); for (let i = 0; i < header.length; i++) { // If a bitmask is set if (options.mask) { // If header doesn't equal `buf` with bits masked off if (header[i] !== (options.mask[i] & buf[i + options.offset])) { return false; } } else if (header[i] !== buf[i + options.offset]) { return false; } } return true; }; const checkString = (header, options) => check(toBytes(header), options); if (check([0xFF, 0xD8, 0xFF])) { return { ext: 'jpg', mime: 'image/jpeg' }; } if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) { return { ext: 'png', mime: 'image/png' }; } if (check([0x47, 0x49, 0x46])) { return { ext: 'gif', mime: 'image/gif' }; } if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) { return { ext: 'webp', mime: 'image/webp' }; } if (check([0x46, 0x4C, 0x49, 0x46])) { return { ext: 'flif', mime: 'image/flif' }; } // Needs to be before `tif` check if ( (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {offset: 8}) ) { return { ext: 'cr2', mime: 'image/x-canon-cr2' }; } if ( check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A]) ) { return { ext: 'tif', mime: 'image/tiff' }; } if (check([0x42, 0x4D])) { return { ext: 'bmp', mime: 'image/bmp' }; } if (check([0x49, 0x49, 0xBC])) { return { ext: 'jxr', mime: 'image/vnd.ms-photo' }; } if (check([0x38, 0x42, 0x50, 0x53])) { return { ext: 'psd', mime: 'image/vnd.adobe.photoshop' }; } // Zip-based file formats // Need to be before the `zip` check if (check([0x50, 0x4B, 0x3, 0x4])) { if ( check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30}) ) { return { ext: 'epub', mime: 'application/epub+zip' }; } // Assumes signed `.xpi` from addons.mozilla.org if (check(xpiZipFilename, {offset: 30})) { return { ext: 'xpi', mime: 'application/x-xpinstall' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) { return { ext: 'odt', mime: 'application/vnd.oasis.opendocument.text' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) { return { ext: 'ods', mime: 'application/vnd.oasis.opendocument.spreadsheet' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) { return { ext: 'odp', mime: 'application/vnd.oasis.opendocument.presentation' }; } // https://github.com/file/file/blob/master/magic/Magdir/msooxml if (check(oxmlContentTypes, {offset: 30}) || check(oxmlRels, {offset: 30})) { const sliced = buf.subarray(4, 4 + 2000); const nextZipHeaderIndex = arr => arr.findIndex((el, i, arr) => arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4); const header2Pos = nextZipHeaderIndex(sliced); if (header2Pos !== -1) { const slicedAgain = buf.subarray(header2Pos + 8, header2Pos + 8 + 1000); const header3Pos = nextZipHeaderIndex(slicedAgain); if (header3Pos !== -1) { const offset = 8 + header2Pos + header3Pos + 30; if (checkString('word/', {offset})) { return { ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }; } if (checkString('ppt/', {offset})) { return { ext: 'pptx', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }; } if (checkString('xl/', {offset})) { return { ext: 'xlsx', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }; } } } } } if ( check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8) ) { return { ext: 'zip', mime: 'application/zip' }; } if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) { return { ext: 'tar', mime: 'application/x-tar' }; } if ( check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1) ) { return { ext: 'rar', mime: 'application/x-rar-compressed' }; } if (check([0x1F, 0x8B, 0x8])) { return { ext: 'gz', mime: 'application/gzip' }; } if (check([0x42, 0x5A, 0x68])) { return { ext: 'bz2', mime: 'application/x-bzip2' }; } if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) { return { ext: '7z', mime: 'application/x-7z-compressed' }; } if (check([0x78, 0x01])) { return { ext: 'dmg', mime: 'application/x-apple-diskimage' }; } if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5 ( check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) && ( check([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41 check([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42 check([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM check([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2 check([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4 check([0x4D, 0x34, 0x56], {offset: 8}) || // M4V check([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH ) )) { return { ext: 'mp4', mime: 'video/mp4' }; } if (check([0x4D, 0x54, 0x68, 0x64])) { return { ext: 'mid', mime: 'audio/midi' }; } // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska if (check([0x1A, 0x45, 0xDF, 0xA3])) { const sliced = buf.subarray(4, 4 + 4096); const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82); if (idPos !== -1) { const docTypePos = idPos + 3; const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0)); if (findDocType('matroska')) { return { ext: 'mkv', mime: 'video/x-matroska' }; } if (findDocType('webm')) { return { ext: 'webm', mime: 'video/webm' }; } } } if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {offset: 4}) || check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) || check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG check([0x77, 0x69, 0x64, 0x65], {offset: 4})) { return { ext: 'mov', mime: 'video/quicktime' }; } // RIFF file format which might be AVI, WAV, QCP, etc if (check([0x52, 0x49, 0x46, 0x46])) { if (check([0x41, 0x56, 0x49], {offset: 8})) { return { ext: 'avi', mime: 'video/x-msvideo' }; } if (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) { return { ext: 'wav', mime: 'audio/x-wav' }; } // QLCM, QCP file if (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) { return { ext: 'qcp', mime: 'audio/qcelp' }; } } if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) { return { ext: 'wmv', mime: 'video/x-ms-wmv' }; } if ( check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3]) ) { return { ext: 'mpg', mime: 'video/mpeg' }; } if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) { return { ext: '3gp', mime: 'video/3gpp' }; } // Check for MPEG header at different starting offsets for (let start = 0; start < 2 && start < (buf.length - 16); start++) { if ( check([0x49, 0x44, 0x33], {offset: start}) || // ID3 header check([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header ) { return { ext: 'mp3', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header ) { return { ext: 'mp2', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS ) { return { ext: 'mp2', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS ) { return { ext: 'mp4', mime: 'audio/mpeg' }; } } if ( check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) || check([0x4D, 0x34, 0x41, 0x20]) ) { return { ext: 'm4a', mime: 'audio/m4a' }; } // Needs to be before `ogg` check if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) { return { ext: 'opus', mime: 'audio/opus' }; } // If 'OggS' in first bytes, then OGG container if (check([0x4F, 0x67, 0x67, 0x53])) { // This is a OGG container // If ' theora' in header. if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) { return { ext: 'ogv', mime: 'video/ogg' }; } // If '\x01video' in header. if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) { return { ext: 'ogm', mime: 'video/ogg' }; } // If ' FLAC' in header https://xiph.org/flac/faq.html if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) { return { ext: 'oga', mime: 'audio/ogg' }; } // 'Speex ' in header https://en.wikipedia.org/wiki/Speex if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) { return { ext: 'spx', mime: 'audio/ogg' }; } // If '\x01vorbis' in header if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) { return { ext: 'ogg', mime: 'audio/ogg' }; } // Default OGG container https://www.iana.org/assignments/media-types/application/ogg return { ext: 'ogx', mime: 'application/ogg' }; } if (check([0x66, 0x4C, 0x61, 0x43])) { return { ext: 'flac', mime: 'audio/x-flac' }; } if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) { return { ext: 'amr', mime: 'audio/amr' }; } if (check([0x25, 0x50, 0x44, 0x46])) { return { ext: 'pdf', mime: 'application/pdf' }; } if (check([0x4D, 0x5A])) { return { ext: 'exe', mime: 'application/x-msdownload' }; } if ( (buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {offset: 1}) ) { return { ext: 'swf', mime: 'application/x-shockwave-flash' }; } if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) { return { ext: 'rtf', mime: 'application/rtf' }; } if (check([0x00, 0x61, 0x73, 0x6D])) { return { ext: 'wasm', mime: 'application/wasm' }; } if ( check([0x77, 0x4F, 0x46, 0x46]) && ( check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) ) ) { return { ext: 'woff', mime: 'font/woff' }; } if ( check([0x77, 0x4F, 0x46, 0x32]) && ( check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) ) ) { return { ext: 'woff2', mime: 'font/woff2' }; } if ( check([0x4C, 0x50], {offset: 34}) && ( check([0x00, 0x00, 0x01], {offset: 8}) || check([0x01, 0x00, 0x02], {offset: 8}) || check([0x02, 0x00, 0x02], {offset: 8}) ) ) { return { ext: 'eot', mime: 'application/octet-stream' }; } if (check([0x00, 0x01, 0x00, 0x00, 0x00])) { return { ext: 'ttf', mime: 'font/ttf' }; } if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) { return { ext: 'otf', mime: 'font/otf' }; } if (check([0x00, 0x00, 0x01, 0x00])) { return { ext: 'ico', mime: 'image/x-icon' }; } if (check([0x00, 0x00, 0x02, 0x00])) { return { ext: 'cur', mime: 'image/x-icon' }; } if (check([0x46, 0x4C, 0x56, 0x01])) { return { ext: 'flv', mime: 'video/x-flv' }; } if (check([0x25, 0x21])) { return { ext: 'ps', mime: 'application/postscript' }; } if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) { return { ext: 'xz', mime: 'application/x-xz' }; } if (check([0x53, 0x51, 0x4C, 0x69])) { return { ext: 'sqlite', mime: 'application/x-sqlite3' }; } if (check([0x4E, 0x45, 0x53, 0x1A])) { return { ext: 'nes', mime: 'application/x-nintendo-nes-rom' }; } if (check([0x43, 0x72, 0x32, 0x34])) { return { ext: 'crx', mime: 'application/x-google-chrome-extension' }; } if ( check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28]) ) { return { ext: 'cab', mime: 'application/vnd.ms-cab-compressed' }; } // Needs to be before `ar` check if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) { return { ext: 'deb', mime: 'application/x-deb' }; } if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) { return { ext: 'ar', mime: 'application/x-unix-archive' }; } if (check([0xED, 0xAB, 0xEE, 0xDB])) { return { ext: 'rpm', mime: 'application/x-rpm' }; } if ( check([0x1F, 0xA0]) || check([0x1F, 0x9D]) ) { return { ext: 'Z', mime: 'application/x-compress' }; } if (check([0x4C, 0x5A, 0x49, 0x50])) { return { ext: 'lz', mime: 'application/x-lzip' }; } if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) { return { ext: 'msi', mime: 'application/x-msi' }; } if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) { return { ext: 'mxf', mime: 'application/mxf' }; } if (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) { return { ext: 'mts', mime: 'video/mp2t' }; } if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) { return { ext: 'blend', mime: 'application/x-blender' }; } if (check([0x42, 0x50, 0x47, 0xFB])) { return { ext: 'bpg', mime: 'image/bpg' }; } if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) { // JPEG-2000 family if (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) { return { ext: 'jp2', mime: 'image/jp2' }; } if (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) { return { ext: 'jpx', mime: 'image/jpx' }; } if (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) { return { ext: 'jpm', mime: 'image/jpm' }; } if (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) { return { ext: 'mj2', mime: 'image/mj2' }; } } if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) { return { ext: 'aif', mime: 'audio/aiff' }; } if (checkString('<?xml ')) { return { ext: 'xml', mime: 'application/xml' }; } if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) { return { ext: 'mobi', mime: 'application/x-mobipocket-ebook' }; } // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format) if (check([0x66, 0x74, 0x79, 0x70], {offset: 4})) { if (check([0x6D, 0x69, 0x66, 0x31], {offset: 8})) { return { ext: 'heic', mime: 'image/heif' }; } if (check([0x6D, 0x73, 0x66, 0x31], {offset: 8})) { return { ext: 'heic', mime: 'image/heif-sequence' }; } if (check([0x68, 0x65, 0x69, 0x63], {offset: 8}) || check([0x68, 0x65, 0x69, 0x78], {offset: 8})) { return { ext: 'heic', mime: 'image/heic' }; } if (check([0x68, 0x65, 0x76, 0x63], {offset: 8}) || check([0x68, 0x65, 0x76, 0x78], {offset: 8})) { return { ext: 'heic', mime: 'image/heic-sequence' }; } } return null; };
jmhmd/dat-lambda
client/lib/file-type.js
JavaScript
mit
15,936
let fs = require("fs"); let path = require("path"); let cp = require("child_process"); function runCommand(folder, args) { cp.spawn("npm", args, { env: process.env, cwd: folder, stdio: "inherit" }); } function getPackages(category) { let folder = path.join(__dirname, category); return fs .readdirSync(folder) .map(function(dir) { let fullPath = path.join(folder, dir); // check for a package.json file if (!fs.existsSync(path.join(fullPath, "package.json"))) { return; } return fullPath; }) .filter(function(pkg) { return pkg !== undefined; }); } function runCommandInCategory(category, args) { let pkgs = getPackages(category); pkgs.forEach(function(pkg) { runCommand(pkg, args); }); } let CATEGORIES = ["react", "vue", "svelte", "misc"]; let category = process.argv[2]; let args = process.argv.slice(3); if (category === "all") { CATEGORIES.forEach(function(c) { runCommandInCategory(c, args); }); } else { runCommandInCategory(category, args); }
pshrmn/curi
examples/updateCategory.js
JavaScript
mit
1,046
var models=require('../models/models.js'); // Autoload :id de comentarios exports.load=function (req,res,next,commentId) { models.Comment.find({ where:{ id:Number(commentId) } }).then(function (comment) { if(comment){ req.comment=comment; next(); }else{ next(new Error('No existe commentId=' +commentId)) } }).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/new exports.new=function (req,res) { res.render('comments/new.ejs',{quizid:req.params.quizId, errors:[]}); }; //POST /quizes/:quizId/comments exports.create=function (req,res) { var comment =models.Comment.build( { texto:req.body.comment.texto, QuizId:req.params.quizId, }); comment .validate() .then( function (err) { if(err){ res.render('comments/new.ejs', {comment:comment,quizid:req.params.quizId,errors:err.errors}); }else{ comment //save :guarda en DB campo texto .save() .then(function () { res.redirect('/quizes/'+req.params.quizId); }); } } ).catch(function (error) { next(error); }); }; //GET /quizes/:quizId/comments/:commentId/publish exports.publish=function (req,res) { req.comment.publicado=true; req.comment.save({fields:["publicado"]}).then( function () { res.redirect('/quizes/'+req.params.quizId); }).catch(function (error) { next(error); }); };
armero1989/quiz-2016
controllers/comment_controller.js
JavaScript
mit
1,348
import React, { PropTypes } from 'react'; import TodoItem from './TodoItem'; const TodoList = ({todos}) => ( <ul className="todo-list"> {todos.map(todo => <TodoItem key={todo.id} {...todo} /> )} </ul> ); TodoList.propTypes = { todos: PropTypes.array.isRequired } export default TodoList;
johny/react-redux-todo-app
src/components/TodoList.js
JavaScript
mit
312
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2017 Christian Boulanger License: MIT: https://opensource.org/licenses/MIT See the LICENSE file in the project's top-level directory for details. Authors: * Christian Boulanger ([email protected], @cboulanger) ************************************************************************ */ const process = require("process"); const path = require("upath"); const semver = require("semver"); const fs = qx.tool.utils.Promisify.fs; /** * Installs a package */ qx.Class.define("qx.tool.cli.commands.package.Migrate", { extend: qx.tool.cli.commands.Package, statics: { /** * Flag to prevent recursive call to process() */ migrationInProcess: false, /** * Return the Yargs configuration object * @return {{}} */ getYargsCommand: function() { return { command: "migrate", describe: "migrates the package system to a newer version.", builder: { "verbose": { alias: "v", describe: "Verbose logging" }, "quiet": { alias: "q", describe: "No output" } } }; } }, members: { /** * Announces or applies a migration * @param {Boolean} announceOnly If true, announce the migration without * applying it. */ process: async function(announceOnly=false) { const self = qx.tool.cli.commands.package.Migrate; if (self.migrationInProcess) { return; } self.migrationInProcess = true; let needFix = false; // do not call this.base(arguments) here! let pkg = qx.tool.cli.commands.Package; let cwd = process.cwd(); let migrateFiles = [ [ path.join(cwd, pkg.lockfile.filename), path.join(cwd, pkg.lockfile.legacy_filename) ], [ path.join(cwd, pkg.cache_dir), path.join(cwd, pkg.legacy_cache_dir) ], [ path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.package_cache_name), path.join(qx.tool.cli.ConfigDb.getDirectory(), pkg.legacy_package_cache_name) ] ]; if (this.checkFilesToRename(migrateFiles).length) { let replaceInFiles = [{ files: path.join(cwd, ".gitignore"), from: pkg.legacy_cache_dir + "/", to: pkg.cache_dir + "/" }]; await this.migrate(migrateFiles, replaceInFiles, announceOnly); if (announceOnly) { needFix = true; } else { if (!this.argv.quiet) { qx.tool.compiler.Console.info("Fixing path names in the lockfile..."); } this.argv.reinstall = true; await (new qx.tool.cli.commands.package.Upgrade(this.argv)).process(); } } // Migrate all manifest in a package const registryModel = qx.tool.config.Registry.getInstance(); let manifestModels =[]; if (await registryModel.exists()) { // we have a qooxdoo.json index file containing the paths of libraries in the repository await registryModel.load(); let libraries = registryModel.getLibraries(); for (let library of libraries) { manifestModels.push((new qx.tool.config.Abstract(qx.tool.config.Manifest.config)).set({baseDir: path.join(cwd, library.path)})); } } else if (fs.existsSync(qx.tool.config.Manifest.config.fileName)) { manifestModels.push(qx.tool.config.Manifest.getInstance()); } for (const manifestModel of manifestModels) { await manifestModel.set({warnOnly: true}).load(); manifestModel.setValidate(false); needFix = false; let s = ""; if (!qx.lang.Type.isArray(manifestModel.getValue("info.authors"))) { needFix = true; s += " missing info.authors\n"; } if (!semver.valid(manifestModel.getValue("info.version"))) { needFix = true; s += " missing or invalid info.version\n"; } let obj = { "info.qooxdoo-versions": null, "info.qooxdoo-range": null, "provides.type": null, "requires.qxcompiler": null, "requires.qooxdoo-sdk": null, "requires.qooxdoo-compiler": null }; if (manifestModel.keyExists(obj)) { needFix = true; s += " obsolete entry:\n"; for (let key in obj) { if (obj[key]) { s += " " + key + "\n"; } } } if (needFix) { if (announceOnly) { qx.tool.compiler.Console.warn("*** Manifest(s) need to be updated:\n" + s); } else { manifestModel .transform("info.authors", authors => { if (authors === "") { return []; } else if (qx.lang.Type.isString(authors)) { return [{name: authors}]; } else if (qx.lang.Type.isObject(authors)) { return [{ name: authors.name, email: authors.email }]; } else if (qx.lang.Type.isArray(authors)) { return authors.map(r => qx.lang.Type.isObject(r) ? { name: r.name, email: r.email } : { name: r } ); } return []; }) .transform("info.version", version => { let coerced = semver.coerce(version); if (coerced === null) { qx.tool.compiler.Console.warn(`*** Version string '${version}' could not be interpreted as semver, changing to 1.0.0`); return "1.0.0"; } return String(coerced); }) .unset("info.qooxdoo-versions") .unset("info.qooxdoo-range") .unset("provides.type") .unset("requires.qxcompiler") .unset("requires.qooxdoo-compiler") .unset("requires.qooxdoo-sdk"); await manifestModel.save(); if (!this.argv.quiet) { qx.tool.compiler.Console.info(`Updated settings in ${manifestModel.getRelativeDataPath()}.`); } } } // check framework and compiler dependencies // if none are given in the Manifest, use the present framework and compiler const compiler_version = qx.tool.compiler.Version.VERSION; const compiler_range = manifestModel.getValue("requires.@qooxdoo/compiler") || compiler_version; const framework_version = await this.getLibraryVersion(await this.getGlobalQxPath()); const framework_range = manifestModel.getValue("requires.@qooxdoo/framework") || framework_version; if ( !semver.satisfies(compiler_version, compiler_range) || !semver.satisfies(framework_version, framework_range)) { needFix = true; if (announceOnly) { qx.tool.compiler.Console.warn(`*** Mismatch between installed framework version (${framework_version}) and/or compiler version (${compiler_version}) and the declared dependencies in the Manifest.`); } else { manifestModel .setValue("requires.@qooxdoo/compiler", "^" + compiler_version) .setValue("requires.@qooxdoo/framework", "^" + framework_version); manifestModel.setWarnOnly(false); // now model should validate await manifestModel.save(); if (!this.argv.quiet) { qx.tool.compiler.Console.info(`Updated dependencies in ${manifestModel.getRelativeDataPath()}.`); } } } manifestModel.setValidate(true); } if (!announceOnly) { let compileJsonFilename = path.join(process.cwd(), "compile.json"); let replaceInFiles = [{ files: compileJsonFilename, from: "\"qx/browser\"", to: "\"@qooxdoo/qx/browser\"" }]; await this.migrate([compileJsonFilename], replaceInFiles); } let compileJsFilename = path.join(process.cwd(), "compile.js"); if (await fs.existsAsync(compileJsFilename)) { let data = await fs.readFileAsync(compileJsFilename, "utf8"); if (data.indexOf("module.exports") < 0) { qx.tool.compiler.Console.warn("*** Your compile.js appears to be missing a `module.exports` statement - please see https://git.io/fjBqU for more details"); } } self.migrationInProcess = false; if (needFix) { if (announceOnly) { qx.tool.compiler.Console.error(`*** Try executing 'qx package migrate' to apply the changes. Alternatively, upgrade or downgrade framework and/or compiler to match the library dependencies.`); process.exit(1); } qx.tool.compiler.Console.info("Migration completed."); } else if (!announceOnly && !this.argv.quiet) { qx.tool.compiler.Console.info("Everything is up-to-date. No migration necessary."); } } } });
johnspackman/qxcompiler
source/class/qx/tool/cli/commands/package/Migrate.js
JavaScript
mit
9,371
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY const daggy = require('daggy') const compose = (f, g) => x => f(g(x)) const id = x => x //===============Define Coyoneda========= // create constructor with props 'x' and 'f' // 'x' is our value, 'f' is a function const Coyoneda = daggy.tagged('x', 'f') // map composes the function Coyoneda.prototype.map = function(f) { return Coyoneda(this.x, compose(f, this.f)) } Coyoneda.prototype.lower = function() { return this.x.map(this.f) } // lift starts off Coyoneda with the 'id' function Coyoneda.lift = x => Coyoneda(x, id) //===============Map over a non-Functor - Set ========= // Set does not have a 'map' method const set = new Set([1, 1, 2, 3, 3, 4]) console.log("Set([1, 1, 2, 3, 3, 4]) : ", set) // Wrap set into Coyoneda with 'id' function const coyoResult = Coyoneda.lift(set) .map(x => x + 1) .map(x => `${x}!`) console.log( "Coyoneda.lift(set).map(x => x + 1).map(x => `${x}!`): ", coyoResult ) // equivalent to buildUpFn = coyoResult.f, ourSet = coyoResult.x const {f: builtUpFn, x: ourSet} = coyoResult console.log("builtUpFn is: ", builtUpFn, "; ourSet is: ", ourSet) ourSet .forEach(n => console.log(builtUpFn(n))) // 2! // 3! // 4! // 5! //===============Lift a functor in (Array) and achieve Loop fusion========= console.log( `Coyoneda.lift([1,2,3]).map(x => x * 2).map(x => x - 1).lower() : `, Coyoneda.lift([1,2,3]) .map(x => x * 2) .map(x => x - 1) .lower() ) // [ 1, 3, 5 ] //===============Make Any Type a Functor========= // Any object becomes a functor when placed in Coyoneda const Container = daggy.tagged('x') const tunacan = Container("tuna") const res = Coyoneda.lift(tunacan) .map(x => x.toUpperCase()) .map(x => x + '!') const {f: fn, x: can} = res console.log(fn(can.x)) // TUNA!
dmitriz/functional-examples
examples/coyoneda.js
JavaScript
mit
1,828
var map, boroughSearch = [], theaterSearch = [], museumSearch = []; /* Basemap Layers */ var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png"); var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png"); var mbTerrainReg = L.tileLayer("https://{s}.tiles.mapbox.com/v3/aj.um7z9lus/{z}/{x}/{y}.png"); var mapquestOAM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }); var mapquestHYB = L.layerGroup([L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0pml9h7/{z}/{x}/{y}.png", { maxZoom: 19, }), L.tileLayer("http://{s}.mqcdn.com/tiles/1.0.0/hyb/{z}/{x}/{y}.png", { maxZoom: 19, subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"], })]); map = L.map("map", { zoom: 5, center: [39, -95], layers: [mapquestOSM] }); /* Larger screens get expanded layer control */ if (document.body.clientWidth <= 767) { var isCollapsed = true; } else { var isCollapsed = false; } var baseLayers = { "Street Map": mapquestOSM, "Aerial Imagery": mapquestOAM, "Imagery with Streets": mapquestHYB }; var overlays = {}; var layerControl = L.control.layers(baseLayers, {}, { collapsed: isCollapsed }).addTo(map); /* Add overlay layers to map after defining layer control to preserver order */ var sidebar = L.control.sidebar("sidebar", { closeButton: true, position: "left" }).addTo(map); sidebar.toggle(); /* Highlight search box text on click */ $("#searchbox").click(function () { $(this).select(); }); /* Placeholder hack for IE */ if (navigator.appName == "Microsoft Internet Explorer") { $("input").each(function () { if ($(this).val() === "" && $(this).attr("placeholder") !== "") { $(this).val($(this).attr("placeholder")); $(this).focus(function () { if ($(this).val() === $(this).attr("placeholder")) $(this).val(""); }); $(this).blur(function () { if ($(this).val() === "") $(this).val($(this).attr("placeholder")); }); } }); } $(function(){ var popup = { init : function() { // position popup windowW = $(window).width(); $("#map").on("mousemove", function(e) { var x = e.pageX + 20; var y = e.pageY; var windowH = $(window).height(); if (y > (windowH - 100)) { var y = e.pageY - 100; } else { var y = e.pageY - 20; } $("#info").css({ "left": x, "top": y }); }); } }; popup.init(); })
availabs/transit_analyst
assets/js/main.js
JavaScript
mit
2,596
/////////////////////////////////////////////////////////////////////////// // 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", "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" }, "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", "delete": "Usuwanie", "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.13/widgets/CostAnalysis/setting/nls/pl/strings.js
JavaScript
mit
10,828
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('commentator', 'Unit | Model | commentator', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { let model = this.subject(); // let store = this.store(); assert.ok(!!model); });
morontt/zend-blog-3-backend
spa/tests/unit/models/commentator-test.js
JavaScript
mit
318
const fs = require('fs') const { normalize, resolve, join, sep } = require('path') function getAppDir () { let dir = process.cwd() while (dir.length && dir[dir.length - 1] !== sep) { if (fs.existsSync(join(dir, 'quasar.conf.js'))) { return dir } dir = normalize(join(dir, '..')) } const { fatal } = require('./helpers/logger') fatal(`Error. This command must be executed inside a Quasar v1+ project folder.`) } const appDir = getAppDir() const cliDir = resolve(__dirname, '..') const srcDir = resolve(appDir, 'src') const pwaDir = resolve(appDir, 'src-pwa') const ssrDir = resolve(appDir, 'src-ssr') const cordovaDir = resolve(appDir, 'src-cordova') const capacitorDir = resolve(appDir, 'src-capacitor') const electronDir = resolve(appDir, 'src-electron') const bexDir = resolve(appDir, 'src-bex') module.exports = { cliDir, appDir, srcDir, pwaDir, ssrDir, cordovaDir, capacitorDir, electronDir, bexDir, resolve: { cli: dir => join(cliDir, dir), app: dir => join(appDir, dir), src: dir => join(srcDir, dir), pwa: dir => join(pwaDir, dir), ssr: dir => join(ssrDir, dir), cordova: dir => join(cordovaDir, dir), capacitor: dir => join(capacitorDir, dir), electron: dir => join(electronDir, dir), bex: dir => join(bexDir, dir) } }
rstoenescu/quasar-framework
app/lib/app-paths.js
JavaScript
mit
1,321
module.exports = { testClient: 'http://localhost:8089/dist/', mochaTimeout: 10000, testLayerIds: [0], seleniumTimeouts: { script: 5000, implicit: 1000, pageLoad: 5000 } }
KlausBenndorf/guide4you
tests/config.js
JavaScript
mit
193
'use strict'; import Maths from './maths.js' import FSM from './fsm.js' import { Animation, Interpolation } from './animation.js' export { Maths, FSM, Interpolation, Animation }
InconceivableVizzini/interjs
src/inter.js
JavaScript
mit
179
// Runs the wiki on port 80 var server = require('./server'); server.run(80);
rswingler/byuwiki
server/controller/js/wiki.js
JavaScript
mit
79
var Type = require("@kaoscript/runtime").Type; module.exports = function(expect) { class Shape { constructor() { this.__ks_init(); this.__ks_cons(arguments); } __ks_init_0() { this._color = ""; } __ks_init() { Shape.prototype.__ks_init_0.call(this); } __ks_cons_0(color) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(color === void 0 || color === null) { throw new TypeError("'color' is not nullable"); } else if(!Type.isString(color)) { throw new TypeError("'color' is not of type 'String'"); } this._color = color; } __ks_cons(args) { if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } __ks_func_color_0() { return this._color; } color() { if(arguments.length === 0) { return Shape.prototype.__ks_func_color_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } __ks_func_draw_0() { return "I'm drawing a " + this._color + " rectangle."; } draw() { if(arguments.length === 0) { return Shape.prototype.__ks_func_draw_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } } Shape.prototype.__ks_cons_1 = function() { this._color = "red"; }; Shape.prototype.__ks_cons = function(args) { if(args.length === 0) { Shape.prototype.__ks_cons_1.apply(this); } else if(args.length === 1) { Shape.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } } let shape = new Shape(); expect(shape.draw()).to.equals("I'm drawing a red rectangle."); };
kaoscript/kaoscript
test/fixtures/compile/implement/implement.ctor.nseal.alias.js
JavaScript
mit
1,741
'use strict' angular .module('softvApp') .controller('ModalAddhubCtrl', function (clusterFactory, tapFactory, $rootScope, areaTecnicaFactory, $uibModalInstance, opcion, ngNotify, $state) { function init() { if (opcion.opcion === 1) { vm.blockForm2 = true; muestraColonias(); muestrarelaciones(); vm.Titulo = 'Nuevo HUB'; } else if (opcion.opcion === 2) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { console.log(); vm.blockForm2 = false; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Editar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } else if (opcion.opcion === 3) { areaTecnicaFactory.GetConHub(opcion.id, '', '', 3).then(function (data) { vm.blockForm2 = true; vm.blocksave = true; var hub = data.GetConHubResult[0]; vm.Clv_Txt = hub.Clv_txt; vm.Titulo = 'Consultar HUB - '+hub.Clv_txt; vm.Descripcion = hub.Descripcion; vm.clv_hub = hub.Clv_Sector; muestraColonias(); muestrarelaciones(); }); } } function muestraColonias() { areaTecnicaFactory.GetMuestraColoniaHub(0, 0, 0) .then(function (data) { vm.colonias = data.GetMuestraColoniaHubResult; }); } function AddSector() { if (opcion.opcion === 1) { areaTecnicaFactory.GetNueHub(0, vm.Clv_Txt, vm.Descripcion).then(function (data) { if (data.GetNueHubResult > 0) { vm.clv_hub = data.GetNueHubResult; ngNotify.set('El HUB se ha registrado correctamente ,ahora puedes agregar la relación con las colonias', 'success'); $rootScope.$broadcast('reloadlista'); vm.blockForm2 = false; vm.blocksave = true; } else { ngNotify.set('La clave del HUB ya existe', 'error'); } }); } else if (opcion.opcion === 2) { areaTecnicaFactory.GetModHub(vm.clv_hub, vm.Clv_Txt, vm.Descripcion).then(function (data) { console.log(data); ngNotify.set('El HUB se ha editado correctamente', 'success'); $rootScope.$broadcast('reloadlista'); $uibModalInstance.dismiss('cancel'); }); } } function cancel() { $uibModalInstance.dismiss('cancel'); } function validaRelacion(clv) { var count = 0; vm.RelColonias.forEach(function (item) { count += (item.IdColonia === clv) ? 1 : 0; }); return (count > 0) ? true : false; } function NuevaRelacionSecColonia() { if (validaRelacion(vm.Colonia.IdColonia) === true) { ngNotify.set('La relación HUB-COLONIA ya esta establecida', 'warn'); return; } areaTecnicaFactory.GetNueRelHubColonia(vm.clv_hub, vm.Colonia.IdColonia) .then(function (data) { muestrarelaciones(); ngNotify.set('se agrego la relación correctamente', 'success'); }); } function muestrarelaciones() { areaTecnicaFactory.GetConRelHubColonia(vm.clv_hub) .then(function (rel) { console.log(rel); vm.RelColonias = rel.GetConRelHubColoniaResult; }); } function deleterelacion(clv) { clusterFactory.GetQuitarEliminarRelClusterSector(2, vm.clv_cluster, clv).then(function (data) { ngNotify.set('Se eliminó la relación correctamente', 'success'); muestrarelaciones(); }); } var vm = this; init(); vm.cancel = cancel; vm.clv_hub = 0; vm.RelColonias = []; vm.AddSector = AddSector; vm.NuevaRelacionSecColonia = NuevaRelacionSecColonia; });
alesabas/Softv
app/scripts/controllers/areatecnica/ModalAddhubCtrl.js
JavaScript
mit
3,930
'use strict'; var path = require('path'); var fs = require('fs'); module.exports = function(gen,cb) { var sections; if (gen.config.get('framework')==='bigwheel') { var model = require(path.join(process.cwd(),'src/model/index.js')); sections = ['Preloader']; Object.keys(model).forEach(function(key) { if (key.charAt(0)==="/") sections.push(key.substr(1) || 'Landing'); }); } else { sections = ['Landing']; } nextSection(sections,gen,cb); }; function nextSection(arr,gen,cb) { if (arr.length>0) { createSection(arr.shift(),gen,function() { nextSection(arr,gen,cb); }); } else { if (cb) cb(); } } function createSection(cur,gen,cb) { var name = gen.config.get('sectionNames') ? '{{section}}.js' : 'index.js'; var style = gen.config.get('sectionNames') ? '{{section}}.{{css}}' : 'style.{{css}}'; var count = 0; var total = 0; var done = function() { count++; if (count>=total) cb(); }; fs.stat('src/sections/'+cur+'/',function(err,stat) { if (err) { gen.config.set('section',cur); if (gen.config.get('framework')==='bigwheel') { var type = cur==='Preloader' ? 'preloader' : 'normal'; gen.copy('templates/sections/{{framework}}/'+type+'/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/'+type+'/style.css','src/sections/{{section}}/'+style,done); gen.copy('templates/sections/{{framework}}/'+type+'/template.hbs','src/sections/{{section}}/template.hbs',done); gen.copy('templates/.gitkeep','src/ui/{{section}}/.gitkeep',done); total += 4; } else if (gen.config.get('framework')==='react') { gen.copy('templates/sections/{{framework}}/index.js','src/sections/{{section}}/'+name,done); gen.copy('templates/sections/{{framework}}/style.css','src/sections/{{section}}/'+style,done); total += 2; } } else { done(); } }); };
Jam3/generator-jam3
lib/createSections.js
JavaScript
mit
1,958
'use strict'; describe('Controller: MainCtrl', function () { // load the controller's module beforeEach(module('pillzApp')); var MainCtrl, scope, $httpBackend; // Initialize the controller and a mock scope beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('/api/awesomeThings') .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']); scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings).toBeUndefined(); $httpBackend.flush(); expect(scope.awesomeThings.length).toBe(4); }); });
captDaylight/pillz
test/client/spec/controllers/main.js
JavaScript
mit
769
'use strict'; var assert = require('power-assert'); var resetStorage = require('./'); var dbName = 'test-item'; describe('#localStorage', function () { beforeEach(function (done) { localStorage.clear(); done(); }); it('should save value', function () { var expected = { foo: 'bar', goo: 'nuu' }; localStorage.setItem('item', JSON.stringify(expected)); assert.deepEqual(expected, JSON.parse(localStorage.getItem('item'))); }); it('should clear value', function (done) { var input = { foo: 'bar', goo: 'nuu' }; localStorage.setItem('item', JSON.stringify(input)); resetStorage .localStorage() .then(function () { assert.equal(null, localStorage.getItem('item')); done(); }); }); }); describe('#indexedDB', function () { var db; beforeEach(function (done) { var req = indexedDB.deleteDatabase('test-item'); req.onsuccess = function() { done(); }; }); // http://dev.classmethod.jp/ria/html5/html5-indexed-database-api/ it('should save value', function (done) { if (!indexedDB) { throw new Error('Your browser doesn\'t support a stable version of IndexedDB.'); } var openRequest = indexedDB.open(dbName, 2); var key = 'foo'; var value = 'bar'; var expected = {}; expected[key] = value; openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onupgradeneeded = function(event) { db = event.target.result; var store = db.createObjectStore('mystore', { keyPath: 'mykey'}); store.createIndex('myvalueIndex', 'myvalue'); }; openRequest.onsuccess = function() { db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.put({ mykey: key, myvalue: value }); request.onsuccess = function () { var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.get(key); request.onsuccess = function (event) { assert.equal(value, event.target.result.myvalue); db.close(); done(); }; request.onerror = function (event) { db.close(); throw new Error(event.toString); }; }; request.onerror = function(event) { db.close(); throw new Error(event.toString); }; }; }); it.skip('should clear value. Writing this test is too hard for me.', function (done) { if (true) {// eslint-disable-line no-constant-condition throw new Error(); } if (!indexedDB) { throw new Error('Your browser doesn\'t support a stable version of IndexedDB.'); } var openRequest = indexedDB.open(dbName, 2); var key = 'foo'; var value = 'bar'; var expected = {}; expected[key] = value; openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onupgradeneeded = function(event) { db = event.target.result; var store = db.createObjectStore('mystore', { keyPath: 'mykey'}); store.createIndex('myvalueIndex', 'myvalue'); }; openRequest.onsuccess = function() { db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.put({ mykey: key, myvalue: value }); request.onsuccess = function () { db.close(); var openRequest = indexedDB.open(dbName, 2); openRequest.onerror = function(event) { throw new Error(event.toString); }; openRequest.onsuccess = function() { var db = openRequest.result; var transaction = db.transaction(['mystore'], 'readwrite'); var store = transaction.objectStore('mystore'); var request = store.get(key); request.onsuccess = function (event) { assert.equal(value, event.target.result.myvalue); db.close(); done(); }; request.onerror = function (event) { db.close(); throw new Error(event.toString); }; }; }; request.onerror = function(event) { db.close(); throw new Error(event.toString); }; }; }); });
pandawing/node-reset-storage
test.js
JavaScript
mit
4,421
import React from 'react' import DocumentTitle from 'react-document-title' import ReactHeight from 'react-height' import Header from './header/header' import Content from './content/content' import Footer from './footer/footer' import { APP_NAME } from '../constants' class Layout extends React.Component { render() { const hfStyle = { flex: 'none' } const contentStyle = { flex: 1 } const containerStyle = { display: 'flex', minHeight: window.innerHeight, flexDirection: 'column' } return ( <div style={containerStyle}> <DocumentTitle title={APP_NAME}/> <Header style={hfStyle}/> <Content style={contentStyle}/> <Footer style={hfStyle}/> </div> ) } } export default Layout
HendrikCrause/crossword-creator
src/components/layout.js
JavaScript
mit
792
var i18n = require('i18n'); var _ = require('lodash'); exports.register = function (plugin, options, next) { i18n.configure(options); plugin.ext('onPreResponse', function (request, extNext) { // If is an error message if(request.response.isBoom) { i18n.setLocale(getLocale(request, options)); request.response.output.payload.message = i18n.__(request.response.output.payload.message); return extNext(request.response); } extNext(); }); next(); }; var getLocale = function(request, options) { i18n.init(request.raw.req); if(_.contains(_.keys(i18n.getCatalog()), request.raw.req.language)) { return request.raw.req.language; } else { return options.defaultLocale; } };
jozzhart/josepoo
lib/index.js
JavaScript
mit
731