code stringlengths 2 1.05M |
|---|
$(function() {
var pUploader = new qq.FileUploader({
element: document.getElementById('photos-uploader'),
action: usedcar.resourceURL,
onSubmit : function() {
pUploader.setParams({
vin : $("#VIN").val(),
action : 'upload-photo'
});
}
});
var tUploader = new qq.FileUploader({
element: document.getElementById('thumbnail-uploader'),
action: usedcar.resourceURL,
onSubmit : function() {
tUploader.setParams({
vin : $("#VIN").val(),
action : 'upload-thumbnail'
});
}
});
$("#year").datepicker({dateFormat: "yy", changeYear: true});
var dateOptions = { changeYear: true };
$("#regDate1").datepicker(dateOptions);
$("#serviceDate11").datepicker(dateOptions);
$("#serviceDate12").datepicker(dateOptions);
$("#regDate2").datepicker(dateOptions);
$("#serviceDate21").datepicker(dateOptions);
$("#serviceDate22").datepicker(dateOptions);
$("#tabs").tabs({
show: function(event, ui) {
if (ui.index == 1) {
refreshProfile();
}
else if (ui.index == 2) {
$(':input','#adminForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$("#carAttrs").hide();
$('#VIN').focus();
}
else {
refreshStore();
}
}
});
$('#VIN').keypress(function(e) {
clearTimeout(usedcar.timer);
usedcar.timer = setTimeout("getCarAttrs()", 400);
});
});
function refreshProfile() {
$.post(usedcar.resourceURL, {
action : 'getProfile'
}, function(response) {
if(response.status == 'success'){
var user = response.data.user;
$('#firstName').val(user.firstName);
$('#lastName').val(user.lastName);
displayLikedCars(response.data.likedCarImages);
}
}, "json");
}
function displayLikedCars(likedCarImages) {
var likedCarRows = '';
for (key in likedCarImages) {
var imageBinData = likedCarImages[key];
imageBinData = imageBinData == null ? '' :
String.fromCharCode.apply(String, imageBinData);
var row = $('#likesRowTemplate').html();
row = row.replace("%vin%", key)
.replace("%imageBinData%", imageBinData);
likedCarRows += row + '<hr />';
}
$('#likesContent').html(likedCarRows);
}
function refreshStore() {
$.post(usedcar.resourceURL, {
action : 'store'
}, function(response) {
if (response.status == 'success') {
renderRows(response.data.cars);
}
}, "json");
}
usedcar.dummyImage = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
function renderRows(cars) {
var rows = '';
for(var i = 0; i < cars.length; i++) {
var row = $('#rowTemplate').html();
var binImageData = cars[i].thumbnail;
binImageData = binImageData == null ? usedcar.dummyImage :
String.fromCharCode.apply(String, binImageData);
for(var j = 0; j < 6; j++) {
cars[i].photos[j] = cars[i].photos[j] == undefined ? binImageData :
String.fromCharCode.apply(String, cars[i].photos[j]);
}
row = row.replace(/%vin%/g, cars[i].VIN)
.replace("%make%", cars[i].make)
.replace("%model%", cars[i].model)
.replace("%style%", cars[i].style)
.replace("%year%", cars[i].year)
.replace("%mileage%", cars[i].mileage)
.replace("%color%", cars[i].color)
.replace("%price%", cars[i].price)
.replace("%automatic%", cars[i].automatic)
.replace("%imageBinData%", binImageData)
.replace("%p0%", cars[i].photos[0])
.replace("%p1%", cars[i].photos[1])
.replace("%p2%", cars[i].photos[2])
.replace("%p3%", cars[i].photos[3])
.replace("%p4%", cars[i].photos[4])
.replace("%p5%", cars[i].photos[5]);
rows += row + '<hr />';
}
$('#rows').html(rows);
}
function getCarAttrs() {
var vin = $("#VIN").val();
if (vin == '') {
$("#carAttrs").hide();
return;
}
$.post(usedcar.resourceURL, {
vin : vin,
action : 'getCar'
}, function(response) {
if(response.status == 'success'){
var car = response.data.car;
$('#make').val(car.make);
$('#model').val(car.model);
$('#style').val(car.style);
$('#year').val(car.year);
$('#mileage').val(car.mileage);
$('#color').val(car.color);
if (car.automatic == true) {
$('#rd1').attr('checked', true);
}
else {
$('#rd2').attr('checked', true);
}
$('#price').val(car.price);
if (car.history != null) {
$('#regDate1').val(formatDate(car.history[0].regDate));
$('#regMileage1').val(car.history[0].mileage);
$('#regState1').val(car.history[0].state);
$('#serviceDate11').val(formatDate(car.history[0].serviceRecord[0].serviceDate));
$('#serviceDate12').val(formatDate(car.history[0].serviceRecord[1].serviceDate));
$('#notes11').val(car.history[0].serviceRecord[0].notes);
$('#notes12').val(car.history[0].serviceRecord[1].notes);
$('#regDate2').val(formatDate(car.history[1].regDate));
$('#regMileage2').val(car.history[1].mileage);
$('#regState2').val(car.history[1].state);
$('#serviceDate21').val(formatDate(car.history[1].serviceRecord[0].serviceDate));
$('#serviceDate22').val(formatDate(car.history[1].serviceRecord[1].serviceDate));
$('#notes21').val(car.history[1].serviceRecord[0].notes);
$('#notes22').val(car.history[1].serviceRecord[1].notes);
}
}
}, "json");
$("#carAttrs").show("fast");
}
function formatDate(d) {
var date = new Date(d);
return date.getMonth() + '/' + date.getDay() + '/' + date.getFullYear();
}
function deleteCar() {
$.post(usedcar.resourceURL, {
vin : $('#VIN').val(),
action : 'deleteCar'
}, function(response) {
if (response.status == 'success') {
$(':input','#adminForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
$("#carAttrs").hide();
$('#VIN').focus();
}
}, "json");
}
function saveCar() {
var history =
[
{
regDate : $('#regDate1').val(),
mileage : parseInt($('#regMileage1').val()),
state : $('#regState1').val(),
serviceRecord : [
{serviceDate: $('#serviceDate11').val(), notes : $('#notes11').val()},
{serviceDate: $('#serviceDate12').val(), notes : $('#notes12').val()}
]
},
{
regDate : $('#regDate2').val(),
mileage : parseInt($('#regMileage2').val()),
state : $('#regState2').val(),
serviceRecord : [
{serviceDate: $('#serviceDate21').val(), notes : $('#notes21').val()},
{serviceDate: $('#serviceDate22').val(), notes : $('#notes22').val()}
]
}
];
$.post(usedcar.resourceURL, {
vin : $('#VIN').val(),
make : $('#make').val(),
model : $('#model').val(),
style : $('#style').val(),
year : $('#year').val(),
mileage : $('#mileage').val(),
color : $('#color').val(),
automatic : $("input[name='automatic']:checked").val(),
price : $('#price').val(),
history : JSON.stringify(history),
action : 'saveCar'
}, function(response) {
if (response.status == 'success') {
//TODO
}
}, "json");
}
function likeCar(vin) {
$.post(usedcar.resourceURL, {
vin : vin,
action : 'likeCar'
}, function(response) {
if (response.status == 'success') {
//TODO
}
}, "json");
}
function unlikeCar(vin) {
$.post(usedcar.resourceURL, {
vin : vin,
action : 'unlikeCar'
}, function(response) {
if (response.status == 'success') {
refreshProfile();
}
}, "json");
}
function saveUser() {
$.post(usedcar.resourceURL, {
firstName : $('#firstName').val(),
lastName : $('#lastName').val(),
action : 'saveUser'
}, function(response) {
if (response.status == 'success') {
//TODO
}
}, "json");
} |
'use strict';
import window from 'global/window';
import document from 'global/document';
import mejs from '../core/mejs';
import {renderer} from '../core/renderer';
import {createEvent} from '../utils/general';
import {typeChecks} from '../utils/media';
/**
* YouTube renderer
*
* Uses <iframe> approach and uses YouTube API to manipulate it.
* Note: IE6-7 don't have postMessage so don't support <iframe> API, and IE8 doesn't fire the onReady event,
* so it doesn't work - not sure if Google problem or not.
* @see https://developers.google.com/youtube/iframe_api_reference
*/
const YouTubeApi = {
/**
* @type {Boolean}
*/
isIframeStarted: false,
/**
* @type {Boolean}
*/
isIframeLoaded: false,
/**
* @type {Array}
*/
iframeQueue: [],
/**
* Create a queue to prepare the creation of <iframe>
*
* @param {Object} settings - an object with settings needed to create <iframe>
*/
enqueueIframe: (settings) => {
// Check whether YouTube API is already loaded.
YouTubeApi.isLoaded = typeof YT !== 'undefined' && YT.loaded;
if (YouTubeApi.isLoaded) {
YouTubeApi.createIframe(settings);
} else {
YouTubeApi.loadIframeApi();
YouTubeApi.iframeQueue.push(settings);
}
},
/**
* Load YouTube API script on the header of the document
*
*/
loadIframeApi: () => {
if (!YouTubeApi.isIframeStarted) {
const tag = document.createElement('script');
tag.src = '//www.youtube.com/player_api';
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
YouTubeApi.isIframeStarted = true;
}
},
/**
* Process queue of YouTube <iframe> element creation
*
*/
iFrameReady: () => {
YouTubeApi.isLoaded = true;
YouTubeApi.isIframeLoaded = true;
while (YouTubeApi.iframeQueue.length > 0) {
const settings = YouTubeApi.iframeQueue.pop();
YouTubeApi.createIframe(settings);
}
},
/**
* Create a new instance of YouTube API player and trigger a custom event to initialize it
*
* @param {Object} settings - an object with settings needed to create <iframe>
*/
createIframe: (settings) => {
return new YT.Player(settings.containerId, settings);
},
/**
* Extract ID from YouTube's URL to be loaded through API
* Valid URL format(s):
* - http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
* - http://www.youtube.com/v/VIDEO_ID?version=3
* - http://youtu.be/Djd6tPrxc08
* - http://www.youtube-nocookie.com/watch?feature=player_embedded&v=yyWWXSwtPP0
*
* @param {String} url
* @return {string}
*/
getYouTubeId: (url) => {
let youTubeId = '';
if (url.indexOf('?') > 0) {
// assuming: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
youTubeId = YouTubeApi.getYouTubeIdFromParam(url);
// if it's http://www.youtube.com/v/VIDEO_ID?version=3
if (youTubeId === '') {
youTubeId = YouTubeApi.getYouTubeIdFromUrl(url);
}
} else {
youTubeId = YouTubeApi.getYouTubeIdFromUrl(url);
}
return youTubeId;
},
/**
* Get ID from URL with format: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
*
* @param {String} url
* @returns {string}
*/
getYouTubeIdFromParam: (url) => {
if (url === undefined || url === null || !url.trim().length) {
return null;
}
const
parts = url.split('?'),
parameters = parts[1].split('&')
;
let youTubeId = '';
for (let i = 0, total = parameters.length; i < total; i++) {
const paramParts = parameters[i].split('=');
if (paramParts[0] === 'v') {
youTubeId = paramParts[1];
break;
}
}
return youTubeId;
},
/**
* Get ID from URL with formats
* - http://www.youtube.com/v/VIDEO_ID?version=3
* - http://youtu.be/Djd6tPrxc08
* @param {String} url
* @return {?String}
*/
getYouTubeIdFromUrl: (url) => {
if (url === undefined || url === null || !url.trim().length) {
return null;
}
const parts = url.split('?');
url = parts[0];
return url.substring(url.lastIndexOf('/') + 1);
},
/**
* Inject `no-cookie` element to URL. Only works with format: http://www.youtube.com/v/VIDEO_ID?version=3
* @param {String} url
* @return {?String}
*/
getYouTubeNoCookieUrl: (url) => {
if (url === undefined || url === null || !url.trim().length || !url.includes('//www.youtube')) {
return url;
}
const parts = url.split('/');
parts[2] = parts[2].replace('.com', '-nocookie.com');
return parts.join('/');
}
};
const YouTubeIframeRenderer = {
name: 'youtube_iframe',
options: {
prefix: 'youtube_iframe',
/**
* Custom configuration for YouTube player
*
* @see https://developers.google.com/youtube/player_parameters#Parameters
* @type {Object}
*/
youtube: {
autoplay: 0,
controls: 0,
disablekb: 1,
end: 0,
loop: 0,
modestbranding: 0,
playsinline: 0,
rel: 0,
showinfo: 0,
start: 0,
iv_load_policy: 3,
// custom to inject `-nocookie` element in URL
nocookie: false
}
},
/**
* Determine if a specific element type can be played with this render
*
* @param {String} type
* @return {Boolean}
*/
canPlayType: (type) => ['video/youtube', 'video/x-youtube'].includes(type),
/**
* Create the player instance and add all native events/methods/properties as possible
*
* @param {MediaElement} mediaElement Instance of mejs.MediaElement already created
* @param {Object} options All the player configuration options passed through constructor
* @param {Object[]} mediaFiles List of sources with format: {src: url, type: x/y-z}
* @return {Object}
*/
create: (mediaElement, options, mediaFiles) => {
// API objects
const
youtube = {},
apiStack = [],
readyState = 4
;
let
youTubeApi = null,
paused = true,
ended = false,
youTubeIframe = null,
volume = 1
;
youtube.options = options;
youtube.id = mediaElement.id + '_' + options.prefix;
youtube.mediaElement = mediaElement;
// wrappers for get/set
const
props = mejs.html5media.properties,
assignGettersSetters = (propName) => {
// add to flash state that we will store
const capName = `${propName.substring(0, 1).toUpperCase()}${propName.substring(1)}`;
youtube[`get${capName}`] = () => {
if (youTubeApi !== null) {
const value = null;
// figure out how to get youtube dta here
switch (propName) {
case 'currentTime':
return youTubeApi.getCurrentTime();
case 'duration':
return youTubeApi.getDuration();
case 'volume':
volume = youTubeApi.getVolume() / 100;
return volume;
case 'paused':
return paused;
case 'ended':
return ended;
case 'muted':
return youTubeApi.isMuted();
case 'buffered':
const percentLoaded = youTubeApi.getVideoLoadedFraction(),
duration = youTubeApi.getDuration();
return {
start: () => {
return 0;
},
end: () => {
return percentLoaded * duration;
},
length: 1
};
case 'src':
return youTubeApi.getVideoUrl();
case 'readyState':
return readyState;
}
return value;
} else {
return null;
}
};
youtube[`set${capName}`] = (value) => {
if (youTubeApi !== null) {
// do something
switch (propName) {
case 'src':
const url = typeof value === 'string' ? value : value[0].src,
videoId = YouTubeApi.getYouTubeId(url);
if (mediaElement.originalNode.autoplay) {
youTubeApi.loadVideoById(videoId);
} else {
youTubeApi.cueVideoById(videoId);
}
break;
case 'currentTime':
youTubeApi.seekTo(value);
break;
case 'muted':
if (value) {
youTubeApi.mute();
} else {
youTubeApi.unMute();
}
setTimeout(() => {
const event = createEvent('volumechange', youtube);
mediaElement.dispatchEvent(event);
}, 50);
break;
case 'volume':
volume = value;
youTubeApi.setVolume(value * 100);
setTimeout(() => {
const event = createEvent('volumechange', youtube);
mediaElement.dispatchEvent(event);
}, 50);
break;
case 'readyState':
const event = createEvent('canplay', youtube);
mediaElement.dispatchEvent(event);
break;
default:
console.log('youtube ' + youtube.id, propName, 'UNSUPPORTED property');
break;
}
} else {
// store for after "READY" event fires
apiStack.push({type: 'set', propName: propName, value: value});
}
};
}
;
for (let i = 0, total = props.length; i < total; i++) {
assignGettersSetters(props[i]);
}
// add wrappers for native methods
const
methods = mejs.html5media.methods,
assignMethods = (methodName) => {
// run the method on the native HTMLMediaElement
youtube[methodName] = () => {
if (youTubeApi !== null) {
// DO method
switch (methodName) {
case 'play':
paused = false;
return youTubeApi.playVideo();
case 'pause':
paused = true;
return youTubeApi.pauseVideo();
case 'load':
return null;
}
} else {
apiStack.push({type: 'call', methodName: methodName});
}
};
}
;
for (let i = 0, total = methods.length; i < total; i++) {
assignMethods(methods[i]);
}
// CREATE YouTube
const youtubeContainer = document.createElement('div');
youtubeContainer.id = youtube.id;
// If `nocookie` feature was enabled, modify original URL
if (youtube.options.youtube.nocookie) {
mediaElement.originalNode.setAttribute('src', YouTubeApi.getYouTubeNoCookieUrl(mediaFiles[0].src));
}
mediaElement.originalNode.parentNode.insertBefore(youtubeContainer, mediaElement.originalNode);
mediaElement.originalNode.style.display = 'none';
const
isAudio = mediaElement.originalNode.tagName.toLowerCase() === 'audio',
height = isAudio ? '0' : mediaElement.originalNode.height,
width = isAudio ? '0' : mediaElement.originalNode.width,
videoId = YouTubeApi.getYouTubeId(mediaFiles[0].src),
youtubeSettings = {
id: youtube.id,
containerId: youtubeContainer.id,
videoId: videoId,
height: height,
width: width,
playerVars: Object.assign({
controls: 0,
rel: 0,
disablekb: 1,
showinfo: 0,
modestbranding: 0,
html5: 1,
playsinline: 0,
start: 0,
end: 0,
iv_load_policy: 3
}, youtube.options.youtube),
origin: window.location.host,
events: {
onReady: (e) => {
mediaElement.youTubeApi = youTubeApi = e.target;
mediaElement.youTubeState = {
paused: true,
ended: false
};
// do call stack
if (apiStack.length) {
for (let i = 0, total = apiStack.length; i < total; i++) {
const stackItem = apiStack[i];
if (stackItem.type === 'set') {
const
propName = stackItem.propName,
capName = `${propName.substring(0, 1).toUpperCase()}${propName.substring(1)}`
;
youtube[`set${capName}`](stackItem.value);
} else if (stackItem.type === 'call') {
youtube[stackItem.methodName]();
}
}
}
// a few more events
youTubeIframe = youTubeApi.getIframe();
const
events = ['mouseover', 'mouseout'],
assignEvents = (e) => {
const newEvent = createEvent(e.type, youtube);
mediaElement.dispatchEvent(newEvent);
}
;
for (let i = 0, total = events.length; i < total; i++) {
youTubeIframe.addEventListener(events[i], assignEvents, false);
}
// send init events
const initEvents = ['rendererready', 'loadeddata', 'loadedmetadata', 'canplay'];
for (let i = 0, total = initEvents.length; i < total; i++) {
const event = createEvent(initEvents[i], youtube);
mediaElement.dispatchEvent(event);
}
},
onStateChange: (e) => {
// translate events
let events = [];
switch (e.data) {
case -1: // not started
events = ['loadedmetadata'];
paused = true;
ended = false;
break;
case 0: // YT.PlayerState.ENDED
events = ['ended'];
paused = false;
ended = true;
youtube.stopInterval();
break;
case 1: // YT.PlayerState.PLAYING
events = ['play', 'playing'];
paused = false;
ended = false;
youtube.startInterval();
break;
case 2: // YT.PlayerState.PAUSED
events = ['pause'];
paused = true;
ended = false;
youtube.stopInterval();
break;
case 3: // YT.PlayerState.BUFFERING
events = ['progress'];
ended = false;
break;
case 5: // YT.PlayerState.CUED
events = ['loadeddata', 'loadedmetadata', 'canplay'];
paused = true;
ended = false;
break;
}
// send events up
for (let i = 0, total = events.length; i < total; i++) {
const event = createEvent(events[i], youtube);
mediaElement.dispatchEvent(event);
}
},
onError: (e) => {
const event = createEvent('error', youtube);
event.data = e.data;
mediaElement.dispatchEvent(event);
}
}
}
;
// The following will prevent that in mobile devices, YouTube is displayed in fullscreen when using audio
if (isAudio) {
youtubeSettings.playerVars.playsinline = 1;
}
// send it off for async loading and creation
YouTubeApi.enqueueIframe(youtubeSettings);
youtube.onEvent = (eventName, player, _youTubeState) => {
if (_youTubeState !== null && _youTubeState !== undefined) {
mediaElement.youTubeState = _youTubeState;
}
};
youtube.setSize = (width, height) => {
if (youTubeApi !== null) {
youTubeApi.setSize(width, height);
}
};
youtube.hide = () => {
youtube.stopInterval();
youtube.pause();
if (youTubeIframe) {
youTubeIframe.style.display = 'none';
}
};
youtube.show = () => {
if (youTubeIframe) {
youTubeIframe.style.display = '';
}
};
youtube.destroy = () => {
youTubeApi.destroy();
};
youtube.interval = null;
youtube.startInterval = () => {
// create timer
youtube.interval = setInterval(() => {
const event = createEvent('timeupdate', youtube);
mediaElement.dispatchEvent(event);
}, 250);
};
youtube.stopInterval = () => {
if (youtube.interval) {
clearInterval(youtube.interval);
}
};
return youtube;
}
};
if (window.postMessage && typeof window.addEventListener) {
window.onYouTubePlayerAPIReady = () => {
YouTubeApi.iFrameReady();
};
typeChecks.push((url) => {
url = url.toLowerCase();
return (url.includes('//www.youtube') || url.includes('//youtu.be')) ? 'video/x-youtube' : null;
});
renderer.add(YouTubeIframeRenderer);
} |
/*jslint node: true */
/*global describe, it */
"use strict";
var assert = require('assert');
var skein = require('../build/Release/skein');
describe('Echo test', function () {
describe('echo test', function () {
it('should echo buffer object', function (done) {
var crypto = new skein.Crypto();
var expected = new Buffer([1, 2, 3]);
crypto.echo(expected, function (data) {
assert.ok(data.compare(expected) === 0);
done();
});
});
});
});
describe('Encrypt test', function () {
describe('encrypt test', function () {
it('should encrypt a string', function (done) {
var crypto = new skein.Crypto();
crypto.calcHash("my top secret password", function (err, hash) {
assert.equal(err, null);
assert.equal(hash.length, 64);
crypto.encrypt(hash, "Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν", function (err, data) {
assert.equal(err, null);
assert.equal(data.length, 76);
done();
});
});
});
it('should throw wrong number of arguments exception', function () {
var crypto = new skein.Crypto();
try {
crypto.encrypt();
} catch (e) {
assert.equal(e.message, 'There must be 3 arguments');
}
});
it('should throw argument type exception', function () {
var crypto = new skein.Crypto();
try {
crypto.encrypt(123, "foo", 123);
} catch (e) {
assert.equal(e.message, 'Expected a buffer, a string and a function');
}
});
});
});
describe('Decrypt test', function () {
describe('decrypt test', function () {
it('should decrypt a string', function (done) {
var crypto = new skein.Crypto();
crypto.calcHash("my top secret password", function (err, hash) {
assert.equal(err, null);
assert.equal(hash.length, 64);
var text = "Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν";
crypto.encrypt(hash, text, function (err, cyphered) {
assert.equal(err, null);
crypto.decrypt(hash, cyphered, function (err, decyphered) {
assert.equal(err, null);
assert.equal(decyphered, text);
done();
});
});
});
});
});
});
describe('CalcHash test', function () {
describe('calcHash test', function () {
it('should calculate a hash', function (done) {
var crypto = new skein.Crypto();
crypto.calcHash("my top secret password", function (err, data) {
assert.equal(err, null);
assert.equal(data.length, 64);
done();
});
});
it('should throw wrong number of arguments exception', function () {
var crypto = new skein.Crypto();
try {
crypto.calcHash();
} catch (e) {
assert.equal(e.message, 'There must be two arguments');
}
});
it('should throw argument type exception', function () {
var crypto = new skein.Crypto();
try {
crypto.calcHash(123, "foo");
} catch (e) {
assert.equal(e.message, 'Expected a string and a function');
}
});
});
});
|
'use strict';
const chalk = require('chalk');
const EOL = require('os').EOL;
module.exports = function(initialMargin, shouldDescriptionBeGrey) {
initialMargin = initialMargin || '';
let output = '';
let options = this.anonymousOptions;
// <anonymous-option-1> ...
if (options.length) {
output += ` ${chalk.yellow(
options
.map(option => {
// blueprints we insert brackets, commands already have them
if (option.indexOf('<') === 0) {
return option;
} else {
return `<${option}>`;
}
})
.join(' ')
)}`;
}
options = this.availableOptions;
// <options...>
if (options.length) {
output += ` ${chalk.cyan('<options...>')}`;
}
// Description
let description = this.description;
if (description) {
if (shouldDescriptionBeGrey) {
description = chalk.grey(description);
}
output += `${EOL + initialMargin} ${description}`;
}
// aliases: a b c
if (this.aliases && this.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(`aliases: ${this.aliases.filter(a => a).join(', ')}`)}`;
}
// --available-option (Required) (Default: value)
// ...
options.forEach(option => {
output += `${EOL + initialMargin} ${chalk.cyan(`--${option.name}`)}`;
if (option.values) {
output += chalk.cyan(`=${option.values.join('|')}`);
}
if (option.type) {
let types = Array.isArray(option.type) ? option.type.map(formatType).join(', ') : formatType(option.type);
output += ` ${chalk.cyan(`(${types})`)}`;
}
if (option.required) {
output += ` ${chalk.cyan('(Required)')}`;
}
if (option.default !== undefined) {
output += ` ${chalk.cyan(`(Default: ${formatValue(option.default)})`)}`;
}
if (option.description) {
output += ` ${option.description}`;
}
if (option.aliases && option.aliases.length) {
output += `${EOL + initialMargin} ${chalk.grey(
`aliases: ${option.aliases
.map(a => {
if (typeof a === 'string') {
return (a.length > 4 ? '--' : '-') + a + (option.type === Boolean ? '' : ' <value>');
} else {
let key = Object.keys(a)[0];
return `${(key.length > 4 ? '--' : '-') + key} (--${option.name}=${formatValue(a[key])})`;
}
})
.join(', ')}`
)}`;
}
});
return output;
};
function formatType(type) {
return typeof type === 'string' ? formatValue(type) : type.name;
}
function formatValue(val) {
return val === '' ? '""' : val;
}
|
import React from 'react';
import {connect} from 'react-redux';
let SearchOptions = () => {
const handleClick = (e) => {
debugger;
}
return (
<div className='in-line'>
<button onClick={handleClick}>Case</button>
</div>
)
}
export default SearchOptions;
|
'use strict';
//Setting up route
angular.module('leagues').config(['$stateProvider',
function($stateProvider) {
// Leagues state routing
$stateProvider.
state('listLeagues', {
url: '/leagues',
templateUrl: 'modules/leagues/views/list-leagues.client.view.html'
}).
state('createLeague', {
url: '/leagues/create',
templateUrl: 'modules/leagues/views/create-league.client.view.html'
}).
state('viewLeague', {
url: '/leagues/:leagueId',
templateUrl: 'modules/leagues/views/view-league.client.view.html'
}).
state('viewLeagueJoin', {
url: '/leagues/:leagueId/join',
templateUrl: 'modules/leagues/views/view-league.client.view.html'
}).
state('editLeague', {
url: '/leagues/:leagueId/edit',
templateUrl: 'modules/leagues/views/edit-league.client.view.html'
});
}
]);
|
/* demo/test/004-ship-controls.js */
define ([
'keypress',
'physicsjs',
'howler',
'1401/objects/sysloop',
'1401/settings',
'1401/system/renderer',
'1401/system/visualfactory',
'1401/system/piecefactory',
'1401-games/demo/modules/controls'
], function (
KEY,
PHYSICS,
HOWLER,
SYSLOOP,
SETTINGS,
RENDERER,
VISUALFACTORY,
PIECEFACTORY,
SHIPCONTROLS
) {
var DBGOUT = true;
///////////////////////////////////////////////////////////////////////////////
/** SUBMODULE TEST 004 *******************************************************\
Add rudimentary physics and ship controls
///////////////////////////////////////////////////////////////////////////////
/** MODULE DECLARATION *******************************************************/
var MOD = SYSLOOP.New("Test04");
MOD.EnableUpdate( true );
MOD.EnableInput( true );
MOD.SetHandler( 'GetInput', m_GetInput);
MOD.SetHandler( 'Start', m_Start );
MOD.SetHandler( 'Construct', m_Construct );
MOD.SetHandler( 'Update', m_Update);
///////////////////////////////////////////////////////////////////////////////
/** PRIVATE VARS *************************************************************/
var crixa; // ship piece
var crixa_inputs; // encoded controller inputs
var starfields = []; // parallax starfield layersey
var snd_pewpew; // sound instance (howler.js)
var snd_music;
///////////////////////////////////////////////////////////////////////////////
/** MODULE HANDLER FUNCTIONS *************************************************/
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Construct() {
var i, platform;
var cam = RENDERER.Viewport().WorldCam3D();
var z = cam.position.z;
var fog = new THREE.Fog(0x000000,z-100,z+50);
RENDERER.SetWorldVisualFog(fog);
/* add lights so mesh colors show */
var ambientLight = new THREE.AmbientLight(0x222222);
RENDERER.AddWorldVisual(ambientLight);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
RENDERER.AddWorldVisual(directionalLight);
/* make starfield */
var starBright = [
new THREE.Color( 1.0, 1.0, 1.0 ),
new THREE.Color( 0.5, 0.5, 0.7 ),
new THREE.Color( 0.3, 0.3, 0.5 )
];
var starSpec = {
parallax: 1
};
starfields = [];
for (i=0;i<3;i++) {
starSpec.color=starBright[i];
var sf = VISUALFACTORY.MakeStarField( starSpec );
starSpec.parallax *= 0.5;
sf.position.set(0,0,-100-i);
RENDERER.AddBackgroundVisual(sf);
starfields.push(sf);
}
/* make crixa ship */
var shipSprite = VISUALFACTORY.MakeDefaultSprite();
shipSprite.SetZoom(1.0);
RENDERER.AddWorldVisual(shipSprite);
var seq = {
grid: { columns:2, rows:1, stacked:true },
sequences: [
{ name: 'flicker', framecount: 2, fps:4 }
]
};
shipSprite.DefineSequences(SETTINGS.AssetPath('resources/crixa.png'),seq);
// shipSprite.PlaySequence("flicker");
crixa = PIECEFACTORY.NewMovingPiece("crixa");
crixa.SetVisual(shipSprite);
crixa.SetPositionXYZ(0,0,0);
// add extra shooting command
crixa.Shoot = function ( bool ) {
if (bool) snd_pewpew.play();
};
// demonstration of texture validity
var textureLoaded = crixa.Visual().TextureIsLoaded();
console.log("SHIP TEXTURE LOADED TEST OK?",textureLoaded);
if (textureLoaded) {
console.log(". spritesheet dim",crixa.Visual().TextureDimensions());
console.log(". sprite dim",crixa.Visual().SpriteDimensions());
} else {
console.log(".. note textures load asynchronously, so the dimensions are not available yet...");
console.log(".. sprite class handles this automatically so you don't have to.");
}
// make sprites
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.SetZoom(1.0);
platform.position.set(0,100,100-(i*50));
RENDERER.AddWorldVisual(platform);
}
for (i=0;i<3;i++) {
platform = VISUALFACTORY.MakeStaticSprite(
SETTINGS.AssetPath('resources/teleport.png'),
do_nothing
);
platform.position.set(0,-125,100-(i*50));
platform.SetZoom(1.25);
RENDERER.AddWorldVisual(platform);
}
function do_nothing () {}
// load sound
var sfx = SETTINGS.AssetPath('resources/pewpew.ogg');
snd_pewpew = new Howl({
urls: [sfx]
});
}
/// HEAP-SAVING PRE-ALLOCATED VARIABLES /////////////////////////////////////
var x, rot, vp, layers, i, sf;
var cin;
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_Start() {
RENDERER.SelectWorld3D();
SHIPCONTROLS.BindKeys();
window.DBG_Out( "TEST 04 <b>Simple Ship Movement and Control</b>" );
window.DBG_Out( "<tt>game-main include: 1401-games/demo/tests/004</tt>" );
window.DBG_Out( "Use WASDQE to move. SPACE brakes. C fires." );
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function m_GetInput ( interval_ms ) {
cin = crixa_inputs = SHIPCONTROLS.GetInput();
if (!!crixa_inputs.forward_acc) {
crixa.Visual().GoSequence("flicker",1);
} else {
crixa.Visual().GoSequence("flicker",0);
}
crixa.Accelerate(cin.forward_acc,cin.side_acc);
crixa.Brake(crixa_inputs.brake_lin);
crixa.AccelerateRotation(cin.rot_acc);
crixa.BrakeRotation(crixa_inputs.brake_rot);
crixa.Shoot(SHIPCONTROLS.Fire());
}
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var counter = 0;
var dx = 3;
function m_Update ( interval_ms ) {
vp = RENDERER.Viewport();
vp.Track(crixa.Position());
/* rotate stars */
layers = starfields.length;
for (i=0;i<starfields.length;i++){
sf = starfields[i];
sf.Track(crixa.Position());
}
counter += interval_ms;
}
///////////////////////////////////////////////////////////////////////////////
/** RETURN MODULE DEFINITION FOR REQUIREJS ***********************************/
return MOD;
});
|
(function () {
'use strict';
angular.module('haceruido.main', ['ngRoute'])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$location'];
function MainCtrl($scope, $location) {
var vm = this;
vm.posts = [];
vm.ver = ver;
//var refFull = new Firebase('https://estomehaceruido.firebaseio.com/posts');
//refFull.on('value', function (childSnapshot, prevChildKey) {
// // code to handle new child.
// vm.posts.push({key: childSnapshot.key(), value: childSnapshot.val()});
//
// if (!$scope.$$phase) {
// $scope.$apply();
// }
//});
function ver(id) {
$location.path('detalle/' + id);
}
}
})();
|
/* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var MapsLocalFlorist = _react2.default.createClass({
displayName: 'MapsLocalFlorist',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M12 22c4.97 0 9-4.03 9-9-4.97 0-9 4.03-9 9zM5.6 10.25c0 1.38 1.12 2.5 2.5 2.5.53 0 1.01-.16 1.42-.44l-.02.19c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5l-.02-.19c.4.28.89.44 1.42.44 1.38 0 2.5-1.12 2.5-2.5 0-1-.59-1.85-1.43-2.25.84-.4 1.43-1.25 1.43-2.25 0-1.38-1.12-2.5-2.5-2.5-.53 0-1.01.16-1.42.44l.02-.19C14.5 2.12 13.38 1 12 1S9.5 2.12 9.5 3.5l.02.19c-.4-.28-.89-.44-1.42-.44-1.38 0-2.5 1.12-2.5 2.5 0 1 .59 1.85 1.43 2.25-.84.4-1.43 1.25-1.43 2.25zM12 5.5c1.38 0 2.5 1.12 2.5 2.5s-1.12 2.5-2.5 2.5S9.5 9.38 9.5 8s1.12-2.5 2.5-2.5zM3 13c0 4.97 4.03 9 9 9 0-4.97-4.03-9-9-9z'}));
}
});
exports.default = MapsLocalFlorist;
module.exports = exports['default'];
|
angular
.module('app', [
"ui.router"
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
//-----home-----//
.state('home', {
url: '/',
templateUrl: 'templates/home.html'
})
//-----about-----//
.state('about', {
url: '/about',
templateUrl: 'templates/about.html'
})
.state('about.home', {
url: '/',
templateUrl: 'templates/about/home.html'
})
.state('about.beast', {
url: "/bloodborne",
templateUrl: 'templates/about/beast.html'
})
.state('about.dark', {
url: "/darksouls",
templateUrl: 'templates/about/dark.html'
})
.state('about.dark-ii', {
url: "/darksouls-ii",
templateUrl: 'templates/about/dark-ii.html'
})
.state('about.demon', {
url: "/demonsouls",
templateUrl: 'templates/about/demon.html'
})
//-----items-----//
.state('items', {
url: '/items',
templateUrl: 'templates/items.html'
})
.state('items.home', {
url: '/',
templateUrl: 'templates/items/home.html'
})
.state('items.weapons', {
url: '/weapons',
templateUrl: 'templates/items/weapons.html'
})
.state('items.shields', {
url: '/shields',
templateUrl: 'templates/items/shields.html'
})
.state('items.armor', {
url: '/armor',
templateUrl: 'templates/items/armor.html'
})
.state('items.accessories', {
url: '/accessories',
templateUrl: 'templates/items/accessories.html'
})
.state('items.consumables', {
url: '/cons',
templateUrl: 'templates/items/consumables.html'
})
.state('items.miscellaneous', {
url: '/miscellaneous',
templateUrl: 'templates/items/misc.html'
})
//-----gameplay-----//
.state('gameplay', {
url: '/gameplay',
templateUrl: 'templates/gameplay.html'
})
.state('gameplay.home', {
url: '/',
templateUrl: 'templates/gameplay/home.html'
})
.state('gameplay.mechanics', {
url: '/mechanics',
templateUrl: 'templates/gameplay/mechanics.html'
})
.state('gameplay.covenants', {
url: '/covenants',
templateUrl: 'templates/gameplay/covenants.html'
})
//-----guides-----//
.state('guides', {
url: '/guides',
templateUrl: 'templates/guides.html'
})
.state('guides.home', {
url: '/',
templateUrl: 'templates/guides/home.html'
})
.state('guides.beast', {
url: "/bloodborne",
templateUrl: 'templates/guides/beast.html'
})
.state('guides.dark-ii', {
url: "/darksouls-ii",
templateUrl: 'templates/guides/dark-ii.html'
})
.state('guides.dark', {
url: "/darksouls",
templateUrl: 'templates/guides/dark.html'
})
.state('guides.demon', {
url: "/demonsouls",
templateUrl: 'templates/guides/demon.html'
})
//-----contact-----//
.state('contact', {
url: 'about/us',
templateUrl: 'templates/about/site.html'
})
}])
|
const { SevenBoom } = require('graphql-apollo-errors');
module.exports = async (root, { _id }, ctx) => {
// get model
const { Card } = ctx.db;
const card = await Card.findById(_id);
// if not found throw 404
if (!card) {
const errorMessage = `Card with id: ${ _id } not found`;
const errorData = { _id };
const errorName = 'CARD_NOT_FOUND';
const err = SevenBoom.notFound(errorMessage, errorData, errorName);
throw err;
}
// if already deleted throw 403
if (card.deleted) {
const errorMessage = `Card with id: ${ _id } is already deleted`;
const errorData = { _id };
const errorName = 'NOT_ALLOWED';
const err = SevenBoom.forbidden(errorMessage, errorData, errorName);
throw err;
}
// set card deleted
card.deleted = true;
await card.save();
// return true
return true;
};
|
const path = require('path');
const assert = require('assert');
const common = require('../../common.js');
const CommandGlobals = require('../../lib/globals/commands.js');
const MockServer = require('../../lib/mockserver.js');
const {settings} = common;
const {runTests} = common.require('index.js');
describe('testRunWithExternalGlobals', function() {
beforeEach(function(done) {
this.server = MockServer.init();
this.server.on('listening', () => {
done();
});
});
afterEach(function(done) {
CommandGlobals.afterEach.call(this, done);
});
beforeEach(function() {
process.removeAllListeners('exit');
process.removeAllListeners('uncaughtException');
process.removeAllListeners('unhandledRejection');
});
it('testRun with external globals', function() {
let testsPath = path.join(__dirname, '../../sampletests/before-after/sampleSingleTest.js');
const globals = {
reporterCount: 0
};
return runTests(testsPath, settings({
globals,
globals_path: path.join(__dirname, '../../extra/external-globals.js'),
output_folder: false
}));
});
});
|
import Schema from '@lyra/schema'
export default Schema.compile({
name: 'myBlog',
types: [
{
type: 'object',
name: 'blogPost',
fields: [
{
title: 'Title',
type: 'string',
name: 'title'
},
{
title: 'Body',
name: 'body',
type: 'array',
of: [{type: 'block'}]
}
]
}
]
})
|
import Ember from 'ember';
export default Ember.Controller.extend({
flashMessages: Ember.inject.service(),
actions: {
emailWarn(status) {
const ev = status.emailValidator;
const flash = this.get('flashMessages');
console.log(status);
if(ev.code === 'cleared-warning') {
flash.success(`The warning code "${ev.clearedCode}" has been cleared and is now ok.`);
} else {
flash.warning(`The email address has entered the "${ev.state}" state with an error code of "${ev.code}"`);
}
}
}
});
|
//=============================================================================
// CharacterScaleChanger.js
// ----------------------------------------------------------------------------
// Copyright (c) 2017-2019 Tsumio
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
// ----------------------------------------------------------------------------
// Version
// 1.1.0 2019/06/27 Scaleの変更にシンボル名を指定できるようにした。
// 1.0.0 2019/06/26 公開。
// ----------------------------------------------------------------------------
// [GitHub] : https://github.com/Tsumio/rmmv-plugins
// [Blog] : http://ntgame.wpblog.jp/
// [Twitter]: https://twitter.com/TsumioNtGame
//=============================================================================
/*:
* @plugindesc Change the Character scale at once.
* @author Tsumio
*
* @param ----Basic Settings----
* @desc
* @default
*
* @help Change the Character scale at once.
*
* ----feature----
* -> Change the character scale at once
* -> You can get the Scale that has changed
*
* ----how to use----
* After introducing this plugin, use the script command.
* If you want to change scale only for events that have a specific memo tag specified
* it is necessary to set up the memo field.
* The specification method of this memo field is as follows.
* <scale:distinguishedName>
*
* For example, if you want to distinguish by "MiniCharacter", write as follows in the event memo field.
* <scale:MiniCharacter>
*
* It is possible to specify the same for multiple events.
* If multiple events are specified, multiple events are affected by scale change at the same time.
*
* ----scripts----
* -> Change of all character size
* $gameSystem.changeCharacterScale(ScaleX, ScaleY);
* Ex: Increase both horizontal and vertical 1.5 times
* $gameSystem.changeCharacterScale(1.5, 1.5);
*
* -> Get currently all scaleX
* $gameSystem.getCharacterScaleX();
*
* -> Get currently all scaleY
* $gameSystem.getCharacterScaleY();
*
* -> Change the scale only for events where a specific memo tag is specified
* $gameSystem.changeCharacterScale(ScaleX, ScaleY, 'Symbol');
* Example: Scale of the event group for which the "miniCharacter" is specified in the memo filed.
* $gameSystem.changeCharacterScale(0.5, 0.5, 'miniCharacter');
*
* ----symbol----
* In the script $gameSystem.changeCharacterScale(scaleX, scaleY, 'symbol')
* If you do not specify a Symbol Name, "all" is implicitly specified.
* Furthermore, to specify characters other than events, specify the following symbol names.
*
* -> Player character: player
* -> Follower: follower
* -> Vehicle: vehicle
*
* Also, do not use "null" and "all" for symbol name.
*
* ----priority----
* The priority of scale change is
* 1.Scale specified by individual symbol name
* 2.Implicitly specified all (no symbol name specified)
*
* ----change log---
* 1.1.0 2019/06/27 It became possible to specify a symbol name in the change of Scale.
* 1.0.0 2019/06/26 Release.
*
* ----remarks----
* I shall not be responsible for any loss, damages and troubles from using this plugin.
*
* --Terms of Use--
* This plugin is free for both commercial and non-commercial use.
* You may edit the source code to suit your needs,
* so long as you don't claim the source code belongs to you.
*
*/
/*:ja
* @plugindesc キャラクターのScaleを一括で変更します。
* @author ツミオ
*
* @param ----基本的な設定----
* @desc
* @default
*
*
* @help キャラクターのScaleを一括で変更します。
*
* 【特徴】
* ・キャラクターのScaleを一括で変更します
* ・変更したScaleを取得できます
*
* 【使用方法】
* プラグインの導入後、スクリプトコマンドから使用します。
* また、特定のメモタグが指定されているイベントだけScaleを変更したい場合
* メモ欄の設定が必要になります。
* このメモ欄の指定方法は以下の通りです。
* <scale:区別名>
*
* 例えば「ミニキャラ」で区別したい場合、イベントのメモ欄に以下のように記述します。
* <scale:ミニキャラ>
*
* この区別名は複数のイベントに同じものを指定することが可能です。
* 複数のイベントに指定した場合、複数のイベントが同時にScale変更の影響を受けます。
*
* 【スクリプト】
* ・キャラクターサイズの一括変更
* $gameSystem.changeCharacterScale(横のScale, 縦のScale);
* 例:横も縦も一括して1.5倍にする
* $gameSystem.changeCharacterScale(1.5, 1.5);
*
* ・現在設定している一括変更分の横のScaleの取得
* $gameSystem.getCharacterScaleX();
*
* ・現在設定している縦の一括変更分のScaleの取得
* $gameSystem.getCharacterScaleY();
*
* ・特定のメモタグが指定されているイベントだけScaleを変更
* $gameSystem.changeCharacterScale(横のScale, 縦のScale, '区別名');
* 例:メモ欄でミニキャラが指定されたイベント郡のScaleを縦も横も0.5倍する
* $gameSystem.changeCharacterScale(0.5, 0.5, 'ミニキャラ');
*
* 【区別名】
* $gameSystem.changeCharacterScale(横のScale, 縦のScale, '区別名')のスクリプトにおいて
* 区別名の指定を省略した場合は暗黙的に「all」が指定されたことになります。
* また、イベント以外のキャラクターを指定するには以下の区別名を指定します。
*
* ・プレイヤーキャラクター:player
* ・フォロワー:follower
* ・乗り物:vehicle
*
* また、区別名には「null」と「all」を使用しないでください。
*
* 【優先順位】
* Scale変更の優先順位は
* 1.個別の区別名で指定したサイズ
* 2.暗黙的に指定されたall(区別名の指定なし)
* の順になります。
*
* 【更新履歴】
* 1.1.0 2019/06/27 Scaleの変更にシンボル名を指定できるようにした。
* 1.0.0 2019/06/26 公開。
*
* 【備考】
* 当プラグインを利用したことによるいかなる損害に対しても、制作者は一切の責任を負わないこととします。
*
* 【利用規約】
* ソースコードの著作権者が自分であると主張しない限り、
* 作者に無断で改変、再配布が可能です。
* 利用形態(商用、18禁利用等)についても制限はありません。
* 自由に使用してください。
*/
(function() {
'use strict';
var pluginName = 'CharacterScaleChanger';
////=============================================================================
//// Local function
//// These functions checks & formats pluguin's command parameters.
//// I borrowed these functions from Triacontane.Thanks!
////=============================================================================
var getParamString = function(paramNames) {
if (!Array.isArray(paramNames)) paramNames = [paramNames];
for (var i = 0; i < paramNames.length; i++) {
var name = PluginManager.parameters(pluginName)[paramNames[i]];
if (name) return name;
}
return '';
};
var getParamNumber = function(paramNames, min, max) {
var value = getParamString(paramNames);
if (arguments.length < 2) min = -Infinity;
if (arguments.length < 3) max = Infinity;
return (parseInt(value) || 0).clamp(min, max);
};
//This function is not written by Triacontane.Tsumio wrote this function !
var convertParam = function(param) {
if(param !== undefined){
try {
return JSON.parse(param);
}catch(e){
console.group();
console.error('%cParameter is invalid ! You should check the following parameter !','background-color: #5174FF');
console.error('Parameter:' + eval(param));
console.error('Error message :' + e);
console.groupEnd();
}
}
};
//This function is not written by Triacontane.Tsumio wrote this function !
var convertArrayParam = function(param) {
if(param !== undefined){
try {
const array = JSON.parse(param);
for(let i = 0; i < array.length; i++) {
array[i] = JSON.parse(array[i]);
}
return array;
}catch(e){
console.group();
console.error('%cParameter is invalid ! You should check the following parameter !','background-color: #5174FF');
console.error('Parameter:' + eval(param));
console.error('Error message :' + e);
console.groupEnd();
}
}
};
/**
* Convert to number.Receive converted JSON object.
* @param {Object} obj
*
*/
//This function is not written by Triacontane.Tsumio wrote this function !
var convertToNumber = function(obj) {
for(var prop in obj) {
obj[prop] = Number(obj[prop]);
}
return obj;
}
////=============================================================================
//// Get and set pluguin parameters.
////=============================================================================
var param = {};
////=============================================================================
//// Game_System
//// スケールのサイズを保存する
////=============================================================================
//初期化時にScaleを保存するオブジェクトを作成
const _Game_System_initialize = Game_System.prototype.initialize;
Game_System.prototype.initialize = function() {
_Game_System_initialize.call(this);
this._characterScaleDict = {};
};
//本当は変更してほしくない。イミュータブルにしたいが……。
Game_System.prototype.characterScaleDict = function() {
if(!this._characterScaleDict) {
this._characterScaleDict = {};
}
return this._characterScaleDict;
};
//スケールの値の保存と適用を同時におこなう
Game_System.prototype.changeCharacterScale = function(scaleX = 1, scaleY = 1, symbol = Game_Scale.ALL_SYMBOL) {
this._setCharacterScale(scaleX, scaleY, symbol);
this._applyCharacterScale(symbol);
};
//XのScaleを取得する
Game_System.prototype.getCharacterScaleX = function(symbol = Game_Scale.ALL_SYMBOL) {
const target = this.characterScaleDict()[symbol];
return target ? target.x : 1;
};
//YのScaleを取得する
Game_System.prototype.getCharacterScaleY = function(symbol = Game_Scale.ALL_SYMBOL) {
const target = this.characterScaleDict()[symbol];
return target ? target.y : 1;
};
//Scaleの変更を適用する
Game_System.prototype._applyCharacterScale = function(symbol = Game_Scale.ALL_SYMBOL) {
if(SceneManager._scene._spriteset) {
const scaleX = this.getCharacterScaleX(symbol);
const scaleY = this.getCharacterScaleY(symbol);
SceneManager._scene._spriteset.setCharacterScale(scaleX, scaleY, symbol);
}
};
//Scaleの変更をModelに保存する
Game_System.prototype._setCharacterScale = function(scaleX = 1, scaleY = 1, symbol = Game_Scale.ALL_SYMBOL) {
const target = this.characterScaleDict()[symbol];
if(!target) {
this.characterScaleDict()[symbol] = new Game_Scale(scaleX, scaleY, symbol);
}
this.characterScaleDict()[symbol].set(scaleX, scaleY);
};
////=============================================================================
//// Game_Character
//// Scaleの設定のためのメモ欄取得機能を基底クラスに追加する
////=============================================================================
//各子クラスでオーバーライドすることを想定
Game_Character.prototype.scaleMeta = function() {
return 'null';
};
////=============================================================================
//// Game_Event
//// Scaleの設定のためのメモ欄取得機能を追加
////=============================================================================
Game_Event.prototype.scaleMeta = function() {
return this.event().meta[Game_Scale.META_NAME] || 'null';
};
////=============================================================================
//// Game_Player
//// Scaleの設定のためのメモ欄取得機能を追加
////=============================================================================
Game_Player.prototype.scaleMeta = function() {
return 'player';
};
////=============================================================================
//// Game_Follower
//// Scaleの設定のためのメモ欄取得機能を追加
////=============================================================================
Game_Follower.prototype.scaleMeta = function() {
return 'follower';
};
////=============================================================================
//// GameVehicle
//// Scaleの設定のためのメモ欄取得機能を追加
////=============================================================================
Game_Vehicle.prototype.scaleMeta = function() {
return 'vehicle';
};
////=============================================================================
//// Spriteset_Map
//// キャラクター郡のサイズを変更する
////=============================================================================
//現在のScaleを適用する
const _Spriteset_Map_createCharacters = Spriteset_Map.prototype.createCharacters;
Spriteset_Map.prototype.createCharacters = function() {
_Spriteset_Map_createCharacters.call(this);
//最初にAllSymbolのスケールを変更
this._changeOnlyAllSymbolSprite();
//その後、AllSymbol以外の別のシンボルを全て変更
this._changeAllCharacterScaleExceptAllSymbol();
};
//Scaleの変更をSpriteに直接セットする
Spriteset_Map.prototype.setCharacterScale = function(scaleX, scaleY, symbol) {
if(symbol === Game_Scale.ALL_SYMBOL) {
this._applyCharacterScale(this._characterSprites, scaleX, scaleY);
}else {
const targetSpriteList = this._characterSprites.filter(sprite => sprite && sprite._character.scaleMeta() === symbol);
this._applyCharacterScale(targetSpriteList, scaleX, scaleY);
}
};
Spriteset_Map.prototype._applyCharacterScale = function(targetSpriteList, scaleX, scaleY) {
targetSpriteList.forEach(sprite => sprite && sprite.scale.set(scaleX, scaleY));
};
//Game_Scale.ALL_SYMBOLのみを変更する
Spriteset_Map.prototype._changeOnlyAllSymbolSprite = function() {
const scaleX = $gameSystem.getCharacterScaleX();
const scaleY = $gameSystem.getCharacterScaleY();
this.setCharacterScale(scaleX, scaleY, Game_Scale.ALL_SYMBOL);
};
//Game_Scale.ALL_SYMBOL以外のシンボルを全て変更適用する
Spriteset_Map.prototype._changeAllCharacterScaleExceptAllSymbol = function() {
const allKeyList = Object.getOwnPropertyNames($gameSystem.characterScaleDict());
const keyList = allKeyList.filter(key => key !== Game_Scale.ALL_SYMBOL);
keyList.forEach(key => {
const scaleMoedl = $gameSystem.characterScaleDict()[key];
const scaleX = scaleMoedl.x;
const scaleY = scaleMoedl.y;
this.setCharacterScale(scaleX, scaleY, key);
});
};
////=============================================================================
//// Game_Scale
//// 倍率を保持するオブジェクト
////=============================================================================
class Game_Scale {
constructor(scaleX = 1, scaleY = 1, symbol = Game_Scale.ALL_SYMBOL) {
this._x = scaleX;
this._y = scaleY;
this._symbol = symbol;
}
/**
* 「全ての要素」を表すシンボル名
*/
static get ALL_SYMBOL() {
return 'all';
}
/**
* イベントのメモ欄で使用するメタタグ名
*/
static get META_NAME() {
return 'scale';
}
get x() {
return this._x;
}
get y() {
return this._y;
}
get symbol() {
return this._symbol;
}
/**
* Scaleを設定する。
* @param {Number} x
* @param {Number} y
*/
set(x = 1, y = 1) {
this._x = x;
this._y = y;
}
}
window[Game_Scale.name] = Game_Scale;
})(); |
'use strict';
import gulp from 'gulp';
import webpack from 'webpack-stream';
import config from '../config';
// use webpack.config.js to build modules
gulp.task('webpack', () => {
return gulp.src(config.paths.js.entry)
.pipe(webpack(require('../webpack.config')))
.pipe(gulp.dest(config.paths.js.dest));
});
|
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { Provider } from 'react-redux'
import configureStore from './src/store'
import App from './src/App'
const store = configureStore({})
// if (process.env.NODE_ENV !== 'production') {
// const { whyDidYouUpdate } = require('why-did-you-update')
// whyDidYouUpdate(React)
// }
const render = (component, selector) =>
ReactDOM.render(
<AppContainer>
<Provider store={store}>{component}</Provider>
</AppContainer>,
document.querySelector(selector),
)
// render(<App />, '#root')
|
// Universal Links (iOS) and depp links (Android) support
function Links(phonegap) {
"use strict";
function onLink(event) {
beyond.navigate(event.path);
}
function onPhonegapReady() {
if (beyond.params.local) {
return;
}
var ul = window.universalLinks;
if (!ul) {
return;
}
ul.subscribe(null, onLink);
}
if (beyond.phonegap.isPhonegap) {
phonegap.done(onPhonegapReady);
}
}
new Links(beyond.phonegap);
|
/**
*/
(function (cornerstoneWADOImageLoader) {
"use strict";
function convertYBRFullByPlane(imageFrame, rgbaBuffer) {
if (imageFrame === undefined) {
throw "decodeRGB: ybrBuffer must not be undefined";
}
if (imageFrame.length % 3 !== 0) {
throw "decodeRGB: ybrBuffer length must be divisble by 3";
}
var numPixels = imageFrame.length / 3;
var rgbaIndex = 0;
var yIndex = 0;
var cbIndex = numPixels;
var crIndex = numPixels * 2;
for (var i = 0; i < numPixels; i++) {
var y = imageFrame[yIndex++];
var cb = imageFrame[cbIndex++];
var cr = imageFrame[crIndex++];
rgbaBuffer[rgbaIndex++] = y + 1.40200 * (cr - 128);// red
rgbaBuffer[rgbaIndex++] = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128); // green
rgbaBuffer[rgbaIndex++] = y + 1.77200 * (cb - 128); // blue
rgbaBuffer[rgbaIndex++] = 255; //alpha
}
}
// module exports
cornerstoneWADOImageLoader.convertYBRFullByPlane = convertYBRFullByPlane;
}(cornerstoneWADOImageLoader)); |
//idyangu
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'idyangu' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'idyangu.services' is found in services.js
// 'idyangu.controllers' is found in controllers.js
// use OcLazy load to load modules on the fly
// angular.module('idyangu', ['idyangu.controllers', 'id-yangu-routes', 'idyangu.directives', ' idyangu.services'])
var app = angular.module('idyangu', ['ui.router', 'idyangu.controllers', ' idyangu.services', 'idyangu.routes', 'idyangu.directives'])
|
import EventEmitter from 'events'
import NetworkHandler from '../src/handler/network'
import eventLog from './__fixtures__/events.json'
class MyEmitter extends EventEmitter {}
test('network handler', () => {
const cdpMock = new MyEmitter()
const handler = new NetworkHandler(cdpMock)
eventLog.forEach((log) => {
if (!log.method) {
return
}
cdpMock.emit(log.method, log.params)
})
expect(handler.requestTypes).toEqual({
Document: { size: 24714, encoded: 0, count: 1 },
Other: { size: 311, encoded: 311, count: 7 }
})
})
|
module.exports = function (path) {
return require((process.env.APP_DIR_FOR_CODE_COVERAGE || '../') + 'lib/' + path);
}; |
import {all, call, put, select, takeEvery} from 'redux-saga/effects';
import {
createClassroomAssignment,
getCourses,
} from '../clients/googleClassroom';
import {createProjectSnapshot} from '../clients/firebase';
import {assignmentCreated, assignmentNotCreated} from '../actions/assignments';
import {coursesFullyLoaded, coursesLoaded} from '../actions/ui';
import {getCourse, getCurrentProject} from '../selectors';
import {generateTextPreview} from '../util/compileProject';
import {createSnapshotUrl} from '../util/exportUrls';
export function* openAssignmentCreator() {
let pageToken;
do {
const {courses, nextPageToken} = yield call(getCourses, pageToken);
yield put(coursesLoaded(courses));
pageToken = nextPageToken;
} while (pageToken);
yield put(coursesFullyLoaded());
}
export function* createAssignment({
payload: {selectedCourseId, dueDate, assignmentState},
}) {
const project = yield select(getCurrentProject);
const snapshotKey = yield call(createProjectSnapshot, project);
const [url, title] = yield all([
call(createSnapshotUrl, snapshotKey),
call(generateTextPreview, project),
]);
const assignmentData = {
courseId: selectedCourseId,
dueDate,
url,
title,
state: assignmentState,
};
try {
const assignment = yield call(createClassroomAssignment, assignmentData);
if (assignment.alternateLink) {
yield put(
assignmentCreated({
url: assignment.alternateLink,
exportType: 'assignment',
}),
);
} else {
const course = yield select(getCourse, selectedCourseId);
yield put(
assignmentCreated({
url: course.alternateLink,
exportType: 'assignment-draft',
}),
);
}
} catch (e) {
yield put(assignmentNotCreated());
}
}
export default function* assignments() {
yield all([
takeEvery('OPEN_ASSIGNMENT_CREATOR', openAssignmentCreator),
takeEvery('CREATE_ASSIGNMENT', createAssignment),
]);
}
|
// # Ghost Data API
// Provides access from anywhere to the Ghost data layer.
//
// Ghost's JSON API is integral to the workings of Ghost, regardless of whether you want to access data internally,
// from a theme, an app, or from an external app, you'll use the Ghost JSON API to do so.
var _ = require('lodash'),
Promise = require('bluebird'),
config = require('../config'),
// Include Endpoints
configuration = require('./configuration'),
db = require('./db'),
mail = require('./mail'),
notifications = require('./notifications'),
posts = require('./posts'),
roles = require('./roles'),
settings = require('./settings'),
tags = require('./tags'),
themes = require('./themes'),
users = require('./users'),
slugs = require('./slugs'),
postType = require('./postType'),
positions = require('./positions'),
positionRelations = require('./positionRelations'),
authentication = require('./authentication'),
uploads = require('./upload'),
dataExport = require('../data/export'),
errors = require('../errors'),
http,
formatHttpErrors,
addHeaders,
cacheInvalidationHeader,
locationHeader,
contentDispositionHeader,
init;
/**
* ### Init
* Initialise the API - populate the settings cache
* @return {Promise(Settings)} Resolves to Settings Collection
*/
init = function () {
return settings.updateSettingsCache();
};
/**
* ### Cache Invalidation Header
* Calculate the header string for the X-Cache-Invalidate: header.
* The resulting string instructs any cache in front of the blog that request has occurred which invalidates any cached
* versions of the listed URIs.
*
* `/*` is used to mean the entire cache is invalid
*
* @private
* @param {Express.request} req Original HTTP Request
* @param {Object} result API method result
* @return {Promise(String)} Resolves to header string
*/
cacheInvalidationHeader = function (req, result) {
var parsedUrl = req._parsedUrl.pathname.replace(/^\/|\/$/g, '').split('/'),
method = req.method,
endpoint = parsedUrl[0],
id = parsedUrl[1],
cacheInvalidate,
jsonResult = result.toJSON ? result.toJSON() : result,
post,
hasStatusChanged,
wasDeleted,
wasPublishedUpdated;
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
if (endpoint === 'settings' || endpoint === 'users' || endpoint === 'db') {
cacheInvalidate = '/*';
} else if (endpoint === 'posts') {
post = jsonResult.posts[0];
hasStatusChanged = post.statusChanged;
wasDeleted = method === 'DELETE';
// Invalidate cache when post was updated but not when post is draft
wasPublishedUpdated = method === 'PUT' && post.status === 'published';
// Remove the statusChanged value from the response
delete post.statusChanged;
// Don't set x-cache-invalidate header for drafts
if (hasStatusChanged || wasDeleted || wasPublishedUpdated) {
cacheInvalidate = '/, /page/*, /rss/, /rss/*, /tag/*, /author/*';
if (id && post.slug) {
return config.urlForPost(settings, post).then(function (postUrl) {
return cacheInvalidate + ', ' + postUrl;
});
}
}
}
}
return Promise.resolve(cacheInvalidate);
};
/**
* ### Location Header
*
* If the API request results in the creation of a new object, construct a Location: header which points to the new
* resource.
*
* @private
* @param {Express.request} req Original HTTP Request
* @param {Object} result API method result
* @return {Promise(String)} Resolves to header string
*/
locationHeader = function (req, result) {
var apiRoot = config.urlFor('api'),
location,
newObject;
if (req.method === 'POST') {
if (result.hasOwnProperty('posts')) {
newObject = result.posts[0];
location = apiRoot + '/posts/' + newObject.id + '/?status=' + newObject.status;
} else if (result.hasOwnProperty('notifications')) {
newObject = result.notifications[0];
location = apiRoot + '/notifications/' + newObject.id;
} else if (result.hasOwnProperty('users')) {
newObject = result.users[0];
location = apiRoot + '/users/' + newObject.id;
}
}
return Promise.resolve(location);
};
/**
* ### Content Disposition Header
* create a header that invokes the 'Save As' dialog in the browser when exporting the database to file. The 'filename'
* parameter is governed by [RFC6266](http://tools.ietf.org/html/rfc6266#section-4.3).
*
* For encoding whitespace and non-ISO-8859-1 characters, you MUST use the "filename*=" attribute, NOT "filename=".
* Ideally, both. Examples: http://tools.ietf.org/html/rfc6266#section-5
*
* We'll use ISO-8859-1 characters here to keep it simple.
*
* @private
* @see http://tools.ietf.org/html/rfc598
* @return {string}
*/
contentDispositionHeader = function () {
return dataExport.fileName().then(function (filename) {
return 'Attachment; filename="' + filename + '"';
});
};
/**
* ### Format HTTP Errors
* Converts the error response from the API into a format which can be returned over HTTP
*
* @private
* @param {Array} error
* @return {{errors: Array, statusCode: number}}
*/
formatHttpErrors = function (error) {
var statusCode = 500,
errors = [];
if (!_.isArray(error)) {
error = [].concat(error);
}
_.each(error, function (errorItem) {
var errorContent = {};
// TODO: add logic to set the correct status code
statusCode = errorItem.code || 500;
errorContent.message = _.isString(errorItem) ? errorItem :
(_.isObject(errorItem) ? errorItem.message : 'Unknown API Error');
errorContent.type = errorItem.type || 'InternalServerError';
errors.push(errorContent);
});
return {errors: errors, statusCode: statusCode};
};
addHeaders = function (apiMethod, req, res, result) {
var ops = [],
cacheInvalidation,
location,
contentDisposition;
cacheInvalidation = cacheInvalidationHeader(req, result)
.then(function addCacheHeader(header) {
if (header) {
res.set({'X-Cache-Invalidate': header});
}
});
ops.push(cacheInvalidation);
if (req.method === 'POST') {
location = locationHeader(req, result)
.then(function addLocationHeader(header) {
if (header) {
res.set({Location: header});
// The location header indicates that a new object was created.
// In this case the status code should be 201 Created
res.status(201);
}
});
ops.push(location);
}
if (apiMethod === db.exportContent) {
contentDisposition = contentDispositionHeader()
.then(function addContentDispositionHeader(header) {
// Add Content-Disposition Header
if (apiMethod === db.exportContent) {
res.set({
'Content-Disposition': header
});
}
});
ops.push(contentDisposition);
}
return Promise.all(ops);
};
/**
* ### HTTP
*
* Decorator for API functions which are called via an HTTP request. Takes the API method and wraps it so that it gets
* data from the request and returns a sensible JSON response.
*
* @public
* @param {Function} apiMethod API method to call
* @return {Function} middleware format function to be called by the route when a matching request is made
*/
http = function (apiMethod) {
return function (req, res) {
// We define 2 properties for using as arguments in API calls:
var object = req.body,
response,
options = _.extend({}, req.files, req.query, req.params, {
context: {
user: (req.user && req.user.id) ? req.user.id : null
}
});
// If this is a GET, or a DELETE, req.body should be null, so we only have options (route and query params)
// If this is a PUT, POST, or PATCH, req.body is an object
if (_.isEmpty(object)) {
object = options;
options = {};
}
return apiMethod(object, options)
// Handle adding headers
.then(function onSuccess(result) {
response = result;
// Add X-Cache-Invalidate header
return addHeaders(apiMethod, req, res, result);
}).then(function () {
// #### Success
// Send a properly formatting HTTP response containing the data with correct headers
res.json(response || {});
}).catch(function onError(error) {
errors.logError(error);
// #### Error
var httpErrors = formatHttpErrors(error);
// Send a properly formatted HTTP response containing the errors
res.status(httpErrors.statusCode).json({errors: httpErrors.errors});
});
};
};
/**
* ## Public API
*/
module.exports = {
// Extras
init: init,
http: http,
// API Endpoints
configuration: configuration,
db: db,
mail: mail,
notifications: notifications,
posts: posts,
roles: roles,
settings: settings,
tags: tags,
themes: themes,
users: users,
slugs: slugs,
authentication: authentication,
uploads: uploads,
postType: postType,
positions: positions,
positionRelations: positionRelations
};
/**
* ## API Methods
*
* Most API methods follow the BREAD pattern, although not all BREAD methods are available for all resources.
* Most API methods have a similar signature, they either take just `options`, or both `object` and `options`.
* For RESTful resources `object` is always a model object of the correct type in the form `name: [{object}]`
* `options` is an object with several named properties, the possibilities are listed for each method.
*
* Read / Edit / Destroy routes expect some sort of identifier (id / slug / key) for which object they are handling
*
* All API methods take a context object as one of the options:
*
* @typedef context
* Context provides information for determining permissions. Usually a user, but sometimes an app, or the internal flag
* @param {Number} user (optional)
* @param {String} app (optional)
* @param {Boolean} internal (optional)
*/
|
'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');
var ComponentServiceGenerator = yeoman.generators.NamedBase.extend({
init: function () {
console.log('Generating a service component called ' + this.name + '.');
},
files: function () {
var dir = 'app/components/' + this.name + '/';
this.mkdir(dir)
this.template('_service.js', dir + this.name + '.js');
this.template('_service-test.js', dir + this.name + '-test.js');
}
});
module.exports = ComponentServiceGenerator; |
export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
export const SELECT_REDDIT = 'SELECT_REDDIT'
export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'
export function selectReddit(reddit) {
return {
type: SELECT_REDDIT,
reddit
}
}
export function invalidateReddit(reddit) {
return {
type: INVALIDATE_REDDIT,
reddit
}
}
export function requestPosts(reddit) {
return {
type: REQUEST_POSTS,
reddit
}
}
export function receivePosts(reddit, posts) {
return {
type: RECEIVE_POSTS,
reddit,
posts,
receivedAt: Date.now()
}
} |
'use strict';
var Config = require('../src/config');
var fs = require('fs');
var sh = require('shelljs');
describe('Config', function() {
var config = new Config();
afterEach(function() {
sh.rm('-rf', './config/');
});
describe('Create config', function() {
it('should call init and isExistOrCreate the methods when creating', function() {
Config.prototype.init = function() {
};
Config.prototype.isExistOrCreate = function() {
};
spyOn(Config.prototype, 'init').and.callThrough();
spyOn(Config.prototype, 'isExistOrCreate').and.callThrough();
var config = new Config();
expect(Config.prototype.init).toHaveBeenCalled();
expect(Config.prototype.isExistOrCreate).toHaveBeenCalled();
});
});
it('should create config data and fs when initing', function() {
expect(config.fs).toBeDefined();
expect(config.config.dirName).toEqual('config/');
expect(config.config.fileName).toEqual('config-manager.json');
});
it('should get path', function() {
var expected = 'config/config-manager.json';
var path = config.getPath();
expect(path).toEqual(expected);
});
it('should create', function() {
config.craeteDir = function() {
};
config.save = function() {
};
spyOn(config, 'craeteDir').and.callThrough();
spyOn(config, 'save').and.callThrough();
config.create();
expect(config.craeteDir).toHaveBeenCalled();
expect(config.save).toHaveBeenCalled();
});
});
|
/*
(c) Copyright 2016-2019 Hewlett Packard Enterprise Development LP
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
const buildD3Chart = require('../../src/charting/chart');
const fs = require("fs");
const path = require("path");
const expect = require("chai").expect;
const chai = require('chai');
chai.should();
describe('Chart', function() {
this.timeout(2900);
let networkMetricList = [
{metricName:'receiveKilobytesPerSec',metricSamples: [ '69', '69', '69']},
{metricName:'transmitKilobytesPerSec',metricSamples: [ '71', '71', '71',]}
];
it('buildD3Chart', (done) => {
let robot = {adapterName: 'shell', logger: {}};
buildD3Chart(robot, 'room', 'result', networkMetricList, 300).then((result) => {
result.should.equal('Adapter shell does not support web file upload.');
expect(fs.existsSync(`result-chart.png`)).to.equal(true);
}).then(() => done());
});
});
|
// HumanizeDuration.js - https://git.io/j0HgmQ
;(function () {
// This has to be defined separately because of a bug: we want to alias
// `gr` and `el` for backwards-compatiblity. In a breaking change, we can
// remove `gr` entirely.
// See https://github.com/EvanHahn/HumanizeDuration.js/issues/143 for more.
var greek = {
y: function (c) { return c === 1 ? 'χρόνος' : 'χρόνια' },
mo: function (c) { return c === 1 ? 'μήνας' : 'μήνες' },
w: function (c) { return c === 1 ? 'εβδομάδα' : 'εβδομάδες' },
d: function (c) { return c === 1 ? 'μέρα' : 'μέρες' },
h: function (c) { return c === 1 ? 'ώρα' : 'ώρες' },
m: function (c) { return c === 1 ? 'λεπτό' : 'λεπτά' },
s: function (c) { return c === 1 ? 'δευτερόλεπτο' : 'δευτερόλεπτα' },
ms: function (c) { return c === 1 ? 'χιλιοστό του δευτερολέπτου' : 'χιλιοστά του δευτερολέπτου' },
decimal: ','
}
var languages = {
ar: {
y: function (c) { return c === 1 ? 'سنة' : 'سنوات' },
mo: function (c) { return c === 1 ? 'شهر' : 'أشهر' },
w: function (c) { return c === 1 ? 'أسبوع' : 'أسابيع' },
d: function (c) { return c === 1 ? 'يوم' : 'أيام' },
h: function (c) { return c === 1 ? 'ساعة' : 'ساعات' },
m: function (c) {
return ['دقيقة', 'دقائق'][getArabicForm(c)]
},
s: function (c) { return c === 1 ? 'ثانية' : 'ثواني' },
ms: function (c) { return c === 1 ? 'جزء من الثانية' : 'أجزاء من الثانية' },
decimal: ','
},
bg: {
y: function (c) { return ['години', 'година', 'години'][getSlavicForm(c)] },
mo: function (c) { return ['месеца', 'месец', 'месеца'][getSlavicForm(c)] },
w: function (c) { return ['седмици', 'седмица', 'седмици'][getSlavicForm(c)] },
d: function (c) { return ['дни', 'ден', 'дни'][getSlavicForm(c)] },
h: function (c) { return ['часа', 'час', 'часа'][getSlavicForm(c)] },
m: function (c) { return ['минути', 'минута', 'минути'][getSlavicForm(c)] },
s: function (c) { return ['секунди', 'секунда', 'секунди'][getSlavicForm(c)] },
ms: function (c) { return ['милисекунди', 'милисекунда', 'милисекунди'][getSlavicForm(c)] },
decimal: ','
},
ca: {
y: function (c) { return 'any' + (c === 1 ? '' : 's') },
mo: function (c) { return 'mes' + (c === 1 ? '' : 'os') },
w: function (c) { return 'setman' + (c === 1 ? 'a' : 'es') },
d: function (c) { return 'di' + (c === 1 ? 'a' : 'es') },
h: function (c) { return 'hor' + (c === 1 ? 'a' : 'es') },
m: function (c) { return 'minut' + (c === 1 ? '' : 's') },
s: function (c) { return 'segon' + (c === 1 ? '' : 's') },
ms: function (c) { return 'milisegon' + (c === 1 ? '' : 's') },
decimal: ','
},
cs: {
y: function (c) { return ['rok', 'roku', 'roky', 'let'][getCzechOrSlovakForm(c)] },
mo: function (c) { return ['měsíc', 'měsíce', 'měsíce', 'měsíců'][getCzechOrSlovakForm(c)] },
w: function (c) { return ['týden', 'týdne', 'týdny', 'týdnů'][getCzechOrSlovakForm(c)] },
d: function (c) { return ['den', 'dne', 'dny', 'dní'][getCzechOrSlovakForm(c)] },
h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodin'][getCzechOrSlovakForm(c)] },
m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getCzechOrSlovakForm(c)] },
s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getCzechOrSlovakForm(c)] },
ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getCzechOrSlovakForm(c)] },
decimal: ','
},
da: {
y: 'år',
mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') },
w: function (c) { return 'uge' + (c === 1 ? '' : 'r') },
d: function (c) { return 'dag' + (c === 1 ? '' : 'e') },
h: function (c) { return 'time' + (c === 1 ? '' : 'r') },
m: function (c) { return 'minut' + (c === 1 ? '' : 'ter') },
s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') },
ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') },
decimal: ','
},
de: {
y: function (c) { return 'Jahr' + (c === 1 ? '' : 'e') },
mo: function (c) { return 'Monat' + (c === 1 ? '' : 'e') },
w: function (c) { return 'Woche' + (c === 1 ? '' : 'n') },
d: function (c) { return 'Tag' + (c === 1 ? '' : 'e') },
h: function (c) { return 'Stunde' + (c === 1 ? '' : 'n') },
m: function (c) { return 'Minute' + (c === 1 ? '' : 'n') },
s: function (c) { return 'Sekunde' + (c === 1 ? '' : 'n') },
ms: function (c) { return 'Millisekunde' + (c === 1 ? '' : 'n') },
decimal: ','
},
el: greek,
en: {
y: function (c) { return 'year' + (c === 1 ? '' : 's') },
mo: function (c) { return 'month' + (c === 1 ? '' : 's') },
w: function (c) { return 'week' + (c === 1 ? '' : 's') },
d: function (c) { return 'day' + (c === 1 ? '' : 's') },
h: function (c) { return 'hour' + (c === 1 ? '' : 's') },
m: function (c) { return 'minute' + (c === 1 ? '' : 's') },
s: function (c) { return 'second' + (c === 1 ? '' : 's') },
ms: function (c) { return 'millisecond' + (c === 1 ? '' : 's') },
decimal: '.'
},
es: {
y: function (c) { return 'año' + (c === 1 ? '' : 's') },
mo: function (c) { return 'mes' + (c === 1 ? '' : 'es') },
w: function (c) { return 'semana' + (c === 1 ? '' : 's') },
d: function (c) { return 'día' + (c === 1 ? '' : 's') },
h: function (c) { return 'hora' + (c === 1 ? '' : 's') },
m: function (c) { return 'minuto' + (c === 1 ? '' : 's') },
s: function (c) { return 'segundo' + (c === 1 ? '' : 's') },
ms: function (c) { return 'milisegundo' + (c === 1 ? '' : 's') },
decimal: ','
},
et: {
y: function (c) { return 'aasta' + (c === 1 ? '' : 't') },
mo: function (c) { return 'kuu' + (c === 1 ? '' : 'd') },
w: function (c) { return 'nädal' + (c === 1 ? '' : 'at') },
d: function (c) { return 'päev' + (c === 1 ? '' : 'a') },
h: function (c) { return 'tund' + (c === 1 ? '' : 'i') },
m: function (c) { return 'minut' + (c === 1 ? '' : 'it') },
s: function (c) { return 'sekund' + (c === 1 ? '' : 'it') },
ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'it') },
decimal: ','
},
fa: {
y: 'سال',
mo: 'ماه',
w: 'هفته',
d: 'روز',
h: 'ساعت',
m: 'دقیقه',
s: 'ثانیه',
ms: 'میلی ثانیه',
decimal: '.'
},
fi: {
y: function (c) { return c === 1 ? 'vuosi' : 'vuotta' },
mo: function (c) { return c === 1 ? 'kuukausi' : 'kuukautta' },
w: function (c) { return 'viikko' + (c === 1 ? '' : 'a') },
d: function (c) { return 'päivä' + (c === 1 ? '' : 'ä') },
h: function (c) { return 'tunti' + (c === 1 ? '' : 'a') },
m: function (c) { return 'minuutti' + (c === 1 ? '' : 'a') },
s: function (c) { return 'sekunti' + (c === 1 ? '' : 'a') },
ms: function (c) { return 'millisekunti' + (c === 1 ? '' : 'a') },
decimal: ','
},
fo: {
y: 'ár',
mo: function (c) { return c === 1 ? 'mánaður' : 'mánaðir' },
w: function (c) { return c === 1 ? 'vika' : 'vikur' },
d: function (c) { return c === 1 ? 'dagur' : 'dagar' },
h: function (c) { return c === 1 ? 'tími' : 'tímar' },
m: function (c) { return c === 1 ? 'minuttur' : 'minuttir' },
s: 'sekund',
ms: 'millisekund',
decimal: ','
},
fr: {
y: function (c) { return 'an' + (c >= 2 ? 's' : '') },
mo: 'mois',
w: function (c) { return 'semaine' + (c >= 2 ? 's' : '') },
d: function (c) { return 'jour' + (c >= 2 ? 's' : '') },
h: function (c) { return 'heure' + (c >= 2 ? 's' : '') },
m: function (c) { return 'minute' + (c >= 2 ? 's' : '') },
s: function (c) { return 'seconde' + (c >= 2 ? 's' : '') },
ms: function (c) { return 'milliseconde' + (c >= 2 ? 's' : '') },
decimal: ','
},
gr: greek,
he: {
y: function (c) { return c === 1 ? 'שנה' : 'שנים' },
mo: function (c) { return c === 1 ? 'חודש' : 'חודשים' },
w: function (c) { return c === 1 ? 'שבוע' : 'שבועות' },
d: function (c) { return c === 1 ? 'יום' : 'ימים' },
h: function (c) { return c === 1 ? 'שעה' : 'שעות' },
m: function (c) { return c === 1 ? 'דקה' : 'דקות' },
s: function (c) { return c === 1 ? 'שניה' : 'שניות' },
ms: function (c) { return c === 1 ? 'מילישנייה' : 'מילישניות' },
decimal: '.'
},
hr: {
y: function (c) {
if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) {
return 'godine'
}
return 'godina'
},
mo: function (c) {
if (c === 1) {
return 'mjesec'
} else if (c === 2 || c === 3 || c === 4) {
return 'mjeseca'
}
return 'mjeseci'
},
w: function (c) {
if (c % 10 === 1 && c !== 11) {
return 'tjedan'
}
return 'tjedna'
},
d: function (c) { return c === 1 ? 'dan' : 'dana' },
h: function (c) {
if (c === 1) {
return 'sat'
} else if (c === 2 || c === 3 || c === 4) {
return 'sata'
}
return 'sati'
},
m: function (c) {
var mod10 = c % 10
if ((mod10 === 2 || mod10 === 3 || mod10 === 4) && (c < 10 || c > 14)) {
return 'minute'
}
return 'minuta'
},
s: function (c) {
if ((c === 10 || c === 11 || c === 12 || c === 13 || c === 14 || c === 16 || c === 17 || c === 18 || c === 19) || (c % 10 === 5)) {
return 'sekundi'
} else if (c % 10 === 1) {
return 'sekunda'
} else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) {
return 'sekunde'
}
return 'sekundi'
},
ms: function (c) {
if (c === 1) {
return 'milisekunda'
} else if (c % 10 === 2 || c % 10 === 3 || c % 10 === 4) {
return 'milisekunde'
}
return 'milisekundi'
},
decimal: ','
},
hu: {
y: 'év',
mo: 'hónap',
w: 'hét',
d: 'nap',
h: 'óra',
m: 'perc',
s: 'másodperc',
ms: 'ezredmásodperc',
decimal: ','
},
id: {
y: 'tahun',
mo: 'bulan',
w: 'minggu',
d: 'hari',
h: 'jam',
m: 'menit',
s: 'detik',
ms: 'milidetik',
decimal: '.'
},
is: {
y: 'ár',
mo: function (c) { return 'mánuð' + (c === 1 ? 'ur' : 'ir') },
w: function (c) { return 'vik' + (c === 1 ? 'a' : 'ur') },
d: function (c) { return 'dag' + (c === 1 ? 'ur' : 'ar') },
h: function (c) { return 'klukkutím' + (c === 1 ? 'i' : 'ar') },
m: function (c) { return 'mínút' + (c === 1 ? 'a' : 'ur') },
s: function (c) { return 'sekúnd' + (c === 1 ? 'a' : 'ur') },
ms: function (c) { return 'millisekúnd' + (c === 1 ? 'a' : 'ur') },
decimal: '.'
},
it: {
y: function (c) { return 'ann' + (c === 1 ? 'o' : 'i') },
mo: function (c) { return 'mes' + (c === 1 ? 'e' : 'i') },
w: function (c) { return 'settiman' + (c === 1 ? 'a' : 'e') },
d: function (c) { return 'giorn' + (c === 1 ? 'o' : 'i') },
h: function (c) { return 'or' + (c === 1 ? 'a' : 'e') },
m: function (c) { return 'minut' + (c === 1 ? 'o' : 'i') },
s: function (c) { return 'second' + (c === 1 ? 'o' : 'i') },
ms: function (c) { return 'millisecond' + (c === 1 ? 'o' : 'i') },
decimal: ','
},
ja: {
y: '年',
mo: '月',
w: '週',
d: '日',
h: '時間',
m: '分',
s: '秒',
ms: 'ミリ秒',
decimal: '.'
},
ko: {
y: '년',
mo: '개월',
w: '주일',
d: '일',
h: '시간',
m: '분',
s: '초',
ms: '밀리 초',
decimal: '.'
},
lo: {
y: 'ປີ',
mo: 'ເດືອນ',
w: 'ອາທິດ',
d: 'ມື້',
h: 'ຊົ່ວໂມງ',
m: 'ນາທີ',
s: 'ວິນາທີ',
ms: 'ມິນລິວິນາທີ',
decimal: ','
},
lt: {
y: function (c) { return ((c % 10 === 0) || (c % 100 >= 10 && c % 100 <= 20)) ? 'metų' : 'metai' },
mo: function (c) { return ['mėnuo', 'mėnesiai', 'mėnesių'][getLithuanianForm(c)] },
w: function (c) { return ['savaitė', 'savaitės', 'savaičių'][getLithuanianForm(c)] },
d: function (c) { return ['diena', 'dienos', 'dienų'][getLithuanianForm(c)] },
h: function (c) { return ['valanda', 'valandos', 'valandų'][getLithuanianForm(c)] },
m: function (c) { return ['minutė', 'minutės', 'minučių'][getLithuanianForm(c)] },
s: function (c) { return ['sekundė', 'sekundės', 'sekundžių'][getLithuanianForm(c)] },
ms: function (c) { return ['milisekundė', 'milisekundės', 'milisekundžių'][getLithuanianForm(c)] },
decimal: ','
},
lv: {
y: function (c) { return ['gads', 'gadi'][getLatvianForm(c)] },
mo: function (c) { return ['mēnesis', 'mēneši'][getLatvianForm(c)] },
w: function (c) { return ['nedēļa', 'nedēļas'][getLatvianForm(c)] },
d: function (c) { return ['diena', 'dienas'][getLatvianForm(c)] },
h: function (c) { return ['stunda', 'stundas'][getLatvianForm(c)] },
m: function (c) { return ['minūte', 'minūtes'][getLatvianForm(c)] },
s: function (c) { return ['sekunde', 'sekundes'][getLatvianForm(c)] },
ms: function (c) { return ['milisekunde', 'milisekundes'][getLatvianForm(c)] },
decimal: ','
},
ms: {
y: 'tahun',
mo: 'bulan',
w: 'minggu',
d: 'hari',
h: 'jam',
m: 'minit',
s: 'saat',
ms: 'milisaat',
decimal: '.'
},
nl: {
y: 'jaar',
mo: function (c) { return c === 1 ? 'maand' : 'maanden' },
w: function (c) { return c === 1 ? 'week' : 'weken' },
d: function (c) { return c === 1 ? 'dag' : 'dagen' },
h: 'uur',
m: function (c) { return c === 1 ? 'minuut' : 'minuten' },
s: function (c) { return c === 1 ? 'seconde' : 'seconden' },
ms: function (c) { return c === 1 ? 'milliseconde' : 'milliseconden' },
decimal: ','
},
no: {
y: 'år',
mo: function (c) { return 'måned' + (c === 1 ? '' : 'er') },
w: function (c) { return 'uke' + (c === 1 ? '' : 'r') },
d: function (c) { return 'dag' + (c === 1 ? '' : 'er') },
h: function (c) { return 'time' + (c === 1 ? '' : 'r') },
m: function (c) { return 'minutt' + (c === 1 ? '' : 'er') },
s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') },
ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') },
decimal: ','
},
pl: {
y: function (c) { return ['rok', 'roku', 'lata', 'lat'][getPolishForm(c)] },
mo: function (c) { return ['miesiąc', 'miesiąca', 'miesiące', 'miesięcy'][getPolishForm(c)] },
w: function (c) { return ['tydzień', 'tygodnia', 'tygodnie', 'tygodni'][getPolishForm(c)] },
d: function (c) { return ['dzień', 'dnia', 'dni', 'dni'][getPolishForm(c)] },
h: function (c) { return ['godzina', 'godziny', 'godziny', 'godzin'][getPolishForm(c)] },
m: function (c) { return ['minuta', 'minuty', 'minuty', 'minut'][getPolishForm(c)] },
s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekund'][getPolishForm(c)] },
ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekund'][getPolishForm(c)] },
decimal: ','
},
pt: {
y: function (c) { return 'ano' + (c === 1 ? '' : 's') },
mo: function (c) { return c === 1 ? 'mês' : 'meses' },
w: function (c) { return 'semana' + (c === 1 ? '' : 's') },
d: function (c) { return 'dia' + (c === 1 ? '' : 's') },
h: function (c) { return 'hora' + (c === 1 ? '' : 's') },
m: function (c) { return 'minuto' + (c === 1 ? '' : 's') },
s: function (c) { return 'segundo' + (c === 1 ? '' : 's') },
ms: function (c) { return 'milissegundo' + (c === 1 ? '' : 's') },
decimal: ','
},
ro: {
y: function (c) { return c === 1 ? 'an' : 'ani' },
mo: function (c) { return c === 1 ? 'lună' : 'luni' },
w: function (c) { return c === 1 ? 'săptămână' : 'săptămâni' },
d: function (c) { return c === 1 ? 'zi' : 'zile' },
h: function (c) { return c === 1 ? 'oră' : 'ore' },
m: function (c) { return c === 1 ? 'minut' : 'minute' },
s: function (c) { return c === 1 ? 'secundă' : 'secunde' },
ms: function (c) { return c === 1 ? 'milisecundă' : 'milisecunde' },
decimal: ','
},
ru: {
y: function (c) { return ['лет', 'год', 'года'][getSlavicForm(c)] },
mo: function (c) { return ['месяцев', 'месяц', 'месяца'][getSlavicForm(c)] },
w: function (c) { return ['недель', 'неделя', 'недели'][getSlavicForm(c)] },
d: function (c) { return ['дней', 'день', 'дня'][getSlavicForm(c)] },
h: function (c) { return ['часов', 'час', 'часа'][getSlavicForm(c)] },
m: function (c) { return ['минут', 'минута', 'минуты'][getSlavicForm(c)] },
s: function (c) { return ['секунд', 'секунда', 'секунды'][getSlavicForm(c)] },
ms: function (c) { return ['миллисекунд', 'миллисекунда', 'миллисекунды'][getSlavicForm(c)] },
decimal: ','
},
uk: {
y: function (c) { return ['років', 'рік', 'роки'][getSlavicForm(c)] },
mo: function (c) { return ['місяців', 'місяць', 'місяці'][getSlavicForm(c)] },
w: function (c) { return ['тижнів', 'тиждень', 'тижні'][getSlavicForm(c)] },
d: function (c) { return ['днів', 'день', 'дні'][getSlavicForm(c)] },
h: function (c) { return ['годин', 'година', 'години'][getSlavicForm(c)] },
m: function (c) { return ['хвилин', 'хвилина', 'хвилини'][getSlavicForm(c)] },
s: function (c) { return ['секунд', 'секунда', 'секунди'][getSlavicForm(c)] },
ms: function (c) { return ['мілісекунд', 'мілісекунда', 'мілісекунди'][getSlavicForm(c)] },
decimal: ','
},
ur: {
y: 'سال',
mo: function (c) { return c === 1 ? 'مہینہ' : 'مہینے' },
w: function (c) { return c === 1 ? 'ہفتہ' : 'ہفتے' },
d: 'دن',
h: function (c) { return c === 1 ? 'گھنٹہ' : 'گھنٹے' },
m: 'منٹ',
s: 'سیکنڈ',
ms: 'ملی سیکنڈ',
decimal: '.'
},
sk: {
y: function (c) { return ['rok', 'roky', 'roky', 'rokov'][getCzechOrSlovakForm(c)] },
mo: function (c) { return ['mesiac', 'mesiace', 'mesiace', 'mesiacov'][getCzechOrSlovakForm(c)] },
w: function (c) { return ['týždeň', 'týždne', 'týždne', 'týždňov'][getCzechOrSlovakForm(c)] },
d: function (c) { return ['deň', 'dni', 'dni', 'dní'][getCzechOrSlovakForm(c)] },
h: function (c) { return ['hodina', 'hodiny', 'hodiny', 'hodín'][getCzechOrSlovakForm(c)] },
m: function (c) { return ['minúta', 'minúty', 'minúty', 'minút'][getCzechOrSlovakForm(c)] },
s: function (c) { return ['sekunda', 'sekundy', 'sekundy', 'sekúnd'][getCzechOrSlovakForm(c)] },
ms: function (c) { return ['milisekunda', 'milisekundy', 'milisekundy', 'milisekúnd'][getCzechOrSlovakForm(c)] },
decimal: ','
},
sv: {
y: 'år',
mo: function (c) { return 'månad' + (c === 1 ? '' : 'er') },
w: function (c) { return 'veck' + (c === 1 ? 'a' : 'or') },
d: function (c) { return 'dag' + (c === 1 ? '' : 'ar') },
h: function (c) { return 'timm' + (c === 1 ? 'e' : 'ar') },
m: function (c) { return 'minut' + (c === 1 ? '' : 'er') },
s: function (c) { return 'sekund' + (c === 1 ? '' : 'er') },
ms: function (c) { return 'millisekund' + (c === 1 ? '' : 'er') },
decimal: ','
},
tr: {
y: 'yıl',
mo: 'ay',
w: 'hafta',
d: 'gün',
h: 'saat',
m: 'dakika',
s: 'saniye',
ms: 'milisaniye',
decimal: ','
},
th: {
y: 'ปี',
mo: 'เดือน',
w: 'อาทิตย์',
d: 'วัน',
h: 'ชั่วโมง',
m: 'นาที',
s: 'วินาที',
ms: 'มิลลิวินาที',
decimal: '.'
},
vi: {
y: 'năm',
mo: 'tháng',
w: 'tuần',
d: 'ngày',
h: 'giờ',
m: 'phút',
s: 'giây',
ms: 'mili giây',
decimal: ','
},
zh_CN: {
y: '年',
mo: '个月',
w: '周',
d: '天',
h: '小时',
m: '分钟',
s: '秒',
ms: '毫秒',
decimal: '.'
},
zh_TW: {
y: '年',
mo: '個月',
w: '周',
d: '天',
h: '小時',
m: '分鐘',
s: '秒',
ms: '毫秒',
decimal: '.'
}
}
// You can create a humanizer, which returns a function with default
// parameters.
function humanizer (passedOptions) {
var result = function humanizer (ms, humanizerOptions) {
var options = extend({}, result, humanizerOptions || {})
return doHumanization(ms, options)
}
return extend(result, {
language: 'en',
delimiter: ', ',
spacer: ' ',
conjunction: '',
serialComma: true,
units: ['y', 'mo', 'w', 'd', 'h', 'm', 's'],
languages: {},
round: false,
unitMeasures: {
y: 31557600000,
mo: 2629800000,
w: 604800000,
d: 86400000,
h: 3600000,
m: 60000,
s: 1000,
ms: 1
}
}, passedOptions)
}
// The main function is just a wrapper around a default humanizer.
var humanizeDuration = humanizer({})
// Build dictionary from options
function getDictionary (options) {
var languagesFromOptions = [options.language]
if (has(options, 'fallbacks')) {
if (isArray(options.fallbacks) && options.fallbacks.length) {
languagesFromOptions = languagesFromOptions.concat(options.fallbacks)
} else {
throw new Error('fallbacks must be an array with at least one element')
}
}
for (var i = 0; i < languagesFromOptions.length; i++) {
var languageToTry = languagesFromOptions[i]
if (has(options.languages, languageToTry)) {
return options.languages[languageToTry]
} else if (has(languages, languageToTry)) {
return languages[languageToTry]
}
}
throw new Error('No language found.')
}
// doHumanization does the bulk of the work.
function doHumanization (ms, options) {
var i, len, piece
// Make sure we have a positive number.
// Has the nice sideffect of turning Number objects into primitives.
ms = Math.abs(ms)
var dictionary = getDictionary(options)
var pieces = []
// Start at the top and keep removing units, bit by bit.
var unitName, unitMS, unitCount
for (i = 0, len = options.units.length; i < len; i++) {
unitName = options.units[i]
unitMS = options.unitMeasures[unitName]
// What's the number of full units we can fit?
if (i + 1 === len) {
if (has(options, 'maxDecimalPoints')) {
// We need to use this expValue to avoid rounding functionality of toFixed call
var expValue = Math.pow(10, options.maxDecimalPoints)
var unitCountFloat = (ms / unitMS)
unitCount = parseFloat((Math.floor(expValue * unitCountFloat) / expValue).toFixed(options.maxDecimalPoints))
} else {
unitCount = ms / unitMS
}
} else {
unitCount = Math.floor(ms / unitMS)
}
// Add the string.
pieces.push({
unitCount: unitCount,
unitName: unitName
})
// Remove what we just figured out.
ms -= unitCount * unitMS
}
var firstOccupiedUnitIndex = 0
for (i = 0; i < pieces.length; i++) {
if (pieces[i].unitCount) {
firstOccupiedUnitIndex = i
break
}
}
if (options.round) {
var ratioToLargerUnit, previousPiece
for (i = pieces.length - 1; i >= 0; i--) {
piece = pieces[i]
piece.unitCount = Math.round(piece.unitCount)
if (i === 0) { break }
previousPiece = pieces[i - 1]
ratioToLargerUnit = options.unitMeasures[previousPiece.unitName] / options.unitMeasures[piece.unitName]
if ((piece.unitCount % ratioToLargerUnit) === 0 || (options.largest && ((options.largest - 1) < (i - firstOccupiedUnitIndex)))) {
previousPiece.unitCount += piece.unitCount / ratioToLargerUnit
piece.unitCount = 0
}
}
}
var result = []
for (i = 0, pieces.length; i < len; i++) {
piece = pieces[i]
if (piece.unitCount) {
result.push(render(piece.unitCount, piece.unitName, dictionary, options))
}
if (result.length === options.largest) { break }
}
if (result.length) {
if (!options.conjunction || result.length === 1) {
return result.join(options.delimiter)
} else if (result.length === 2) {
return result.join(options.conjunction)
} else if (result.length > 2) {
return result.slice(0, -1).join(options.delimiter) + (options.serialComma ? ',' : '') + options.conjunction + result.slice(-1)
}
} else {
return render(0, options.units[options.units.length - 1], dictionary, options)
}
}
function render (count, type, dictionary, options) {
var decimal
if (has(options, 'decimal')) {
decimal = options.decimal
} else if (has(dictionary, 'decimal')) {
decimal = dictionary.decimal
} else {
decimal = '.'
}
var countStr = count.toString().replace('.', decimal)
var dictionaryValue = dictionary[type]
var word
if (typeof dictionaryValue === 'function') {
word = dictionaryValue(count)
} else {
word = dictionaryValue
}
return countStr + options.spacer + word
}
function extend (destination) {
var source
for (var i = 1; i < arguments.length; i++) {
source = arguments[i]
for (var prop in source) {
if (has(source, prop)) {
destination[prop] = source[prop]
}
}
}
return destination
}
// Internal helper function for Polish language.
function getPolishForm (c) {
if (c === 1) {
return 0
} else if (Math.floor(c) !== c) {
return 1
} else if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) {
return 2
} else {
return 3
}
}
// Internal helper function for Russian and Ukranian languages.
function getSlavicForm (c) {
if (Math.floor(c) !== c) {
return 2
} else if ((c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0) {
return 0
} else if (c % 10 === 1) {
return 1
} else if (c > 1) {
return 2
} else {
return 0
}
}
// Internal helper function for Slovak language.
function getCzechOrSlovakForm (c) {
if (c === 1) {
return 0
} else if (Math.floor(c) !== c) {
return 1
} else if (c % 10 >= 2 && c % 10 <= 4 && c % 100 < 10) {
return 2
} else {
return 3
}
}
// Internal helper function for Lithuanian language.
function getLithuanianForm (c) {
if (c === 1 || (c % 10 === 1 && c % 100 > 20)) {
return 0
} else if (Math.floor(c) !== c || (c % 10 >= 2 && c % 100 > 20) || (c % 10 >= 2 && c % 100 < 10)) {
return 1
} else {
return 2
}
}
// Internal helper function for Latvian language.
function getLatvianForm (c) {
if (c === 1 || (c % 10 === 1 && c % 100 !== 11)) {
return 0
} else {
return 1
}
}
// Internal helper function for Arabic language.
function getArabicForm (c) {
if (c <= 2) { return 0 }
if (c > 2 && c < 11) { return 1 }
return 0
}
// We need to make sure we support browsers that don't have
// `Array.isArray`, so we define a fallback here.
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]'
}
function has (obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key)
}
humanizeDuration.getSupportedLanguages = function getSupportedLanguages () {
var result = []
for (var language in languages) {
if (has(languages, language) && language !== 'gr') {
result.push(language)
}
}
return result
}
humanizeDuration.humanizer = humanizer
if (typeof define === 'function' && define.amd) {
define(function () {
return humanizeDuration
})
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = humanizeDuration
} else {
this.humanizeDuration = humanizeDuration
}
})(); // eslint-disable-line semi
|
module.exports = function(FileModel) {
};
|
"use strict";
const _ = require('lodash');
const request = require('request-promise');
const Promise = require('bluebird');
const RequestParameters = require('./request-parameters');
const uriTemplate = _.template('Vanguard/Grimoire/${membershipType}/${membershipId}/');
const parameters = new RequestParameters([{
"required": true,
"type": "path",
"name": "membershipType"
}, {
"required": true,
"type": "path",
"name": "membershipId"
}, {
"required": false,
"type": "query",
"name": "definitions"
}, {
"required": false,
"type": "query",
"name": "flavour"
}, {
"required": false,
"type": "query",
"name": "single"
}]);
class AccountGrimoireRequest {
constructor(apiKey, values) {
this.apiKey = apiKey;
_.defaults(this, parameters.defaults());
_.merge(this, values);
}
execute(host) {
let error = parameters.validate(this);
if (error) {
return Promise.reject(error);
}
let options = parameters.buildOptions(this);
let uri = (host || '') + uriTemplate(options.path);
return request({
uri: uri,
method: 'GET',
headers: {
'x-api-key': this.apiKey
},
qs: _.isEmpty(options.query) ? undefined : options.query,
body: _.isEmpty(options.body) ? undefined : options.body,
json: true
});
}
validate() {
return parameters.validate(this);
}
}
module.exports = AccountGrimoireRequest;
|
var fs = require('fs'),
path = require('path'),
os = require('os'),
vfs = require('../lib/fs'),
tmpDir = os.tmpdir || os.tmpDir || function() { return '/tmp'; },
TEST_DIR = path.join(__dirname, 'test-dir');
module.exports = {
setUp : function(done) {
fs.mkdirSync(TEST_DIR);
done();
},
tearDown : function(done) {
fs.rmdirSync(TEST_DIR);
done();
},
'should make temporary file with default options' : function(test) {
var filePath;
vfs.makeTmpFile()
.then(
function(_filePath) {
return vfs.exists(filePath = _filePath);
},
function() {
test.ok(false);
throw Error();
})
.then(function(exists) {
fs.unlinkSync(filePath);
test.strictEqual(path.dirname(filePath), path.resolve(tmpDir()));
test.strictEqual(path.extname(filePath), '.tmp');
test.ok(exists);
})
.always(function() {
test.done();
});
},
'should make temporary file in custom directory' : function(test) {
var filePath;
vfs.makeTmpFile({ dir : TEST_DIR })
.then(
function(_filePath) {
return vfs.exists(filePath = _filePath);
},
function() {
test.ok(false);
throw Error();
})
.then(function(exists) {
fs.unlinkSync(filePath);
test.ok(exists);
test.strictEqual(path.dirname(filePath), TEST_DIR);
})
.always(function() {
test.done();
})
},
'should make temporary file with custom prefix' : function(test) {
var filePath;
vfs.makeTmpFile({ prefix : '__prefix' })
.then(
function(_filePath) {
return vfs.exists(filePath = _filePath);
},
function() {
test.ok(false);
throw Error();
})
.then(function(exists) {
fs.unlinkSync(filePath);
test.ok(exists);
test.ok(filePath.indexOf('__prefix') > -1);
})
.always(function() {
test.done();
})
},
'should make temporary file with custom extension' : function(test) {
var filePath;
vfs.makeTmpFile({ ext : '.css' })
.then(
function(_filePath) {
return vfs.exists(filePath = _filePath);
},
function() {
test.ok(false);
throw Error();
})
.then(function(exists) {
fs.unlinkSync(filePath);
test.ok(exists);
test.strictEqual(path.extname(filePath), '.css');
})
.always(function() {
test.done();
})
}
}; |
/**
* @author alteredq / http://alteredqualia.com/
*/
var Clock = function(autoStart) {
this.autoStart = (autoStart !== undefined) ? autoStart : true;
this.startTime = 0;
this.oldTime = 0;
this.elapsedTime = 0;
this.running = false;
}
Object.assign(Clock.prototype, {
start: function() {
this.startTime = (typeof performance === 'undefined' ? Date : performance).now();
this.oldTime = this.startTime;
this.elapsedTime = 0;
this.running = true;
},
stop: function() {
this.getElapsedTime();
this.running = false;
this.autoStart = false;
},
getElapsedTime: function() {
this.getDelta();
return this.elapsedTime;
},
getDelta: function() {
var diff = 0;
if (this.autoStart && !this.running) {
this.start();
return 0;
}
if (this.running) {
var newTime = (typeof performance === 'undefined' ? Date : performance).now();
diff = (newTime - this.oldTime) / 1000;
this.oldTime = newTime;
this.elapsedTime += diff;
}
return diff;
}
});
export { Clock }; |
'use strict';
var exec = require('child_process').exec,
MotorBoat = require('motorboat'),
CommandError = require('./command/command-error');
function SpeedBoat(options) {
MotorBoat.call(this, options);
}
SpeedBoat.prototype = Object.create(MotorBoat.prototype);
SpeedBoat.prototype.constructor = SpeedBoat;
SpeedBoat.prototype.plot = function (boxId, cmd, cb) {
var self = this;
var plot = function (cb) {
console.log('running command:', cmd);
self.runInstanceCommand(boxId, cmd, function (err, result) {
if (err) {
var error = new CommandError('unable to run command: ' + err.toString(), cmd);
error.innerError = err;
return cb(err);
}
cb(null, result);
});
};
/*
* If we have a callback already, invoke the plot and
* let the callback handle the result
*/
if (cb) {
return plot(cb);
}
/*
* If we don't have a callback, the plot will be used
* elsewhere (e.g., in an async.* method)
*/
return plot;
};
SpeedBoat.prototype.purgeKnownHost = function (ipAddress, knownHostsPath, cb) {
var cmd = ('ssh-keygen -f "%s" -R %s')
.replace('%s', knownHostsPath)
.replace('%s', ipAddress);
console.info('purging known host', cmd);
exec(cmd, function (err, stdout, stderr) {
if (err) {
console.error(stderr.toString());
return cb(err);
}
console.info((stdout || '').toString());
cb();
});
};
module.exports = SpeedBoat; |
var collide = require('../');
var test = require('tape');
test('collisions', function (t) {
var a = { left: 4, right: 8, top: 100, bottom: 140 };
var b = { left: 6, top: 90, height: 20, width: 1 };
var c = { x: -3, y: 20, width: 400, height: 300 };
var d = { x: 2, y: 8 };
var e = { x: 0, y: 0, width: 10, height: 10};
t.equal(collide(a,b), false, 'a,b -> false');
t.equal(collide(a,c), true, 'a,c -> true');
t.equal(collide(a,d), false, 'a,d -> false');
t.equal(collide(b,c), true, 'b,c -> true');
t.equal(collide(b,d), false, 'b,d -> false');
t.equal(collide(c,d), false, 'c,d -> false');
t.equal(collide(d,e), true, 'd,e -> true');
t.end();
});
|
const { readFileSync, writeFileSync } = require('fs')
const { resolve } = require('path')
const { version } = require('../../package.json')
const MANIFEST_PATH = resolve(__dirname, '../../assets/manifest.json')
const TARGET_PATH = resolve(__dirname, '../../build/manifest.json')
function getContent() {
const manifestJSON = JSON.parse(readFileSync(MANIFEST_PATH))
manifestJSON.version = version
manifestJSON.background.persistent = false
return JSON.stringify(manifestJSON, null, 2)
}
function writeManifest() {
const content = getContent()
writeFileSync(TARGET_PATH, content)
}
if (require.main === module) {
writeManifest()
}
|
/**
* Created by hstancu on 11/18/2016.
*/
function divshow(url_name, backup_name) {
document.getElementById("divPicture").style.backgroundImage = "url('" + url_name + "'),url('" + backup_name + "')";
document.getElementById("divPicture").style.backgroundRepeat = "no-repeat";
document.getElementById("divPicture").style.backgroundPosition = "center center";
document.getElementById("divPicture").style.backgroundSize = "cover"
//document.getElementById("divPicture").style.background="#ffffff url('" +url_name +"') no-repeat center";
$('#viewprofilepic').modal();
}
function parameterExists(page) {
var field = page;
var url = window.location.href;
if (url.indexOf('?' + field + '=') != -1)
return true;
else if (url.indexOf('&' + field + '=') != -1)
return true;
return false;
}
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
/*function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("?")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}*/
$(document).ready(function () {
/* if($('#field').is(':disabled')){
$('#go_btn').prop('disabled', true);
}*/
$('#field').one('change', function() {
$('#search').prop('disabled', false);
});
if (parameterExists("field") == true) {
$('#field').val(findGetParameter("field"));
}
if (parameterExists("search") == true) {
$('#search').val(findGetParameter("search"));
}
$('#go_btn').attr('disabled', true);
if ($("#search")[0].value =='') {
$('#search').attr('disabled', true);
}else{
$('#search').attr('disabled', false);
}
/* //if ($("#field ")[0].selectedIndex == 0) {
if ($("#field")[0].value == 'filter') {
$('#search').attr('disabled', true);
}else{
$('#search').attr('disabled', false);
}*/
$('input[name="search"]').on('keyup',function() {
var search_value = $('input[name="search"]').val();
if(search_value != '') {
$('#go_btn').attr('disabled' , false);
}else{
$('#go_btn').attr('disabled' , true);
}
});
$(".to_home").click(function () {
location.href='/UpWeGo/admin';
});
$(".log_out").click(function () {
logout();
});
function filterBy(){
$.ajax({
url: base_url + "admin/filterBy",
data: $('#filter').serializeArray(),
dataType: 'json',
success: function (response) {
if(response.success){
location.href = "/UpWeGo";
}else{
location.href = "/UpWeGo";
}
},
type: 'POST'
});
}
function logout() {
$.ajax({
url: base_url + "login/logout",
dataType: 'json',
success: function (response) {
if(response.success){
location.href = "/UpWeGo";
}else{
alert("Ceva nu a mers bine, inapoi la login");
location.href = "/UpWeGo";
}
},
type: 'POST'
});
}
/*if (parameterExists("page") == true && parseInt(findGetParameter("page")) > parseInt(document.getElementById('pageCount').textContent)) { // only for manual changing the url
var x=findGetParameter("page");
alert(x.match(/^\d+$/));
if (findGetParameter("page").match(/^\d+$/)) {
var items = document.getElementById('rows_per_page').value;
var max = document.getElementById('pageCount').textContent;
max = parseInt(max);
var go = "pageindex?page=" + max + "&items=" + items;
window.location.href = go;
}else{
alert('Invalid URL'); // not working..
}
}*/
if (parameterExists("page") == false) {
$("#list-1").addClass("active");
} else {
$("#list-" + findGetParameter("page")).addClass("active"); //// ATENTIE ! AICI PREIA #list-4&items in loc de 4 doar !
}
if (parameterExists("items") == true) {
$('input[name=rows_per_page]').val(findGetParameter("items"));
}
//.$_GET["field"]."&search=".$_GET["search"]
// var field = document.getElementById('field').value;
// var search = document.getElementById('search').value;
$("#goto_page").on('keyup', function (e) {
if (e.keyCode == 13) {
var page = document.getElementById('goto_page').value;
var items = document.getElementById('rows_per_page').value;
var max = document.getElementById('pageCount').textContent.substring(1);
if(parameterExists("field") == true && parameterExists("search")){
var field=findGetParameter("field");
var search=findGetParameter("search");
/*alert(page);
alert(items);
alert(max);
alert(field);
alert(search);*/
if (page.match(/^\d+$/) && parseInt(page)>0) {
page = parseInt(page);
max = parseInt(max);
if (page > max) {
if (parameterExists("page") == true) {
var go = "pageindex?page=" + max + "&items=" + items + "&field=" + field + "&search=" + search; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
else {
var go = "admin/pageindex?page=" + max + "&items=" + items + "&field=" + field + "&search=" + search ; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
}
else {
if (parameterExists("page") == true) {
var go = "pageindex?page=" + page + "&items=" + items + "&field=" + field + "&search=" + search; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
else {
var go = "admin/pageindex?page=" + page + "&items=" + items + "&field=" + field + "&search=" + search; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
}
}
else {
alert('Cannot send to this page! Please use only positive natural numbers.');
}
}else {
//alert(page);
//alert(items);
//alert(max);
if (page.match(/^\d+$/) && parseInt(page) > 0) {
page = parseInt(page);
max = parseInt(max);
if (page > max) {
if (parameterExists("page") == true) {
var go = "pageindex?page=" + max + "&items=" + items; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
else {
var go = "admin/pageindex?page=" + max + "&items=" + items; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
}
else {
if (parameterExists("page") == true) {
var go = "pageindex?page=" + page + "&items=" + items; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
else {
var go = "admin/pageindex?page=" + page + "&items=" + items; // cum de nu trebuie sa scriu si admin/pagein.... ?
window.location.href = go;
}
}
}
else {
alert('Cannot send to this page! Please use only positive natural numbers.');
}
}
}
});
$("#rows_per_page").on('keyup', function (e) {
if (e.keyCode == 13) {
//var page= $("#goto_page").val();
var items = $('#rows_per_page').val();
//var max = $("#pageCount").val();
//var max = document.getElementById('pageCount').value;
if(parameterExists("field") == true && parameterExists("search")) {
var field = findGetParameter("field");
var search = findGetParameter("search");
if (items.match(/^\d+$/) && parseInt(items) > 0) {
items = parseInt(items);
if (parameterExists("page") == false) {
var go = "admin/pageindex?page=1" + "&items=" + items + "&field=" + field + "&search=" + search;
window.location.href = go;
} else {
//var go="pageindex?page="+findGetParameter("page")+"&items="+items;
var go = "pageindex?page=1" + "&items=" + items + "&field=" + field + "&search=" + search;
window.location.href = go;
}
}
else {
alert('Please use only positive natural numbers.');
}
}else{
if (items.match(/^\d+$/) && parseInt(items) > 0) {
items = parseInt(items);
if (parameterExists("page") == false) {
var go = "admin/pageindex?page=1" + "&items=" + items;
window.location.href = go;
} else {
//var go="pageindex?page="+findGetParameter("page")+"&items="+items;
var go = "pageindex?page=1" + "&items=" + items;
window.location.href = go;
}
}
else {
alert('Please use only positive natural numbers.');
}
}
}
});
});
|
app.factory('Routine', ['DataModel', 'Config', '$http',
function (DataModel, Config, $http) {
// Constructor
function Routine(data) {
if (data) {
this.setData(data);
}
};
// Methods
Routine.prototype = new DataModel(Config.HostServices + "/api/Routine");
Routine.prototype.GetLastRoutine = function () {
var $this = this;
return $http.get($this.url + '/GetLastRoutine/').success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.GetByClientId = function (id) {
var $this = this;
return $http.get($this.url + '/GetByClientId/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
Routine.prototype.HistoryClient = function (id) {
var $this = this;
return $http.get($this.url + '/HistoryClient/' + id).success(function (response) {
if (response && response.Status == 0) {
angular.extend($this, response.Result);
}
});
};
return Routine;
}
]); |
Clazz.declarePackage ("J.shape");
Clazz.load (["J.shape.AtomShape"], "J.shape.Halos", ["JU.BSUtil", "$.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.colixSelection = 2;
this.bsHighlight = null;
this.colixHighlight = 10;
Clazz.instantialize (this, arguments);
}, J.shape, "Halos", J.shape.AtomShape);
Clazz.defineMethod (c$, "initState",
function () {
this.translucentAllowed = false;
});
Clazz.overrideMethod (c$, "setProperty",
function (propertyName, value, bs) {
if ("translucency" === propertyName) return;
if ("argbSelection" === propertyName) {
this.colixSelection = JU.C.getColix ((value).intValue ());
return;
}if ("argbHighlight" === propertyName) {
this.colixHighlight = JU.C.getColix ((value).intValue ());
return;
}if ("highlight" === propertyName) {
this.bsHighlight = value;
return;
}if (propertyName === "deleteModelAtoms") {
JU.BSUtil.deleteBits (this.bsHighlight, bs);
}this.setPropAS (propertyName, value, bs);
}, "~S,~O,JU.BS");
Clazz.overrideMethod (c$, "setModelVisibilityFlags",
function (bs) {
var bsSelected = (this.vwr.getSelectionHalosEnabled () ? this.vwr.bsA () : null);
for (var i = this.ac; --i >= 0; ) this.atoms[i].setShapeVisibility (this.vf, bsSelected != null && bsSelected.get (i) || this.mads != null && this.mads[i] != 0);
}, "JU.BS");
Clazz.overrideMethod (c$, "getShapeState",
function () {
return this.vwr.getShapeState (this);
});
});
|
import Ember from 'ember';
import { task, drop, restartable, enqueue, maxConcurrency } from 'ember-concurrency';
import {
enqueueTasksPolicy,
dropQueuedTasksPolicy,
cancelOngoingTasksPolicy,
} from 'ember-concurrency/-buffer-policy';
let decorators = { drop, restartable, enqueue };
const decoratorPolicies = [
['drop', dropQueuedTasksPolicy],
['enqueue', enqueueTasksPolicy],
['restartable', cancelOngoingTasksPolicy],
];
module('Unit: decorators');
decoratorPolicies.forEach(([decoratorName, bufferPolicy]) => {
let decorator = decorators[decoratorName];
decoratorTest(`${decoratorName}`, decorator, bufferPolicy);
decoratorTest(`${decoratorName}()`, decorator(), bufferPolicy);
});
function decoratorTest(decoratorName, decorator, bufferPolicy) {
test(`task accepts ${decoratorName} as a decorator arg`, function(assert) {
assert.expect(1);
let Obj = Ember.Object.extend({
myTask: task(decorator, function * () { }),
});
Ember.run(() => {
let obj = Obj.create();
let task = obj.get('myTask');
assert.equal(task.bufferPolicy, bufferPolicy);
});
});
}
test(`task accepts maxConcurrency as a decorator arg`, function(assert) {
assert.expect(1);
let Obj = Ember.Object.extend({
myTask: task(maxConcurrency(5), function * () { }),
});
Ember.run(() => {
let obj = Obj.create();
let task = obj.get('myTask');
assert.equal(task._maxConcurrency, 5);
});
});
|
/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/jquery/dist/jquery.js');
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
return app.toTree();
};
|
describe('Tesselation', function() {
var myBase, myTess;
beforeEach(function() {
myBase = new Polygon(60, 60, 60, 0, 6);
myTess = new Tesselation(60,60, myBase, 3, true);
});
describe('init', function() {
it('initalizes with a baseGon', function() {
expect(myTess.baseGon).toBe(myBase);
});
it('initializes with a depth', function() {
expect(myTess.depth).toBe(3);
});
it('initializes with a propFlag', function() {
expect(myTess.propFlag).toBe(true);
});
it('initializes with a baseAngle', function() {
expect(myTess.baseAngle).toBe(myBase.baseAngle);
});
it('initializes with a apoOffset', function() {
expect(myTess.apoOffset).toBe(myBase.apoOffset);
});
it('initializes with a cx', function() {
expect(myTess.cx).toBe(60);
});
it('initializes with a cy', function() {
expect(myTess.cy).toBe(60);
});
it('initializes with a radius', function() {
expect(myTess.radius).toBeNumber();
});
it('initializes with a rotation', function() {
expect(myTess.rotation).toBeNumber();
});
it('initializes with a sideCount', function() {
expect(myTess.sideCount).toBe(6);
});
});
describe('subclass', function() {
it('inherits methods from Polygon', function() {
expect(myTess instanceof Polygon).toBeTrue();
});
describe('update', function() {
it('calls the Polygon::update method', function() {
myTess.update();
expect(myTess.vertices).toBeArray();
});
});
});
}); |
packages[pkg] !== "read-write";
|
/* globals Polymer:false, console:false */
'use strict';
Polymer('vege-table-leaf', {
value: null,
stringValue: null,
type: '',
specialType: true,
specialTypes: ['json', 'html', 'xml', 'url', 'object', 'image', 'element', 'counts'],
typeChanged: function() {
this.specialType = (this.specialTypes.indexOf(this.type) !== -1);
},
valueChanged: function() {
this.stringValue = this.convert();
if (this.type == 'element') {
this.$.element.innerHTML = '';
this.$.element.appendChild(this.stringValue);
}
},
convert: function() {
if (this.value === null || this.value === undefined) {
return null;
}
switch (this.type) {
//case 'json':
//return JSON.stringify(this.value, null, ' ');
case 'number':
return Math.round(this.value);
case 'list':
return this.value ? this.value.slice(0, 25).join('\n') : null; // TODO: remove slice
case 'date':
return this.value.toLocaleDateString(); // TODO: format
case 'element':
var element = document.createElement(this.value[0]);
var attributes = this.value[1];
Object.keys(attributes).forEach(function(key) {
element[key] = attributes[key];
});
return element;
//case 'url':
//return this.value.href;
//this.$.element.appendChild(element);
//return;
//var blob = new Blob([div.innerHTML], { type: 'text/html' });
//return URL.createObjectURL(blob);
default:
return this.value;
}
},
showObject: function() {
var value = this.value;
this.fire('show-object', {
path: this.leafName,
items: Object.keys(value).map(function(key) {
return {
key: key,
value: JSON.stringify(value[key], null, ' ')
};
})
});
}
}); |
/**
* @license
* PlayCanvas Engine v1.50.0 revision e397e986a
* Copyright 2011-2021 PlayCanvas Ltd. All rights reserved.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pcx = {}));
})(this, (function (exports) { 'use strict';
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
var CpuTimer = function () {
function CpuTimer(app) {
this._frameIndex = 0;
this._frameTimings = [];
this._timings = [];
this._prevTimings = [];
this.unitsName = "ms";
this.decimalPlaces = 1;
this.enabled = true;
app.on('frameupdate', this.begin.bind(this, 'update'));
app.on('framerender', this.mark.bind(this, 'render'));
app.on('frameend', this.mark.bind(this, 'other'));
}
var _proto = CpuTimer.prototype;
_proto.begin = function begin(name) {
if (!this.enabled) {
return;
}
if (this._frameIndex < this._frameTimings.length) {
this._frameTimings.splice(this._frameIndex);
}
var tmp = this._prevTimings;
this._prevTimings = this._timings;
this._timings = this._frameTimings;
this._frameTimings = tmp;
this._frameIndex = 0;
this.mark(name);
};
_proto.mark = function mark(name) {
if (!this.enabled) {
return;
}
var timestamp = pc.now();
if (this._frameIndex > 0) {
var prev = this._frameTimings[this._frameIndex - 1];
prev[1] = timestamp - prev[1];
} else if (this._timings.length > 0) {
var _prev = this._timings[this._timings.length - 1];
_prev[1] = timestamp - _prev[1];
}
if (this._frameIndex >= this._frameTimings.length) {
this._frameTimings.push([name, timestamp]);
} else {
var timing = this._frameTimings[this._frameIndex];
timing[0] = name;
timing[1] = timestamp;
}
this._frameIndex++;
};
_createClass(CpuTimer, [{
key: "timings",
get: function get() {
return this._timings.slice(0, -1).map(function (v) {
return v[1];
});
}
}]);
return CpuTimer;
}();
var GpuTimer = function () {
function GpuTimer(app) {
this._gl = app.graphicsDevice.gl;
this._ext = app.graphicsDevice.extDisjointTimerQuery;
this._freeQueries = [];
this._frameQueries = [];
this._frames = [];
this._timings = [];
this._prevTimings = [];
this.enabled = true;
this.unitsName = "ms";
this.decimalPlaces = 1;
app.on('frameupdate', this.begin.bind(this, 'update'));
app.on('framerender', this.mark.bind(this, 'render'));
app.on('frameend', this.end.bind(this));
}
var _proto = GpuTimer.prototype;
_proto.loseContext = function loseContext() {
this._freeQueries = [];
this._frameQueries = [];
this._frames = [];
};
_proto.begin = function begin(name) {
if (!this.enabled) {
return;
}
if (this._frameQueries.length > 0) {
this.end();
}
this._checkDisjoint();
if (this._frames.length > 0) {
if (this._resolveFrameTimings(this._frames[0], this._prevTimings)) {
var tmp = this._prevTimings;
this._prevTimings = this._timings;
this._timings = tmp;
this._freeQueries = this._freeQueries.concat(this._frames.splice(0, 1)[0]);
}
}
this.mark(name);
};
_proto.mark = function mark(name) {
if (!this.enabled) {
return;
}
if (this._frameQueries.length > 0) {
this._gl.endQuery(this._ext.TIME_ELAPSED_EXT);
}
var query = this._allocateQuery();
query[0] = name;
this._gl.beginQuery(this._ext.TIME_ELAPSED_EXT, query[1]);
this._frameQueries.push(query);
};
_proto.end = function end() {
if (!this.enabled) {
return;
}
this._gl.endQuery(this._ext.TIME_ELAPSED_EXT);
this._frames.push(this._frameQueries);
this._frameQueries = [];
};
_proto._checkDisjoint = function _checkDisjoint() {
var disjoint = this._gl.getParameter(this._ext.GPU_DISJOINT_EXT);
if (disjoint) {
this._freeQueries = [this._frames, [this._frameQueries], [this._freeQueries]].flat(2);
this._frameQueries = [];
this._frames = [];
}
};
_proto._allocateQuery = function _allocateQuery() {
return this._freeQueries.length > 0 ? this._freeQueries.splice(-1, 1)[0] : ["", this._gl.createQuery()];
};
_proto._resolveFrameTimings = function _resolveFrameTimings(frame, timings) {
if (!this._gl.getQueryParameter(frame[frame.length - 1][1], this._gl.QUERY_RESULT_AVAILABLE)) {
return false;
}
for (var i = 0; i < frame.length; ++i) {
timings[i] = [frame[i][0], this._gl.getQueryParameter(frame[i][1], this._gl.QUERY_RESULT) * 0.000001];
}
return true;
};
_createClass(GpuTimer, [{
key: "timings",
get: function get() {
return this._timings.map(function (v) {
return v[1];
});
}
}]);
return GpuTimer;
}();
var StatsTimer = function () {
function StatsTimer(app, statNames, decimalPlaces, unitsName, multiplier) {
var _this = this;
this.app = app;
this.values = [];
this.statNames = statNames;
if (this.statNames.length > 3) this.statNames.length = 3;
this.unitsName = unitsName;
this.decimalPlaces = decimalPlaces;
this.multiplier = multiplier || 1;
var resolve = function resolve(path, obj) {
return path.split('.').reduce(function (prev, curr) {
return prev ? prev[curr] : null;
}, obj || _this);
};
app.on('frameupdate', function (ms) {
for (var i = 0; i < _this.statNames.length; i++) {
_this.values[i] = resolve(_this.statNames[i], _this.app.stats) * _this.multiplier;
}
});
}
_createClass(StatsTimer, [{
key: "timings",
get: function get() {
return this.values;
}
}]);
return StatsTimer;
}();
var Graph = function () {
function Graph(name, app, watermark, textRefreshRate, timer) {
this.name = name;
this.device = app.graphicsDevice;
this.timer = timer;
this.watermark = watermark;
this.enabled = false;
this.textRefreshRate = textRefreshRate;
this.avgTotal = 0;
this.avgTimer = 0;
this.avgCount = 0;
this.timingText = "";
this.texture = null;
this.yOffset = 0;
this.cursor = 0;
this.sample = new Uint8ClampedArray(4);
this.sample.set([0, 0, 0, 255]);
app.on('frameupdate', this.update.bind(this));
this.counter = 0;
}
var _proto = Graph.prototype;
_proto.loseContext = function loseContext() {
if (this.timer && typeof this.timer.loseContext === 'function') {
this.timer.loseContext();
}
};
_proto.update = function update(ms) {
var timings = this.timer.timings;
var total = timings.reduce(function (a, v) {
return a + v;
}, 0);
this.avgTotal += total;
this.avgTimer += ms;
this.avgCount++;
if (this.avgTimer > this.textRefreshRate) {
this.timingText = (this.avgTotal / this.avgCount).toFixed(this.timer.decimalPlaces);
this.avgTimer = 0;
this.avgTotal = 0;
this.avgCount = 0;
}
if (this.enabled) {
var value = 0;
var range = 1.5 * this.watermark;
for (var i = 0; i < timings.length; ++i) {
value += Math.floor(timings[i] / range * 255);
this.sample[i] = value;
}
this.sample[3] = this.watermark / range * 255;
var gl = this.device.gl;
this.device.bindTexture(this.texture);
gl.texSubImage2D(gl.TEXTURE_2D, 0, this.cursor, this.yOffset, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, this.sample);
this.cursor++;
if (this.cursor === this.texture.width) {
this.cursor = 0;
}
}
};
_proto.render = function render(render2d, x, y, w, h) {
render2d.quad(this.texture, x + w, y, -w, h, this.cursor, 0.5 + this.yOffset, -w, 0, this.enabled);
};
return Graph;
}();
var WordAtlas = function () {
function WordAtlas(texture, words) {
var canvas = document.createElement('canvas');
canvas.width = texture.width;
canvas.height = texture.height;
var context = canvas.getContext('2d', {
alpha: true
});
context.font = '10px "Lucida Console", Monaco, monospace';
context.textAlign = "left";
context.textBaseline = "alphabetic";
context.fillStyle = "rgb(255, 255, 255)";
var padding = 5;
var x = padding;
var y = padding;
var placements = [];
for (var i = 0; i < words.length; ++i) {
var measurement = context.measureText(words[i]);
var l = Math.ceil(-measurement.actualBoundingBoxLeft);
var r = Math.ceil(measurement.actualBoundingBoxRight);
var a = Math.ceil(measurement.actualBoundingBoxAscent);
var d = Math.ceil(measurement.actualBoundingBoxDescent);
var w = l + r;
var h = a + d;
if (x + w >= canvas.width) {
x = padding;
y += 16;
}
context.fillStyle = words[i].length === 1 ? "rgb(255, 255, 255)" : "rgb(150, 150, 150)";
context.fillText(words[i], x - l, y + a);
placements.push({
l: l,
r: r,
a: a,
d: d,
x: x,
y: y,
w: w,
h: h
});
x += w + padding;
}
var wordMap = {};
words.forEach(function (w, i) {
wordMap[w] = i;
});
this.words = words;
this.wordMap = wordMap;
this.placements = placements;
this.texture = texture;
var source = context.getImageData(0, 0, canvas.width, canvas.height);
var dest = texture.lock();
for (var _y = 0; _y < source.height; ++_y) {
for (var _x = 0; _x < source.width; ++_x) {
var offset = (_x + _y * texture.width) * 4;
dest[offset] = 255;
dest[offset + 1] = 255;
dest[offset + 2] = 255;
var red = source.data[(_x + (source.height - 1 - _y) * source.width) * 4];
var alpha = source.data[(_x + (source.height - 1 - _y) * source.width) * 4 + 3];
dest[offset + 3] = alpha * (red > 150 ? 1 : 0.7);
}
}
}
var _proto = WordAtlas.prototype;
_proto.render = function render(render2d, word, x, y) {
var p = this.placements[this.wordMap[word]];
if (p) {
var padding = 1;
render2d.quad(this.texture, x + p.l - padding, y - p.d + padding, p.w + padding * 2, p.h + padding * 2, p.x - padding, 64 - p.y - p.h - padding, undefined, undefined, true);
return p.w;
}
return 0;
};
return WordAtlas;
}();
var Render2d = function () {
function Render2d(device, colors, maxQuads) {
var _this = this;
if (maxQuads === void 0) {
maxQuads = 512;
}
var vertexShader = 'attribute vec3 vertex_position;\n' + 'attribute vec4 vertex_texCoord0;\n' + 'uniform vec4 screenAndTextureSize;\n' + 'varying vec4 uv0;\n' + 'varying float enabled;\n' + 'void main(void) {\n' + ' vec2 pos = vertex_position.xy / screenAndTextureSize.xy;\n' + ' gl_Position = vec4(pos * 2.0 - 1.0, 0.5, 1.0);\n' + ' uv0 = vec4(vertex_texCoord0.xy / screenAndTextureSize.zw, vertex_texCoord0.zw);\n' + ' enabled = vertex_position.z;\n' + '}\n';
var fragmentShader = 'varying vec4 uv0;\n' + 'varying float enabled;\n' + 'uniform vec4 clr;\n' + 'uniform vec4 col0;\n' + 'uniform vec4 col1;\n' + 'uniform vec4 col2;\n' + 'uniform vec4 watermark;\n' + 'uniform float watermarkSize;\n' + 'uniform vec4 background;\n' + 'uniform sampler2D source;\n' + 'void main (void) {\n' + ' vec4 tex = texture2D(source, uv0.xy);\n' + ' if (!(tex.rgb == vec3(1.0, 1.0, 1.0))) {\n' + ' if (enabled < 0.5)\n' + ' tex = background;\n' + ' else if (abs(uv0.w - tex.a) < watermarkSize)\n' + ' tex = watermark;\n' + ' else if (uv0.w < tex.r)\n' + ' tex = col0;\n' + ' else if (uv0.w < tex.g)\n' + ' tex = col1;\n' + ' else if (uv0.w < tex.b)\n' + ' tex = col2;\n' + ' else\n' + ' tex = background;\n' + ' }\n' + ' gl_FragColor = tex * clr;\n' + '}\n';
var format = new pc.VertexFormat(device, [{
semantic: pc.SEMANTIC_POSITION,
components: 3,
type: pc.TYPE_FLOAT32
}, {
semantic: pc.SEMANTIC_TEXCOORD0,
components: 4,
type: pc.TYPE_FLOAT32
}]);
var indices = new Uint16Array(maxQuads * 6);
for (var i = 0; i < maxQuads; ++i) {
indices[i * 6 + 0] = i * 4;
indices[i * 6 + 1] = i * 4 + 1;
indices[i * 6 + 2] = i * 4 + 2;
indices[i * 6 + 3] = i * 4;
indices[i * 6 + 4] = i * 4 + 2;
indices[i * 6 + 5] = i * 4 + 3;
}
this.device = device;
this.shader = pc.shaderChunks.createShaderFromCode(device, vertexShader, fragmentShader, "mini-stats");
this.buffer = new pc.VertexBuffer(device, format, maxQuads * 4, pc.BUFFER_STREAM);
this.data = new Float32Array(this.buffer.numBytes / 4);
this.indexBuffer = new pc.IndexBuffer(device, pc.INDEXFORMAT_UINT16, maxQuads * 6, pc.BUFFER_STATIC, indices);
this.prims = [];
this.prim = null;
this.primIndex = -1;
this.quads = 0;
var setupColor = function setupColor(name, value) {
_this[name] = new Float32Array([value.r, value.g, value.b, value.a]);
_this[name + "Id"] = device.scope.resolve(name);
};
setupColor("col0", colors.graph0);
setupColor("col1", colors.graph1);
setupColor("col2", colors.graph2);
setupColor("watermark", colors.watermark);
setupColor("background", colors.background);
this.watermarkSizeId = device.scope.resolve('watermarkSize');
this.clrId = device.scope.resolve('clr');
this.clr = new Float32Array(4);
this.screenTextureSizeId = device.scope.resolve('screenAndTextureSize');
this.screenTextureSize = new Float32Array(4);
}
var _proto = Render2d.prototype;
_proto.quad = function quad(texture, x, y, w, h, u, v, uw, uh, enabled) {
var quad = this.quads++;
var prim = this.prim;
if (prim && prim.texture === texture) {
prim.count += 6;
} else {
this.primIndex++;
if (this.primIndex === this.prims.length) {
prim = {
type: pc.PRIMITIVE_TRIANGLES,
indexed: true,
base: quad * 6,
count: 6,
texture: texture
};
this.prims.push(prim);
} else {
prim = this.prims[this.primIndex];
prim.base = quad * 6;
prim.count = 6;
prim.texture = texture;
}
this.prim = prim;
}
var x1 = x + w;
var y1 = y + h;
var u1 = u + (uw === undefined ? w : uw);
var v1 = v + (uh === undefined ? h : uh);
var colorize = enabled ? 1 : 0;
this.data.set([x, y, colorize, u, v, 0, 0, x1, y, colorize, u1, v, 1, 0, x1, y1, colorize, u1, v1, 1, 1, x, y1, colorize, u, v1, 0, 1], 4 * 7 * quad);
};
_proto.render = function render(clr, height) {
var device = this.device;
var buffer = this.buffer;
buffer.setData(this.data.buffer);
device.updateBegin();
device.setDepthTest(false);
device.setDepthWrite(false);
device.setCullMode(pc.CULLFACE_NONE);
device.setBlending(true);
device.setBlendFunctionSeparate(pc.BLENDMODE_SRC_ALPHA, pc.BLENDMODE_ONE_MINUS_SRC_ALPHA, pc.BLENDMODE_ONE, pc.BLENDMODE_ONE);
device.setBlendEquationSeparate(pc.BLENDEQUATION_ADD, pc.BLENDEQUATION_ADD);
device.setVertexBuffer(buffer, 0);
device.setIndexBuffer(this.indexBuffer);
device.setShader(this.shader);
var pr = Math.min(device.maxPixelRatio, window.devicePixelRatio);
this.clr.set(clr, 0);
this.clrId.setValue(this.clr);
this.screenTextureSize[0] = device.width / pr;
this.screenTextureSize[1] = device.height / pr;
this.col0Id.setValue(this.col0);
this.col1Id.setValue(this.col1);
this.col2Id.setValue(this.col2);
this.watermarkId.setValue(this.watermark);
this.backgroundId.setValue(this.background);
for (var i = 0; i <= this.primIndex; ++i) {
var prim = this.prims[i];
this.screenTextureSize[2] = prim.texture.width;
this.screenTextureSize[3] = prim.texture.height;
this.screenTextureSizeId.setValue(this.screenTextureSize);
device.constantTexSource.setValue(prim.texture);
this.watermarkSizeId.setValue(0.5 / height);
device.draw(prim);
}
device.updateEnd();
this.prim = null;
this.primIndex = -1;
this.quads = 0;
};
return Render2d;
}();
var MiniStats = function () {
function MiniStats(app, options) {
var _this = this;
var device = app.graphicsDevice;
this._contextLostHandler = function (event) {
event.preventDefault();
if (_this.graphs) {
for (var i = 0; i < _this.graphs.length; i++) {
_this.graphs[i].loseContext();
}
}
};
device.canvas.addEventListener("webglcontextlost", this._contextLostHandler, false);
options = options || MiniStats.getDefaultOptions();
var graphs = this.initGraphs(app, device, options);
var words = ["", "ms", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."];
graphs.forEach(function (graph) {
words.push(graph.name);
});
if (options.stats) {
options.stats.forEach(function (stat) {
if (stat.unitsName) words.push(stat.unitsName);
});
}
words = words.filter(function (item, index) {
return words.indexOf(item) >= index;
});
var maxWidth = options.sizes.reduce(function (max, v) {
return v.width > max ? v.width : max;
}, 0);
var wordAtlasData = this.initWordAtlas(device, words, maxWidth, graphs.length);
var texture = wordAtlasData.texture;
graphs.forEach(function (graph, i) {
graph.texture = texture;
graph.yOffset = i;
});
this.sizes = options.sizes;
this._activeSizeIndex = options.startSizeIndex;
var div = document.createElement('div');
div.style.cssText = 'position:fixed;bottom:0;left:0;background:transparent;';
document.body.appendChild(div);
div.addEventListener('mouseenter', function (event) {
_this.opacity = 1.0;
});
div.addEventListener('mouseleave', function (event) {
_this.opacity = 0.5;
});
div.addEventListener('click', function (event) {
event.preventDefault();
if (_this._enabled) {
_this.activeSizeIndex = (_this.activeSizeIndex + 1) % _this.sizes.length;
_this.resize(_this.sizes[_this.activeSizeIndex].width, _this.sizes[_this.activeSizeIndex].height, _this.sizes[_this.activeSizeIndex].graphs);
}
});
device.on("resizecanvas", function () {
_this.updateDiv();
});
app.on('postrender', function () {
if (_this._enabled) {
_this.render();
}
});
this.device = device;
this.texture = texture;
this.wordAtlas = wordAtlasData.atlas;
this.render2d = new Render2d(device, options.colors);
this.graphs = graphs;
this.div = div;
this.width = 0;
this.height = 0;
this.gspacing = 2;
this.clr = [1, 1, 1, 0.5];
this._enabled = true;
this.activeSizeIndex = this._activeSizeIndex;
}
MiniStats.getDefaultOptions = function getDefaultOptions() {
return {
sizes: [{
width: 100,
height: 16,
spacing: 0,
graphs: false
}, {
width: 128,
height: 32,
spacing: 2,
graphs: true
}, {
width: 256,
height: 64,
spacing: 2,
graphs: true
}],
startSizeIndex: 0,
textRefreshRate: 500,
colors: {
graph0: new pc.Color(0.7, 0.2, 0.2, 1),
graph1: new pc.Color(0.2, 0.7, 0.2, 1),
graph2: new pc.Color(0.2, 0.2, 0.7, 1),
watermark: new pc.Color(0.4, 0.4, 0.2, 1),
background: new pc.Color(0, 0, 0, 1.0)
},
cpu: {
enabled: true,
watermark: 33
},
gpu: {
enabled: true,
watermark: 33
},
stats: [{
name: "Frame",
stats: ["frame.ms"],
decimalPlaces: 1,
unitsName: "ms",
watermark: 33
}, {
name: "DrawCalls",
stats: ["drawCalls.total"],
watermark: 1000
}]
};
};
var _proto = MiniStats.prototype;
_proto.initWordAtlas = function initWordAtlas(device, words, maxWidth, numGraphs) {
var texture = new pc.Texture(device, {
name: 'mini-stats',
width: pc.math.nextPowerOfTwo(maxWidth),
height: 64,
mipmaps: false,
minFilter: pc.FILTER_NEAREST,
magFilter: pc.FILTER_NEAREST
});
var wordAtlas = new WordAtlas(texture, words);
var dest = texture.lock();
for (var i = 0; i < texture.width * numGraphs; ++i) {
dest.set([0, 0, 0, 255], i * 4);
}
texture.unlock();
device.setTexture(texture, 0);
return {
atlas: wordAtlas,
texture: texture
};
};
_proto.initGraphs = function initGraphs(app, device, options) {
var graphs = [];
if (options.cpu.enabled) {
var timer = new CpuTimer(app);
var graph = new Graph('CPU', app, options.cpu.watermark, options.textRefreshRate, timer);
graphs.push(graph);
}
if (options.gpu.enabled && device.extDisjointTimerQuery) {
var _timer = new GpuTimer(app);
var _graph = new Graph('GPU', app, options.gpu.watermark, options.textRefreshRate, _timer);
graphs.push(_graph);
}
if (options.stats) {
options.stats.forEach(function (entry) {
var timer = new StatsTimer(app, entry.stats, entry.decimalPlaces, entry.unitsName, entry.multiplier);
var graph = new Graph(entry.name, app, entry.watermark, options.textRefreshRate, timer);
graphs.push(graph);
});
}
return graphs;
};
_proto.render = function render() {
var graphs = this.graphs;
var wordAtlas = this.wordAtlas;
var render2d = this.render2d;
var width = this.width;
var height = this.height;
var gspacing = this.gspacing;
for (var i = 0; i < graphs.length; ++i) {
var graph = graphs[i];
var y = i * (height + gspacing);
graph.render(render2d, 0, y, width, height);
var x = 1;
y += height - 13;
x += wordAtlas.render(render2d, graph.name, x, y) + 10;
var timingText = graph.timingText;
for (var j = 0; j < timingText.length; ++j) {
x += wordAtlas.render(render2d, timingText[j], x, y);
}
if (graph.timer.unitsName) {
x += 3;
wordAtlas.render(render2d, graph.timer.unitsName, x, y);
}
}
render2d.render(this.clr, height);
};
_proto.resize = function resize(width, height, showGraphs) {
var graphs = this.graphs;
for (var i = 0; i < graphs.length; ++i) {
graphs[i].enabled = showGraphs;
}
this.width = width;
this.height = height;
this.updateDiv();
};
_proto.updateDiv = function updateDiv() {
var rect = this.device.canvas.getBoundingClientRect();
this.div.style.left = rect.left + "px";
this.div.style.bottom = window.innerHeight - rect.bottom + "px";
this.div.style.width = this.width + "px";
this.div.style.height = this.overallHeight + "px";
};
_createClass(MiniStats, [{
key: "activeSizeIndex",
get: function get() {
return this._activeSizeIndex;
},
set: function set(value) {
this._activeSizeIndex = value;
this.gspacing = this.sizes[value].spacing;
this.resize(this.sizes[value].width, this.sizes[value].height, this.sizes[value].graphs);
}
}, {
key: "opacity",
get: function get() {
return this.clr[3];
},
set: function set(value) {
this.clr[3] = value;
}
}, {
key: "overallHeight",
get: function get() {
var graphs = this.graphs;
var spacing = this.gspacing;
return this.height * graphs.length + spacing * (graphs.length - 1);
}
}, {
key: "enabled",
get: function get() {
return this._enabled;
},
set: function set(value) {
if (value !== this._enabled) {
this._enabled = value;
for (var i = 0; i < this.graphs.length; ++i) {
this.graphs[i].enabled = value;
this.graphs[i].timer.enabled = value;
}
}
}
}]);
return MiniStats;
}();
exports.MiniStats = MiniStats;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
const express = require('express');
const router = express.Router();
const md5 = require('md5');
router.get('/', (req, res) => {
res.render('changePassword', {
title: 'Đổi mật khẩu'
});
});
router.post('/', (req, res, next) => {
const q = req.body;
if (!q.oldPassword || !q.password || !q.retype) {
return next(new Error('Invalid request'));
}
if (md5(q.oldPassword) !== req.user.password) {
return next(new Error('Mật khẩu không chính xác!'));
}
if (q.password !== q.retype) {
return next(new Error('Mật khẩu không trùng nhau!'));
}
req.user.password = md5(q.password);
req.user.save(() => {
res.redirect('/');
});
});
module.exports = router;
|
//>>built
define(["dojo/_base/declare","dojo/_base/lang","dojo/_base/json","dojo/has","esri/kernel","esri/lang","esri/graphicsUtils","esri/tasks/NATypes"],function(f,k,c,l,m,g,e,h){return f(null,{declaredClass:"esri.tasks.ClosestFacilityParameters",accumulateAttributes:null,attributeParameterValues:null,defaultCutoff:null,defaultTargetFacilityCount:null,directionsLanguage:null,directionsLengthUnits:null,directionsOutputType:null,directionsStyleName:null,directionsTimeAttribute:null,doNotLocateOnRestrictedElements:!0,
facilities:null,impedanceAttribute:null,incidents:null,outputGeometryPrecision:null,outputGeometryPrecisionUnits:null,outputLines:null,outSpatialReference:null,pointBarriers:null,polygonBarriers:null,polylineBarriers:null,restrictionAttributes:null,restrictUTurns:null,returnDirections:!1,returnFacilities:!1,returnIncidents:!1,returnPointBarriers:!1,returnPolylgonBarriers:!1,returnPolylineBarriers:!1,returnRoutes:!0,travelDirection:null,useHierarchy:!1,timeOfDay:null,timeOfDayUsage:null,toJson:function(d){var b=
{returnDirections:this.returnDirections,returnFacilities:this.returnFacilities,returnIncidents:this.returnIncidents,returnBarriers:this.returnPointBarriers,returnPolygonBarriers:this.returnPolygonBarriers,returnPolylineBarriers:this.returnPolylineBarriers,returnCFRoutes:this.returnRoutes,useHierarchy:this.useHierarchy,attributeParameterValues:this.attributeParameterValues&&c.toJson(this.attributeParameterValues),defaultCutoff:this.defaultCutoff,defaultTargetFacilityCount:this.defaultTargetFacilityCount,
directionsLanguage:this.directionsLanguage,directionsLengthUnits:h.LengthUnit[this.directionsLengthUnits],directionsTimeAttributeName:this.directionsTimeAttribute,impedanceAttributeName:this.impedanceAttribute,outputGeometryPrecision:this.outputGeometryPrecision,outputGeometryPrecisionUnits:this.outputGeometryPrecisionUnits,outputLines:this.outputLines,outSR:this.outSpatialReference?this.outSpatialReference.wkid||c.toJson(this.outSpatialReference.toJson()):null,restrictionAttributeNames:this.restrictionAttributes?
this.restrictionAttributes.join(","):null,restrictUTurns:this.restrictUTurns,accumulateAttributeNames:this.accumulateAttributes?this.accumulateAttributes.join(","):null,travelDirection:this.travelDirection,timeOfDay:this.timeOfDay&&this.timeOfDay.getTime(),directionsStyleName:this.directionsStyleName};if(this.directionsOutputType)switch(this.directionsOutputType.toLowerCase()){case "complete":b.directionsOutputType="esriDOTComplete";break;case "complete-no-events":b.directionsOutputType="esriDOTCompleteNoEvents";
break;case "instructions-only":b.directionsOutputType="esriDOTInstructionsOnly";break;case "standard":b.directionsOutputType="esriDOTStandard";break;case "summary-only":b.directionsOutputType="esriDOTSummaryOnly";break;default:b.directionsOutputType=this.directionsOutputType}if(this.timeOfDayUsage){var a;switch(this.timeOfDayUsage.toLowerCase()){case "start":a="esriNATimeOfDayUseAsStartTime";break;case "end":a="esriNATimeOfDayUseAsEndTime";break;default:a=this.timeOfDayUsage}b.timeOfDayUsage=a}a=
this.incidents;"esri.tasks.FeatureSet"===a.declaredClass&&0<a.features.length?b.incidents=c.toJson({type:"features",features:e._encodeGraphics(a.features,d&&d["incidents.features"]),doNotLocateOnRestrictedElements:this.doNotLocateOnRestrictedElements}):"esri.tasks.DataLayer"===a.declaredClass?b.incidents=a:"esri.tasks.DataFile"===a.declaredClass&&(b.incidents=c.toJson({type:"features",url:a.url,doNotLocateOnRestrictedElements:this.doNotLocateOnRestrictedElements}));a=this.facilities;"esri.tasks.FeatureSet"===
a.declaredClass&&0<a.features.length?b.facilities=c.toJson({type:"features",features:e._encodeGraphics(a.features,d&&d["facilities.features"]),doNotLocateOnRestrictedElements:this.doNotLocateOnRestrictedElements}):"esri.tasks.DataLayer"===a.declaredClass?b.facilities=a:"esri.tasks.DataFile"===a.declaredClass&&(b.facilities=c.toJson({type:"features",url:a.url,doNotLocateOnRestrictedElements:this.doNotLocateOnRestrictedElements}));a=function(a,b){return!a?null:"esri.tasks.FeatureSet"===a.declaredClass?
0<a.features.length?c.toJson({type:"features",features:e._encodeGraphics(a.features,d&&d[b])}):null:"esri.tasks.DataLayer"===a.declaredClass?a:"esri.tasks.DataFile"===a.declaredClass?c.toJson({type:"features",url:a.url}):c.toJson(a)};this.pointBarriers&&(b.barriers=a(this.pointBarriers,"pointBarriers.features"));this.polygonBarriers&&(b.polygonBarriers=a(this.polygonBarriers,"polygonBarriers.features"));this.polylineBarriers&&(b.polylineBarriers=a(this.polylineBarriers,"polylineBarriers.features"));
return g.filter(b,function(a){if(null!==a)return!0})}})}); |
module.exports = function(grunt) {
var qunit = require("qunit");
var log = qunit.log;
grunt.registerMultiTask("node-qunit", "Runs node-qunit ", function() {
var done = this.async(),
started = new Date(),
callback = this.data.callback;
// Setup Qunit
qunit.setup(this.data.setup || {
log: {
summary: true,
errors: true
}
});
// Run tests
var files = {};
if(this.data.code) files.code = this.data.code;
if(this.data.deps) files.deps = this.data.deps;
if(this.data.tests) files.tests = this.data.tests;
qunit.run(files, function(err, result) {
if(!result) {
throw "Could not get results for Qunit test. Check previous exceptions";
}
result.started = started;
result.completed = new Date();
var waitForAsync = false;
this.async = function() {
waitForAsync = true;
return function(status) {
done(typeof status === "undefined" ? (result.failed === 0) : status);
log.reset();
};
};
var res;
if(typeof callback === "function") {
res = callback(err, result);
}
if(!waitForAsync) {
done(typeof res === "undefined" ? (result.failed === 0) : res);
log.reset();
}
});
});
}; |
'use strict';
module.exports = function soap(echo) {
return echo;
}; |
/**
* @license Highcharts Gantt JS v9.3.0 (2021-10-21)
*
* Tree Grid
*
* (c) 2016-2021 Jon Arild Nygard
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/treegrid', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Core/Axis/BrokenAxis.js', [_modules['Extensions/Stacking.js'], _modules['Core/Utilities.js']], function (StackItem, U) {
/* *
*
* (c) 2009-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var addEvent = U.addEvent,
find = U.find,
fireEvent = U.fireEvent,
isArray = U.isArray,
isNumber = U.isNumber,
pick = U.pick;
/* *
*
* Composition
*
* */
/**
* Axis with support of broken data rows.
* @private
*/
var BrokenAxis;
(function (BrokenAxis) {
/* *
*
* Declarations
*
* */
/* *
*
* Constants
*
* */
var composedClasses = [];
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* Adds support for broken axes.
* @private
*/
function compose(AxisClass, SeriesClass) {
if (composedClasses.indexOf(AxisClass) === -1) {
composedClasses.push(AxisClass);
AxisClass.keepProps.push('brokenAxis');
addEvent(AxisClass, 'init', onAxisInit);
addEvent(AxisClass, 'afterInit', onAxisAfterInit);
addEvent(AxisClass, 'afterSetTickPositions', onAxisAfterSetTickPositions);
addEvent(AxisClass, 'afterSetOptions', onAxisAfterSetOptions);
}
if (composedClasses.indexOf(SeriesClass) === -1) {
composedClasses.push(SeriesClass);
var seriesProto = SeriesClass.prototype;
seriesProto.drawBreaks = seriesDrawBreaks;
seriesProto.gappedPath = seriesGappedPath;
addEvent(SeriesClass, 'afterGeneratePoints', onSeriesAfterGeneratePoints);
addEvent(SeriesClass, 'afterRender', onSeriesAfterRender);
}
return AxisClass;
}
BrokenAxis.compose = compose;
/**
* @private
*/
function onAxisAfterInit() {
if (typeof this.brokenAxis !== 'undefined') {
this.brokenAxis.setBreaks(this.options.breaks, false);
}
}
/**
* Force Axis to be not-ordinal when breaks are defined.
* @private
*/
function onAxisAfterSetOptions() {
var axis = this;
if (axis.brokenAxis && axis.brokenAxis.hasBreaks) {
axis.options.ordinal = false;
}
}
/**
* @private
*/
function onAxisAfterSetTickPositions() {
var axis = this,
brokenAxis = axis.brokenAxis;
if (brokenAxis &&
brokenAxis.hasBreaks) {
var tickPositions = axis.tickPositions,
info = axis.tickPositions.info,
newPositions = [];
for (var i = 0; i < tickPositions.length; i++) {
if (!brokenAxis.isInAnyBreak(tickPositions[i])) {
newPositions.push(tickPositions[i]);
}
}
axis.tickPositions = newPositions;
axis.tickPositions.info = info;
}
}
/**
* @private
*/
function onAxisInit() {
var axis = this;
if (!axis.brokenAxis) {
axis.brokenAxis = new Additions(axis);
}
}
/**
* @private
*/
function onSeriesAfterGeneratePoints() {
var _a = this,
isDirty = _a.isDirty,
connectNulls = _a.options.connectNulls,
points = _a.points,
xAxis = _a.xAxis,
yAxis = _a.yAxis;
// Set, or reset visibility of the points. Axis.setBreaks marks
// the series as isDirty
if (isDirty) {
var i = points.length;
while (i--) {
var point = points[i];
// Respect nulls inside the break (#4275)
var nullGap = point.y === null && connectNulls === false;
var isPointInBreak = (!nullGap && ((xAxis &&
xAxis.brokenAxis &&
xAxis.brokenAxis.isInAnyBreak(point.x,
true)) || (yAxis &&
yAxis.brokenAxis &&
yAxis.brokenAxis.isInAnyBreak(point.y,
true))));
// Set point.visible if in any break.
// If not in break, reset visible to original value.
point.visible = isPointInBreak ?
false :
point.options.visible !== false;
}
}
}
/**
* @private
*/
function onSeriesAfterRender() {
this.drawBreaks(this.xAxis, ['x']);
this.drawBreaks(this.yAxis, pick(this.pointArrayMap, ['y']));
}
/**
* @private
*/
function seriesDrawBreaks(axis, keys) {
var series = this,
points = series.points;
var breaks,
threshold,
eventName,
y;
if (axis && // #5950
axis.brokenAxis &&
axis.brokenAxis.hasBreaks) {
var brokenAxis_1 = axis.brokenAxis;
keys.forEach(function (key) {
breaks = brokenAxis_1 && brokenAxis_1.breakArray || [];
threshold = axis.isXAxis ?
axis.min :
pick(series.options.threshold, axis.min);
points.forEach(function (point) {
y = pick(point['stack' + key.toUpperCase()], point[key]);
breaks.forEach(function (brk) {
if (isNumber(threshold) && isNumber(y)) {
eventName = false;
if ((threshold < brk.from && y > brk.to) ||
(threshold > brk.from && y < brk.from)) {
eventName = 'pointBreak';
}
else if ((threshold < brk.from && y > brk.from && y < brk.to) ||
(threshold > brk.from && y > brk.to && y < brk.from)) {
eventName = 'pointInBreak';
}
if (eventName) {
fireEvent(axis, eventName, { point: point, brk: brk });
}
}
});
});
});
}
}
/**
* Extend getGraphPath by identifying gaps in the data so that we
* can draw a gap in the line or area. This was moved from ordinal
* axis module to broken axis module as of #5045.
*
* @private
* @function Highcharts.Series#gappedPath
*
* @return {Highcharts.SVGPathArray}
* Gapped path
*/
function seriesGappedPath() {
var currentDataGrouping = this.currentDataGrouping,
groupingSize = currentDataGrouping && currentDataGrouping.gapSize,
points = this.points.slice(),
yAxis = this.yAxis;
var gapSize = this.options.gapSize,
i = points.length - 1,
stack;
/**
* Defines when to display a gap in the graph, together with the
* [gapUnit](plotOptions.series.gapUnit) option.
*
* In case when `dataGrouping` is enabled, points can be grouped
* into a larger time span. This can make the grouped points to
* have a greater distance than the absolute value of `gapSize`
* property, which will result in disappearing graph completely.
* To prevent this situation the mentioned distance between
* grouped points is used instead of previously defined
* `gapSize`.
*
* In practice, this option is most often used to visualize gaps
* in time series. In a stock chart, intraday data is available
* for daytime hours, while gaps will appear in nights and
* weekends.
*
* @see [gapUnit](plotOptions.series.gapUnit)
* @see [xAxis.breaks](#xAxis.breaks)
*
* @sample {highstock} stock/plotoptions/series-gapsize/
* Setting the gap size to 2 introduces gaps for weekends in
* daily datasets.
*
* @type {number}
* @default 0
* @product highstock
* @requires modules/broken-axis
* @apioption plotOptions.series.gapSize
*/
/**
* Together with [gapSize](plotOptions.series.gapSize), this
* option defines where to draw gaps in the graph.
*
* When the `gapUnit` is `"relative"` (default), a gap size of 5
* means that if the distance between two points is greater than
* 5 times that of the two closest points, the graph will be
* broken.
*
* When the `gapUnit` is `"value"`, the gap is based on absolute
* axis values, which on a datetime axis is milliseconds. This
* also applies to the navigator series that inherits gap
* options from the base series.
*
* @see [gapSize](plotOptions.series.gapSize)
*
* @type {string}
* @default relative
* @since 5.0.13
* @product highstock
* @validvalue ["relative", "value"]
* @requires modules/broken-axis
* @apioption plotOptions.series.gapUnit
*/
if (gapSize && i > 0) { // #5008
// Gap unit is relative
if (this.options.gapUnit !== 'value') {
gapSize *= this.basePointRange;
}
// Setting a new gapSize in case dataGrouping is enabled
// (#7686)
if (groupingSize &&
groupingSize > gapSize &&
// Except when DG is forced (e.g. from other series)
// and has lower granularity than actual points (#11351)
groupingSize >= this.basePointRange) {
gapSize = groupingSize;
}
// extension for ordinal breaks
var current = void 0,
next = void 0;
while (i--) {
// Reassign next if it is not visible
if (!(next && next.visible !== false)) {
next = points[i + 1];
}
current = points[i];
// Skip iteration if one of the points is not visible
if (next.visible === false || current.visible === false) {
continue;
}
if (next.x - current.x > gapSize) {
var xRange = (current.x + next.x) / 2;
points.splice(// insert after this one
i + 1, 0, {
isNull: true,
x: xRange
});
// For stacked chart generate empty stack items,
// #6546
if (yAxis.stacking && this.options.stacking) {
stack = yAxis.stacking.stacks[this.stackKey][xRange] =
new StackItem(yAxis, yAxis.options
.stackLabels, false, xRange, this.stack);
stack.total = 0;
}
}
// Assign current to next for the upcoming iteration
next = current;
}
}
// Call base method
return this.getGraphPath(points);
}
/* *
*
* Class
*
* */
/**
* Provides support for broken axes.
* @private
* @class
*/
var Additions = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Additions(axis) {
this.hasBreaks = false;
this.axis = axis;
}
/* *
*
* Static Functions
*
* */
/**
* @private
*/
Additions.isInBreak = function (brk, val) {
var repeat = brk.repeat || Infinity,
from = brk.from,
length = brk.to - brk.from,
test = (val >= from ?
(val - from) % repeat :
repeat - ((from - val) % repeat));
var ret;
if (!brk.inclusive) {
ret = test < length && test !== 0;
}
else {
ret = test <= length;
}
return ret;
};
/**
* @private
*/
Additions.lin2Val = function (val) {
var axis = this;
var brokenAxis = axis.brokenAxis;
var breakArray = brokenAxis && brokenAxis.breakArray;
if (!breakArray || !isNumber(val)) {
return val;
}
var nval = val,
brk,
i;
for (i = 0; i < breakArray.length; i++) {
brk = breakArray[i];
if (brk.from >= nval) {
break;
}
else if (brk.to < nval) {
nval += brk.len;
}
else if (Additions.isInBreak(brk, nval)) {
nval += brk.len;
}
}
return nval;
};
/**
* @private
*/
Additions.val2Lin = function (val) {
var axis = this;
var brokenAxis = axis.brokenAxis;
var breakArray = brokenAxis && brokenAxis.breakArray;
if (!breakArray || !isNumber(val)) {
return val;
}
var nval = val,
brk,
i;
for (i = 0; i < breakArray.length; i++) {
brk = breakArray[i];
if (brk.to <= val) {
nval -= brk.len;
}
else if (brk.from >= val) {
break;
}
else if (Additions.isInBreak(brk, val)) {
nval -= (val - brk.from);
break;
}
}
return nval;
};
/* *
*
* Functions
*
* */
/**
* Returns the first break found where the x is larger then break.from
* and smaller then break.to.
*
* @param {number} x
* The number which should be within a break.
*
* @param {Array<Highcharts.XAxisBreaksOptions>} breaks
* The array of breaks to search within.
*
* @return {Highcharts.XAxisBreaksOptions|undefined}
* Returns the first break found that matches, returns false if no break
* is found.
*/
Additions.prototype.findBreakAt = function (x, breaks) {
return find(breaks, function (b) {
return b.from < x && x < b.to;
});
};
/**
* @private
*/
Additions.prototype.isInAnyBreak = function (val, testKeep) {
var brokenAxis = this,
axis = brokenAxis.axis,
breaks = axis.options.breaks || [];
var i = breaks.length,
inbrk,
keep,
ret;
if (i && isNumber(val)) {
while (i--) {
if (Additions.isInBreak(breaks[i], val)) {
inbrk = true;
if (!keep) {
keep = pick(breaks[i].showPoints, !axis.isXAxis);
}
}
}
if (inbrk && testKeep) {
ret = inbrk && !keep;
}
else {
ret = inbrk;
}
}
return ret;
};
/**
* Dynamically set or unset breaks in an axis. This function in lighter
* than usin Axis.update, and it also preserves animation.
*
* @private
* @function Highcharts.Axis#setBreaks
*
* @param {Array<Highcharts.XAxisBreaksOptions>} [breaks]
* The breaks to add. When `undefined` it removes existing breaks.
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart immediately.
*/
Additions.prototype.setBreaks = function (breaks, redraw) {
var brokenAxis = this;
var axis = brokenAxis.axis;
var hasBreaks = (isArray(breaks) && !!breaks.length);
axis.isDirty = brokenAxis.hasBreaks !== hasBreaks;
brokenAxis.hasBreaks = hasBreaks;
axis.options.breaks = axis.userOptions.breaks = breaks;
axis.forceRedraw = true; // Force recalculation in setScale
// Recalculate series related to the axis.
axis.series.forEach(function (series) {
series.isDirty = true;
});
if (!hasBreaks && axis.val2lin === Additions.val2Lin) {
// Revert to prototype functions
delete axis.val2lin;
delete axis.lin2val;
}
if (hasBreaks) {
axis.userOptions.ordinal = false;
axis.lin2val = Additions.lin2Val;
axis.val2lin = Additions.val2Lin;
axis.setExtremes = function (newMin, newMax, redraw, animation, eventArguments) {
// If trying to set extremes inside a break, extend min to
// after, and max to before the break ( #3857 )
if (brokenAxis.hasBreaks) {
var breaks_1 = (this.options.breaks || []);
var axisBreak = void 0;
while ((axisBreak = brokenAxis.findBreakAt(newMin, breaks_1))) {
newMin = axisBreak.to;
}
while ((axisBreak = brokenAxis.findBreakAt(newMax, breaks_1))) {
newMax = axisBreak.from;
}
// If both min and max is within the same break.
if (newMax < newMin) {
newMax = newMin;
}
}
axis.constructor.prototype.setExtremes.call(this, newMin, newMax, redraw, animation, eventArguments);
};
axis.setAxisTranslation = function () {
axis.constructor.prototype.setAxisTranslation.call(this);
brokenAxis.unitLength = void 0;
if (brokenAxis.hasBreaks) {
var breaks_2 = axis.options.breaks || [],
// Temporary one:
breakArrayT_1 = [],
breakArray_1 = [],
pointRangePadding = pick(axis.pointRangePadding, 0);
var length_1 = 0,
inBrk_1,
repeat_1,
min_1 = axis.userMin || axis.min,
max_1 = axis.userMax || axis.max,
start_1,
i_1;
// Min & max check (#4247)
breaks_2.forEach(function (brk) {
repeat_1 = brk.repeat || Infinity;
if (isNumber(min_1) && isNumber(max_1)) {
if (Additions.isInBreak(brk, min_1)) {
min_1 += (brk.to % repeat_1) - (min_1 % repeat_1);
}
if (Additions.isInBreak(brk, max_1)) {
max_1 -= (max_1 % repeat_1) - (brk.from % repeat_1);
}
}
});
// Construct an array holding all breaks in the axis
breaks_2.forEach(function (brk) {
start_1 = brk.from;
repeat_1 = brk.repeat || Infinity;
if (isNumber(min_1) && isNumber(max_1)) {
while (start_1 - repeat_1 > min_1) {
start_1 -= repeat_1;
}
while (start_1 < min_1) {
start_1 += repeat_1;
}
for (i_1 = start_1; i_1 < max_1; i_1 += repeat_1) {
breakArrayT_1.push({
value: i_1,
move: 'in'
});
breakArrayT_1.push({
value: i_1 + brk.to - brk.from,
move: 'out',
size: brk.breakSize
});
}
}
});
breakArrayT_1.sort(function (a, b) {
return ((a.value === b.value) ?
((a.move === 'in' ? 0 : 1) -
(b.move === 'in' ? 0 : 1)) :
a.value - b.value);
});
// Simplify the breaks
inBrk_1 = 0;
start_1 = min_1;
breakArrayT_1.forEach(function (brk) {
inBrk_1 += (brk.move === 'in' ? 1 : -1);
if (inBrk_1 === 1 && brk.move === 'in') {
start_1 = brk.value;
}
if (inBrk_1 === 0 && isNumber(start_1)) {
breakArray_1.push({
from: start_1,
to: brk.value,
len: brk.value - start_1 - (brk.size || 0)
});
length_1 += brk.value - start_1 - (brk.size || 0);
}
});
brokenAxis.breakArray = breakArray_1;
// Used with staticScale, and below the actual axis
// length, when breaks are substracted.
if (isNumber(min_1) && isNumber(max_1) && isNumber(axis.min)) {
brokenAxis.unitLength = max_1 - min_1 - length_1 +
pointRangePadding;
fireEvent(axis, 'afterBreaks');
if (axis.staticScale) {
axis.transA = axis.staticScale;
}
else if (brokenAxis.unitLength) {
axis.transA *=
(max_1 - axis.min + pointRangePadding) /
brokenAxis.unitLength;
}
if (pointRangePadding) {
axis.minPixelPadding =
axis.transA * (axis.minPointOffset || 0);
}
axis.min = min_1;
axis.max = max_1;
}
}
};
}
if (pick(redraw, true)) {
axis.chart.redraw();
}
};
return Additions;
}());
BrokenAxis.Additions = Additions;
})(BrokenAxis || (BrokenAxis = {}));
/* *
*
* Default Export
*
* */
return BrokenAxis;
});
_registerModule(_modules, 'Core/Axis/GridAxis.js', [_modules['Core/Axis/Axis.js'], _modules['Core/Axis/AxisDefaults.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (Axis, AxisDefaults, H, U) {
/* *
*
* (c) 2016 Highsoft AS
* Authors: Lars A. V. Cabrera
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var dateFormats = H.dateFormats;
var addEvent = U.addEvent,
defined = U.defined,
erase = U.erase,
find = U.find,
isArray = U.isArray,
isNumber = U.isNumber,
merge = U.merge,
pick = U.pick,
timeUnits = U.timeUnits,
wrap = U.wrap;
/* *
*
* Functions
*
* */
/* eslint-disable require-jsdoc */
function argsToArray(args) {
return Array.prototype.slice.call(args, 1);
}
function isObject(x) {
// Always use strict mode
return U.isObject(x, true);
}
function applyGridOptions(axis) {
var options = axis.options;
// Center-align by default
/*
if (!options.labels) {
options.labels = {};
}
*/
options.labels.align = pick(options.labels.align, 'center');
// @todo: Check against tickLabelPlacement between/on etc
/* Prevents adding the last tick label if the axis is not a category
axis.
Since numeric labels are normally placed at starts and ends of a
range of value, and this module makes the label point at the value,
an "extra" label would appear. */
if (!axis.categories) {
options.showLastLabel = false;
}
// Prevents rotation of labels when squished, as rotating them would not
// help.
axis.labelRotation = 0;
options.labels.rotation = 0;
}
/**
* Axis with grid support.
* @private
*/
var GridAxis;
(function (GridAxis) {
/* *
*
* Declarations
*
* */
/**
* Enum for which side the axis is on. Maps to axis.side.
* @private
*/
var Side;
(function (Side) {
Side[Side["top"] = 0] = "top";
Side[Side["right"] = 1] = "right";
Side[Side["bottom"] = 2] = "bottom";
Side[Side["left"] = 3] = "left";
})(Side = GridAxis.Side || (GridAxis.Side = {}));
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* Extends axis class with grid support.
* @private
*/
function compose(AxisClass, ChartClass, TickClass) {
if (AxisClass.keepProps.indexOf('grid') === -1) {
AxisClass.keepProps.push('grid');
AxisClass.prototype.getMaxLabelDimensions = getMaxLabelDimensions;
wrap(AxisClass.prototype, 'unsquish', wrapUnsquish);
// Add event handlers
addEvent(AxisClass, 'init', onInit);
addEvent(AxisClass, 'afterGetOffset', onAfterGetOffset);
addEvent(AxisClass, 'afterGetTitlePosition', onAfterGetTitlePosition);
addEvent(AxisClass, 'afterInit', onAfterInit);
addEvent(AxisClass, 'afterRender', onAfterRender);
addEvent(AxisClass, 'afterSetAxisTranslation', onAfterSetAxisTranslation);
addEvent(AxisClass, 'afterSetOptions', onAfterSetOptions);
addEvent(AxisClass, 'afterSetOptions', onAfterSetOptions2);
addEvent(AxisClass, 'afterSetScale', onAfterSetScale);
addEvent(AxisClass, 'afterTickSize', onAfterTickSize);
addEvent(AxisClass, 'trimTicks', onTrimTicks);
addEvent(AxisClass, 'destroy', onDestroy);
}
addEvent(ChartClass, 'afterSetChartSize', onChartAfterSetChartSize);
addEvent(TickClass, 'afterGetLabelPosition', onTickAfterGetLabelPosition);
addEvent(TickClass, 'labelFormat', onTickLabelFormat);
return AxisClass;
}
GridAxis.compose = compose;
/**
* Get the largest label width and height.
*
* @private
* @function Highcharts.Axis#getMaxLabelDimensions
*
* @param {Highcharts.Dictionary<Highcharts.Tick>} ticks
* All the ticks on one axis.
*
* @param {Array<number|string>} tickPositions
* All the tick positions on one axis.
*
* @return {Highcharts.SizeObject}
* Object containing the properties height and width.
*
* @todo Move this to the generic axis implementation, as it is used there.
*/
function getMaxLabelDimensions(ticks, tickPositions) {
var dimensions = {
width: 0,
height: 0
};
tickPositions.forEach(function (pos) {
var tick = ticks[pos];
var labelHeight = 0,
labelWidth = 0,
label;
if (isObject(tick)) {
label = isObject(tick.label) ? tick.label : {};
// Find width and height of label
labelHeight = label.getBBox ? label.getBBox().height : 0;
if (label.textStr && !isNumber(label.textPxLength)) {
label.textPxLength = label.getBBox().width;
}
labelWidth = isNumber(label.textPxLength) ?
// Math.round ensures crisp lines
Math.round(label.textPxLength) :
0;
if (label.textStr) {
// Set the tickWidth same as the label width after ellipsis
// applied #10281
labelWidth = Math.round(label.getBBox().width);
}
// Update the result if width and/or height are larger
dimensions.height = Math.max(labelHeight, dimensions.height);
dimensions.width = Math.max(labelWidth, dimensions.width);
}
});
// For tree grid, add indentation
if (this.options.type === 'treegrid' &&
this.treeGrid &&
this.treeGrid.mapOfPosToGridNode) {
var treeDepth = this.treeGrid.mapOfPosToGridNode[-1].height || 0;
dimensions.width += this.options.labels.indentation * (treeDepth - 1);
}
return dimensions;
}
/**
* Handle columns and getOffset.
* @private
*/
function onAfterGetOffset() {
var grid = this.grid;
(grid && grid.columns || []).forEach(function (column) {
column.getOffset();
});
}
/**
* @private
*/
function onAfterGetTitlePosition(e) {
var axis = this;
var options = axis.options;
var gridOptions = options.grid || {};
if (gridOptions.enabled === true) {
// compute anchor points for each of the title align options
var axisTitle = axis.axisTitle,
axisHeight = axis.height,
horiz = axis.horiz,
axisLeft = axis.left,
offset = axis.offset,
opposite = axis.opposite,
options_1 = axis.options,
axisTop = axis.top,
axisWidth = axis.width;
var tickSize = axis.tickSize();
var titleWidth = axisTitle && axisTitle.getBBox().width;
var xOption = options_1.title.x;
var yOption = options_1.title.y;
var titleMargin = pick(options_1.title.margin,
horiz ? 5 : 10);
var titleFontSize = axis.chart.renderer.fontMetrics(options_1.title.style.fontSize,
axisTitle).f;
var crispCorr = tickSize ? tickSize[0] / 2 : 0;
// TODO account for alignment
// the position in the perpendicular direction of the axis
var offAxis = ((horiz ? axisTop + axisHeight : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
crispCorr +
(axis.side === GridAxis.Side.bottom ? titleFontSize : 0));
e.titlePosition.x = horiz ?
axisLeft - (titleWidth || 0) / 2 - titleMargin + xOption :
offAxis + (opposite ? axisWidth : 0) + offset + xOption;
e.titlePosition.y = horiz ?
(offAxis -
(opposite ? axisHeight : 0) +
(opposite ? titleFontSize : -titleFontSize) / 2 +
offset +
yOption) :
axisTop - titleMargin + yOption;
}
}
/**
* @private
*/
function onAfterInit() {
var axis = this;
var chart = axis.chart,
_a = axis.options.grid,
gridOptions = _a === void 0 ? {} : _a,
userOptions = axis.userOptions;
if (gridOptions.enabled) {
applyGridOptions(axis);
}
if (gridOptions.columns) {
var columns = axis.grid.columns = [];
var columnIndex = axis.grid.columnIndex = 0;
// Handle columns, each column is a grid axis
while (++columnIndex < gridOptions.columns.length) {
var columnOptions = merge(userOptions,
gridOptions.columns[gridOptions.columns.length - columnIndex - 1], {
linkedTo: 0,
// Force to behave like category axis
type: 'category',
// Disable by default the scrollbar on the grid axis
scrollbar: {
enabled: false
}
});
delete columnOptions.grid.columns; // Prevent recursion
var column = new Axis(axis.chart,
columnOptions);
column.grid.isColumn = true;
column.grid.columnIndex = columnIndex;
// Remove column axis from chart axes array, and place it
// in the columns array.
erase(chart.axes, column);
erase(chart[axis.coll], column);
columns.push(column);
}
}
}
/**
* Draw an extra line on the far side of the outermost axis,
* creating floor/roof/wall of a grid. And some padding.
* ```
* Make this:
* (axis.min) __________________________ (axis.max)
* | | | | |
* Into this:
* (axis.min) __________________________ (axis.max)
* ___|____|____|____|____|__
* ```
* @private
*/
function onAfterRender() {
var axis = this,
grid = axis.grid,
options = axis.options,
gridOptions = options.grid || {};
if (gridOptions.enabled === true) {
var min = axis.min || 0,
max = axis.max || 0;
// @todo acutual label padding (top, bottom, left, right)
axis.maxLabelDimensions = axis.getMaxLabelDimensions(axis.ticks, axis.tickPositions);
// Remove right wall before rendering if updating
if (axis.rightWall) {
axis.rightWall.destroy();
}
/*
Draw an extra axis line on outer axes
>
Make this: |______|______|______|___
> _________________________
Into this: |______|______|______|__|
*/
if (axis.grid && axis.grid.isOuterAxis() && axis.axisLine) {
var lineWidth = options.lineWidth;
if (lineWidth) {
var linePath = axis.getLinePath(lineWidth),
startPoint = linePath[0],
endPoint = linePath[1],
// Negate distance if top or left axis
// Subtract 1px to draw the line at the end of the tick
tickLength = (axis.tickSize('tick') || [1])[0],
distance = (tickLength - 1) * ((axis.side === GridAxis.Side.top ||
axis.side === GridAxis.Side.left) ? -1 : 1);
// If axis is horizontal, reposition line path vertically
if (startPoint[0] === 'M' && endPoint[0] === 'L') {
if (axis.horiz) {
startPoint[2] += distance;
endPoint[2] += distance;
}
else {
startPoint[1] += distance;
endPoint[1] += distance;
}
}
// If it doesn't exist, add an upper and lower border
// for the vertical grid axis.
if (!axis.horiz && axis.chart.marginRight) {
var upperBorderStartPoint = startPoint,
upperBorderEndPoint = [
'L',
axis.left,
startPoint[2] || 0
],
upperBorderPath = [upperBorderStartPoint,
upperBorderEndPoint],
lowerBorderEndPoint = [
'L',
axis.chart.chartWidth - axis.chart.marginRight,
axis.toPixels(max + axis.tickmarkOffset)
],
lowerBorderStartPoint = [
'M',
endPoint[1] || 0,
axis.toPixels(max + axis.tickmarkOffset)
],
lowerBorderPath = [lowerBorderStartPoint,
lowerBorderEndPoint];
if (!axis.grid.upperBorder && min % 1 !== 0) {
axis.grid.upperBorder = axis.grid.renderBorder(upperBorderPath);
}
if (axis.grid.upperBorder) {
axis.grid.upperBorder.attr({
stroke: options.lineColor,
'stroke-width': options.lineWidth
});
axis.grid.upperBorder.animate({
d: upperBorderPath
});
}
if (!axis.grid.lowerBorder && max % 1 !== 0) {
axis.grid.lowerBorder = axis.grid.renderBorder(lowerBorderPath);
}
if (axis.grid.lowerBorder) {
axis.grid.lowerBorder.attr({
stroke: options.lineColor,
'stroke-width': options.lineWidth
});
axis.grid.lowerBorder.animate({
d: lowerBorderPath
});
}
}
// Render an extra line parallel to the existing axes,
// to close the grid.
if (!axis.grid.axisLineExtra) {
axis.grid.axisLineExtra = axis.grid.renderBorder(linePath);
}
else {
axis.grid.axisLineExtra.attr({
stroke: options.lineColor,
'stroke-width': options.lineWidth
});
axis.grid.axisLineExtra.animate({
d: linePath
});
}
// show or hide the line depending on
// options.showEmpty
axis.axisLine[axis.showAxis ? 'show' : 'hide'](true);
}
}
(grid && grid.columns || []).forEach(function (column) {
column.render();
});
// Manipulate the tick mark visibility
// based on the axis.max- allows smooth scrolling.
if (!axis.horiz &&
axis.chart.hasRendered &&
(axis.scrollbar ||
(axis.linkedParent && axis.linkedParent.scrollbar))) {
var tickmarkOffset = axis.tickmarkOffset,
lastTick = axis.tickPositions[axis.tickPositions.length - 1],
firstTick = axis.tickPositions[0];
var label = void 0;
while ((label = axis.hiddenLabels.pop()) && label.element) {
label.show(); // #15453
}
// Hide/show firts tick label.
label = axis.ticks[firstTick].label;
if (label) {
if (min - firstTick > tickmarkOffset) {
axis.hiddenLabels.push(label.hide());
}
else {
label.show();
}
}
// Hide/show last tick mark/label.
label = axis.ticks[lastTick].label;
if (label) {
if (lastTick - max > tickmarkOffset) {
axis.hiddenLabels.push(label.hide());
}
else {
label.show();
}
}
var mark = axis.ticks[lastTick].mark;
if (mark) {
if (lastTick - max < tickmarkOffset && lastTick - max > 0 && axis.ticks[lastTick].isLast) {
mark.hide();
}
else if (axis.ticks[lastTick - 1]) {
mark.show();
}
}
}
}
}
/**
* @private
*/
function onAfterSetAxisTranslation() {
var axis = this;
var tickInfo = axis.tickPositions && axis.tickPositions.info;
var options = axis.options;
var gridOptions = options.grid || {};
var userLabels = axis.userOptions.labels || {};
// Fire this only for the Gantt type chart, #14868.
if (gridOptions.enabled) {
if (axis.horiz) {
axis.series.forEach(function (series) {
series.options.pointRange = 0;
});
// Lower level time ticks, like hours or minutes, represent
// points in time and not ranges. These should be aligned
// left in the grid cell by default. The same applies to
// years of higher order.
if (tickInfo &&
options.dateTimeLabelFormats &&
options.labels &&
!defined(userLabels.align) &&
(options.dateTimeLabelFormats[tickInfo.unitName].range === false ||
tickInfo.count > 1 // years
)) {
options.labels.align = 'left';
if (!defined(userLabels.x)) {
options.labels.x = 3;
}
}
}
else {
// Don't trim ticks which not in min/max range but
// they are still in the min/max plus tickInterval.
if (this.options.type !== 'treegrid' &&
axis.grid &&
axis.grid.columns) {
this.minPointOffset = this.tickInterval;
}
}
}
}
/**
* Creates a left and right wall on horizontal axes:
* - Places leftmost tick at the start of the axis, to create a left
* wall
* - Ensures that the rightmost tick is at the end of the axis, to
* create a right wall.
* @private
*/
function onAfterSetOptions(e) {
var options = this.options,
userOptions = e.userOptions,
gridOptions = ((options && isObject(options.grid)) ? options.grid : {});
var gridAxisOptions;
if (gridOptions.enabled === true) {
// Merge the user options into default grid axis options so
// that when a user option is set, it takes presedence.
gridAxisOptions = merge(true, {
className: ('highcharts-grid-axis ' + (userOptions.className || '')),
dateTimeLabelFormats: {
hour: {
list: ['%H:%M', '%H']
},
day: {
list: ['%A, %e. %B', '%a, %e. %b', '%E']
},
week: {
list: ['Week %W', 'W%W']
},
month: {
list: ['%B', '%b', '%o']
}
},
grid: {
borderWidth: 1
},
labels: {
padding: 2,
style: {
fontSize: '13px'
}
},
margin: 0,
title: {
text: null,
reserveSpace: false,
rotation: 0
},
// In a grid axis, only allow one unit of certain types,
// for example we shouln't have one grid cell spanning
// two days.
units: [[
'millisecond',
[1, 10, 100]
], [
'second',
[1, 10]
], [
'minute',
[1, 5, 15]
], [
'hour',
[1, 6]
], [
'day',
[1]
], [
'week',
[1]
], [
'month',
[1]
], [
'year',
null
]]
}, userOptions);
// X-axis specific options
if (this.coll === 'xAxis') {
// For linked axes, tickPixelInterval is used only if
// the tickPositioner below doesn't run or returns
// undefined (like multiple years)
if (defined(userOptions.linkedTo) &&
!defined(userOptions.tickPixelInterval)) {
gridAxisOptions.tickPixelInterval = 350;
}
// For the secondary grid axis, use the primary axis'
// tick intervals and return ticks one level higher.
if (
// Check for tick pixel interval in options
!defined(userOptions.tickPixelInterval) &&
// Only for linked axes
defined(userOptions.linkedTo) &&
!defined(userOptions.tickPositioner) &&
!defined(userOptions.tickInterval)) {
gridAxisOptions.tickPositioner = function (min, max) {
var parentInfo = (this.linkedParent &&
this.linkedParent.tickPositions &&
this.linkedParent.tickPositions.info);
if (parentInfo) {
var units = (gridAxisOptions.units || []);
var unitIdx = void 0,
count = void 0,
unitName = void 0;
for (var i = 0; i < units.length; i++) {
if (units[i][0] ===
parentInfo.unitName) {
unitIdx = i;
break;
}
}
// Get the first allowed count on the next
// unit.
if (units[unitIdx + 1]) {
unitName = units[unitIdx + 1][0];
count =
(units[unitIdx + 1][1] || [1])[0];
// In case the base X axis shows years, make
// the secondary axis show ten times the
// years (#11427)
}
else if (parentInfo.unitName === 'year') {
unitName = 'year';
count = parentInfo.count * 10;
}
var unitRange = timeUnits[unitName];
this.tickInterval = unitRange * count;
return this.getTimeTicks({
unitRange: unitRange,
count: count,
unitName: unitName
}, min, max, this.options.startOfWeek);
}
};
}
}
// Now merge the combined options into the axis options
merge(true, this.options, gridAxisOptions);
if (this.horiz) {
/* _________________________
Make this: ___|_____|_____|_____|__|
^ ^
_________________________
Into this: |_____|_____|_____|_____|
^ ^ */
options.minPadding = pick(userOptions.minPadding, 0);
options.maxPadding = pick(userOptions.maxPadding, 0);
}
// If borderWidth is set, then use its value for tick and
// line width.
if (isNumber(options.grid.borderWidth)) {
options.tickWidth = options.lineWidth =
gridOptions.borderWidth;
}
}
}
/**
* @private
*/
function onAfterSetOptions2(e) {
var axis = this;
var userOptions = e.userOptions;
var gridOptions = userOptions && userOptions.grid || {};
var columns = gridOptions.columns;
// Add column options to the parent axis. Children has their column
// options set on init in onGridAxisAfterInit.
if (gridOptions.enabled && columns) {
merge(true, axis.options, columns[columns.length - 1]);
}
}
/**
* Handle columns and setScale.
* @private
*/
function onAfterSetScale() {
var axis = this;
(axis.grid.columns || []).forEach(function (column) {
column.setScale();
});
}
/**
* Draw vertical axis ticks extra long to create cell floors and roofs.
* Overrides the tickLength for vertical axes.
* @private
*/
function onAfterTickSize(e) {
var defaultLeftAxisOptions = AxisDefaults.defaultLeftAxisOptions;
var _a = this,
horiz = _a.horiz,
maxLabelDimensions = _a.maxLabelDimensions,
_b = _a.options.grid,
gridOptions = _b === void 0 ? {} : _b;
if (gridOptions.enabled && maxLabelDimensions) {
var labelPadding = (Math.abs(defaultLeftAxisOptions.labels.x) * 2);
var distance = horiz ?
gridOptions.cellHeight || labelPadding + maxLabelDimensions.height :
labelPadding + maxLabelDimensions.width;
if (isArray(e.tickSize)) {
e.tickSize[0] = distance;
}
else {
e.tickSize = [distance, 0];
}
}
}
/**
* @private
*/
function onChartAfterSetChartSize() {
this.axes.forEach(function (axis) {
(axis.grid && axis.grid.columns || []).forEach(function (column) {
column.setAxisSize();
column.setAxisTranslation();
});
});
}
/**
* @private
*/
function onDestroy(e) {
var grid = this.grid;
(grid.columns || []).forEach(function (column) {
column.destroy(e.keepEvents);
});
grid.columns = void 0;
}
/**
* Wraps axis init to draw cell walls on vertical axes.
* @private
*/
function onInit(e) {
var axis = this;
var userOptions = e.userOptions || {};
var gridOptions = userOptions.grid || {};
if (gridOptions.enabled && defined(gridOptions.borderColor)) {
userOptions.tickColor = userOptions.lineColor = gridOptions.borderColor;
}
if (!axis.grid) {
axis.grid = new Additions(axis);
}
axis.hiddenLabels = [];
}
/**
* Center tick labels in cells.
* @private
*/
function onTickAfterGetLabelPosition(e) {
var tick = this,
label = tick.label,
axis = tick.axis,
reversed = axis.reversed,
chart = axis.chart,
options = axis.options,
gridOptions = options.grid || {},
labelOpts = axis.options.labels,
align = labelOpts.align,
// verticalAlign is currently not supported for axis.labels.
verticalAlign = 'middle', // labelOpts.verticalAlign,
side = GridAxis.Side[axis.side],
tickmarkOffset = e.tickmarkOffset,
tickPositions = axis.tickPositions,
tickPos = tick.pos - tickmarkOffset,
nextTickPos = (isNumber(tickPositions[e.index + 1]) ?
tickPositions[e.index + 1] - tickmarkOffset :
(axis.max || 0) + tickmarkOffset),
tickSize = axis.tickSize('tick'),
tickWidth = tickSize ? tickSize[0] : 0,
crispCorr = tickSize ? tickSize[1] / 2 : 0;
var labelHeight,
lblMetrics,
lines,
bottom,
top,
left,
right;
// Only center tick labels in grid axes
if (gridOptions.enabled === true) {
// Calculate top and bottom positions of the cell.
if (side === 'top') {
bottom = axis.top + axis.offset;
top = bottom - tickWidth;
}
else if (side === 'bottom') {
top = chart.chartHeight - axis.bottom + axis.offset;
bottom = top + tickWidth;
}
else {
bottom = axis.top + axis.len - (axis.translate(reversed ? nextTickPos : tickPos) || 0);
top = axis.top + axis.len - (axis.translate(reversed ? tickPos : nextTickPos) || 0);
}
// Calculate left and right positions of the cell.
if (side === 'right') {
left = chart.chartWidth - axis.right + axis.offset;
right = left + tickWidth;
}
else if (side === 'left') {
right = axis.left + axis.offset;
left = right - tickWidth;
}
else {
left = Math.round(axis.left + (axis.translate(reversed ? nextTickPos : tickPos) || 0)) - crispCorr;
right = Math.min(// #15742
Math.round(axis.left + (axis.translate(reversed ? tickPos : nextTickPos) || 0)) - crispCorr, axis.left + axis.len);
}
tick.slotWidth = right - left;
// Calculate the positioning of the label based on
// alignment.
e.pos.x = (align === 'left' ?
left :
align === 'right' ?
right :
left + ((right - left) / 2) // default to center
);
e.pos.y = (verticalAlign === 'top' ?
top :
verticalAlign === 'bottom' ?
bottom :
top + ((bottom - top) / 2) // default to middle
);
lblMetrics = chart.renderer.fontMetrics(labelOpts.style.fontSize, label && label.element);
labelHeight = label ? label.getBBox().height : 0;
// Adjustment to y position to align the label correctly.
// Would be better to have a setter or similar for this.
if (!labelOpts.useHTML) {
lines = Math.round(labelHeight / lblMetrics.h);
e.pos.y += (
// Center the label
// TODO: why does this actually center the label?
((lblMetrics.b - (lblMetrics.h - lblMetrics.f)) / 2) +
// Adjust for height of additional lines.
-(((lines - 1) * lblMetrics.h) / 2));
}
else {
e.pos.y += (
// Readjust yCorr in htmlUpdateTransform
lblMetrics.b +
// Adjust for height of html label
-(labelHeight / 2));
}
e.pos.x += (axis.horiz && labelOpts.x) || 0;
}
}
/**
* @private
*/
function onTickLabelFormat(ctx) {
var axis = ctx.axis,
value = ctx.value;
if (axis.options.grid &&
axis.options.grid.enabled) {
var tickPos = axis.tickPositions;
var series = (axis.linkedParent || axis).series[0];
var isFirst = value === tickPos[0];
var isLast = value === tickPos[tickPos.length - 1];
var point = series && find(series.options.data,
function (p) {
return p[axis.isXAxis ? 'x' : 'y'] === value;
});
var pointCopy = void 0;
if (point && series.is('gantt')) {
// For the Gantt set point aliases to the pointCopy
// to do not change the original point
pointCopy = merge(point);
H.seriesTypes.gantt.prototype.pointClass
.setGanttPointAliases(pointCopy);
}
// Make additional properties available for the
// formatter
ctx.isFirst = isFirst;
ctx.isLast = isLast;
ctx.point = pointCopy;
}
}
/**
* Makes tick labels which are usually ignored in a linked axis
* displayed if they are within range of linkedParent.min.
* ```
* _____________________________
* | | | | |
* Make this: | | 2 | 3 | 4 |
* |___|_______|_______|_______|
* ^
* _____________________________
* | | | | |
* Into this: | 1 | 2 | 3 | 4 |
* |___|_______|_______|_______|
* ^
* ```
* @private
* @todo Does this function do what the drawing says? Seems to affect
* ticks and not the labels directly?
*/
function onTrimTicks() {
var axis = this;
var options = axis.options;
var gridOptions = options.grid || {};
var categoryAxis = axis.categories;
var tickPositions = axis.tickPositions;
var firstPos = tickPositions[0];
var lastPos = tickPositions[tickPositions.length - 1];
var linkedMin = axis.linkedParent && axis.linkedParent.min;
var linkedMax = axis.linkedParent && axis.linkedParent.max;
var min = linkedMin || axis.min;
var max = linkedMax || axis.max;
var tickInterval = axis.tickInterval;
var endMoreThanMin = (firstPos < min &&
firstPos + tickInterval > min);
var startLessThanMax = (lastPos > max &&
lastPos - tickInterval < max);
if (gridOptions.enabled === true &&
!categoryAxis &&
(axis.horiz || axis.isLinked)) {
if (endMoreThanMin && !options.startOnTick) {
tickPositions[0] = min;
}
if (startLessThanMax && !options.endOnTick) {
tickPositions[tickPositions.length - 1] = max;
}
}
}
/**
* Avoid altering tickInterval when reserving space.
* @private
*/
function wrapUnsquish(proceed) {
var axis = this;
var _a = axis.options.grid,
gridOptions = _a === void 0 ? {} : _a;
if (gridOptions.enabled === true && axis.categories) {
return axis.tickInterval;
}
return proceed.apply(axis, argsToArray(arguments));
}
/* *
*
* Class
*
* */
/**
* Additions for grid axes.
* @private
* @class
*/
var Additions = /** @class */ (function () {
/* *
*
* Constructors
*
* */
function Additions(axis) {
this.axis = axis;
}
/* *
*
* Functions
*
* */
/**
* Checks if an axis is the outer axis in its dimension. Since
* axes are placed outwards in order, the axis with the highest
* index is the outermost axis.
*
* Example: If there are multiple x-axes at the top of the chart,
* this function returns true if the axis supplied is the last
* of the x-axes.
*
* @private
*
* @return {boolean}
* True if the axis is the outermost axis in its dimension; false if
* not.
*/
Additions.prototype.isOuterAxis = function () {
var axis = this.axis;
var chart = axis.chart;
var columnIndex = axis.grid.columnIndex;
var columns = (axis.linkedParent && axis.linkedParent.grid.columns ||
axis.grid.columns);
var parentAxis = columnIndex ? axis.linkedParent : axis;
var thisIndex = -1,
lastIndex = 0;
chart[axis.coll].forEach(function (otherAxis, index) {
if (otherAxis.side === axis.side && !otherAxis.options.isInternal) {
lastIndex = index;
if (otherAxis === parentAxis) {
// Get the index of the axis in question
thisIndex = index;
}
}
});
return (lastIndex === thisIndex &&
(isNumber(columnIndex) ? columns.length === columnIndex : true));
};
/**
* Add extra border based on the provided path.
* *
* @private
*
* @param {SVGPath} path
* The path of the border.
*
* @return {Highcharts.SVGElement}
*/
Additions.prototype.renderBorder = function (path) {
var axis = this.axis,
renderer = axis.chart.renderer,
options = axis.options,
extraBorderLine = renderer.path(path)
.addClass('highcharts-axis-line')
.add(axis.axisBorder);
if (!renderer.styledMode) {
extraBorderLine.attr({
stroke: options.lineColor,
'stroke-width': options.lineWidth,
zIndex: 7
});
}
return extraBorderLine;
};
return Additions;
}());
GridAxis.Additions = Additions;
})(GridAxis || (GridAxis = {}));
/* *
*
* Registry
*
* */
// First letter of the day of the week, e.g. 'M' for 'Monday'.
dateFormats.E = function (timestamp) {
return this.dateFormat('%a', timestamp, true).charAt(0);
};
// Adds week date format
dateFormats.W = function (timestamp) {
var d = new this.Date(timestamp);
var firstDay = (this.get('Day',
d) + 6) % 7;
var thursday = new this.Date(d.valueOf());
this.set('Date', thursday, this.get('Date', d) - firstDay + 3);
var firstThursday = new this.Date(this.get('FullYear',
thursday), 0, 1);
if (this.get('Day', firstThursday) !== 4) {
this.set('Month', d, 0);
this.set('Date', d, 1 + (11 - this.get('Day', firstThursday)) % 7);
}
return (1 +
Math.floor((thursday.valueOf() - firstThursday.valueOf()) / 604800000)).toString();
};
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* @productdesc {gantt}
* For grid axes (like in Gantt charts),
* it is possible to declare as a list to provide different
* formats depending on available space.
*
* Defaults to:
* ```js
* {
* hour: { list: ['%H:%M', '%H'] },
* day: { list: ['%A, %e. %B', '%a, %e. %b', '%E'] },
* week: { list: ['Week %W', 'W%W'] },
* month: { list: ['%B', '%b', '%o'] }
* }
* ```
*
* @sample {gantt} gantt/grid-axis/date-time-label-formats
* Gantt chart with custom axis date format.
*
* @apioption xAxis.dateTimeLabelFormats
*/
/**
* Set grid options for the axis labels. Requires Highcharts Gantt.
*
* @since 6.2.0
* @product gantt
* @apioption xAxis.grid
*/
/**
* Enable grid on the axis labels. Defaults to true for Gantt charts.
*
* @type {boolean}
* @default true
* @since 6.2.0
* @product gantt
* @apioption xAxis.grid.enabled
*/
/**
* Set specific options for each column (or row for horizontal axes) in the
* grid. Each extra column/row is its own axis, and the axis options can be set
* here.
*
* @sample gantt/demo/left-axis-table
* Left axis as a table
*
* @type {Array<Highcharts.XAxisOptions>}
* @apioption xAxis.grid.columns
*/
/**
* Set border color for the label grid lines.
*
* @type {Highcharts.ColorString}
* @apioption xAxis.grid.borderColor
*/
/**
* Set border width of the label grid lines.
*
* @type {number}
* @default 1
* @apioption xAxis.grid.borderWidth
*/
/**
* Set cell height for grid axis labels. By default this is calculated from font
* size. This option only applies to horizontal axes.
*
* @sample gantt/grid-axis/cellheight
* Gant chart with custom cell height
* @type {number}
* @apioption xAxis.grid.cellHeight
*/
''; // keeps doclets above in JS file
return GridAxis;
});
_registerModule(_modules, 'Gantt/Tree.js', [_modules['Core/Utilities.js']], function (U) {
/* *
*
* (c) 2016-2021 Highsoft AS
*
* Authors: Jon Arild Nygard
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
/* eslint no-console: 0 */
var extend = U.extend,
isNumber = U.isNumber,
pick = U.pick;
/**
* Creates an object map from parent id to childrens index.
*
* @private
* @function Highcharts.Tree#getListOfParents
*
* @param {Array<*>} data
* List of points set in options. `Array.parent` is parent id of point.
*
* @param {Array<string>} ids
* List of all point ids.
*
* @return {Highcharts.Dictionary<Array<*>>}
* Map from parent id to children index in data
*/
var getListOfParents = function (data,
ids) {
var listOfParents = data.reduce(function (prev,
curr) {
var parent = pick(curr.parent, '');
if (typeof prev[parent] === 'undefined') {
prev[parent] = [];
}
prev[parent].push(curr);
return prev;
}, {}), parents = Object.keys(listOfParents);
// If parent does not exist, hoist parent to root of tree.
parents.forEach(function (parent, list) {
var children = listOfParents[parent];
if ((parent !== '') && (ids.indexOf(parent) === -1)) {
children.forEach(function (child) {
list[''].push(child);
});
delete list[parent];
}
});
return listOfParents;
};
var getNode = function (id,
parent,
level,
data,
mapOfIdToChildren,
options) {
var descendants = 0,
height = 0,
after = options && options.after,
before = options && options.before,
node = {
data: data,
depth: level - 1,
id: id,
level: level,
parent: parent
},
start,
end,
children;
// Allow custom logic before the children has been created.
if (typeof before === 'function') {
before(node, options);
}
// Call getNode recursively on the children. Calulate the height of the
// node, and the number of descendants.
children = ((mapOfIdToChildren[id] || [])).map(function (child) {
var node = getNode(child.id,
id, (level + 1),
child,
mapOfIdToChildren,
options),
childStart = child.start,
childEnd = (child.milestone === true ?
childStart :
child.end);
// Start should be the lowest child.start.
start = ((!isNumber(start) || childStart < start) ?
childStart :
start);
// End should be the largest child.end.
// If child is milestone, then use start as end.
end = ((!isNumber(end) || childEnd > end) ?
childEnd :
end);
descendants = descendants + 1 + node.descendants;
height = Math.max(node.height + 1, height);
return node;
});
// Calculate start and end for point if it is not already explicitly set.
if (data) {
data.start = pick(data.start, start);
data.end = pick(data.end, end);
}
extend(node, {
children: children,
descendants: descendants,
height: height
});
// Allow custom logic after the children has been created.
if (typeof after === 'function') {
after(node, options);
}
return node;
};
var getTree = function (data,
options) {
var ids = data.map(function (d) {
return d.id;
}), mapOfIdToChildren = getListOfParents(data, ids);
return getNode('', null, 1, null, mapOfIdToChildren, options);
};
var Tree = {
getListOfParents: getListOfParents,
getNode: getNode,
getTree: getTree
};
return Tree;
});
_registerModule(_modules, 'Core/Axis/TreeGridTick.js', [_modules['Core/Utilities.js']], function (U) {
/* *
*
* (c) 2016 Highsoft AS
* Authors: Jon Arild Nygard
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var addEvent = U.addEvent,
isObject = U.isObject,
isNumber = U.isNumber,
pick = U.pick,
wrap = U.wrap;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
var TreeGridTick;
(function (TreeGridTick) {
/* *
*
* Interfaces
*
* */
/* *
*
* Variables
*
* */
var applied = false;
/* *
*
* Functions
*
* */
/**
* @private
*/
function compose(TickClass) {
if (!applied) {
addEvent(TickClass, 'init', onInit);
wrap(TickClass.prototype, 'getLabelPosition', wrapGetLabelPosition);
wrap(TickClass.prototype, 'renderLabel', wrapRenderLabel);
// backwards compatibility
TickClass.prototype.collapse = function (redraw) {
this.treeGrid.collapse(redraw);
};
TickClass.prototype.expand = function (redraw) {
this.treeGrid.expand(redraw);
};
TickClass.prototype.toggleCollapse = function (redraw) {
this.treeGrid.toggleCollapse(redraw);
};
applied = true;
}
}
TreeGridTick.compose = compose;
/**
* @private
*/
function onInit() {
var tick = this;
if (!tick.treeGrid) {
tick.treeGrid = new Additions(tick);
}
}
/**
* @private
*/
function onTickHover(label) {
label.addClass('highcharts-treegrid-node-active');
if (!label.renderer.styledMode) {
label.css({
textDecoration: 'underline'
});
}
}
/**
* @private
*/
function onTickHoverExit(label, options) {
var css = isObject(options.style) ? options.style : {};
label.removeClass('highcharts-treegrid-node-active');
if (!label.renderer.styledMode) {
label.css({ textDecoration: css.textDecoration });
}
}
/**
* @private
*/
function renderLabelIcon(tick, params) {
var treeGrid = tick.treeGrid,
isNew = !treeGrid.labelIcon,
renderer = params.renderer,
labelBox = params.xy,
options = params.options,
width = options.width || 0,
height = options.height || 0,
iconCenter = {
x: labelBox.x - (width / 2) - (options.padding || 0),
y: labelBox.y - (height / 2)
},
rotation = params.collapsed ? 90 : 180,
shouldRender = params.show && isNumber(iconCenter.y);
var icon = treeGrid.labelIcon;
if (!icon) {
treeGrid.labelIcon = icon = renderer
.path(renderer.symbols[options.type](options.x || 0, options.y || 0, width, height))
.addClass('highcharts-label-icon')
.add(params.group);
}
// Set the new position, and show or hide
icon.attr({ y: shouldRender ? 0 : -9999 }); // #14904, #1338
// Presentational attributes
if (!renderer.styledMode) {
icon
.attr({
cursor: 'pointer',
'fill': pick(params.color, "#666666" /* neutralColor60 */),
'stroke-width': 1,
stroke: options.lineColor,
strokeWidth: options.lineWidth || 0
});
}
// Update the icon positions
icon[isNew ? 'attr' : 'animate']({
translateX: iconCenter.x,
translateY: iconCenter.y,
rotation: rotation
});
}
/**
* @private
*/
function wrapGetLabelPosition(proceed, x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var tick = this,
lbOptions = pick(tick.options && tick.options.labels,
labelOptions),
pos = tick.pos,
axis = tick.axis,
options = axis.options,
isTreeGrid = options.type === 'treegrid',
result = proceed.apply(tick,
[x,
y,
label,
horiz,
lbOptions,
tickmarkOffset,
index,
step]);
var symbolOptions,
indentation,
mapOfPosToGridNode,
node,
level;
if (isTreeGrid) {
symbolOptions = (lbOptions && isObject(lbOptions.symbol, true) ?
lbOptions.symbol :
{});
indentation = (lbOptions && isNumber(lbOptions.indentation) ?
lbOptions.indentation :
0);
mapOfPosToGridNode = axis.treeGrid.mapOfPosToGridNode;
node = mapOfPosToGridNode && mapOfPosToGridNode[pos];
level = (node && node.depth) || 1;
result.x += (
// Add space for symbols
((symbolOptions.width || 0) +
((symbolOptions.padding || 0) * 2)) +
// Apply indentation
((level - 1) * indentation));
}
return result;
}
/**
* @private
*/
function wrapRenderLabel(proceed) {
var tick = this, pos = tick.pos, axis = tick.axis, label = tick.label, mapOfPosToGridNode = axis.treeGrid.mapOfPosToGridNode, options = axis.options, labelOptions = pick(tick.options && tick.options.labels, options && options.labels), symbolOptions = (labelOptions && isObject(labelOptions.symbol, true) ?
labelOptions.symbol :
{}), node = mapOfPosToGridNode && mapOfPosToGridNode[pos], level = node && node.depth, isTreeGrid = options.type === 'treegrid', shouldRender = axis.tickPositions.indexOf(pos) > -1, prefixClassName = 'highcharts-treegrid-node-', styledMode = axis.chart.styledMode;
var collapsed,
addClassName,
removeClassName;
if (isTreeGrid && node) {
// Add class name for hierarchical styling.
if (label &&
label.element) {
label.addClass(prefixClassName + 'level-' + level);
}
}
proceed.apply(tick, Array.prototype.slice.call(arguments, 1));
if (isTreeGrid &&
label &&
label.element &&
node &&
node.descendants &&
node.descendants > 0) {
collapsed = axis.treeGrid.isCollapsed(node);
renderLabelIcon(tick, {
color: !styledMode && label.styles && label.styles.color || '',
collapsed: collapsed,
group: label.parentGroup,
options: symbolOptions,
renderer: label.renderer,
show: shouldRender,
xy: label.xy
});
// Add class name for the node.
addClassName = prefixClassName +
(collapsed ? 'collapsed' : 'expanded');
removeClassName = prefixClassName +
(collapsed ? 'expanded' : 'collapsed');
label
.addClass(addClassName)
.removeClass(removeClassName);
if (!styledMode) {
label.css({
cursor: 'pointer'
});
}
// Add events to both label text and icon
[label, tick.treeGrid.labelIcon].forEach(function (object) {
if (object && !object.attachedTreeGridEvents) {
// On hover
addEvent(object.element, 'mouseover', function () {
onTickHover(label);
});
// On hover out
addEvent(object.element, 'mouseout', function () {
onTickHoverExit(label, labelOptions);
});
addEvent(object.element, 'click', function () {
tick.treeGrid.toggleCollapse();
});
object.attachedTreeGridEvents = true;
}
});
}
}
/* *
*
* Classes
*
* */
/**
* @private
* @class
*/
var Additions = /** @class */ (function () {
/* *
*
* Constructors
*
* */
/**
* @private
*/
function Additions(tick) {
this.tick = tick;
}
/* *
*
* Functions
*
* */
/**
* Collapse the grid cell. Used when axis is of type treegrid.
*
* @see gantt/treegrid-axis/collapsed-dynamically/demo.js
*
* @private
* @function Highcharts.Tick#collapse
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart or wait for an explicit call to
* {@link Highcharts.Chart#redraw}
*/
Additions.prototype.collapse = function (redraw) {
var tick = this.tick,
axis = tick.axis,
brokenAxis = axis.brokenAxis;
if (brokenAxis &&
axis.treeGrid.mapOfPosToGridNode) {
var pos = tick.pos,
node = axis.treeGrid.mapOfPosToGridNode[pos],
breaks = axis.treeGrid.collapse(node);
brokenAxis.setBreaks(breaks, pick(redraw, true));
}
};
/**
* Expand the grid cell. Used when axis is of type treegrid.
*
* @see gantt/treegrid-axis/collapsed-dynamically/demo.js
*
* @private
* @function Highcharts.Tick#expand
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart or wait for an explicit call to
* {@link Highcharts.Chart#redraw}
*/
Additions.prototype.expand = function (redraw) {
var tick = this.tick,
axis = tick.axis,
brokenAxis = axis.brokenAxis;
if (brokenAxis &&
axis.treeGrid.mapOfPosToGridNode) {
var pos = tick.pos,
node = axis.treeGrid.mapOfPosToGridNode[pos],
breaks = axis.treeGrid.expand(node);
brokenAxis.setBreaks(breaks, pick(redraw, true));
}
};
/**
* Toggle the collapse/expand state of the grid cell. Used when axis is
* of type treegrid.
*
* @see gantt/treegrid-axis/collapsed-dynamically/demo.js
*
* @private
* @function Highcharts.Tick#toggleCollapse
*
* @param {boolean} [redraw=true]
* Whether to redraw the chart or wait for an explicit call to
* {@link Highcharts.Chart#redraw}
*/
Additions.prototype.toggleCollapse = function (redraw) {
var tick = this.tick,
axis = tick.axis,
brokenAxis = axis.brokenAxis;
if (brokenAxis &&
axis.treeGrid.mapOfPosToGridNode) {
var pos = tick.pos,
node = axis.treeGrid.mapOfPosToGridNode[pos],
breaks = axis.treeGrid.toggleCollapse(node);
brokenAxis.setBreaks(breaks, pick(redraw, true));
}
};
return Additions;
}());
TreeGridTick.Additions = Additions;
})(TreeGridTick || (TreeGridTick = {}));
return TreeGridTick;
});
_registerModule(_modules, 'Series/TreeUtilities.js', [_modules['Core/Color/Color.js'], _modules['Core/Utilities.js']], function (Color, U) {
/* *
*
* (c) 2014-2021 Highsoft AS
*
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var extend = U.extend,
isArray = U.isArray,
isNumber = U.isNumber,
isObject = U.isObject,
merge = U.merge,
pick = U.pick;
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
function getColor(node, options) {
var index = options.index,
mapOptionsToLevel = options.mapOptionsToLevel,
parentColor = options.parentColor,
parentColorIndex = options.parentColorIndex,
series = options.series,
colors = options.colors,
siblings = options.siblings,
points = series.points,
chartOptionsChart = series.chart.options.chart;
var getColorByPoint,
point,
level,
colorByPoint,
colorIndexByPoint,
color,
colorIndex;
/**
* @private
*/
var variateColor = function (color) {
var colorVariation = level && level.colorVariation;
if (colorVariation &&
colorVariation.key === 'brightness' &&
index &&
siblings) {
return Color.parse(color).brighten(colorVariation.to * (index / siblings)).get();
}
return color;
};
if (node) {
point = points[node.i];
level = mapOptionsToLevel[node.level] || {};
getColorByPoint = point && level.colorByPoint;
if (getColorByPoint) {
colorIndexByPoint = point.index % (colors ?
colors.length :
chartOptionsChart.colorCount);
colorByPoint = colors && colors[colorIndexByPoint];
}
// Select either point color, level color or inherited color.
if (!series.chart.styledMode) {
color = pick(point && point.options.color, level && level.color, colorByPoint, parentColor && variateColor(parentColor), series.color);
}
colorIndex = pick(point && point.options.colorIndex, level && level.colorIndex, colorIndexByPoint, parentColorIndex, options.colorIndex);
}
return {
color: color,
colorIndex: colorIndex
};
}
/**
* Creates a map from level number to its given options.
*
* @private
*
* @param {object} params
* Object containing parameters.
* - `defaults` Object containing default options. The default options are
* merged with the userOptions to get the final options for a specific
* level.
* - `from` The lowest level number.
* - `levels` User options from series.levels.
* - `to` The highest level number.
*
* @return {Highcharts.Dictionary<object>|null}
* Returns a map from level number to its given options.
*/
function getLevelOptions(params) {
var result = null,
defaults,
converted,
i,
from,
to,
levels;
if (isObject(params)) {
result = {};
from = isNumber(params.from) ? params.from : 1;
levels = params.levels;
converted = {};
defaults = isObject(params.defaults) ? params.defaults : {};
if (isArray(levels)) {
converted = levels.reduce(function (obj, item) {
var level,
levelIsConstant,
options;
if (isObject(item) && isNumber(item.level)) {
options = merge({}, item);
levelIsConstant = pick(options.levelIsConstant, defaults.levelIsConstant);
// Delete redundant properties.
delete options.levelIsConstant;
delete options.level;
// Calculate which level these options apply to.
level = item.level + (levelIsConstant ? 0 : from - 1);
if (isObject(obj[level])) {
merge(true, obj[level], options); // #16329
}
else {
obj[level] = options;
}
}
return obj;
}, {});
}
to = isNumber(params.to) ? params.to : 1;
for (i = 0; i <= to; i++) {
result[i] = merge({}, defaults, isObject(converted[i]) ? converted[i] : {});
}
}
return result;
}
/**
* @private
* @todo Combine buildTree and buildNode with setTreeValues
* @todo Remove logic from Treemap and make it utilize this mixin.
*/
function setTreeValues(tree, options) {
var before = options.before,
idRoot = options.idRoot,
mapIdToNode = options.mapIdToNode,
nodeRoot = mapIdToNode[idRoot],
levelIsConstant = (options.levelIsConstant !== false),
points = options.points,
point = points[tree.i],
optionsPoint = point && point.options || {},
children = [];
var childrenTotal = 0;
tree.levelDynamic = tree.level - (levelIsConstant ? 0 : nodeRoot.level);
tree.name = pick(point && point.name, '');
tree.visible = (idRoot === tree.id ||
options.visible === true);
if (typeof before === 'function') {
tree = before(tree, options);
}
// First give the children some values
tree.children.forEach(function (child, i) {
var newOptions = extend({},
options);
extend(newOptions, {
index: i,
siblings: tree.children.length,
visible: tree.visible
});
child = setTreeValues(child, newOptions);
children.push(child);
if (child.visible) {
childrenTotal += child.val;
}
});
// Set the values
var value = pick(optionsPoint.value,
childrenTotal);
tree.visible = value >= 0 && (childrenTotal > 0 || tree.visible);
tree.children = children;
tree.childrenTotal = childrenTotal;
tree.isLeaf = tree.visible && !childrenTotal;
tree.val = value;
return tree;
}
/**
* Update the rootId property on the series. Also makes sure that it is
* accessible to exporting.
*
* @private
*
* @param {object} series
* The series to operate on.
*
* @return {string}
* Returns the resulting rootId after update.
*/
function updateRootId(series) {
var rootId,
options;
if (isObject(series)) {
// Get the series options.
options = isObject(series.options) ? series.options : {};
// Calculate the rootId.
rootId = pick(series.rootNode, options.rootId, '');
// Set rootId on series.userOptions to pick it up in exporting.
if (isObject(series.userOptions)) {
series.userOptions.rootId = rootId;
}
// Set rootId on series to pick it up on next update.
series.rootNode = rootId;
}
return rootId;
}
/* *
*
* Default Export
*
* */
var TreeUtilities = {
getColor: getColor,
getLevelOptions: getLevelOptions,
setTreeValues: setTreeValues,
updateRootId: updateRootId
};
return TreeUtilities;
});
_registerModule(_modules, 'Core/Axis/TreeGridAxis.js', [_modules['Core/Axis/BrokenAxis.js'], _modules['Core/Axis/GridAxis.js'], _modules['Gantt/Tree.js'], _modules['Core/Axis/TreeGridTick.js'], _modules['Series/TreeUtilities.js'], _modules['Core/Utilities.js']], function (BrokenAxis, GridAxis, Tree, TreeGridTick, TU, U) {
/* *
*
* (c) 2016 Highsoft AS
* Authors: Jon Arild Nygard
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var getLevelOptions = TU.getLevelOptions;
var addEvent = U.addEvent,
find = U.find,
fireEvent = U.fireEvent,
isArray = U.isArray,
isObject = U.isObject,
isString = U.isString,
merge = U.merge,
pick = U.pick,
wrap = U.wrap;
/**
* @private
*/
var TreeGridAxis;
(function (TreeGridAxis) {
/* *
*
* Declarations
*
* */
/* *
*
* Variables
*
* */
var TickConstructor;
/* *
*
* Functions
*
* */
/**
* @private
*/
function compose(AxisClass, ChartClass, SeriesClass, TickClass) {
if (AxisClass.keepProps.indexOf('treeGrid') === -1) {
AxisClass.keepProps.push('treeGrid');
TickConstructor = TickClass;
wrap(AxisClass.prototype, 'generateTick', wrapGenerateTick);
wrap(AxisClass.prototype, 'init', wrapInit);
wrap(AxisClass.prototype, 'setTickInterval', wrapSetTickInterval);
// Make utility functions available for testing.
AxisClass.prototype.utils = {
getNode: Tree.getNode
};
GridAxis.compose(AxisClass, ChartClass, TickClass);
BrokenAxis.compose(AxisClass, SeriesClass);
TreeGridTick.compose(TickClass);
}
return AxisClass;
}
TreeGridAxis.compose = compose;
/**
* @private
*/
function getBreakFromNode(node, max) {
var to = node.collapseEnd || 0;
var from = node.collapseStart || 0;
// In broken-axis, the axis.max is minimized until it is not within a
// break. Therefore, if break.to is larger than axis.max, the axis.to
// should not add the 0.5 axis.tickMarkOffset, to avoid adding a break
// larger than axis.max.
// TODO consider simplifying broken-axis and this might solve itself
if (to >= max) {
from -= 0.5;
}
return {
from: from,
to: to,
showPoints: false
};
}
/**
* Creates a tree structure of the data, and the treegrid. Calculates
* categories, and y-values of points based on the tree.
*
* @private
* @function getTreeGridFromData
*
* @param {Array<Highcharts.GanttPointOptions>} data
* All the data points to display in the axis.
*
* @param {boolean} uniqueNames
* Wether or not the data node with the same name should share grid cell. If
* true they do share cell. False by default.
*
* @param {number} numberOfSeries
*
* @return {object}
* Returns an object containing categories, mapOfIdToNode,
* mapOfPosToGridNode, and tree.
*
* @todo There should be only one point per line.
* @todo It should be optional to have one category per point, or merge
* cells
* @todo Add unit-tests.
*/
function getTreeGridFromData(data, uniqueNames, numberOfSeries) {
var categories = [],
collapsedNodes = [],
mapOfIdToNode = {},
uniqueNamesEnabled = typeof uniqueNames === 'boolean' ? uniqueNames : false;
var mapOfPosToGridNode = {},
posIterator = -1;
// Build the tree from the series data.
var treeParams = {
// After the children has been created.
after: function (node) {
var gridNode = mapOfPosToGridNode[node.pos];
var height = 0,
descendants = 0;
gridNode.children.forEach(function (child) {
descendants += (child.descendants || 0) + 1;
height = Math.max((child.height || 0) + 1, height);
});
gridNode.descendants = descendants;
gridNode.height = height;
if (gridNode.collapsed) {
collapsedNodes.push(gridNode);
}
},
// Before the children has been created.
before: function (node) {
var data = isObject(node.data,
true) ? node.data : {},
name = isString(data.name) ? data.name : '',
parentNode = mapOfIdToNode[node.parent],
parentGridNode = (isObject(parentNode,
true) ?
mapOfPosToGridNode[parentNode.pos] :
null),
hasSameName = function (x) {
return x.name === name;
};
var gridNode,
pos;
// If not unique names, look for sibling node with the same name
if (uniqueNamesEnabled &&
isObject(parentGridNode, true) &&
!!(gridNode = find(parentGridNode.children, hasSameName))) {
// If there is a gridNode with the same name, reuse position
pos = gridNode.pos;
// Add data node to list of nodes in the grid node.
gridNode.nodes.push(node);
}
else {
// If it is a new grid node, increment position.
pos = posIterator++;
}
// Add new grid node to map.
if (!mapOfPosToGridNode[pos]) {
mapOfPosToGridNode[pos] = gridNode = {
depth: parentGridNode ? parentGridNode.depth + 1 : 0,
name: name,
id: data.id,
nodes: [node],
children: [],
pos: pos
};
// If not root, then add name to categories.
if (pos !== -1) {
categories.push(name);
}
// Add name to list of children.
if (isObject(parentGridNode, true)) {
parentGridNode.children.push(gridNode);
}
}
// Add data node to map
if (isString(node.id)) {
mapOfIdToNode[node.id] = node;
}
// If one of the points are collapsed, then start the grid node
// in collapsed state.
if (gridNode &&
data.collapsed === true) {
gridNode.collapsed = true;
}
// Assign pos to data node
node.pos = pos;
}
};
var updateYValuesAndTickPos = function (map,
numberOfSeries) {
var setValues = function (gridNode,
start,
result) {
var nodes = gridNode.nodes,
padding = 0.5;
var end = start + (start === -1 ? 0 : numberOfSeries - 1);
var diff = (end - start) / 2,
pos = start + diff;
nodes.forEach(function (node) {
var data = node.data;
if (isObject(data, true)) {
// Update point
data.y = start + (data.seriesIndex || 0);
// Remove the property once used
delete data.seriesIndex;
}
node.pos = pos;
});
result[pos] = gridNode;
gridNode.pos = pos;
gridNode.tickmarkOffset = diff + padding;
gridNode.collapseStart = end + padding;
gridNode.children.forEach(function (child) {
setValues(child, end + 1, result);
end = (child.collapseEnd || 0) - padding;
});
// Set collapseEnd to the end of the last child node.
gridNode.collapseEnd = end + padding;
return result;
};
return setValues(map['-1'], -1, {});
};
// Create tree from data
var tree = Tree.getTree(data,
treeParams);
// Update y values of data, and set calculate tick positions.
mapOfPosToGridNode = updateYValuesAndTickPos(mapOfPosToGridNode, numberOfSeries);
// Return the resulting data.
return {
categories: categories,
mapOfIdToNode: mapOfIdToNode,
mapOfPosToGridNode: mapOfPosToGridNode,
collapsedNodes: collapsedNodes,
tree: tree
};
}
/**
* Builds the tree of categories and calculates its positions.
* @private
* @param {object} e Event object
* @param {object} e.target The chart instance which the event was fired on.
* @param {object[]} e.target.axes The axes of the chart.
*/
function onBeforeRender(e) {
var chart = e.target,
axes = chart.axes;
axes.filter(function (axis) {
return axis.options.type === 'treegrid';
}).forEach(function (axis) {
var options = axis.options || {},
labelOptions = options.labels,
uniqueNames = options.uniqueNames,
max = options.max,
// Check whether any of series is rendering for the first
// time, visibility has changed, or its data is dirty, and
// only then update. #10570, #10580
// Also check if mapOfPosToGridNode exists. #10887
isDirty = (!axis.treeGrid.mapOfPosToGridNode ||
axis.series.some(function (series) {
return !series.hasRendered ||
series.isDirtyData ||
series.isDirty;
}));
var numberOfSeries = 0,
data,
treeGrid;
if (isDirty) {
// Concatenate data from all series assigned to this axis.
data = axis.series.reduce(function (arr, s) {
if (s.visible) {
// Push all data to array
(s.options.data || []).forEach(function (data) {
// For using keys - rebuild the data structure
if (s.options.keys && s.options.keys.length) {
data = s.pointClass.prototype.optionsToObject.call({ series: s }, data);
s.pointClass.setGanttPointAliases(data);
}
if (isObject(data, true)) {
// Set series index on data. Removed again
// after use.
data.seriesIndex = numberOfSeries;
arr.push(data);
}
});
// Increment series index
if (uniqueNames === true) {
numberOfSeries++;
}
}
return arr;
}, []);
// If max is higher than set data - add a
// dummy data to render categories #10779
if (max && data.length < max) {
for (var i = data.length; i <= max; i++) {
data.push({
// Use the zero-width character
// to avoid conflict with uniqueNames
name: i + '\u200B'
});
}
}
// setScale is fired after all the series is initialized,
// which is an ideal time to update the axis.categories.
treeGrid = getTreeGridFromData(data, uniqueNames || false, (uniqueNames === true) ? numberOfSeries : 1);
// Assign values to the axis.
axis.categories = treeGrid.categories;
axis.treeGrid.mapOfPosToGridNode = treeGrid.mapOfPosToGridNode;
axis.hasNames = true;
axis.treeGrid.tree = treeGrid.tree;
// Update yData now that we have calculated the y values
axis.series.forEach(function (series) {
var axisData = (series.options.data || []).map(function (d) {
if (isArray(d) && series.options.keys && series.options.keys.length) {
// Get the axisData from the data array used to
// build the treeGrid where has been modified
data.forEach(function (point) {
if (d.indexOf(point.x) >= 0 && d.indexOf(point.x2) >= 0) {
d = point;
}
});
}
return isObject(d, true) ? merge(d) : d;
});
// Avoid destroying points when series is not visible
if (series.visible) {
series.setData(axisData, false);
}
});
// Calculate the label options for each level in the tree.
axis.treeGrid.mapOptionsToLevel =
getLevelOptions({
defaults: labelOptions,
from: 1,
levels: labelOptions && labelOptions.levels,
to: axis.treeGrid.tree && axis.treeGrid.tree.height
});
// Setting initial collapsed nodes
if (e.type === 'beforeRender') {
axis.treeGrid.collapsedNodes = treeGrid.collapsedNodes;
}
}
});
}
/**
* Generates a tick for initial positioning.
*
* @private
* @function Highcharts.GridAxis#generateTick
*
* @param {Function} proceed
* The original generateTick function.
*
* @param {number} pos
* The tick position in axis values.
*/
function wrapGenerateTick(proceed, pos) {
var axis = this,
mapOptionsToLevel = axis.treeGrid.mapOptionsToLevel || {},
isTreeGrid = axis.options.type === 'treegrid',
ticks = axis.ticks;
var tick = ticks[pos],
levelOptions,
options,
gridNode;
if (isTreeGrid &&
axis.treeGrid.mapOfPosToGridNode) {
gridNode = axis.treeGrid.mapOfPosToGridNode[pos];
levelOptions = mapOptionsToLevel[gridNode.depth];
if (levelOptions) {
options = {
labels: levelOptions
};
}
if (!tick &&
TickConstructor) {
ticks[pos] = tick =
new TickConstructor(axis, pos, void 0, void 0, {
category: gridNode.name,
tickmarkOffset: gridNode.tickmarkOffset,
options: options
});
}
else {
// update labels depending on tick interval
tick.parameters.category = gridNode.name;
tick.options = options;
tick.addLabel();
}
}
else {
proceed.apply(axis, Array.prototype.slice.call(arguments, 1));
}
}
/**
* @private
*/
function wrapInit(proceed, chart, userOptions) {
var axis = this,
isTreeGrid = userOptions.type === 'treegrid';
if (!axis.treeGrid) {
axis.treeGrid = new Additions(axis);
}
// Set default and forced options for TreeGrid
if (isTreeGrid) {
// Add event for updating the categories of a treegrid.
// NOTE Preferably these events should be set on the axis.
addEvent(chart, 'beforeRender', onBeforeRender);
addEvent(chart, 'beforeRedraw', onBeforeRender);
// Add new collapsed nodes on addseries
addEvent(chart, 'addSeries', function (e) {
if (e.options.data) {
var treeGrid = getTreeGridFromData(e.options.data,
userOptions.uniqueNames || false, 1);
axis.treeGrid.collapsedNodes = (axis.treeGrid.collapsedNodes || []).concat(treeGrid.collapsedNodes);
}
});
// Collapse all nodes in axis.treegrid.collapsednodes
// where collapsed equals true.
addEvent(axis, 'foundExtremes', function () {
if (axis.treeGrid.collapsedNodes) {
axis.treeGrid.collapsedNodes.forEach(function (node) {
var breaks = axis.treeGrid.collapse(node);
if (axis.brokenAxis) {
axis.brokenAxis.setBreaks(breaks, false);
// remove the node from the axis collapsedNodes
if (axis.treeGrid.collapsedNodes) {
axis.treeGrid.collapsedNodes = axis.treeGrid.collapsedNodes.filter(function (n) {
return node.collapseStart !== n.collapseStart ||
node.collapseEnd !== n.collapseEnd;
});
}
}
});
}
});
// If staticScale is not defined on the yAxis
// and chart height is set, set axis.isDirty
// to ensure collapsing works (#12012)
addEvent(axis, 'afterBreaks', function () {
if (axis.coll === 'yAxis' &&
!axis.staticScale &&
axis.chart.options.chart.height) {
axis.isDirty = true;
}
});
userOptions = merge({
// Default options
grid: {
enabled: true
},
// TODO: add support for align in treegrid.
labels: {
align: 'left',
/**
* Set options on specific levels in a tree grid axis. Takes
* precedence over labels options.
*
* @sample {gantt} gantt/treegrid-axis/labels-levels
* Levels on TreeGrid Labels
*
* @type {Array<*>}
* @product gantt
* @apioption yAxis.labels.levels
*
* @private
*/
levels: [{
/**
* Specify the level which the options within this object
* applies to.
*
* @type {number}
* @product gantt
* @apioption yAxis.labels.levels.level
*
* @private
*/
level: void 0
}, {
level: 1,
/**
* @type {Highcharts.CSSObject}
* @product gantt
* @apioption yAxis.labels.levels.style
*
* @private
*/
style: {
/** @ignore-option */
fontWeight: 'bold'
}
}],
/**
* The symbol for the collapse and expand icon in a
* treegrid.
*
* @product gantt
* @optionparent yAxis.labels.symbol
*
* @private
*/
symbol: {
/**
* The symbol type. Points to a definition function in
* the `Highcharts.Renderer.symbols` collection.
*
* @type {Highcharts.SymbolKeyValue}
*
* @private
*/
type: 'triangle',
x: -5,
y: -5,
height: 10,
width: 10,
padding: 5
}
},
uniqueNames: false
}, userOptions, {
// Forced options
reversed: true,
// grid.columns is not supported in treegrid
grid: {
columns: void 0
}
});
}
// Now apply the original function with the original arguments,
// which are sliced off this function's arguments
proceed.apply(axis, [chart, userOptions]);
if (isTreeGrid) {
axis.hasNames = true;
axis.options.showLastLabel = true;
}
}
/**
* Set the tick positions, tickInterval, axis min and max.
*
* @private
* @function Highcharts.GridAxis#setTickInterval
*
* @param {Function} proceed
* The original setTickInterval function.
*/
function wrapSetTickInterval(proceed) {
var axis = this,
options = axis.options,
isTreeGrid = options.type === 'treegrid';
if (isTreeGrid) {
axis.min = pick(axis.userMin, options.min, axis.dataMin);
axis.max = pick(axis.userMax, options.max, axis.dataMax);
fireEvent(axis, 'foundExtremes');
// setAxisTranslation modifies the min and max according to
// axis breaks.
axis.setAxisTranslation();
axis.tickmarkOffset = 0.5;
axis.tickInterval = 1;
axis.tickPositions = axis.treeGrid.mapOfPosToGridNode ?
axis.treeGrid.getTickPositions() :
[];
}
else {
proceed.apply(axis, Array.prototype.slice.call(arguments, 1));
}
}
/* *
*
* Classes
*
* */
/**
* @private
* @class
*/
var Additions = /** @class */ (function () {
/* *
*
* Constructors
*
* */
/**
* @private
*/
function Additions(axis) {
this.axis = axis;
}
/* *
*
* Functions
*
* */
/**
* Set the collapse status.
*
* @private
*
* @param {Highcharts.Axis} axis
* The axis to check against.
*
* @param {Highcharts.GridNode} node
* The node to collapse.
*/
Additions.prototype.setCollapsedStatus = function (node) {
var axis = this.axis,
chart = axis.chart;
axis.series.forEach(function (series) {
var data = series.options.data;
if (node.id && data) {
var point = chart.get(node.id),
dataPoint = data[series.data.indexOf(point)];
if (point && dataPoint) {
point.collapsed = node.collapsed;
dataPoint.collapsed = node.collapsed;
}
}
});
};
/**
* Calculates the new axis breaks to collapse a node.
*
* @private
*
* @param {Highcharts.Axis} axis
* The axis to check against.
*
* @param {Highcharts.GridNode} node
* The node to collapse.
*
* @param {number} pos
* The tick position to collapse.
*
* @return {Array<object>}
* Returns an array of the new breaks for the axis.
*/
Additions.prototype.collapse = function (node) {
var axis = this.axis,
breaks = (axis.options.breaks || []),
obj = getBreakFromNode(node,
axis.max);
breaks.push(obj);
// Change the collapsed flag #13838
node.collapsed = true;
axis.treeGrid.setCollapsedStatus(node);
return breaks;
};
/**
* Calculates the new axis breaks to expand a node.
*
* @private
*
* @param {Highcharts.Axis} axis
* The axis to check against.
*
* @param {Highcharts.GridNode} node
* The node to expand.
*
* @param {number} pos
* The tick position to expand.
*
* @return {Array<object>}
* Returns an array of the new breaks for the axis.
*/
Additions.prototype.expand = function (node) {
var axis = this.axis,
breaks = (axis.options.breaks || []),
obj = getBreakFromNode(node,
axis.max);
// Change the collapsed flag #13838
node.collapsed = false;
axis.treeGrid.setCollapsedStatus(node);
// Remove the break from the axis breaks array.
return breaks.reduce(function (arr, b) {
if (b.to !== obj.to || b.from !== obj.from) {
arr.push(b);
}
return arr;
}, []);
};
/**
* Creates a list of positions for the ticks on the axis. Filters out
* positions that are outside min and max, or is inside an axis break.
*
* @private
*
* @return {Array<number>}
* List of positions.
*/
Additions.prototype.getTickPositions = function () {
var axis = this.axis,
roundedMin = Math.floor(axis.min / axis.tickInterval) * axis.tickInterval,
roundedMax = Math.ceil(axis.max / axis.tickInterval) * axis.tickInterval;
return Object.keys(axis.treeGrid.mapOfPosToGridNode || {}).reduce(function (arr, key) {
var pos = +key;
if (pos >= roundedMin &&
pos <= roundedMax &&
!(axis.brokenAxis && axis.brokenAxis.isInAnyBreak(pos))) {
arr.push(pos);
}
return arr;
}, []);
};
/**
* Check if a node is collapsed.
*
* @private
*
* @param {Highcharts.Axis} axis
* The axis to check against.
*
* @param {object} node
* The node to check if is collapsed.
*
* @param {number} pos
* The tick position to collapse.
*
* @return {boolean}
* Returns true if collapsed, false if expanded.
*/
Additions.prototype.isCollapsed = function (node) {
var axis = this.axis,
breaks = (axis.options.breaks || []),
obj = getBreakFromNode(node,
axis.max);
return breaks.some(function (b) {
return b.from === obj.from && b.to === obj.to;
});
};
/**
* Calculates the new axis breaks after toggling the collapse/expand
* state of a node. If it is collapsed it will be expanded, and if it is
* exapended it will be collapsed.
*
* @private
*
* @param {Highcharts.Axis} axis
* The axis to check against.
*
* @param {Highcharts.GridNode} node
* The node to toggle.
*
* @return {Array<object>}
* Returns an array of the new breaks for the axis.
*/
Additions.prototype.toggleCollapse = function (node) {
return (this.isCollapsed(node) ?
this.expand(node) :
this.collapse(node));
};
return Additions;
}());
TreeGridAxis.Additions = Additions;
})(TreeGridAxis || (TreeGridAxis = {}));
return TreeGridAxis;
});
_registerModule(_modules, 'masters/modules/treegrid.src.js', [_modules['Core/Globals.js'], _modules['Core/Axis/TreeGridAxis.js']], function (Highcharts, TreeGridAxis) {
var G = Highcharts;
// Compositions
TreeGridAxis.compose(G.Axis, G.Chart, G.Series, G.Tick);
});
})); |
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Field, reduxForm } from 'redux-form'
import BackButton from '../BackButton'
import tomsterLogo from '../../images/tomster23.png'
import doggyLogo from '../../images/dog11.png'
import gridLogo from '../../images/option-grid.png'
export class Options extends Component {
render () {
return (
<div>
<div className="section">
<div className="section-title">
Options
</div>
</div>
<div className="section">
<div className="options-label">
Figure
</div>
<div className="options-container options-input">
<Field name="figure" id="tomster" component="input"
type="radio" value="tomster" />
<label htmlFor="tomster" className="options-button">
<img alt="tomster" src={tomsterLogo}
className="options-button-figure" />
</label>
<Field name="figure" id="dog" component="input"
type="radio" value="dog" />
<label htmlFor="dog" className="options-button">
<img alt="doggy" src={doggyLogo}
className="options-button-figure" />
</label>
</div>
</div>
<div className="section">
<div className="options-label">
Size
</div>
<div className="options-container options-input">
<Field name="size" id="4x4" component="input"
type="radio" value="4" />
<label htmlFor="4x4" className="options-button">
<span
style={{backgroundImage: `url(${gridLogo})`}}
className="options-button-size">
4 x 4
</span>
</label>
<Field name="size" id="6x6" component="input"
type="radio" value="6" />
<label htmlFor="6x6" className="options-button">
<span
style={{backgroundImage: `url(${gridLogo})`}}
className="options-button-size">
6 x 6
</span>
</label>
<Field name="size" id="8x8" component="input"
type="radio" value="8" />
<label htmlFor="8x8" className="options-button">
<span
style={{backgroundImage: `url(${gridLogo})`}}
className="options-button-size">
8 x 8
</span>
</label>
</div>
</div>
<div className="section">
<div className="options-label">
Music
</div>
<div className="options-container options-input">
<label className="options-switch">
<Field name="music" id="music" component="input" type="checkbox"
className="options-switch-checkbox" />
<div className="options-switch-slider" />
</label>
</div>
</div>
<div className="section">
<div className="options-label">
Music volume
</div>
<div className="options-container">
<Field name="musicVolume" id="musicVolume" component="input" type="range"
step="0.1" min="0.1" max="1" />
</div>
</div>
<div className="section">
<div className="options-label">
Sound effects
</div>
<div className="options-container">
<label className="options-switch">
<Field name="soundEffects" id="soundEffects"
component="input" type="checkbox"
className="options-switch-checkbox" />
<div className="options-switch-slider" />
</label>
</div>
</div>
<div className="section">
<div className="options-label">
Effects volume
</div>
<div className="options-container">
<Field name="effectsVolume" id="effectsVolume"
component="input" type="range"
step="0.1" min="0.1" max="1" />
</div>
</div>
<BackButton />
</div>
)
}
}
const mapStateToProps = state => ({
initialValues: state.intialOptions
})
export const OptionsForm = connect(mapStateToProps)(
reduxForm({
form: 'options',
destroyOnUnmount: false
})(Options)
)
|
console.log('build/webpack.base.conf.js');
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: ['babel-polyfill', './src/main.js']
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production' ?
config.build.assetsPublicPath : config.dev.assetsPublicPath
},
externals: {
"element-ui": 'window.ELEMENT',
'vue': 'window.Vue',
'vue-router': 'window.VueRouter',
'vuex': 'window.Vuex'
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src')
}
},
module: {
rules: [{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
|
/*
Highcharts Gantt JS v9.3.3 (2022-02-01)
Tree Grid
(c) 2016-2021 Jon Arild Nygard
License: www.highcharts.com/license
*/
'use strict';(function(h){"object"===typeof module&&module.exports?(h["default"]=h,module.exports=h):"function"===typeof define&&define.amd?define("highcharts/modules/treegrid",["highcharts"],function(B){h(B);h.Highcharts=B;return h}):h("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(h){function B(h,u,z,r){h.hasOwnProperty(u)||(h[u]=r.apply(null,z))}h=h?h._modules:{};B(h,"Core/Axis/BrokenAxis.js",[h["Extensions/Stacking.js"],h["Core/Utilities.js"]],function(h,u){var z=u.addEvent,r=u.find,
v=u.fireEvent,n=u.isArray,k=u.isNumber,x=u.pick,C;(function(a){function g(){"undefined"!==typeof this.brokenAxis&&this.brokenAxis.setBreaks(this.options.breaks,!1)}function q(){this.brokenAxis&&this.brokenAxis.hasBreaks&&(this.options.ordinal=!1)}function u(){var a=this.brokenAxis;if(a&&a.hasBreaks){for(var b=this.tickPositions,e=this.tickPositions.info,G=[],l=0;l<b.length;l++)a.isInAnyBreak(b[l])||G.push(b[l]);this.tickPositions=G;this.tickPositions.info=e}}function C(){this.brokenAxis||(this.brokenAxis=
new y(this))}function f(){var a=this.options.connectNulls,b=this.points,e=this.xAxis,G=this.yAxis;if(this.isDirty)for(var l=b.length;l--;){var H=b[l],c=!(null===H.y&&!1===a)&&(e&&e.brokenAxis&&e.brokenAxis.isInAnyBreak(H.x,!0)||G&&G.brokenAxis&&G.brokenAxis.isInAnyBreak(H.y,!0));H.visible=c?!1:!1!==H.options.visible}}function d(){this.drawBreaks(this.xAxis,["x"]);this.drawBreaks(this.yAxis,x(this.pointArrayMap,["y"]))}function e(a,b){var e=this,I=e.points,l,F,c,m;if(a&&a.brokenAxis&&a.brokenAxis.hasBreaks){var d=
a.brokenAxis;b.forEach(function(b){l=d&&d.breakArray||[];F=a.isXAxis?a.min:x(e.options.threshold,a.min);I.forEach(function(e){m=x(e["stack"+b.toUpperCase()],e[b]);l.forEach(function(b){if(k(F)&&k(m)){c=!1;if(F<b.from&&m>b.to||F>b.from&&m<b.from)c="pointBreak";else if(F<b.from&&m>b.from&&m<b.to||F>b.from&&m>b.to&&m<b.from)c="pointInBreak";c&&v(a,c,{point:e,brk:b})}})})})}}function c(){var b=this.currentDataGrouping,a=b&&b.gapSize;b=this.points.slice();var e=this.yAxis,c=this.options.gapSize,l=b.length-
1,d;if(c&&0<l)for("value"!==this.options.gapUnit&&(c*=this.basePointRange),a&&a>c&&a>=this.basePointRange&&(c=a),d=void 0;l--;)d&&!1!==d.visible||(d=b[l+1]),a=b[l],!1!==d.visible&&!1!==a.visible&&(d.x-a.x>c&&(d=(a.x+d.x)/2,b.splice(l+1,0,{isNull:!0,x:d}),e.stacking&&this.options.stacking&&(d=e.stacking.stacks[this.stackKey][d]=new h(e,e.options.stackLabels,!1,d,this.stack),d.total=0)),d=a);return this.getGraphPath(b)}var b=[];a.compose=function(a,I){-1===b.indexOf(a)&&(b.push(a),a.keepProps.push("brokenAxis"),
z(a,"init",C),z(a,"afterInit",g),z(a,"afterSetTickPositions",u),z(a,"afterSetOptions",q));if(-1===b.indexOf(I)){b.push(I);var F=I.prototype;F.drawBreaks=e;F.gappedPath=c;z(I,"afterGeneratePoints",f);z(I,"afterRender",d)}return a};var y=function(){function a(a){this.hasBreaks=!1;this.axis=a}a.isInBreak=function(a,b){var e=a.repeat||Infinity,l=a.from,d=a.to-a.from;b=b>=l?(b-l)%e:e-(l-b)%e;return a.inclusive?b<=d:b<d&&0!==b};a.lin2Val=function(b){var e=this.brokenAxis;e=e&&e.breakArray;if(!e||!k(b))return b;
var d;for(d=0;d<e.length;d++){var l=e[d];if(l.from>=b)break;else l.to<b?b+=l.len:a.isInBreak(l,b)&&(b+=l.len)}return b};a.val2Lin=function(b){var e=this.brokenAxis;e=e&&e.breakArray;if(!e||!k(b))return b;var d=b,l;for(l=0;l<e.length;l++){var c=e[l];if(c.to<=b)d-=c.len;else if(c.from>=b)break;else if(a.isInBreak(c,b)){d-=b-c.from;break}}return d};a.prototype.findBreakAt=function(a,b){return r(b,function(b){return b.from<a&&a<b.to})};a.prototype.isInAnyBreak=function(b,e){var d=this.axis,l=d.options.breaks||
[],c=l.length,J;if(c&&k(b)){for(;c--;)if(a.isInBreak(l[c],b)){var m=!0;J||(J=x(l[c].showPoints,!d.isXAxis))}var w=m&&e?m&&!J:m}return w};a.prototype.setBreaks=function(b,e){var d=this,c=d.axis,g=n(b)&&!!b.length;c.isDirty=d.hasBreaks!==g;d.hasBreaks=g;c.options.breaks=c.userOptions.breaks=b;c.forceRedraw=!0;c.series.forEach(function(b){b.isDirty=!0});g||c.val2lin!==a.val2Lin||(delete c.val2lin,delete c.lin2val);g&&(c.userOptions.ordinal=!1,c.lin2val=a.lin2Val,c.val2lin=a.val2Lin,c.setExtremes=function(b,
a,e,E,g){if(d.hasBreaks){for(var m=this.options.breaks||[],w;w=d.findBreakAt(b,m);)b=w.to;for(;w=d.findBreakAt(a,m);)a=w.from;a<b&&(a=b)}c.constructor.prototype.setExtremes.call(this,b,a,e,E,g)},c.setAxisTranslation=function(){c.constructor.prototype.setAxisTranslation.call(this);d.unitLength=void 0;if(d.hasBreaks){var b=c.options.breaks||[],e=[],w=[],g=x(c.pointRangePadding,0),l=0,A,f=c.userMin||c.min,y=c.userMax||c.max,q;b.forEach(function(b){A=b.repeat||Infinity;k(f)&&k(y)&&(a.isInBreak(b,f)&&
(f+=b.to%A-f%A),a.isInBreak(b,y)&&(y-=y%A-b.from%A))});b.forEach(function(b){p=b.from;A=b.repeat||Infinity;if(k(f)&&k(y)){for(;p-A>f;)p-=A;for(;p<f;)p+=A;for(q=p;q<y;q+=A)e.push({value:q,move:"in"}),e.push({value:q+b.to-b.from,move:"out",size:b.breakSize})}});e.sort(function(b,p){return b.value===p.value?("in"===b.move?0:1)-("in"===p.move?0:1):b.value-p.value});var t=0;var p=f;e.forEach(function(b){t+="in"===b.move?1:-1;1===t&&"in"===b.move&&(p=b.value);0===t&&k(p)&&(w.push({from:p,to:b.value,len:b.value-
p-(b.size||0)}),l+=b.value-p-(b.size||0))});d.breakArray=w;k(f)&&k(y)&&k(c.min)&&(d.unitLength=y-f-l+g,v(c,"afterBreaks"),c.staticScale?c.transA=c.staticScale:d.unitLength&&(c.transA*=(y-c.min+g)/d.unitLength),g&&(c.minPixelPadding=c.transA*(c.minPointOffset||0)),c.min=f,c.max=y)}});x(e,!0)&&c.chart.redraw()};return a}();a.Additions=y})(C||(C={}));return C});B(h,"Core/Axis/GridAxis.js",[h["Core/Axis/Axis.js"],h["Core/Axis/AxisDefaults.js"],h["Core/Globals.js"],h["Core/Utilities.js"]],function(h,u,
z,r){var v=z.dateFormats,n=r.addEvent,k=r.defined,x=r.erase,C=r.find,a=r.isArray,g=r.isNumber,q=r.merge,D=r.pick,K=r.timeUnits,f=r.wrap,d;(function(e){function c(b,p){var a={width:0,height:0};p.forEach(function(p){p=b[p];if(r.isObject(p,!0)){var t=r.isObject(p.label,!0)?p.label:{};p=t.getBBox?t.getBBox().height:0;t.textStr&&!g(t.textPxLength)&&(t.textPxLength=t.getBBox().width);var c=g(t.textPxLength)?Math.round(t.textPxLength):0;t.textStr&&(c=Math.round(t.getBBox().width));a.height=Math.max(p,a.height);
a.width=Math.max(c,a.width)}});"treegrid"===this.options.type&&this.treeGrid&&this.treeGrid.mapOfPosToGridNode&&(a.width+=this.options.labels.indentation*((this.treeGrid.mapOfPosToGridNode[-1].height||0)-1));return a}function b(){var b=this.grid;(b&&b.columns||[]).forEach(function(b){b.getOffset()})}function d(b){if(!0===(this.options.grid||{}).enabled){var p=this.axisTitle,a=this.height,t=this.horiz,c=this.left,d=this.offset,m=this.opposite,g=this.options,f=this.top,w=this.width,l=this.tickSize(),
y=p&&p.getBBox().width,E=g.title.x,k=g.title.y,A=D(g.title.margin,t?5:10);p=this.chart.renderer.fontMetrics(g.title.style.fontSize,p).f;l=(t?f+a:c)+(t?1:-1)*(m?-1:1)*(l?l[0]/2:0)+(this.side===e.Side.bottom?p:0);b.titlePosition.x=t?c-(y||0)/2-A+E:l+(m?w:0)+d+E;b.titlePosition.y=t?l-(m?a:0)+(m?p:-p)/2+d+k:f-A+k}}function F(){var b=this.chart,p=this.options.grid;p=void 0===p?{}:p;var a=this.userOptions;if(p.enabled){var c=this.options;c.labels.align=D(c.labels.align,"center");this.categories||(c.showLastLabel=
!1);this.labelRotation=0;c.labels.rotation=0}if(p.columns){c=this.grid.columns=[];for(var e=this.grid.columnIndex=0;++e<p.columns.length;){var d=q(a,p.columns[p.columns.length-e-1],{linkedTo:0,type:"category",scrollbar:{enabled:!1}});delete d.grid.columns;d=new h(this.chart,d);d.grid.isColumn=!0;d.grid.columnIndex=e;x(b.axes,d);x(b[this.coll],d);c.push(d)}}}function I(){var b=this.grid,a=this.options;if(!0===(a.grid||{}).enabled){var c=this.min||0,d=this.max||0;this.maxLabelDimensions=this.getMaxLabelDimensions(this.ticks,
this.tickPositions);this.rightWall&&this.rightWall.destroy();if(this.grid&&this.grid.isOuterAxis()&&this.axisLine){var m=a.lineWidth;if(m){m=this.getLinePath(m);var g=m[0],f=m[1],l=((this.tickSize("tick")||[1])[0]-1)*(this.side===e.Side.top||this.side===e.Side.left?-1:1);"M"===g[0]&&"L"===f[0]&&(this.horiz?(g[2]+=l,f[2]+=l):(g[1]+=l,f[1]+=l));!this.horiz&&this.chart.marginRight&&(g=[g,["L",this.left,g[2]||0]],l=["L",this.chart.chartWidth-this.chart.marginRight,this.toPixels(d+this.tickmarkOffset)],
f=[["M",f[1]||0,this.toPixels(d+this.tickmarkOffset)],l],this.grid.upperBorder||0===c%1||(this.grid.upperBorder=this.grid.renderBorder(g)),this.grid.upperBorder&&(this.grid.upperBorder.attr({stroke:a.lineColor,"stroke-width":a.lineWidth}),this.grid.upperBorder.animate({d:g})),this.grid.lowerBorder||0===d%1||(this.grid.lowerBorder=this.grid.renderBorder(f)),this.grid.lowerBorder&&(this.grid.lowerBorder.attr({stroke:a.lineColor,"stroke-width":a.lineWidth}),this.grid.lowerBorder.animate({d:f})));this.grid.axisLineExtra?
(this.grid.axisLineExtra.attr({stroke:a.lineColor,"stroke-width":a.lineWidth}),this.grid.axisLineExtra.animate({d:m})):this.grid.axisLineExtra=this.grid.renderBorder(m);this.axisLine[this.showAxis?"show":"hide"](!0)}}(b&&b.columns||[]).forEach(function(b){b.render()});if(!this.horiz&&this.chart.hasRendered&&(this.scrollbar||this.linkedParent&&this.linkedParent.scrollbar)){b=this.tickmarkOffset;a=this.tickPositions[this.tickPositions.length-1];m=this.tickPositions[0];for(f=void 0;(f=this.hiddenLabels.pop())&&
f.element;)f.show();(f=this.ticks[m].label)&&(c-m>b?this.hiddenLabels.push(f.hide()):f.show());(f=this.ticks[a].label)&&(a-d>b?this.hiddenLabels.push(f.hide()):f.show());(c=this.ticks[a].mark)&&(a-d<b&&0<a-d&&this.ticks[a].isLast?c.hide():this.ticks[a-1]&&c.show())}}}function v(){var b=this.tickPositions&&this.tickPositions.info,a=this.options,c=this.userOptions.labels||{};(a.grid||{}).enabled&&(this.horiz?(this.series.forEach(function(b){b.options.pointRange=0}),b&&a.dateTimeLabelFormats&&a.labels&&
!k(c.align)&&(!1===a.dateTimeLabelFormats[b.unitName].range||1<b.count)&&(a.labels.align="left",k(c.x)||(a.labels.x=3))):"treegrid"!==this.options.type&&this.grid&&this.grid.columns&&(this.minPointOffset=this.tickInterval))}function G(b){var a=this.options;b=b.userOptions;var c=a&&r.isObject(a.grid,!0)?a.grid:{};if(!0===c.enabled){var d=q(!0,{className:"highcharts-grid-axis "+(b.className||""),dateTimeLabelFormats:{hour:{list:["%H:%M","%H"]},day:{list:["%A, %e. %B","%a, %e. %b","%E"]},week:{list:["Week %W",
"W%W"]},month:{list:["%B","%b","%o"]}},grid:{borderWidth:1},labels:{padding:2,style:{fontSize:"13px"}},margin:0,title:{text:null,reserveSpace:!1,rotation:0},units:[["millisecond",[1,10,100]],["second",[1,10]],["minute",[1,5,15]],["hour",[1,6]],["day",[1]],["week",[1]],["month",[1]],["year",null]]},b);"xAxis"===this.coll&&(k(b.linkedTo)&&!k(b.tickPixelInterval)&&(d.tickPixelInterval=350),k(b.tickPixelInterval)||!k(b.linkedTo)||k(b.tickPositioner)||k(b.tickInterval)||(d.tickPositioner=function(b,a){var c=
this.linkedParent&&this.linkedParent.tickPositions&&this.linkedParent.tickPositions.info;if(c){for(var t=d.units||[],p=void 0,e=void 0,m=void 0,f=0;f<t.length;f++)if(t[f][0]===c.unitName){p=f;break}t[p+1]?(m=t[p+1][0],e=(t[p+1][1]||[1])[0]):"year"===c.unitName&&(m="year",e=10*c.count);c=K[m];this.tickInterval=c*e;return this.getTimeTicks({unitRange:c,count:e,unitName:m},b,a,this.options.startOfWeek)}}));q(!0,this.options,d);this.horiz&&(a.minPadding=D(b.minPadding,0),a.maxPadding=D(b.maxPadding,0));
g(a.grid.borderWidth)&&(a.tickWidth=a.lineWidth=c.borderWidth)}}function l(b){b=(b=b.userOptions)&&b.grid||{};var a=b.columns;b.enabled&&a&&q(!0,this.options,a[a.length-1])}function H(){(this.grid.columns||[]).forEach(function(b){b.setScale()})}function J(b){var c=u.defaultLeftAxisOptions,d=this.horiz,e=this.maxLabelDimensions,t=this.options.grid;t=void 0===t?{}:t;t.enabled&&e&&(c=2*Math.abs(c.labels.x),d=d?t.cellHeight||c+e.height:c+e.width,a(b.tickSize)?b.tickSize[0]=d:b.tickSize=[d,0])}function m(){this.axes.forEach(function(b){(b.grid&&
b.grid.columns||[]).forEach(function(b){b.setAxisSize();b.setAxisTranslation()})})}function w(b){var a=this.grid;(a.columns||[]).forEach(function(a){a.destroy(b.keepEvents)});a.columns=void 0}function E(b){b=b.userOptions||{};var a=b.grid||{};a.enabled&&k(a.borderColor)&&(b.tickColor=b.lineColor=a.borderColor);this.grid||(this.grid=new L(this));this.hiddenLabels=[]}function M(b){var a=this.label,c=this.axis,d=c.reversed,m=c.chart,t=c.options.grid||{},f=c.options.labels,l=f.align,w=e.Side[c.side],
y=b.tickmarkOffset,E=c.tickPositions,k=this.pos-y;E=g(E[b.index+1])?E[b.index+1]-y:(c.max||0)+y;var A=c.tickSize("tick");y=A?A[0]:0;A=A?A[1]/2:0;if(!0===t.enabled){if("top"===w){t=c.top+c.offset;var q=t-y}else"bottom"===w?(q=m.chartHeight-c.bottom+c.offset,t=q+y):(t=c.top+c.len-(c.translate(d?E:k)||0),q=c.top+c.len-(c.translate(d?k:E)||0));"right"===w?(w=m.chartWidth-c.right+c.offset,d=w+y):"left"===w?(d=c.left+c.offset,w=d-y):(w=Math.round(c.left+(c.translate(d?E:k)||0))-A,d=Math.min(Math.round(c.left+
(c.translate(d?k:E)||0))-A,c.left+c.len));this.slotWidth=d-w;b.pos.x="left"===l?w:"right"===l?d:w+(d-w)/2;b.pos.y=q+(t-q)/2;m=m.renderer.fontMetrics(f.style.fontSize,a&&a.element);a=a?a.getBBox().height:0;f.useHTML?b.pos.y+=m.b+-(a/2):(a=Math.round(a/m.h),b.pos.y+=(m.b-(m.h-m.f))/2+-((a-1)*m.h/2));b.pos.x+=c.horiz&&f.x||0}}function A(b){var a=b.axis,c=b.value;if(a.options.grid&&a.options.grid.enabled){var d=a.tickPositions,e=(a.linkedParent||a).series[0],m=c===d[0];d=c===d[d.length-1];var t=e&&C(e.options.data,
function(b){return b[a.isXAxis?"x":"y"]===c}),f=void 0;t&&e.is("gantt")&&(f=q(t),z.seriesTypes.gantt.prototype.pointClass.setGanttPointAliases(f));b.isFirst=m;b.isLast=d;b.point=f}}function N(){var b=this.options,a=this.categories,c=this.tickPositions,d=c[0],e=c[c.length-1],m=this.linkedParent&&this.linkedParent.min||this.min,f=this.linkedParent&&this.linkedParent.max||this.max,g=this.tickInterval;!0!==(b.grid||{}).enabled||a||!this.horiz&&!this.isLinked||(d<m&&d+g>m&&!b.startOnTick&&(c[0]=m),e>f&&
e-g<f&&!b.endOnTick&&(c[c.length-1]=f))}function O(b){var a=this.options.grid;return!0===(void 0===a?{}:a).enabled&&this.categories?this.tickInterval:b.apply(this,Array.prototype.slice.call(arguments,1))}(function(b){b[b.top=0]="top";b[b.right=1]="right";b[b.bottom=2]="bottom";b[b.left=3]="left"})(e.Side||(e.Side={}));e.compose=function(a,e,g){-1===a.keepProps.indexOf("grid")&&(a.keepProps.push("grid"),a.prototype.getMaxLabelDimensions=c,f(a.prototype,"unsquish",O),n(a,"init",E),n(a,"afterGetOffset",
b),n(a,"afterGetTitlePosition",d),n(a,"afterInit",F),n(a,"afterRender",I),n(a,"afterSetAxisTranslation",v),n(a,"afterSetOptions",G),n(a,"afterSetOptions",l),n(a,"afterSetScale",H),n(a,"afterTickSize",J),n(a,"trimTicks",N),n(a,"destroy",w));n(e,"afterSetChartSize",m);n(g,"afterGetLabelPosition",M);n(g,"labelFormat",A);return a};var L=function(){function b(b){this.axis=b}b.prototype.isOuterAxis=function(){var b=this.axis,a=b.grid.columnIndex,c=b.linkedParent&&b.linkedParent.grid.columns||b.grid.columns,
d=a?b.linkedParent:b,e=-1,m=0;b.chart[b.coll].forEach(function(a,c){a.side!==b.side||a.options.isInternal||(m=c,a===d&&(e=c))});return m===e&&(g(a)?c.length===a:!0)};b.prototype.renderBorder=function(b){var a=this.axis,c=a.chart.renderer,d=a.options;b=c.path(b).addClass("highcharts-axis-line").add(a.axisBorder);c.styledMode||b.attr({stroke:d.lineColor,"stroke-width":d.lineWidth,zIndex:7});return b};return b}();e.Additions=L})(d||(d={}));v.E=function(a){return this.dateFormat("%a",a,!0).charAt(0)};
v.W=function(a){a=new this.Date(a);var c=(this.get("Day",a)+6)%7,b=new this.Date(a.valueOf());this.set("Date",b,this.get("Date",a)-c+3);c=new this.Date(this.get("FullYear",b),0,1);4!==this.get("Day",c)&&(this.set("Month",a,0),this.set("Date",a,1+(11-this.get("Day",c))%7));return(1+Math.floor((b.valueOf()-c.valueOf())/6048E5)).toString()};"";return d});B(h,"Gantt/Tree.js",[h["Core/Utilities.js"]],function(h){var u=h.extend,z=h.isNumber,r=h.pick,v=function(k,h){var n=k.reduce(function(a,g){var k=r(g.parent,
"");"undefined"===typeof a[k]&&(a[k]=[]);a[k].push(g);return a},{});Object.keys(n).forEach(function(a,g){var k=n[a];""!==a&&-1===h.indexOf(a)&&(k.forEach(function(a){g[""].push(a)}),delete g[a])});return n},n=function(k,h,v,a,g,q){var D=0,x=0,f=q&&q.after,d=q&&q.before;h={data:a,depth:v-1,id:k,level:v,parent:h};var e,c;"function"===typeof d&&d(h,q);d=(g[k]||[]).map(function(b){var a=n(b.id,k,v+1,b,g,q),d=b.start;b=!0===b.milestone?d:b.end;e=!z(e)||d<e?d:e;c=!z(c)||b>c?b:c;D=D+1+a.descendants;x=Math.max(a.height+
1,x);return a});a&&(a.start=r(a.start,e),a.end=r(a.end,c));u(h,{children:d,descendants:D,height:x});"function"===typeof f&&f(h,q);return h};return{getListOfParents:v,getNode:n,getTree:function(k,h){var u=k.map(function(a){return a.id});k=v(k,u);return n("",null,1,null,k,h)}}});B(h,"Core/Axis/TreeGridTick.js",[h["Core/Utilities.js"]],function(h){var u=h.addEvent,z=h.isObject,r=h.isNumber,v=h.pick,n=h.wrap,k;(function(h){function k(){this.treeGrid||(this.treeGrid=new x(this))}function a(a,d){a=a.treeGrid;
var e=!a.labelIcon,c=d.renderer,b=d.xy,f=d.options,g=f.width||0,h=f.height||0,k=b.x-g/2-(f.padding||0);b=b.y-h/2;var q=d.collapsed?90:180,l=d.show&&r(b),n=a.labelIcon;n||(a.labelIcon=n=c.path(c.symbols[f.type](f.x||0,f.y||0,g,h)).addClass("highcharts-label-icon").add(d.group));n.attr({y:l?0:-9999});c.styledMode||n.attr({cursor:"pointer",fill:v(d.color,"#666666"),"stroke-width":1,stroke:f.lineColor,strokeWidth:f.lineWidth||0});n[e?"attr":"animate"]({translateX:k,translateY:b,rotation:q})}function g(a,
d,e,c,b,g,h,k,q){var f=v(this.options&&this.options.labels,g);g=this.pos;var l=this.axis,n="treegrid"===l.options.type;a=a.apply(this,[d,e,c,b,f,h,k,q]);n&&(d=f&&z(f.symbol,!0)?f.symbol:{},f=f&&r(f.indentation)?f.indentation:0,g=(g=(l=l.treeGrid.mapOfPosToGridNode)&&l[g])&&g.depth||1,a.x+=(d.width||0)+2*(d.padding||0)+(g-1)*f);return a}function q(f){var d=this,e=d.pos,c=d.axis,b=d.label,g=c.treeGrid.mapOfPosToGridNode,h=c.options,k=v(d.options&&d.options.labels,h&&h.labels),q=k&&z(k.symbol,!0)?k.symbol:
{},n=(g=g&&g[e])&&g.depth;h="treegrid"===h.type;var l=-1<c.tickPositions.indexOf(e);e=c.chart.styledMode;h&&g&&b&&b.element&&b.addClass("highcharts-treegrid-node-level-"+n);f.apply(d,Array.prototype.slice.call(arguments,1));h&&b&&b.element&&g&&g.descendants&&0<g.descendants&&(c=c.treeGrid.isCollapsed(g),a(d,{color:!e&&b.styles&&b.styles.color||"",collapsed:c,group:b.parentGroup,options:q,renderer:b.renderer,show:l,xy:b.xy}),q="highcharts-treegrid-node-"+(c?"expanded":"collapsed"),b.addClass("highcharts-treegrid-node-"+
(c?"collapsed":"expanded")).removeClass(q),e||b.css({cursor:"pointer"}),[b,d.treeGrid.labelIcon].forEach(function(a){a&&!a.attachedTreeGridEvents&&(u(a.element,"mouseover",function(){b.addClass("highcharts-treegrid-node-active");b.renderer.styledMode||b.css({textDecoration:"underline"})}),u(a.element,"mouseout",function(){var a=z(k.style)?k.style:{};b.removeClass("highcharts-treegrid-node-active");b.renderer.styledMode||b.css({textDecoration:a.textDecoration})}),u(a.element,"click",function(){d.treeGrid.toggleCollapse()}),
a.attachedTreeGridEvents=!0)}))}var D=!1;h.compose=function(a){D||(u(a,"init",k),n(a.prototype,"getLabelPosition",g),n(a.prototype,"renderLabel",q),a.prototype.collapse=function(a){this.treeGrid.collapse(a)},a.prototype.expand=function(a){this.treeGrid.expand(a)},a.prototype.toggleCollapse=function(a){this.treeGrid.toggleCollapse(a)},D=!0)};var x=function(){function a(a){this.tick=a}a.prototype.collapse=function(a){var d=this.tick,c=d.axis,b=c.brokenAxis;b&&c.treeGrid.mapOfPosToGridNode&&(d=c.treeGrid.collapse(c.treeGrid.mapOfPosToGridNode[d.pos]),
b.setBreaks(d,v(a,!0)))};a.prototype.expand=function(a){var d=this.tick,c=d.axis,b=c.brokenAxis;b&&c.treeGrid.mapOfPosToGridNode&&(d=c.treeGrid.expand(c.treeGrid.mapOfPosToGridNode[d.pos]),b.setBreaks(d,v(a,!0)))};a.prototype.toggleCollapse=function(a){var d=this.tick,c=d.axis,b=c.brokenAxis;b&&c.treeGrid.mapOfPosToGridNode&&(d=c.treeGrid.toggleCollapse(c.treeGrid.mapOfPosToGridNode[d.pos]),b.setBreaks(d,v(a,!0)))};return a}();h.Additions=x})(k||(k={}));return k});B(h,"Series/TreeUtilities.js",[h["Core/Color/Color.js"],
h["Core/Utilities.js"]],function(h,u){function v(a,g){var h=g.before,k=g.idRoot,n=g.mapIdToNode[k],f=g.points[a.i],d=f&&f.options||{},e=[],c=0;a.levelDynamic=a.level-(!1!==g.levelIsConstant?0:n.level);a.name=C(f&&f.name,"");a.visible=k===a.id||!0===g.visible;"function"===typeof h&&(a=h(a,g));a.children.forEach(function(b,d){var f=r({},g);r(f,{index:d,siblings:a.children.length,visible:a.visible});b=v(b,f);e.push(b);b.visible&&(c+=b.val)});h=C(d.value,c);a.visible=0<=h&&(0<c||a.visible);a.children=
e;a.childrenTotal=c;a.isLeaf=a.visible&&!c;a.val=h;return a}var r=u.extend,B=u.isArray,n=u.isNumber,k=u.isObject,x=u.merge,C=u.pick;return{getColor:function(a,g){var k=g.index,n=g.mapOptionsToLevel,u=g.parentColor,f=g.parentColorIndex,d=g.series,e=g.colors,c=g.siblings,b=d.points,v=d.chart.options.chart,r;if(a){b=b[a.i];a=n[a.level]||{};if(n=b&&a.colorByPoint){var x=b.index%(e?e.length:v.colorCount);var z=e&&e[x]}if(!d.chart.styledMode){e=b&&b.options.color;v=a&&a.color;if(r=u)r=(r=a&&a.colorVariation)&&
"brightness"===r.key&&k&&c?h.parse(u).brighten(k/c*r.to).get():u;r=C(e,v,z,r,d.color)}var B=C(b&&b.options.colorIndex,a&&a.colorIndex,x,f,g.colorIndex)}return{color:r,colorIndex:B}},getLevelOptions:function(a){var g=null;if(k(a)){g={};var h=n(a.from)?a.from:1;var r=a.levels;var u={};var f=k(a.defaults)?a.defaults:{};B(r)&&(u=r.reduce(function(a,e){if(k(e)&&n(e.level)){var c=x({},e);var b=C(c.levelIsConstant,f.levelIsConstant);delete c.levelIsConstant;delete c.level;e=e.level+(b?0:h-1);k(a[e])?x(!0,
a[e],c):a[e]=c}return a},{}));r=n(a.to)?a.to:1;for(a=0;a<=r;a++)g[a]=x({},f,k(u[a])?u[a]:{})}return g},setTreeValues:v,updateRootId:function(a){if(k(a)){var g=k(a.options)?a.options:{};g=C(a.rootNode,g.rootId,"");k(a.userOptions)&&(a.userOptions.rootId=g);a.rootNode=g}return g}}});B(h,"Core/Axis/TreeGridAxis.js",[h["Core/Axis/BrokenAxis.js"],h["Core/Axis/GridAxis.js"],h["Gantt/Tree.js"],h["Core/Axis/TreeGridTick.js"],h["Series/TreeUtilities.js"],h["Core/Utilities.js"]],function(h,u,z,r,B,n){var k=
B.getLevelOptions,v=n.addEvent,C=n.find,a=n.fireEvent,g=n.isArray,q=n.isObject,D=n.isString,K=n.merge,f=n.pick,d=n.wrap,e;(function(c){function b(a,b){var c=a.collapseEnd||0;a=a.collapseStart||0;c>=b&&(a-=.5);return{from:a,to:c,showPoints:!1}}function e(a,b,c){var d=[],e=[],m={},g="boolean"===typeof b?b:!1,f={},h=-1;a=z.getTree(a,{after:function(a){a=f[a.pos];var b=0,c=0;a.children.forEach(function(a){c+=(a.descendants||0)+1;b=Math.max((a.height||0)+1,b)});a.descendants=c;a.height=b;a.collapsed&&
e.push(a)},before:function(a){var b=q(a.data,!0)?a.data:{},c=D(b.name)?b.name:"",e=m[a.parent];e=q(e,!0)?f[e.pos]:null;var k=function(a){return a.name===c},l;g&&q(e,!0)&&(l=C(e.children,k))?(k=l.pos,l.nodes.push(a)):k=h++;f[k]||(f[k]=l={depth:e?e.depth+1:0,name:c,id:b.id,nodes:[a],children:[],pos:k},-1!==k&&d.push(c),q(e,!0)&&e.children.push(l));D(a.id)&&(m[a.id]=a);l&&!0===b.collapsed&&(l.collapsed=!0);a.pos=k}});f=function(a,b){var c=function(a,d,e){var m=d+(-1===d?0:b-1),g=(m-d)/2,f=d+g;a.nodes.forEach(function(a){var b=
a.data;q(b,!0)&&(b.y=d+(b.seriesIndex||0),delete b.seriesIndex);a.pos=f});e[f]=a;a.pos=f;a.tickmarkOffset=g+.5;a.collapseStart=m+.5;a.children.forEach(function(a){c(a,m+1,e);m=(a.collapseEnd||0)-.5});a.collapseEnd=m+.5;return e};return c(a["-1"],-1,{})}(f,c);return{categories:d,mapOfIdToNode:m,mapOfPosToGridNode:f,collapsedNodes:e,tree:a}}function n(a){a.target.axes.filter(function(a){return"treegrid"===a.options.type}).forEach(function(b){var c=b.options||{},d=c.labels,m=c.uniqueNames;c=c.max;var f=
0;if(!b.treeGrid.mapOfPosToGridNode||b.series.some(function(a){return!a.hasRendered||a.isDirtyData||a.isDirty})){var h=b.series.reduce(function(a,b){b.visible&&((b.options.data||[]).forEach(function(c){b.options.keys&&b.options.keys.length&&(c=b.pointClass.prototype.optionsToObject.call({series:b},c),b.pointClass.setGanttPointAliases(c));q(c,!0)&&(c.seriesIndex=f,a.push(c))}),!0===m&&f++);return a},[]);if(c&&h.length<c)for(var l=h.length;l<=c;l++)h.push({name:l+"\u200b"});c=e(h,m||!1,!0===m?f:1);
b.categories=c.categories;b.treeGrid.mapOfPosToGridNode=c.mapOfPosToGridNode;b.hasNames=!0;b.treeGrid.tree=c.tree;b.series.forEach(function(a){var b=(a.options.data||[]).map(function(b){g(b)&&a.options.keys&&a.options.keys.length&&h.forEach(function(a){0<=b.indexOf(a.x)&&0<=b.indexOf(a.x2)&&(b=a)});return q(b,!0)?K(b):b});a.visible&&a.setData(b,!1)});b.treeGrid.mapOptionsToLevel=k({defaults:d,from:1,levels:d&&d.levels,to:b.treeGrid.tree&&b.treeGrid.tree.height});"beforeRender"===a.type&&(b.treeGrid.collapsedNodes=
c.collapsedNodes)}})}function x(a,b){var c=this.treeGrid.mapOptionsToLevel||{},d=this.ticks,e=d[b],m;if("treegrid"===this.options.type&&this.treeGrid.mapOfPosToGridNode){var f=this.treeGrid.mapOfPosToGridNode[b];(c=c[f.depth])&&(m={labels:c});!e&&l?d[b]=new l(this,b,void 0,void 0,{category:f.name,tickmarkOffset:f.tickmarkOffset,options:m}):(e.parameters.category=f.name,e.options=m,e.addLabel())}else a.apply(this,Array.prototype.slice.call(arguments,1))}function B(a,b,c){var d=this,f="treegrid"===
c.type;d.treeGrid||(d.treeGrid=new H(d));f&&(v(b,"beforeRender",n),v(b,"beforeRedraw",n),v(b,"addSeries",function(a){a.options.data&&(a=e(a.options.data,c.uniqueNames||!1,1),d.treeGrid.collapsedNodes=(d.treeGrid.collapsedNodes||[]).concat(a.collapsedNodes))}),v(d,"foundExtremes",function(){d.treeGrid.collapsedNodes&&d.treeGrid.collapsedNodes.forEach(function(a){var b=d.treeGrid.collapse(a);d.brokenAxis&&(d.brokenAxis.setBreaks(b,!1),d.treeGrid.collapsedNodes&&(d.treeGrid.collapsedNodes=d.treeGrid.collapsedNodes.filter(function(b){return a.collapseStart!==
b.collapseStart||a.collapseEnd!==b.collapseEnd})))})}),v(d,"afterBreaks",function(){"yAxis"===d.coll&&!d.staticScale&&d.chart.options.chart.height&&(d.isDirty=!0)}),c=K({grid:{enabled:!0},labels:{align:"left",levels:[{level:void 0},{level:1,style:{fontWeight:"bold"}}],symbol:{type:"triangle",x:-5,y:-5,height:10,width:10,padding:5}},uniqueNames:!1},c,{reversed:!0,grid:{columns:void 0}}));a.apply(d,[b,c]);f&&(d.hasNames=!0,d.options.showLastLabel=!0)}function G(b){var c=this.options;"treegrid"===c.type?
(this.min=f(this.userMin,c.min,this.dataMin),this.max=f(this.userMax,c.max,this.dataMax),a(this,"foundExtremes"),this.setAxisTranslation(),this.tickmarkOffset=.5,this.tickInterval=1,this.tickPositions=this.treeGrid.mapOfPosToGridNode?this.treeGrid.getTickPositions():[]):b.apply(this,Array.prototype.slice.call(arguments,1))}var l;c.compose=function(a,b,c,e){-1===a.keepProps.indexOf("treeGrid")&&(a.keepProps.push("treeGrid"),l=e,d(a.prototype,"generateTick",x),d(a.prototype,"init",B),d(a.prototype,
"setTickInterval",G),a.prototype.utils={getNode:z.getNode},u.compose(a,b,e),h.compose(a,c),r.compose(e));return a};var H=function(){function a(a){this.axis=a}a.prototype.setCollapsedStatus=function(a){var b=this.axis,c=b.chart;b.series.forEach(function(b){var d=b.options.data;if(a.id&&d){var e=c.get(a.id);b=d[b.data.indexOf(e)];e&&b&&(e.collapsed=a.collapsed,b.collapsed=a.collapsed)}})};a.prototype.collapse=function(a){var c=this.axis,d=c.options.breaks||[],e=b(a,c.max);d.push(e);a.collapsed=!0;c.treeGrid.setCollapsedStatus(a);
return d};a.prototype.expand=function(a){var c=this.axis,d=c.options.breaks||[],e=b(a,c.max);a.collapsed=!1;c.treeGrid.setCollapsedStatus(a);return d.reduce(function(a,b){b.to===e.to&&b.from===e.from||a.push(b);return a},[])};a.prototype.getTickPositions=function(){var a=this.axis,b=Math.floor(a.min/a.tickInterval)*a.tickInterval,c=Math.ceil(a.max/a.tickInterval)*a.tickInterval;return Object.keys(a.treeGrid.mapOfPosToGridNode||{}).reduce(function(d,e){e=+e;!(e>=b&&e<=c)||a.brokenAxis&&a.brokenAxis.isInAnyBreak(e)||
d.push(e);return d},[])};a.prototype.isCollapsed=function(a){var c=this.axis,d=c.options.breaks||[],e=b(a,c.max);return d.some(function(a){return a.from===e.from&&a.to===e.to})};a.prototype.toggleCollapse=function(a){return this.isCollapsed(a)?this.expand(a):this.collapse(a)};return a}();c.Additions=H})(e||(e={}));return e});B(h,"masters/modules/treegrid.src.js",[h["Core/Globals.js"],h["Core/Axis/TreeGridAxis.js"]],function(h,u){u.compose(h.Axis,h.Chart,h.Series,h.Tick)})});
//# sourceMappingURL=treegrid.js.map |
'use strict';
// Configuring the Customers module
angular.module('customers').run(['Menus',
function (Menus) {
Menus.addMenuItem('topbar', {
title: 'Manage Customers',
state: 'customers',
icon: 'fa-users',
type: 'dropdown'
});
// Add the dropdown list item
Menus.addSubMenuItem('topbar', 'customers', {
title: 'List Customers',
state: 'customers.list'
});
// Add the dropdown create item
Menus.addSubMenuItem('topbar', 'customers', {
title: 'Create A Customer',
state: 'customers.create'
});
}
]);
|
'use strict'
const thunk = require('thunks')()
const tool = require('./tool')
const sendCommand = require('./connection').sendCommand
// (Disque 0.0.1) `disque command`
// `node check-commands.js`
const commandsInfo = {
ackjob: [-1, ['write', 'fast'], 0, 0, 0],
addjob: [-4, ['write', 'denyoom', 'fast'], 0, 0, 0],
auth: [2, ['readonly', 'loading', 'fast'], 0, 0, 0],
bgrewriteaof: [1, ['readonly', 'admin'], 0, 0, 0],
client: [-2, ['readonly', 'admin'], 0, 0, 0],
cluster: [-2, ['readonly', 'admin'], 0, 0, 0],
command: [0, ['readonly', 'loading'], 0, 0, 0],
config: [-2, ['readonly', 'admin'], 0, 0, 0],
debug: [-2, ['admin'], 0, 0, 0],
deljob: [-1, ['write', 'fast'], 0, 0, 0],
dequeue: [-1, ['write', 'fast'], 0, 0, 0],
enqueue: [-1, ['write', 'denyoom', 'fast'], 0, 0, 0],
fastack: [-1, ['write', 'fast'], 0, 0, 0],
getjob: [-2, ['write', 'fast'], 0, 0, 0],
hello: [1, ['readonly', 'fast'], 0, 0, 0],
info: [-1, ['readonly', 'loading'], 0, 0, 0],
jscan: [-1, ['readonly'], 0, 0, 0],
latency: [-2, ['readonly', 'admin', 'loading'], 0, 0, 0],
loadjob: [2, ['write'], 0, 0, 0],
monitor: [1, ['readonly', 'admin'], 0, 0, 0],
nack: [-1, ['write', 'denyoom', 'fast'], 0, 0, 0],
pause: [-3, ['readonly', 'fast'], 0, 0, 0],
ping: [-1, ['readonly', 'fast'], 0, 0, 0],
qlen: [2, ['readonly', 'fast'], 0, 0, 0],
qpeek: [3, ['readonly'], 0, 0, 0],
qscan: [-1, ['readonly'], 0, 0, 0],
qstat: [2, ['readonly', 'fast'], 0, 0, 0],
show: [2, ['readonly', 'fast'], 0, 0, 0],
shutdown: [-1, ['readonly', 'admin', 'loading'], 0, 0, 0],
slowlog: [-2, ['readonly'], 0, 0, 0],
time: [1, ['readonly', 'fast'], 0, 0, 0],
working: [2, ['write', 'fast'], 0, 0, 0]
}
// fake QUIT command info~
commandsInfo.quit = [1, ['readonly', 'noscript'], 0, 0, 0]
const commands = Object.keys(commandsInfo)
exports.initCommands = function (proto) {
proto.clientCommands = commands
commands.map(function (command) {
proto[command] = function () {
return sendCommand(this, command, adjustArgs(arguments))
}
})
/* overrides */
// Parse the reply from INFO into a hash.
proto.info = function () {
return sendCommand(this, 'info', adjustArgs(arguments), formatInfo)
}
proto.show = function () {
return sendCommand(this, 'show', adjustArgs(arguments), toHash)
}
proto.qstat = function () {
return sendCommand(this, 'qstat', adjustArgs(arguments), toHash)
}
proto.monitor = function () {
// monit all nodes in cluster mode
let tasks = []
tool.each(this._disqueState.pool, (connection) => {
if (!connection.monitorMode) tasks.push(connection.sendCommand('monitor', []))
connection.monitorMode = true
})
return thunk.all.call(this, tasks)
}
commands.map((command) => {
proto[command.toUpperCase()] = proto[command]
})
}
function adjustArgs (args) {
return Array.isArray(args[0]) ? args[0] : args
}
function toHash (array) {
// disque returned (nil)
if (!array) return null
let hash = {}
for (let i = 0, len = array.length; i < len; i += 2) {
hash[array[i]] = array[i + 1]
}
return hash
}
function formatInfo (info) {
let hash = {}
info.toString().split('\r\n').map((line) => {
let index = line.indexOf(':')
if (index === -1) return
let name = line.slice(0, index)
hash[name] = line.slice(index + 1)
})
return hash
}
|
// # **TickModel**
// A Backbone.Model that represents the data required to build a CMapTickView. The model contains
// a data object that has keys for each row to display in the view and array values for each tick
// to display in each row. An example data object might look like this:
// {PC3: [.23,-.28], MCF7: [-0.6]}
// example usage
// tick_model = new TickModel();
Barista.Models.TickModel = Backbone.Model.extend({
// ### defaults
// set up defaults for model values
// 1. {String} **title** the title to use in the plot, defaults to *""*
// 2. {Object} **data_object** the data object to use when plotting. defualts to *{}*
defaults: {
title: "",
data_object: {}
}
}); |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Navigation.css';
import Link from '../Link';
import {UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem} from 'reactstrap';
class Navigation extends React.Component {
logout() {
fetch('/logout', {
credentials: 'include',
}).then(function (response) {
document.cookie = 'connect.sid' + '=; Max-Age=0';
window.location.href = '/'
}).catch(alert);
}
render() {
const {profile} = this.props;
return (
<div className={s.root} role="navigation">
{profile
? <span><Link className={s.link} to="/profile">
{profile}
</Link>
<span className={s.spacer}>или</span>
<span className={s.link} onClick={() => this.logout()}>Выйти</span>
</span>
: <span>
<Link className={`${s.link} ${s.forCompany}`} to="/register/company">
ДЛЯ КОМПАНИЙ
</Link>
{' '}<span className={s.spacer}> | </span>
<Link className={s.link} to="/login">
ВОЙТИ
</Link>
{/*{' '}<span className={s.spacer}> | </span>*/}
{/*<UncontrolledDropdown className={s.dropdown}>*/}
{/*<DropdownToggle>*/}
{/*<i className="fa fa-bars" aria-hidden="true"></i>*/}
{/*</DropdownToggle>*/}
{/*<DropdownMenu>*/}
{/*<DropdownItem header>Header</DropdownItem>*/}
{/*<DropdownItem disabled>Action</DropdownItem>*/}
{/*<DropdownItem>Another Action</DropdownItem>*/}
{/*<DropdownItem divider/>*/}
{/*<DropdownItem>Another Action</DropdownItem>*/}
{/*</DropdownMenu>*/}
{/*</UncontrolledDropdown>*/}
</span>}
</div>
);
}
}
export default withStyles(s)(Navigation);
|
import fs from 'fs-extra';
import path from 'path';
import express from 'express';
import multer from 'multer';
import config from 'config';
import logger from '../lib/logger';
import { basename } from '../public/js/core/utils';
const publicDirectory = path.resolve(__dirname, '..', 'public');
const uploadDirectory = path.resolve(__dirname, '..', 'upload');
let options = {
CONST: undefined,
database: undefined
};
function setOptions(hash) {
options = hash;
}
function initDirectories(app) {
if (!fs.existsSync(config.get('dataDirectory'))) {
fs.mkdirpSync(config.get('dataDirectory'));
}
if (!fs.existsSync(uploadDirectory)) {
fs.mkdirpSync(uploadDirectory);
}
app.use(express.static(publicDirectory));
app.use('/files', express.static(config.get('dataDirectory')));
app.use(multer({ dest: uploadDirectory }));
}
function deleteThemeDirectoryFromFragment(fragment) {
const directory = path.resolve(publicDirectory, 'files', 'theme', fragment);
return new Promise((resolve, reject) => {
fs.remove(directory, err => {
if (err) {
logger.error(err);
return reject(err);
}
return resolve();
});
});
}
function duplicateFilesFromFragments(oldFragment, newFragment) {
const oldDirectory = path.resolve(
publicDirectory,
'files',
'theme',
oldFragment
);
const newDirectory = path.resolve(
publicDirectory,
'files',
'theme',
newFragment
);
return new Promise((resolve, reject) => {
fs.copy(oldDirectory, newDirectory, err => {
if (err) {
logger.error(err);
return reject(err);
}
return resolve();
});
});
}
function cleanObsoleteLayerFilesInThatDirectory(themeModel, directoryName) {
const fragment = themeModel.get('fragment');
const layers = themeModel.get('layers').models;
const directory = path.resolve(
publicDirectory,
`files/theme/${fragment}/${directoryName}/`
);
try {
fs.statSync(directory);
} catch (e) {
return false;
}
const re = new RegExp(`^/files/theme/${fragment}/${directoryName}/`);
const cacheRe = /^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}.geojson$/;
const modelFiles = [];
for (const layer of layers) {
const fileUri = layer.get('fileUri');
if (fileUri && re.test(fileUri)) {
const fileUriBaseName = basename(fileUri);
modelFiles.push(fileUriBaseName);
if (cacheRe.test(fileUriBaseName)) {
const layerUuid = layer.get('uuid');
modelFiles.push(`${layerUuid}-archived.json`);
modelFiles.push(`${layerUuid}-modified.json`);
modelFiles.push(`${layerUuid}-deleted.json`);
}
}
}
return fs.readdir(directory, (err, directoryFiles) => {
if (err) {
logger.error(err);
return;
}
for (const file of directoryFiles) {
const filePath = path.resolve(directory, file);
if (modelFiles.indexOf(file) === -1) {
fs.unlink(filePath);
logger.info('The following obsolete file has been removed:', filePath);
}
}
});
}
function cleanObsoleteLayerFiles(themeModel) {
cleanObsoleteLayerFilesInThatDirectory(themeModel, 'shape');
cleanObsoleteLayerFilesInThatDirectory(themeModel, 'overPassCache');
}
function uploadFile(req, res, file, directory, osmId, tagName) {
file.originalname = file.originalname.toLowerCase();
let i = 2;
const fullDirectory = `${config.get('dataDirectory')}/${directory}`;
let publicPath = `/files/${directory}/${file.originalname}`;
let baseName = path.basename(file.originalname, `.${file.extension}`);
let fullPath = `${fullDirectory}/${file.originalname}`;
if (osmId && tagName) {
baseName = `${osmId}_${tagName}`;
publicPath = `/files/${directory}/${baseName}.${file.extension}`;
fullPath = `${fullDirectory}/${baseName}.${file.extension}`;
}
if (!fs.existsSync(fullDirectory)) {
fs.mkdirpSync(fullDirectory);
}
while (fs.existsSync(fullPath) === true) {
const fileName = `${baseName}_${i}.${file.extension}`;
publicPath = `/files/${directory}/${fileName}`;
fullPath = `${fullDirectory}/${fileName}`;
i += 1;
}
return new Promise((resolve, reject) => {
fs.move(file.path, fullPath, err => {
if (err) {
logger.error(err);
return reject(err);
}
const result = {};
result[file.fieldname] = publicPath;
return resolve(result);
});
});
}
class Api {
static postShapeFile(req, res) {
const fragment = req.query.fragment;
const promises = [];
for (const field in req.files) {
if ({}.hasOwnProperty.call(req.files, field)) {
const file = req.files[field];
const fileSize = file.size / 1024;
const maxFileSize = config.get('client.uploadMaxShapeFileSize');
if (fileSize > maxFileSize) {
return res.sendStatus(413);
}
const extension = file.extension.toLowerCase();
if (options.CONST.shapeFileExtensions.indexOf(extension) === -1) {
return res.sendStatus(415);
}
promises.push(
uploadFile(req, res, req.files[field], `theme/${fragment}/shape`)
);
}
}
return Promise.all(promises)
.then(results => {
res.send(results);
})
.catch(() => {
res.sendStatus(500);
});
}
static postNonOsmDataFile(req, res) {
const fragment = req.query.fragment;
const osmId = req.query.osmId;
const promises = [];
for (const field in req.files) {
if ({}.hasOwnProperty.call(req.files, field)) {
const file = req.files[field];
const tagName = field.replace(/^fileInput_\w+_(.*)$/g, '$1');
const fileSize = file.size / 1024;
const maxFileSize = config.get('client.uploadMaxNonOsmDataFileSize');
if (fileSize > maxFileSize) {
return res.status(413).send({ fileInput: field });
}
promises.push(
uploadFile(
req,
res,
req.files[field],
`theme/${fragment}/nonOsmData`,
osmId,
tagName
)
);
}
}
return Promise.all(promises)
.then(results => {
res.send(results);
})
.catch(() => {
res.sendStatus(500);
});
}
}
export default {
setOptions,
initDirectories,
deleteThemeDirectoryFromFragment,
duplicateFilesFromFragments,
cleanObsoleteLayerFiles,
Api
};
|
var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
var bower = require('gulp-bower');
var uglify = require('gulp-uglify');
var mincss = require('gulp-cssmin');
var concat = require('gulp-concat');
var ignore = require('gulp-ignore');
var del = require('del');
var lib = 'wwwroot/dist';
var content = 'wwwroot/Content';
/* LIMPIO LA CARPETA DE DESTINO */
gulp.task('clean',function(done){
del(lib, done);
});
/* ME ASEGURO DE QUE TODOS LOS PAQUETES DE bower.json ESTAN INSTALADOS */
gulp.task('bower:install', ['clean'], function () {
return bower();
});
gulp.task('showfiles', ['bower:install'], function () {
console.log(mainBowerFiles());
return;
});
/* MINIFICO TODOS LOS PAQUETES */
gulp.task('minifyJs', ['bower:install'], function () {
return gulp.src(mainBowerFiles())
.pipe(ignore.exclude([ "**/*.css" ]))
.pipe(uglify())
.pipe(gulp.dest(lib+'/js'));
});
/* MINIFICO JS PARTICULARES CREADOS POR MI */
gulp.task('minifyJsContent', ['minifyJs'], function () {
return gulp.src(content+'/js/*.js')
.pipe(uglify())
.pipe(gulp.dest(lib+'/js'));
});
/* MINIFICO CSS PARTICULARES CREADOS POR MI */
gulp.task('minifyCssContent', ['minifyJsContent'], function () {
return gulp.src(content+'/css/site.css')
.pipe(concat('front.css'))
.pipe(mincss())
.pipe(gulp.dest(lib+'/css/bundle/'));
});
/* BUNDLE PARA FRONT */
gulp.task('bundleFront', ['minifyCssContent'], function () {
return gulp.src([lib+'/js/layzr.js',lib+'/js/material.min.js',lib+'/js/layout.js'])
.pipe(concat('front.js'))
.pipe(gulp.dest(lib+'/js/bundle/'));
});
gulp.task('default', ['bundleFront'], function () {
return;
}); |
import config from 'config';
import path from 'path';
import api from '~/api/index.js';
export const PROVIDER_TYPE = {
MOVIES: 'movies',
SHOWS: 'shows'
};
const providers = {};
/**
* Get the correct API provider for a given provider type.
*
* @param {String} providerType -- PROVIDER_TYPE.MOVIES or PROVIDER_TYPE.SHOWS
* @returns {Object}
*/
export default function getProvider(providerType) {
if (!providerType) {
throw new Error('Missing a provider type');
}
let provider = providers[providerType];
if (!provider) {
const providerName = config.get(`alexa-libby.${providerType}.provider`).toLowerCase();
try {
provider = require(path.resolve(__dirname, providerName + '.js'));
providers[providerType] = provider;
}
catch (e) {
const apis = Object.keys(api).reduce((acc, val, i, arr) => {
const isLast = i === arr.length - 1;
return acc += `${isLast ? 'and ' : ''}"${val}"${!isLast ? ', ' : ''}`;
}, '');
throw new Error(`Invalid provider name: "${providerName}". ` +
`Valid values are ${apis}, all lower case.`);
}
}
return provider;
}
|
describe('tooltip', function() {
var elm,
elmBody,
scope,
elmScope,
tooltipScope,
$document;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip'));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(inject(function($rootScope, $compile, _$document_) {
elmBody = angular.element(
'<div><span uib-tooltip="tooltip text" tooltip-animation="false">Selector Text</span></div>'
);
$document = _$document_;
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
function trigger(element, evt) {
evt = new Event(evt);
element[0].dispatchEvent(evt);
element.scope().$$childTail.$digest();
}
it('should not be open initially', inject(function() {
expect(tooltipScope.isOpen).toBe(false);
// We can only test *that* the tooltip-popup element wasn't created as the
// implementation is templated and replaced.
expect(elmBody.children().length).toBe(1);
}));
it('should open on mouseenter', inject(function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
// We can only test *that* the tooltip-popup element was created as the
// implementation is templated and replaced.
expect(elmBody.children().length).toBe(2);
}));
it('should close on mouseleave', inject(function() {
trigger(elm, 'mouseenter');
trigger(elm, 'mouseleave');
expect(tooltipScope.isOpen).toBe(false);
}));
it('should not animate on animation set to false', inject(function() {
expect(tooltipScope.animation).toBe(false);
}));
it('should have default placement of "top"', inject(function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.placement).toBe('top');
}));
it('should allow specification of placement', inject(function($compile) {
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-placement="bottom">Selector Text</span>'
))(scope);
scope.$apply();
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
trigger(elm, 'mouseenter');
expect(tooltipScope.placement).toBe('bottom');
}));
it('should update placement dynamically', inject(function($compile, $timeout) {
scope.place = 'bottom';
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-placement="{{place}}">Selector Text</span>'
))(scope);
scope.$apply();
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
trigger(elm, 'mouseenter');
expect(tooltipScope.placement).toBe('bottom');
scope.place = 'right';
scope.$digest();
$timeout.flush();
expect(tooltipScope.placement).toBe('right');
}));
it('should work inside an ngRepeat', inject(function($compile) {
elm = $compile(angular.element(
'<ul>'+
'<li ng-repeat="item in items">'+
'<span uib-tooltip="{{item.tooltip}}">{{item.name}}</span>'+
'</li>'+
'</ul>'
))(scope);
scope.items = [
{ name: 'One', tooltip: 'First Tooltip' }
];
scope.$digest();
var tt = angular.element(elm.find('li > span')[0]);
trigger(tt, 'mouseenter');
expect(tt.text()).toBe(scope.items[0].name);
tooltipScope = tt.scope().$$childTail;
expect(tooltipScope.content).toBe(scope.items[0].tooltip);
trigger(tt, 'mouseleave');
expect(tooltipScope.isOpen).toBeFalsy();
}));
it('should show correct text when in an ngRepeat', inject(function($compile, $timeout) {
elm = $compile(angular.element(
'<ul>'+
'<li ng-repeat="item in items">'+
'<span uib-tooltip="{{item.tooltip}}">{{item.name}}</span>'+
'</li>'+
'</ul>'
))(scope);
scope.items = [
{ name: 'One', tooltip: 'First Tooltip' },
{ name: 'Second', tooltip: 'Second Tooltip' }
];
scope.$digest();
var tt_1 = angular.element(elm.find('li > span')[0]);
var tt_2 = angular.element(elm.find('li > span')[1]);
trigger(tt_1, 'mouseenter');
trigger(tt_1, 'mouseleave');
$timeout.flush();
trigger(tt_2, 'mouseenter');
expect(tt_1.text()).toBe(scope.items[0].name);
expect(tt_2.text()).toBe(scope.items[1].name);
tooltipScope = tt_2.scope().$$childTail;
expect(tooltipScope.content).toBe(scope.items[1].tooltip);
expect(elm.find('.tooltip-inner').text()).toBe(scope.items[1].tooltip);
trigger(tt_2, 'mouseleave');
}));
it('should only have an isolate scope on the popup', inject(function($compile) {
var ttScope;
scope.tooltipMsg = 'Tooltip Text';
scope.alt = 'Alt Message';
elmBody = $compile(angular.element(
'<div><span alt={{alt}} uib-tooltip="{{tooltipMsg}}" tooltip-animation="false">Selector Text</span></div>'
))(scope);
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
trigger(elm, 'mouseenter');
expect(elm.attr('alt')).toBe(scope.alt);
ttScope = angular.element(elmBody.children()[1]).isolateScope();
expect(ttScope.placement).toBe('top');
expect(ttScope.content).toBe(scope.tooltipMsg);
trigger(elm, 'mouseleave');
//Isolate scope contents should be the same after hiding and showing again (issue 1191)
trigger(elm, 'mouseenter');
ttScope = angular.element(elmBody.children()[1]).isolateScope();
expect(ttScope.placement).toBe('top');
expect(ttScope.content).toBe(scope.tooltipMsg);
}));
it('should not show tooltips if there is nothing to show - issue #129', inject(function($compile) {
elmBody = $compile(angular.element(
'<div><span uib-tooltip="">Selector Text</span></div>'
))(scope);
scope.$digest();
elmBody.find('span').trigger('mouseenter');
expect(elmBody.children().length).toBe(1);
}));
it('should close the tooltip when its trigger element is destroyed', inject(function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
elm.remove();
elmScope.$destroy();
expect(elmBody.children().length).toBe(0);
}));
it('issue 1191 - scope on the popup should always be child of correct element scope', function() {
var ttScope;
trigger(elm, 'mouseenter');
ttScope = angular.element(elmBody.children()[1]).scope();
expect(ttScope.$parent).toBe(tooltipScope);
trigger(elm, 'mouseleave');
// After leaving and coming back, the scope's parent should be the same
trigger(elm, 'mouseenter');
ttScope = angular.element(elmBody.children()[1]).scope();
expect(ttScope.$parent).toBe(tooltipScope);
trigger(elm, 'mouseleave');
});
describe('with specified enable expression', function() {
beforeEach(inject(function($compile) {
scope.enable = false;
elmBody = $compile(angular.element(
'<div><span uib-tooltip="tooltip text" tooltip-enable="enable">Selector Text</span></div>'
))(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it('should not open ', inject(function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBeFalsy();
expect(elmBody.children().length).toBe(1);
}));
it('should open', inject(function() {
scope.enable = true;
scope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBeTruthy();
expect(elmBody.children().length).toBe(2);
}));
});
describe('with specified popup delay', function() {
var $timeout;
beforeEach(inject(function($compile, _$timeout_) {
$timeout = _$timeout_;
scope.delay = '1000';
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-popup-delay="{{delay}}" ng-disabled="disabled">Selector Text</span>'
))(scope);
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
scope.$digest();
}));
it('should open after timeout', function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
$timeout.flush();
expect(tooltipScope.isOpen).toBe(true);
});
it('should not open if mouseleave before timeout', function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
trigger(elm, 'mouseleave');
$timeout.flush();
expect(tooltipScope.isOpen).toBe(false);
});
it('should use default popup delay if specified delay is not a number', function() {
scope.delay = 'text1000';
scope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
});
it('should not open if disabled is present', function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
$timeout.flush(500);
expect(tooltipScope.isOpen).toBe(false);
elmScope.disabled = true;
elmScope.$digest();
expect(tooltipScope.isOpen).toBe(false);
});
it('should open when not disabled after being disabled - issue #4204', function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
$timeout.flush(500);
elmScope.disabled = true;
elmScope.$digest();
$timeout.flush(500);
expect(tooltipScope.isOpen).toBe(false);
elmScope.disabled = false;
elmScope.$digest();
trigger(elm, 'mouseenter');
$timeout.flush();
expect(tooltipScope.isOpen).toBe(true);
});
it('should close the tooltips in order', inject(function($compile) {
var elm2 = $compile('<div><span uib-tooltip="tooltip #2" tooltip-is-open="isOpen2">Selector Text</span></div>')(scope);
scope.$digest();
elm2 = elm2.find('span');
var tooltipScope2 = elm2.scope().$$childTail;
tooltipScope2.isOpen = false;
scope.$digest();
trigger(elm, 'mouseenter');
tooltipScope2.$digest();
$timeout.flush();
expect(tooltipScope.isOpen).toBe(true);
expect(tooltipScope2.isOpen).toBe(false);
trigger(elm2, 'mouseenter');
tooltipScope2.$digest();
$timeout.flush();
expect(tooltipScope.isOpen).toBe(true);
expect(tooltipScope2.isOpen).toBe(true);
var evt = $.Event('keypress');
evt.which = 27;
$document.trigger(evt);
tooltipScope.$digest();
tooltipScope2.$digest();
expect(tooltipScope.isOpen).toBe(true);
expect(tooltipScope2.isOpen).toBe(false);
var evt2 = $.Event('keypress');
evt2.which = 27;
$document.trigger(evt2);
tooltipScope.$digest();
tooltipScope2.$digest();
expect(tooltipScope.isOpen).toBe(false);
expect(tooltipScope2.isOpen).toBe(false);
}));
});
describe('with specified popup close delay', function() {
var $timeout;
beforeEach(inject(function($compile, _$timeout_) {
$timeout = _$timeout_;
scope.delay = '1000';
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-popup-close-delay="{{delay}}" ng-disabled="disabled">Selector Text</span>'
))(scope);
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
scope.$digest();
}));
it('should close after timeout', function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
trigger(elm, 'mouseleave');
$timeout.flush();
expect(tooltipScope.isOpen).toBe(false);
});
it('should use default popup close delay if specified delay is not a number and close after delay', function() {
scope.delay = 'text1000';
scope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.popupCloseDelay).toBe(500);
expect(tooltipScope.isOpen).toBe(true);
trigger(elm, 'mouseleave');
$timeout.flush();
expect(tooltipScope.isOpen).toBe(false);
});
it('should open when not disabled after being disabled and close after delay - issue #4204', function() {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
elmScope.disabled = true;
elmScope.$digest();
$timeout.flush(500);
expect(tooltipScope.isOpen).toBe(false);
elmScope.disabled = false;
elmScope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
trigger(elm, 'mouseleave');
$timeout.flush();
expect(tooltipScope.isOpen).toBe(false);
});
});
describe('with an is-open attribute', function() {
beforeEach(inject(function ($compile) {
scope.isOpen = false;
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-is-open="isOpen" >Selector Text</span>'
))(scope);
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
scope.$digest();
}));
it('should show and hide with the controller value', function() {
expect(tooltipScope.isOpen).toBe(false);
elmScope.isOpen = true;
elmScope.$digest();
expect(tooltipScope.isOpen).toBe(true);
elmScope.isOpen = false;
elmScope.$digest();
expect(tooltipScope.isOpen).toBe(false);
});
it('should update the controller value', function() {
trigger(elm, 'mouseenter');
expect(elmScope.isOpen).toBe(true);
trigger(elm, 'mouseleave');
expect(elmScope.isOpen).toBe(false);
});
});
describe('with an is-open attribute expression', function() {
beforeEach(inject(function($compile) {
scope.isOpen = false;
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-is-open="isOpen === true" >Selector Text</span>'
))(scope);
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
scope.$digest();
}));
it('should show and hide with the expression', function() {
expect(tooltipScope.isOpen).toBe(false);
elmScope.isOpen = true;
elmScope.$digest();
expect(tooltipScope.isOpen).toBe(true);
elmScope.isOpen = false;
elmScope.$digest();
expect(tooltipScope.isOpen).toBe(false);
});
});
describe('with a trigger attribute', function() {
var scope, elmBody, elm, elmScope;
beforeEach(inject(function($rootScope) {
scope = $rootScope;
}));
it('should use it to show but set the hide trigger based on the map for mapped triggers', inject(function($compile) {
elmBody = angular.element(
'<div><input uib-tooltip="Hello!" tooltip-trigger="focus" /></div>'
);
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'focus');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'blur');
expect(tooltipScope.isOpen).toBeFalsy();
}));
it('should use it as both the show and hide triggers for unmapped triggers', inject(function($compile) {
elmBody = angular.element(
'<div><input uib-tooltip="Hello!" tooltip-trigger="fakeTriggerAttr" /></div>'
);
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'fakeTriggerAttr');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'fakeTriggerAttr');
expect(tooltipScope.isOpen).toBeFalsy();
}));
it('should only set up triggers once', inject(function($compile) {
scope.test = true;
elmBody = angular.element(
'<div>' +
'<input uib-tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' +
'<input uib-tooltip="Hello!" tooltip-trigger="{{ (test && \'mouseenter\' || \'click\') }}" />' +
'</div>'
);
$compile(elmBody)(scope);
scope.$apply();
var elm1 = elmBody.find('input').eq(0);
var elm2 = elmBody.find('input').eq(1);
var elmScope1 = elm1.scope();
var elmScope2 = elm2.scope();
var tooltipScope2 = elmScope2.$$childTail;
scope.$apply('test = false');
// click trigger isn't set
elm2.click();
expect(tooltipScope2.isOpen).toBeFalsy();
// mouseenter trigger is still set
trigger(elm2, 'mouseenter');
expect(tooltipScope2.isOpen).toBeTruthy();
}));
it('should accept multiple triggers based on the map for mapped triggers', inject(function($compile) {
elmBody = angular.element(
'<div><input uib-tooltip="Hello!" tooltip-trigger="focus fakeTriggerAttr" /></div>'
);
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'focus');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'blur');
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'fakeTriggerAttr');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'fakeTriggerAttr');
expect(tooltipScope.isOpen).toBeFalsy();
}));
it('should not show when trigger is set to "none"', inject(function($compile) {
elmBody = angular.element(
'<div><input uib-tooltip="Hello!" tooltip-trigger="none" /></div>'
);
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
elm.trigger('mouseenter');
expect(tooltipScope.isOpen).toBeFalsy();
}));
it('should toggle on click and hide when anything else is clicked when trigger is set to "outsideClick"', inject(function($compile, $document) {
elm = $compile(angular.element(
'<span uib-tooltip="tooltip text" tooltip-trigger="outsideClick">Selector Text</span>'
))(scope);
scope.$apply();
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
// start off
expect(tooltipScope.isOpen).toBeFalsy();
// toggle
trigger(elm, 'click');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'click');
expect(tooltipScope.isOpen).toBeFalsy();
// click on, outsideClick off
trigger(elm, 'click');
expect(tooltipScope.isOpen).toBeTruthy();
angular.element($document[0].body).trigger('click');
tooltipScope.$digest();
expect(tooltipScope.isOpen).toBeFalsy();
}));
});
describe('with an append-to-body attribute', function() {
var scope, elmBody, elm, elmScope, $body;
beforeEach(inject(function($rootScope) {
scope = $rootScope;
}));
afterEach(function() {
$body.find('.tooltip').remove();
});
it('should append to the body', inject(function($compile, $document) {
$body = $document.find('body');
elmBody = angular.element(
'<div><span uib-tooltip="tooltip text" tooltip-append-to-body="true">Selector Text</span></div>'
);
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
var bodyLength = $body.children().length;
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
expect(elmBody.children().length).toBe(1);
expect($body.children().length).toEqual(bodyLength + 1);
}));
});
describe('cleanup', function() {
var elmBody, elm, elmScope, tooltipScope;
function inCache() {
var match = false;
angular.forEach(angular.element.cache, function(item) {
if (item.data && item.data.$scope === tooltipScope) {
match = true;
}
});
return match;
}
beforeEach(inject(function($compile, $rootScope) {
elmBody = angular.element('<div><input uib-tooltip="Hello!" tooltip-trigger="fooTrigger" /></div>');
$compile(elmBody)($rootScope);
$rootScope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
trigger(elm, 'fooTrigger');
tooltipScope = elmScope.$$childTail.$$childTail;
}));
it('should not contain a cached reference when not visible', inject(function($timeout) {
expect(inCache()).toBeTruthy();
elmScope.$destroy();
expect(inCache()).toBeFalsy();
}));
});
describe('observers', function() {
var elmBody, elm, elmScope, scope, tooltipScope;
beforeEach(inject(function($compile, $rootScope) {
scope = $rootScope;
scope.content = 'tooltip content';
scope.placement = 'top';
elmBody = angular.element('<div><input uib-tooltip="{{content}}" tooltip-placement={{placement}} /></div>');
$compile(elmBody)(scope);
scope.$apply();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it('should be removed when tooltip hides', inject(function($timeout) {
expect(tooltipScope.content).toBe(undefined);
expect(tooltipScope.placement).toBe(undefined);
trigger(elm, 'mouseenter');
expect(tooltipScope.content).toBe('tooltip content');
expect(tooltipScope.placement).toBe('top');
scope.content = 'tooltip content updated';
scope.placement = 'bottom';
scope.$apply();
expect(tooltipScope.content).toBe('tooltip content updated');
expect(tooltipScope.placement).toBe('bottom');
trigger(elm, 'mouseleave');
$timeout.flush();
scope.content = 'tooltip content updated after close';
scope.placement = 'left';
scope.$apply();
expect(tooltipScope.content).toBe('tooltip content updated');
expect(tooltipScope.placement).toBe('bottom');
}));
});
});
describe('tooltipWithDifferentSymbols', function() {
var elmBody;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip'));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
// configure interpolate provider to use [[ ]] instead of {{ }}
beforeEach(module(function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.startSymbol(']]');
}));
function trigger(element, evt) {
evt = new Event(evt);
element[0].dispatchEvent(evt);
element.scope().$$childTail.$digest();
}
it('should show the correct tooltip text', inject(function($compile, $rootScope) {
elmBody = angular.element(
'<div><input type="text" uib-tooltip="My tooltip" tooltip-trigger="focus" tooltip-placement="right" /></div>'
);
$compile(elmBody)($rootScope);
$rootScope.$apply();
var elmInput = elmBody.find('input');
trigger(elmInput, 'focus');
expect(elmInput.next().find('div').next().html()).toBe('My tooltip');
}));
});
describe('tooltip positioning', function() {
var elm, elmBody, elmScope, tooltipScope, scope;
var $position;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
$tooltipProvider.options({ animation: false });
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(inject(function($rootScope, $compile, $uibPosition) {
$position = $uibPosition;
spyOn($position, 'positionElements').and.callThrough();
scope = $rootScope;
scope.text = 'Some Text';
elmBody = $compile(angular.element(
'<div><span uib-tooltip="{{ text }}">Selector Text</span></div>'
))(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
function trigger(element, evt) {
evt = new Event(evt);
element[0].dispatchEvent(evt);
element.scope().$$childTail.$digest();
}
it('should re-position when value changes', inject(function($timeout) {
trigger(elm, 'mouseenter');
scope.$digest();
$timeout.flush();
var startingPositionCalls = $position.positionElements.calls.count();
scope.text = 'New Text';
scope.$digest();
$timeout.flush();
expect(elm.attr('uib-tooltip')).toBe('New Text');
expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1);
// Check that positionElements was called with elm
expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0])
.toBe(elm[0]);
scope.$digest();
$timeout.verifyNoPendingTasks();
expect($position.positionElements.calls.count()).toEqual(startingPositionCalls + 1);
expect($position.positionElements.calls.argsFor(startingPositionCalls)[0][0])
.toBe(elm[0]);
scope.$digest();
}));
});
describe('tooltipHtml', function() {
var elm, elmBody, elmScope, tooltipScope, scope;
// load the tooltip code
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
$tooltipProvider.options({ animation: false });
}));
// load the template
beforeEach(module('template/tooltip/tooltip-html-popup.html'));
beforeEach(inject(function($rootScope, $compile, $sce) {
scope = $rootScope;
scope.html = 'I say: <strong class="hello">Hello!</strong>';
scope.safeHtml = $sce.trustAsHtml(scope.html);
elmBody = $compile(angular.element(
'<div><span uib-tooltip-html="safeHtml">Selector Text</span></div>'
))(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
function trigger(element, evt) {
evt = new Event(evt);
element[0].dispatchEvent(evt);
element.scope().$$childTail.$digest();
}
it('should render html properly', inject(function() {
trigger(elm, 'mouseenter');
expect(elmBody.find('.tooltip-inner').html()).toBe(scope.html);
}));
it('should not open if html is empty', function() {
scope.safeHtml = null;
scope.$digest();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
});
it('should show on mouseenter and hide on mouseleave', inject(function($sce) {
expect(tooltipScope.isOpen).toBe(false);
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
expect(elmBody.children().length).toBe(2);
expect($sce.getTrustedHtml(tooltipScope.contentExp())).toEqual(scope.html);
trigger(elm, 'mouseleave');
expect(tooltipScope.isOpen).toBe(false);
expect(elmBody.children().length).toBe(1);
}));
});
describe('$tooltipProvider', function() {
var elm,
elmBody,
scope,
elmScope,
tooltipScope;
function trigger(element, evt) {
evt = new Event(evt);
element[0].dispatchEvent(evt);
element.scope().$$childTail.$digest();
}
describe('popupDelay', function() {
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
$tooltipProvider.options({popupDelay: 1000});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
}));
it('should open after timeout', inject(function($timeout) {
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(false);
$timeout.flush();
expect(tooltipScope.isOpen).toBe(true);
}));
});
describe('appendToBody', function() {
var $body;
beforeEach(module('template/tooltip/tooltip-popup.html'));
beforeEach(module('ui.bootstrap.tooltip', function($tooltipProvider) {
$tooltipProvider.options({ appendToBody: true });
}));
afterEach(function() {
$body.find('.tooltip').remove();
});
it('should append to the body', inject(function($rootScope, $compile, $document) {
$body = $document.find('body');
elmBody = angular.element(
'<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
var bodyLength = $body.children().length;
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
expect(elmBody.children().length).toBe(1);
expect($body.children().length).toEqual(bodyLength + 1);
}));
it('should close on location change', inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBe(true);
scope.$broadcast('$locationChangeSuccess');
scope.$digest();
expect(tooltipScope.isOpen).toBe(false);
}));
});
describe('triggers', function() {
describe('triggers with a mapped value', function() {
beforeEach(module('ui.bootstrap.tooltip', function($uibTooltipProvider) {
$uibTooltipProvider.options({trigger: 'focus'});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
it('should use the show trigger and the mapped value for the hide trigger', inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><input uib-tooltip="tooltip text" /></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'focus');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'blur');
expect(tooltipScope.isOpen).toBeFalsy();
}));
it('should override the show and hide triggers if there is an attribute', inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><input uib-tooltip="tooltip text" tooltip-trigger="mouseenter"/></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'mouseenter');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'mouseleave');
expect(tooltipScope.isOpen).toBeFalsy();
}));
});
describe('triggers with a custom mapped value', function() {
beforeEach(module('ui.bootstrap.tooltip', function($uibTooltipProvider) {
$uibTooltipProvider.setTriggers({ customOpenTrigger: 'foo bar' });
$uibTooltipProvider.options({trigger: 'customOpenTrigger'});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
it('should use the show trigger and the mapped value for the hide trigger', inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><input uib-tooltip="tooltip text" /></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('input');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'customOpenTrigger');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'foo');
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'customOpenTrigger');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'bar');
expect(tooltipScope.isOpen).toBeFalsy();
}));
});
describe('triggers without a mapped value', function() {
beforeEach(module('ui.bootstrap.tooltip', function($uibTooltipProvider) {
$uibTooltipProvider.options({trigger: 'fakeTrigger'});
}));
// load the template
beforeEach(module('template/tooltip/tooltip-popup.html'));
it('should use the show trigger to hide', inject(function($rootScope, $compile) {
elmBody = angular.element(
'<div><span uib-tooltip="tooltip text">Selector Text</span></div>'
);
scope = $rootScope;
$compile(elmBody)(scope);
scope.$digest();
elm = elmBody.find('span');
elmScope = elm.scope();
tooltipScope = elmScope.$$childTail;
expect(tooltipScope.isOpen).toBeFalsy();
trigger(elm, 'fakeTrigger');
expect(tooltipScope.isOpen).toBeTruthy();
trigger(elm, 'fakeTrigger');
expect(tooltipScope.isOpen).toBeFalsy();
}));
});
});
});
|
search_result['3591']=["topic_000000000000089F_attached_props--.html","PostVacancyStageListDto Attached Properties",""]; |
var EvolutionGame = EvolutionGame || {};
EvolutionGame.GameState = {
create: function() {
this.background = this.game.add.sprite(0, 0, 'space'); //fundo
this.background.inputEnabled = true;
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.playerManager = new EvolutionGame.PlayerManager(this.game);
this.DROP_BOX_INTERVAL = 6;
this.MAX_PLAYER_COUNT = 16;
this.playerCreatorTimer = this.game.time.events.loop(Phaser.Timer.SECOND * this.DROP_BOX_INTERVAL, this.createPlayer, this);
},
createPlayer: function() {
// console.log(this.playerManager.players.length);
if (this.playerManager.players.length < this.MAX_PLAYER_COUNT) {
var minX = 30,
maxX = this.game.width-30,
minY = 370,
maxY = this.game.height-60;
dropX = Utils.getRandomInt(minX, maxX);
dropY = Utils.getRandomInt(minY, maxY);
this.playerManager.createPlayer(dropX, dropY, 1, false);
}
}
}; |
/**
* @class PrettyJSON.view.Row
* @extends Backbone.View
*
* @author #rbarriga
* @version 0.1
*
*/
PrettyTable.view.Row = Backbone.View.extend({
initialize:function(opt) {
this.el = $('<tr />');
this.counterpart = opt.counterpart; //used by comparer
this.model = opt.model;
this.headers = opt.headers;
this.importantInfo = opt.importantInfo;
this.next = opt.next;
this.previous = opt.previous;
if(this.counterpart !== undefined) {
this.counterpart.counterpart = this;
}
this.cells = [];
this.renderCells();
},
renderCells:function() {
if(this.model === undefined) {
return;
}
if(this.headers !== undefined && this.headers.length !== 0) {
_.each(this.headers, function(header) {
var opt = {data: this.model[header.text]};
var cell = new PrettyTable.view.Cell(opt);
this.el.append(cell.el);
this.cells.push(cell);
}, this);
} else {
var cellCounterpart = this.counterpart === undefined ? undefined : this.counterpart.cells[0];
var opt = {counterpart: cellCounterpart, data: this.model, importantInfo: this.importantInfo};
var cell = new PrettyTable.view.Cell(opt);
this.el.append(cell.el);
this.cells.push(cell);
}
//Creating actions icons and binding to the passed in functions
if(this.next || this.previous) {
var actions = '';
if(this.previous) actions += '<a href="#" class="previous"><i class="fa fa-lg fa-chevron-left"></i>' //creating html
if(this.next) actions += '<a href="#" class="next"><i class="fa fa-lg fa-chevron-right"></i></a>';
var opt = {data: actions}
var cell = new PrettyTable.view.Cell(opt);
this.el.append(cell.el);
if(this.next) cell.el.find("a.next").on("click", {next: this.next, row: this, model: this.model}, function(e){
e.data.next(e.data.row, e.data.model)
})
if(this.previous) cell.el.find("a.previous").on("click", {previous: this.previous, row: this, model: this.model}, function(e){
e.data.previous(e.data.row, e.data.model)
})
}
},
setVisible:function(yes) { //used by comparer
if(yes) {
this.el.css('visibility', 'visible');
} else {
this.el.css('visibility', 'hidden');
}
},
update:function(model) {
this.model = model;
this.el.empty();
this.cells = [];
this.renderCells();
}
});
|
(function() {
var interval, t;
t = 10;
interval = setInterval(function() {
if (t > 0) {
return console.log(t--);
} else {
console.log('BLAST OFF!');
return phantom.exit();
}
}, 1000);
}).call(this);
|
/*!
* Bootstrap-select v1.13.16 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Hiçbiri seçilmedi',
noneResultsText: 'Hiçbir sonuç bulunamadı {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} öğe seçildi' : '{0} öğe seçildi';
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Limit aşıldı (maksimum {n} sayıda öğe )' : 'Limit aşıldı (maksimum {n} sayıda öğe)',
(numGroup == 1) ? 'Grup limiti aşıldı (maksimum {n} sayıda öğe)' : 'Grup limiti aşıldı (maksimum {n} sayıda öğe)'
];
},
selectAllText: 'Tümünü Seç',
deselectAllText: 'Seçiniz',
multipleSeparator: ', '
};
})(jQuery);
}));
//# sourceMappingURL=defaults-tr_TR.js.map |
module.exports={title:"Ionic",hex:"3880FF",source:"https://ionicframework.com/press",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Ionic Icon</title><path d="M12 6.53A5.476 5.476 0 0 0 6.53 12c0 3.014 2.452 5.47 5.47 5.47s5.47-2.456 5.47-5.47S15.014 6.53 12 6.53zM22.345 4.523a2.494 2.494 0 1 1-4.988 0 2.494 2.494 0 0 1 4.988 0z"/><path d="M22.922 7.027l-.103-.23-.169.188c-.408.464-.928.82-1.505 1.036l-.159.061.066.155a9.745 9.745 0 0 1 .75 3.759c0 5.405-4.397 9.806-9.806 9.806S2.194 17.405 2.194 12 6.596 2.194 12 2.194c1.467 0 2.883.319 4.2.947l.155.075.066-.155a3.767 3.767 0 0 1 1.106-1.453l.197-.159-.225-.117A11.905 11.905 0 0 0 12.001.001c-6.619 0-12 5.381-12 12s5.381 12 12 12 12-5.381 12-12c0-1.73-.361-3.403-1.078-4.973z"/></svg>'}; |
/**
* Tom Select v1.3.0
* Licensed under the Apache License, Version 2.0 (the "License");
*/
import TomSelect from '../../tom-select.js';
import getSettings from '../../getSettings.js';
import { addEvent } from '../../utils.js';
/**
* Plugin: "change_listener" (Tom Select)
* Copyright (c) contributors
*
* 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.
*
*/
TomSelect.define('change_listener', function (options) {
var self = this;
var changed = false;
addEvent(self.input, 'change', () => {
// prevent infinite loops
if (changed) {
changed = false;
return;
}
changed = true;
var settings = getSettings(self.input, {});
self.setupOptions(settings.options, settings.optgroups);
self.setValue(settings.items);
});
});
//# sourceMappingURL=plugin.js.map
|
/*!
* Copyright (c) 2017 ~ present NAVER Corp.
* billboard.js project is licensed under the MIT license
*
* billboard.js, JavaScript chart library
* https://naver.github.io/billboard.js/
*
* @version 3.1.5
* @requires billboard.js
* @summary billboard.js plugin
*/
import { select } from 'd3-selection';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var _extendStatics = function extendStatics(d, b) {
return _extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) Object.prototype.hasOwnProperty.call(b, p) && (d[p] = b[p]);
}, _extendStatics(d, b);
};
function __extends(d, b) {
function __() {
this.constructor = d;
}
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + (b + "") + " is not a constructor or null");
_extendStatics(d, b), d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/**
* Copyright (c) 2017 ~ present NAVER Corp.
* billboard.js project is licensed under the MIT license
*/
/**
* Base class to generate billboard.js plugin
* @class Plugin
*/
/**
* Version info string for plugin
* @name version
* @static
* @memberof Plugin
* @type {string}
* @example
* bb.plugin.stanford.version; // ex) 1.9.0
*/
var Plugin = /*#__PURE__*/function () {
/**
* Version info string for plugin
* @name version
* @static
* @memberof Plugin
* @type {String}
* @example
* bb.plugin.stanford.version; // ex) 1.9.0
*/
/**
* Constructor
* @param {Any} options config option object
* @private
*/
function Plugin(options) {
options === void 0 && (options = {}), this.$$, this.options = options;
}
/**
* Lifecycle hook for 'beforeInit' phase.
* @private
*/
var _proto = Plugin.prototype;
return _proto.$beforeInit = function $beforeInit() {}
/**
* Lifecycle hook for 'init' phase.
* @private
*/
, _proto.$init = function $init() {}
/**
* Lifecycle hook for 'afterInit' phase.
* @private
*/
, _proto.$afterInit = function $afterInit() {}
/**
* Lifecycle hook for 'redraw' phase.
* @private
*/
, _proto.$redraw = function $redraw() {}
/**
* Lifecycle hook for 'willDestroy' phase.
* @private
*/
, _proto.$willDestroy = function $willDestroy() {
var _this = this;
Object.keys(this).forEach(function (key) {
_this[key] = null, delete _this[key];
});
}, Plugin;
}();
Plugin.version = "#3.1.5#";
/**
* Bubble compare diagram plugin.<br>
* Compare data 3-dimensional ways: x-axis, y-axis & bubble-size.
* - **NOTE:**
* - Plugins aren't built-in. Need to be loaded or imported to be used.
* - Non required modules from billboard.js core, need to be installed separately.
* - **Required modules:**
* - [d3-selection](https://github.com/d3/d3-selection)
* @class plugin-bubblecompare
* @requires d3-selection
* @param {object} options bubble compare plugin options
* @augments Plugin
* @returns {BubbleCompare}
* @example
* // Plugin must be loaded before the use.
* <script src="$YOUR_PATH/plugin/billboardjs-plugin-bubblecompare.js"></script>
*
* var chart = bb.generate({
* data: {
* columns: [ ... ],
* type: "bubble"
* }
* ...
* plugins: [
* new bb.plugin.bubblecompare({
* minR: 11,
* maxR: 74,
* expandScale: 1.1
* }),
* ]
* });
* @example
* import {bb} from "billboard.js";
* import BubbleCompare from "billboard.js/dist/billboardjs-plugin-bubblecompare.esm";
*
* bb.generate({
* plugins: [
* new BubbleCompare({ ... })
* ]
* })
*/
var BubbleCompare = /** @class */ (function (_super) {
__extends(BubbleCompare, _super);
function BubbleCompare(options) {
var _this = _super.call(this, options) || this;
return _this;
}
BubbleCompare.prototype.$init = function () {
var $$ = this.$$;
$$.findClosest = this.findClosest.bind(this);
$$.getBubbleR = this.getBubbleR.bind(this);
$$.pointExpandedR = this.pointExpandedR.bind(this);
};
BubbleCompare.prototype.pointExpandedR = function (d) {
var baseR = this.getBubbleR(d);
var _a = this.options.expandScale, expandScale = _a === void 0 ? 1 : _a;
BubbleCompare.raiseFocusedBubbleLayer(d);
this.changeCursorPoint();
return baseR * expandScale;
};
BubbleCompare.raiseFocusedBubbleLayer = function (d) {
d.raise && select(d.node().parentNode.parentNode).raise();
};
BubbleCompare.prototype.changeCursorPoint = function () {
this.$$.$el.svg.select(".bb-event-rect").style("cursor", "pointer");
};
BubbleCompare.prototype.findClosest = function (values, pos) {
var _this = this;
var $$ = this.$$;
return values
.filter(function (v) { return v && !$$.isBarType(v.id); })
.reduce(function (acc, cur) {
var d = $$.dist(cur, pos);
return d < _this.getBubbleR(cur) ? cur : acc;
}, 0);
};
BubbleCompare.prototype.getBubbleR = function (d) {
var _this = this;
var _a = this.options, minR = _a.minR, maxR = _a.maxR;
var curVal = this.getZData(d);
if (!curVal)
return minR;
var _b = this.$$.data.targets.reduce(function (_a, cur) {
var accMin = _a[0], accMax = _a[1];
var val = _this.getZData(cur.values[0]);
return [Math.min(accMin, val), Math.max(accMax, val)];
}, [10000, 0]), min = _b[0], max = _b[1];
var size = min > 0 && max === min ? 0 : curVal / max;
return Math.abs(size) * (maxR - minR) + minR;
};
BubbleCompare.prototype.getZData = function (d) {
return this.$$.isBubbleZType(d) ?
this.$$.getBubbleZData(d.value, "z") :
d.value;
};
BubbleCompare.version = "0.0.1";
return BubbleCompare;
}(Plugin));
export { BubbleCompare as default };
|
import { W as WidgetBehavior } from './index-e00f48fc.js';
class FormatterBehavior extends WidgetBehavior {
static get formatter() {}
static get params() {
return {
localized: true,
};
}
init() {
super.init();
}
connected() {
super.connected();
this.apply();
}
changed(name, value) {
super.changed(name, value);
if (name in this.props) {
if (this.isConnected) {
this.apply();
}
}
}
apply() {
if (!this.locale) {
this.setLocale(this.lang);
}
this.host.innerHTML = this.constructor.formatter(this.value, this.locale, this);
}
fromHostValue(value, silent) {
this.value = value;
this.apply();
}
}
export { FormatterBehavior as F };
|
/*
Highstock JS v9.0.1 (2021-02-15)
Advanced Highstock tools
(c) 2010-2021 Highsoft AS
Author: Torstein Honsi
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/price-indicator",["highcharts","highcharts/modules/stock"],function(c){a(c);a.Highcharts=c;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function c(a,d,c,f){a.hasOwnProperty(d)||(a[d]=f.apply(null,c))}a=a?a._modules:{};c(a,"Extensions/PriceIndication.js",[a["Core/Series/Series.js"],a["Core/Utilities.js"]],function(a,
c){var d=c.addEvent,f=c.isArray,m=c.merge;d(a,"afterRender",function(){var a=this.options,c=a.pointRange,d=a.lastVisiblePrice,e=a.lastPrice;if((d||e)&&"highcharts-navigator-series"!==a.id){var n=this.xAxis,b=this.yAxis,p=b.crosshair,q=b.cross,r=b.crossLabel,g=this.points,h=g.length,k=this.xData[this.xData.length-1],l=this.yData[this.yData.length-1];e&&e.enabled&&(b.crosshair=b.options.crosshair=a.lastPrice,b.cross=this.lastPrice,e=f(l)?l[3]:l,b.drawCrosshair(null,{x:k,y:e,plotX:n.toPixels(k,!0),plotY:b.toPixels(e,
!0)}),this.yAxis.cross&&(this.lastPrice=this.yAxis.cross,this.lastPrice.y=e));d&&d.enabled&&0<h&&(c=g[h-1].x===k||null===c?1:2,b.crosshair=b.options.crosshair=m({color:"transparent"},a.lastVisiblePrice),b.cross=this.lastVisiblePrice,a=g[h-c],this.crossLabel&&(this.crossLabel.destroy(),delete b.crossLabel),b.drawCrosshair(null,a),b.cross&&(this.lastVisiblePrice=b.cross,"number"===typeof a.y&&(this.lastVisiblePrice.y=a.y)),this.crossLabel=b.crossLabel);b.crosshair=b.options.crosshair=p;b.cross=q;b.crossLabel=
r}})});c(a,"masters/modules/price-indicator.src.js",[],function(){})});
//# sourceMappingURL=price-indicator.js.map |
import { registerVersion, _registerComponent, _getProvider, getApp } from 'https://www.gstatic.com/firebasejs/9.6.2/firebase-app.js';
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The JS SDK supports 5 log levels and also allows a user the ability to
* silence the logs altogether.
*
* The order is a follows:
* DEBUG < VERBOSE < INFO < WARN < ERROR
*
* All of the log types above the current log level will be captured (i.e. if
* you set the log level to `INFO`, errors will still be logged, but `DEBUG` and
* `VERBOSE` logs will not)
*/
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE";
LogLevel[LogLevel["INFO"] = 2] = "INFO";
LogLevel[LogLevel["WARN"] = 3] = "WARN";
LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
LogLevel[LogLevel["SILENT"] = 5] = "SILENT";
})(LogLevel || (LogLevel = {}));
const levelStringToEnum = {
'debug': LogLevel.DEBUG,
'verbose': LogLevel.VERBOSE,
'info': LogLevel.INFO,
'warn': LogLevel.WARN,
'error': LogLevel.ERROR,
'silent': LogLevel.SILENT
};
/**
* The default log level
*/
const defaultLogLevel = LogLevel.INFO;
/**
* By default, `console.debug` is not displayed in the developer console (in
* chrome). To avoid forcing users to have to opt-in to these logs twice
* (i.e. once for firebase, and once in the console), we are sending `DEBUG`
* logs to the `console.log` function.
*/
const ConsoleMethod = {
[LogLevel.DEBUG]: 'log',
[LogLevel.VERBOSE]: 'log',
[LogLevel.INFO]: 'info',
[LogLevel.WARN]: 'warn',
[LogLevel.ERROR]: 'error'
};
/**
* The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR
* messages on to their corresponding console counterparts (if the log method
* is supported by the current log level)
*/
const defaultLogHandler = (instance, logType, ...args) => {
if (logType < instance.logLevel) {
return;
}
const now = new Date().toISOString();
const method = ConsoleMethod[logType];
if (method) {
console[method](`[${now}] ${instance.name}:`, ...args);
}
else {
throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
}
};
class Logger {
/**
* Gives you an instance of a Logger to capture messages according to
* Firebase's logging scheme.
*
* @param name The name that the logs will be associated with
*/
constructor(name) {
this.name = name;
/**
* The log level of the given Logger instance.
*/
this._logLevel = defaultLogLevel;
/**
* The main (internal) log handler for the Logger instance.
* Can be set to a new function in internal package code but not by user.
*/
this._logHandler = defaultLogHandler;
/**
* The optional, additional, user-defined log handler for the Logger instance.
*/
this._userLogHandler = null;
}
get logLevel() {
return this._logLevel;
}
set logLevel(val) {
if (!(val in LogLevel)) {
throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
}
this._logLevel = val;
}
// Workaround for setter/getter having to be the same type.
setLogLevel(val) {
this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;
}
get logHandler() {
return this._logHandler;
}
set logHandler(val) {
if (typeof val !== 'function') {
throw new TypeError('Value assigned to `logHandler` must be a function');
}
this._logHandler = val;
}
get userLogHandler() {
return this._userLogHandler;
}
set userLogHandler(val) {
this._userLogHandler = val;
}
/**
* The functions below are all based on the `console` interface
*/
debug(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);
this._logHandler(this, LogLevel.DEBUG, ...args);
}
log(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.VERBOSE, ...args);
this._logHandler(this, LogLevel.VERBOSE, ...args);
}
info(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);
this._logHandler(this, LogLevel.INFO, ...args);
}
warn(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);
this._logHandler(this, LogLevel.WARN, ...args);
}
error(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);
this._logHandler(this, LogLevel.ERROR, ...args);
}
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function isBrowserExtension() {
const runtime = typeof chrome === 'object'
? chrome.runtime
: typeof browser === 'object'
? browser.runtime
: undefined;
return typeof runtime === 'object' && runtime.id !== undefined;
}
/**
* This method checks if indexedDB is supported by current browser/service worker context
* @return true if indexedDB is supported by current browser/service worker context
*/
function isIndexedDBAvailable() {
return typeof indexedDB === 'object';
}
/**
* This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
* if errors occur during the database open operation.
*
* @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
* private browsing)
*/
function validateIndexedDBOpenable() {
return new Promise((resolve, reject) => {
try {
let preExist = true;
const DB_CHECK_NAME = 'validate-browser-context-for-indexeddb-analytics-module';
const request = self.indexedDB.open(DB_CHECK_NAME);
request.onsuccess = () => {
request.result.close();
// delete database only when it doesn't pre-exist
if (!preExist) {
self.indexedDB.deleteDatabase(DB_CHECK_NAME);
}
resolve(true);
};
request.onupgradeneeded = () => {
preExist = false;
};
request.onerror = () => {
var _a;
reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || '');
};
}
catch (error) {
reject(error);
}
});
}
/**
*
* This method checks whether cookie is enabled within current browser
* @return true if cookie is enabled within current browser
*/
function areCookiesEnabled() {
if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {
return false;
}
return true;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Standardized Firebase Error.
*
* Usage:
*
* // Typescript string literals for type-safe codes
* type Err =
* 'unknown' |
* 'object-not-found'
* ;
*
* // Closure enum for type-safe error codes
* // at-enum {string}
* var Err = {
* UNKNOWN: 'unknown',
* OBJECT_NOT_FOUND: 'object-not-found',
* }
*
* let errors: Map<Err, string> = {
* 'generic-error': "Unknown error",
* 'file-not-found': "Could not find file: {$file}",
* };
*
* // Type-safe function - must pass a valid error code as param.
* let error = new ErrorFactory<Err>('service', 'Service', errors);
*
* ...
* throw error.create(Err.GENERIC);
* ...
* throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
* ...
* // Service: Could not file file: foo.txt (service/file-not-found).
*
* catch (e) {
* assert(e.message === "Could not find file: foo.txt.");
* if (e.code === 'service/file-not-found') {
* console.log("Could not read file: " + e['file']);
* }
* }
*/
const ERROR_NAME = 'FirebaseError';
// Based on code from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
class FirebaseError extends Error {
constructor(
/** The error code for this error. */
code, message,
/** Custom data for this error. */
customData) {
super(message);
this.code = code;
this.customData = customData;
/** The custom name for all FirebaseErrors. */
this.name = ERROR_NAME;
// Fix For ES5
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, FirebaseError.prototype);
// Maintains proper stack trace for where our error was thrown.
// Only available on V8.
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ErrorFactory.prototype.create);
}
}
}
class ErrorFactory {
constructor(service, serviceName, errors) {
this.service = service;
this.serviceName = serviceName;
this.errors = errors;
}
create(code, ...data) {
const customData = data[0] || {};
const fullCode = `${this.service}/${code}`;
const template = this.errors[code];
const message = template ? replaceTemplate(template, customData) : 'Error';
// Service Name: Error message (service/code).
const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
const error = new FirebaseError(fullCode, fullMessage, customData);
return error;
}
}
function replaceTemplate(template, data) {
return template.replace(PATTERN, (_, key) => {
const value = data[key];
return value != null ? String(value) : `<${key}?>`;
});
}
const PATTERN = /\{\$([^}]+)}/g;
/**
* Deep equal two objects. Support Arrays and Objects.
*/
function deepEqual(a, b) {
if (a === b) {
return true;
}
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
for (const k of aKeys) {
if (!bKeys.includes(k)) {
return false;
}
const aProp = a[k];
const bProp = b[k];
if (isObject(aProp) && isObject(bProp)) {
if (!deepEqual(aProp, bProp)) {
return false;
}
}
else if (aProp !== bProp) {
return false;
}
}
for (const k of bKeys) {
if (!aKeys.includes(k)) {
return false;
}
}
return true;
}
function isObject(thing) {
return thing !== null && typeof thing === 'object';
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The amount of milliseconds to exponentially increase.
*/
const DEFAULT_INTERVAL_MILLIS = 1000;
/**
* The factor to backoff by.
* Should be a number greater than 1.
*/
const DEFAULT_BACKOFF_FACTOR = 2;
/**
* The maximum milliseconds to increase to.
*
* <p>Visible for testing
*/
const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.
/**
* The percentage of backoff time to randomize by.
* See
* http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic
* for context.
*
* <p>Visible for testing
*/
const RANDOM_FACTOR = 0.5;
/**
* Based on the backoff method from
* https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.
* Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.
*/
function calculateBackoffMillis(backoffCount, intervalMillis = DEFAULT_INTERVAL_MILLIS, backoffFactor = DEFAULT_BACKOFF_FACTOR) {
// Calculates an exponentially increasing value.
// Deviation: calculates value from count and a constant interval, so we only need to save value
// and count to restore state.
const currBaseValue = intervalMillis * Math.pow(backoffFactor, backoffCount);
// A random "fuzz" to avoid waves of retries.
// Deviation: randomFactor is required.
const randomWait = Math.round(
// A fraction of the backoff value to add/subtract.
// Deviation: changes multiplication order to improve readability.
RANDOM_FACTOR *
currBaseValue *
// A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
// if we add or subtract.
(Math.random() - 0.5) *
2);
// Limits backoff to max to avoid effectively permanent backoff.
return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function getModularInstance(service) {
if (service && service._delegate) {
return service._delegate;
}
else {
return service;
}
}
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
class Component {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
constructor(name, instanceFactory, type) {
this.name = name;
this.instanceFactory = instanceFactory;
this.type = type;
this.multipleInstances = false;
/**
* Properties to be added to the service namespace
*/
this.serviceProps = {};
this.instantiationMode = "LAZY" /* LAZY */;
this.onInstanceCreated = null;
}
setInstantiationMode(mode) {
this.instantiationMode = mode;
return this;
}
setMultipleInstances(multipleInstances) {
this.multipleInstances = multipleInstances;
return this;
}
setServiceProps(props) {
this.serviceProps = props;
return this;
}
setInstanceCreatedCallback(callback) {
this.onInstanceCreated = callback;
return this;
}
}
function toArray(arr) {
return Array.prototype.slice.call(arr);
}
function promisifyRequest(request) {
return new Promise(function(resolve, reject) {
request.onsuccess = function() {
resolve(request.result);
};
request.onerror = function() {
reject(request.error);
};
});
}
function promisifyRequestCall(obj, method, args) {
var request;
var p = new Promise(function(resolve, reject) {
request = obj[method].apply(obj, args);
promisifyRequest(request).then(resolve, reject);
});
p.request = request;
return p;
}
function promisifyCursorRequestCall(obj, method, args) {
var p = promisifyRequestCall(obj, method, args);
return p.then(function(value) {
if (!value) return;
return new Cursor(value, p.request);
});
}
function proxyProperties(ProxyClass, targetProp, properties) {
properties.forEach(function(prop) {
Object.defineProperty(ProxyClass.prototype, prop, {
get: function() {
return this[targetProp][prop];
},
set: function(val) {
this[targetProp][prop] = val;
}
});
});
}
function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) {
properties.forEach(function(prop) {
if (!(prop in Constructor.prototype)) return;
ProxyClass.prototype[prop] = function() {
return promisifyRequestCall(this[targetProp], prop, arguments);
};
});
}
function proxyMethods(ProxyClass, targetProp, Constructor, properties) {
properties.forEach(function(prop) {
if (!(prop in Constructor.prototype)) return;
ProxyClass.prototype[prop] = function() {
return this[targetProp][prop].apply(this[targetProp], arguments);
};
});
}
function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) {
properties.forEach(function(prop) {
if (!(prop in Constructor.prototype)) return;
ProxyClass.prototype[prop] = function() {
return promisifyCursorRequestCall(this[targetProp], prop, arguments);
};
});
}
function Index(index) {
this._index = index;
}
proxyProperties(Index, '_index', [
'name',
'keyPath',
'multiEntry',
'unique'
]);
proxyRequestMethods(Index, '_index', IDBIndex, [
'get',
'getKey',
'getAll',
'getAllKeys',
'count'
]);
proxyCursorRequestMethods(Index, '_index', IDBIndex, [
'openCursor',
'openKeyCursor'
]);
function Cursor(cursor, request) {
this._cursor = cursor;
this._request = request;
}
proxyProperties(Cursor, '_cursor', [
'direction',
'key',
'primaryKey',
'value'
]);
proxyRequestMethods(Cursor, '_cursor', IDBCursor, [
'update',
'delete'
]);
// proxy 'next' methods
['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) {
if (!(methodName in IDBCursor.prototype)) return;
Cursor.prototype[methodName] = function() {
var cursor = this;
var args = arguments;
return Promise.resolve().then(function() {
cursor._cursor[methodName].apply(cursor._cursor, args);
return promisifyRequest(cursor._request).then(function(value) {
if (!value) return;
return new Cursor(value, cursor._request);
});
});
};
});
function ObjectStore(store) {
this._store = store;
}
ObjectStore.prototype.createIndex = function() {
return new Index(this._store.createIndex.apply(this._store, arguments));
};
ObjectStore.prototype.index = function() {
return new Index(this._store.index.apply(this._store, arguments));
};
proxyProperties(ObjectStore, '_store', [
'name',
'keyPath',
'indexNames',
'autoIncrement'
]);
proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [
'put',
'add',
'delete',
'clear',
'get',
'getAll',
'getKey',
'getAllKeys',
'count'
]);
proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [
'openCursor',
'openKeyCursor'
]);
proxyMethods(ObjectStore, '_store', IDBObjectStore, [
'deleteIndex'
]);
function Transaction(idbTransaction) {
this._tx = idbTransaction;
this.complete = new Promise(function(resolve, reject) {
idbTransaction.oncomplete = function() {
resolve();
};
idbTransaction.onerror = function() {
reject(idbTransaction.error);
};
idbTransaction.onabort = function() {
reject(idbTransaction.error);
};
});
}
Transaction.prototype.objectStore = function() {
return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments));
};
proxyProperties(Transaction, '_tx', [
'objectStoreNames',
'mode'
]);
proxyMethods(Transaction, '_tx', IDBTransaction, [
'abort'
]);
function UpgradeDB(db, oldVersion, transaction) {
this._db = db;
this.oldVersion = oldVersion;
this.transaction = new Transaction(transaction);
}
UpgradeDB.prototype.createObjectStore = function() {
return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments));
};
proxyProperties(UpgradeDB, '_db', [
'name',
'version',
'objectStoreNames'
]);
proxyMethods(UpgradeDB, '_db', IDBDatabase, [
'deleteObjectStore',
'close'
]);
function DB(db) {
this._db = db;
}
DB.prototype.transaction = function() {
return new Transaction(this._db.transaction.apply(this._db, arguments));
};
proxyProperties(DB, '_db', [
'name',
'version',
'objectStoreNames'
]);
proxyMethods(DB, '_db', IDBDatabase, [
'close'
]);
// Add cursor iterators
// TODO: remove this once browsers do the right thing with promises
['openCursor', 'openKeyCursor'].forEach(function(funcName) {
[ObjectStore, Index].forEach(function(Constructor) {
// Don't create iterateKeyCursor if openKeyCursor doesn't exist.
if (!(funcName in Constructor.prototype)) return;
Constructor.prototype[funcName.replace('open', 'iterate')] = function() {
var args = toArray(arguments);
var callback = args[args.length - 1];
var nativeObject = this._store || this._index;
var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1));
request.onsuccess = function() {
callback(request.result);
};
};
});
});
// polyfill getAll
[Index, ObjectStore].forEach(function(Constructor) {
if (Constructor.prototype.getAll) return;
Constructor.prototype.getAll = function(query, count) {
var instance = this;
var items = [];
return new Promise(function(resolve) {
instance.iterateCursor(query, function(cursor) {
if (!cursor) {
resolve(items);
return;
}
items.push(cursor.value);
if (count !== undefined && items.length == count) {
resolve(items);
return;
}
cursor.continue();
});
});
};
});
function openDb(name, version, upgradeCallback) {
var p = promisifyRequestCall(indexedDB, 'open', [name, version]);
var request = p.request;
if (request) {
request.onupgradeneeded = function(event) {
if (upgradeCallback) {
upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction));
}
};
}
return p.then(function(db) {
return new DB(db);
});
}
const name$1 = "@firebase/installations";
const version$1 = "0.5.5";
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const PENDING_TIMEOUT_MS = 10000;
const PACKAGE_VERSION = `w:${version$1}`;
const INTERNAL_AUTH_VERSION = 'FIS_v2';
const INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';
const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour
const SERVICE = 'installations';
const SERVICE_NAME = 'Installations';
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ERROR_DESCRIPTION_MAP = {
["missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: "{$valueName}"',
["not-registered" /* NOT_REGISTERED */]: 'Firebase Installation is not registered.',
["installation-not-found" /* INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',
["request-failed" /* REQUEST_FAILED */]: '{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',
["app-offline" /* APP_OFFLINE */]: 'Could not process request. Application offline.',
["delete-pending-registration" /* DELETE_PENDING_REGISTRATION */]: "Can't delete installation while there is a pending registration request."
};
const ERROR_FACTORY$1 = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);
/** Returns true if error is a FirebaseError that is based on an error from the server. */
function isServerError(error) {
return (error instanceof FirebaseError &&
error.code.includes("request-failed" /* REQUEST_FAILED */));
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function getInstallationsEndpoint({ projectId }) {
return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;
}
function extractAuthTokenInfoFromResponse(response) {
return {
token: response.token,
requestStatus: 2 /* COMPLETED */,
expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),
creationTime: Date.now()
};
}
async function getErrorFromResponse(requestName, response) {
const responseJson = await response.json();
const errorData = responseJson.error;
return ERROR_FACTORY$1.create("request-failed" /* REQUEST_FAILED */, {
requestName,
serverCode: errorData.code,
serverMessage: errorData.message,
serverStatus: errorData.status
});
}
function getHeaders$1({ apiKey }) {
return new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
'x-goog-api-key': apiKey
});
}
function getHeadersWithAuth(appConfig, { refreshToken }) {
const headers = getHeaders$1(appConfig);
headers.append('Authorization', getAuthorizationHeader(refreshToken));
return headers;
}
/**
* Calls the passed in fetch wrapper and returns the response.
* If the returned response has a status of 5xx, re-runs the function once and
* returns the response.
*/
async function retryIfServerError(fn) {
const result = await fn();
if (result.status >= 500 && result.status < 600) {
// Internal Server Error. Retry request.
return fn();
}
return result;
}
function getExpiresInFromResponseExpiresIn(responseExpiresIn) {
// This works because the server will never respond with fractions of a second.
return Number(responseExpiresIn.replace('s', '000'));
}
function getAuthorizationHeader(refreshToken) {
return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
async function createInstallationRequest(appConfig, { fid }) {
const endpoint = getInstallationsEndpoint(appConfig);
const headers = getHeaders$1(appConfig);
const body = {
fid,
authVersion: INTERNAL_AUTH_VERSION,
appId: appConfig.appId,
sdkVersion: PACKAGE_VERSION
};
const request = {
method: 'POST',
headers,
body: JSON.stringify(body)
};
const response = await retryIfServerError(() => fetch(endpoint, request));
if (response.ok) {
const responseValue = await response.json();
const registeredInstallationEntry = {
fid: responseValue.fid || fid,
registrationStatus: 2 /* COMPLETED */,
refreshToken: responseValue.refreshToken,
authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)
};
return registeredInstallationEntry;
}
else {
throw await getErrorFromResponse('Create Installation', response);
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Returns a promise that resolves after given time passes. */
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function bufferToBase64UrlSafe(array) {
const b64 = btoa(String.fromCharCode(...array));
return b64.replace(/\+/g, '-').replace(/\//g, '_');
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const VALID_FID_PATTERN = /^[cdef][\w-]{21}$/;
const INVALID_FID = '';
/**
* Generates a new FID using random values from Web Crypto API.
* Returns an empty string if FID generation fails for any reason.
*/
function generateFid() {
try {
// A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5
// bytes. our implementation generates a 17 byte array instead.
const fidByteArray = new Uint8Array(17);
const crypto = self.crypto || self.msCrypto;
crypto.getRandomValues(fidByteArray);
// Replace the first 4 random bits with the constant FID header of 0b0111.
fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);
const fid = encode(fidByteArray);
return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;
}
catch (_a) {
// FID generation errored
return INVALID_FID;
}
}
/** Converts a FID Uint8Array to a base64 string representation. */
function encode(fidByteArray) {
const b64String = bufferToBase64UrlSafe(fidByteArray);
// Remove the 23rd character that was added because of the extra 4 bits at the
// end of our 17 byte array, and the '=' padding.
return b64String.substr(0, 22);
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Returns a string key that can be used to identify the app. */
function getKey(appConfig) {
return `${appConfig.appName}!${appConfig.appId}`;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fidChangeCallbacks = new Map();
/**
* Calls the onIdChange callbacks with the new FID value, and broadcasts the
* change to other tabs.
*/
function fidChanged(appConfig, fid) {
const key = getKey(appConfig);
callFidChangeCallbacks(key, fid);
broadcastFidChange(key, fid);
}
function callFidChangeCallbacks(key, fid) {
const callbacks = fidChangeCallbacks.get(key);
if (!callbacks) {
return;
}
for (const callback of callbacks) {
callback(fid);
}
}
function broadcastFidChange(key, fid) {
const channel = getBroadcastChannel();
if (channel) {
channel.postMessage({ key, fid });
}
closeBroadcastChannel();
}
let broadcastChannel = null;
/** Opens and returns a BroadcastChannel if it is supported by the browser. */
function getBroadcastChannel() {
if (!broadcastChannel && 'BroadcastChannel' in self) {
broadcastChannel = new BroadcastChannel('[Firebase] FID Change');
broadcastChannel.onmessage = e => {
callFidChangeCallbacks(e.data.key, e.data.fid);
};
}
return broadcastChannel;
}
function closeBroadcastChannel() {
if (fidChangeCallbacks.size === 0 && broadcastChannel) {
broadcastChannel.close();
broadcastChannel = null;
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DATABASE_NAME = 'firebase-installations-database';
const DATABASE_VERSION = 1;
const OBJECT_STORE_NAME = 'firebase-installations-store';
let dbPromise = null;
function getDbPromise() {
if (!dbPromise) {
dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, upgradeDB => {
// We don't use 'break' in this switch statement, the fall-through
// behavior is what we want, because if there are multiple versions between
// the old version and the current version, we want ALL the migrations
// that correspond to those versions to run, not only the last one.
// eslint-disable-next-line default-case
switch (upgradeDB.oldVersion) {
case 0:
upgradeDB.createObjectStore(OBJECT_STORE_NAME);
}
});
}
return dbPromise;
}
/** Assigns or overwrites the record for the given key with the given value. */
async function set(appConfig, value) {
const key = getKey(appConfig);
const db = await getDbPromise();
const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
const objectStore = tx.objectStore(OBJECT_STORE_NAME);
const oldValue = await objectStore.get(key);
await objectStore.put(value, key);
await tx.complete;
if (!oldValue || oldValue.fid !== value.fid) {
fidChanged(appConfig, value.fid);
}
return value;
}
/** Removes record(s) from the objectStore that match the given key. */
async function remove(appConfig) {
const key = getKey(appConfig);
const db = await getDbPromise();
const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
await tx.objectStore(OBJECT_STORE_NAME).delete(key);
await tx.complete;
}
/**
* Atomically updates a record with the result of updateFn, which gets
* called with the current value. If newValue is undefined, the record is
* deleted instead.
* @return Updated value
*/
async function update(appConfig, updateFn) {
const key = getKey(appConfig);
const db = await getDbPromise();
const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');
const store = tx.objectStore(OBJECT_STORE_NAME);
const oldValue = await store.get(key);
const newValue = updateFn(oldValue);
if (newValue === undefined) {
await store.delete(key);
}
else {
await store.put(newValue, key);
}
await tx.complete;
if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {
fidChanged(appConfig, newValue.fid);
}
return newValue;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Updates and returns the InstallationEntry from the database.
* Also triggers a registration request if it is necessary and possible.
*/
async function getInstallationEntry(appConfig) {
let registrationPromise;
const installationEntry = await update(appConfig, oldEntry => {
const installationEntry = updateOrCreateInstallationEntry(oldEntry);
const entryWithPromise = triggerRegistrationIfNecessary(appConfig, installationEntry);
registrationPromise = entryWithPromise.registrationPromise;
return entryWithPromise.installationEntry;
});
if (installationEntry.fid === INVALID_FID) {
// FID generation failed. Waiting for the FID from the server.
return { installationEntry: await registrationPromise };
}
return {
installationEntry,
registrationPromise
};
}
/**
* Creates a new Installation Entry if one does not exist.
* Also clears timed out pending requests.
*/
function updateOrCreateInstallationEntry(oldEntry) {
const entry = oldEntry || {
fid: generateFid(),
registrationStatus: 0 /* NOT_STARTED */
};
return clearTimedOutRequest(entry);
}
/**
* If the Firebase Installation is not registered yet, this will trigger the
* registration and return an InProgressInstallationEntry.
*
* If registrationPromise does not exist, the installationEntry is guaranteed
* to be registered.
*/
function triggerRegistrationIfNecessary(appConfig, installationEntry) {
if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {
if (!navigator.onLine) {
// Registration required but app is offline.
const registrationPromiseWithError = Promise.reject(ERROR_FACTORY$1.create("app-offline" /* APP_OFFLINE */));
return {
installationEntry,
registrationPromise: registrationPromiseWithError
};
}
// Try registering. Change status to IN_PROGRESS.
const inProgressEntry = {
fid: installationEntry.fid,
registrationStatus: 1 /* IN_PROGRESS */,
registrationTime: Date.now()
};
const registrationPromise = registerInstallation(appConfig, inProgressEntry);
return { installationEntry: inProgressEntry, registrationPromise };
}
else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {
return {
installationEntry,
registrationPromise: waitUntilFidRegistration(appConfig)
};
}
else {
return { installationEntry };
}
}
/** This will be executed only once for each new Firebase Installation. */
async function registerInstallation(appConfig, installationEntry) {
try {
const registeredInstallationEntry = await createInstallationRequest(appConfig, installationEntry);
return set(appConfig, registeredInstallationEntry);
}
catch (e) {
if (isServerError(e) && e.customData.serverCode === 409) {
// Server returned a "FID can not be used" error.
// Generate a new ID next time.
await remove(appConfig);
}
else {
// Registration failed. Set FID as not registered.
await set(appConfig, {
fid: installationEntry.fid,
registrationStatus: 0 /* NOT_STARTED */
});
}
throw e;
}
}
/** Call if FID registration is pending in another request. */
async function waitUntilFidRegistration(appConfig) {
// Unfortunately, there is no way of reliably observing when a value in
// IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),
// so we need to poll.
let entry = await updateInstallationRequest(appConfig);
while (entry.registrationStatus === 1 /* IN_PROGRESS */) {
// createInstallation request still in progress.
await sleep(100);
entry = await updateInstallationRequest(appConfig);
}
if (entry.registrationStatus === 0 /* NOT_STARTED */) {
// The request timed out or failed in a different call. Try again.
const { installationEntry, registrationPromise } = await getInstallationEntry(appConfig);
if (registrationPromise) {
return registrationPromise;
}
else {
// if there is no registrationPromise, entry is registered.
return installationEntry;
}
}
return entry;
}
/**
* Called only if there is a CreateInstallation request in progress.
*
* Updates the InstallationEntry in the DB based on the status of the
* CreateInstallation request.
*
* Returns the updated InstallationEntry.
*/
function updateInstallationRequest(appConfig) {
return update(appConfig, oldEntry => {
if (!oldEntry) {
throw ERROR_FACTORY$1.create("installation-not-found" /* INSTALLATION_NOT_FOUND */);
}
return clearTimedOutRequest(oldEntry);
});
}
function clearTimedOutRequest(entry) {
if (hasInstallationRequestTimedOut(entry)) {
return {
fid: entry.fid,
registrationStatus: 0 /* NOT_STARTED */
};
}
return entry;
}
function hasInstallationRequestTimedOut(installationEntry) {
return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&
installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
async function generateAuthTokenRequest({ appConfig, platformLoggerProvider }, installationEntry) {
const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);
const headers = getHeadersWithAuth(appConfig, installationEntry);
// If platform logger exists, add the platform info string to the header.
const platformLogger = platformLoggerProvider.getImmediate({
optional: true
});
if (platformLogger) {
headers.append('x-firebase-client', platformLogger.getPlatformInfoString());
}
const body = {
installation: {
sdkVersion: PACKAGE_VERSION
}
};
const request = {
method: 'POST',
headers,
body: JSON.stringify(body)
};
const response = await retryIfServerError(() => fetch(endpoint, request));
if (response.ok) {
const responseValue = await response.json();
const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);
return completedAuthToken;
}
else {
throw await getErrorFromResponse('Generate Auth Token', response);
}
}
function getGenerateAuthTokenEndpoint(appConfig, { fid }) {
return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Returns a valid authentication token for the installation. Generates a new
* token if one doesn't exist, is expired or about to expire.
*
* Should only be called if the Firebase Installation is registered.
*/
async function refreshAuthToken(installations, forceRefresh = false) {
let tokenPromise;
const entry = await update(installations.appConfig, oldEntry => {
if (!isEntryRegistered(oldEntry)) {
throw ERROR_FACTORY$1.create("not-registered" /* NOT_REGISTERED */);
}
const oldAuthToken = oldEntry.authToken;
if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {
// There is a valid token in the DB.
return oldEntry;
}
else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {
// There already is a token request in progress.
tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);
return oldEntry;
}
else {
// No token or token expired.
if (!navigator.onLine) {
throw ERROR_FACTORY$1.create("app-offline" /* APP_OFFLINE */);
}
const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);
tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);
return inProgressEntry;
}
});
const authToken = tokenPromise
? await tokenPromise
: entry.authToken;
return authToken;
}
/**
* Call only if FID is registered and Auth Token request is in progress.
*
* Waits until the current pending request finishes. If the request times out,
* tries once in this thread as well.
*/
async function waitUntilAuthTokenRequest(installations, forceRefresh) {
// Unfortunately, there is no way of reliably observing when a value in
// IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),
// so we need to poll.
let entry = await updateAuthTokenRequest(installations.appConfig);
while (entry.authToken.requestStatus === 1 /* IN_PROGRESS */) {
// generateAuthToken still in progress.
await sleep(100);
entry = await updateAuthTokenRequest(installations.appConfig);
}
const authToken = entry.authToken;
if (authToken.requestStatus === 0 /* NOT_STARTED */) {
// The request timed out or failed in a different call. Try again.
return refreshAuthToken(installations, forceRefresh);
}
else {
return authToken;
}
}
/**
* Called only if there is a GenerateAuthToken request in progress.
*
* Updates the InstallationEntry in the DB based on the status of the
* GenerateAuthToken request.
*
* Returns the updated InstallationEntry.
*/
function updateAuthTokenRequest(appConfig) {
return update(appConfig, oldEntry => {
if (!isEntryRegistered(oldEntry)) {
throw ERROR_FACTORY$1.create("not-registered" /* NOT_REGISTERED */);
}
const oldAuthToken = oldEntry.authToken;
if (hasAuthTokenRequestTimedOut(oldAuthToken)) {
return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });
}
return oldEntry;
});
}
async function fetchAuthTokenFromServer(installations, installationEntry) {
try {
const authToken = await generateAuthTokenRequest(installations, installationEntry);
const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });
await set(installations.appConfig, updatedInstallationEntry);
return authToken;
}
catch (e) {
if (isServerError(e) &&
(e.customData.serverCode === 401 || e.customData.serverCode === 404)) {
// Server returned a "FID not found" or a "Invalid authentication" error.
// Generate a new ID next time.
await remove(installations.appConfig);
}
else {
const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });
await set(installations.appConfig, updatedInstallationEntry);
}
throw e;
}
}
function isEntryRegistered(installationEntry) {
return (installationEntry !== undefined &&
installationEntry.registrationStatus === 2 /* COMPLETED */);
}
function isAuthTokenValid(authToken) {
return (authToken.requestStatus === 2 /* COMPLETED */ &&
!isAuthTokenExpired(authToken));
}
function isAuthTokenExpired(authToken) {
const now = Date.now();
return (now < authToken.creationTime ||
authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);
}
/** Returns an updated InstallationEntry with an InProgressAuthToken. */
function makeAuthTokenRequestInProgressEntry(oldEntry) {
const inProgressAuthToken = {
requestStatus: 1 /* IN_PROGRESS */,
requestTime: Date.now()
};
return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });
}
function hasAuthTokenRequestTimedOut(authToken) {
return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&
authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Creates a Firebase Installation if there isn't one for the app and
* returns the Installation ID.
* @param installations - The `Installations` instance.
*
* @public
*/
async function getId(installations) {
const installationsImpl = installations;
const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl.appConfig);
if (registrationPromise) {
registrationPromise.catch(console.error);
}
else {
// If the installation is already registered, update the authentication
// token if needed.
refreshAuthToken(installationsImpl).catch(console.error);
}
return installationEntry.fid;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Returns a Firebase Installations auth token, identifying the current
* Firebase Installation.
* @param installations - The `Installations` instance.
* @param forceRefresh - Force refresh regardless of token expiration.
*
* @public
*/
async function getToken(installations, forceRefresh = false) {
const installationsImpl = installations;
await completeInstallationRegistration(installationsImpl.appConfig);
// At this point we either have a Registered Installation in the DB, or we've
// already thrown an error.
const authToken = await refreshAuthToken(installationsImpl, forceRefresh);
return authToken.token;
}
async function completeInstallationRegistration(appConfig) {
const { registrationPromise } = await getInstallationEntry(appConfig);
if (registrationPromise) {
// A createInstallation request is in progress. Wait until it finishes.
await registrationPromise;
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function extractAppConfig(app) {
if (!app || !app.options) {
throw getMissingValueError('App Configuration');
}
if (!app.name) {
throw getMissingValueError('App Name');
}
// Required app config keys
const configKeys = [
'projectId',
'apiKey',
'appId'
];
for (const keyName of configKeys) {
if (!app.options[keyName]) {
throw getMissingValueError(keyName);
}
}
return {
appName: app.name,
projectId: app.options.projectId,
apiKey: app.options.apiKey,
appId: app.options.appId
};
}
function getMissingValueError(valueName) {
return ERROR_FACTORY$1.create("missing-app-config-values" /* MISSING_APP_CONFIG_VALUES */, {
valueName
});
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const INSTALLATIONS_NAME = 'installations';
const INSTALLATIONS_NAME_INTERNAL = 'installations-internal';
const publicFactory = (container) => {
const app = container.getProvider('app').getImmediate();
// Throws if app isn't configured properly.
const appConfig = extractAppConfig(app);
const platformLoggerProvider = _getProvider(app, 'platform-logger');
const installationsImpl = {
app,
appConfig,
platformLoggerProvider,
_delete: () => Promise.resolve()
};
return installationsImpl;
};
const internalFactory = (container) => {
const app = container.getProvider('app').getImmediate();
// Internal FIS instance relies on public FIS instance.
const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();
const installationsInternal = {
getId: () => getId(installations),
getToken: (forceRefresh) => getToken(installations, forceRefresh)
};
return installationsInternal;
};
function registerInstallations() {
_registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, "PUBLIC" /* PUBLIC */));
_registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, "PRIVATE" /* PRIVATE */));
}
/**
* Firebase Installations
*
* @packageDocumentation
*/
registerInstallations();
registerVersion(name$1, version$1);
// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
registerVersion(name$1, version$1, 'esm2017');
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Type constant for Firebase Analytics.
*/
const ANALYTICS_TYPE = 'analytics';
// Key to attach FID to in gtag params.
const GA_FID_KEY = 'firebase_id';
const ORIGIN_KEY = 'origin';
const FETCH_TIMEOUT_MILLIS = 60 * 1000;
const DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';
const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const logger = new Logger('@firebase/analytics');
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Makeshift polyfill for Promise.allSettled(). Resolves when all promises
* have either resolved or rejected.
*
* @param promises Array of promises to wait for.
*/
function promiseAllSettled(promises) {
return Promise.all(promises.map(promise => promise.catch(e => e)));
}
/**
* Inserts gtag script tag into the page to asynchronously download gtag.
* @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
*/
function insertScriptTag(dataLayerName, measurementId) {
const script = document.createElement('script');
// We are not providing an analyticsId in the URL because it would trigger a `page_view`
// without fid. We will initialize ga-id using gtag (config) command together with fid.
script.src = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;
script.async = true;
document.head.appendChild(script);
}
/**
* Get reference to, or create, global datalayer.
* @param dataLayerName Name of datalayer (most often the default, "_dataLayer").
*/
function getOrCreateDataLayer(dataLayerName) {
// Check for existing dataLayer and create if needed.
let dataLayer = [];
if (Array.isArray(window[dataLayerName])) {
dataLayer = window[dataLayerName];
}
else {
window[dataLayerName] = dataLayer;
}
return dataLayer;
}
/**
* Wrapped gtag logic when gtag is called with 'config' command.
*
* @param gtagCore Basic gtag function that just appends to dataLayer.
* @param initializationPromisesMap Map of appIds to their initialization promises.
* @param dynamicConfigPromisesList Array of dynamic config fetch promises.
* @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
* @param measurementId GA Measurement ID to set config for.
* @param gtagParams Gtag config params to set.
*/
async function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) {
// If config is already fetched, we know the appId and can use it to look up what FID promise we
/// are waiting for, and wait only on that one.
const correspondingAppId = measurementIdToAppId[measurementId];
try {
if (correspondingAppId) {
await initializationPromisesMap[correspondingAppId];
}
else {
// If config is not fetched yet, wait for all configs (we don't know which one we need) and
// find the appId (if any) corresponding to this measurementId. If there is one, wait on
// that appId's initialization promise. If there is none, promise resolves and gtag
// call goes through.
const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList);
const foundConfig = dynamicConfigResults.find(config => config.measurementId === measurementId);
if (foundConfig) {
await initializationPromisesMap[foundConfig.appId];
}
}
}
catch (e) {
logger.error(e);
}
gtagCore("config" /* CONFIG */, measurementId, gtagParams);
}
/**
* Wrapped gtag logic when gtag is called with 'event' command.
*
* @param gtagCore Basic gtag function that just appends to dataLayer.
* @param initializationPromisesMap Map of appIds to their initialization promises.
* @param dynamicConfigPromisesList Array of dynamic config fetch promises.
* @param measurementId GA Measurement ID to log event to.
* @param gtagParams Params to log with this event.
*/
async function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) {
try {
let initializationPromisesToWaitFor = [];
// If there's a 'send_to' param, check if any ID specified matches
// an initializeIds() promise we are waiting for.
if (gtagParams && gtagParams['send_to']) {
let gaSendToList = gtagParams['send_to'];
// Make it an array if is isn't, so it can be dealt with the same way.
if (!Array.isArray(gaSendToList)) {
gaSendToList = [gaSendToList];
}
// Checking 'send_to' fields requires having all measurement ID results back from
// the dynamic config fetch.
const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList);
for (const sendToId of gaSendToList) {
// Any fetched dynamic measurement ID that matches this 'send_to' ID
const foundConfig = dynamicConfigResults.find(config => config.measurementId === sendToId);
const initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId];
if (initializationPromise) {
initializationPromisesToWaitFor.push(initializationPromise);
}
else {
// Found an item in 'send_to' that is not associated
// directly with an FID, possibly a group. Empty this array,
// exit the loop early, and let it get populated below.
initializationPromisesToWaitFor = [];
break;
}
}
}
// This will be unpopulated if there was no 'send_to' field , or
// if not all entries in the 'send_to' field could be mapped to
// a FID. In these cases, wait on all pending initialization promises.
if (initializationPromisesToWaitFor.length === 0) {
initializationPromisesToWaitFor = Object.values(initializationPromisesMap);
}
// Run core gtag function with args after all relevant initialization
// promises have been resolved.
await Promise.all(initializationPromisesToWaitFor);
// Workaround for http://b/141370449 - third argument cannot be undefined.
gtagCore("event" /* EVENT */, measurementId, gtagParams || {});
}
catch (e) {
logger.error(e);
}
}
/**
* Wraps a standard gtag function with extra code to wait for completion of
* relevant initialization promises before sending requests.
*
* @param gtagCore Basic gtag function that just appends to dataLayer.
* @param initializationPromisesMap Map of appIds to their initialization promises.
* @param dynamicConfigPromisesList Array of dynamic config fetch promises.
* @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
*/
function wrapGtag(gtagCore,
/**
* Allows wrapped gtag calls to wait on whichever intialization promises are required,
* depending on the contents of the gtag params' `send_to` field, if any.
*/
initializationPromisesMap,
/**
* Wrapped gtag calls sometimes require all dynamic config fetches to have returned
* before determining what initialization promises (which include FIDs) to wait for.
*/
dynamicConfigPromisesList,
/**
* Wrapped gtag config calls can narrow down which initialization promise (with FID)
* to wait for if the measurementId is already fetched, by getting the corresponding appId,
* which is the key for the initialization promises map.
*/
measurementIdToAppId) {
/**
* Wrapper around gtag that ensures FID is sent with gtag calls.
* @param command Gtag command type.
* @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.
* @param gtagParams Params if event is EVENT/CONFIG.
*/
async function gtagWrapper(command, idOrNameOrParams, gtagParams) {
try {
// If event, check that relevant initialization promises have completed.
if (command === "event" /* EVENT */) {
// If EVENT, second arg must be measurementId.
await gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams);
}
else if (command === "config" /* CONFIG */) {
// If CONFIG, second arg must be measurementId.
await gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams);
}
else {
// If SET, second arg must be params.
gtagCore("set" /* SET */, idOrNameOrParams);
}
}
catch (e) {
logger.error(e);
}
}
return gtagWrapper;
}
/**
* Creates global gtag function or wraps existing one if found.
* This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and
* 'event' calls that belong to the GAID associated with this Firebase instance.
*
* @param initializationPromisesMap Map of appIds to their initialization promises.
* @param dynamicConfigPromisesList Array of dynamic config fetch promises.
* @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.
* @param dataLayerName Name of global GA datalayer array.
* @param gtagFunctionName Name of global gtag function ("gtag" if not user-specified).
*/
function wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) {
// Create a basic core gtag function
let gtagCore = function (..._args) {
// Must push IArguments object, not an array.
window[dataLayerName].push(arguments);
};
// Replace it with existing one if found
if (window[gtagFunctionName] &&
typeof window[gtagFunctionName] === 'function') {
// @ts-ignore
gtagCore = window[gtagFunctionName];
}
window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId);
return {
gtagCore,
wrappedGtag: window[gtagFunctionName]
};
}
/**
* Returns first script tag in DOM matching our gtag url pattern.
*/
function findGtagScriptOnPage() {
const scriptTags = window.document.getElementsByTagName('script');
for (const tag of Object.values(scriptTags)) {
if (tag.src && tag.src.includes(GTAG_URL)) {
return tag;
}
}
return null;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ERRORS = {
["already-exists" /* ALREADY_EXISTS */]: 'A Firebase Analytics instance with the appId {$id} ' +
' already exists. ' +
'Only one Firebase Analytics instance can be created for each appId.',
["already-initialized" /* ALREADY_INITIALIZED */]: 'initializeAnalytics() cannot be called again with different options than those ' +
'it was initially called with. It can be called again with the same options to ' +
'return the existing instance, or getAnalytics() can be used ' +
'to get a reference to the already-intialized instance.',
["already-initialized-settings" /* ALREADY_INITIALIZED_SETTINGS */]: 'Firebase Analytics has already been initialized.' +
'settings() must be called before initializing any Analytics instance' +
'or it will have no effect.',
["interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */]: 'Firebase Analytics Interop Component failed to instantiate: {$reason}',
["invalid-analytics-context" /* INVALID_ANALYTICS_CONTEXT */]: 'Firebase Analytics is not supported in this environment. ' +
'Wrap initialization of analytics in analytics.isSupported() ' +
'to prevent initialization in unsupported environments. Details: {$errorInfo}',
["indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */]: 'IndexedDB unavailable or restricted in this environment. ' +
'Wrap initialization of analytics in analytics.isSupported() ' +
'to prevent initialization in unsupported environments. Details: {$errorInfo}',
["fetch-throttle" /* FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +
' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',
["config-fetch-failed" /* CONFIG_FETCH_FAILED */]: 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',
["no-api-key" /* NO_API_KEY */]: 'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
'contain a valid API key.',
["no-app-id" /* NO_APP_ID */]: 'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field to' +
'contain a valid app ID.'
};
const ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Backoff factor for 503 errors, which we want to be conservative about
* to avoid overloading servers. Each retry interval will be
* BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one
* will be ~30 seconds (with fuzzing).
*/
const LONG_RETRY_FACTOR = 30;
/**
* Base wait interval to multiplied by backoffFactor^backoffCount.
*/
const BASE_INTERVAL_MILLIS = 1000;
/**
* Stubbable retry data storage class.
*/
class RetryData {
constructor(throttleMetadata = {}, intervalMillis = BASE_INTERVAL_MILLIS) {
this.throttleMetadata = throttleMetadata;
this.intervalMillis = intervalMillis;
}
getThrottleMetadata(appId) {
return this.throttleMetadata[appId];
}
setThrottleMetadata(appId, metadata) {
this.throttleMetadata[appId] = metadata;
}
deleteThrottleMetadata(appId) {
delete this.throttleMetadata[appId];
}
}
const defaultRetryData = new RetryData();
/**
* Set GET request headers.
* @param apiKey App API key.
*/
function getHeaders(apiKey) {
return new Headers({
Accept: 'application/json',
'x-goog-api-key': apiKey
});
}
/**
* Fetches dynamic config from backend.
* @param app Firebase app to fetch config for.
*/
async function fetchDynamicConfig(appFields) {
var _a;
const { appId, apiKey } = appFields;
const request = {
method: 'GET',
headers: getHeaders(apiKey)
};
const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);
const response = await fetch(appUrl, request);
if (response.status !== 200 && response.status !== 304) {
let errorMessage = '';
try {
// Try to get any error message text from server response.
const jsonResponse = (await response.json());
if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) {
errorMessage = jsonResponse.error.message;
}
}
catch (_ignored) { }
throw ERROR_FACTORY.create("config-fetch-failed" /* CONFIG_FETCH_FAILED */, {
httpStatus: response.status,
responseMessage: errorMessage
});
}
return response.json();
}
/**
* Fetches dynamic config from backend, retrying if failed.
* @param app Firebase app to fetch config for.
*/
async function fetchDynamicConfigWithRetry(app,
// retryData and timeoutMillis are parameterized to allow passing a different value for testing.
retryData = defaultRetryData, timeoutMillis) {
const { appId, apiKey, measurementId } = app.options;
if (!appId) {
throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */);
}
if (!apiKey) {
if (measurementId) {
return {
measurementId,
appId
};
}
throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */);
}
const throttleMetadata = retryData.getThrottleMetadata(appId) || {
backoffCount: 0,
throttleEndTimeMillis: Date.now()
};
const signal = new AnalyticsAbortSignal();
setTimeout(async () => {
// Note a very low delay, eg < 10ms, can elapse before listeners are initialized.
signal.abort();
}, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS);
return attemptFetchDynamicConfigWithRetry({ appId, apiKey, measurementId }, throttleMetadata, signal, retryData);
}
/**
* Runs one retry attempt.
* @param appFields Necessary app config fields.
* @param throttleMetadata Ongoing metadata to determine throttling times.
* @param signal Abort signal.
*/
async function attemptFetchDynamicConfigWithRetry(appFields, { throttleEndTimeMillis, backoffCount }, signal, retryData = defaultRetryData // for testing
) {
const { appId, measurementId } = appFields;
// Starts with a (potentially zero) timeout to support resumption from stored state.
// Ensures the throttle end time is honored if the last attempt timed out.
// Note the SDK will never make a request if the fetch timeout expires at this point.
try {
await setAbortableTimeout(signal, throttleEndTimeMillis);
}
catch (e) {
if (measurementId) {
logger.warn(`Timed out fetching this Firebase app's measurement ID from the server.` +
` Falling back to the measurement ID ${measurementId}` +
` provided in the "measurementId" field in the local Firebase config. [${e.message}]`);
return { appId, measurementId };
}
throw e;
}
try {
const response = await fetchDynamicConfig(appFields);
// Note the SDK only clears throttle state if response is success or non-retriable.
retryData.deleteThrottleMetadata(appId);
return response;
}
catch (e) {
if (!isRetriableError(e)) {
retryData.deleteThrottleMetadata(appId);
if (measurementId) {
logger.warn(`Failed to fetch this Firebase app's measurement ID from the server.` +
` Falling back to the measurement ID ${measurementId}` +
` provided in the "measurementId" field in the local Firebase config. [${e.message}]`);
return { appId, measurementId };
}
else {
throw e;
}
}
const backoffMillis = Number(e.customData.httpStatus) === 503
? calculateBackoffMillis(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR)
: calculateBackoffMillis(backoffCount, retryData.intervalMillis);
// Increments backoff state.
const throttleMetadata = {
throttleEndTimeMillis: Date.now() + backoffMillis,
backoffCount: backoffCount + 1
};
// Persists state.
retryData.setThrottleMetadata(appId, throttleMetadata);
logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);
return attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData);
}
}
/**
* Supports waiting on a backoff by:
*
* <ul>
* <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>
* <li>Listening on a signal bus for abort events, just like the Fetch API</li>
* <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled
* request appear the same.</li>
* </ul>
*
* <p>Visible for testing.
*/
function setAbortableTimeout(signal, throttleEndTimeMillis) {
return new Promise((resolve, reject) => {
// Derives backoff from given end time, normalizing negative numbers to zero.
const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);
const timeout = setTimeout(resolve, backoffMillis);
// Adds listener, rather than sets onabort, because signal is a shared object.
signal.addEventListener(() => {
clearTimeout(timeout);
// If the request completes before this timeout, the rejection has no effect.
reject(ERROR_FACTORY.create("fetch-throttle" /* FETCH_THROTTLE */, {
throttleEndTimeMillis
}));
});
});
}
/**
* Returns true if the {@link Error} indicates a fetch request may succeed later.
*/
function isRetriableError(e) {
if (!(e instanceof FirebaseError) || !e.customData) {
return false;
}
// Uses string index defined by ErrorData, which FirebaseError implements.
const httpStatus = Number(e.customData['httpStatus']);
return (httpStatus === 429 ||
httpStatus === 500 ||
httpStatus === 503 ||
httpStatus === 504);
}
/**
* Shims a minimal AbortSignal (copied from Remote Config).
*
* <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects
* of networking, such as retries. Firebase doesn't use AbortController enough to justify a
* polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be
* swapped out if/when we do.
*/
class AnalyticsAbortSignal {
constructor() {
this.listeners = [];
}
addEventListener(listener) {
this.listeners.push(listener);
}
abort() {
this.listeners.forEach(listener => listener());
}
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
async function validateIndexedDB() {
if (!isIndexedDBAvailable()) {
logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, {
errorInfo: 'IndexedDB is not available in this environment.'
}).message);
return false;
}
else {
try {
await validateIndexedDBOpenable();
}
catch (e) {
logger.warn(ERROR_FACTORY.create("indexeddb-unavailable" /* INDEXEDDB_UNAVAILABLE */, {
errorInfo: e
}).message);
return false;
}
}
return true;
}
/**
* Initialize the analytics instance in gtag.js by calling config command with fid.
*
* NOTE: We combine analytics initialization and setting fid together because we want fid to be
* part of the `page_view` event that's sent during the initialization
* @param app Firebase app
* @param gtagCore The gtag function that's not wrapped.
* @param dynamicConfigPromisesList Array of all dynamic config promises.
* @param measurementIdToAppId Maps measurementID to appID.
* @param installations _FirebaseInstallationsInternal instance.
*
* @returns Measurement ID.
*/
async function _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName, options) {
var _a;
const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);
// Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.
dynamicConfigPromise
.then(config => {
measurementIdToAppId[config.measurementId] = config.appId;
if (app.options.measurementId &&
config.measurementId !== app.options.measurementId) {
logger.warn(`The measurement ID in the local Firebase config (${app.options.measurementId})` +
` does not match the measurement ID fetched from the server (${config.measurementId}).` +
` To ensure analytics events are always sent to the correct Analytics property,` +
` update the` +
` measurement ID field in the local config or remove it from the local config.`);
}
})
.catch(e => logger.error(e));
// Add to list to track state of all dynamic config promises.
dynamicConfigPromisesList.push(dynamicConfigPromise);
const fidPromise = validateIndexedDB().then(envIsValid => {
if (envIsValid) {
return installations.getId();
}
else {
return undefined;
}
});
const [dynamicConfig, fid] = await Promise.all([
dynamicConfigPromise,
fidPromise
]);
// Detect if user has already put the gtag <script> tag on this page.
if (!findGtagScriptOnPage()) {
insertScriptTag(dataLayerName, dynamicConfig.measurementId);
}
// This command initializes gtag.js and only needs to be called once for the entire web app,
// but since it is idempotent, we can call it multiple times.
// We keep it together with other initialization logic for better code structure.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
gtagCore('js', new Date());
// User config added first. We don't want users to accidentally overwrite
// base Firebase config properties.
const configProperties = (_a = options === null || options === void 0 ? void 0 : options.config) !== null && _a !== void 0 ? _a : {};
// guard against developers accidentally setting properties with prefix `firebase_`
configProperties[ORIGIN_KEY] = 'firebase';
configProperties.update = true;
if (fid != null) {
configProperties[GA_FID_KEY] = fid;
}
// It should be the first config command called on this GA-ID
// Initialize this GA-ID and set FID on it using the gtag config API.
// Note: This will trigger a page_view event unless 'send_page_view' is set to false in
// `configProperties`.
gtagCore("config" /* CONFIG */, dynamicConfig.measurementId, configProperties);
return dynamicConfig.measurementId;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Analytics Service class.
*/
class AnalyticsService {
constructor(app) {
this.app = app;
}
_delete() {
delete initializationPromisesMap[this.app.options.appId];
return Promise.resolve();
}
}
/**
* Maps appId to full initialization promise. Wrapped gtag calls must wait on
* all or some of these, depending on the call's `send_to` param and the status
* of the dynamic config fetches (see below).
*/
let initializationPromisesMap = {};
/**
* List of dynamic config fetch promises. In certain cases, wrapped gtag calls
* wait on all these to be complete in order to determine if it can selectively
* wait for only certain initialization (FID) promises or if it must wait for all.
*/
let dynamicConfigPromisesList = [];
/**
* Maps fetched measurementIds to appId. Populated when the app's dynamic config
* fetch completes. If already populated, gtag config calls can use this to
* selectively wait for only this app's initialization promise (FID) instead of all
* initialization promises.
*/
const measurementIdToAppId = {};
/**
* Name for window global data layer array used by GA: defaults to 'dataLayer'.
*/
let dataLayerName = 'dataLayer';
/**
* Name for window global gtag function used by GA: defaults to 'gtag'.
*/
let gtagName = 'gtag';
/**
* Reproduction of standard gtag function or reference to existing
* gtag function on window object.
*/
let gtagCoreFunction;
/**
* Wrapper around gtag function that ensures FID is sent with all
* relevant event and config calls.
*/
let wrappedGtagFunction;
/**
* Flag to ensure page initialization steps (creation or wrapping of
* dataLayer and gtag script) are only run once per page load.
*/
let globalInitDone = false;
/**
* Configures Firebase Analytics to use custom `gtag` or `dataLayer` names.
* Intended to be used if `gtag.js` script has been installed on
* this page independently of Firebase Analytics, and is using non-default
* names for either the `gtag` function or for `dataLayer`.
* Must be called before calling `getAnalytics()` or it won't
* have any effect.
*
* @public
*
* @param options - Custom gtag and dataLayer names.
*/
function settings(options) {
if (globalInitDone) {
throw ERROR_FACTORY.create("already-initialized" /* ALREADY_INITIALIZED */);
}
if (options.dataLayerName) {
dataLayerName = options.dataLayerName;
}
if (options.gtagName) {
gtagName = options.gtagName;
}
}
/**
* Returns true if no environment mismatch is found.
* If environment mismatches are found, throws an INVALID_ANALYTICS_CONTEXT
* error that also lists details for each mismatch found.
*/
function warnOnBrowserContextMismatch() {
const mismatchedEnvMessages = [];
if (isBrowserExtension()) {
mismatchedEnvMessages.push('This is a browser extension environment.');
}
if (!areCookiesEnabled()) {
mismatchedEnvMessages.push('Cookies are not available.');
}
if (mismatchedEnvMessages.length > 0) {
const details = mismatchedEnvMessages
.map((message, index) => `(${index + 1}) ${message}`)
.join(' ');
const err = ERROR_FACTORY.create("invalid-analytics-context" /* INVALID_ANALYTICS_CONTEXT */, {
errorInfo: details
});
logger.warn(err.message);
}
}
/**
* Analytics instance factory.
* @internal
*/
function factory(app, installations, options) {
warnOnBrowserContextMismatch();
const appId = app.options.appId;
if (!appId) {
throw ERROR_FACTORY.create("no-app-id" /* NO_APP_ID */);
}
if (!app.options.apiKey) {
if (app.options.measurementId) {
logger.warn(`The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest` +
` measurement ID for this Firebase app. Falling back to the measurement ID ${app.options.measurementId}` +
` provided in the "measurementId" field in the local Firebase config.`);
}
else {
throw ERROR_FACTORY.create("no-api-key" /* NO_API_KEY */);
}
}
if (initializationPromisesMap[appId] != null) {
throw ERROR_FACTORY.create("already-exists" /* ALREADY_EXISTS */, {
id: appId
});
}
if (!globalInitDone) {
// Steps here should only be done once per page: creation or wrapping
// of dataLayer and global gtag function.
getOrCreateDataLayer(dataLayerName);
const { wrappedGtag, gtagCore } = wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagName);
wrappedGtagFunction = wrappedGtag;
gtagCoreFunction = gtagCore;
globalInitDone = true;
}
// Async but non-blocking.
// This map reflects the completion state of all promises for each appId.
initializationPromisesMap[appId] = _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCoreFunction, dataLayerName, options);
const analyticsInstance = new AnalyticsService(app);
return analyticsInstance;
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Logs an analytics event through the Firebase SDK.
*
* @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
* @param eventName Google Analytics event name, choose from standard list or use a custom string.
* @param eventParams Analytics event parameters.
*/
async function logEvent$1(gtagFunction, initializationPromise, eventName, eventParams, options) {
if (options && options.global) {
gtagFunction("event" /* EVENT */, eventName, eventParams);
return;
}
else {
const measurementId = await initializationPromise;
const params = Object.assign(Object.assign({}, eventParams), { 'send_to': measurementId });
gtagFunction("event" /* EVENT */, eventName, params);
}
}
/**
* Set screen_name parameter for this Google Analytics ID.
*
* @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
* @param screenName Screen name string to set.
*/
async function setCurrentScreen$1(gtagFunction, initializationPromise, screenName, options) {
if (options && options.global) {
gtagFunction("set" /* SET */, { 'screen_name': screenName });
return Promise.resolve();
}
else {
const measurementId = await initializationPromise;
gtagFunction("config" /* CONFIG */, measurementId, {
update: true,
'screen_name': screenName
});
}
}
/**
* Set user_id parameter for this Google Analytics ID.
*
* @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
* @param id User ID string to set
*/
async function setUserId$1(gtagFunction, initializationPromise, id, options) {
if (options && options.global) {
gtagFunction("set" /* SET */, { 'user_id': id });
return Promise.resolve();
}
else {
const measurementId = await initializationPromise;
gtagFunction("config" /* CONFIG */, measurementId, {
update: true,
'user_id': id
});
}
}
/**
* Set all other user properties other than user_id and screen_name.
*
* @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event
* @param properties Map of user properties to set
*/
async function setUserProperties$1(gtagFunction, initializationPromise, properties, options) {
if (options && options.global) {
const flatProperties = {};
for (const key of Object.keys(properties)) {
// use dot notation for merge behavior in gtag.js
flatProperties[`user_properties.${key}`] = properties[key];
}
gtagFunction("set" /* SET */, flatProperties);
return Promise.resolve();
}
else {
const measurementId = await initializationPromise;
gtagFunction("config" /* CONFIG */, measurementId, {
update: true,
'user_properties': properties
});
}
}
/**
* Set whether collection is enabled for this ID.
*
* @param enabled If true, collection is enabled for this ID.
*/
async function setAnalyticsCollectionEnabled$1(initializationPromise, enabled) {
const measurementId = await initializationPromise;
window[`ga-disable-${measurementId}`] = !enabled;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Returns an {@link Analytics} instance for the given app.
*
* @public
*
* @param app - The {@link https://www.gstatic.com/firebasejs/9.6.2/firebase-app.js#FirebaseApp} to use.
*/
function getAnalytics(app = getApp()) {
app = getModularInstance(app);
// Dependencies
const analyticsProvider = _getProvider(app, ANALYTICS_TYPE);
if (analyticsProvider.isInitialized()) {
return analyticsProvider.getImmediate();
}
return initializeAnalytics(app);
}
/**
* Returns an {@link Analytics} instance for the given app.
*
* @public
*
* @param app - The {@link https://www.gstatic.com/firebasejs/9.6.2/firebase-app.js#FirebaseApp} to use.
*/
function initializeAnalytics(app, options = {}) {
// Dependencies
const analyticsProvider = _getProvider(app, ANALYTICS_TYPE);
if (analyticsProvider.isInitialized()) {
const existingInstance = analyticsProvider.getImmediate();
if (deepEqual(options, analyticsProvider.getOptions())) {
return existingInstance;
}
else {
throw ERROR_FACTORY.create("already-initialized" /* ALREADY_INITIALIZED */);
}
}
const analyticsInstance = analyticsProvider.initialize({ options });
return analyticsInstance;
}
/**
* This is a public static method provided to users that wraps four different checks:
*
* 1. Check if it's not a browser extension environment.
* 2. Check if cookies are enabled in current browser.
* 3. Check if IndexedDB is supported by the browser environment.
* 4. Check if the current browser context is valid for using `IndexedDB.open()`.
*
* @public
*
*/
async function isSupported() {
if (isBrowserExtension()) {
return false;
}
if (!areCookiesEnabled()) {
return false;
}
if (!isIndexedDBAvailable()) {
return false;
}
try {
const isDBOpenable = await validateIndexedDBOpenable();
return isDBOpenable;
}
catch (error) {
return false;
}
}
/**
* Use gtag `config` command to set `screen_name`.
*
* @public
*
* @param analyticsInstance - The {@link Analytics} instance.
* @param screenName - Screen name to set.
*/
function setCurrentScreen(analyticsInstance, screenName, options) {
analyticsInstance = getModularInstance(analyticsInstance);
setCurrentScreen$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], screenName, options).catch(e => logger.error(e));
}
/**
* Use gtag `config` command to set `user_id`.
*
* @public
*
* @param analyticsInstance - The {@link Analytics} instance.
* @param id - User ID to set.
*/
function setUserId(analyticsInstance, id, options) {
analyticsInstance = getModularInstance(analyticsInstance);
setUserId$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], id, options).catch(e => logger.error(e));
}
/**
* Use gtag `config` command to set all params specified.
*
* @public
*/
function setUserProperties(analyticsInstance, properties, options) {
analyticsInstance = getModularInstance(analyticsInstance);
setUserProperties$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], properties, options).catch(e => logger.error(e));
}
/**
* Sets whether Google Analytics collection is enabled for this app on this device.
* Sets global `window['ga-disable-analyticsId'] = true;`
*
* @public
*
* @param analyticsInstance - The {@link Analytics} instance.
* @param enabled - If true, enables collection, if false, disables it.
*/
function setAnalyticsCollectionEnabled(analyticsInstance, enabled) {
analyticsInstance = getModularInstance(analyticsInstance);
setAnalyticsCollectionEnabled$1(initializationPromisesMap[analyticsInstance.app.options.appId], enabled).catch(e => logger.error(e));
}
/**
* Sends a Google Analytics event with given `eventParams`. This method
* automatically associates this logged event with this Firebase web
* app instance on this device.
* List of official event parameters can be found in the gtag.js
* reference documentation:
* {@link https://developers.google.com/gtagjs/reference/ga4-events
* | the GA4 reference documentation}.
*
* @public
*/
function logEvent(analyticsInstance, eventName, eventParams, options) {
analyticsInstance = getModularInstance(analyticsInstance);
logEvent$1(wrappedGtagFunction, initializationPromisesMap[analyticsInstance.app.options.appId], eventName, eventParams, options).catch(e => logger.error(e));
}
const name = "@firebase/analytics";
const version = "0.7.5";
/**
* Firebase Analytics
*
* @packageDocumentation
*/
function registerAnalytics() {
_registerComponent(new Component(ANALYTICS_TYPE, (container, { options: analyticsOptions }) => {
// getImmediate for FirebaseApp will always succeed
const app = container.getProvider('app').getImmediate();
const installations = container
.getProvider('installations-internal')
.getImmediate();
return factory(app, installations, analyticsOptions);
}, "PUBLIC" /* PUBLIC */));
_registerComponent(new Component('analytics-internal', internalFactory, "PRIVATE" /* PRIVATE */));
registerVersion(name, version);
// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
registerVersion(name, version, 'esm2017');
function internalFactory(container) {
try {
const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();
return {
logEvent: (eventName, eventParams, options) => logEvent(analytics, eventName, eventParams, options)
};
}
catch (e) {
throw ERROR_FACTORY.create("interop-component-reg-failed" /* INTEROP_COMPONENT_REG_FAILED */, {
reason: e
});
}
}
}
registerAnalytics();
export { getAnalytics, initializeAnalytics, isSupported, logEvent, setAnalyticsCollectionEnabled, setCurrentScreen, setUserId, setUserProperties, settings };
//# sourceMappingURL=firebase-analytics.js.map
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.10.1 (2021-11-03)
*/
(function () {
'use strict';
var global$2 = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
var global = tinymce.util.Tools.resolve('tinymce.util.Tools');
var getContentStyle = function (editor) {
return editor.getParam('content_style', '', 'string');
};
var shouldUseContentCssCors = function (editor) {
return editor.getParam('content_css_cors', false, 'boolean');
};
var getBodyClassByHash = function (editor) {
var bodyClass = editor.getParam('body_class', '', 'hash');
return bodyClass[editor.id] || '';
};
var getBodyClass = function (editor) {
var bodyClass = editor.getParam('body_class', '', 'string');
if (bodyClass.indexOf('=') === -1) {
return bodyClass;
} else {
return getBodyClassByHash(editor);
}
};
var getBodyIdByHash = function (editor) {
var bodyId = editor.getParam('body_id', '', 'hash');
return bodyId[editor.id] || bodyId;
};
var getBodyId = function (editor) {
var bodyId = editor.getParam('body_id', 'tinymce', 'string');
if (bodyId.indexOf('=') === -1) {
return bodyId;
} else {
return getBodyIdByHash(editor);
}
};
var getPreviewHtml = function (editor) {
var headHtml = '';
var encode = editor.dom.encode;
var contentStyle = getContentStyle(editor);
headHtml += '<base href="' + encode(editor.documentBaseURI.getURI()) + '">';
var cors = shouldUseContentCssCors(editor) ? ' crossorigin="anonymous"' : '';
global.each(editor.contentCSS, function (url) {
headHtml += '<link type="text/css" rel="stylesheet" href="' + encode(editor.documentBaseURI.toAbsolute(url)) + '"' + cors + '>';
});
if (contentStyle) {
headHtml += '<style type="text/css">' + contentStyle + '</style>';
}
var bodyId = getBodyId(editor);
var bodyClass = getBodyClass(editor);
var isMetaKeyPressed = global$1.mac ? 'e.metaKey' : 'e.ctrlKey && !e.altKey';
var preventClicksOnLinksScript = '<script>' + 'document.addEventListener && document.addEventListener("click", function(e) {' + 'for (var elm = e.target; elm; elm = elm.parentNode) {' + 'if (elm.nodeName === "A" && !(' + isMetaKeyPressed + ')) {' + 'e.preventDefault();' + '}' + '}' + '}, false);' + '</script> ';
var directionality = editor.getBody().dir;
var dirAttr = directionality ? ' dir="' + encode(directionality) + '"' : '';
var previewHtml = '<!DOCTYPE html>' + '<html>' + '<head>' + headHtml + '</head>' + '<body id="' + encode(bodyId) + '" class="mce-content-body ' + encode(bodyClass) + '"' + dirAttr + '>' + editor.getContent() + preventClicksOnLinksScript + '</body>' + '</html>';
return previewHtml;
};
var open = function (editor) {
var content = getPreviewHtml(editor);
var dataApi = editor.windowManager.open({
title: 'Preview',
size: 'large',
body: {
type: 'panel',
items: [{
name: 'preview',
type: 'iframe',
sandboxed: true
}]
},
buttons: [{
type: 'cancel',
name: 'close',
text: 'Close',
primary: true
}],
initialData: { preview: content }
});
dataApi.focus('close');
};
var register$1 = function (editor) {
editor.addCommand('mcePreview', function () {
open(editor);
});
};
var register = function (editor) {
var onAction = function () {
return editor.execCommand('mcePreview');
};
editor.ui.registry.addButton('preview', {
icon: 'preview',
tooltip: 'Preview',
onAction: onAction
});
editor.ui.registry.addMenuItem('preview', {
icon: 'preview',
text: 'Preview',
onAction: onAction
});
};
function Plugin () {
global$2.add('preview', function (editor) {
register$1(editor);
register(editor);
});
}
Plugin();
}());
|
const path=require("path");module.exports={mode:"production",entry:["babel-polyfill","./src/bowser.js"],output:{path:path.resolve(__dirname,"dist"),filename:"bowser.compiled.js",library:"bowser",libraryTarget:"umd",globalObject:"this"},module:{rules:[{test:/\.js$/,exclude:/(node_modules|bower_components)/,use:{loader:"babel-loader"}}]}}; |
var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var app = require('../../../app.js');
var models = require('../../../models');
var utils = require('../../utils');
var server;
describe('/quiz/:id', function() {
var qd;
before(function(done) {
server = app.listen(app.get('port'), function() {
models.sequelize.sync({ force: true }).then(function () {
utils.insertQuizDescriptor(models, 'Example Quiz Descriptor Title').then(function(res) {
qd = res;
done();
});
});
});
});
after(function(done) {
server.close();
done();
});
describe('/quiz/:id', function() {
describe('when quiz id does not exist', function() {
before(function(done) {
browser.get('/quiz/'+qd.id+1);
done();
});
it('should successfuly get the given url, but the page should render the 404 template', function(done) {
expect(browser.getCurrentUrl()).to.eventually.include('/quiz/'+qd.id+1);
browser.findElement(by.id('fourOFour')).then(function() {
done();
});
});
});
describe('quiz title', function() {
before(function(done) {
browser.get('/quiz/'+qd.id);
done();
});
it('should display the quiz title on the page', function() {
expect(element(by.binding('quizStarter.qd.title')).getText()).to.eventually.equal(qd.title);
});
});
describe('Start Quiz', function() {
beforeEach(function(done) {
browser.get('/quiz/'+qd.id);
done();
});
it('should go to /quiz/:id/:seed when the user clicks the Start Quiz button', function() {
element(by.buttonText('Start Quiz')).click();
expect(browser.getCurrentUrl()).to.eventually.include(browser.baseUrl + '/quiz/' + qd.id + '/');
});
it('should go to /quiz/:id/:seed with seed corresponding to the valid seed input', function() {
element(by.model('quizStarter.seed')).sendKeys('abcd4444');
element(by.buttonText('Start Quiz')).click();
expect(browser.getCurrentUrl()).to.eventually.include(browser.baseUrl + '/quiz/' + qd.id + '/abcd4444');
});
});
});
}); |
/* Kazakh (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Dmitriy Karasyov (dmitriy.karasyov@gmail.com). */
(function (factory) {
// AMD. Register as an anonymous module.
module.exports = factory(require('../datepicker'));;
}(function (datepicker) {
datepicker.regional['kk'] = {
closeText: '\u0416\u0430\u0431\u0443',
prevText: '<\u0410\u043B\u0434\u044B\u04A3\u0493\u044B',
nextText: '\u041A\u0435\u043B\u0435\u0441\u0456>',
currentText: '\u0411\u04AF\u0433\u0456\u043D',
monthNames: [
'\u049A\u0430\u04A3\u0442\u0430\u0440',
'\u0410\u049B\u043F\u0430\u043D',
'\u041D\u0430\u0443\u0440\u044B\u0437',
'\u0421\u04D9\u0443\u0456\u0440',
'\u041C\u0430\u043C\u044B\u0440',
'\u041C\u0430\u0443\u0441\u044B\u043C',
'\u0428\u0456\u043B\u0434\u0435',
'\u0422\u0430\u043C\u044B\u0437',
'\u049A\u044B\u0440\u043A\u04AF\u0439\u0435\u043A',
'\u049A\u0430\u0437\u0430\u043D',
'\u049A\u0430\u0440\u0430\u0448\u0430',
'\u0416\u0435\u043B\u0442\u043E\u049B\u0441\u0430\u043D'
],
monthNamesShort: [
'\u049A\u0430\u04A3',
'\u0410\u049B\u043F',
'\u041D\u0430\u0443',
'\u0421\u04D9\u0443',
'\u041C\u0430\u043C',
'\u041C\u0430\u0443',
'\u0428\u0456\u043B',
'\u0422\u0430\u043C',
'\u049A\u044B\u0440',
'\u049A\u0430\u0437',
'\u049A\u0430\u0440',
'\u0416\u0435\u043B'
],
dayNames: [
'\u0416\u0435\u043A\u0441\u0435\u043D\u0431\u0456',
'\u0414\u04AF\u0439\u0441\u0435\u043D\u0431\u0456',
'\u0421\u0435\u0439\u0441\u0435\u043D\u0431\u0456',
'\u0421\u04D9\u0440\u0441\u0435\u043D\u0431\u0456',
'\u0411\u0435\u0439\u0441\u0435\u043D\u0431\u0456',
'\u0416\u04B1\u043C\u0430',
'\u0421\u0435\u043D\u0431\u0456'
],
dayNamesShort: [
'\u0436\u043A\u0441',
'\u0434\u0441\u043D',
'\u0441\u0441\u043D',
'\u0441\u0440\u0441',
'\u0431\u0441\u043D',
'\u0436\u043C\u0430',
'\u0441\u043D\u0431'
],
dayNamesMin: [
'\u0416\u043A',
'\u0414\u0441',
'\u0421\u0441',
'\u0421\u0440',
'\u0411\u0441',
'\u0416\u043C',
'\u0421\u043D'
],
weekHeader: '\u041D\u0435',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
datepicker.setDefaults(datepicker.regional['kk']);
return datepicker.regional['kk'];
})); |
//= require chartkick
//= require Chart.bundle
|
/*
* Globalize Culture tr-TR
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined"
&& typeof exports !== "undefined"
&& typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "tr-TR", "default", {
name: "tr-TR",
englishName: "Turkish (Turkey)",
nativeName: "Türkçe (Türkiye)",
language: "tr",
numberFormat: {
",": ".",
".": ",",
percent: {
pattern: ["-%n","%n"],
",": ".",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": ".",
".": ",",
symbol: "TL"
}
},
calendars: {
standard: {
"/": ".",
firstDay: 1,
days: {
names: ["Pazar","Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi"],
namesAbbr: ["Paz","Pzt","Sal","Çar","Per","Cum","Cmt"],
namesShort: ["Pz","Pt","Sa","Ça","Pe","Cu","Ct"]
},
months: {
names: ["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık",""],
namesAbbr: ["Oca","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara",""]
},
AM: null,
PM: null,
patterns: {
d: "dd.MM.yyyy",
D: "dd MMMM yyyy dddd",
t: "HH:mm",
T: "HH:mm:ss",
f: "dd MMMM yyyy dddd HH:mm",
F: "dd MMMM yyyy dddd HH:mm:ss",
M: "dd MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
---
permalink: "/projects/the-cost-of-education/map-hamilton-county-school-spending/map.js"
---
(function() {
"use strict";
var
container = document.querySelector("#container"),
map = document.querySelector("#map"),
sliders = document.querySelector("#sliders"),
mobile = +(container.offsetWidth <= 414),
data
;
window.onresize = function() {
draw();
}
function draw(mapWidth) {
var margin = {
top: 0,
right: 0,
bottom: 0,
left: 0,
width: function() { return this.right + this.left; },
height: function() { return this.top + this.bottom; }
};
var ratio = { width: 1, height: 1.05 };
var width = function() {
if (!mapWidth) {
var mapWidth = +map.offsetWidth;
}
return mapWidth - margin.width();
}();
var height = function() {
var f = ratio.height / ratio.width;
return Math.round(width * f - margin.height());
}();
// Map setup
// ---------------------------------------------------------------------------
map.innerHTML = "";
var zones = {
high: topojson.feature(data, data.objects.high),
middle: topojson.feature(data, data.objects.middle),
elementary: topojson.feature(data, data.objects.elementary)
};
var color = d3.scale.ordinal()
.range(['rgb(236,231,242)','rgb(166,189,219)','rgb(54,144,192)','rgb(4,90,141)','rgb(8,68,89)'])
.domain([1,2,3,4,5]);
var projection = d3.geo.mercator()
.center(d3.geo.centroid(zones.elementary))
.translate([width / 2, height / 2])
.scale(width * 100)
.rotate([-.3, -.5])
;
var path = d3.geo.path()
.projection(projection);
var svg = d3.select(map).append("svg")
.attr("width", width + margin.width())
.attr("height", height + margin.height())
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var schools = svg.selectAll("g.school")
.data(zones.elementary.features)
.enter().append("g")
.attr("class", "school");
// Call default attributes on pageload
schools.append("path").call(pathAttr);
schools.append("circle").call(circleAttr);
// g.school path attributes
function pathAttr(d) {
d.attr("d", path)
.attr("fill", function(d) { return color(d.properties.quantile); })
.attr("fill-opacity", 1)
.attr("stroke", "white")
.attr("stroke-width", "1px")
.call(tooltip)
.call(modal);
}
// g.school circle attributes
function circleAttr(d) {
d.attr("class", "location")
.attr("cx", function(d) { return point(d).x; })
.attr("cy", function(d) { return point(d).y; })
.attr("r", 2)
.attr("fill", "#252525");
}
// Returns x, y positions from object's long/lat
function point(d) {
var point = projection([d.properties.longitude, d.properties.latitude]);
return { x: point[0], y: point[1] }
}
// Tooltip
// ---------------------------------------------------------------------------
function tooltip(d) {
d.on("mousemove", function(d) {
var tooltip = d3.select("#tooltip").classed("hidden", false);
tooltip.attr("pointer-events", "none")
.style("left", d3.event.pageX + 15 + "px")
.style("top", d3.event.pageY - 15 + "px");
tooltip.html(d.properties.school);
// wider border
d3.select(this).attr("stroke-width", "2px");
})
.on("mouseout", function() {
d3.select(this).attr("stroke-width", "1px"); // Resets border size
d3.select("#tooltip").classed("hidden", true);
});
}
// Modal window
// ---------------------------------------------------------------------------
function modal(d) {
var
modal = d3.select("#modal"),
close = modal.selectAll(".close")
;
// Event opens modal
d.on("click", function(d) {
openModal(map);
modalTable(d.properties);
if (!mobile) {
modalChart(d.properties);
}
});
// Event closes modal
close.on("click", function() {
d3.event.stopPropagation();
d3.event.preventDefault();
closeModal();
});
// Closes modal window
function closeModal() {
if (!modal.classed("hidden")) {
modal.classed("hidden", true);
modal.selectAll(".chart").remove();
}
}
function openModal(container) {
d3.event.stopPropagation();
d3.event.preventDefault()
closeModal();
modal.classed("hidden", false).style({
left: container.offsetLeft + "px",
top: container.offsetTop + "px",
width: container.offsetWidth + "px"
});
}
function modalTable(d) {
var table = modal.select("table");
var cells = table.selectAll("tr td:last-child");
table.select("caption").html(d.school);
cells[0].forEach(function(td) {
var
html,
selection = d3.select(td);
switch(selection.attr("class")) {
case "minority":
case "poverty":
case "special":
case "ell":
html = d3.format("%.0f")(d[selection.attr("class")]);
break;
case "funding":
html = d3.format("$,.0f")(d[selection.attr("class")]);
break;
default:
html = d[selection.attr("class")];
}
selection.html(html);
})
}
function modalChart(d) {
var grades = [
{ name: "Elementary", value: 7095 },
{ name: "Middle", value: 7198 },
{ name: "High", value: 6557 }
];
var data = [
{ name: d.school, value: d.funding },
{ name: "Hamilton County average", value: 7234 }
];
grades.forEach(function(grade) {
if (grade.name == d.type) {
grade.name += " school average";
data.push(grade);
}
});
// Add div here to determine svg container width
var chart = modal.append("div").attr("class", "chart");
chart.html("Average spending per student");
// Dimensions
margin.top = 16; margin.bottom = 32; margin.left = 160; margin.right = 0;
var width = +document.querySelector(".chart").offsetWidth - margin.width();
var height = 90;
// Scales, axis
var x = d3.scale.linear()
.domain([0, 12000])
.range([0, width]);
var y = d3.scale.ordinal()
.domain(data.map(function(d) { return d.name; }))
.rangeRoundBands([0, height], 0.2);
var axis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(d3.format("$,"))
.tickSize(-height, 0, 0)
.tickValues([6000,8000,10000]);
// Chart
var svg = d3.select("div.chart").append("svg")
.attr("width", width + margin.width())
.attr("height", height + margin.height())
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g").attr("class", "axis")
.call(axis)
.attr("transform", "translate(0," + height + ")");
var bars = svg.selectAll("g.bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) {
return "translate(0," + y(d.name) + ")";
});
bars.append("rect")
.attr("x", x(0))
.attr("y", 0)
.attr("height", y.rangeBand())
.attr("width", function(d) { return x(d.value); })
.attr("fill", color.range()[2]);
bars.append("text")
.attr("x", 0)
.text(function(d) { return d.name; });
bars.append("text")
.attr("x", function(d) { return x(d.value); })
.attr("fill", "white")
.text(function(d) { return d3.format("$,.0f")(d.value); })
bars.selectAll("text")
.attr("y", y.rangeBand() / 2)
.attr("dx", -5);
}
} // End of modal()
// Legend
// ---------------------------------------------------------------------------
var legend = function(width, data) {
var height = 36;
var scale = d3.scale.ordinal()
.domain(data)
.rangeRoundBands([0, width]);
var legend = svg.append("g")
.attr("id", "legend")
.attr("height", height)
.attr("width", width)
.attr("transform", "translate(8,20)");
// Legend label centered on desktop
legend.append("text")
.attr("x", (mobile) ? 0 : width / 2)
.attr("text-anchor", (mobile) ? "start" : "middle")
.text("Per-student spending");
var keys = legend.selectAll("g.key")
.data(data)
.enter().append("g")
.attr("class", "key")
.attr("transform", "translate(0,8)");
keys.append("rect")
.attr("fill", function(d) { return d; })
.attr("x", function(d) { return scale(d); })
.attr("y", 16)
.attr("width", scale.rangeBand())
.attr("height", 10);
keys.append("text")
.attr("x", function(d) { return scale(d) + scale.rangeBand() / 2; })
.attr("y", 12)
.text(function(d,i) {
switch(i) {
case 0: return (mobile) ? "–10%" : "<–10%";
case 2: return (mobile) ? "Avg" : "Average";
case 4: return (mobile) ? "+10%" : ">+10%";
default: return "";
}
});
}(width * .33, color.range());
// Input control
// ---------------------------------------------------------------------------
// Check for IE
// http://jsfiddle.net/jquerybyexample/gk7xA/
function isIE() {
var sAgent = window.navigator.userAgent;
var idx = sAgent.indexOf("MSIE");
if (idx > 0) {
return parseInt(sAgent.substring(idx+ 5, sAgent.indexOf(".", idx)));
} else if (!!navigator.userAgent.match(/Trident\/7\./)) {
return 11;
} else {
return 0;
}
}
// Listen for "change" events in IE, otherwise listen for "input" events
if (isIE()) {
d3.select(sliders).selectAll("input").on("change", filter);
} else {
d3.select(sliders).selectAll("input").on("input", filter);
}
function filter() {
// Range input settings
var
grade = +(d3.select("#sliders #grade input")[0][0].value),
funding = +(d3.select("#sliders #funding input")[0][0].value),
minority = +(d3.select("#sliders #minority input")[0][0].value),
poverty = +(d3.select("#sliders #poverty input")[0][0].value),
district = +(d3.select("#sliders #district input")[0][0].value)
;
grade = ["elementary","middle","high"][grade - 1];
// Update grade data
var schools = svg.selectAll("g.school")
.data(zones[grade].features);
// Remove unused svg elements
schools.exit().remove();
schools.select("path").remove();
schools.select("circle").remove();
// Add new svg groups
schools.enter().append("g").attr("class", "school");
// Append path to group
schools.append("path")
// Call default attributes
.call(pathAttr)
// Adjust fill-opacity, stroke via range input values
.attr("fill-opacity", function(d) {
var
props = d.properties,
mute = 0.3,
full = 1,
opacity
;
switch (true) {
case (props.funding <= funding):
case (props.minority <= minority):
case (props.poverty <= poverty):
opacity = mute;
break;
default:
opacity = full;
}
if (district != 0 && props.district != district) {
opacity = mute;
}
return opacity;
})
.attr("stroke", function(d) {
if (district == 0) { return "white"; }
if (d.properties.district == district) { return "#6d6e70"; }
});
// Append circle to group with default attributes
schools.append("circle").call(circleAttr);
// Update label outputs
d3.select("#grade-output").html(grade);
d3.select("#funding-output").html(d3.format("$,")(funding));
d3.select("#minority-output").html(d3.format("%.01f")(minority));
d3.select("#poverty-output").html(d3.format("%.01f")(poverty));
d3.select("#district-output").html(function() {
return [
"Countywide",
"In the 1st District",
"In the 2nd District",
"In the 3rd District",
"In the 4th District",
"In the 5th District",
"In the 6th District",
"In the 7th District",
"In the 8th District",
"In the 9th District"
][district];
});
}
} // End of draw()
// Load and map geo/topojson data
// ---------------------------------------------------------------------------
d3.json("school-zones.topo.json", function(error, geo) {
if (error) throw error;
data = geo;
d3.csv("data.csv", type, function(error, csv) {
if (error) throw error;
for (var grade in data.objects) {
var schools = data.objects[grade].geometries;
// To do: Refactor
schools.forEach(function(school) {
csv.forEach(function(row) {
if (school.properties.geoid == row.geoid) {
return school.properties = {
school: row.school,
longitude: row.longitude,
latitude: row.latitude,
funding: row.spending,
minority: row.minority,
poverty: row.economic_disadvantage,
district: row.district,
quantile: row.quantile,
grades: row.grades,
adm: row.adm,
special: row.special_education,
ell: row.ell,
type: row.type
};
}
})
})
}
new pym.Child({ renderCallback: draw });
});
});
function type(d) {
for (var key in d) {
if (+d[key]) {
d[key] = +d[key];
} else {
d[key] = d[key];
}
}
return d;
}
})(); |
class Search {
constructor() {
this.searchElement = document.querySelector('#search');
this.resultsContainer = document.querySelector('.results');
this.stationPreview = new StationPreview();
this.autoComplete = this.autoComplete.bind(this);
this.onClick = this.onClick.bind(this);
this.registerEventListeners();
this.autoComplete();
}
registerEventListeners() {
this.searchElement.addEventListener('input', this.autoComplete);
document.querySelector('.close').addEventListener('click', function() {
document.querySelector('.station-preview').style.display = "none";
});
}
autoComplete() {
var query = this.searchElement.value;
var resultsContainer = this.resultsContainer;
var listener = this.onClick;
this.getSearchResults(query).then(function(results) {
resultsContainer.innerHTML = '';
for(var i = 0; i < results.length; i++) {
var result = results[i];
var div = document.createElement('div');
div.innerHTML = result.name;
div.className = 'result';
div.id = result.id;
div.addEventListener('click', listener);
resultsContainer.appendChild(div);
}
});
}
onClick(evt) {
var stationPreview = this.stationPreview;
this.getStopInfo(evt.target.id)
.then(function(json) {
stationPreview.renderStation(json);
})
}
getSearchResults(query) {
query = query.trim();
return new Promise(function(resolve, reject) {
if(query.length === 0) resolve([]);
else fetch("https://api.tfl.gov.uk/Stoppoint/Search/" + query + "?modes=tube")
.then(function(response) {
response.json().then(function(json) {
resolve(json.matches);
});
});
});
}
getStopInfo(id) {
return new Promise(function(resolve, reject) {
fetch("https://api.tfl.gov.uk/Stoppoint/" + id)
.then(function(response) {
response.json().then(function(json) {
resolve(json);
});
})
});
}
}
window.addEventListener('load', new Search());
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;
/**
* Provides a resouce group with name 'testgroup101' and location 'West US'.
*
* @param {string} resourceGroupName Resource Group name 'testgroup101'.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link SampleResourceGroup} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _getSampleResourceGroup(resourceGroupName, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
let queryParameters = [];
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorModel']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = new client.models['SampleResourceGroup']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
}
/** Class representing a Group. */
class Group {
/**
* Create a Group.
* @param {MicrosoftAzureTestUrl} client Reference to the service client.
*/
constructor(client) {
this.client = client;
this._getSampleResourceGroup = _getSampleResourceGroup;
}
/**
* Provides a resouce group with name 'testgroup101' and location 'West US'.
*
* @param {string} resourceGroupName Resource Group name 'testgroup101'.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<SampleResourceGroup>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getSampleResourceGroupWithHttpOperationResponse(resourceGroupName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._getSampleResourceGroup(resourceGroupName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Provides a resouce group with name 'testgroup101' and location 'West US'.
*
* @param {string} resourceGroupName Resource Group name 'testgroup101'.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {SampleResourceGroup} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link SampleResourceGroup} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
getSampleResourceGroup(resourceGroupName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._getSampleResourceGroup(resourceGroupName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._getSampleResourceGroup(resourceGroupName, options, optionalCallback);
}
}
}
module.exports = Group;
|
import $ from 'dom7';
import { window, document } from 'ssr-window';
import Utils from '../../utils/utils';
import Device from '../../utils/device';
const Input = {
ignoreTypes: ['checkbox', 'button', 'submit', 'range', 'radio', 'image'],
createTextareaResizableShadow() {
const $shadowEl = $(document.createElement('textarea'));
$shadowEl.addClass('textarea-resizable-shadow');
$shadowEl.prop({
disabled: true,
readonly: true,
});
Input.textareaResizableShadow = $shadowEl;
},
textareaResizableShadow: undefined,
resizeTextarea(textareaEl) {
const app = this;
const $textareaEl = $(textareaEl);
if (!Input.textareaResizableShadow) {
Input.createTextareaResizableShadow();
}
const $shadowEl = Input.textareaResizableShadow;
if (!$textareaEl.length) return;
if (!$textareaEl.hasClass('resizable')) return;
if (Input.textareaResizableShadow.parents().length === 0) {
app.root.append($shadowEl);
}
const styles = window.getComputedStyle($textareaEl[0]);
('padding-top padding-bottom padding-left padding-right margin-left margin-right margin-top margin-bottom width font-size font-family font-style font-weight line-height font-variant text-transform letter-spacing border box-sizing display').split(' ').forEach((style) => {
let styleValue = styles[style];
if (('font-size line-height letter-spacing width').split(' ').indexOf(style) >= 0) {
styleValue = styleValue.replace(',', '.');
}
$shadowEl.css(style, styleValue);
});
const currentHeight = $textareaEl[0].clientHeight;
$shadowEl.val('');
const initialHeight = $shadowEl[0].scrollHeight;
$shadowEl.val($textareaEl.val());
$shadowEl.css('height', 0);
const scrollHeight = $shadowEl[0].scrollHeight;
if (currentHeight !== scrollHeight) {
if (scrollHeight > initialHeight) {
$textareaEl.css('height', `${scrollHeight}px`);
} else if (scrollHeight < currentHeight) {
$textareaEl.css('height', '');
}
if (scrollHeight > initialHeight || scrollHeight < currentHeight) {
$textareaEl.trigger('textarea:resize', { initialHeight, currentHeight, scrollHeight });
app.emit('textareaResize', { initialHeight, currentHeight, scrollHeight });
}
}
},
validate(inputEl) {
const $inputEl = $(inputEl);
if (!$inputEl.length) return;
const $itemInputEl = $inputEl.parents('.item-input');
const $inputWrapEl = $inputEl.parents('.input');
const validity = $inputEl[0].validity;
const validationMessage = $inputEl.dataset().errorMessage || $inputEl[0].validationMessage || '';
if (!validity) return;
if (!validity.valid) {
let $errorEl = $inputEl.nextAll('.item-input-error-message, .input-error-message');
if (validationMessage) {
if ($errorEl.length === 0) {
$errorEl = $(`<div class="${$inputWrapEl.length ? 'input-error-message' : 'item-input-error-message'}"></div>`);
$errorEl.insertAfter($inputEl);
}
$errorEl.text(validationMessage);
}
if ($errorEl.length > 0) {
$itemInputEl.addClass('item-input-with-error-message');
$inputWrapEl.addClass('input-with-error-message');
}
$itemInputEl.addClass('item-input-invalid');
$inputWrapEl.addClass('input-invalid');
$inputEl.addClass('input-invalid');
} else {
$itemInputEl.removeClass('item-input-invalid item-input-with-error-message');
$inputWrapEl.removeClass('input-invalid input-with-error-message');
$inputEl.removeClass('input-invalid');
}
},
validateInputs(el) {
const app = this;
$(el).find('input, textarea, select').each((index, inputEl) => {
app.input.validate(inputEl);
});
},
focus(inputEl) {
const $inputEl = $(inputEl);
const type = $inputEl.attr('type');
if (Input.ignoreTypes.indexOf(type) >= 0) return;
$inputEl.parents('.item-input').addClass('item-input-focused');
$inputEl.parents('.input').addClass('input-focused');
$inputEl.addClass('input-focused');
},
blur(inputEl) {
const $inputEl = $(inputEl);
$inputEl.parents('.item-input').removeClass('item-input-focused');
$inputEl.parents('.input').removeClass('input-focused');
$inputEl.removeClass('input-focused');
},
checkEmptyState(inputEl) {
const app = this;
let $inputEl = $(inputEl);
if (!$inputEl.is('input, select, textarea, .item-input [contenteditable]')) {
$inputEl = $inputEl.find('input, select, textarea, .item-input [contenteditable]').eq(0);
}
if (!$inputEl.length) return;
const isContentEditable = $inputEl[0].hasAttribute('contenteditable');
let value;
if (isContentEditable) {
if ($inputEl.find('.text-editor-placeholder').length) value = '';
else value = $inputEl.html();
} else {
value = $inputEl.val();
}
const $itemInputEl = $inputEl.parents('.item-input');
const $inputWrapEl = $inputEl.parents('.input');
if ((value && (typeof value === 'string' && value.trim() !== '')) || (Array.isArray(value) && value.length > 0)) {
$itemInputEl.addClass('item-input-with-value');
$inputWrapEl.addClass('input-with-value');
$inputEl.addClass('input-with-value');
$inputEl.trigger('input:notempty');
app.emit('inputNotEmpty', $inputEl[0]);
} else {
$itemInputEl.removeClass('item-input-with-value');
$inputWrapEl.removeClass('input-with-value');
$inputEl.removeClass('input-with-value');
$inputEl.trigger('input:empty');
app.emit('inputEmpty', $inputEl[0]);
}
},
scrollIntoView(inputEl, duration = 0, centered, force) {
const $inputEl = $(inputEl);
const $scrollableEl = $inputEl.parents('.page-content, .panel, .card-expandable .card-content').eq(0);
if (!$scrollableEl.length) {
return false;
}
const contentHeight = $scrollableEl[0].offsetHeight;
const contentScrollTop = $scrollableEl[0].scrollTop;
const contentPaddingTop = parseInt($scrollableEl.css('padding-top'), 10);
const contentPaddingBottom = parseInt($scrollableEl.css('padding-bottom'), 10);
const contentOffsetTop = $scrollableEl.offset().top - contentScrollTop;
const inputOffsetTop = $inputEl.offset().top - contentOffsetTop;
const inputHeight = $inputEl[0].offsetHeight;
const min = (inputOffsetTop + contentScrollTop) - contentPaddingTop;
const max = ((inputOffsetTop + contentScrollTop) - contentHeight) + contentPaddingBottom + inputHeight;
const centeredPosition = min + ((max - min) / 2);
if (contentScrollTop > min) {
$scrollableEl.scrollTop(centered ? centeredPosition : min, duration);
return true;
}
if (contentScrollTop < max) {
$scrollableEl.scrollTop(centered ? centeredPosition : max, duration);
return true;
}
if (force) {
$scrollableEl.scrollTop(centered ? centeredPosition : max, duration);
}
return false;
},
init() {
const app = this;
Input.createTextareaResizableShadow();
function onFocus() {
const inputEl = this;
if (app.params.input.scrollIntoViewOnFocus) {
if (Device.android) {
$(window).once('resize', () => {
if (document && document.activeElement === inputEl) {
app.input.scrollIntoView(inputEl, app.params.input.scrollIntoViewDuration, app.params.input.scrollIntoViewCentered, app.params.input.scrollIntoViewAlways);
}
});
} else {
app.input.scrollIntoView(inputEl, app.params.input.scrollIntoViewDuration, app.params.input.scrollIntoViewCentered, app.params.input.scrollIntoViewAlways);
}
}
app.input.focus(inputEl);
}
function onBlur() {
const $inputEl = $(this);
const tag = $inputEl[0].nodeName.toLowerCase();
app.input.blur($inputEl);
if ($inputEl.dataset().validate || $inputEl.attr('validate') !== null || $inputEl.attr('data-validate-on-blur') !== null) {
app.input.validate($inputEl);
}
// Resize textarea
if (tag === 'textarea' && $inputEl.hasClass('resizable')) {
if (Input.textareaResizableShadow) Input.textareaResizableShadow.remove();
}
}
function onChange() {
const $inputEl = $(this);
const type = $inputEl.attr('type');
const tag = $inputEl[0].nodeName.toLowerCase();
const isContentEditable = $inputEl[0].hasAttribute('contenteditable');
if (Input.ignoreTypes.indexOf(type) >= 0) return;
// Check Empty State
app.input.checkEmptyState($inputEl);
if (isContentEditable) return;
// Check validation
if ($inputEl.attr('data-validate-on-blur') === null && ($inputEl.dataset().validate || $inputEl.attr('validate') !== null)) {
app.input.validate($inputEl);
}
// Resize textarea
if (tag === 'textarea' && $inputEl.hasClass('resizable')) {
app.input.resizeTextarea($inputEl);
}
}
function onInvalid(e) {
const $inputEl = $(this);
if ($inputEl.attr('data-validate-on-blur') === null && ($inputEl.dataset().validate || $inputEl.attr('validate') !== null)) {
e.preventDefault();
app.input.validate($inputEl);
}
}
function clearInput() {
const $clicked = $(this);
const $inputEl = $clicked.siblings('input, textarea').eq(0);
const previousValue = $inputEl.val();
$inputEl
.val('')
.trigger('input change')
.focus()
.trigger('input:clear', previousValue);
app.emit('inputClear', previousValue);
}
$(document).on('click', '.input-clear-button', clearInput);
$(document).on('change input', 'input, textarea, select, .item-input [contenteditable]', onChange, true);
$(document).on('focus', 'input, textarea, select, .item-input [contenteditable]', onFocus, true);
$(document).on('blur', 'input, textarea, select, .item-input [contenteditable]', onBlur, true);
$(document).on('invalid', 'input, textarea, select', onInvalid, true);
},
};
export default {
name: 'input',
params: {
input: {
scrollIntoViewOnFocus: Device.android,
scrollIntoViewCentered: false,
scrollIntoViewDuration: 0,
scrollIntoViewAlways: false,
},
},
create() {
const app = this;
Utils.extend(app, {
input: {
scrollIntoView: Input.scrollIntoView.bind(app),
focus: Input.focus.bind(app),
blur: Input.blur.bind(app),
validate: Input.validate.bind(app),
validateInputs: Input.validateInputs.bind(app),
checkEmptyState: Input.checkEmptyState.bind(app),
resizeTextarea: Input.resizeTextarea.bind(app),
init: Input.init.bind(app),
},
});
},
on: {
init() {
const app = this;
app.input.init();
},
tabMounted(tabEl) {
const app = this;
const $tabEl = $(tabEl);
$tabEl.find('.item-input, .input').each((itemInputIndex, itemInputEl) => {
const $itemInputEl = $(itemInputEl);
$itemInputEl.find('input, select, textarea, [contenteditable]').each((inputIndex, inputEl) => {
const $inputEl = $(inputEl);
if (Input.ignoreTypes.indexOf($inputEl.attr('type')) >= 0) return;
app.input.checkEmptyState($inputEl);
});
});
$tabEl.find('textarea.resizable').each((textareaIndex, textareaEl) => {
app.input.resizeTextarea(textareaEl);
});
},
pageInit(page) {
const app = this;
const $pageEl = page.$el;
$pageEl.find('.item-input, .input').each((itemInputIndex, itemInputEl) => {
const $itemInputEl = $(itemInputEl);
$itemInputEl.find('input, select, textarea, [contenteditable]').each((inputIndex, inputEl) => {
const $inputEl = $(inputEl);
if (Input.ignoreTypes.indexOf($inputEl.attr('type')) >= 0) return;
app.input.checkEmptyState($inputEl);
});
});
$pageEl.find('textarea.resizable').each((textareaIndex, textareaEl) => {
app.input.resizeTextarea(textareaEl);
});
},
'panelBreakpoint panelCollapsedBreakpoint panelResize panelOpen panelSwipeOpen resize viewMasterDetailBreakpoint': function onPanelOpen(instance) {
const app = this;
if (instance && instance.$el) {
instance.$el.find('textarea.resizable').each((textareaIndex, textareaEl) => {
app.input.resizeTextarea(textareaEl);
});
} else {
$('textarea.resizable').each((textareaIndex, textareaEl) => {
app.input.resizeTextarea(textareaEl);
});
}
},
},
};
|
'use strict';
module.exports = require('./build/index');
|
import npm from '../adapters/npm';
import S3 from '../adapters/s3';
export default async (event, context, callback) => {
const { registry, bucket, region } = process.env;
const storage = new S3({ region, bucket });
const name = `${decodeURIComponent(event.name)}`;
const tarName = `${decodeURIComponent(event.tar)}`;
try {
const fileName = tarName.replace(`${name}-`, '');
const pkgBuffer = await storage.get(`${name}/${fileName}`);
return callback(null, pkgBuffer.toString('base64'));
} catch (storageError) {
if (storageError.code === 'NoSuchKey') {
try {
const npmPkgBuffer = await npm.tar(registry, `${event.name}/-/${event.tar}`);
return callback(null, npmPkgBuffer.toString('base64'));
} catch (npmError) {
return callback(npmError);
}
}
return callback(storageError);
}
};
|
/**
* @class ShadowTemplate
* @classdesc Mixin for stamping a template into a Shadow DOM subtree upon
* component instantiation
*
* If a component defines a template property (as a string or referencing a HTML
* template), when the component class is instantiated, a shadow root will be
* created on the instance, and the contents of the template will be cloned into
* the shadow root.
*
* For the time being, this extension retains support for Shadow DOM v0.
* That will eventually be deprecated as browsers implement Shadow DOM v1.
*/
// Feature detection for old Shadow DOM v0.
const USING_SHADOW_DOM_V0 = (typeof HTMLElement.prototype.createShadowRoot !== 'undefined');
export default (base) => class ShadowTemplate extends base {
/*
* If the component defines a template, a shadow root will be created on the
* component instance, and the template stamped into it.
*/
createdCallback() {
if (super.createdCallback) { super.createdCallback(); }
let template = this.template;
// TODO: Save the processed template with the component's class prototype
// so it doesn't need to be processed with every instantiation.
if (template) {
if (typeof template === 'string') {
// Upgrade plain string to real template.
template = createTemplateWithInnerHTML(template);
}
if (USING_SHADOW_DOM_V0) {
polyfillSlotWithContent(template);
}
if (window.ShadowDOMPolyfill) {
shimTemplateStyles(template, this.localName);
}
// this.log("cloning template into shadow root");
let root = USING_SHADOW_DOM_V0 ?
this.createShadowRoot() : // Shadow DOM v0
this.attachShadow({ mode: 'open' }); // Shadow DOM v1
let clone = document.importNode(template.content, true);
root.appendChild(clone);
}
}
};
// Convert a plain string of HTML into a real template element.
function createTemplateWithInnerHTML(innerHTML) {
let template = document.createElement('template');
// REVIEW: Is there an easier way to do this?
// We'd like to just set innerHTML on the template content, but since it's
// a DocumentFragment, that doesn't work.
let div = document.createElement('div');
div.innerHTML = innerHTML;
while (div.childNodes.length > 0) {
template.content.appendChild(div.childNodes[0]);
}
return template;
}
// Replace occurences of v1 slot elements with v0 content elements.
// This does not yet map named slots to content select clauses.
function polyfillSlotWithContent(template) {
[].forEach.call(template.content.querySelectorAll('slot'), slotElement => {
let contentElement = document.createElement('content');
slotElement.parentNode.replaceChild(contentElement, slotElement);
});
}
// Invoke basic style shimming with ShadowCSS.
function shimTemplateStyles(template, tag) {
window.WebComponents.ShadowCSS.shimStyling(template.content, tag);
}
|
/**
* Retrieves the devices location.
* @see extend
*
* @author Joseph Fehrman
* @since 07/09/2016
* @return Promise chain representing coordinates.
*/
function locale(options){
/**
* Private object designed to house coordinates.
*/
var Location = function(latitude, longitude , options){
this.longitude = longitude;
this.latitude = latitude;
this.options = options;
}
this.geo_options = {
enableHighAccuracy: true,
maximumAge : 30000,
timeout : 27000
};
extend(geo_options, options);
return new Promise(function(resolve, reject){
// Evaluate if the browser supports GPS location.
if(navigator.geolocation){
// Get the current location.
navigator.geolocation.getCurrentPosition(locationSuccess, locationFailed, geo_options);
}else{
// Evaluate that the browser does not support GPS location show the following error message.
reject(Error("Can not locate device's location. Browser does not support GPS locations."));
alert("Could not locate device's location.");
}
/**
* Private function for successful geolocation queries.
*/
function locationSuccess(position){
resolve(new Location(position.coords.latitude, position.coords.longitude, geo_options));
}
/**
* Private function for failed geolocation queries.
*/
function locationFailed(error){
console.error("Location error " + error.code + ": " + error.message);
alert("Could not locate device's location.")
}
});
} |
////////////////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT) //
// //
// Copyright (C) 2015 Christopher Mejía Montoya - me@chrissmejia.com - chrissmejia.com //
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy //
// of this software and associated documentation files (the "Software"), to deal //
// in the Software without restriction, including without limitation the rights //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //
// copies of the Software, and to permit persons to whom the Software is //
// furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included in all //
// copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //
// SOFTWARE. //
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
// Main Object, everything it's contained here
//------------------------------------------------------------------------------------------
var jsConfirm = {
name : 'jsConfirm',
version : '0.0.1',
cache: {}, // Don't hit the DOM at least that is strictly necessary
settings: {},
window: '', // Current window type, don't ask the DOM
target: '', // Current DOM target
resized: false, // Avoid recalcule until is strictly necessary
};
//------------------------------------------------------------------------------------------
// Setup the window
//------------------------------------------------------------------------------------------
jsConfirm.init = function (className, settings) {
"use strict";
// Checking if it's already initialized
if (className in jsConfirm.settings) {
console.error(className + " is already initialized");
return;
}
// Checking if a callback it's provided
if (typeof settings.callback !== "function") {
console.error("Callback it's not provided for " + className);
return;
}
// Run only the first time
if (!Object.keys(jsConfirm.settings).length) {
// Events
window.addEventListener("resize", jsConfirm._resize, false);
document.body.addEventListener('click', jsConfirm._click, false);
}
// Initializing element
// Storing settings
jsConfirm.settings[className] = settings;
};
//------------------------------------------------------------------------------------------
// onClick event
//------------------------------------------------------------------------------------------
jsConfirm._click = function(e) {
"use strict";
e = e || window.event;
var target = e.target || e.srcElement;
// Listen to close modal
if (jsConfirm._hasClass(target, "jsConfirmClose")) {
jsConfirm._hide();
jsConfirm._preventDefault(e);
return;
}
// Listen only a elements
if (target.nodeName !== 'A') {
return;
}
// Show window for any of the set it classNames
for (var modal in jsConfirm.settings) {
if (jsConfirm._hasClass(target, modal)) {
jsConfirm._show(target, modal);
jsConfirm._preventDefault(e);
return;
}
}
if (target.getAttribute('id') === "jsConfirmProceed") {
if (jsConfirm.settings[jsConfirm.window].url) { // Ajax request
var params = [];
var extra = jsConfirm.settings[jsConfirm.window].extra;
if (extra) {
for (var key in extra) {
if (extra.hasOwnProperty(key)) {
params.push(key + "=" + extra[key]);
}
}
}
jsConfirm._postForm(
jsConfirm.settings[jsConfirm.window].url,
params,
jsConfirm.settings[jsConfirm.window].callback,
true
);
} else {
jsConfirm.settings[jsConfirm.window].callback(jsConfirm.target);
jsConfirm._hide(); // Close modal window
}
jsConfirm._preventDefault(e);
}
};
//------------------------------------------------------------------------------------------
// Post data to API
//------------------------------------------------------------------------------------------
jsConfirm._postForm = function(url, params, callback, retry) {
"use strict";
var req = new XMLHttpRequest();
req.onerror = function() {
if (retry) {
setTimeout(function() {
jsConfirm._postForm(url, params, callback, false);
}, 1000);
}
};
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
callback(jsConfirm.target, JSON.parse(req.responseText));
jsConfirm._hide();
}
};
req.open('POST', url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
if (params) {
var data = params.join("&");
req.send(data);
} else {
req.send();
}
};
//------------------------------------------------------------------------------------------
// Don't hit the DOM at least that is strictly necessary
// Check if the value it's already calculated
//------------------------------------------------------------------------------------------
jsConfirm._get = function(name, getFn, force) {
"use strict";
if (jsConfirm.cache[name] && !force) {
return jsConfirm.cache[name];
}
jsConfirm.cache[name] = getFn;
return jsConfirm.cache[name];
};
//------------------------------------------------------------------------------------------
// Create the modal if don't exists and place in the right position
//------------------------------------------------------------------------------------------
jsConfirm._prepareModal = function() {
"use strict";
var modalWindow = document.getElementById("jsConfirm"); // DOM object
if (!document.getElementById(modalWindow)) { // Modal don't exists
jsConfirm._createModal();
modalWindow = document.getElementById("jsConfirm");
}
if (jsConfirm.resized) { // Window size change
jsConfirm._recalculate(modalWindow);
jsConfirm.resized = false;
}
jsConfirm._startPosition(modalWindow, false);
};
//------------------------------------------------------------------------------------------
// Create the modal
//------------------------------------------------------------------------------------------
jsConfirm._createModal = function() {
"use strict";
// Core
var modalWindow = document.createElement("div");
modalWindow.setAttribute("id", "jsConfirm");
// Close icon
var icon = document.createElement("a");
icon.setAttribute("class", "jsConfirmClose icon");
icon.setAttribute("href", "#");
modalWindow.appendChild(icon);
// Title
var title = document.createElement("div");
title.setAttribute("class", "title");
title.textContent = "Delete Image";
modalWindow.appendChild(title);
// Description
var description = document.createElement("div");
description.setAttribute("class", "description");
description.textContent = "Are you sure you want to delete it?";
modalWindow.appendChild(description);
// Buttons
var buttons = document.createElement("div");
buttons.setAttribute("class", "buttons");
var cancel = document.createElement("a");
cancel.setAttribute("class", "cancel jsConfirmClose");
cancel.setAttribute("href", "#");
cancel.textContent = "Cancel";
buttons.appendChild(cancel);
var proceed = document.createElement("a");
proceed.setAttribute("id", "jsConfirmProceed");
proceed.setAttribute("class", "proceed");
proceed.setAttribute("href", "#");
proceed.textContent = "Delete file";
buttons.appendChild(proceed);
modalWindow.appendChild(buttons);
// Append modal to the body
document.body.appendChild(modalWindow);
// Background
var modalWindowBackground = document.createElement("div");
modalWindowBackground.setAttribute("id", "jsConfirmBackground");
modalWindowBackground.setAttribute("class", "jsConfirmClose");
// Append background to the body
document.body.appendChild(modalWindowBackground);
};
//------------------------------------------------------------------------------------------
// Check if the modal window it's visible without hit the DOM
//------------------------------------------------------------------------------------------
jsConfirm._visible = function() {
"use strict";
if (jsConfirm.window) {
return true;
}
return false;
};
//------------------------------------------------------------------------------------------
// Cache neet to be refreshed when the windows it's resized
//------------------------------------------------------------------------------------------
jsConfirm._resize = function() {
"use strict";
if (jsConfirm._visible()) {
var modalWindow = document.getElementById("jsConfirm");
jsConfirm._recalculate(modalWindow);
jsConfirm._center(modalWindow, false);
} else {
jsConfirm.resized = true; // Avoid recalcule until is strictly necessary
}
};
//------------------------------------------------------------------------------------------
// Refresh cache size calculations
//------------------------------------------------------------------------------------------
jsConfirm._recalculate = function(d) {
"use strict";
jsConfirm._get("_windowHeight", jsConfirm._windowHeight(), true);
jsConfirm._get("_windowWidth", jsConfirm._windowWidth(), true);
jsConfirm._get("_modalWidth", jsConfirm._modalWidth(d), true);
};
//------------------------------------------------------------------------------------------
// x-browser prevent default action and cancel bubbling
//------------------------------------------------------------------------------------------
jsConfirm._preventDefault = function (e) {
"use strict";
if (typeof e.preventDefault === 'function') {
e.preventDefault();
e.stopPropagation();
} else {
e.returnValue = false;
e.cancelBubble = true;
}
};
//------------------------------------------------------------------------------------------
// Remove a class from an object using the id
//------------------------------------------------------------------------------------------
jsConfirm._removeClass = function (d, className) {
"use strict";
className = " " + className; //must keep a space before class name
d.className = d.className.replace(className,""); // first remove the class name if that already exists
};
//------------------------------------------------------------------------------------------
// Add a class from an object using the id
//------------------------------------------------------------------------------------------
jsConfirm._addClass = function (d, className) {
"use strict";
jsConfirm._removeClass(d, className); // first remove the class name if that already exists
d.className = d.className + " " + className; // adding new class name
};
//------------------------------------------------------------------------------------------
// Check if an element has a class
//------------------------------------------------------------------------------------------
jsConfirm._hasClass = function (d, className) {
"use strict";
var re = new RegExp("(?:^| )" + className + "(?:$| )", 'g');
if (d.className.match(re)) {
return true;
}
return false;
};
//------------------------------------------------------------------------------------------
// Get child element from parent by class name
//------------------------------------------------------------------------------------------
jsConfirm._getChildByClass = function (d, className) {
"use strict";
var childNodes = d.getElementsByClassName(className);
if (!childNodes.length) {
console.error("The element don't exists");
}
return childNodes[0];
};
//------------------------------------------------------------------------------------------
// Get child element from parent by more than one class name
//------------------------------------------------------------------------------------------
jsConfirm._getChildByClasses = function (d, classNames) {
"use strict";
var classArray = classNames.split(" ");
var classArrayLength = classArray.length; // Performance
// Search in order
for (var i = 0; i < classArrayLength; i++) {
d = jsConfirm._getChildByClass(d, classArray[i]);
}
return d;
};
//------------------------------------------------------------------------------------------
// Get the window width
//------------------------------------------------------------------------------------------
jsConfirm._windowWidth = function () {
"use strict";
return Math.max(document.documentElement.clientWidth, window.innerWidth || 0); // Window inner width
};
//------------------------------------------------------------------------------------------
// Get the window height
//------------------------------------------------------------------------------------------
jsConfirm._windowHeight = function () {
"use strict";
return Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // Window inner height
};
//------------------------------------------------------------------------------------------
// Get the modal width
//------------------------------------------------------------------------------------------
jsConfirm._modalWidth = function (d) {
"use strict";
return parseInt(window.getComputedStyle(d).width, 10); // modal width
};
//------------------------------------------------------------------------------------------
// Get the modal height
//------------------------------------------------------------------------------------------
jsConfirm._modalHeight = function (d) {
"use strict";
return parseInt(window.getComputedStyle(d).height, 10); // modal height
};
//------------------------------------------------------------------------------------------
// Center the modal in x axys
//------------------------------------------------------------------------------------------
jsConfirm._hCenter = function (d) {
"use strict";
var windowWidth = jsConfirm._get("_windowWidth", jsConfirm._windowWidth());
var dWidth = jsConfirm._get("_modalWidth", jsConfirm._modalWidth(d));
d.style.left = ((windowWidth - dWidth) / 2) + "px"; // Place at center
};
//------------------------------------------------------------------------------------------
// Center the modal in y axys
//------------------------------------------------------------------------------------------
jsConfirm._vCenter = function (d) {
"use strict";
var windowHeight = jsConfirm._get("_windowHeight", jsConfirm._windowHeight());
var dHeight = jsConfirm._modalHeight(d); // Not cached because change every launch depending of the description
d.style.top = ((windowHeight - dHeight) / 2) + "px"; // Place at vcenter
};
//------------------------------------------------------------------------------------------
// Center the modal in the screen
//------------------------------------------------------------------------------------------
jsConfirm._center = function (d, animate) {
"use strict";
if (!animate) {
jsConfirm._addClass(d, "notransition");
}
jsConfirm._vCenter(d);
jsConfirm._hCenter(d);
if (!animate) {
var forceReflow = d.offsetLeft + d.offsetTop; // Hack to fire DOM changes
jsConfirm._removeClass(d, "notransition");
}
};
//------------------------------------------------------------------------------------------
// Move the modal window to his start position
//------------------------------------------------------------------------------------------
jsConfirm._startPosition = function (d, animate) {
"use strict";
var modalHeight = jsConfirm._modalHeight(d); // Not cached because change every launch depending of the description
if (!animate) {
jsConfirm._addClass(d, "notransition");
}
jsConfirm._hCenter(d);
d.style.top = "-" + (modalHeight + 100) + "px"; // +100 because safari mobile has a bug
if (!animate) {
var forceReflow = d.offsetLeft + d.offsetTop; // Hack to fire DOM changes
jsConfirm._removeClass(d, "notransition");
}
};
//------------------------------------------------------------------------------------------
// Show the modal
//------------------------------------------------------------------------------------------
jsConfirm._show = function (d, className) {
"use strict";
jsConfirm._prepareModal();
var background = document.getElementById("jsConfirmBackground"); // DOM object
jsConfirm._addClass(background, "show");
var modalWindow = document.getElementById("jsConfirm"); // DOM object
// Setting title (Optional)
if (jsConfirm.settings[className].title) {
var title = jsConfirm._getChildByClass(modalWindow, "title");
title.textContent = jsConfirm.settings[className].title;
}
// Setting text (Optional)
if (jsConfirm.settings[className].text) {
var text = jsConfirm._getChildByClass(modalWindow, "description");
var customHTML = jsConfirm.settings[className].text;
var dataArray = jsConfirm.settings[className].data;
var dataArrayLength = dataArray.length - 1; // Performance
for (var i = dataArrayLength; i >= 0; i--) {
customHTML = customHTML.replace("{/" + dataArray[i] + "/}", "<span>" + d.getAttribute("data-" + dataArray[i]) + "</span>");
}
text.innerHTML = customHTML;
}
// Setting cancelText (Optional)
if (jsConfirm.settings[className].cancelText) {
var cancelText = jsConfirm._getChildByClass(modalWindow, "cancel");
cancelText.textContent = jsConfirm.settings[className].cancelText;
}
// Setting proceedText (Optional)
if (jsConfirm.settings[className].proceedText) {
var proceedText = jsConfirm._getChildByClass(modalWindow, "proceed");
proceedText.textContent = jsConfirm.settings[className].proceedText;
}
jsConfirm.window = className;
jsConfirm.target = d;
jsConfirm._vCenter(modalWindow);
};
//------------------------------------------------------------------------------------------
// Hide the modal
//------------------------------------------------------------------------------------------
jsConfirm._hide = function () {
"use strict";
var modalWindow = document.getElementById("jsConfirm"); // DOM object
jsConfirm._startPosition(modalWindow, true);
var background = document.getElementById("jsConfirmBackground"); // DOM object
jsConfirm._removeClass(background, "show");
jsConfirm.window = "";
jsConfirm.target = "";
}; |
/**
* jQuery Horizontal Navigation 1.0
* https://github.com/sebnitu/horizontalNav
*
* By Sebastian Nitu - Copyright 2012 - All rights reserved
* Author URL: http://sebnitu.com
*/
(function($) {
$.fn.horizontalNav = function(options) {
// Extend our default options with those provided.
var opts = $.extend({}, $.fn.horizontalNav.defaults, options);
return this.each(function () {
// Save our object
var $this = $(this);
// Build element specific options
// This lets me access options with this syntax: o.optionName
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
// Save the wrapper. The wrapper is the element that
// we figure out what the full width should be
if ($this.is('ul')) {
var ul_wrap = $this.parent();
} else {
var ul_wrap = $this;
}
// Grab elements we'll need and add some default styles
var ul = $this.is('ul') ? $this : ul_wrap.find('> ul'), // The unordered list element
li = ul.find('> li'), // All list items
li_last = li.last(), // Last list item
li_count = li.size(), // The number of navigation elements
li_a = li.find('> a'); // Remove padding from the links
if (o.minimumItems && o.minimumItems > li_count) {
$this.addClass("horizontalNav-notprocessed");
return false;
}
// If set to responsive, re-construct after every browser resize
if ( o.responsive === true ) {
// Only need to do this for IE7 and below
// or if we set tableDisplay to false
if ( (o.tableDisplay != true) || (navigator.userAgent.match(/msie [6]/i)) ) {
resizeTrigger( _construct, o.responsiveDelay );
}
}
if ($('.clearHorizontalNav').length ) {
ul_wrap.css({ 'zoom' : '1' });
} else {
ul_wrap.css({ 'zoom' : '1' }).append('<div class="clearHorizontalNav">');
// let's append a clearfixing element to the ul wrapper
$('.clearHorizontalNav').css({
'display' : 'block',
'overflow' : 'hidden',
'visibility' : 'hidden',
'width' : 0,
'height' : 0,
'clear' : 'both'
});
}
// Initiate the plugin
_construct();
// Returns the true inner width of an element
// Essentially it's the inner width without padding.
function trueInnerWidth(element) {
return element.innerWidth() - (
parseInt(element.css('padding-left')) + parseInt(element.css('padding-right'))
);
}
// Call funcion on browser resize
function resizeTrigger(callback, delay) {
// Delay before function is called
delay = delay || 100;
// Call function on resize
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
callback();
}, delay);
});
}
// The heavy lifting of this plugin. This is where we
// find and set the appropriate widths for list items
function _construct() {
if ( (o.tableDisplay != true) || (navigator.userAgent.match(/msie [6]/i)) ) {
// IE7 doesn't support the "display: table" method
// so we need to do it the hard way.
// Add some styles
ul.css({ 'float' : 'left' });
li.css({ 'float' : 'left', 'width' : 'auto' });
li_a.css({ 'padding-left' : 0, 'padding-right' : 0 });
// Grabbing widths and doing some math
var ul_width = trueInnerWidth(ul),
ul_width_outer = ul.outerWidth(true),
ul_width_extra = ul_width_outer - ul_width,
full_width = trueInnerWidth(ul_wrap),
extra_width = (full_width - ul_width_extra) - ul_width,
li_padding = Math.floor( extra_width / li_count );
// Cycle through the list items and give them widths
li.each(function(index) {
var li_width = trueInnerWidth( $(this) );
$(this).css({ 'width' : (li_width + li_padding) + 'px' });
});
// Get the leftover pixels after we set every itms width
var li_last_width = trueInnerWidth(li_last) + ( (full_width - ul_width_extra) - trueInnerWidth(ul) );
// I hate to do this but for some reason Firefox (v13.0) and IE are always
// one pixel off when rendering. So this is a quick fix for that.
if ($.browser.mozilla || $.browser.msie) {
li_last_width = li_last_width - 1;
}
// Add the leftovers to the last navigation item
li_last.css({ 'width' : li_last_width + 'px' });
} else {
// Every modern browser supports the "display: table" method
// so this is the best way to do it for them.
ul.css({ 'display' : 'table', 'float' : 'none', 'width' : '100%' });
li.css({ 'display' : 'table-cell', 'float' : 'none' });
}
$this.addClass("horizontalNav-processed").removeClass("horizontalNav-notprocessed");
}
}); // @end of return this.each()
};
$.fn.horizontalNav.defaults = {
responsive : true,
responsiveDelay : 100,
tableDisplay : true,
minimumItems : 0
};
})(jQuery); |
//event.js
//Handle keyboard/mouse/touch events in the Canvas
(function() {
//returns an O3D object or false otherwise.
function toO3D(n) {
return n !== true ? n : false;
}
//Returns an element position
var getPos = function(elem) {
var bbox = elem.getBoundingClientRect();
return {
x: bbox.left,
y: bbox.top,
bbox: bbox
};
};
//event object wrapper
var event = {
get: function(e, win) {
win = win || window;
return e || win.event;
},
getWheel: function(e) {
return e.wheelDelta? e.wheelDelta / 120 : -(e.detail || 0) / 3;
},
getKey: function(e) {
var code = e.which || e.keyCode;
var key = keyOf(code);
//onkeydown
var fKey = code - 111;
if (fKey > 0 && fKey < 13) key = 'f' + fKey;
key = key || String.fromCharCode(code).toLowerCase();
return {
code: code,
key: key,
shift: e.shiftKey,
control: e.ctrlKey,
alt: e.altKey,
meta: e.metaKey
};
},
isRightClick: function(e) {
return (e.which == 3 || e.button == 2);
},
getPos: function(e, win) {
// get mouse position
win = win || window;
e = e || win.event;
var doc = win.document;
doc = doc.documentElement || doc.body;
//TODO(nico): make touch event handling better
if(e.touches && e.touches.length) {
e = e.touches[0];
}
var page = {
x: e.pageX || (e.clientX + doc.scrollLeft),
y: e.pageY || (e.clientY + doc.scrollTop)
};
return page;
},
stop: function(e) {
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
};
var EventsProxy = function(app, opt) {
var domElem = app.canvas;
this.scene = app.scene;
this.domElem = domElem;
this.pos = getPos(domElem);
this.opt = this.callbacks = opt;
this.size = {
width: domElem.width || domElem.offsetWidth,
height: domElem.height || domElem.offsetHeight
};
this.attachEvents();
};
EventsProxy.prototype = {
hovered: false,
pressed: false,
touched: false,
touchMoved: false,
moved: false,
attachEvents: function() {
var domElem = this.domElem,
opt = this.opt,
that = this;
if (opt.disableContextMenu) {
domElem.oncontextmenu = function() { return false; };
}
['mouseup', 'mousedown', 'mousemove', 'mouseover', 'mouseout',
'touchstart', 'touchmove', 'touchend'].forEach(function(action) {
domElem.addEventListener(action, function(e, win) {
that[action](that.eventInfo(action, e, win));
}, false);
});
['keydown', 'keyup'].forEach(function(action) {
document.addEventListener(action, function(e, win) {
that[action](that.eventInfo(action, e, win));
}, false);
});
//"well, this is embarrassing..."
var type = '';
if (!document.getBoxObjectFor && window.mozInnerScreenX == null) {
type = 'mousewheel';
} else {
type = 'DOMMouseScroll';
}
domElem.addEventListener(type, function(e, win) {
that['mousewheel'](that.eventInfo('mousewheel', e, win));
}, false);
},
eventInfo: function(type, e, win) {
var domElem = this.domElem,
scene = this.scene,
opt = this.opt,
size = this.getSize(),
relative = opt.relative,
centerOrigin = opt.centerOrigin,
pos = opt.cachePosition && this.pos || getPos(domElem),
ge = event.get(e, win),
epos = event.getPos(e, win),
evt = {};
//get Position
var x = epos.x, y = epos.y;
if (relative) {
x -= pos.x; y-= pos.y;
if (centerOrigin) {
x -= size.width / 2;
y -= size.height / 2;
y *= -1; //y axis now points to the top of the screen
}
}
switch (type) {
case 'mousewheel':
evt.wheel = event.getWheel(ge);
break;
case 'keydown':
case 'keyup':
$.extend(evt, event.getKey(ge));
break;
case 'mouseup':
evt.isRightClick = event.isRightClick(ge);
break;
}
var cacheTarget;
$.extend(evt, {
x: x,
y: y,
cache: false,
//stop event propagation
stop: function() {
event.stop(ge);
},
//get the target element of the event
getTarget: function() {
if (cacheTarget) return cacheTarget;
return (cacheTarget = !opt.picking || scene.pick(epos.x - pos.x, epos.y - pos.y, opt.lazyPicking) || true);
}
});
//wrap native event
evt.event = ge;
return evt;
},
getSize: function() {
if (this.cacheSize) {
return this.size;
}
var domElem = this.domElem;
return {
width: domElem.width || domElem.offsetWidth,
height: domElem.height || domElem.offsetHeight
};
},
mouseup: function(e) {
if(!this.moved) {
if(e.isRightClick) {
this.callbacks.onRightClick(e, this.hovered);
} else {
this.callbacks.onClick(e, toO3D(this.pressed));
}
}
if(this.pressed) {
if(this.moved) {
this.callbacks.onDragEnd(e, toO3D(this.pressed));
} else {
this.callbacks.onDragCancel(e, toO3D(this.pressed));
}
this.pressed = this.moved = false;
}
},
mouseout: function(e) {
//mouseout canvas
var rt = e.relatedTarget,
domElem = this.domElem;
while(rt && rt.parentNode) {
if(domElem == rt.parentNode) return;
rt = rt.parentNode;
}
if(this.hovered) {
this.callbacks.onMouseLeave(e, this.hovered);
this.hovered = false;
}
if (this.pressed && this.moved) {
this.callbacks.onDragEnd(e);
this.pressed = this.moved = false;
}
},
mouseover: function(e) {},
mousemove: function(e) {
if(this.pressed) {
this.moved = true;
this.callbacks.onDragMove(e, toO3D(this.pressed));
return;
}
if(this.hovered) {
var target = toO3D(e.getTarget());
if(!target || target.hash != this.hash) {
this.callbacks.onMouseLeave(e, this.hovered);
this.hovered = target;
this.hash = target;
if(target) {
this.hash = target.hash;
this.callbacks.onMouseEnter(e, this.hovered);
}
} else {
this.callbacks.onMouseMove(e, this.hovered);
}
} else {
this.hovered = toO3D(e.getTarget());
this.hash = this.hovered;
if(this.hovered) {
this.hash = this.hovered.hash;
this.callbacks.onMouseEnter(e, this.hovered);
}
}
if (!this.opt.picking) {
this.callbacks.onMouseMove(e);
}
},
mousewheel: function(e) {
this.callbacks.onMouseWheel(e);
},
mousedown: function(e) {
this.pressed = e.getTarget();
this.callbacks.onDragStart(e, toO3D(this.pressed));
},
touchstart: function(e) {
this.touched = e.getTarget();
this.callbacks.onTouchStart(e, toO3D(this.touched));
},
touchmove: function(e) {
if(this.touched) {
this.touchMoved = true;
this.callbacks.onTouchMove(e, toO3D(this.touched));
}
},
touchend: function(e) {
if(this.touched) {
if(this.touchMoved) {
this.callbacks.onTouchEnd(e, toO3D(this.touched));
} else {
this.callbacks.onTouchCancel(e, toO3D(this.touched));
}
this.touched = this.touchMoved = false;
}
},
keydown: function(e) {
this.callbacks.onKeyDown(e);
},
keyup: function(e) {
this.callbacks.onKeyUp(e);
}
};
var Events = {};
Events.create = function(app, opt) {
opt = $.extend({
cachePosition: true,
cacheSize: true,
relative: true,
centerOrigin: true,
disableContextMenu: true,
bind: false,
picking: false,
lazyPicking: false,
onClick: $.empty,
onRightClick: $.empty,
onDragStart: $.empty,
onDragMove: $.empty,
onDragEnd: $.empty,
onDragCancel: $.empty,
onTouchStart: $.empty,
onTouchMove: $.empty,
onTouchEnd: $.empty,
onTouchCancel: $.empty,
onMouseMove: $.empty,
onMouseEnter: $.empty,
onMouseLeave: $.empty,
onMouseWheel: $.empty,
onKeyDown: $.empty,
onKeyUp: $.empty
}, opt || {});
var bind = opt.bind;
if (bind) {
for (var name in opt) {
if (name.match(/^on[a-zA-Z0-9]+$/)) {
(function (name, fn) {
opt[name] = function() {
return fn.apply(bind, Array.prototype.slice.call(arguments));
};
})(name, opt[name]);
}
}
}
new EventsProxy(app, opt);
//assign event handler to app.
app.events = opt;
};
Events.Keys = {
'enter': 13,
'up': 38,
'down': 40,
'left': 37,
'right': 39,
'esc': 27,
'space': 32,
'backspace': 8,
'tab': 9,
'delete': 46
};
function keyOf(code) {
var keyMap = Events.Keys;
for (var name in keyMap) {
if (keyMap[name] == code) {
return name;
}
}
}
PhiloGL.Events = Events;
})();
|
/*! Animatelo | The MIT License (MIT) | Copyright (c) 2017 GibboK */
; (function (animatelo) {
'use strict';
animatelo.swing = function (selector, options) {
var keyframeset = [
{
"transform": 'rotate3d(0, 0, 1, 0deg)',
"offset": "0",
"easing": "ease"
},
{
"transform": "rotate3d(0, 0, 1, 15deg)",
"offset": "0.2",
"easing": "ease"
},
{
"transform": "rotate3d(0, 0, 1, -10deg)",
"offset": "0.4",
"easing": "ease"
},
{
"transform": "rotate3d(0, 0, 1, 5deg)",
"offset": "0.6",
"easing": "ease"
},
{
"transform": "rotate3d(0, 0, 1, -5deg)",
"offset": "0.8",
"easing": "ease"
},
{
"transform": "rotate3d(0, 0, 1, 0deg)",
"offset": "1",
"easing": "ease"
}
];
return animatelo._animate(selector, keyframeset, options);
}
})(window.animatelo = window.animatelo || {}); |
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
import { addPointSnap, addLineSnap, addLineSegmentSnap } from './snap';
import * as Geometry from './geometry';
import { Map, List } from 'immutable';
import { SNAP_POINT, SNAP_LINE, SNAP_SEGMENT } from './snap';
export function sceneSnapElements(scene) {
var snapElements = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new List();
var snapMask = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Map();
var a = void 0,
b = void 0,
c = void 0;
return snapElements.withMutations(function (snapElements) {
scene.layers.forEach(function (layer) {
var lines = layer.lines,
vertices = layer.vertices;
vertices.forEach(function (_ref) {
var vertexID = _ref.id,
x = _ref.x,
y = _ref.y;
if (snapMask.get(SNAP_POINT)) {
addPointSnap(snapElements, x, y, 10, 10, vertexID);
}
if (snapMask.get(SNAP_LINE)) {
var _Geometry$horizontalL = Geometry.horizontalLine(y);
a = _Geometry$horizontalL.a;
b = _Geometry$horizontalL.b;
c = _Geometry$horizontalL.c;
addLineSnap(snapElements, a, b, c, 10, 1, vertexID);
var _Geometry$verticalLin = Geometry.verticalLine(x);
a = _Geometry$verticalLin.a;
b = _Geometry$verticalLin.b;
c = _Geometry$verticalLin.c;
addLineSnap(snapElements, a, b, c, 10, 1, vertexID);
}
});
if (snapMask.get(SNAP_SEGMENT)) {
lines.forEach(function (_ref2) {
var lineID = _ref2.id,
_ref2$vertices = _slicedToArray(_ref2.vertices, 2),
v0 = _ref2$vertices[0],
v1 = _ref2$vertices[1];
var _vertices$get = vertices.get(v0),
x1 = _vertices$get.x,
y1 = _vertices$get.y;
var _vertices$get2 = vertices.get(v1),
x2 = _vertices$get2.x,
y2 = _vertices$get2.y;
addLineSegmentSnap(snapElements, x1, y1, x2, y2, 20, 1, lineID);
});
}
});
});
} |
(function($) {
/**
* Moves elements to/from the first positions of their respective parents.
* @param {jQuery} $elements Elements (or selector) to move.
* @param {bool} condition If true, moves elements to the top. Otherwise, moves elements back to their original locations.
*/
$.prioritize = function($elements, condition) {
var key = '__prioritize';
// Expand $elements if it's not already a jQuery object.
if (typeof $elements != 'jQuery')
$elements = $($elements);
// Step through elements.
$elements.each(function() {
var $e = $(this), $p,
$parent = $e.parent();
// No parent? Bail.
if ($parent.length == 0)
return;
// Not moved? Move it.
if (!$e.data(key)) {
// Condition is false? Bail.
if (!condition)
return;
// Get placeholder (which will serve as our point of reference for when this element needs to move back).
$p = $e.prev();
// Couldn't find anything? Means this element's already at the top, so bail.
if ($p.length == 0)
return;
// Move element to top of parent.
$e.prependTo($parent);
// Mark element as moved.
$e.data(key, $p);
}
// Moved already?
else {
// Condition is true? Bail.
if (condition)
return;
$p = $e.data(key);
// Move element back to its original location (using our placeholder).
$e.insertAfter($p);
// Unmark element as moved.
$e.removeData(key);
}
});
};
})(jQuery);
|
angular.module('directives.crud.edit', [])
// Apply this directive to an element at or below a form that will manage CRUD operations on a resource.
// - The resource must expose the following instance methods: $saveOrUpdate(), $id() and $remove()
.directive('crudEdit', ['$parse', function($parse) {
return {
// We ask this directive to create a new child scope so that when we add helper methods to the scope
// it doesn't make a mess of the parent scope.
// - Be aware that if you write to the scope from within the form then you must remember that there is a child scope at the point
scope: true,
// We need access to a form so we require a FormController from this element or a parent element
require: '^form',
// This directive can only appear as an attribute
link: function(scope, element, attrs, form) {
// We extract the value of the crudEdit attribute
// - it should be an assignable expression evaluating to the model (resource) that is going to be edited
var resourceGetter = $parse(attrs.crudEdit);
var resourceSetter = resourceGetter.assign;
// Store the resource object for easy access
var resource = resourceGetter(scope);
// Store a copy for reverting the changes
var original = angular.copy(resource);
var checkResourceMethod = function(methodName) {
if ( !angular.isFunction(resource[methodName]) ) {
throw new Error('crudEdit directive: The resource must expose the ' + methodName + '() instance method');
}
};
checkResourceMethod('$saveOrUpdate');
checkResourceMethod('$id');
checkResourceMethod('$remove');
// This function helps us extract the callback functions from the directive attributes
var makeFn = function(attrName) {
var fn = scope.$eval(attrs[attrName]);
if ( !angular.isFunction(fn) ) {
throw new Error('crudEdit directive: The attribute "' + attrName + '" must evaluate to a function');
}
return fn;
};
// Set up callbacks with fallback
// onSave attribute -> onSave scope -> noop
var userOnSave = attrs.onSave ? makeFn('onSave') : ( scope.onSave || angular.noop );
var onSave = function(result, status, headers, config) {
// Reset the original to help with reverting and pristine checks
original = result;
userOnSave(result, status, headers, config);
};
// onRemove attribute -> onRemove scope -> onSave attribute -> onSave scope -> noop
var onRemove = attrs.onRemove ? makeFn('onRemove') : ( scope.onRemove || onSave );
// onError attribute -> onError scope -> noop
var onError = attrs.onError ? makeFn('onError') : ( scope.onError || angular.noop );
// The following functions should be triggered by elements on the form
// - e.g. ng-click="save()"
scope.save = function() {
resource.$saveOrUpdate(onSave, onSave, onError, onError);
};
scope.revertChanges = function() {
resource = angular.copy(original);
resourceSetter(scope, resource);
form.$setPristine();
};
scope.remove = function() {
if(resource.$id()) {
resource.$remove(onRemove, onError);
} else {
onRemove();
}
};
// The following functions can be called to modify the behaviour of elements in the form
// - e.g. ng-disable="!canSave()"
scope.canSave = function() {
return form.$valid && !angular.equals(resource, original);
};
scope.canRevert = function() {
return !angular.equals(resource, original);
};
scope.canRemove = function() {
return resource.$id();
};
/**
* Get the CSS classes for this item, to be used by the ng-class directive
* @param {string} fieldName The name of the field on the form, for which we want to get the CSS classes
* @return {object} A hash where each key is a CSS class and the corresponding value is true if the class is to be applied.
*/
scope.getCssClasses = function(fieldName) {
var ngModelContoller = form[fieldName];
return {
error: ngModelContoller.$invalid && !angular.equals(resource, original),
success: ngModelContoller.$valid && !angular.equals(resource, original)
};
};
/**
* Whether to show an error message for the specified error
* @param {string} fieldName The name of the field on the form, of which we want to know whether to show the error
* @param {string} error - The name of the error as given by a validation directive
* @return {Boolean} true if the error should be shown
*/
scope.showError = function(fieldName, error) {
return form[fieldName].$error[error];
};
}
};
}]); |
var mach = require("mach");
var Ambidex = require("../../Ambidex.server.js");
var utilities = require("../utilities.js");
function TardisGallery(
{
ambidexPromises,
settings
}
) {
var customSettings = settings;
settings = utilities.recursiveCloneWithDefaults(
customSettings,
require("./settings.default.js")
);
// Introspect URLS from ambidexes, if they aren't already set
if (settings.URLS) {
settings.APPEND_PATH_TO_URLS = customSettings.APPEND_PATH_TO_URLS || false;
if (ambidexPromises) {
var { HOST, PORT } = ambidexPromises[0].ambidexInProgress._get("settings");
settings.URLS = settings.URLS.map(
URL => URL.startsWith("/") && !URL.startsWith("//")
? `//${ HOST }:${ PORT }${ URL }`
: URL
);
}
} else {
settings.URLS = ambidexPromises.map(
promise => {
var { HOST, PORT } = promise.ambidexInProgress._get("settings");
return `//${ HOST }:${ PORT }`
}
);
}
var self = new Ambidex({ settings });
self.mapper = mach.mapper();
ambidexPromises = ambidexPromises.concat(self);
ambidexPromises.forEach(
promise => promise.ambidexInProgress._isBeingServedExternally = true
);
// Make sure the Ambidexes are dormant, then serve them by HOST with mapper
return Promise.all(
ambidexPromises
).then(
ambidexes => Promise.all(
ambidexes.map(
ambidex => {
if (ambidex.stack.nodeServer && ambidex.stack.nodeServer.address()) {
return new Promise(
(resolve, reject) => {
ambidex.stack.nodeServer.close(
() => resolve(ambidex)
);
}
);
} else {
return ambidex;
}
}
)
)
).then(
ambidexes => {
ambidexes.forEach(
ambidex => {
var { HOST, BASE_URL } = ambidex._get("settings");
if (!BASE_URL)
BASE_URL = "/"
if (!BASE_URL.startsWith("/"))
BASE_URL = "/" + BASE_URL
if (!BASE_URL.endsWith("/"))
BASE_URL = BASE_URL + "/"
self.mapper.map(
ambidex === self.ambidexInProgress
? "/"
: `http://${ HOST }${ BASE_URL }`,
ambidex.stack
);
}
);
return ambidexes;
}
).then(
ambidexes => {
ambidexes.forEach(
ambidex => console.info(`Starting mach for ${ ambidex._get("settings").NAME } on ${ settings.HOST }:${ settings.PORT }…`)
);
self.mapper.nodeServer = mach.serve(
self.mapper,
settings.VM_PORT || settings.PORT
);
return self;
}
).catch(
error => console.error(error.stack)
);
}
module.exports = TardisGallery;
|
'use strict';
// Setting up route
angular.module('users').config(['$stateProvider',
function($stateProvider) {
// Users state routing
$stateProvider.
state('app.profile', {
url: '/settings/profile',
templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
}).
state('app.password', {
url: '/settings/password',
templateUrl: 'modules/users/views/settings/change-password.client.view.html'
}).
state('app.accounts', {
url: '/settings/accounts',
templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
}).
state('app.signup', {
url: '/signup',
templateUrl: 'modules/users/views/authentication/signup.client.view.html'
}).
state('app.signin', {
url: '/signin',
templateUrl: 'modules/users/views/authentication/signin.client.view.html'
}).
state('app.forgot', {
url: '/password/forgot',
templateUrl: 'modules/users/views/password/forgot-password.client.view.html'
}).
state('app.reset-invalid', {
url: '/password/reset/invalid',
templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html'
}).
state('app.reset-success', {
url: '/password/reset/success',
templateUrl: 'modules/users/views/password/reset-password-success.client.view.html'
}).
state('app.reset', {
url: '/password/reset/:token',
templateUrl: 'modules/users/views/password/reset-password.client.view.html'
});
}
]); |
angular.module('common')
.factory('UserDataProvider',
[
'$http',
'$q',
function
($http, $q) {
var getTablet = function(userId) {
var defered = $q.defer();
var tabletPromise = defered.promise;
$http({
method: "GET",
url: "/records?userId=" + userId + "&logout_at&populate=tabletId"
}).success(function(theTablet){
defered.resolve(theTablet);
}).error(function(err){
console.error(err);
defered.reject(err);
});
return tabletPromise;
};
var getTabletHistory = function(studentId) {
var defered = $q.defer();
var tabletPromise = defered.promise;
$http({
method: "GET",
url: "/records?userId=" + studentId + "&populate=tabletId"
}).success(function(theTablet){
defered.resolve(theTablet);
}).error(function(err){
console.error(err);
defered.reject(err);
});
return tabletPromise;
};
var getUser = function(tabletId, callBack){
var defered = $q.defer();
var userPromise = defered.promise;
$http({
method: "GET",
url: "/records?tabletId=" + tabletId + "&logout_at&populate=userId"
}).success(function(theUser){
if(callBack){
callBack(theUser);
}
defered.resolve(theUser);
}).error(function(err){
console.error(err);
});
return userPromise;
};
var login = function (password, callBack) {
$http({
method: 'POST',
url: '/login',
data: {
username: me.username,
password: password
}
}).success(function () {
callBack(true);
}).error(function (err) {
callBack(false, err);
});
};
var getStudentsId = function(length, class_number) {
var results = [];
var id = '';
for(var i=1; i<=length; i++) {
if(i<10) {
id = class_number+'0'+i;
}else{
id = class_number+i;
}
results.push(id);
}
return results;
};
var generateStudentInstance = function(ids, names) {
var results = [];
if(names) {
_.each(names, function(user_name, index) {
var user = {};
user.username = ids[index];
user.password = user.usernames;
user.roles = ['student'];
user.name = user_name;
user.have_profile = false;
results.push(user);
});
return results;
}else if(ids) {
_.each(ids, function(userId) {
var user = {};
user.username = userId;
user.password = user.username;
user.roles = ['student'];
user.have_profile = false;
results.push(user);
});
return results;
}
};
var sendPostJoinUsers = function(users, classNum) {
return $http.post('/join/students', {users: users, classNum: classNum});
};
var autoCreateStudents = function(users_count, class_number) {
var usernames = getStudentsId(users_count, class_number);
var users = generateStudentInstance(usernames);
return sendPostJoinUsers(users, class_number);
};
var manualCreateStudents = function(names, class_number) {
var usernames = getStudentsId(names.length, class_number);
var users = generateStudentInstance(usernames, names);
return sendPostJoinUsers(users, class_number);
};
var manualCreateSingleStudent = function(users, classNum) {
return sendPostJoinUsers(users, classNum);
};
var editStudentName = function(student) {
return $http.put('/users/'+student._id, {name: student.name});
};
var resetStudentPassword = function(student) {
return $http.put('/users/'+student._id, {password: student.username});
};
return {
login: login,
getTablet: getTablet,
getTabletHistory: getTabletHistory,
getUser: getUser,
autoCreateStudents: autoCreateStudents,
manualCreateStudents: manualCreateStudents,
manualCreateSingleStudent: manualCreateSingleStudent,
editStudentName: editStudentName,
resetStudentPassword: resetStudentPassword
};
}]);
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.encodeVersion = encodeVersion;
exports.encodeHeader = encodeHeader;
exports.encodeU32 = encodeU32;
exports.encodeVec = encodeVec;
exports.encodeValtype = encodeValtype;
exports.encodeMutability = encodeMutability;
exports.encodeUTF8Vec = encodeUTF8Vec;
exports.encodeLimits = encodeLimits;
exports.encodeModuleImport = encodeModuleImport;
exports.encodeSectionMetadata = encodeSectionMetadata;
exports.encodeCallInstruction = encodeCallInstruction;
exports.encodeCallIndirectInstruction = encodeCallIndirectInstruction;
exports.encodeModuleExport = encodeModuleExport;
exports.encodeTypeInstruction = encodeTypeInstruction;
exports.encodeInstr = encodeInstr;
exports.encodeGlobal = encodeGlobal;
exports.encodeFuncBody = encodeFuncBody;
exports.encodeIndexInFuncSection = encodeIndexInFuncSection;
var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));
var leb = _interopRequireWildcard(require("@webassemblyjs/leb128"));
var _index = require("../index");
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function assertNotIdentifierNode(n) {
if (n.type === "Identifier") {
throw new Error("Unsupported node Identifier");
}
}
function encodeVersion(v) {
var bytes = _helperWasmBytecode.default.moduleVersion;
bytes[0] = v;
return bytes;
}
function encodeHeader() {
return _helperWasmBytecode.default.magicModuleHeader;
}
function encodeU32(v) {
var uint8view = new Uint8Array(leb.encodeU32(v));
var array = _toConsumableArray(uint8view);
return array;
}
function encodeVec(elements) {
var size = elements.length;
return [size].concat(_toConsumableArray(elements));
}
function encodeValtype(v) {
var byte = _helperWasmBytecode.default.valtypesByString[v];
if (typeof byte === "undefined") {
throw new Error("Unknown valtype: " + v);
}
return parseInt(byte, 10);
}
function encodeMutability(v) {
var byte = _helperWasmBytecode.default.globalTypesByString[v];
if (typeof byte === "undefined") {
throw new Error("Unknown mutability: " + v);
}
return parseInt(byte, 10);
}
function encodeUTF8Vec(str) {
var charCodes = str.split("").map(function (x) {
return x.charCodeAt(0);
});
return encodeVec(charCodes);
}
function encodeLimits(n) {
var out = [];
if (typeof n.max === "number") {
out.push(0x01);
out.push.apply(out, _toConsumableArray(encodeU32(n.min))); // $FlowIgnore: ensured by the typeof
out.push.apply(out, _toConsumableArray(encodeU32(n.max)));
} else {
out.push(0x00);
out.push.apply(out, _toConsumableArray(encodeU32(n.min)));
}
return out;
}
function encodeModuleImport(n) {
var out = [];
out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.module)));
out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));
switch (n.descr.type) {
case "GlobalType":
{
out.push(0x03); // $FlowIgnore: GlobalType ensure that these props exists
out.push(encodeValtype(n.descr.valtype)); // $FlowIgnore: GlobalType ensure that these props exists
out.push(encodeMutability(n.descr.mutability));
break;
}
case "Memory":
{
out.push(0x02); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
break;
}
case "Table":
{
out.push(0x01);
out.push(0x70); // element type
// $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeLimits(n.descr.limits)));
break;
}
case "FuncImportDescr":
{
out.push(0x00); // $FlowIgnore
assertNotIdentifierNode(n.descr.id); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
break;
}
default:
throw new Error("Unsupport operation: encode module import of type: " + n.descr.type);
}
return out;
}
function encodeSectionMetadata(n) {
var out = [];
var sectionId = _helperWasmBytecode.default.sections[n.section];
if (typeof sectionId === "undefined") {
throw new Error("Unknown section: " + n.section);
}
if (n.section === "start") {
/**
* This is not implemented yet because it's a special case which
* doesn't have a vector in its section.
*/
throw new Error("Unsupported section encoding of type start");
}
out.push(sectionId);
out.push.apply(out, _toConsumableArray(encodeU32(n.size.value)));
out.push.apply(out, _toConsumableArray(encodeU32(n.vectorOfSize.value)));
return out;
}
function encodeCallInstruction(n) {
var out = [];
assertNotIdentifierNode(n.index);
out.push(0x10); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.index.value)));
return out;
}
function encodeCallIndirectInstruction(n) {
var out = []; // $FlowIgnore
assertNotIdentifierNode(n.index);
out.push(0x11); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.index.value))); // add a reserved byte
out.push(0x00);
return out;
}
function encodeModuleExport(n) {
var out = [];
assertNotIdentifierNode(n.descr.id);
var exportTypeByteString = _helperWasmBytecode.default.exportTypesByName[n.descr.exportType];
if (typeof exportTypeByteString === "undefined") {
throw new Error("Unknown export of type: " + n.descr.exportType);
}
var exportTypeByte = parseInt(exportTypeByteString, 10);
out.push.apply(out, _toConsumableArray(encodeUTF8Vec(n.name)));
out.push(exportTypeByte); // $FlowIgnore
out.push.apply(out, _toConsumableArray(encodeU32(n.descr.id.value)));
return out;
}
function encodeTypeInstruction(n) {
var out = [0x60];
var params = n.functype.params.map(function (x) {
return x.valtype;
}).map(encodeValtype);
var results = n.functype.results.map(encodeValtype);
out.push.apply(out, _toConsumableArray(encodeVec(params)));
out.push.apply(out, _toConsumableArray(encodeVec(results)));
return out;
}
function encodeInstr(n) {
var out = [];
var instructionName = n.id;
if (typeof n.object === "string") {
instructionName = "".concat(n.object, ".").concat(String(n.id));
}
var byteString = _helperWasmBytecode.default.symbolsByName[instructionName];
if (typeof byteString === "undefined") {
throw new Error("encodeInstr: unknown instruction " + JSON.stringify(instructionName));
}
var byte = parseInt(byteString, 10);
out.push(byte);
if (n.args) {
n.args.forEach(function (arg) {
if (arg.type === "NumberLiteral") {
out.push.apply(out, _toConsumableArray(encodeU32(arg.value)));
} else {
throw new Error("Unsupported instruction argument encoding " + JSON.stringify(arg.type));
}
});
}
return out;
}
function encodeExpr(instrs) {
var out = [];
instrs.forEach(function (instr) {
// $FlowIgnore
var n = (0, _index.encodeNode)(instr);
out.push.apply(out, _toConsumableArray(n));
});
out.push(0x0b); // end
return out;
}
function encodeGlobal(n) {
var out = [];
var _n$globalType = n.globalType,
valtype = _n$globalType.valtype,
mutability = _n$globalType.mutability;
out.push(encodeValtype(valtype));
out.push(encodeMutability(mutability));
out.push.apply(out, _toConsumableArray(encodeExpr(n.init)));
return out;
}
function encodeFuncBody(n) {
var out = [];
out.push(-1); // temporary function body size
// FIXME(sven): get the func locals?
var localBytes = encodeVec([]);
out.push.apply(out, _toConsumableArray(localBytes));
var funcBodyBytes = encodeExpr(n.body);
out[0] = funcBodyBytes.length + localBytes.length;
out.push.apply(out, _toConsumableArray(funcBodyBytes));
return out;
}
function encodeIndexInFuncSection(n) {
assertNotIdentifierNode(n.index); // $FlowIgnore
return encodeU32(n.index.value);
} |
/* @flow */
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { graphql, compose } from 'react-apollo';
import styled from 'styled-components';
// internal
import Button from '@boldr/ui/Button';
import Heading from '@boldr/ui/Heading';
import { Control, FormField, Form, TextFormField } from '@boldr/ui/Form';
import { formatReduxFormErrors } from '../../../../../core/reduxFormErrors';
import ADD_TAG_MUTATION from '../../gql/addTag.mutation.graphql';
import TAGS_QUERY from '../../gql/tags.graphql';
export type Props = {
addTagMutation: Function,
handleSubmit: Function,
reset?: Function,
submitting?: boolean,
pristine?: boolean,
};
const style = {
margin: 12,
};
const TagFormPanel = styled.div`
padding: 2em;
margin: 0 auto;
`;
class AddTag extends React.Component<Props, *> {
addTagMutation = values => {
const { addTagMutation } = this.props;
return addTagMutation(values).catch(formatReduxFormErrors);
};
props: Props;
render() {
// eslint-disable-line
const { handleSubmit, reset, submitting, pristine } = this.props;
return (
<TagFormPanel>
<Heading type="h3" text="Add a New Tag" />
<Form className="boldr-form__addtag" onSubmit={handleSubmit(this.addTagMutation)}>
<Field id="tag-name" name="name" component={TextFormField} type="text" label="Name" />
<FormField isGrouped>
<Control>
<Button htmlType="submit" kind="primary" style={style} disabled={submitting}>
Save
</Button>
</Control>
<Control>
<Button
onClick={reset}
style={style}
kind="primary"
disabled={submitting || pristine}
outline>
Reset
</Button>
</Control>
</FormField>
</Form>
</TagFormPanel>
);
}
}
export default compose(
// $FlowIssue
graphql(ADD_TAG_MUTATION, {
props: ({ mutate }) => ({
addTagMutation: values =>
mutate({
variables: { input: values },
// $FlowIssue
refetchQueries: [
{
query: TAGS_QUERY,
variables: {
offset: 0,
limit: 20,
},
},
],
}),
}),
}),
reduxForm({
form: 'addTagForm',
}),
)(AddTag);
|
var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var test = require('tap').test
var npm = require('../../')
var common = require('../common-tap.js')
var pkg = common.pkg
var cache = common.cache
test('npm version <semver> updates shrinkwrap - no git', function (t) {
setup()
npm.load({ cache: cache, registry: common.registry }, function () {
npm.commands.version(['patch'], function (err) {
if (err) return t.fail('Error perform version patch')
var shrinkwrap = require(path.resolve(pkg, 'npm-shrinkwrap.json'))
t.equal(shrinkwrap.version, '0.0.1', 'got expected version')
t.end()
})
})
})
test('npm version <semver> updates git works with no shrinkwrap', function (t) {
setup()
rimraf.sync(path.resolve(pkg, 'npm-shrinkwrap.json'))
npm.config.set('sign-git-commit', false)
npm.config.set('sign-git-tag', false)
common.makeGitRepo({
path: pkg,
added: ['package.json']
}, version)
function version (er, stdout, stderr) {
t.ifError(er, 'git repo initialized without issue')
t.notOk(stderr, 'no error output')
npm.commands.version(['patch'], checkCommit)
}
function checkCommit (er) {
t.ifError(er, 'version command ran without error')
var shrinkwrap = require(path.resolve(pkg, 'npm-shrinkwrap.json'))
t.equal(shrinkwrap.version, '0.0.1', 'got expected version')
var opts = { cwd: pkg, env: { PATH: process.env.PATH } }
var git = require('../../lib/utils/git.js')
git.whichAndExec(
['show', 'HEAD', '--name-only'],
opts,
function (er, stdout, stderr) {
t.ifError(er, 'git show ran without issues')
t.notOk(stderr, 'no error output')
var lines = stdout.split('\n')
t.notEqual(lines.indexOf('package.json'), -1, 'package.json commited')
t.equal(lines.indexOf('npm-shrinkwrap.json'), -1, 'npm-shrinkwrap.json not present')
t.end()
}
)
}
})
test('npm version <semver> updates shrinkwrap and updates git', function (t) {
setup()
npm.config.set('sign-git-commit', false)
npm.config.set('sign-git-tag', false)
common.makeGitRepo({
path: pkg,
added: ['package.json', 'npm-shrinkwrap.json']
}, version)
function version (er, stdout, stderr) {
t.ifError(er, 'git repo initialized without issue')
t.notOk(stderr, 'no error output')
npm.commands.version(['patch'], checkCommit)
}
function checkCommit (er) {
t.ifError(er, 'version command ran without error')
var shrinkwrap = require(path.resolve(pkg, 'npm-shrinkwrap.json'))
t.equal(shrinkwrap.version, '0.0.1', 'got expected version')
var git = require('../../lib/utils/git.js')
var opts = { cwd: pkg, env: { PATH: process.env.PATH } }
git.whichAndExec(
['show', 'HEAD', '--name-only'],
opts,
function (er, stdout, stderr) {
t.ifError(er, 'git show ran without issues')
t.notOk(stderr, 'no error output')
var lines = stdout.split('\n')
t.notEqual(lines.indexOf('package.json'), -1, 'package.json commited')
t.notEqual(lines.indexOf('npm-shrinkwrap.json'), -1, 'npm-shrinkwrap.json commited')
t.end()
}
)
}
})
function setup () {
process.chdir(__dirname)
rimraf.sync(pkg)
mkdirp.sync(pkg)
var contents = {
author: 'Nathan Bowser && Faiq Raza',
name: 'version-with-shrinkwrap-test',
version: '0.0.0',
description: 'Test for version with shrinkwrap update'
}
fs.writeFileSync(path.resolve(pkg, 'package.json'), JSON.stringify(contents), 'utf8')
fs.writeFileSync(path.resolve(pkg, 'npm-shrinkwrap.json'), JSON.stringify(contents), 'utf8')
process.chdir(pkg)
}
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
// ES6 String API extensions tests -- verifies the API shape and basic functionality
WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
function verifyThrowsIfRegExpSearchString(functionName) {
var f = String.prototype[functionName].bind("abc");
var re = /./;
assert.throws(f.bind(undefined, re), TypeError, "Regular RegExp");
helpers.withPropertyDeleted(RegExp.prototype, Symbol.match, function () {
assert.throws(f.bind(undefined, re), TypeError, "Regular RegExp without Symbol.match property");
})
re = 1;
assert.doesNotThrow(f.bind(undefined, re), "Not an Object (Number)");
re = {};
assert.doesNotThrow(f.bind(undefined, re), "Object without Symbol.match property");
re = {
[Symbol.match]: true
};
assert.throws(f.bind(undefined, re), TypeError, "Object with Boolean Symbol.match property");
re = {
[Symbol.match]: 'coerced to true'
};
assert.throws(f.bind(undefined, re), TypeError, "Object with Symbol.match property coerced to 'true'");
re = {
[Symbol.match]: null
};
assert.doesNotThrow(f.bind(undefined, re), "Object with Symbol.match property coerced to 'false'");
}
var tests = [
{
name: "Array prototype and String prototype should have spec defined built-ins with correct lengths",
body: function () {
assert.isTrue(Array.prototype.hasOwnProperty('find'), "Array.prototype should have a find method");
assert.isTrue(Array.prototype.hasOwnProperty('findIndex'), "Array.prototype should have a findIndex method");
assert.isTrue(String.prototype.hasOwnProperty('repeat'), "String.prototype should have a repeat method");
assert.isTrue(String.prototype.hasOwnProperty('startsWith'), "String.prototype should have a startsWith method");
assert.isTrue(String.prototype.hasOwnProperty('endsWith'), "String.prototype should have a endsWith method");
assert.isTrue(String.prototype.hasOwnProperty('includes'), "String.prototype should have a includes method");
assert.isTrue(Array.prototype.find.length === 1, "find method takes two arguments but the second is optional and the spec says the length must be 1");
assert.isTrue(Array.prototype.findIndex.length === 1, "findIndex method takes two arguments but the second is optional and the spec says the length must be 1");
assert.isTrue(String.prototype.repeat.length === 1, "repeat method takes zero arguments");
assert.isTrue(String.prototype.startsWith.length === 1, "startsWith method takes two arguments but the second is optional and the spec says the length must be 1");
assert.isTrue(String.prototype.endsWith.length === 1, "endsWith method takes two arguments but the second is optional and the spec says the length must be 1");
assert.isTrue(String.prototype.includes.length === 1, "includes method takes two arguments but the second is optional and the spec says the length must be 1");
}
},
{
name: "find takes a predicate and applies it to each element in the array in ascending order until the predicate returns true, then find returns that element",
body: function () {
assert.throws(function () { Array.prototype.find.call(); }, TypeError, "find throws TypeError if it is given no arguments", "Array.prototype.find: 'this' is null or undefined");
assert.throws(function () { Array.prototype.find.call(undefined); }, TypeError, "find throws TypeError if its this argument is undefined", "Array.prototype.find: 'this' is null or undefined");
assert.throws(function () { Array.prototype.find.call(undefined, function () { return true; }, {}); }, TypeError, "find throws TypeError if its this argument is undefined even if given further arguments", "Array.prototype.find: 'this' is null or undefined");
assert.throws(function () { Array.prototype.find.call(null); }, TypeError, "find throws TypeError if its this argument is null", "Array.prototype.find: 'this' is null or undefined");
assert.throws(function () { Array.prototype.find.call(null, function () { return true; }, {}); }, TypeError, "find throws TypeError if its this argument is null even if given further arguments", "Array.prototype.find: 'this' is null or undefined");
var arr = [ 1, 2, 3 ];
// Test missing/invalid predicate argument
assert.throws(function () { arr.find(); }, TypeError, "find throws TypeError if it is given no predicate argument", "Array.prototype.find: argument is not a Function object");
assert.throws(function () { arr.find({}); }, TypeError, "find throws TypeError if it is given a non-Function object predicate argument", "Array.prototype.find: argument is not a Function object");
var fakeArrWithLengthGetter = {
__proto__: Array.prototype,
get length () { throw new Error('getter called'); }
};
assert.throws(function () { fakeArrWithLengthGetter.find(); }, Error, "find gets length property, calling getter method, before checking for a valid predicate function argument", "getter called");
// Test simple predicates matching each element
assert.areEqual( 1, arr.find(function (v, i, a) { return true; }), "Simple predicate always returns true, should find first item");
assert.areEqual( 1, arr.find(function (v, i, a) { if (i >= 1) { assert.fail("shouldn't visit index > 0"); } return v === 1; }), "Simple predicate matching first element, should find first element");
assert.areEqual( 2, arr.find(function (v, i, a) { if (i >= 2) { assert.fail("shouldn't visit index > 1"); } return v === 2; }), "Simple predicate matching second element, should find second element");
assert.areEqual( 3, arr.find(function (v, i, a) { if (i >= 3) { assert.fail("shouldn't visit index > 2"); } return v === 3; }), "Simple predicate matching third element, should find third element");
assert.areEqual(undefined, arr.find(function (v, i, a) { if (i >= 3) { assert.fail("shouldn't visit index > 2"); } return v === 4; }), "Simple predicate matching non-existent element, should not find any element");
assert.areEqual( 2, arr.find(function (v, i, a) { if (i >= 2) { assert.fail("shouldn't visit index > 1"); } return v === 2 || v === 3; }), "Simple predicate matching two elements, second and third, should find first of them, i.e. the second element");
// Test adding elements in predicate function
assert.areEqual(undefined, arr.find(function (v, i, a) { if (i >= 3) { assert.fail("shouldn't visit index > 2 (initial array length"); } a.push(v + 3); return false; }), "Elements added after find has started shouldn't be included in the search");
assert.areEqual([ 1, 2, 3, 4, 5, 6 ], arr, "Three more elements should be added to end of arr");
// Test deleting elements in predicate function that have not been visited
function f(v, i, a) {
if (i % 2 === 1) {
assert.areEqual(undefined, v, "odd indices should be undefined since they were deleted");
} else {
delete a[i+1];
}
return false;
};
assert.areEqual(undefined, arr.find(f), "Elements deleted before being visited after find has started shouldn't be included in the search");
assert.areEqual( 1, arr[0], "Odd elements should be deleted [0]");
assert.areEqual(undefined, arr[1], "Odd elements should be deleted [1]");
assert.areEqual( 3, arr[2], "Odd elements should be deleted [2]");
assert.areEqual(undefined, arr[3], "Odd elements should be deleted [3]");
assert.areEqual( 5, arr[4], "Odd elements should be deleted [4]");
assert.areEqual(undefined, arr[5], "Odd elements should be deleted [5]");
// Test deleting elements in predicate function that have already been visited
assert.areEqual(undefined, arr.find(function (v, i, a) { delete a[i]; return false; }), "Elements deleted after being visited has no effect on the search");
assert.areEqual(undefined, arr[0], "All elements should be deleted [0]");
assert.areEqual(undefined, arr[1], "All elements should be deleted [1]");
assert.areEqual(undefined, arr[2], "All elements should be deleted [2]");
assert.areEqual(undefined, arr[3], "All elements should be deleted [3]");
assert.areEqual(undefined, arr[4], "All elements should be deleted [4]");
assert.areEqual(undefined, arr[5], "All elements should be deleted [5]");
assert.areEqual(6, arr.length, "arr length is still 6");
// Test thisArg argument
var thisArg = { };
assert.areEqual(undefined, arr.find(function (v, i, a) { if (this !== thisArg) { assert.fail("this is not what was passed to second parameter of find()"); } return false; }, thisArg), "Argument passed as the optional second parameter of find should become the this value in the predicate");
// Test and ensure Array.prototype.find calls ToLength
// checks lower bound (negative -> zero)
// upper bound ( pow(2,53)-1 ) cannot be tested in reasonable time
var arr = { '0': 1, '1': 2, '2': 3, length: -1 };
assert.areEqual(undefined, Array.prototype.find.call(arr, function (v, i, a) {assert.fail("shouldn't visit any element when length is less than zero"); return true;}), "find should use ToLength function that clamps length between 0 and pow(2,53)-1");
}
},
{
name: "findIndex takes a predicate and applies it to each element in the array in ascending order until the predicate returns true, then findIndex returns the index of that element",
body: function () {
assert.throws(function () { Array.prototype.findIndex.call(); }, TypeError, "findIndex throws TypeError if it is given no arguments", "Array.prototype.findIndex: 'this' is null or undefined");
assert.throws(function () { Array.prototype.findIndex.call(undefined); }, TypeError, "findIndex throws TypeError if its this argument is undefined", "Array.prototype.findIndex: 'this' is null or undefined");
assert.throws(function () { Array.prototype.findIndex.call(undefined, function () { return true; }, {}); }, TypeError, "findIndex throws TypeError if its this argument is undefined even if given further arguments", "Array.prototype.findIndex: 'this' is null or undefined");
assert.throws(function () { Array.prototype.findIndex.call(null); }, TypeError, "findIndex throws TypeError if its this argument is null", "Array.prototype.findIndex: 'this' is null or undefined");
assert.throws(function () { Array.prototype.findIndex.call(null, function () { return true; }, {}); }, TypeError, "findIndex throws TypeError if its this argument is null even if given further arguments", "Array.prototype.findIndex: 'this' is null or undefined");
var arr = [ 1, 2, 3 ];
// Test missing/invalid predicate argument
assert.throws(function () { arr.findIndex(); }, TypeError, "findIndex throws TypeError if it is given no predicate argument", "Array.prototype.findIndex: argument is not a Function object");
assert.throws(function () { arr.findIndex({}); }, TypeError, "findIndex throws TypeError if it is given a non-Function object predicate argument", "Array.prototype.findIndex: argument is not a Function object");
var fakeArrWithLengthGetter = {
__proto__: Array.prototype,
get length () { throw new Error('getter called'); }
};
assert.throws(function () { fakeArrWithLengthGetter.findIndex(); }, Error, "findIndex gets length property, calling getter method, before checking for a valid predicate function argument", "getter called");
// Test simple predicates matching each element
assert.areEqual( 0, arr.findIndex(function (v, i, a) { return true; }), "Simple predicate always returns true, should find first item");
assert.areEqual( 0, arr.findIndex(function (v, i, a) { if (i >= 1) { assert.fail("shouldn't visit index > 0"); } return v === 1; }), "Simple predicate matching first element, should find first element");
assert.areEqual( 1, arr.findIndex(function (v, i, a) { if (i >= 2) { assert.fail("shouldn't visit index > 1"); } return v === 2; }), "Simple predicate matching second element, should find second element");
assert.areEqual( 2, arr.findIndex(function (v, i, a) { if (i >= 3) { assert.fail("shouldn't visit index > 2"); } return v === 3; }), "Simple predicate matching third element, should find third element");
assert.areEqual(-1, arr.findIndex(function (v, i, a) { if (i >= 3) { assert.fail("shouldn't visit index > 2"); } return v === 4; }), "Simple predicate matching non-existent element, should not find any element");
assert.areEqual( 1, arr.findIndex(function (v, i, a) { if (i >= 2) { assert.fail("shouldn't visit index > 1"); } return v === 2 || v === 3; }), "Simple predicate matching two elements, second and third, should find first of them, i.e. the second element");
// Test adding elements in predicate function
assert.areEqual(-1, arr.findIndex(function (v, i, a) { if (i >= 3) { assert.fail("shouldn't visit index > 2 (initial array length"); } a.push(v + 3); return false; }), "Elements added after findIndex has started shouldn't be included in the search");
assert.areEqual([ 1, 2, 3, 4, 5, 6 ], arr, "Three more elements should be added to end of arr");
// Test deleting elements in predicate function that have not been visited
function f(v, i, a) {
if (i % 2 === 1) {
assert.areEqual(undefined, v, "odd indices should be undefined since they were deleted");
} else {
delete a[i+1];
}
return false;
}
assert.areEqual( -1, arr.findIndex(f), "Elements deleted before being visited after findIndex has started shouldn't be included in the search");
assert.areEqual( 1, arr[0], "Odd elements should be deleted [0]");
assert.areEqual(undefined, arr[1], "Odd elements should be deleted [1]");
assert.areEqual( 3, arr[2], "Odd elements should be deleted [2]");
assert.areEqual(undefined, arr[3], "Odd elements should be deleted [3]");
assert.areEqual( 5, arr[4], "Odd elements should be deleted [4]");
assert.areEqual(undefined, arr[5], "Odd elements should be deleted [5]");
// Test deleting elements in predicate function that have already been visited
assert.areEqual( -1, arr.findIndex(function (v, i, a) { delete a[i]; return false; }), "Elements deleted after being visited has no effect on the search");
assert.areEqual(undefined, arr[0], "All elements should be deleted [0]");
assert.areEqual(undefined, arr[1], "All elements should be deleted [1]");
assert.areEqual(undefined, arr[2], "All elements should be deleted [2]");
assert.areEqual(undefined, arr[3], "All elements should be deleted [3]");
assert.areEqual(undefined, arr[4], "All elements should be deleted [4]");
assert.areEqual(undefined, arr[5], "All elements should be deleted [5]");
assert.areEqual(6, arr.length, "arr length is still 6");
// Test thisArg argument
var thisArg = { };
assert.areEqual(-1, arr.findIndex(function (v, i, a) { if (this !== thisArg) { assert.fail("this is not what was passed to second parameter of findIndex()"); } return false; }, thisArg), "Argument passed as the optional second parameter of findIndex should become the this value in the predicate");
// Test and ensure Array.prototype.findIndex calls ToLength
// checks lower bound (negative -> zero)
// upper bound ( pow(2,53)-1 ) cannot be tested in reasonable time
var arr = { '0': 1, '1': 2, '2': 3, length: -3 };
assert.areEqual(-1, Array.prototype.findIndex.call(arr, function (v, i, a) {assert.fail("shouldn't visit any element when length is less than zero"); return true;}), "findIndex should use ToLength function that clamps length between 0 and pow(2,53)-1");
}
},
{
name: "find and findIndex do not skip 'holes' in arrays and array-likes",
body: function () {
var arr = [,,,,,];
var count = 0;
arr.find(function () { count++; return false; });
assert.areEqual(arr.length, count, "find calls its callback for every element up to the array's length even if those elements are undefined");
count = 0;
arr.findIndex(function () { count++; return false; });
assert.areEqual(arr.length, count, "findIndex calls its callback for every element up to the array's length even if those elements are undefined");
arr = { length: 5, 0: undefined, 1: undefined, 3: undefined };
count = 0;
Array.prototype.find.call(arr, function () { count++; return false; });
assert.areEqual(arr.length, count, "find calls its callback for every element up to the array-like's length even if those elements do not exist on the array-like");
count = 0;
Array.prototype.findIndex.call(arr, function () { count++; return false; });
assert.areEqual(arr.length, count, "findIndex calls its callback for every element up to the array-like's length even if those elements do not exist on the array-like");
}
},
{
name: "repeat takes a string and number and returns a string that is the given string repeated the given number of times",
body: function () {
assert.throws(function () { String.prototype.repeat.call(); }, TypeError, "repeat throws TypeError if it is given no arguments", "String.prototype.repeat: 'this' is null or undefined");
assert.throws(function () { String.prototype.repeat.call(undefined); }, TypeError, "repeat throws TypeError if its this argument is undefined", "String.prototype.repeat: 'this' is null or undefined");
assert.throws(function () { String.prototype.repeat.call(undefined, "", 0); }, TypeError, "repeat throws TypeError if its this argument is undefined even if given further arguments", "String.prototype.repeat: 'this' is null or undefined");
assert.throws(function () { String.prototype.repeat.call(null); }, TypeError, "repeat throws TypeError if its this argument is null", "String.prototype.repeat: 'this' is null or undefined");
assert.throws(function () { String.prototype.repeat.call(null, "", 0); }, TypeError, "repeat throws TypeError if its this argument is null even if given further arguments", "String.prototype.repeat: 'this' is null or undefined");
var s;
s = "";
assert.areEqual("", s.repeat(0), "empty string repeated zero times is the empty string");
assert.areEqual("", s.repeat(NaN), "empty string: NaN converts to zero so produces the empty string");
assert.areEqual("", s.repeat(1), "empty string repeated once is the empty string");
assert.areEqual("", s.repeat(2), "empty string repeated twice is the empty string");
assert.areEqual("", s.repeat(50), "empty string repeated fifty times is the empty string");
s = "a";
assert.areEqual("", s.repeat(0), "single character string repeated zero times is the empty string");
assert.areEqual("", s.repeat(NaN), "single character string: NaN converts to zero so produces the empty string");
assert.areEqual("a", s.repeat(1), "single character string repeated once is itself");
assert.areEqual("aa", s.repeat(2), "single character string repeated twice is a two character string");
assert.areEqual("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", s.repeat(50), "single character string repeated fifty times is a 50 character string");
s = "abc";
assert.areEqual("", s.repeat(0), "multi-character string repeated zero times is the empty string");
assert.areEqual("", s.repeat(NaN), "multi-character string: NaN converts to zero so produces the empty string");
assert.areEqual("abc", s.repeat(1), "multi-character string repeated once is itself");
assert.areEqual("abcabc", s.repeat(2), "3 character string repeated twice is a six character string");
assert.areEqual("abcabcabcabcabcabcabcabcabcabc", s.repeat(10), "3 character string repeated ten times is a 30 character string");
assert.throws(function () { s.repeat(-1); }, RangeError, "negative repeat counts are out of range", "String.prototype.repeat: argument out of range");
assert.throws(function () { s.repeat(-Infinity); }, RangeError, "negative infinite repeat count is out of range", "String.prototype.repeat: argument out of range");
assert.throws(function () { s.repeat(Infinity); }, RangeError, "infinite repeat count is out of range", "String.prototype.repeat: argument out of range");
assert.throws(function () { s.repeat(2 ** 30); }, RangeError, "lengths too large for a string throw");
assert.areEqual("\0\0\0\0", "\0".repeat(4), "null character embedded in string is repeated");
assert.areEqual("a\0ba\0ba\0b", "a\0b".repeat(3), "null character embedded in string mixed with normal characters is repeated");
assert.areEqual("\0abc\0\0abc\0\0abc\0", "\0abc\0".repeat(3), "null character embedded in string surrounding normal characters is repeated");
}
},
{
name: "startsWith returns true if the given search string matches the substring of the given string starting at the given position",
body: function () {
assert.throws(function () { String.prototype.startsWith.call(); }, TypeError, "startsWith throws TypeError if it is given no arguments", "String.prototype.startsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.startsWith.call(undefined); }, TypeError, "startsWith throws TypeError if its this argument is undefined", "String.prototype.startsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.startsWith.call(undefined, "", 0); }, TypeError, "startsWith throws TypeError if its this argument is undefined even if given further arguments", "String.prototype.startsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.startsWith.call(null); }, TypeError, "startsWith throws TypeError if its this argument is null", "String.prototype.startsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.startsWith.call(null, "", 0); }, TypeError, "startsWith throws TypeError if its this argument is null even if given further arguments", "String.prototype.startsWith: 'this' is null or undefined");
var s;
s = "";
assert.isTrue(s.startsWith(""), "the empty string starts with the empty string");
assert.isFalse(s.startsWith("anything"), "the empty string does not start with any non-empty string");
assert.isTrue(s.startsWith("", 1), "the search position is clipped to exist within the string and thus the the empty string starts with the empty string for any given position argument");
assert.isTrue(s.startsWith("", Infinity), "the empty string starts with the empty string even if given starting position is Infinity, since the starting position is clipped");
s = "abcdefghijklmnopqrstuvwxyz";
assert.isTrue(s.startsWith(""), "a non-empty string starts with the empty string");
assert.isTrue(s.startsWith("a"), "single character prefix substring matches the beginning of the string");
assert.isTrue(s.startsWith("abc"), "prefix substring matches the beginning of the string");
assert.isTrue(s.startsWith("abcdefghijklm"), "long prefix substring string matches the beginning of the string");
assert.isTrue(s.startsWith("abcdefghijklmnopqrstuvwxyz"), "identical string matches the beginning of the string");
assert.isFalse(s.startsWith("bcd"), "non-prefix substring does not match beginning of the string");
assert.isFalse(s.startsWith("mnopqrstuv"), "long non-prefix substring does not match beginning of the string");
assert.isFalse(s.startsWith("xyz"), "suffix substring does not match beginning of the string");
assert.isFalse(s.startsWith("abczzz"), "non-substring with partial prefix match does not match beginning of the string");
assert.isTrue(s.startsWith("", 3), "a non-empty string starts with the empty string at any position");
assert.isTrue(s.startsWith("", 26), "a non-empty string starts with the empty string at its end");
assert.isTrue(s.startsWith("", Infinity), "a non-empty string starts with the empty string at its end (Infinity clipped to end position)");
assert.isTrue(s.startsWith("abcd", -Infinity), "a non-empty string starts with a prefix substring at its beginning (-Infinity clipped to start position)");
assert.isTrue(s.startsWith("bcd", 1), "a non-empty string starts with a given substring at the position where that substring begins");
assert.isTrue(s.startsWith("mnopqrstuv", 12), "a non-empty string starts with a given (long) substring at the position where that substring begins");
assert.isTrue(s.startsWith("xyz", 23), "a non-empty string starts with a suffix substring at the position where the suffix begins");
assert.isTrue(s.startsWith("z", 25), "a non-empty string starts with a single character suffix substring at the last position in the string");
assert.isFalse(s.startsWith("z", 26), "a non-empty string does not start with a single suffix substring at the position past the string");
s = "abc\0def";
assert.isTrue(s.startsWith("abc\0def"), "string with embedded null character starts with itself");
assert.isTrue(s.startsWith("abc\0d"), "string with embedded null character starts with prefix including null character");
assert.isTrue(s.startsWith("abc\0"), "string with embedded null character starts with prefix including and ending with null character in search string");
assert.isFalse(s.startsWith("abc\0abc"), "string with embedded null character does not start with string that is only different after null character");
assert.isFalse(s.startsWith("def\0abc"), "string with embedded null character does not start with string that is only different before null character");
assert.isTrue(s.startsWith("\0def", 3), "string with embedded null character starts with substring beginning with null character at corresponding starting position");
var n = 12345;
assert.isTrue(String.prototype.startsWith.call(n, "123"), "startsWith works even when its this argument is not a string object");
assert.isFalse(String.prototype.startsWith.call(n, "45"), "startsWith works even when its this argument is not a string object");
}
},
{
name: "startsWith throws if searchString is a RegExp",
body: verifyThrowsIfRegExpSearchString.bind(undefined, "startsWith")
},
{
name: "endsWith returns true if the given search string matches the substring of the given string ending at the given position",
body: function () {
assert.throws(function () { String.prototype.endsWith.call(); }, TypeError, "endsWith throws TypeError if it is given no arguments", "String.prototype.endsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.endsWith.call(undefined); }, TypeError, "endsWith throws TypeError if its this argument is undefined", "String.prototype.endsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.endsWith.call(undefined, "", 0); }, TypeError, "endsWith throws TypeError if its this argument is undefined even if given further arguments", "String.prototype.endsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.endsWith.call(null); }, TypeError, "endsWith throws TypeError if its this argument is null", "String.prototype.endsWith: 'this' is null or undefined");
assert.throws(function () { String.prototype.endsWith.call(null, "", 0); }, TypeError, "endsWith throws TypeError if its this argument is null even if given further arguments", "String.prototype.endsWith: 'this' is null or undefined");
var s;
s = "";
assert.isTrue(s.endsWith(""), "the empty string ends with the empty string");
assert.isFalse(s.endsWith("anything"), "the empty string does not end with any non-empty string");
assert.isTrue(s.endsWith("", -1), "the search position is clipped to exist within the string and thus the the empty string ends with the empty string for any given position argument");
assert.isTrue(s.endsWith("", Infinity), "the empty string ends with the empty string even if given ending position is Infinity, since the ending position is clipped");
s = "abcdefghijklmnopqrstuvwxyz";
assert.isTrue(s.endsWith(""), "a non-empty string ends with the empty string");
assert.isTrue(s.endsWith("z"), "single character suffix substring matches the beginning of the string");
assert.isTrue(s.endsWith("xyz"), "suffix substring matches the beginning of the string");
assert.isTrue(s.endsWith("nopqrstuvwxyz"), "long suffix substring string matches the beginning of the string");
assert.isTrue(s.endsWith("abcdefghijklmnopqrstuvwxyz"), "identical string matches the beginning of the string");
assert.isFalse(s.endsWith("wxy"), "non-suffix substring does not match beginning of the string");
assert.isFalse(s.endsWith("mnopqrstuv"), "long non-suffix substring does not match beginning of the string");
assert.isFalse(s.endsWith("abc"), "prefix substring does not match beginning of the string");
assert.isFalse(s.endsWith("aaaxyz"), "non-substring with partial suffix match does not match beginning of the string");
assert.isTrue(s.endsWith("", 23), "a non-empty string ends with the empty string at any position");
assert.isTrue(s.endsWith("", 0), "a non-empty string ends with the empty string at its beginning");
assert.isTrue(s.endsWith("wxyz", Infinity), "a non-empty string ends with a suffix substring at its end (Infinity clipped to end position)");
assert.isTrue(s.endsWith("", -Infinity), "a non-empty string ends with the empty string at its beginning (-Infinity clipped to start position)");
assert.isTrue(s.endsWith("wxy", 25), "a non-empty string ends with a given substring at the position where that substring ends");
assert.isTrue(s.endsWith("mnopqrstuv", 22), "a non-empty string ends with a given (long) substring at the position where that substring ends");
assert.isTrue(s.endsWith("abc", 3), "a non-empty string ends with a prefix substring at the position where the prefix ends");
assert.isTrue(s.endsWith("a", 1), "a non-empty string ends with a single character prefix substring at the first position in the string");
assert.isFalse(s.endsWith("a", 0), "a non-empty string does not end with a single prefix substring at the position past the beginning of the string");
s = "abc\0def";
assert.isTrue(s.endsWith("abc\0def"), "string with embedded null character ends with itself");
assert.isTrue(s.endsWith("c\0def"), "string with embedded null character ends with prefix including null character");
assert.isTrue(s.endsWith("\0def"), "string with embedded null character ends with prefix including and starting with null character in search string");
assert.isFalse(s.endsWith("abc\0abc"), "string with embedded null character does not end with string that is only different after null character");
assert.isFalse(s.endsWith("def\0abc"), "string with embedded null character does not end with string that is only different before null character");
assert.isTrue(s.endsWith("abc\0", 4), "string with embedded null character ends with substring ending with null character at corresponding ending position");
var n = 12345;
assert.isTrue(String.prototype.endsWith.call(n, "345"), "endsWith works even when its this argument is not a string object");
assert.isFalse(String.prototype.endsWith.call(n, "12"), "endsWith works even when its this argument is not a string object");
}
},
{
name: "endsWith throws if searchString is a RegExp",
body: verifyThrowsIfRegExpSearchString.bind(undefined, "endsWith")
},
{
name: "includes returns true if the given search string matches any substring of the given string",
body: function () {
assert.throws(function () { String.prototype.includes.call(); }, TypeError, "includes throws TypeError if it is given no arguments", "String.prototype.includes: 'this' is null or undefined");
assert.throws(function () { String.prototype.includes.call(undefined); }, TypeError, "includes throws TypeError if its this argument is undefined", "String.prototype.includes: 'this' is null or undefined");
assert.throws(function () { String.prototype.includes.call(undefined, "", 0); }, TypeError, "includes throws TypeError if its this argument is undefined even if given further arguments", "String.prototype.includes: 'this' is null or undefined");
assert.throws(function () { String.prototype.includes.call(null); }, TypeError, "includes throws TypeError if its this argument is null", "String.prototype.includes: 'this' is null or undefined");
assert.throws(function () { String.prototype.includes.call(null, "", 0); }, TypeError, "includes throws TypeError if its this argument is null even if given further arguments", "String.prototype.includes: 'this' is null or undefined");
var s;
s = "";
assert.isTrue(s.includes(""), "the empty string includes the empty string");
assert.isFalse(s.includes("anything"), "the empty string includes no non-empty strings");
assert.isTrue(s.includes("", 1), "the search position is clipped to exist within the string and thus the empty string includes itself for any given position argument");
assert.isTrue(s.includes("", Infinity), "the empty string includes the empty string even if given ending position is Infinity, since the ending position is clipped");
s = "abcdefghijklmnopqrstuvwxyz";
assert.isTrue(s.includes(""), "a non-empty string includes the empty string");
assert.isTrue(s.includes("abc"), "substring found at the beginning of the string");
assert.isTrue(s.includes("xyz"), "substring found at the end of the string");
assert.isTrue(s.includes("z"), "substring found at the very end of the string");
assert.isTrue(s.includes("ijklmno"), "substring found in the middle of the string");
assert.isFalse(s.includes("abczzz"), "substring partially matches at the beginning of the string but is not a match");
assert.isFalse(s.includes("xyzaaa"), "substring partially matches at the ending of the string but is not a match");
assert.isFalse(s.includes("zaaa"), "substring partially matches at the very ending of the string but is not a match");
assert.isFalse(s.includes("ijklxyz"), "substring partially matches in the middle of the string but is not a match");
assert.isTrue(s.includes("", 26), "a non-empty string includes the empty string even at the end");
assert.isTrue(s.includes("", Infinity), "a non-empty string includes the empty string even at the end (Infinity clipped to end position)");
assert.isTrue(s.includes("abc", -Infinity), "a non-empty string includes a substring starting at the beginning (-Infinity clipped to start position)");
assert.isFalse(s.includes("z", 26), "a non-empty string includes no non-empty string at the end");
assert.isTrue(s.includes("z", 25), "starting at the last character, a string includes its last character");
assert.isFalse(s.includes("y", 25), "starting at the last character, a string does not contain previous characters");
assert.isFalse(s.includes("abc", 1), "a string does not contain a substring if the only occurrence begins before the given start position");
assert.isTrue(s.includes("mnop", 5), "substring found in the middle of a string after the given start position");
assert.isTrue(s.includes("efg", 4), "substring found in the middle of a string at the given start position");
s = "abc\0def";
assert.isTrue(s.includes("abc\0def"), "string with embedded null character includes itself");
assert.isTrue(s.includes("abc\0d"), "string with embedded null character includes prefix including null character");
assert.isTrue(s.includes("abc\0"), "string with embedded null character includes prefix including and ending with null character in search string");
assert.isTrue(s.includes("\0def"), "string with embedded null character includes prefix including and starting with null character in search string");
assert.isFalse(s.includes("abc\0abc"), "string with embedded null character does not contain string that is only different after null character");
assert.isFalse(s.includes("def\0abc"), "string with embedded null character does not contain string that is only different before null character");
assert.isTrue(s.includes("\0def", 3), "string with embedded null character includes with substring beginning with null character at corresponding starting position");
var n = 12345;
assert.isTrue(String.prototype.includes.call(n, "34"), "includes works even when its this argument is not a string object");
assert.isFalse(String.prototype.includes.call(n, "7"), "includes works even when its this argument is not a string object");
}
},
{
name: "includes throws if searchString is a RegExp",
body: verifyThrowsIfRegExpSearchString.bind(undefined, "includes")
},
{
name: "String.fromCodePoint has correct shape",
body: function() {
assert.areEqual(1, String.fromCodePoint.length, "String.fromCodePoint.length === 1");
}
},
];
testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.